@narumitw/pi-btw 0.60.3 → 0.61.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -4
- package/dist/index.ts +1674 -958
- package/dist/index.ts.map +4 -4
- package/docs/workflows.md +10 -2
- package/package.json +4 -4
- package/src/btw.ts +17 -79
- package/src/conversation-context.ts +74 -0
- package/src/fullscreen-ui.ts +196 -7
- package/src/main-thread-updates.ts +40 -0
- package/src/main-tree-picker.ts +2 -0
- package/src/menu.ts +34 -2
- package/src/settings.ts +49 -0
- package/src/side-thread.ts +16 -4
- package/src/transcript-pager.ts +9 -1
- package/src/workspace-layout.ts +559 -0
package/dist/index.ts
CHANGED
|
@@ -440,6 +440,53 @@ function escapeTerminalControls(text) {
|
|
|
440
440
|
}).join("");
|
|
441
441
|
}
|
|
442
442
|
|
|
443
|
+
// src/conversation-context.ts
|
|
444
|
+
var MAX_CONTEXT_CHARS = 4e4;
|
|
445
|
+
function buildConversationContext(entries) {
|
|
446
|
+
const sections = [];
|
|
447
|
+
for (const entry of entries) {
|
|
448
|
+
if (entry.type !== "message" || !entry.message?.role) continue;
|
|
449
|
+
const role = entry.message.role;
|
|
450
|
+
if (role !== "user" && role !== "assistant") continue;
|
|
451
|
+
const contentLines = extractContentLines(entry.message.content);
|
|
452
|
+
if (contentLines.length === 0) continue;
|
|
453
|
+
const label = role === "user" ? "User" : "Assistant";
|
|
454
|
+
const status = entry.message.stopReason && entry.message.stopReason !== "stop" ? ` (${entry.message.stopReason})` : "";
|
|
455
|
+
sections.push(`${label}${status}: ${contentLines.join("\n")}`);
|
|
456
|
+
}
|
|
457
|
+
return truncateFromStart(sections.join("\n\n"), MAX_CONTEXT_CHARS);
|
|
458
|
+
}
|
|
459
|
+
function extractContentLines(content) {
|
|
460
|
+
if (typeof content === "string") return [content.trim()].filter(Boolean);
|
|
461
|
+
if (!Array.isArray(content)) return [];
|
|
462
|
+
const lines = [];
|
|
463
|
+
for (const part of content) {
|
|
464
|
+
if (!part || typeof part !== "object") continue;
|
|
465
|
+
const block = part;
|
|
466
|
+
if (block.type === "text" && typeof block.text === "string") {
|
|
467
|
+
lines.push(block.text.trim());
|
|
468
|
+
} else if (block.type === "toolCall" && typeof block.name === "string") {
|
|
469
|
+
lines.push(`Tool call: ${block.name}(${formatJson(block.arguments)})`);
|
|
470
|
+
} else if (block.type === "toolResult" && typeof block.name === "string") {
|
|
471
|
+
lines.push(`Tool result from ${block.name}: ${formatJson(block.result)}`);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return lines.filter(Boolean);
|
|
475
|
+
}
|
|
476
|
+
function formatJson(value) {
|
|
477
|
+
if (value === void 0) return "";
|
|
478
|
+
try {
|
|
479
|
+
return JSON.stringify(value);
|
|
480
|
+
} catch {
|
|
481
|
+
return String(value);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
function truncateFromStart(text, maxChars) {
|
|
485
|
+
if (text.length <= maxChars) return text;
|
|
486
|
+
return `[Earlier context omitted; showing the last ${maxChars} characters.]
|
|
487
|
+
${text.slice(-maxChars)}`;
|
|
488
|
+
}
|
|
489
|
+
|
|
443
490
|
// src/fullscreen-ui.ts
|
|
444
491
|
import { spawn } from "node:child_process";
|
|
445
492
|
import {
|
|
@@ -451,7 +498,7 @@ import {
|
|
|
451
498
|
Key as Key2,
|
|
452
499
|
parseKey,
|
|
453
500
|
TuiAltScreen,
|
|
454
|
-
truncateToWidth as
|
|
501
|
+
truncateToWidth as truncateToWidth3
|
|
455
502
|
} from "@earendil-works/pi-tui";
|
|
456
503
|
|
|
457
504
|
// src/keybindings.ts
|
|
@@ -689,977 +736,1657 @@ var BtwPasteGuard = class {
|
|
|
689
736
|
}
|
|
690
737
|
};
|
|
691
738
|
|
|
692
|
-
// src/
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
keybindings,
|
|
718
|
-
ctx,
|
|
719
|
-
run,
|
|
720
|
-
(value) => {
|
|
721
|
-
try {
|
|
722
|
-
liveEditorText = ctx.ui.getEditorText();
|
|
723
|
-
restoreEditor = true;
|
|
724
|
-
} catch {
|
|
725
|
-
}
|
|
726
|
-
done(value);
|
|
727
|
-
},
|
|
728
|
-
createTui,
|
|
729
|
-
options
|
|
730
|
-
);
|
|
731
|
-
return host;
|
|
732
|
-
},
|
|
733
|
-
{
|
|
734
|
-
overlay: true,
|
|
735
|
-
onHandle: (handle) => host?.setParentOverlay(handle)
|
|
736
|
-
}
|
|
739
|
+
// src/workspace-layout.ts
|
|
740
|
+
import {
|
|
741
|
+
HStack,
|
|
742
|
+
isFocusable,
|
|
743
|
+
ScrollView,
|
|
744
|
+
truncateToWidth as truncateToWidth2,
|
|
745
|
+
visibleWidth as visibleWidth2
|
|
746
|
+
} from "@earendil-works/pi-tui";
|
|
747
|
+
|
|
748
|
+
// src/settings.ts
|
|
749
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
750
|
+
import { constants } from "node:fs";
|
|
751
|
+
import { mkdir, open, rename, rm, writeFile } from "node:fs/promises";
|
|
752
|
+
import { basename, dirname, join } from "node:path";
|
|
753
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
754
|
+
|
|
755
|
+
// src/side-thread.ts
|
|
756
|
+
import { randomUUID } from "node:crypto";
|
|
757
|
+
var BTW_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
758
|
+
function createSideThread(conversationContext) {
|
|
759
|
+
return { conversationContext, turns: [], routingSessionId: randomUUID() };
|
|
760
|
+
}
|
|
761
|
+
function buildSideThreadMessages(thread, question) {
|
|
762
|
+
const answeredTurns = thread.turns.filter(
|
|
763
|
+
(turn) => turn.kind === "answered"
|
|
737
764
|
);
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
}
|
|
765
|
+
const messages = [];
|
|
766
|
+
if (answeredTurns.length === 0) {
|
|
767
|
+
messages.push(createUserMessage(buildUserPrompt(question, thread.conversationContext)));
|
|
768
|
+
return messages;
|
|
743
769
|
}
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
function dispatchBtwInput(listeners, data) {
|
|
749
|
-
let current = data;
|
|
750
|
-
for (const group of [listeners.beforeAll, listeners.beforeViewport, listeners.regular]) {
|
|
751
|
-
for (const listener of group) {
|
|
752
|
-
const result = listener(current);
|
|
753
|
-
if (result?.consume) return result;
|
|
754
|
-
if (result?.data !== void 0) current = result.data;
|
|
755
|
-
}
|
|
770
|
+
const [first, ...rest] = answeredTurns;
|
|
771
|
+
messages.push(createUserMessage(buildUserPrompt(first.question, thread.conversationContext)), first.response);
|
|
772
|
+
for (const turn of rest) {
|
|
773
|
+
messages.push(createUserMessage(buildFollowUpPrompt(turn.question)), turn.response);
|
|
756
774
|
}
|
|
757
|
-
|
|
775
|
+
messages.push(createUserMessage(buildFollowUpPrompt(question)));
|
|
776
|
+
return messages;
|
|
758
777
|
}
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
778
|
+
async function completeSideThreadTurn({
|
|
779
|
+
thread,
|
|
780
|
+
model,
|
|
781
|
+
question,
|
|
782
|
+
thinkingLevel,
|
|
783
|
+
auth,
|
|
784
|
+
signal,
|
|
785
|
+
completeSimple,
|
|
786
|
+
sessionId
|
|
787
|
+
}) {
|
|
788
|
+
if (signal?.aborted) return { kind: "aborted" };
|
|
789
|
+
try {
|
|
790
|
+
const response = await completeSimple(
|
|
791
|
+
model,
|
|
792
|
+
{ systemPrompt: SYSTEM_PROMPT, messages: buildSideThreadMessages(thread, question) },
|
|
793
|
+
buildStreamOptions(
|
|
794
|
+
auth,
|
|
795
|
+
{ thinkingLevel, signal, model, sessionId, routingSessionId: thread.routingSessionId },
|
|
796
|
+
completeSimple.appliesRequestHeaderTransforms === true
|
|
797
|
+
)
|
|
798
|
+
);
|
|
799
|
+
if (signal?.aborted || response?.stopReason === "aborted") return { kind: "aborted" };
|
|
800
|
+
if (!isAssistantMessage(response)) {
|
|
801
|
+
return { kind: "error", message: "The side model returned a malformed response." };
|
|
774
802
|
}
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
if (!listeners) return super.addInputListener(listener);
|
|
781
|
-
listeners.beforeAll.add(listener);
|
|
782
|
-
return () => listeners.beforeAll.delete(listener);
|
|
783
|
-
}
|
|
784
|
-
addInputListenerBeforeViewport(listener) {
|
|
785
|
-
const listeners = btwInputListeners.get(this);
|
|
786
|
-
if (!listeners) return super.addInputListener(listener);
|
|
787
|
-
listeners.beforeViewport.add(listener);
|
|
788
|
-
return () => listeners.beforeViewport.delete(listener);
|
|
789
|
-
}
|
|
790
|
-
removeInputListener(listener) {
|
|
791
|
-
const listeners = btwInputListeners.get(this);
|
|
792
|
-
if (!listeners) {
|
|
793
|
-
super.removeInputListener(listener);
|
|
794
|
-
return;
|
|
803
|
+
if (response.stopReason === "error") {
|
|
804
|
+
return {
|
|
805
|
+
kind: "error",
|
|
806
|
+
message: response.errorMessage ?? "The side model returned an error."
|
|
807
|
+
};
|
|
795
808
|
}
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
809
|
+
const answer = extractAssistantText(response) || "No response received.";
|
|
810
|
+
thread.turns.push({ kind: "answered", question, answer, response });
|
|
811
|
+
return { kind: "answered", response, answer };
|
|
812
|
+
} catch (error) {
|
|
813
|
+
if (signal?.aborted) return { kind: "aborted" };
|
|
814
|
+
return { kind: "error", message: formatError(error) };
|
|
799
815
|
}
|
|
800
|
-
};
|
|
801
|
-
var BRACKETED_PASTE_START = "\x1B[200~";
|
|
802
|
-
var BRACKETED_PASTE_END = "\x1B[201~";
|
|
803
|
-
var ALT_SCREEN_ACTIONS_BEFORE_BOTTOM = [
|
|
804
|
-
"tui.altScreen.search",
|
|
805
|
-
"tui.altScreen.searchNext",
|
|
806
|
-
"tui.altScreen.searchPrevious",
|
|
807
|
-
"tui.altScreen.searchClose",
|
|
808
|
-
"tui.altScreen.pageUp",
|
|
809
|
-
"tui.altScreen.pageDown",
|
|
810
|
-
"tui.altScreen.halfPageUp",
|
|
811
|
-
"tui.altScreen.halfPageDown",
|
|
812
|
-
"tui.altScreen.lineUp",
|
|
813
|
-
"tui.altScreen.lineDown",
|
|
814
|
-
"tui.altScreen.previousPrompt",
|
|
815
|
-
"tui.altScreen.nextPrompt",
|
|
816
|
-
"tui.altScreen.top"
|
|
817
|
-
];
|
|
818
|
-
var KEY_MODIFIER_ORDER = ["shift", "ctrl", "alt", "super"];
|
|
819
|
-
var MATCHABLE_SPECIAL_KEYS = /* @__PURE__ */ new Set([
|
|
820
|
-
"space",
|
|
821
|
-
"tab",
|
|
822
|
-
"enter",
|
|
823
|
-
"backspace",
|
|
824
|
-
"delete",
|
|
825
|
-
"insert",
|
|
826
|
-
"home",
|
|
827
|
-
"end",
|
|
828
|
-
"pageup",
|
|
829
|
-
"pagedown",
|
|
830
|
-
"up",
|
|
831
|
-
"down",
|
|
832
|
-
"left",
|
|
833
|
-
"right"
|
|
834
|
-
]);
|
|
835
|
-
var MATCHABLE_SYMBOL_KEYS = new Set("`-=[]\\;',./!@#$%^&*()_+|~{}:<>?");
|
|
836
|
-
function normalizedKeyId(key) {
|
|
837
|
-
const parts = key.toLowerCase().split("+");
|
|
838
|
-
const base = parts.at(-1);
|
|
839
|
-
if (!base) return "";
|
|
840
|
-
const normalizedBase = base === "esc" ? "escape" : base === "return" ? "enter" : base;
|
|
841
|
-
const modifiers = KEY_MODIFIER_ORDER.filter((modifier) => parts.includes(modifier));
|
|
842
|
-
return [...modifiers, normalizedBase].join("+");
|
|
843
816
|
}
|
|
844
|
-
function
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
if (base === "pagedown") parts[parts.length - 1] = "pageDown";
|
|
849
|
-
return formatKeyLabel2(parts.join("+"));
|
|
817
|
+
function extractAssistantText(response) {
|
|
818
|
+
return response.content.filter(
|
|
819
|
+
(content) => content !== null && typeof content === "object" && content.type === "text" && typeof content.text === "string"
|
|
820
|
+
).map((content) => content.text).join("\n").trim();
|
|
850
821
|
}
|
|
851
|
-
function
|
|
852
|
-
|
|
853
|
-
const
|
|
854
|
-
|
|
855
|
-
if (base === "escape") return modifiers.length === 0;
|
|
856
|
-
if (base === "clear") {
|
|
857
|
-
return modifiers.length === 0 || modifiers.length === 1 && (modifiers[0] === "shift" || modifiers[0] === "ctrl");
|
|
858
|
-
}
|
|
859
|
-
if (/^f(?:[1-9]|1[0-2])$/u.test(base)) return modifiers.length === 0;
|
|
860
|
-
return MATCHABLE_SPECIAL_KEYS.has(base) || base.length === 1 && (/^[a-z0-9]$/u.test(base) || MATCHABLE_SYMBOL_KEYS.has(base));
|
|
822
|
+
function isAssistantMessage(value) {
|
|
823
|
+
if (value === null || typeof value !== "object") return false;
|
|
824
|
+
const candidate = value;
|
|
825
|
+
return candidate.role === "assistant" && Array.isArray(candidate.content) && typeof candidate.stopReason === "string";
|
|
861
826
|
}
|
|
862
|
-
function
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
827
|
+
function buildUserPrompt(question, conversationContext) {
|
|
828
|
+
return [
|
|
829
|
+
"Answer this side question without modifying the main conversation.",
|
|
830
|
+
"",
|
|
831
|
+
"<side_question>",
|
|
832
|
+
question,
|
|
833
|
+
"</side_question>",
|
|
834
|
+
"",
|
|
835
|
+
"<conversation_context>",
|
|
836
|
+
conversationContext || "No prior conversation context was available.",
|
|
837
|
+
"</conversation_context>"
|
|
838
|
+
].join("\n");
|
|
867
839
|
}
|
|
868
|
-
function
|
|
869
|
-
|
|
870
|
-
const base = parts.at(-1) ?? "";
|
|
871
|
-
if (parts.length === 2 && parts[0] === "ctrl") return rawCtrlInput(base);
|
|
872
|
-
if (isKittyProtocolActive2()) return void 0;
|
|
873
|
-
if (parts.length === 2 && parts[0] === "alt" && base.length === 1) return `\x1B${base}`;
|
|
874
|
-
if (parts.length === 3 && parts[0] === "ctrl" && parts[1] === "alt") {
|
|
875
|
-
const input = rawCtrlInput(base);
|
|
876
|
-
return input ? `\x1B${input}` : void 0;
|
|
877
|
-
}
|
|
878
|
-
return void 0;
|
|
840
|
+
function buildFollowUpPrompt(question) {
|
|
841
|
+
return ["Continue the same side conversation.", "", "<side_question>", question, "</side_question>"].join("\n");
|
|
879
842
|
}
|
|
880
|
-
function
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
843
|
+
function createUserMessage(text) {
|
|
844
|
+
return {
|
|
845
|
+
role: "user",
|
|
846
|
+
content: [{ type: "text", text }],
|
|
847
|
+
timestamp: Date.now()
|
|
848
|
+
};
|
|
884
849
|
}
|
|
885
|
-
function
|
|
886
|
-
|
|
850
|
+
function getOpencodeSessionHeaders(model, sessionId) {
|
|
851
|
+
if (!sessionId || model.provider !== "opencode" && model.provider !== "opencode-go") return void 0;
|
|
852
|
+
return { "x-opencode-session": sessionId, "x-opencode-client": "pi" };
|
|
887
853
|
}
|
|
888
|
-
function
|
|
889
|
-
if (!
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
const
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
}
|
|
906
|
-
if (!copyOnSelect) {
|
|
907
|
-
for (const copyKey of keybindings.getKeys("app.message.copy")) {
|
|
908
|
-
unavailableKeyIdentities.add(keyInputIdentity(String(copyKey)));
|
|
909
|
-
}
|
|
910
|
-
}
|
|
911
|
-
const key = keybindings.getKeys("tui.altScreen.bottom").map((candidate) => keyInputIdentity(String(candidate))).find(
|
|
912
|
-
(identity) => identity && canMatchKeyInput(identity) && !unavailableKeyIdentities.has(identity) && formatEffectiveKeyLabel(identity)
|
|
913
|
-
);
|
|
914
|
-
const label = theme.fg("text", " \u2193 Jump to latest message");
|
|
915
|
-
const shortcut = key ? theme.fg("muted", ` \xB7 ${formatEffectiveKeyLabel(key)}`) : "";
|
|
916
|
-
return theme.bg("selectedBg", `${label}${shortcut} `);
|
|
917
|
-
},
|
|
918
|
-
searchCurrentMatchStyle: (text) => theme.bold(theme.inverse(styleSearchMatch(text))),
|
|
919
|
-
openUrl,
|
|
920
|
-
copySelection: async (text) => {
|
|
921
|
-
try {
|
|
922
|
-
await copyToClipboard2(text);
|
|
923
|
-
return true;
|
|
924
|
-
} catch {
|
|
925
|
-
return false;
|
|
926
|
-
}
|
|
927
|
-
}
|
|
928
|
-
});
|
|
929
|
-
if (!copyOnSelect) {
|
|
930
|
-
let isInBracketedPaste = false;
|
|
931
|
-
fullscreen.addInputListenerBeforeViewport((data) => {
|
|
932
|
-
const wasInBracketedPaste = isInBracketedPaste;
|
|
933
|
-
const startsBracketedPaste = data.includes(BRACKETED_PASTE_START);
|
|
934
|
-
if (startsBracketedPaste) isInBracketedPaste = true;
|
|
935
|
-
if (isInBracketedPaste && data.includes(BRACKETED_PASTE_END)) {
|
|
936
|
-
isInBracketedPaste = false;
|
|
937
|
-
}
|
|
938
|
-
if (wasInBracketedPaste || startsBracketedPaste || fullscreen.hasFocusedOverlay() || isKeyRelease2(data) || !keybindings.matches(data, "app.message.copy")) {
|
|
939
|
-
return void 0;
|
|
940
|
-
}
|
|
941
|
-
if (!fullscreen.hasActiveSelection()) {
|
|
942
|
-
fullscreen.flash("No selection to copy");
|
|
943
|
-
return { consume: true };
|
|
944
|
-
}
|
|
945
|
-
void fullscreen.copyActiveSelectionToClipboard().catch(() => fullscreen.flash("Copy failed"));
|
|
946
|
-
return { consume: true };
|
|
947
|
-
});
|
|
854
|
+
function mergeSessionHeaders(authHeaders, sessionHeaders) {
|
|
855
|
+
if (!sessionHeaders && !authHeaders) return void 0;
|
|
856
|
+
return { ...sessionHeaders, ...authHeaders };
|
|
857
|
+
}
|
|
858
|
+
function buildStreamOptions(auth, { thinkingLevel, signal, model, sessionId, routingSessionId }, applyRequestHeaderTransforms) {
|
|
859
|
+
const sessionHeaders = model ? getOpencodeSessionHeaders(model, sessionId) : void 0;
|
|
860
|
+
const options = {
|
|
861
|
+
apiKey: auth?.apiKey,
|
|
862
|
+
headers: applyRequestHeaderTransforms ? auth?.headers : mergeSessionHeaders(auth?.headers, sessionHeaders),
|
|
863
|
+
env: auth?.env,
|
|
864
|
+
signal,
|
|
865
|
+
// Pi documents sessionId as optional, but providers use it for request routing and
|
|
866
|
+
// some provider overrides require it. Pi core also mints a fresh ID for one-off requests.
|
|
867
|
+
sessionId: routingSessionId
|
|
868
|
+
};
|
|
869
|
+
if (applyRequestHeaderTransforms && sessionHeaders) {
|
|
870
|
+
options.transformHeaders = (headers) => mergeSessionHeaders(headers, sessionHeaders) ?? {};
|
|
948
871
|
}
|
|
949
|
-
|
|
872
|
+
if (thinkingLevel !== "off") options.reasoning = thinkingLevel;
|
|
873
|
+
return options;
|
|
950
874
|
}
|
|
951
|
-
function
|
|
952
|
-
|
|
953
|
-
spawn(command, args, { stdio: "ignore", detached: true }).on("error", () => {
|
|
954
|
-
}).unref();
|
|
875
|
+
function formatError(error) {
|
|
876
|
+
return error instanceof Error ? error.message : String(error);
|
|
955
877
|
}
|
|
956
|
-
var
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
878
|
+
var SYSTEM_PROMPT = `You answer quick side questions for a coding-agent user.
|
|
879
|
+
|
|
880
|
+
Use 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.`;
|
|
881
|
+
|
|
882
|
+
// src/settings.ts
|
|
883
|
+
var BTW_SETTINGS_FILE = "pi-btw.json";
|
|
884
|
+
var BTW_LAYOUTS = ["fullscreen", "left-pane", "right-pane"];
|
|
885
|
+
var DEFAULT_BTW_LAYOUT = "fullscreen";
|
|
886
|
+
var DEFAULT_FULLSCREEN_COPY_ON_SELECT = true;
|
|
887
|
+
var DEFAULT_REMEMBER_THINKING_LEVEL_CHANGES = true;
|
|
888
|
+
var DEFAULT_BTW_SIDE_PANE_RATIO = 0.5;
|
|
889
|
+
var MIN_BTW_SIDE_PANE_RATIO = 0.2;
|
|
890
|
+
var MAX_BTW_SIDE_PANE_RATIO = 0.8;
|
|
891
|
+
var MAX_SETTINGS_BYTES = 64 * 1024;
|
|
892
|
+
var mutationQueues = /* @__PURE__ */ new Map();
|
|
893
|
+
function btwSettingsPath() {
|
|
894
|
+
return join(getAgentDir(), BTW_SETTINGS_FILE);
|
|
895
|
+
}
|
|
896
|
+
function normalizeBtwSettings(value) {
|
|
897
|
+
if (!isSettingsDocument(value)) return void 0;
|
|
898
|
+
const settings = {};
|
|
899
|
+
if (Object.hasOwn(value, "keybindings")) {
|
|
900
|
+
const keys = value.keybindings;
|
|
901
|
+
if (!isSettingsDocument(keys)) return void 0;
|
|
902
|
+
settings.keybindings = {};
|
|
903
|
+
for (const action of BTW_SHORTCUT_ACTIONS) {
|
|
904
|
+
if (!Object.hasOwn(keys, action)) continue;
|
|
905
|
+
const key = normalizeBtwKey(keys[action]);
|
|
906
|
+
if (!key) return void 0;
|
|
907
|
+
settings.keybindings[action] = key;
|
|
908
|
+
}
|
|
967
909
|
}
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
run;
|
|
973
|
-
done;
|
|
974
|
-
createTui;
|
|
975
|
-
options;
|
|
976
|
-
fullscreen;
|
|
977
|
-
parentOverlay;
|
|
978
|
-
cancelActiveCustom;
|
|
979
|
-
hardCancelActiveCustom;
|
|
980
|
-
removeHardCancelListener;
|
|
981
|
-
removeUpstreamAbortListener;
|
|
982
|
-
started = false;
|
|
983
|
-
disposed = false;
|
|
984
|
-
finished = false;
|
|
985
|
-
parentStopped = false;
|
|
986
|
-
parentRestoreAttempted = false;
|
|
987
|
-
fullscreenCreated = false;
|
|
988
|
-
fullscreenStopped = false;
|
|
989
|
-
parentRestoreQueued = false;
|
|
990
|
-
parentRestorePromise;
|
|
991
|
-
cleanupError;
|
|
992
|
-
lifetimeController = new AbortController();
|
|
993
|
-
setParentOverlay(overlay) {
|
|
994
|
-
this.parentOverlay = overlay;
|
|
910
|
+
if (Object.hasOwn(value, "model")) {
|
|
911
|
+
const model = Reflect.get(value, "model");
|
|
912
|
+
if (typeof model !== "string" || !parseBtwModelReference(model)) return void 0;
|
|
913
|
+
settings.model = model;
|
|
995
914
|
}
|
|
996
|
-
|
|
997
|
-
|
|
915
|
+
if (Object.hasOwn(value, "thinkingLevel")) {
|
|
916
|
+
const thinkingLevel = Reflect.get(value, "thinkingLevel");
|
|
917
|
+
if (!isBtwThinkingLevel(thinkingLevel)) return void 0;
|
|
918
|
+
settings.thinkingLevel = thinkingLevel;
|
|
998
919
|
}
|
|
999
|
-
|
|
920
|
+
if (Object.hasOwn(value, "rememberThinkingLevelChanges")) {
|
|
921
|
+
const remember = Reflect.get(value, "rememberThinkingLevelChanges");
|
|
922
|
+
if (typeof remember !== "boolean") return void 0;
|
|
923
|
+
settings.rememberThinkingLevelChanges = remember;
|
|
1000
924
|
}
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
this.cancelActiveCustom?.();
|
|
925
|
+
if (Object.hasOwn(value, "fullscreenCopyOnSelect")) {
|
|
926
|
+
const copyOnSelect = Reflect.get(value, "fullscreenCopyOnSelect");
|
|
927
|
+
if (typeof copyOnSelect !== "boolean") return void 0;
|
|
928
|
+
settings.fullscreenCopyOnSelect = copyOnSelect;
|
|
1006
929
|
}
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
let outcome;
|
|
1012
|
-
try {
|
|
1013
|
-
if (this.disposed) throw new FullscreenUiDisposedError();
|
|
1014
|
-
this.parent.stop({ preserveScreen: true });
|
|
1015
|
-
this.parentStopped = true;
|
|
1016
|
-
if (this.disposed) throw new FullscreenUiDisposedError();
|
|
1017
|
-
this.fullscreen = this.createTui(this.parent, this.theme, this.keybindings, this.options);
|
|
1018
|
-
this.fullscreenCreated = true;
|
|
1019
|
-
this.fullscreen.start();
|
|
1020
|
-
const shortcuts = resolveBtwShortcuts(
|
|
1021
|
-
this.options.keybindings,
|
|
1022
|
-
this.keybindings,
|
|
1023
|
-
this.options.copyOnSelect ?? true
|
|
1024
|
-
);
|
|
1025
|
-
setBtwShortcuts(this.fullscreen, shortcuts);
|
|
1026
|
-
let previousWarnings = [];
|
|
1027
|
-
const reportWarnings = () => {
|
|
1028
|
-
const warnings = shortcuts.warnings;
|
|
1029
|
-
for (const warning of warnings) {
|
|
1030
|
-
if (previousWarnings.includes(warning)) continue;
|
|
1031
|
-
try {
|
|
1032
|
-
this.ctx.ui.notify(`Pi BTW: ${warning}`, "warning");
|
|
1033
|
-
} catch {
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
previousWarnings = warnings;
|
|
1037
|
-
};
|
|
1038
|
-
const pasteGuard = new BtwPasteGuard();
|
|
1039
|
-
const addHardCancelListener = this.fullscreen.addInputListenerBeforeAll?.bind(this.fullscreen) ?? this.fullscreen.addInputListenerBeforeViewport?.bind(this.fullscreen) ?? this.fullscreen.addInputListener.bind(this.fullscreen);
|
|
1040
|
-
this.removeHardCancelListener = addHardCancelListener((data) => {
|
|
1041
|
-
reportWarnings();
|
|
1042
|
-
if (pasteGuard.consume(data) || !shortcuts.matches(data, "exit")) return void 0;
|
|
1043
|
-
this.disposed = true;
|
|
1044
|
-
this.lifetimeController.abort();
|
|
1045
|
-
try {
|
|
1046
|
-
this.hardCancelActiveCustom?.();
|
|
1047
|
-
} finally {
|
|
1048
|
-
this.queueParentRestore();
|
|
1049
|
-
}
|
|
1050
|
-
return { consume: true };
|
|
1051
|
-
});
|
|
1052
|
-
outcome = { kind: "completed", value: await this.run(this.createContext()) };
|
|
1053
|
-
} catch (error) {
|
|
1054
|
-
outcome = { kind: "failed", error };
|
|
1055
|
-
}
|
|
1056
|
-
try {
|
|
1057
|
-
this.cancelActiveCustom?.();
|
|
1058
|
-
} catch (error) {
|
|
1059
|
-
this.cleanupError ??= error;
|
|
1060
|
-
}
|
|
1061
|
-
if (this.parentRestorePromise) await this.parentRestorePromise;
|
|
1062
|
-
else this.restoreParent();
|
|
1063
|
-
if (this.cleanupError !== void 0) outcome = { kind: "failed", error: this.cleanupError };
|
|
1064
|
-
this.finished = true;
|
|
1065
|
-
this.done(outcome);
|
|
930
|
+
if (Object.hasOwn(value, "layout")) {
|
|
931
|
+
const layout = Reflect.get(value, "layout");
|
|
932
|
+
if (!isBtwLayout(layout)) return void 0;
|
|
933
|
+
settings.layout = layout;
|
|
1066
934
|
}
|
|
1067
|
-
|
|
1068
|
-
const
|
|
1069
|
-
if (!
|
|
1070
|
-
|
|
1071
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
1072
|
-
this.removeUpstreamAbortListener = () => signal.removeEventListener("abort", onAbort);
|
|
1073
|
-
if (signal.aborted) onAbort();
|
|
935
|
+
if (Object.hasOwn(value, "sidePaneRatio")) {
|
|
936
|
+
const sidePaneRatio = Reflect.get(value, "sidePaneRatio");
|
|
937
|
+
if (!isBtwSidePaneRatio(sidePaneRatio)) return void 0;
|
|
938
|
+
settings.sidePaneRatio = sidePaneRatio;
|
|
1074
939
|
}
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
940
|
+
return settings;
|
|
941
|
+
}
|
|
942
|
+
function parseBtwModelReference(reference) {
|
|
943
|
+
if (/[\s\p{Cc}]/u.test(reference)) return void 0;
|
|
944
|
+
const separator = reference.indexOf("/");
|
|
945
|
+
if (separator <= 0 || separator === reference.length - 1) return void 0;
|
|
946
|
+
return { provider: reference.slice(0, separator), modelId: reference.slice(separator + 1) };
|
|
947
|
+
}
|
|
948
|
+
function effectiveBtwLayout(settings) {
|
|
949
|
+
return settings.layout ?? DEFAULT_BTW_LAYOUT;
|
|
950
|
+
}
|
|
951
|
+
function effectiveFullscreenCopyOnSelect(settings) {
|
|
952
|
+
return settings.fullscreenCopyOnSelect ?? DEFAULT_FULLSCREEN_COPY_ON_SELECT;
|
|
953
|
+
}
|
|
954
|
+
function effectiveRememberThinkingLevelChanges(settings) {
|
|
955
|
+
return settings.rememberThinkingLevelChanges ?? DEFAULT_REMEMBER_THINKING_LEVEL_CHANGES;
|
|
956
|
+
}
|
|
957
|
+
function effectiveBtwSidePaneRatio(settings) {
|
|
958
|
+
return isBtwSidePaneRatio(settings.sidePaneRatio) ? settings.sidePaneRatio : DEFAULT_BTW_SIDE_PANE_RATIO;
|
|
959
|
+
}
|
|
960
|
+
async function readBtwSettings(settingsPath = btwSettingsPath()) {
|
|
961
|
+
await awaitBtwSettingsWrites(settingsPath);
|
|
962
|
+
return readBtwSettingsUncoordinated(settingsPath);
|
|
963
|
+
}
|
|
964
|
+
function updateBtwSettings(patch, options = {}) {
|
|
965
|
+
const settingsPath = options.settingsPath ?? btwSettingsPath();
|
|
966
|
+
return enqueueMutation(settingsPath, async () => {
|
|
967
|
+
options.signal?.throwIfAborted();
|
|
968
|
+
const current = await readSettingsDocumentForUpdate(settingsPath);
|
|
969
|
+
options.signal?.throwIfAborted();
|
|
970
|
+
options.validateCurrent?.(normalizeBtwSettings(current) ?? {});
|
|
971
|
+
const updated = applyBtwSettingsPatch(current, patch);
|
|
972
|
+
const settings = normalizeBtwSettings(updated);
|
|
973
|
+
if (!settings) throw invalidSettingsError(settingsPath, "invalid settings shape");
|
|
974
|
+
await publishSettings(settingsPath, updated, options.signal, options.beforeRename);
|
|
975
|
+
return settings;
|
|
976
|
+
});
|
|
977
|
+
}
|
|
978
|
+
async function awaitBtwSettingsWrites(settingsPath = btwSettingsPath()) {
|
|
979
|
+
await mutationQueues.get(settingsPath);
|
|
980
|
+
}
|
|
981
|
+
function enqueueMutation(settingsPath, mutation) {
|
|
982
|
+
const previous = mutationQueues.get(settingsPath) ?? Promise.resolve();
|
|
983
|
+
const result = previous.then(mutation, mutation);
|
|
984
|
+
const settled = result.then(
|
|
985
|
+
() => void 0,
|
|
986
|
+
() => void 0
|
|
987
|
+
);
|
|
988
|
+
mutationQueues.set(settingsPath, settled);
|
|
989
|
+
void settled.finally(() => {
|
|
990
|
+
if (mutationQueues.get(settingsPath) === settled) mutationQueues.delete(settingsPath);
|
|
991
|
+
});
|
|
992
|
+
return result;
|
|
993
|
+
}
|
|
994
|
+
async function readBtwSettingsUncoordinated(settingsPath) {
|
|
995
|
+
let contents;
|
|
996
|
+
try {
|
|
997
|
+
contents = await readSettingsContents(settingsPath);
|
|
998
|
+
} catch (error) {
|
|
999
|
+
if (isNodeError(error) && error.code === "ENOENT") return { kind: "missing" };
|
|
1000
|
+
return { kind: "invalid", reason: `${settingsPath}: ${formatError2(error)}` };
|
|
1087
1001
|
}
|
|
1088
|
-
|
|
1089
|
-
const
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1002
|
+
try {
|
|
1003
|
+
const settings = normalizeBtwSettings(JSON.parse(contents));
|
|
1004
|
+
return settings ? { kind: "loaded", settings } : { kind: "invalid", reason: `${settingsPath}: invalid settings shape` };
|
|
1005
|
+
} catch {
|
|
1006
|
+
return { kind: "invalid", reason: `${settingsPath}: invalid JSON` };
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
async function readSettingsDocumentForUpdate(settingsPath) {
|
|
1010
|
+
let contents;
|
|
1011
|
+
try {
|
|
1012
|
+
contents = await readSettingsContents(settingsPath);
|
|
1013
|
+
} catch (error) {
|
|
1014
|
+
if (isNodeError(error) && error.code === "ENOENT") return {};
|
|
1015
|
+
throw invalidSettingsError(settingsPath, formatError2(error));
|
|
1016
|
+
}
|
|
1017
|
+
let parsed;
|
|
1018
|
+
try {
|
|
1019
|
+
parsed = JSON.parse(contents);
|
|
1020
|
+
} catch {
|
|
1021
|
+
throw invalidSettingsError(settingsPath, "invalid JSON");
|
|
1022
|
+
}
|
|
1023
|
+
if (!isSettingsDocument(parsed) || !normalizeBtwSettings(parsed)) {
|
|
1024
|
+
throw invalidSettingsError(settingsPath, "invalid settings shape");
|
|
1025
|
+
}
|
|
1026
|
+
return parsed;
|
|
1027
|
+
}
|
|
1028
|
+
async function readSettingsContents(settingsPath) {
|
|
1029
|
+
const flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0);
|
|
1030
|
+
const handle = await open(settingsPath, flags);
|
|
1031
|
+
try {
|
|
1032
|
+
const descriptorStats = await handle.stat();
|
|
1033
|
+
if (!descriptorStats.isFile()) throw new Error("settings path is not a regular file");
|
|
1034
|
+
if (descriptorStats.size > MAX_SETTINGS_BYTES) {
|
|
1035
|
+
throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
|
|
1102
1036
|
}
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
}
|
|
1037
|
+
const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);
|
|
1038
|
+
let offset = 0;
|
|
1039
|
+
while (offset < buffer.byteLength) {
|
|
1040
|
+
const { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset, offset);
|
|
1041
|
+
if (bytesRead === 0) break;
|
|
1042
|
+
offset += bytesRead;
|
|
1110
1043
|
}
|
|
1111
|
-
if (
|
|
1112
|
-
|
|
1113
|
-
this.parentOverlay = void 0;
|
|
1114
|
-
try {
|
|
1115
|
-
parentOverlay?.setHidden(true);
|
|
1116
|
-
} catch (error) {
|
|
1117
|
-
this.cleanupError ??= error;
|
|
1044
|
+
if (offset > MAX_SETTINGS_BYTES) {
|
|
1045
|
+
throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
|
|
1118
1046
|
}
|
|
1119
1047
|
try {
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
} catch (error) {
|
|
1124
|
-
this.cleanupError ??= error;
|
|
1048
|
+
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, offset));
|
|
1049
|
+
} catch {
|
|
1050
|
+
throw new Error("settings file is not valid UTF-8");
|
|
1125
1051
|
}
|
|
1052
|
+
} finally {
|
|
1053
|
+
await handle.close();
|
|
1126
1054
|
}
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
return new Proxy(this.ctx, {
|
|
1146
|
-
get: (target, property) => {
|
|
1147
|
-
if (property === "ui") return ui;
|
|
1148
|
-
if (property === "signal") return signal;
|
|
1149
|
-
return Reflect.get(target, property, target);
|
|
1150
|
-
}
|
|
1055
|
+
}
|
|
1056
|
+
async function publishSettings(settingsPath, document, signal, beforeRename) {
|
|
1057
|
+
signal?.throwIfAborted();
|
|
1058
|
+
const contents = `${JSON.stringify(document, null, 2)}
|
|
1059
|
+
`;
|
|
1060
|
+
if (Buffer.byteLength(contents, "utf8") > MAX_SETTINGS_BYTES) {
|
|
1061
|
+
throw new Error(`settings document exceeds ${MAX_SETTINGS_BYTES} bytes`);
|
|
1062
|
+
}
|
|
1063
|
+
const directory = dirname(settingsPath);
|
|
1064
|
+
await mkdir(directory, { recursive: true });
|
|
1065
|
+
signal?.throwIfAborted();
|
|
1066
|
+
const temporaryPath = join(directory, `.${basename(settingsPath)}.${process.pid}.${randomUUID2()}.tmp`);
|
|
1067
|
+
try {
|
|
1068
|
+
await writeFile(temporaryPath, contents, {
|
|
1069
|
+
encoding: "utf8",
|
|
1070
|
+
flag: "wx",
|
|
1071
|
+
mode: 384,
|
|
1072
|
+
signal
|
|
1151
1073
|
});
|
|
1074
|
+
await beforeRename?.(temporaryPath, settingsPath);
|
|
1075
|
+
signal?.throwIfAborted();
|
|
1076
|
+
await rename(temporaryPath, settingsPath);
|
|
1077
|
+
} catch (error) {
|
|
1078
|
+
await rm(temporaryPath, { force: true }).catch(() => void 0);
|
|
1079
|
+
throw error;
|
|
1152
1080
|
}
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
}
|
|
1158
|
-
|
|
1159
|
-
|
|
1081
|
+
}
|
|
1082
|
+
function applyBtwSettingsPatch(current, patch) {
|
|
1083
|
+
const updated = { ...current };
|
|
1084
|
+
if (patch.keybindings) {
|
|
1085
|
+
const keys = isSettingsDocument(current.keybindings) ? { ...current.keybindings } : {};
|
|
1086
|
+
for (const action of BTW_SHORTCUT_ACTIONS) {
|
|
1087
|
+
if (!Object.hasOwn(patch.keybindings, action)) continue;
|
|
1088
|
+
if (patch.keybindings[action] === void 0) delete keys[action];
|
|
1089
|
+
else keys[action] = patch.keybindings[action];
|
|
1160
1090
|
}
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
let overlay;
|
|
1164
|
-
let mounted = false;
|
|
1165
|
-
let layoutMounted = false;
|
|
1166
|
-
let factorySettled = false;
|
|
1167
|
-
let closed = false;
|
|
1168
|
-
let promiseSettled = false;
|
|
1169
|
-
let componentDisposed = false;
|
|
1170
|
-
let pendingValue;
|
|
1171
|
-
let hasPendingValue = false;
|
|
1172
|
-
const disposeComponent = () => {
|
|
1173
|
-
if (!component || componentDisposed) return;
|
|
1174
|
-
componentDisposed = true;
|
|
1175
|
-
try {
|
|
1176
|
-
component.dispose?.();
|
|
1177
|
-
} catch {
|
|
1178
|
-
}
|
|
1179
|
-
};
|
|
1180
|
-
const unmount = () => {
|
|
1181
|
-
let cleanupError;
|
|
1182
|
-
try {
|
|
1183
|
-
if (overlay) overlay.hide();
|
|
1184
|
-
else if (mounted && layoutMounted) fullscreen.setLayoutRoot(void 0);
|
|
1185
|
-
else if (mounted && component) fullscreen.removeChild(component);
|
|
1186
|
-
} catch (error) {
|
|
1187
|
-
cleanupError = error;
|
|
1188
|
-
}
|
|
1189
|
-
if (overlay || mounted) {
|
|
1190
|
-
try {
|
|
1191
|
-
fullscreen.setFocus(null);
|
|
1192
|
-
fullscreen.requestRender();
|
|
1193
|
-
} catch (error) {
|
|
1194
|
-
cleanupError ??= error;
|
|
1195
|
-
}
|
|
1196
|
-
}
|
|
1197
|
-
disposeComponent();
|
|
1198
|
-
if (cleanupError !== void 0) throw cleanupError;
|
|
1199
|
-
};
|
|
1200
|
-
const complete = () => {
|
|
1201
|
-
if (promiseSettled || !hasPendingValue) return;
|
|
1202
|
-
promiseSettled = true;
|
|
1203
|
-
this.cancelActiveCustom = void 0;
|
|
1204
|
-
this.hardCancelActiveCustom = void 0;
|
|
1205
|
-
if (!factorySettled) {
|
|
1206
|
-
resolve(pendingValue);
|
|
1207
|
-
return;
|
|
1208
|
-
}
|
|
1209
|
-
try {
|
|
1210
|
-
unmount();
|
|
1211
|
-
resolve(pendingValue);
|
|
1212
|
-
} catch (error) {
|
|
1213
|
-
reject(error);
|
|
1214
|
-
}
|
|
1215
|
-
};
|
|
1216
|
-
const close = (value) => {
|
|
1217
|
-
if (closed || promiseSettled) return;
|
|
1218
|
-
closed = true;
|
|
1219
|
-
pendingValue = value;
|
|
1220
|
-
hasPendingValue = true;
|
|
1221
|
-
complete();
|
|
1222
|
-
};
|
|
1223
|
-
const fail = (error) => {
|
|
1224
|
-
if (promiseSettled) return;
|
|
1225
|
-
closed = true;
|
|
1226
|
-
promiseSettled = true;
|
|
1227
|
-
this.cancelActiveCustom = void 0;
|
|
1228
|
-
this.hardCancelActiveCustom = void 0;
|
|
1229
|
-
try {
|
|
1230
|
-
unmount();
|
|
1231
|
-
reject(error);
|
|
1232
|
-
} catch (cleanupError) {
|
|
1233
|
-
reject(cleanupError);
|
|
1234
|
-
}
|
|
1235
|
-
};
|
|
1236
|
-
this.cancelActiveCustom = () => {
|
|
1237
|
-
if (promiseSettled) return;
|
|
1238
|
-
disposeComponent();
|
|
1239
|
-
if (!promiseSettled) fail(new FullscreenUiDisposedError());
|
|
1240
|
-
};
|
|
1241
|
-
this.hardCancelActiveCustom = () => {
|
|
1242
|
-
if (promiseSettled) return;
|
|
1243
|
-
try {
|
|
1244
|
-
component?.handleInput?.("");
|
|
1245
|
-
} catch (error) {
|
|
1246
|
-
fail(error);
|
|
1247
|
-
return;
|
|
1248
|
-
}
|
|
1249
|
-
this.cancelActiveCustom?.();
|
|
1250
|
-
};
|
|
1251
|
-
let created;
|
|
1252
|
-
try {
|
|
1253
|
-
created = factory(fullscreen, this.theme, this.keybindings, close);
|
|
1254
|
-
} catch (error) {
|
|
1255
|
-
factorySettled = true;
|
|
1256
|
-
fail(error);
|
|
1257
|
-
return;
|
|
1258
|
-
}
|
|
1259
|
-
Promise.resolve(created).then((value) => {
|
|
1260
|
-
component = value;
|
|
1261
|
-
factorySettled = true;
|
|
1262
|
-
if (promiseSettled) {
|
|
1263
|
-
disposeComponent();
|
|
1264
|
-
return;
|
|
1265
|
-
}
|
|
1266
|
-
if (closed) {
|
|
1267
|
-
complete();
|
|
1268
|
-
return;
|
|
1269
|
-
}
|
|
1270
|
-
if (options?.overlay) {
|
|
1271
|
-
const overlayOptions = typeof options.overlayOptions === "function" ? options.overlayOptions() : options.overlayOptions;
|
|
1272
|
-
overlay = fullscreen.showOverlay(component, overlayOptions);
|
|
1273
|
-
options.onHandle?.(overlay);
|
|
1274
|
-
} else {
|
|
1275
|
-
fullscreen.clear();
|
|
1276
|
-
mounted = true;
|
|
1277
|
-
if (isFullscreenLayoutComponent(component)) {
|
|
1278
|
-
layoutMounted = true;
|
|
1279
|
-
fullscreen.setLayoutRoot(component.getFullscreenLayout());
|
|
1280
|
-
} else {
|
|
1281
|
-
fullscreen.addChild(component);
|
|
1282
|
-
}
|
|
1283
|
-
fullscreen.setFocus(component);
|
|
1284
|
-
fullscreen.requestRender();
|
|
1285
|
-
}
|
|
1286
|
-
}).catch(fail);
|
|
1287
|
-
});
|
|
1091
|
+
if (Object.keys(keys).length) updated.keybindings = keys;
|
|
1092
|
+
else delete updated.keybindings;
|
|
1288
1093
|
}
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1094
|
+
if (Object.hasOwn(patch, "model")) {
|
|
1095
|
+
if (patch.model === void 0) delete updated.model;
|
|
1096
|
+
else updated.model = patch.model;
|
|
1097
|
+
}
|
|
1098
|
+
if (Object.hasOwn(patch, "thinkingLevel")) {
|
|
1099
|
+
if (patch.thinkingLevel === void 0) delete updated.thinkingLevel;
|
|
1100
|
+
else updated.thinkingLevel = patch.thinkingLevel;
|
|
1101
|
+
}
|
|
1102
|
+
if (Object.hasOwn(patch, "rememberThinkingLevelChanges")) {
|
|
1103
|
+
updated.rememberThinkingLevelChanges = patch.rememberThinkingLevelChanges;
|
|
1104
|
+
}
|
|
1105
|
+
if (Object.hasOwn(patch, "fullscreenCopyOnSelect")) {
|
|
1106
|
+
if (patch.fullscreenCopyOnSelect === void 0) delete updated.fullscreenCopyOnSelect;
|
|
1107
|
+
else updated.fullscreenCopyOnSelect = patch.fullscreenCopyOnSelect;
|
|
1108
|
+
}
|
|
1109
|
+
if (Object.hasOwn(patch, "layout")) {
|
|
1110
|
+
if (patch.layout === void 0) delete updated.layout;
|
|
1111
|
+
else updated.layout = patch.layout;
|
|
1112
|
+
}
|
|
1113
|
+
if (Object.hasOwn(patch, "sidePaneRatio")) {
|
|
1114
|
+
if (patch.sidePaneRatio === void 0) delete updated.sidePaneRatio;
|
|
1115
|
+
else updated.sidePaneRatio = patch.sidePaneRatio;
|
|
1116
|
+
}
|
|
1117
|
+
return updated;
|
|
1292
1118
|
}
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
import {
|
|
1296
|
-
copyToClipboard,
|
|
1297
|
-
TreeSelectorComponent
|
|
1298
|
-
} from "@earendil-works/pi-coding-agent";
|
|
1299
|
-
import { Key as Key3, matchesKey as matchesKey3 } from "@earendil-works/pi-tui";
|
|
1300
|
-
|
|
1301
|
-
// src/menu.ts
|
|
1302
|
-
import { getSupportedThinkingLevels } from "@earendil-works/pi-ai";
|
|
1303
|
-
import {
|
|
1304
|
-
BorderedLoader
|
|
1305
|
-
} from "@earendil-works/pi-coding-agent";
|
|
1306
|
-
|
|
1307
|
-
// src/settings.ts
|
|
1308
|
-
import { randomUUID } from "node:crypto";
|
|
1309
|
-
import { constants } from "node:fs";
|
|
1310
|
-
import { mkdir, open, rename, rm, writeFile } from "node:fs/promises";
|
|
1311
|
-
import { basename, dirname, join } from "node:path";
|
|
1312
|
-
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
1313
|
-
|
|
1314
|
-
// src/side-thread.ts
|
|
1315
|
-
var BTW_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
1316
|
-
function createSideThread(conversationContext) {
|
|
1317
|
-
return { conversationContext, turns: [] };
|
|
1119
|
+
function isSettingsDocument(value) {
|
|
1120
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1318
1121
|
}
|
|
1319
|
-
function
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1122
|
+
function isBtwThinkingLevel(value) {
|
|
1123
|
+
return BTW_THINKING_LEVELS.includes(value);
|
|
1124
|
+
}
|
|
1125
|
+
function isBtwLayout(value) {
|
|
1126
|
+
return BTW_LAYOUTS.includes(value);
|
|
1127
|
+
}
|
|
1128
|
+
function isBtwSidePaneRatio(value) {
|
|
1129
|
+
return typeof value === "number" && Number.isFinite(value) && value >= MIN_BTW_SIDE_PANE_RATIO && value <= MAX_BTW_SIDE_PANE_RATIO;
|
|
1130
|
+
}
|
|
1131
|
+
function invalidSettingsError(settingsPath, reason) {
|
|
1132
|
+
return new Error(`pi-btw settings at ${settingsPath} are invalid: ${reason}`);
|
|
1133
|
+
}
|
|
1134
|
+
function isNodeError(error) {
|
|
1135
|
+
return error instanceof Error && "code" in error;
|
|
1136
|
+
}
|
|
1137
|
+
function formatError2(error) {
|
|
1138
|
+
return error instanceof Error ? error.message : String(error);
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
// src/workspace-layout.ts
|
|
1142
|
+
var MIN_BTW_SPLIT_COLUMNS = 80;
|
|
1143
|
+
var PANE_DIVIDER_COLUMNS = 1;
|
|
1144
|
+
var SGR_MOUSE_PRESS_PATTERN = new RegExp("^\\u001b\\[<(\\d+);(\\d+);\\d+M$");
|
|
1145
|
+
var BtwMainThreadInput = class {
|
|
1146
|
+
constructor(initialTarget, resolveTarget, requestRender) {
|
|
1147
|
+
this.resolveTarget = resolveTarget;
|
|
1148
|
+
this.requestRender = requestRender;
|
|
1149
|
+
this.target = hasInput(initialTarget) ? initialTarget : void 0;
|
|
1150
|
+
}
|
|
1151
|
+
resolveTarget;
|
|
1152
|
+
requestRender;
|
|
1153
|
+
target;
|
|
1154
|
+
_focused = false;
|
|
1155
|
+
disposed = false;
|
|
1156
|
+
get focused() {
|
|
1157
|
+
return this._focused;
|
|
1158
|
+
}
|
|
1159
|
+
set focused(value) {
|
|
1160
|
+
this._focused = value;
|
|
1161
|
+
if (this.target && isFocusable(this.target)) this.target.focused = value;
|
|
1162
|
+
}
|
|
1163
|
+
get wantsKeyRelease() {
|
|
1164
|
+
return this.target?.wantsKeyRelease ?? false;
|
|
1165
|
+
}
|
|
1166
|
+
render() {
|
|
1167
|
+
return [];
|
|
1168
|
+
}
|
|
1169
|
+
handleInput(data) {
|
|
1170
|
+
if (this.disposed) return;
|
|
1171
|
+
this.refreshTarget();
|
|
1172
|
+
this.target?.handleInput?.(data);
|
|
1173
|
+
this.refreshTarget();
|
|
1174
|
+
this.requestRender();
|
|
1175
|
+
}
|
|
1176
|
+
refreshTarget() {
|
|
1177
|
+
if (this.disposed) return;
|
|
1178
|
+
const next = this.resolveTarget();
|
|
1179
|
+
if (!hasInput(next) || next === this.target) return;
|
|
1180
|
+
if (this._focused && this.target && isFocusable(this.target)) this.target.focused = false;
|
|
1181
|
+
this.target = next;
|
|
1182
|
+
if (this._focused && isFocusable(next)) next.focused = true;
|
|
1183
|
+
}
|
|
1184
|
+
invalidate() {
|
|
1185
|
+
}
|
|
1186
|
+
dispose() {
|
|
1187
|
+
if (this.disposed) return;
|
|
1188
|
+
this.disposed = true;
|
|
1189
|
+
if (this._focused && this.target && isFocusable(this.target)) this.target.focused = false;
|
|
1190
|
+
this.target = void 0;
|
|
1191
|
+
this._focused = false;
|
|
1192
|
+
}
|
|
1193
|
+
};
|
|
1194
|
+
var BtwSplitPane = class {
|
|
1195
|
+
constructor(options) {
|
|
1196
|
+
this.options = options;
|
|
1197
|
+
this.sidePaneRatio = clampSidePaneRatio(options.sidePaneRatio ?? DEFAULT_BTW_SIDE_PANE_RATIO);
|
|
1198
|
+
this.persistedSidePaneRatio = this.sidePaneRatio;
|
|
1199
|
+
this.mainPane = new MainThreadPane(options.mainThread, options.mainLayout, options.theme, options.terminalRows);
|
|
1200
|
+
this.viewportRouter = new PaneViewportRouter(
|
|
1201
|
+
options.sideScrollView ?? findPrimaryScrollView(options.sideLayout),
|
|
1202
|
+
this.mainPane.getPrimaryScrollView(),
|
|
1203
|
+
options.setViewportTarget
|
|
1204
|
+
);
|
|
1205
|
+
this.viewportRouter.activate("side");
|
|
1206
|
+
const separator = {
|
|
1207
|
+
render: (width) => Array.from({ length: Math.max(1, options.terminalRows()) }, () => truncateToWidth2(this.renderDivider(), width)),
|
|
1208
|
+
handleMouse: (event) => this.handleDividerMouse(event),
|
|
1209
|
+
invalidate() {
|
|
1210
|
+
}
|
|
1211
|
+
};
|
|
1212
|
+
const side = options.sideLayout;
|
|
1213
|
+
const main = this.mainPane.getLayout();
|
|
1214
|
+
this.layoutRoot = options.layout === "left-pane" ? new ResponsivePaneRow(
|
|
1215
|
+
side,
|
|
1216
|
+
separator,
|
|
1217
|
+
main,
|
|
1218
|
+
0,
|
|
1219
|
+
() => this.sidePaneRatio,
|
|
1220
|
+
(width) => this.handleViewportWidth(width)
|
|
1221
|
+
) : new ResponsivePaneRow(
|
|
1222
|
+
main,
|
|
1223
|
+
separator,
|
|
1224
|
+
side,
|
|
1225
|
+
2,
|
|
1226
|
+
() => this.sidePaneRatio,
|
|
1227
|
+
(width) => this.handleViewportWidth(width)
|
|
1228
|
+
);
|
|
1229
|
+
}
|
|
1230
|
+
options;
|
|
1231
|
+
pasteGuard = new BtwPasteGuard();
|
|
1232
|
+
mainPane;
|
|
1233
|
+
layoutRoot;
|
|
1234
|
+
viewportRouter;
|
|
1235
|
+
activePane = "side";
|
|
1236
|
+
sidePaneRatio;
|
|
1237
|
+
persistedSidePaneRatio;
|
|
1238
|
+
dividerDragStartRatio;
|
|
1239
|
+
focusGeneration = 0;
|
|
1240
|
+
ratioSaveGeneration = 0;
|
|
1241
|
+
confirmedRatioSaveGeneration = 0;
|
|
1242
|
+
failedRatioSaveGenerationDuringDrag;
|
|
1243
|
+
disposed = false;
|
|
1244
|
+
getFullscreenLayout() {
|
|
1245
|
+
return this.layoutRoot;
|
|
1246
|
+
}
|
|
1247
|
+
handleTerminalInput(data) {
|
|
1248
|
+
if (this.disposed) return false;
|
|
1249
|
+
const pasted = this.pasteGuard.consume(data);
|
|
1250
|
+
if (this.options.hasFocusedOverlay()) return false;
|
|
1251
|
+
const width = this.terminalColumns();
|
|
1252
|
+
if (width < MIN_BTW_SPLIT_COLUMNS && this.activePane !== "side") this.activatePane("side");
|
|
1253
|
+
if (pasted) {
|
|
1254
|
+
this.forwardPastedInput(data);
|
|
1255
|
+
return true;
|
|
1256
|
+
}
|
|
1257
|
+
if (width < MIN_BTW_SPLIT_COLUMNS) return false;
|
|
1258
|
+
const pane = paneForMouseClick(data, width, this.options.layout, this.sidePaneRatio);
|
|
1259
|
+
if (pane) this.queuePaneFocus(pane);
|
|
1260
|
+
return false;
|
|
1327
1261
|
}
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1262
|
+
render(width) {
|
|
1263
|
+
if (width <= 0) return [];
|
|
1264
|
+
const safeWidth = Math.max(1, width);
|
|
1265
|
+
this.handleViewportWidth(safeWidth);
|
|
1266
|
+
if (safeWidth < MIN_BTW_SPLIT_COLUMNS) {
|
|
1267
|
+
return this.options.sideComponent.render(safeWidth).map((line) => truncateToWidth2(line, safeWidth));
|
|
1268
|
+
}
|
|
1269
|
+
const { sideWidth, mainWidth } = paneWidths(safeWidth, this.options.layout, this.sidePaneRatio);
|
|
1270
|
+
const sideLines = this.options.sideComponent.render(sideWidth);
|
|
1271
|
+
const mainLines = this.mainPane.render(mainWidth);
|
|
1272
|
+
const rows = Math.max(1, this.options.terminalRows());
|
|
1273
|
+
const separator = this.renderDivider();
|
|
1274
|
+
const lines = [];
|
|
1275
|
+
for (let index = 0; index < rows; index += 1) {
|
|
1276
|
+
const sideLine = padLine(sideLines[index] ?? "", sideWidth);
|
|
1277
|
+
const mainLine = padLine(mainLines[index] ?? "", mainWidth);
|
|
1278
|
+
lines.push(
|
|
1279
|
+
this.options.layout === "left-pane" ? `${sideLine}${separator}${mainLine}` : `${mainLine}${separator}${sideLine}`
|
|
1280
|
+
);
|
|
1281
|
+
}
|
|
1282
|
+
return lines.map((line) => truncateToWidth2(line, safeWidth));
|
|
1332
1283
|
}
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
}
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
{
|
|
1351
|
-
buildStreamOptions(
|
|
1352
|
-
auth,
|
|
1353
|
-
{ thinkingLevel, signal, model, sessionId },
|
|
1354
|
-
completeSimple.appliesRequestHeaderTransforms === true
|
|
1355
|
-
)
|
|
1356
|
-
);
|
|
1357
|
-
if (signal?.aborted || response?.stopReason === "aborted") return { kind: "aborted" };
|
|
1358
|
-
if (!isAssistantMessage(response)) {
|
|
1359
|
-
return { kind: "error", message: "The side model returned a malformed response." };
|
|
1284
|
+
invalidate() {
|
|
1285
|
+
this.layoutRoot.invalidate();
|
|
1286
|
+
}
|
|
1287
|
+
dispose() {
|
|
1288
|
+
if (this.disposed) return;
|
|
1289
|
+
this.disposed = true;
|
|
1290
|
+
this.focusGeneration += 1;
|
|
1291
|
+
this.dividerDragStartRatio = void 0;
|
|
1292
|
+
this.failedRatioSaveGenerationDuringDrag = void 0;
|
|
1293
|
+
this.viewportRouter.dispose();
|
|
1294
|
+
}
|
|
1295
|
+
renderDivider() {
|
|
1296
|
+
return this.options.theme.fg("borderMuted", "\u2502");
|
|
1297
|
+
}
|
|
1298
|
+
handleDividerMouse(event) {
|
|
1299
|
+
if (this.disposed) return void 0;
|
|
1300
|
+
if (this.options.hasFocusedOverlay()) {
|
|
1301
|
+
return { handled: true, render: this.cancelDividerDrag() };
|
|
1360
1302
|
}
|
|
1361
|
-
if (
|
|
1362
|
-
return
|
|
1363
|
-
|
|
1364
|
-
|
|
1303
|
+
if (event.type === "press" && event.button === "left") {
|
|
1304
|
+
if (this.terminalColumns() < MIN_BTW_SPLIT_COLUMNS) return void 0;
|
|
1305
|
+
this.focusGeneration += 1;
|
|
1306
|
+
this.dividerDragStartRatio = this.sidePaneRatio;
|
|
1307
|
+
return { handled: true, capture: true, render: false };
|
|
1308
|
+
}
|
|
1309
|
+
if (this.dividerDragStartRatio === void 0) return void 0;
|
|
1310
|
+
if (event.type === "drag") {
|
|
1311
|
+
const changed = this.updateSidePaneRatio(event.screenX);
|
|
1312
|
+
return { handled: true, render: changed };
|
|
1313
|
+
}
|
|
1314
|
+
if (event.type === "release") {
|
|
1315
|
+
const changed = this.updateSidePaneRatio(event.screenX);
|
|
1316
|
+
const startRatio = this.dividerDragStartRatio;
|
|
1317
|
+
const failedDuringDrag = this.failedRatioSaveGenerationDuringDrag === this.ratioSaveGeneration;
|
|
1318
|
+
this.dividerDragStartRatio = void 0;
|
|
1319
|
+
this.failedRatioSaveGenerationDuringDrag = void 0;
|
|
1320
|
+
if (failedDuringDrag && this.sidePaneRatio === this.persistedSidePaneRatio) {
|
|
1321
|
+
return { handled: true, render: changed };
|
|
1322
|
+
}
|
|
1323
|
+
if (this.sidePaneRatio !== startRatio) {
|
|
1324
|
+
this.persistCurrentSidePaneRatio();
|
|
1325
|
+
return { handled: true, render: changed };
|
|
1326
|
+
}
|
|
1327
|
+
const restored = failedDuringDrag && this.restorePersistedSidePaneRatio();
|
|
1328
|
+
return { handled: true, render: changed || restored };
|
|
1329
|
+
}
|
|
1330
|
+
return { handled: true, render: false };
|
|
1331
|
+
}
|
|
1332
|
+
updateSidePaneRatio(dividerColumn) {
|
|
1333
|
+
const width = this.terminalColumns();
|
|
1334
|
+
if (width < MIN_BTW_SPLIT_COLUMNS) return false;
|
|
1335
|
+
const contentWidth = width - PANE_DIVIDER_COLUMNS;
|
|
1336
|
+
const leftWidth = clamp(Math.floor(dividerColumn), 1, contentWidth - 1);
|
|
1337
|
+
const sideWidth = this.options.layout === "left-pane" ? leftWidth : contentWidth - leftWidth;
|
|
1338
|
+
const ratio = clampSidePaneRatio(roundPaneRatio(sideWidth / contentWidth));
|
|
1339
|
+
if (ratio === this.sidePaneRatio) return false;
|
|
1340
|
+
this.sidePaneRatio = ratio;
|
|
1341
|
+
return true;
|
|
1342
|
+
}
|
|
1343
|
+
cancelDividerDrag() {
|
|
1344
|
+
const startRatio = this.dividerDragStartRatio;
|
|
1345
|
+
if (startRatio === void 0) return false;
|
|
1346
|
+
const failedDuringDrag = this.failedRatioSaveGenerationDuringDrag === this.ratioSaveGeneration;
|
|
1347
|
+
this.dividerDragStartRatio = void 0;
|
|
1348
|
+
this.failedRatioSaveGenerationDuringDrag = void 0;
|
|
1349
|
+
return this.setSidePaneRatio(failedDuringDrag ? this.persistedSidePaneRatio : startRatio);
|
|
1350
|
+
}
|
|
1351
|
+
persistCurrentSidePaneRatio() {
|
|
1352
|
+
const persist = this.options.persistSidePaneRatio;
|
|
1353
|
+
const ratio = this.sidePaneRatio;
|
|
1354
|
+
if (!persist) {
|
|
1355
|
+
this.persistedSidePaneRatio = ratio;
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
this.failedRatioSaveGenerationDuringDrag = void 0;
|
|
1359
|
+
const saveGeneration = ++this.ratioSaveGeneration;
|
|
1360
|
+
void Promise.resolve().then(() => persist(ratio)).then(() => {
|
|
1361
|
+
if (saveGeneration <= this.confirmedRatioSaveGeneration) return;
|
|
1362
|
+
this.confirmedRatioSaveGeneration = saveGeneration;
|
|
1363
|
+
this.persistedSidePaneRatio = ratio;
|
|
1364
|
+
}).catch(() => {
|
|
1365
|
+
if (this.disposed || saveGeneration !== this.ratioSaveGeneration) return;
|
|
1366
|
+
const dragActive = this.dividerDragStartRatio !== void 0;
|
|
1367
|
+
const changed = this.restorePersistedSidePaneRatio();
|
|
1368
|
+
if (dragActive) this.failedRatioSaveGenerationDuringDrag = saveGeneration;
|
|
1369
|
+
if (changed) this.options.requestRender();
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
1372
|
+
restorePersistedSidePaneRatio() {
|
|
1373
|
+
return this.setSidePaneRatio(this.persistedSidePaneRatio);
|
|
1374
|
+
}
|
|
1375
|
+
setSidePaneRatio(ratio) {
|
|
1376
|
+
if (ratio === this.sidePaneRatio) return false;
|
|
1377
|
+
this.sidePaneRatio = ratio;
|
|
1378
|
+
this.layoutRoot.invalidate();
|
|
1379
|
+
return true;
|
|
1380
|
+
}
|
|
1381
|
+
queuePaneFocus(pane) {
|
|
1382
|
+
const generation = ++this.focusGeneration;
|
|
1383
|
+
queueMicrotask(() => {
|
|
1384
|
+
if (this.disposed || generation !== this.focusGeneration || this.options.hasFocusedOverlay()) return;
|
|
1385
|
+
this.activatePane(this.terminalColumns() < MIN_BTW_SPLIT_COLUMNS ? "side" : pane);
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
terminalColumns() {
|
|
1389
|
+
return Math.max(1, Math.floor(this.options.terminalColumns()));
|
|
1390
|
+
}
|
|
1391
|
+
handleViewportWidth(width) {
|
|
1392
|
+
if (this.disposed || width >= MIN_BTW_SPLIT_COLUMNS || this.activePane === "side" || this.options.hasFocusedOverlay()) {
|
|
1393
|
+
return;
|
|
1394
|
+
}
|
|
1395
|
+
this.activatePane("side");
|
|
1396
|
+
}
|
|
1397
|
+
activatePane(pane) {
|
|
1398
|
+
if (this.disposed) return;
|
|
1399
|
+
this.activePane = pane;
|
|
1400
|
+
this.viewportRouter.activate(pane);
|
|
1401
|
+
this.options.setFocus(pane === "side" ? this.options.sideComponent : this.options.mainInput);
|
|
1402
|
+
this.options.requestRender();
|
|
1403
|
+
}
|
|
1404
|
+
forwardPastedInput(data) {
|
|
1405
|
+
const target = this.activePane === "side" ? this.options.sideComponent : this.options.mainInput;
|
|
1406
|
+
target.handleInput?.(data);
|
|
1407
|
+
this.options.requestRender();
|
|
1408
|
+
}
|
|
1409
|
+
};
|
|
1410
|
+
var ResponsivePaneRow = class extends HStack {
|
|
1411
|
+
constructor(left, separator, right, sideIndex, sidePaneRatio, onViewportWidth) {
|
|
1412
|
+
super([
|
|
1413
|
+
{ component: left, basis: 1, grow: 0, shrink: 0, minSize: 1 },
|
|
1414
|
+
{
|
|
1415
|
+
component: separator,
|
|
1416
|
+
basis: PANE_DIVIDER_COLUMNS,
|
|
1417
|
+
grow: 0,
|
|
1418
|
+
shrink: 0,
|
|
1419
|
+
minSize: PANE_DIVIDER_COLUMNS
|
|
1420
|
+
},
|
|
1421
|
+
{ component: right, basis: 1, grow: 0, shrink: 0, minSize: 1 }
|
|
1422
|
+
]);
|
|
1423
|
+
this.sideIndex = sideIndex;
|
|
1424
|
+
this.sidePaneRatio = sidePaneRatio;
|
|
1425
|
+
this.onViewportWidth = onViewportWidth;
|
|
1426
|
+
for (const [index, entry] of this.entries.entries()) {
|
|
1427
|
+
entry.visible = (viewport) => {
|
|
1428
|
+
if (index === 0) this.resize(viewport.width);
|
|
1429
|
+
return index === this.sideIndex || viewport.width >= MIN_BTW_SPLIT_COLUMNS;
|
|
1365
1430
|
};
|
|
1366
1431
|
}
|
|
1367
|
-
const answer = extractAssistantText(response) || "No response received.";
|
|
1368
|
-
thread.turns.push({ kind: "answered", question, answer, response });
|
|
1369
|
-
return { kind: "answered", response, answer };
|
|
1370
|
-
} catch (error) {
|
|
1371
|
-
if (signal?.aborted) return { kind: "aborted" };
|
|
1372
|
-
return { kind: "error", message: formatError(error) };
|
|
1373
1432
|
}
|
|
1433
|
+
sideIndex;
|
|
1434
|
+
sidePaneRatio;
|
|
1435
|
+
onViewportWidth;
|
|
1436
|
+
resize(width) {
|
|
1437
|
+
const safeWidth = Math.max(1, Math.floor(width));
|
|
1438
|
+
this.onViewportWidth(safeWidth);
|
|
1439
|
+
if (safeWidth < MIN_BTW_SPLIT_COLUMNS) {
|
|
1440
|
+
for (const [index, entry] of this.entries.entries()) {
|
|
1441
|
+
entry.basis = index === this.sideIndex ? safeWidth : 1;
|
|
1442
|
+
}
|
|
1443
|
+
return;
|
|
1444
|
+
}
|
|
1445
|
+
const layout = this.sideIndex === 0 ? "left-pane" : "right-pane";
|
|
1446
|
+
const { leftWidth, rightWidth } = paneWidths(safeWidth, layout, this.sidePaneRatio());
|
|
1447
|
+
const left = this.entries[0];
|
|
1448
|
+
const separator = this.entries[1];
|
|
1449
|
+
const right = this.entries[2];
|
|
1450
|
+
if (left) left.basis = leftWidth;
|
|
1451
|
+
if (separator) separator.basis = PANE_DIVIDER_COLUMNS;
|
|
1452
|
+
if (right) right.basis = rightWidth;
|
|
1453
|
+
}
|
|
1454
|
+
};
|
|
1455
|
+
var MainThreadPane = class {
|
|
1456
|
+
constructor(mainThread, mainLayout, theme, terminalRows) {
|
|
1457
|
+
this.terminalRows = terminalRows;
|
|
1458
|
+
this.body = {
|
|
1459
|
+
render: (width) => mainThread.render(Math.max(1, width)).map((line) => truncateToWidth2(line, Math.max(1, width))),
|
|
1460
|
+
invalidate() {
|
|
1461
|
+
}
|
|
1462
|
+
};
|
|
1463
|
+
if (mainLayout) {
|
|
1464
|
+
this.layout = mainLayout;
|
|
1465
|
+
this.scroll = findPrimaryScrollView(mainLayout);
|
|
1466
|
+
return;
|
|
1467
|
+
}
|
|
1468
|
+
this.scroll = new ScrollView(this.body, {
|
|
1469
|
+
follow: "end",
|
|
1470
|
+
scrollbar: "auto",
|
|
1471
|
+
scrollbarTrackStyle: (text) => theme.fg("borderMuted", text),
|
|
1472
|
+
scrollbarThumbStyle: (text) => theme.fg("muted", text)
|
|
1473
|
+
});
|
|
1474
|
+
this.layout = this.scroll;
|
|
1475
|
+
}
|
|
1476
|
+
terminalRows;
|
|
1477
|
+
body;
|
|
1478
|
+
layout;
|
|
1479
|
+
scroll;
|
|
1480
|
+
getLayout() {
|
|
1481
|
+
return this.layout;
|
|
1482
|
+
}
|
|
1483
|
+
getPrimaryScrollView() {
|
|
1484
|
+
return this.scroll;
|
|
1485
|
+
}
|
|
1486
|
+
render(width) {
|
|
1487
|
+
if (width <= 0) return [];
|
|
1488
|
+
const safeWidth = Math.max(1, width);
|
|
1489
|
+
const rows = Math.max(1, this.terminalRows());
|
|
1490
|
+
const visible = this.body.render(safeWidth).slice(-rows);
|
|
1491
|
+
return [...Array.from({ length: Math.max(0, rows - visible.length) }, () => ""), ...visible];
|
|
1492
|
+
}
|
|
1493
|
+
};
|
|
1494
|
+
var PaneViewportRouter = class {
|
|
1495
|
+
constructor(side, main, setViewportTarget) {
|
|
1496
|
+
this.side = side;
|
|
1497
|
+
this.main = main;
|
|
1498
|
+
this.setViewportTarget = setViewportTarget;
|
|
1499
|
+
for (const scrollView of [side, main]) {
|
|
1500
|
+
if (scrollView) this.originalPrimary.set(scrollView, scrollView.primary);
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
side;
|
|
1504
|
+
main;
|
|
1505
|
+
setViewportTarget;
|
|
1506
|
+
originalPrimary = /* @__PURE__ */ new Map();
|
|
1507
|
+
disposed = false;
|
|
1508
|
+
activate(pane) {
|
|
1509
|
+
if (this.disposed) return;
|
|
1510
|
+
const target = pane === "side" ? this.side : this.main;
|
|
1511
|
+
for (const scrollView of this.originalPrimary.keys()) setScrollViewPrimary(scrollView, scrollView === target);
|
|
1512
|
+
this.setViewportTarget(target);
|
|
1513
|
+
}
|
|
1514
|
+
dispose() {
|
|
1515
|
+
if (this.disposed) return;
|
|
1516
|
+
this.disposed = true;
|
|
1517
|
+
for (const [scrollView, primary] of this.originalPrimary) setScrollViewPrimary(scrollView, primary);
|
|
1518
|
+
this.setViewportTarget(void 0);
|
|
1519
|
+
}
|
|
1520
|
+
};
|
|
1521
|
+
function setScrollViewPrimary(scrollView, primary) {
|
|
1522
|
+
Reflect.set(scrollView, "primary", primary);
|
|
1523
|
+
}
|
|
1524
|
+
function findPrimaryScrollView(root) {
|
|
1525
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1526
|
+
let fallback;
|
|
1527
|
+
let primary;
|
|
1528
|
+
const visit = (component) => {
|
|
1529
|
+
if (visited.has(component)) return;
|
|
1530
|
+
visited.add(component);
|
|
1531
|
+
if (component instanceof ScrollView) {
|
|
1532
|
+
fallback ??= component;
|
|
1533
|
+
if (component.primary) primary = component;
|
|
1534
|
+
}
|
|
1535
|
+
if (!("children" in component) || !Array.isArray(component.children)) return;
|
|
1536
|
+
for (const child of component.children) visit(child);
|
|
1537
|
+
};
|
|
1538
|
+
visit(root);
|
|
1539
|
+
return primary ?? fallback;
|
|
1540
|
+
}
|
|
1541
|
+
function paneForMouseClick(data, terminalColumns, layout, sidePaneRatio) {
|
|
1542
|
+
const match = SGR_MOUSE_PRESS_PATTERN.exec(data);
|
|
1543
|
+
if (!match) return void 0;
|
|
1544
|
+
const button = Number.parseInt(match[1] ?? "", 10);
|
|
1545
|
+
if ((button & 32) !== 0 || (button & 64) !== 0 || (button & 3) !== 0) return void 0;
|
|
1546
|
+
const column = Number.parseInt(match[2] ?? "", 10) - 1;
|
|
1547
|
+
if (!Number.isFinite(column) || column < 0 || column >= terminalColumns) return void 0;
|
|
1548
|
+
const { leftWidth } = paneWidths(terminalColumns, layout, sidePaneRatio);
|
|
1549
|
+
if (column >= leftWidth && column < leftWidth + PANE_DIVIDER_COLUMNS) return void 0;
|
|
1550
|
+
const clickedLeft = column < leftWidth;
|
|
1551
|
+
if (layout === "left-pane") return clickedLeft ? "side" : "main";
|
|
1552
|
+
return clickedLeft ? "main" : "side";
|
|
1553
|
+
}
|
|
1554
|
+
function paneWidths(width, layout, sidePaneRatio) {
|
|
1555
|
+
const contentWidth = Math.max(2, width - PANE_DIVIDER_COLUMNS);
|
|
1556
|
+
const sideWidth = clamp(
|
|
1557
|
+
Math.round(contentWidth * clampSidePaneRatio(sidePaneRatio)),
|
|
1558
|
+
1,
|
|
1559
|
+
Math.max(1, contentWidth - 1)
|
|
1560
|
+
);
|
|
1561
|
+
const mainWidth = Math.max(1, contentWidth - sideWidth);
|
|
1562
|
+
const leftWidth = layout === "left-pane" ? sideWidth : mainWidth;
|
|
1563
|
+
const rightWidth = layout === "left-pane" ? mainWidth : sideWidth;
|
|
1564
|
+
return { leftWidth, rightWidth, sideWidth, mainWidth };
|
|
1374
1565
|
}
|
|
1375
|
-
function
|
|
1376
|
-
return
|
|
1377
|
-
(content) => content !== null && typeof content === "object" && content.type === "text" && typeof content.text === "string"
|
|
1378
|
-
).map((content) => content.text).join("\n").trim();
|
|
1379
|
-
}
|
|
1380
|
-
function isAssistantMessage(value) {
|
|
1381
|
-
if (value === null || typeof value !== "object") return false;
|
|
1382
|
-
const candidate = value;
|
|
1383
|
-
return candidate.role === "assistant" && Array.isArray(candidate.content) && typeof candidate.stopReason === "string";
|
|
1384
|
-
}
|
|
1385
|
-
function buildUserPrompt(question, conversationContext) {
|
|
1386
|
-
return [
|
|
1387
|
-
"Answer this side question without modifying the main conversation.",
|
|
1388
|
-
"",
|
|
1389
|
-
"<side_question>",
|
|
1390
|
-
question,
|
|
1391
|
-
"</side_question>",
|
|
1392
|
-
"",
|
|
1393
|
-
"<conversation_context>",
|
|
1394
|
-
conversationContext || "No prior conversation context was available.",
|
|
1395
|
-
"</conversation_context>"
|
|
1396
|
-
].join("\n");
|
|
1566
|
+
function clampSidePaneRatio(ratio) {
|
|
1567
|
+
return Number.isFinite(ratio) ? clamp(ratio, MIN_BTW_SIDE_PANE_RATIO, MAX_BTW_SIDE_PANE_RATIO) : DEFAULT_BTW_SIDE_PANE_RATIO;
|
|
1397
1568
|
}
|
|
1398
|
-
function
|
|
1399
|
-
return
|
|
1569
|
+
function roundPaneRatio(ratio) {
|
|
1570
|
+
return Math.round(ratio * 1e4) / 1e4;
|
|
1400
1571
|
}
|
|
1401
|
-
function
|
|
1402
|
-
return
|
|
1403
|
-
role: "user",
|
|
1404
|
-
content: [{ type: "text", text }],
|
|
1405
|
-
timestamp: Date.now()
|
|
1406
|
-
};
|
|
1572
|
+
function clamp(value, minimum, maximum) {
|
|
1573
|
+
return Math.max(minimum, Math.min(maximum, value));
|
|
1407
1574
|
}
|
|
1408
|
-
function
|
|
1409
|
-
|
|
1410
|
-
return { "x-opencode-session": sessionId, "x-opencode-client": "pi" };
|
|
1575
|
+
function hasInput(component) {
|
|
1576
|
+
return component !== null && typeof component.handleInput === "function";
|
|
1411
1577
|
}
|
|
1412
|
-
function
|
|
1413
|
-
|
|
1414
|
-
return {
|
|
1578
|
+
function padLine(line, width) {
|
|
1579
|
+
const truncated = truncateToWidth2(line, width);
|
|
1580
|
+
return `${truncated}${" ".repeat(Math.max(0, width - visibleWidth2(truncated)))}`;
|
|
1415
1581
|
}
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
signal
|
|
1423
|
-
};
|
|
1424
|
-
if (applyRequestHeaderTransforms && sessionHeaders) {
|
|
1425
|
-
options.transformHeaders = (headers) => mergeSessionHeaders(headers, sessionHeaders) ?? {};
|
|
1582
|
+
|
|
1583
|
+
// src/fullscreen-ui.ts
|
|
1584
|
+
var FullscreenUiDisposedError = class extends Error {
|
|
1585
|
+
constructor() {
|
|
1586
|
+
super("The dedicated pi-btw UI was disposed.");
|
|
1587
|
+
this.name = "FullscreenUiDisposedError";
|
|
1426
1588
|
}
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1589
|
+
};
|
|
1590
|
+
async function runBtwFullscreen(ctx, run, options = {}, dependencies = {}) {
|
|
1591
|
+
const createTui = dependencies.createTui ?? ((parent, theme, keybindings, fullscreenOptions) => createBtwFullscreenTui(
|
|
1592
|
+
parent,
|
|
1593
|
+
theme,
|
|
1594
|
+
keybindings,
|
|
1595
|
+
fullscreenOptions.copyOnSelect ?? true,
|
|
1596
|
+
dependencies.manualSelectionCopySupported ?? hasManualSelectionCopyApi(),
|
|
1597
|
+
dependencies.openUrl ?? openUrlInBrowser,
|
|
1598
|
+
dependencies.copyToClipboard ?? copyToHostClipboard
|
|
1599
|
+
));
|
|
1600
|
+
let liveEditorText = ctx.ui.getEditorText();
|
|
1601
|
+
let restoreEditor = false;
|
|
1602
|
+
let host;
|
|
1603
|
+
const outcome = await ctx.ui.custom(
|
|
1604
|
+
(parent, theme, keybindings, done) => {
|
|
1605
|
+
host = new BtwFullscreenHost(
|
|
1606
|
+
parent,
|
|
1607
|
+
theme,
|
|
1608
|
+
keybindings,
|
|
1609
|
+
ctx,
|
|
1610
|
+
run,
|
|
1611
|
+
(value) => {
|
|
1612
|
+
try {
|
|
1613
|
+
liveEditorText = ctx.ui.getEditorText();
|
|
1614
|
+
restoreEditor = true;
|
|
1615
|
+
} catch {
|
|
1616
|
+
}
|
|
1617
|
+
done(value);
|
|
1618
|
+
},
|
|
1619
|
+
createTui,
|
|
1620
|
+
options
|
|
1621
|
+
);
|
|
1622
|
+
return host;
|
|
1623
|
+
},
|
|
1624
|
+
{
|
|
1625
|
+
overlay: true,
|
|
1626
|
+
onHandle: (handle) => host?.setParentOverlay(handle)
|
|
1627
|
+
}
|
|
1628
|
+
);
|
|
1629
|
+
if (restoreEditor) {
|
|
1630
|
+
try {
|
|
1631
|
+
if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
|
|
1632
|
+
} catch {
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
if (outcome.kind === "failed") throw outcome.error;
|
|
1636
|
+
return outcome.value;
|
|
1432
1637
|
}
|
|
1433
|
-
var
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
return join(getAgentDir(), BTW_SETTINGS_FILE);
|
|
1638
|
+
var btwInputListeners = /* @__PURE__ */ new WeakMap();
|
|
1639
|
+
function dispatchBtwInput(listeners, data) {
|
|
1640
|
+
let current = data;
|
|
1641
|
+
for (const group of [listeners.beforeAll, listeners.beforeViewport, listeners.regular]) {
|
|
1642
|
+
for (const listener of group) {
|
|
1643
|
+
const result = listener(current);
|
|
1644
|
+
if (result?.consume) return result;
|
|
1645
|
+
if (result?.data !== void 0) current = result.data;
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
return current === data ? void 0 : { data: current };
|
|
1445
1649
|
}
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
if (!
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1650
|
+
var BtwTuiAltScreen = class extends TuiAltScreen {
|
|
1651
|
+
hasFocusedOverlay() {
|
|
1652
|
+
return this.isOverlayFocused();
|
|
1653
|
+
}
|
|
1654
|
+
setViewportTarget(scrollView) {
|
|
1655
|
+
if (!scrollView) return;
|
|
1656
|
+
const layout = Reflect.get(this, "currentLayout");
|
|
1657
|
+
if (layout) layout.primaryScrollView = scrollView;
|
|
1658
|
+
}
|
|
1659
|
+
addInputListener(listener) {
|
|
1660
|
+
let listeners = btwInputListeners.get(this);
|
|
1661
|
+
if (!listeners) {
|
|
1662
|
+
const registeredListeners = {
|
|
1663
|
+
beforeAll: /* @__PURE__ */ new Set(),
|
|
1664
|
+
beforeViewport: /* @__PURE__ */ new Set(),
|
|
1665
|
+
regular: /* @__PURE__ */ new Set()
|
|
1666
|
+
};
|
|
1667
|
+
btwInputListeners.set(this, registeredListeners);
|
|
1668
|
+
super.addInputListener((data) => dispatchBtwInput(registeredListeners, data));
|
|
1669
|
+
listeners = registeredListeners;
|
|
1458
1670
|
}
|
|
1671
|
+
listeners.regular.add(listener);
|
|
1672
|
+
return () => listeners.regular.delete(listener);
|
|
1459
1673
|
}
|
|
1460
|
-
|
|
1461
|
-
const
|
|
1462
|
-
if (
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
if (Object.hasOwn(value, "thinkingLevel")) {
|
|
1466
|
-
const thinkingLevel = Reflect.get(value, "thinkingLevel");
|
|
1467
|
-
if (!isBtwThinkingLevel(thinkingLevel)) return void 0;
|
|
1468
|
-
settings.thinkingLevel = thinkingLevel;
|
|
1674
|
+
addInputListenerBeforeAll(listener) {
|
|
1675
|
+
const listeners = btwInputListeners.get(this);
|
|
1676
|
+
if (!listeners) return super.addInputListener(listener);
|
|
1677
|
+
listeners.beforeAll.add(listener);
|
|
1678
|
+
return () => listeners.beforeAll.delete(listener);
|
|
1469
1679
|
}
|
|
1470
|
-
|
|
1471
|
-
const
|
|
1472
|
-
if (
|
|
1473
|
-
|
|
1680
|
+
addInputListenerBeforeViewport(listener) {
|
|
1681
|
+
const listeners = btwInputListeners.get(this);
|
|
1682
|
+
if (!listeners) return super.addInputListener(listener);
|
|
1683
|
+
listeners.beforeViewport.add(listener);
|
|
1684
|
+
return () => listeners.beforeViewport.delete(listener);
|
|
1474
1685
|
}
|
|
1475
|
-
|
|
1476
|
-
const
|
|
1477
|
-
if (
|
|
1478
|
-
|
|
1686
|
+
removeInputListener(listener) {
|
|
1687
|
+
const listeners = btwInputListeners.get(this);
|
|
1688
|
+
if (!listeners) {
|
|
1689
|
+
super.removeInputListener(listener);
|
|
1690
|
+
return;
|
|
1691
|
+
}
|
|
1692
|
+
listeners.beforeAll.delete(listener);
|
|
1693
|
+
listeners.beforeViewport.delete(listener);
|
|
1694
|
+
listeners.regular.delete(listener);
|
|
1479
1695
|
}
|
|
1480
|
-
|
|
1696
|
+
};
|
|
1697
|
+
var BRACKETED_PASTE_START = "\x1B[200~";
|
|
1698
|
+
var BRACKETED_PASTE_END = "\x1B[201~";
|
|
1699
|
+
var ALT_SCREEN_ACTIONS_BEFORE_BOTTOM = [
|
|
1700
|
+
"tui.altScreen.search",
|
|
1701
|
+
"tui.altScreen.searchNext",
|
|
1702
|
+
"tui.altScreen.searchPrevious",
|
|
1703
|
+
"tui.altScreen.searchClose",
|
|
1704
|
+
"tui.altScreen.pageUp",
|
|
1705
|
+
"tui.altScreen.pageDown",
|
|
1706
|
+
"tui.altScreen.halfPageUp",
|
|
1707
|
+
"tui.altScreen.halfPageDown",
|
|
1708
|
+
"tui.altScreen.lineUp",
|
|
1709
|
+
"tui.altScreen.lineDown",
|
|
1710
|
+
"tui.altScreen.previousPrompt",
|
|
1711
|
+
"tui.altScreen.nextPrompt",
|
|
1712
|
+
"tui.altScreen.top"
|
|
1713
|
+
];
|
|
1714
|
+
var KEY_MODIFIER_ORDER = ["shift", "ctrl", "alt", "super"];
|
|
1715
|
+
var MATCHABLE_SPECIAL_KEYS = /* @__PURE__ */ new Set([
|
|
1716
|
+
"space",
|
|
1717
|
+
"tab",
|
|
1718
|
+
"enter",
|
|
1719
|
+
"backspace",
|
|
1720
|
+
"delete",
|
|
1721
|
+
"insert",
|
|
1722
|
+
"home",
|
|
1723
|
+
"end",
|
|
1724
|
+
"pageup",
|
|
1725
|
+
"pagedown",
|
|
1726
|
+
"up",
|
|
1727
|
+
"down",
|
|
1728
|
+
"left",
|
|
1729
|
+
"right"
|
|
1730
|
+
]);
|
|
1731
|
+
var MATCHABLE_SYMBOL_KEYS = new Set("`-=[]\\;',./!@#$%^&*()_+|~{}:<>?");
|
|
1732
|
+
function normalizedKeyId(key) {
|
|
1733
|
+
const parts = key.toLowerCase().split("+");
|
|
1734
|
+
const base = parts.at(-1);
|
|
1735
|
+
if (!base) return "";
|
|
1736
|
+
const normalizedBase = base === "esc" ? "escape" : base === "return" ? "enter" : base;
|
|
1737
|
+
const modifiers = KEY_MODIFIER_ORDER.filter((modifier) => parts.includes(modifier));
|
|
1738
|
+
return [...modifiers, normalizedBase].join("+");
|
|
1481
1739
|
}
|
|
1482
|
-
function
|
|
1483
|
-
|
|
1484
|
-
const
|
|
1485
|
-
if (
|
|
1486
|
-
|
|
1740
|
+
function formatEffectiveKeyLabel(key) {
|
|
1741
|
+
const parts = key.split("+");
|
|
1742
|
+
const base = parts.at(-1);
|
|
1743
|
+
if (base === "pageup") parts[parts.length - 1] = "pageUp";
|
|
1744
|
+
if (base === "pagedown") parts[parts.length - 1] = "pageDown";
|
|
1745
|
+
return formatKeyLabel2(parts.join("+"));
|
|
1487
1746
|
}
|
|
1488
|
-
function
|
|
1489
|
-
|
|
1747
|
+
function canMatchKeyInput(key) {
|
|
1748
|
+
const parts = key.split("+");
|
|
1749
|
+
const base = parts.at(-1) ?? "";
|
|
1750
|
+
const modifiers = parts.slice(0, -1);
|
|
1751
|
+
if (base === "escape") return modifiers.length === 0;
|
|
1752
|
+
if (base === "clear") {
|
|
1753
|
+
return modifiers.length === 0 || modifiers.length === 1 && (modifiers[0] === "shift" || modifiers[0] === "ctrl");
|
|
1754
|
+
}
|
|
1755
|
+
if (/^f(?:[1-9]|1[0-2])$/u.test(base)) return modifiers.length === 0;
|
|
1756
|
+
return MATCHABLE_SPECIAL_KEYS.has(base) || base.length === 1 && (/^[a-z0-9]$/u.test(base) || MATCHABLE_SYMBOL_KEYS.has(base));
|
|
1490
1757
|
}
|
|
1491
|
-
function
|
|
1492
|
-
|
|
1758
|
+
function rawCtrlInput(base) {
|
|
1759
|
+
if (base.length !== 1) return void 0;
|
|
1760
|
+
const rawBase = base === "-" ? "_" : base;
|
|
1761
|
+
if (!"abcdefghijklmnopqrstuvwxyz[\\]_".includes(rawBase)) return void 0;
|
|
1762
|
+
return String.fromCharCode(rawBase.charCodeAt(0) & 31);
|
|
1493
1763
|
}
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1764
|
+
function legacyRawInput(key) {
|
|
1765
|
+
const parts = key.split("+");
|
|
1766
|
+
const base = parts.at(-1) ?? "";
|
|
1767
|
+
if (parts.length === 2 && parts[0] === "ctrl") return rawCtrlInput(base);
|
|
1768
|
+
if (isKittyProtocolActive2()) return void 0;
|
|
1769
|
+
if (parts.length === 2 && parts[0] === "alt" && base.length === 1) return `\x1B${base}`;
|
|
1770
|
+
if (parts.length === 3 && parts[0] === "ctrl" && parts[1] === "alt") {
|
|
1771
|
+
const input = rawCtrlInput(base);
|
|
1772
|
+
return input ? `\x1B${input}` : void 0;
|
|
1773
|
+
}
|
|
1774
|
+
return void 0;
|
|
1497
1775
|
}
|
|
1498
|
-
function
|
|
1499
|
-
const
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
const current = await readSettingsDocumentForUpdate(settingsPath);
|
|
1503
|
-
options.signal?.throwIfAborted();
|
|
1504
|
-
options.validateCurrent?.(normalizeBtwSettings(current) ?? {});
|
|
1505
|
-
const updated = applyBtwSettingsPatch(current, patch);
|
|
1506
|
-
const settings = normalizeBtwSettings(updated);
|
|
1507
|
-
if (!settings) throw invalidSettingsError(settingsPath, "invalid settings shape");
|
|
1508
|
-
await publishSettings(settingsPath, updated, options.signal, options.beforeRename);
|
|
1509
|
-
return settings;
|
|
1510
|
-
});
|
|
1776
|
+
function keyInputIdentity(key) {
|
|
1777
|
+
const identity = normalizedKeyId(key);
|
|
1778
|
+
const input = legacyRawInput(identity);
|
|
1779
|
+
return input ? normalizedKeyId(parseKey(input) ?? identity) : identity;
|
|
1511
1780
|
}
|
|
1512
|
-
|
|
1513
|
-
|
|
1781
|
+
function hasManualSelectionCopyApi() {
|
|
1782
|
+
return typeof TuiAltScreen.prototype.hasActiveSelection === "function" && typeof TuiAltScreen.prototype.copyActiveSelectionToClipboard === "function";
|
|
1514
1783
|
}
|
|
1515
|
-
function
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
);
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1784
|
+
function createBtwFullscreenTui(parent, theme, keybindings, copyOnSelect, manualSelectionCopySupported, openUrl, copyToClipboard2) {
|
|
1785
|
+
if (!copyOnSelect && !manualSelectionCopySupported) {
|
|
1786
|
+
throw new Error(
|
|
1787
|
+
"Manual fullscreen selection copying is unavailable in this Pi version; update Pi or enable automatic selection copying."
|
|
1788
|
+
);
|
|
1789
|
+
}
|
|
1790
|
+
const styleSearchMatch = (text) => theme.bg("searchMatchBg", theme.fg("searchMatchText", text));
|
|
1791
|
+
const fullscreen = new BtwTuiAltScreen(parent.terminal, parent.getShowHardwareCursor(), void 0, {
|
|
1792
|
+
mouse: true,
|
|
1793
|
+
copyOnSelect,
|
|
1794
|
+
searchMatchStyle: (text) => theme.underline(styleSearchMatch(text)),
|
|
1795
|
+
scrollToEndIndicator: () => {
|
|
1796
|
+
const unavailableKeyIdentities = /* @__PURE__ */ new Set([keyInputIdentity(Key2.ctrl("c"))]);
|
|
1797
|
+
for (const action of ALT_SCREEN_ACTIONS_BEFORE_BOTTOM) {
|
|
1798
|
+
for (const actionKey of keybindings.getKeys(action)) {
|
|
1799
|
+
unavailableKeyIdentities.add(keyInputIdentity(String(actionKey)));
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
if (!copyOnSelect) {
|
|
1803
|
+
for (const copyKey of keybindings.getKeys("app.message.copy")) {
|
|
1804
|
+
unavailableKeyIdentities.add(keyInputIdentity(String(copyKey)));
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
const key = keybindings.getKeys("tui.altScreen.bottom").map((candidate) => keyInputIdentity(String(candidate))).find(
|
|
1808
|
+
(identity) => identity && canMatchKeyInput(identity) && !unavailableKeyIdentities.has(identity) && formatEffectiveKeyLabel(identity)
|
|
1809
|
+
);
|
|
1810
|
+
const label = theme.fg("text", " \u2193 Jump to latest message");
|
|
1811
|
+
const shortcut = key ? theme.fg("muted", ` \xB7 ${formatEffectiveKeyLabel(key)}`) : "";
|
|
1812
|
+
return theme.bg("selectedBg", `${label}${shortcut} `);
|
|
1813
|
+
},
|
|
1814
|
+
searchCurrentMatchStyle: (text) => theme.bold(theme.inverse(styleSearchMatch(text))),
|
|
1815
|
+
openUrl,
|
|
1816
|
+
copySelection: async (text) => {
|
|
1817
|
+
try {
|
|
1818
|
+
await copyToClipboard2(text);
|
|
1819
|
+
return true;
|
|
1820
|
+
} catch {
|
|
1821
|
+
return false;
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1525
1824
|
});
|
|
1526
|
-
|
|
1825
|
+
if (!copyOnSelect) {
|
|
1826
|
+
let isInBracketedPaste = false;
|
|
1827
|
+
fullscreen.addInputListenerBeforeViewport((data) => {
|
|
1828
|
+
const wasInBracketedPaste = isInBracketedPaste;
|
|
1829
|
+
const startsBracketedPaste = data.includes(BRACKETED_PASTE_START);
|
|
1830
|
+
if (startsBracketedPaste) isInBracketedPaste = true;
|
|
1831
|
+
if (isInBracketedPaste && data.includes(BRACKETED_PASTE_END)) {
|
|
1832
|
+
isInBracketedPaste = false;
|
|
1833
|
+
}
|
|
1834
|
+
if (wasInBracketedPaste || startsBracketedPaste || fullscreen.hasFocusedOverlay() || isKeyRelease2(data) || !keybindings.matches(data, "app.message.copy")) {
|
|
1835
|
+
return void 0;
|
|
1836
|
+
}
|
|
1837
|
+
if (!fullscreen.hasActiveSelection()) {
|
|
1838
|
+
fullscreen.flash("No selection to copy");
|
|
1839
|
+
return { consume: true };
|
|
1840
|
+
}
|
|
1841
|
+
void fullscreen.copyActiveSelectionToClipboard().catch(() => fullscreen.flash("Copy failed"));
|
|
1842
|
+
return { consume: true };
|
|
1843
|
+
});
|
|
1844
|
+
}
|
|
1845
|
+
return fullscreen;
|
|
1527
1846
|
}
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1847
|
+
function openUrlInBrowser(target) {
|
|
1848
|
+
const [command, args] = process.platform === "darwin" ? ["open", [target]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", target]] : ["xdg-open", [target]];
|
|
1849
|
+
spawn(command, args, { stdio: "ignore", detached: true }).on("error", () => {
|
|
1850
|
+
}).unref();
|
|
1851
|
+
}
|
|
1852
|
+
var BtwFullscreenHost = class {
|
|
1853
|
+
constructor(parent, theme, keybindings, ctx, run, done, createTui, options) {
|
|
1854
|
+
this.parent = parent;
|
|
1855
|
+
this.theme = theme;
|
|
1856
|
+
this.keybindings = keybindings;
|
|
1857
|
+
this.ctx = ctx;
|
|
1858
|
+
this.run = run;
|
|
1859
|
+
this.done = done;
|
|
1860
|
+
this.createTui = createTui;
|
|
1861
|
+
this.options = options;
|
|
1862
|
+
const initialMainInput = getFocusedComponent(parent);
|
|
1863
|
+
this.mainThreadInput = new BtwMainThreadInput(
|
|
1864
|
+
initialMainInput,
|
|
1865
|
+
() => {
|
|
1866
|
+
const target = getFocusedComponent(parent);
|
|
1867
|
+
return target === this ? initialMainInput : target;
|
|
1868
|
+
},
|
|
1869
|
+
() => this.fullscreen?.requestRender()
|
|
1870
|
+
);
|
|
1871
|
+
this.sidePaneRatio = options.sidePaneRatio;
|
|
1872
|
+
queueMicrotask(() => void this.start());
|
|
1873
|
+
}
|
|
1874
|
+
parent;
|
|
1875
|
+
theme;
|
|
1876
|
+
keybindings;
|
|
1877
|
+
ctx;
|
|
1878
|
+
run;
|
|
1879
|
+
done;
|
|
1880
|
+
createTui;
|
|
1881
|
+
options;
|
|
1882
|
+
fullscreen;
|
|
1883
|
+
parentOverlay;
|
|
1884
|
+
cancelActiveCustom;
|
|
1885
|
+
hardCancelActiveCustom;
|
|
1886
|
+
removeHardCancelListener;
|
|
1887
|
+
removeUpstreamAbortListener;
|
|
1888
|
+
started = false;
|
|
1889
|
+
disposed = false;
|
|
1890
|
+
finished = false;
|
|
1891
|
+
parentStopped = false;
|
|
1892
|
+
parentRestoreAttempted = false;
|
|
1893
|
+
fullscreenCreated = false;
|
|
1894
|
+
fullscreenStopped = false;
|
|
1895
|
+
parentRestoreQueued = false;
|
|
1896
|
+
parentRestorePromise;
|
|
1897
|
+
cleanupError;
|
|
1898
|
+
removeMainThreadUpdateListener;
|
|
1899
|
+
mainThreadRefreshTimer;
|
|
1900
|
+
mainThreadInput;
|
|
1901
|
+
lifetimeController = new AbortController();
|
|
1902
|
+
pendingSidePaneWrites = /* @__PURE__ */ new Set();
|
|
1903
|
+
sidePaneRatio;
|
|
1904
|
+
sidePaneWriteGeneration = 0;
|
|
1905
|
+
confirmedSidePaneWriteGeneration = 0;
|
|
1906
|
+
setParentOverlay(overlay) {
|
|
1907
|
+
this.parentOverlay = overlay;
|
|
1535
1908
|
}
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
return settings ? { kind: "loaded", settings } : { kind: "invalid", reason: `${settingsPath}: invalid settings shape` };
|
|
1539
|
-
} catch {
|
|
1540
|
-
return { kind: "invalid", reason: `${settingsPath}: invalid JSON` };
|
|
1909
|
+
render(width) {
|
|
1910
|
+
return [truncateToWidth3(this.theme.fg("muted", "Opening btw side thread\u2026"), width)];
|
|
1541
1911
|
}
|
|
1542
|
-
|
|
1543
|
-
async function readSettingsDocumentForUpdate(settingsPath) {
|
|
1544
|
-
let contents;
|
|
1545
|
-
try {
|
|
1546
|
-
contents = await readSettingsContents(settingsPath);
|
|
1547
|
-
} catch (error) {
|
|
1548
|
-
if (isNodeError(error) && error.code === "ENOENT") return {};
|
|
1549
|
-
throw invalidSettingsError(settingsPath, formatError2(error));
|
|
1912
|
+
invalidate() {
|
|
1550
1913
|
}
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1914
|
+
dispose() {
|
|
1915
|
+
if (this.disposed || this.finished) return;
|
|
1916
|
+
this.disposed = true;
|
|
1917
|
+
this.lifetimeController.abort();
|
|
1918
|
+
this.cancelActiveCustom?.();
|
|
1556
1919
|
}
|
|
1557
|
-
|
|
1558
|
-
|
|
1920
|
+
async start() {
|
|
1921
|
+
if (this.started || this.finished) return;
|
|
1922
|
+
this.started = true;
|
|
1923
|
+
this.watchUpstreamCancellation();
|
|
1924
|
+
let outcome;
|
|
1925
|
+
try {
|
|
1926
|
+
if (this.disposed) throw new FullscreenUiDisposedError();
|
|
1927
|
+
this.parent.stop({ preserveScreen: true });
|
|
1928
|
+
this.parentStopped = true;
|
|
1929
|
+
if (this.disposed) throw new FullscreenUiDisposedError();
|
|
1930
|
+
this.fullscreen = this.createTui(this.parent, this.theme, this.keybindings, this.options);
|
|
1931
|
+
this.fullscreenCreated = true;
|
|
1932
|
+
this.fullscreen.start();
|
|
1933
|
+
this.watchMainThreadUpdates();
|
|
1934
|
+
const shortcuts = resolveBtwShortcuts(
|
|
1935
|
+
this.options.keybindings,
|
|
1936
|
+
this.keybindings,
|
|
1937
|
+
this.options.copyOnSelect ?? true
|
|
1938
|
+
);
|
|
1939
|
+
setBtwShortcuts(this.fullscreen, shortcuts);
|
|
1940
|
+
let previousWarnings = [];
|
|
1941
|
+
const reportWarnings = () => {
|
|
1942
|
+
const warnings = shortcuts.warnings;
|
|
1943
|
+
for (const warning of warnings) {
|
|
1944
|
+
if (previousWarnings.includes(warning)) continue;
|
|
1945
|
+
try {
|
|
1946
|
+
this.ctx.ui.notify(`Pi BTW: ${warning}`, "warning");
|
|
1947
|
+
} catch {
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
previousWarnings = warnings;
|
|
1951
|
+
};
|
|
1952
|
+
const pasteGuard = new BtwPasteGuard();
|
|
1953
|
+
const addHardCancelListener = this.fullscreen.addInputListenerBeforeAll?.bind(this.fullscreen) ?? this.fullscreen.addInputListenerBeforeViewport?.bind(this.fullscreen) ?? this.fullscreen.addInputListener.bind(this.fullscreen);
|
|
1954
|
+
this.removeHardCancelListener = addHardCancelListener((data) => {
|
|
1955
|
+
reportWarnings();
|
|
1956
|
+
if (pasteGuard.consume(data) || !shortcuts.matches(data, "exit")) return void 0;
|
|
1957
|
+
this.disposed = true;
|
|
1958
|
+
this.lifetimeController.abort();
|
|
1959
|
+
try {
|
|
1960
|
+
this.hardCancelActiveCustom?.();
|
|
1961
|
+
} finally {
|
|
1962
|
+
this.queueParentRestore();
|
|
1963
|
+
}
|
|
1964
|
+
return { consume: true };
|
|
1965
|
+
});
|
|
1966
|
+
const value = await this.run(this.createContext());
|
|
1967
|
+
await this.waitForSidePaneWrites();
|
|
1968
|
+
outcome = { kind: "completed", value };
|
|
1969
|
+
} catch (error) {
|
|
1970
|
+
await this.waitForSidePaneWrites();
|
|
1971
|
+
outcome = { kind: "failed", error };
|
|
1972
|
+
}
|
|
1973
|
+
try {
|
|
1974
|
+
this.cancelActiveCustom?.();
|
|
1975
|
+
} catch (error) {
|
|
1976
|
+
this.cleanupError ??= error;
|
|
1977
|
+
}
|
|
1978
|
+
if (this.parentRestorePromise) await this.parentRestorePromise;
|
|
1979
|
+
else this.restoreParent();
|
|
1980
|
+
if (this.cleanupError !== void 0) outcome = { kind: "failed", error: this.cleanupError };
|
|
1981
|
+
this.finished = true;
|
|
1982
|
+
this.done(outcome);
|
|
1559
1983
|
}
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1984
|
+
watchUpstreamCancellation() {
|
|
1985
|
+
const signal = this.ctx.signal;
|
|
1986
|
+
if (!signal) return;
|
|
1987
|
+
const onAbort = () => this.dispose();
|
|
1988
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1989
|
+
this.removeUpstreamAbortListener = () => signal.removeEventListener("abort", onAbort);
|
|
1990
|
+
if (signal.aborted) onAbort();
|
|
1991
|
+
}
|
|
1992
|
+
queueParentRestore() {
|
|
1993
|
+
if (this.parentRestoreQueued || this.parentRestoreAttempted) return;
|
|
1994
|
+
this.parentRestoreQueued = true;
|
|
1995
|
+
this.parentRestorePromise = Promise.resolve().then(async () => {
|
|
1996
|
+
try {
|
|
1997
|
+
await this.fullscreen?.terminal.drainInput?.();
|
|
1998
|
+
} catch (error) {
|
|
1999
|
+
this.cleanupError ??= error;
|
|
2000
|
+
}
|
|
2001
|
+
this.parentRestoreQueued = false;
|
|
2002
|
+
this.restoreParent();
|
|
2003
|
+
});
|
|
2004
|
+
}
|
|
2005
|
+
watchMainThreadUpdates() {
|
|
2006
|
+
if ((this.options.layout ?? "fullscreen") === "fullscreen") return;
|
|
2007
|
+
this.removeMainThreadUpdateListener = this.options.subscribeMainThreadUpdates?.(() => {
|
|
2008
|
+
this.mainThreadInput.refreshTarget();
|
|
2009
|
+
if (this.mainThreadRefreshTimer || this.disposed || this.finished) return;
|
|
2010
|
+
this.mainThreadRefreshTimer = setTimeout(() => {
|
|
2011
|
+
this.mainThreadRefreshTimer = void 0;
|
|
2012
|
+
if (!this.disposed && !this.finished) this.fullscreen?.requestRender();
|
|
2013
|
+
}, 0);
|
|
2014
|
+
this.mainThreadRefreshTimer.unref();
|
|
2015
|
+
});
|
|
2016
|
+
}
|
|
2017
|
+
restoreParent() {
|
|
2018
|
+
if (this.mainThreadRefreshTimer) {
|
|
2019
|
+
clearTimeout(this.mainThreadRefreshTimer);
|
|
2020
|
+
this.mainThreadRefreshTimer = void 0;
|
|
1570
2021
|
}
|
|
1571
|
-
const
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
2022
|
+
const removeMainThreadUpdateListener = this.removeMainThreadUpdateListener;
|
|
2023
|
+
this.removeMainThreadUpdateListener = void 0;
|
|
2024
|
+
try {
|
|
2025
|
+
removeMainThreadUpdateListener?.();
|
|
2026
|
+
} catch (error) {
|
|
2027
|
+
this.cleanupError ??= error;
|
|
1577
2028
|
}
|
|
1578
|
-
|
|
1579
|
-
|
|
2029
|
+
this.mainThreadInput.dispose();
|
|
2030
|
+
const removeUpstreamAbortListener = this.removeUpstreamAbortListener;
|
|
2031
|
+
this.removeUpstreamAbortListener = void 0;
|
|
2032
|
+
try {
|
|
2033
|
+
removeUpstreamAbortListener?.();
|
|
2034
|
+
} catch (error) {
|
|
2035
|
+
this.cleanupError ??= error;
|
|
1580
2036
|
}
|
|
2037
|
+
const removeHardCancelListener = this.removeHardCancelListener;
|
|
2038
|
+
this.removeHardCancelListener = void 0;
|
|
1581
2039
|
try {
|
|
1582
|
-
|
|
1583
|
-
} catch {
|
|
1584
|
-
|
|
2040
|
+
removeHardCancelListener?.();
|
|
2041
|
+
} catch (error) {
|
|
2042
|
+
this.cleanupError ??= error;
|
|
2043
|
+
}
|
|
2044
|
+
if (this.fullscreenCreated && !this.fullscreenStopped) {
|
|
2045
|
+
this.fullscreenStopped = true;
|
|
2046
|
+
try {
|
|
2047
|
+
this.fullscreen?.stop({ preserveScreen: true });
|
|
2048
|
+
} catch (error) {
|
|
2049
|
+
this.cleanupError ??= error;
|
|
2050
|
+
}
|
|
2051
|
+
}
|
|
2052
|
+
if (!this.parentStopped || this.parentRestoreAttempted) return;
|
|
2053
|
+
const parentOverlay = this.parentOverlay;
|
|
2054
|
+
this.parentOverlay = void 0;
|
|
2055
|
+
try {
|
|
2056
|
+
parentOverlay?.setHidden(true);
|
|
2057
|
+
} catch (error) {
|
|
2058
|
+
this.cleanupError ??= error;
|
|
2059
|
+
}
|
|
2060
|
+
try {
|
|
2061
|
+
this.parentRestoreAttempted = true;
|
|
2062
|
+
this.parent.start();
|
|
2063
|
+
this.parent.renderNow(false);
|
|
2064
|
+
} catch (error) {
|
|
2065
|
+
this.cleanupError ??= error;
|
|
1585
2066
|
}
|
|
1586
|
-
} finally {
|
|
1587
|
-
await handle.close();
|
|
1588
2067
|
}
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
2068
|
+
createContext() {
|
|
2069
|
+
const ui = new Proxy(this.ctx.ui, {
|
|
2070
|
+
get: (target, property) => {
|
|
2071
|
+
if (property === "custom") {
|
|
2072
|
+
return (factory, options) => this.showCustom(factory, options);
|
|
2073
|
+
}
|
|
2074
|
+
if (property === "notify") {
|
|
2075
|
+
return (message, level) => {
|
|
2076
|
+
target.notify(message, level);
|
|
2077
|
+
const display = sanitizeSingleLine(message);
|
|
2078
|
+
if (display) this.fullscreen?.flash?.(display);
|
|
2079
|
+
};
|
|
2080
|
+
}
|
|
2081
|
+
const value = Reflect.get(target, property, target);
|
|
2082
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
2083
|
+
}
|
|
2084
|
+
});
|
|
2085
|
+
const signal = this.ctx.signal ? AbortSignal.any([this.ctx.signal, this.lifetimeController.signal]) : this.lifetimeController.signal;
|
|
2086
|
+
return new Proxy(this.ctx, {
|
|
2087
|
+
get: (target, property) => {
|
|
2088
|
+
if (property === "ui") return ui;
|
|
2089
|
+
if (property === "signal") return signal;
|
|
2090
|
+
return Reflect.get(target, property, target);
|
|
2091
|
+
}
|
|
2092
|
+
});
|
|
1596
2093
|
}
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
2094
|
+
showCustom(factory, options) {
|
|
2095
|
+
const fullscreen = this.fullscreen;
|
|
2096
|
+
if (!fullscreen || this.disposed || this.finished) {
|
|
2097
|
+
return Promise.reject(new FullscreenUiDisposedError());
|
|
2098
|
+
}
|
|
2099
|
+
if (this.cancelActiveCustom) {
|
|
2100
|
+
return Promise.reject(new Error("pi-btw attempted to open overlapping custom UI."));
|
|
2101
|
+
}
|
|
2102
|
+
return new Promise((resolve, reject) => {
|
|
2103
|
+
let component;
|
|
2104
|
+
let overlay;
|
|
2105
|
+
let splitPane;
|
|
2106
|
+
let removePaneFocusListener;
|
|
2107
|
+
let mounted = false;
|
|
2108
|
+
let layoutMounted = false;
|
|
2109
|
+
let factorySettled = false;
|
|
2110
|
+
let closed = false;
|
|
2111
|
+
let promiseSettled = false;
|
|
2112
|
+
let componentDisposed = false;
|
|
2113
|
+
let pendingValue;
|
|
2114
|
+
let hasPendingValue = false;
|
|
2115
|
+
const disposeComponent = () => {
|
|
2116
|
+
if (!component || componentDisposed) return;
|
|
2117
|
+
componentDisposed = true;
|
|
2118
|
+
try {
|
|
2119
|
+
component.dispose?.();
|
|
2120
|
+
} catch {
|
|
2121
|
+
}
|
|
2122
|
+
};
|
|
2123
|
+
const unmount = () => {
|
|
2124
|
+
let cleanupError;
|
|
2125
|
+
const removeFocusListener = removePaneFocusListener;
|
|
2126
|
+
removePaneFocusListener = void 0;
|
|
2127
|
+
try {
|
|
2128
|
+
removeFocusListener?.();
|
|
2129
|
+
} catch (error) {
|
|
2130
|
+
cleanupError = error;
|
|
2131
|
+
}
|
|
2132
|
+
splitPane?.dispose();
|
|
2133
|
+
splitPane = void 0;
|
|
2134
|
+
try {
|
|
2135
|
+
if (overlay) overlay.hide();
|
|
2136
|
+
else if (mounted && layoutMounted) fullscreen.setLayoutRoot(void 0);
|
|
2137
|
+
else if (mounted && component) fullscreen.removeChild(component);
|
|
2138
|
+
} catch (error) {
|
|
2139
|
+
cleanupError ??= error;
|
|
2140
|
+
}
|
|
2141
|
+
if (overlay || mounted) {
|
|
2142
|
+
try {
|
|
2143
|
+
fullscreen.setFocus(null);
|
|
2144
|
+
fullscreen.requestRender();
|
|
2145
|
+
} catch (error) {
|
|
2146
|
+
cleanupError ??= error;
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
disposeComponent();
|
|
2150
|
+
if (cleanupError !== void 0) throw cleanupError;
|
|
2151
|
+
};
|
|
2152
|
+
const complete = () => {
|
|
2153
|
+
if (promiseSettled || !hasPendingValue) return;
|
|
2154
|
+
promiseSettled = true;
|
|
2155
|
+
this.cancelActiveCustom = void 0;
|
|
2156
|
+
this.hardCancelActiveCustom = void 0;
|
|
2157
|
+
if (!factorySettled) {
|
|
2158
|
+
resolve(pendingValue);
|
|
2159
|
+
return;
|
|
2160
|
+
}
|
|
2161
|
+
try {
|
|
2162
|
+
unmount();
|
|
2163
|
+
resolve(pendingValue);
|
|
2164
|
+
} catch (error) {
|
|
2165
|
+
reject(error);
|
|
2166
|
+
}
|
|
2167
|
+
};
|
|
2168
|
+
const close = (value) => {
|
|
2169
|
+
if (closed || promiseSettled) return;
|
|
2170
|
+
closed = true;
|
|
2171
|
+
pendingValue = value;
|
|
2172
|
+
hasPendingValue = true;
|
|
2173
|
+
complete();
|
|
2174
|
+
};
|
|
2175
|
+
const fail = (error) => {
|
|
2176
|
+
if (promiseSettled) return;
|
|
2177
|
+
closed = true;
|
|
2178
|
+
promiseSettled = true;
|
|
2179
|
+
this.cancelActiveCustom = void 0;
|
|
2180
|
+
this.hardCancelActiveCustom = void 0;
|
|
2181
|
+
try {
|
|
2182
|
+
unmount();
|
|
2183
|
+
reject(error);
|
|
2184
|
+
} catch (cleanupError) {
|
|
2185
|
+
reject(cleanupError);
|
|
2186
|
+
}
|
|
2187
|
+
};
|
|
2188
|
+
this.cancelActiveCustom = () => {
|
|
2189
|
+
if (promiseSettled) return;
|
|
2190
|
+
disposeComponent();
|
|
2191
|
+
if (!promiseSettled) fail(new FullscreenUiDisposedError());
|
|
2192
|
+
};
|
|
2193
|
+
this.hardCancelActiveCustom = () => {
|
|
2194
|
+
if (promiseSettled) return;
|
|
2195
|
+
try {
|
|
2196
|
+
component?.handleInput?.("");
|
|
2197
|
+
} catch (error) {
|
|
2198
|
+
fail(error);
|
|
2199
|
+
return;
|
|
2200
|
+
}
|
|
2201
|
+
this.cancelActiveCustom?.();
|
|
2202
|
+
};
|
|
2203
|
+
let created;
|
|
2204
|
+
try {
|
|
2205
|
+
created = factory(fullscreen, this.theme, this.keybindings, close);
|
|
2206
|
+
} catch (error) {
|
|
2207
|
+
factorySettled = true;
|
|
2208
|
+
fail(error);
|
|
2209
|
+
return;
|
|
2210
|
+
}
|
|
2211
|
+
Promise.resolve(created).then(async (value) => {
|
|
2212
|
+
component = value;
|
|
2213
|
+
factorySettled = true;
|
|
2214
|
+
if (promiseSettled) {
|
|
2215
|
+
disposeComponent();
|
|
2216
|
+
return;
|
|
2217
|
+
}
|
|
2218
|
+
if (closed) {
|
|
2219
|
+
complete();
|
|
2220
|
+
return;
|
|
2221
|
+
}
|
|
2222
|
+
const workspaceLayout = this.options.layout ?? "fullscreen";
|
|
2223
|
+
if (!options?.overlay && workspaceLayout !== "fullscreen") {
|
|
2224
|
+
await this.waitForSidePaneWrites();
|
|
2225
|
+
if (promiseSettled) {
|
|
2226
|
+
disposeComponent();
|
|
2227
|
+
return;
|
|
2228
|
+
}
|
|
2229
|
+
if (closed) {
|
|
2230
|
+
complete();
|
|
2231
|
+
return;
|
|
2232
|
+
}
|
|
2233
|
+
if (this.disposed || this.finished || this.fullscreen !== fullscreen) {
|
|
2234
|
+
fail(new FullscreenUiDisposedError());
|
|
2235
|
+
return;
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
if (options?.overlay) {
|
|
2239
|
+
const overlayOptions = typeof options.overlayOptions === "function" ? options.overlayOptions() : options.overlayOptions;
|
|
2240
|
+
overlay = fullscreen.showOverlay(component, overlayOptions);
|
|
2241
|
+
options.onHandle?.(overlay);
|
|
2242
|
+
} else {
|
|
2243
|
+
fullscreen.clear();
|
|
2244
|
+
mounted = true;
|
|
2245
|
+
if (workspaceLayout !== "fullscreen") {
|
|
2246
|
+
layoutMounted = true;
|
|
2247
|
+
const sideLayout = isFullscreenLayoutComponent(component) ? component.getFullscreenLayout() : component;
|
|
2248
|
+
splitPane = new BtwSplitPane({
|
|
2249
|
+
sideComponent: component,
|
|
2250
|
+
sideLayout,
|
|
2251
|
+
mainThread: this.parent,
|
|
2252
|
+
mainLayout: getParentFullscreenLayout(this.parent),
|
|
2253
|
+
mainInput: this.mainThreadInput,
|
|
2254
|
+
sideScrollView: isFullscreenLayoutComponent(component) ? component.getPrimaryScrollView?.() : void 0,
|
|
2255
|
+
layout: workspaceLayout,
|
|
2256
|
+
theme: this.theme,
|
|
2257
|
+
terminalColumns: () => fullscreen.terminal.columns,
|
|
2258
|
+
terminalRows: () => fullscreen.terminal.rows,
|
|
2259
|
+
hasFocusedOverlay: () => fullscreen.hasFocusedOverlay?.() ?? false,
|
|
2260
|
+
setFocus: (target) => fullscreen.setFocus(target),
|
|
2261
|
+
setViewportTarget: (target) => fullscreen.setViewportTarget?.(target),
|
|
2262
|
+
requestRender: () => fullscreen.requestRender(),
|
|
2263
|
+
sidePaneRatio: this.sidePaneRatio,
|
|
2264
|
+
...this.options.persistSidePaneRatio ? { persistSidePaneRatio: (ratio) => this.persistSidePaneRatio(ratio) } : {}
|
|
2265
|
+
});
|
|
2266
|
+
const addPaneFocusListener = fullscreen.addInputListenerBeforeViewport?.bind(fullscreen) ?? fullscreen.addInputListener.bind(fullscreen);
|
|
2267
|
+
removePaneFocusListener = addPaneFocusListener((data) => {
|
|
2268
|
+
const consumed = splitPane?.handleTerminalInput(data);
|
|
2269
|
+
return consumed ? { consume: true } : void 0;
|
|
2270
|
+
});
|
|
2271
|
+
fullscreen.setLayoutRoot(splitPane.getFullscreenLayout());
|
|
2272
|
+
} else if (isFullscreenLayoutComponent(component)) {
|
|
2273
|
+
layoutMounted = true;
|
|
2274
|
+
fullscreen.setLayoutRoot(component.getFullscreenLayout());
|
|
2275
|
+
} else {
|
|
2276
|
+
fullscreen.addChild(component);
|
|
2277
|
+
}
|
|
2278
|
+
fullscreen.setFocus(component);
|
|
2279
|
+
fullscreen.requestRender();
|
|
2280
|
+
}
|
|
2281
|
+
}).catch(fail);
|
|
1607
2282
|
});
|
|
1608
|
-
await beforeRename?.(temporaryPath, settingsPath);
|
|
1609
|
-
signal?.throwIfAborted();
|
|
1610
|
-
await rename(temporaryPath, settingsPath);
|
|
1611
|
-
} catch (error) {
|
|
1612
|
-
await rm(temporaryPath, { force: true }).catch(() => void 0);
|
|
1613
|
-
throw error;
|
|
1614
2283
|
}
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
2284
|
+
persistSidePaneRatio(ratio) {
|
|
2285
|
+
const persist = this.options.persistSidePaneRatio;
|
|
2286
|
+
if (!persist) {
|
|
2287
|
+
this.sidePaneRatio = ratio;
|
|
2288
|
+
return Promise.resolve();
|
|
2289
|
+
}
|
|
2290
|
+
const writeGeneration = ++this.sidePaneWriteGeneration;
|
|
2291
|
+
let task;
|
|
2292
|
+
task = Promise.resolve().then(() => persist(ratio, this.lifetimeController.signal)).then(() => {
|
|
2293
|
+
if (this.lifetimeController.signal.aborted || writeGeneration <= this.confirmedSidePaneWriteGeneration) {
|
|
2294
|
+
return;
|
|
2295
|
+
}
|
|
2296
|
+
this.confirmedSidePaneWriteGeneration = writeGeneration;
|
|
2297
|
+
this.sidePaneRatio = ratio;
|
|
2298
|
+
}).catch((error) => {
|
|
2299
|
+
if (!this.lifetimeController.signal.aborted) {
|
|
2300
|
+
const message = sanitizeSingleLine(
|
|
2301
|
+
`Pi BTW pane width was not saved; the previous value remains active: ${formatError3(error)}`
|
|
2302
|
+
);
|
|
2303
|
+
try {
|
|
2304
|
+
this.ctx.ui.notify(message, "error");
|
|
2305
|
+
} catch {
|
|
2306
|
+
}
|
|
2307
|
+
this.fullscreen?.flash?.(message);
|
|
2308
|
+
}
|
|
2309
|
+
throw error;
|
|
2310
|
+
}).finally(() => this.pendingSidePaneWrites.delete(task));
|
|
2311
|
+
this.pendingSidePaneWrites.add(task);
|
|
2312
|
+
return task;
|
|
2313
|
+
}
|
|
2314
|
+
async waitForSidePaneWrites() {
|
|
2315
|
+
while (this.pendingSidePaneWrites.size > 0) {
|
|
2316
|
+
await Promise.allSettled([...this.pendingSidePaneWrites]);
|
|
1624
2317
|
}
|
|
1625
|
-
if (Object.keys(keys).length) updated.keybindings = keys;
|
|
1626
|
-
else delete updated.keybindings;
|
|
1627
|
-
}
|
|
1628
|
-
if (Object.hasOwn(patch, "model")) {
|
|
1629
|
-
if (patch.model === void 0) delete updated.model;
|
|
1630
|
-
else updated.model = patch.model;
|
|
1631
|
-
}
|
|
1632
|
-
if (Object.hasOwn(patch, "thinkingLevel")) {
|
|
1633
|
-
if (patch.thinkingLevel === void 0) delete updated.thinkingLevel;
|
|
1634
|
-
else updated.thinkingLevel = patch.thinkingLevel;
|
|
1635
|
-
}
|
|
1636
|
-
if (Object.hasOwn(patch, "rememberThinkingLevelChanges")) {
|
|
1637
|
-
updated.rememberThinkingLevelChanges = patch.rememberThinkingLevelChanges;
|
|
1638
|
-
}
|
|
1639
|
-
if (Object.hasOwn(patch, "fullscreenCopyOnSelect")) {
|
|
1640
|
-
if (patch.fullscreenCopyOnSelect === void 0) delete updated.fullscreenCopyOnSelect;
|
|
1641
|
-
else updated.fullscreenCopyOnSelect = patch.fullscreenCopyOnSelect;
|
|
1642
2318
|
}
|
|
1643
|
-
|
|
2319
|
+
};
|
|
2320
|
+
function formatError3(error) {
|
|
2321
|
+
return error instanceof Error ? error.message : String(error);
|
|
1644
2322
|
}
|
|
1645
|
-
function
|
|
1646
|
-
return
|
|
2323
|
+
function getFocusedComponent(tui) {
|
|
2324
|
+
return tui.getFocusedComponent?.() ?? null;
|
|
1647
2325
|
}
|
|
1648
|
-
function
|
|
1649
|
-
|
|
2326
|
+
function getParentFullscreenLayout(tui) {
|
|
2327
|
+
if (tui.mode !== "fullscreen") return void 0;
|
|
2328
|
+
const layoutRoot = Reflect.get(tui, "layoutRoot");
|
|
2329
|
+
return isComponent(layoutRoot) ? layoutRoot : void 0;
|
|
1650
2330
|
}
|
|
1651
|
-
function
|
|
1652
|
-
return
|
|
2331
|
+
function isComponent(value) {
|
|
2332
|
+
return typeof value === "object" && value !== null && "render" in value && typeof value.render === "function" && "invalidate" in value && typeof value.invalidate === "function";
|
|
1653
2333
|
}
|
|
1654
|
-
function
|
|
1655
|
-
return
|
|
2334
|
+
function isFullscreenLayoutComponent(component) {
|
|
2335
|
+
return "getFullscreenLayout" in component && typeof component.getFullscreenLayout === "function";
|
|
1656
2336
|
}
|
|
1657
|
-
|
|
1658
|
-
|
|
2337
|
+
|
|
2338
|
+
// src/main-thread-updates.ts
|
|
2339
|
+
function registerBtwMainThreadUpdates(pi) {
|
|
2340
|
+
const listeners = /* @__PURE__ */ new WeakMap();
|
|
2341
|
+
const notify = (ctx) => {
|
|
2342
|
+
for (const listener of listeners.get(ctx.sessionManager) ?? []) listener();
|
|
2343
|
+
};
|
|
2344
|
+
pi.on("session_info_changed", (_event, ctx) => notify(ctx));
|
|
2345
|
+
pi.on("session_compact", (_event, ctx) => notify(ctx));
|
|
2346
|
+
pi.on("session_tree", (_event, ctx) => notify(ctx));
|
|
2347
|
+
pi.on("agent_start", (_event, ctx) => notify(ctx));
|
|
2348
|
+
pi.on("agent_end", (_event, ctx) => notify(ctx));
|
|
2349
|
+
pi.on("agent_settled", (_event, ctx) => notify(ctx));
|
|
2350
|
+
pi.on("turn_start", (_event, ctx) => notify(ctx));
|
|
2351
|
+
pi.on("turn_end", (_event, ctx) => notify(ctx));
|
|
2352
|
+
pi.on("message_start", (_event, ctx) => notify(ctx));
|
|
2353
|
+
pi.on("message_update", (_event, ctx) => notify(ctx));
|
|
2354
|
+
pi.on("message_end", (_event, ctx) => notify(ctx));
|
|
2355
|
+
pi.on("tool_execution_start", (_event, ctx) => notify(ctx));
|
|
2356
|
+
pi.on("tool_execution_update", (_event, ctx) => notify(ctx));
|
|
2357
|
+
pi.on("tool_execution_end", (_event, ctx) => notify(ctx));
|
|
2358
|
+
pi.on("model_select", (_event, ctx) => notify(ctx));
|
|
2359
|
+
pi.on("thinking_level_select", (_event, ctx) => notify(ctx));
|
|
2360
|
+
return (sessionManager, listener) => {
|
|
2361
|
+
const active = listeners.get(sessionManager) ?? /* @__PURE__ */ new Set();
|
|
2362
|
+
active.add(listener);
|
|
2363
|
+
listeners.set(sessionManager, active);
|
|
2364
|
+
return () => {
|
|
2365
|
+
active.delete(listener);
|
|
2366
|
+
if (active.size === 0) listeners.delete(sessionManager);
|
|
2367
|
+
};
|
|
2368
|
+
};
|
|
1659
2369
|
}
|
|
1660
2370
|
|
|
2371
|
+
// src/main-tree-picker.ts
|
|
2372
|
+
import {
|
|
2373
|
+
copyToClipboard,
|
|
2374
|
+
TreeSelectorComponent
|
|
2375
|
+
} from "@earendil-works/pi-coding-agent";
|
|
2376
|
+
import { Key as Key3, matchesKey as matchesKey3 } from "@earendil-works/pi-tui";
|
|
2377
|
+
|
|
1661
2378
|
// src/menu.ts
|
|
2379
|
+
import { getSupportedThinkingLevels } from "@earendil-works/pi-ai";
|
|
2380
|
+
import {
|
|
2381
|
+
BorderedLoader
|
|
2382
|
+
} from "@earendil-works/pi-coding-agent";
|
|
1662
2383
|
var SAME_AS_MAIN_THREAD = "Same as main thread";
|
|
2384
|
+
var BTW_LAYOUT_LABELS = {
|
|
2385
|
+
fullscreen: "Fullscreen",
|
|
2386
|
+
"left-pane": "Side thread left",
|
|
2387
|
+
"right-pane": "Side thread right"
|
|
2388
|
+
};
|
|
2389
|
+
var BTW_LAYOUT_VALUES = Object.values(BTW_LAYOUT_LABELS);
|
|
1663
2390
|
async function showBtwCommandMenu(ctx, options) {
|
|
1664
2391
|
if (ctx.mode !== "tui") return "closed";
|
|
1665
2392
|
const { defineMenu, runMenu, sanitizeTerminalText } = await import("@narumitw/pi-tui-kit");
|
|
@@ -1875,7 +2602,7 @@ async function showBtwCommandMenu(ctx, options) {
|
|
|
1875
2602
|
lines: [
|
|
1876
2603
|
`Model: ${displayModelValue(state.settings)}`,
|
|
1877
2604
|
`Thinking: ${displayThinkingSummary(state.settings)} \xB7 Remember changes: ${displayRememberSummary(state.settings)}`,
|
|
1878
|
-
`Copy on select: ${effectiveFullscreenCopyOnSelect(state.settings) ? "On" : "Off"}`
|
|
2605
|
+
`Layout: ${BTW_LAYOUT_LABELS[effectiveBtwLayout(state.settings)]} \xB7 Copy on select: ${effectiveFullscreenCopyOnSelect(state.settings) ? "On" : "Off"}`
|
|
1879
2606
|
],
|
|
1880
2607
|
items: [
|
|
1881
2608
|
{
|
|
@@ -1901,7 +2628,7 @@ async function showBtwCommandMenu(ctx, options) {
|
|
|
1901
2628
|
{
|
|
1902
2629
|
id: "settings",
|
|
1903
2630
|
label: "Settings",
|
|
1904
|
-
description: "Choose model, thinking, keybindings, and selection copying",
|
|
2631
|
+
description: "Choose model, thinking, layout, keybindings, and selection copying",
|
|
1905
2632
|
to: state.kind === "invalid" ? "invalid" : "settings"
|
|
1906
2633
|
}
|
|
1907
2634
|
],
|
|
@@ -1956,6 +2683,14 @@ async function showBtwCommandMenu(ctx, options) {
|
|
|
1956
2683
|
values: ["On", "Off"],
|
|
1957
2684
|
action: "set-fullscreen-copy"
|
|
1958
2685
|
},
|
|
2686
|
+
{
|
|
2687
|
+
id: "layout",
|
|
2688
|
+
label: "Side-thread layout",
|
|
2689
|
+
description: "Use the full workspace or place BTW beside the live, click-to-focus main thread.",
|
|
2690
|
+
currentValue: BTW_LAYOUT_LABELS[effectiveBtwLayout(state.settings)],
|
|
2691
|
+
values: BTW_LAYOUT_VALUES,
|
|
2692
|
+
action: "set-layout"
|
|
2693
|
+
},
|
|
1959
2694
|
...BTW_SHORTCUT_ACTIONS.map((action) => ({
|
|
1960
2695
|
id: action,
|
|
1961
2696
|
label: shortcutLabels[action],
|
|
@@ -2089,6 +2824,19 @@ async function showBtwCommandMenu(ctx, options) {
|
|
|
2089
2824
|
if (!signal.aborted) notifySaveFailure(ctx, error);
|
|
2090
2825
|
return { kind: "rejected" };
|
|
2091
2826
|
}
|
|
2827
|
+
},
|
|
2828
|
+
"set-layout": async ({ value, signal }) => {
|
|
2829
|
+
const layout = Object.entries(BTW_LAYOUT_LABELS).find(([, label]) => label === value)?.[0];
|
|
2830
|
+
if (!layout) return { kind: "rejected" };
|
|
2831
|
+
try {
|
|
2832
|
+
await updateSettings({ layout }, { settingsPath, signal });
|
|
2833
|
+
if (signal.aborted) return { kind: "rejected" };
|
|
2834
|
+
notifySafely(ctx, `Pi BTW layout: ${BTW_LAYOUT_LABELS[layout]}. Applies when BTW next opens.`, "info");
|
|
2835
|
+
return { kind: "stay" };
|
|
2836
|
+
} catch (error) {
|
|
2837
|
+
if (!signal.aborted) notifySaveFailure(ctx, error);
|
|
2838
|
+
return { kind: "rejected" };
|
|
2839
|
+
}
|
|
2092
2840
|
}
|
|
2093
2841
|
}
|
|
2094
2842
|
});
|
|
@@ -2187,7 +2935,7 @@ function clampToAvailableThinkingLevel(requested, available) {
|
|
|
2187
2935
|
function notifySaveFailure(ctx, error) {
|
|
2188
2936
|
notifySafely(
|
|
2189
2937
|
ctx,
|
|
2190
|
-
`Pi BTW settings were not saved; the previous value remains active: ${
|
|
2938
|
+
`Pi BTW settings were not saved; the previous value remains active: ${formatError4(error)}`,
|
|
2191
2939
|
"error"
|
|
2192
2940
|
);
|
|
2193
2941
|
}
|
|
@@ -2197,7 +2945,7 @@ function notifySafely(ctx, message, level) {
|
|
|
2197
2945
|
} catch {
|
|
2198
2946
|
}
|
|
2199
2947
|
}
|
|
2200
|
-
function
|
|
2948
|
+
function formatError4(error) {
|
|
2201
2949
|
return error instanceof Error ? error.message : String(error);
|
|
2202
2950
|
}
|
|
2203
2951
|
|
|
@@ -2290,7 +3038,7 @@ async function pickMainEntry(pi, ctx, dependencies = {}) {
|
|
|
2290
3038
|
if (!settled) notifySafely2(ctx, "Copied selected message", "info");
|
|
2291
3039
|
}).catch((error) => {
|
|
2292
3040
|
if (!settled && !controller.signal.aborted) {
|
|
2293
|
-
notifySafely2(ctx, `Could not copy selected message: ${
|
|
3041
|
+
notifySafely2(ctx, `Could not copy selected message: ${formatError5(error)}`, "error");
|
|
2294
3042
|
}
|
|
2295
3043
|
}).finally(() => {
|
|
2296
3044
|
copyControllers.delete(controller);
|
|
@@ -2318,7 +3066,7 @@ async function pickMainEntry(pi, ctx, dependencies = {}) {
|
|
|
2318
3066
|
tui.requestRender();
|
|
2319
3067
|
} catch (error) {
|
|
2320
3068
|
restoreLabel(entryId);
|
|
2321
|
-
notifySafely2(ctx, `Could not update tree label: ${
|
|
3069
|
+
notifySafely2(ctx, `Could not update tree label: ${formatError5(error)}`, "error");
|
|
2322
3070
|
}
|
|
2323
3071
|
};
|
|
2324
3072
|
selector = createSelector({
|
|
@@ -2394,6 +3142,8 @@ function sanitizeEntryForDisplay(entry) {
|
|
|
2394
3142
|
return { ...entry, thinkingLevel: sanitizeSingleLine(entry.thinkingLevel) };
|
|
2395
3143
|
case "custom":
|
|
2396
3144
|
return { ...entry, customType: sanitizeSingleLine(entry.customType) };
|
|
3145
|
+
case "context_edit":
|
|
3146
|
+
return { ...entry, targetId: sanitizeSingleLine(entry.targetId) };
|
|
2397
3147
|
case "label":
|
|
2398
3148
|
return {
|
|
2399
3149
|
...entry,
|
|
@@ -2505,7 +3255,7 @@ function notifySafely2(ctx, message, level) {
|
|
|
2505
3255
|
} catch {
|
|
2506
3256
|
}
|
|
2507
3257
|
}
|
|
2508
|
-
function
|
|
3258
|
+
function formatError5(error) {
|
|
2509
3259
|
return error instanceof Error ? error.message : String(error);
|
|
2510
3260
|
}
|
|
2511
3261
|
|
|
@@ -2565,16 +3315,16 @@ import {
|
|
|
2565
3315
|
Loader,
|
|
2566
3316
|
Markdown,
|
|
2567
3317
|
matchesKey as matchesKey4,
|
|
2568
|
-
ScrollView,
|
|
2569
|
-
truncateToWidth as
|
|
3318
|
+
ScrollView as ScrollView2,
|
|
3319
|
+
truncateToWidth as truncateToWidth4,
|
|
2570
3320
|
VStack,
|
|
2571
|
-
visibleWidth as
|
|
3321
|
+
visibleWidth as visibleWidth3
|
|
2572
3322
|
} from "@earendil-works/pi-tui";
|
|
2573
3323
|
var TRANSCRIPT_CHROME_LINES = 2;
|
|
2574
3324
|
var MAX_STEERING_DISPLAY_LINES = 3;
|
|
2575
3325
|
var OSC133_MARKERS = ["\x1B]133;A\x07", "\x1B]133;B\x07", "\x1B]133;C\x07"];
|
|
2576
3326
|
var RESERVED_APP_LINES = 3;
|
|
2577
|
-
var PreservingScrollView = class extends
|
|
3327
|
+
var PreservingScrollView = class extends ScrollView2 {
|
|
2578
3328
|
updateLayout(contentHeight, viewportHeight, requestRender) {
|
|
2579
3329
|
const preserveManualPosition = !this.isFollowingEnd;
|
|
2580
3330
|
super.updateLayout(contentHeight, viewportHeight, requestRender);
|
|
@@ -2655,6 +3405,9 @@ var BtwTranscriptPager = class {
|
|
|
2655
3405
|
getFullscreenLayout() {
|
|
2656
3406
|
return this.layoutRoot;
|
|
2657
3407
|
}
|
|
3408
|
+
getPrimaryScrollView() {
|
|
3409
|
+
return this.scrollView;
|
|
3410
|
+
}
|
|
2658
3411
|
render(width) {
|
|
2659
3412
|
if (width <= 0) return [];
|
|
2660
3413
|
const safeWidth = Math.max(1, width);
|
|
@@ -2670,7 +3423,7 @@ var BtwTranscriptPager = class {
|
|
|
2670
3423
|
this.renderFooter(safeWidth),
|
|
2671
3424
|
editorLines,
|
|
2672
3425
|
availableRows
|
|
2673
|
-
).map((line) =>
|
|
3426
|
+
).map((line) => truncateToWidth4(line, safeWidth));
|
|
2674
3427
|
}
|
|
2675
3428
|
handleInput(data) {
|
|
2676
3429
|
if (this.finished) return;
|
|
@@ -2728,7 +3481,7 @@ var BtwTranscriptPager = class {
|
|
|
2728
3481
|
const bringKey = this.shortcuts.label("bringToMain");
|
|
2729
3482
|
if (this.warning) {
|
|
2730
3483
|
const warning = width < 32 ? `Empty \u2022 ${exit}` : `${this.warning} \u2022 ${exit} exit`;
|
|
2731
|
-
return
|
|
3484
|
+
return truncateToWidth4(this.theme.fg("warning", warning), width);
|
|
2732
3485
|
}
|
|
2733
3486
|
const scrollable = this.getMaxScrollOffset() > 0;
|
|
2734
3487
|
const thinking = this.options.thinking;
|
|
@@ -2738,24 +3491,24 @@ var BtwTranscriptPager = class {
|
|
|
2738
3491
|
const fallbackBase = `btw \u2022 Enter \u2022 ${exit}`;
|
|
2739
3492
|
const compactBase = bring ? `btw \u2022 Enter \u2022 ${bringKey} \u2022 ${exit}` : fallbackBase;
|
|
2740
3493
|
const compactWithThinking = `${compactBase}${cycleHint}`;
|
|
2741
|
-
let hints =
|
|
3494
|
+
let hints = visibleWidth3(fullBase) <= width ? fullBase : visibleWidth3(compactWithThinking) <= width ? compactWithThinking : visibleWidth3(compactBase) <= width ? compactBase : fallbackBase;
|
|
2742
3495
|
if (scrollable) {
|
|
2743
3496
|
const history = ` \u2022 ${this.scrollView.scrollTop > 0 ? "\u2191 older" : "\u2193 newer"} \u2022 PgUp/PgDn history`;
|
|
2744
3497
|
const compactHistory = " \u2022 PgUp/PgDn";
|
|
2745
3498
|
const compactScrollable = bring ? `Enter \u2022 ${bringKey} \u2022 ${exit} \u2022 PgUp/PgDn` : `${fallbackBase}${compactHistory}`;
|
|
2746
|
-
if (
|
|
3499
|
+
if (visibleWidth3(`${hints}${history}`) <= width) {
|
|
2747
3500
|
hints += history;
|
|
2748
|
-
} else if (
|
|
3501
|
+
} else if (visibleWidth3(`${compactBase}${history}`) <= width) {
|
|
2749
3502
|
hints = `${compactBase}${history}`;
|
|
2750
|
-
} else if (
|
|
3503
|
+
} else if (visibleWidth3(`${hints}${compactHistory}`) <= width) {
|
|
2751
3504
|
hints += compactHistory;
|
|
2752
|
-
} else if (
|
|
3505
|
+
} else if (visibleWidth3(`${compactBase}${compactHistory}`) <= width) {
|
|
2753
3506
|
hints = `${compactBase}${compactHistory}`;
|
|
2754
|
-
} else if (
|
|
3507
|
+
} else if (visibleWidth3(compactScrollable) <= width) {
|
|
2755
3508
|
hints = compactScrollable;
|
|
2756
3509
|
}
|
|
2757
3510
|
}
|
|
2758
|
-
return
|
|
3511
|
+
return truncateToWidth4(this.theme.fg("muted", hints), width);
|
|
2759
3512
|
}
|
|
2760
3513
|
createHeaderComponent() {
|
|
2761
3514
|
return {
|
|
@@ -2878,6 +3631,9 @@ var BtwAnsweringView = class {
|
|
|
2878
3631
|
getFullscreenLayout() {
|
|
2879
3632
|
return this.layoutRoot;
|
|
2880
3633
|
}
|
|
3634
|
+
getPrimaryScrollView() {
|
|
3635
|
+
return this.scrollView;
|
|
3636
|
+
}
|
|
2881
3637
|
render(width) {
|
|
2882
3638
|
if (width <= 0) return [];
|
|
2883
3639
|
const safeWidth = Math.max(1, width);
|
|
@@ -2904,7 +3660,7 @@ var BtwAnsweringView = class {
|
|
|
2904
3660
|
editorLines,
|
|
2905
3661
|
availableRows,
|
|
2906
3662
|
steeringLines
|
|
2907
|
-
).map((line) =>
|
|
3663
|
+
).map((line) => truncateToWidth4(line, safeWidth));
|
|
2908
3664
|
}
|
|
2909
3665
|
handleInput(data) {
|
|
2910
3666
|
if (this.finished) return;
|
|
@@ -2967,7 +3723,7 @@ var BtwAnsweringView = class {
|
|
|
2967
3723
|
const exit = this.shortcuts.label("exit");
|
|
2968
3724
|
if (this.warning) {
|
|
2969
3725
|
const warning = width < 32 ? `Empty \u2022 ${exit}` : `${this.warning} \u2022 ${exit} cancel`;
|
|
2970
|
-
return
|
|
3726
|
+
return truncateToWidth4(this.theme.fg("warning", warning), width);
|
|
2971
3727
|
}
|
|
2972
3728
|
const baseHint = this.editor ? `Enter steer \u2022 ${exit} cancel` : `${exit} cancel`;
|
|
2973
3729
|
const thinking = this.options.steering?.thinking;
|
|
@@ -2975,10 +3731,10 @@ var BtwAnsweringView = class {
|
|
|
2975
3731
|
const scrollHint = this.getMaxScrollOffset() > 0 ? " \u2022 PgUp/PgDn history" : "";
|
|
2976
3732
|
const hints = `${baseHint}${cycleHint}${scrollHint}`;
|
|
2977
3733
|
const compactHints = this.editor ? `Enter \u2022 ${exit}` : exit;
|
|
2978
|
-
const selectedHints =
|
|
2979
|
-
const loaderWidth = Math.max(1, width -
|
|
3734
|
+
const selectedHints = visibleWidth3(hints) <= width ? hints : compactHints;
|
|
3735
|
+
const loaderWidth = Math.max(1, width - visibleWidth3(selectedHints) - 3);
|
|
2980
3736
|
const loaderLine = this.loader.render(loaderWidth).at(-1) ?? "Answering\u2026";
|
|
2981
|
-
return
|
|
3737
|
+
return truncateToWidth4(`${loaderLine} \u2022 ${this.theme.fg("muted", selectedHints)}`, width);
|
|
2982
3738
|
}
|
|
2983
3739
|
createHeaderComponent() {
|
|
2984
3740
|
return {
|
|
@@ -3050,8 +3806,8 @@ function renderTranscriptLines(components, width) {
|
|
|
3050
3806
|
}
|
|
3051
3807
|
function renderSideThreadHeader(width, theme, thinkingLevel) {
|
|
3052
3808
|
const thinking = thinkingLevel ? ` \xB7 thinking ${thinkingLevel}` : "";
|
|
3053
|
-
const title =
|
|
3054
|
-
const ruleWidth = Math.max(0, width -
|
|
3809
|
+
const title = truncateToWidth4(`\u2500 btw \xB7 side thread${thinking} `, width);
|
|
3810
|
+
const ruleWidth = Math.max(0, width - visibleWidth3(title));
|
|
3055
3811
|
return theme.fg("muted", `${title}${"\u2500".repeat(ruleWidth)}`);
|
|
3056
3812
|
}
|
|
3057
3813
|
function fitComposerLayout(header, contentLines, footer, editorLines, availableRows, statusLines = []) {
|
|
@@ -3074,7 +3830,7 @@ function renderSteeringLines(questions, width, theme, maxLines) {
|
|
|
3074
3830
|
const formatQuestion = (question) => sanitizeSingleLine(question) || "(non-printing message)";
|
|
3075
3831
|
if (maxLines === 1 && questions.length > 1) {
|
|
3076
3832
|
return [
|
|
3077
|
-
|
|
3833
|
+
truncateToWidth4(
|
|
3078
3834
|
theme.fg("dim", `Steering (+${questions.length - 1} more): ${formatQuestion(questions[0] ?? "")}`),
|
|
3079
3835
|
width
|
|
3080
3836
|
)
|
|
@@ -3082,9 +3838,9 @@ function renderSteeringLines(questions, width, theme, maxLines) {
|
|
|
3082
3838
|
}
|
|
3083
3839
|
const hasOverflow = questions.length > maxLines;
|
|
3084
3840
|
const questionLimit = hasOverflow ? Math.max(1, maxLines - 1) : maxLines;
|
|
3085
|
-
const lines = questions.slice(0, questionLimit).map((question) =>
|
|
3841
|
+
const lines = questions.slice(0, questionLimit).map((question) => truncateToWidth4(theme.fg("dim", `Steering: ${formatQuestion(question)}`), width));
|
|
3086
3842
|
if (hasOverflow) {
|
|
3087
|
-
lines.push(
|
|
3843
|
+
lines.push(truncateToWidth4(theme.fg("dim", `Steering: \u2026 +${questions.length - questionLimit} more`), width));
|
|
3088
3844
|
}
|
|
3089
3845
|
return lines;
|
|
3090
3846
|
}
|
|
@@ -3104,7 +3860,6 @@ function escapeTerminalControls2(text) {
|
|
|
3104
3860
|
}
|
|
3105
3861
|
|
|
3106
3862
|
// src/btw.ts
|
|
3107
|
-
var MAX_CONTEXT_CHARS = 4e4;
|
|
3108
3863
|
function createModelRegistryCompleteSimple(modelRegistry) {
|
|
3109
3864
|
const completeSimple = async (model, context, options) => modelRegistry.streamSimple(model, context, options).result();
|
|
3110
3865
|
completeSimple.appliesRequestHeaderTransforms = true;
|
|
@@ -3140,7 +3895,7 @@ async function resolveBtwModel({
|
|
|
3140
3895
|
}
|
|
3141
3896
|
return currentModel && isAvailable(currentModel) ? { model: currentModel } : void 0;
|
|
3142
3897
|
}
|
|
3143
|
-
function
|
|
3898
|
+
function formatError6(error) {
|
|
3144
3899
|
return error instanceof Error ? error.message : String(error);
|
|
3145
3900
|
}
|
|
3146
3901
|
function readBtwSessionId(ctx) {
|
|
@@ -3162,6 +3917,7 @@ function btw(pi, dependencies = {}) {
|
|
|
3162
3917
|
const resolveModel = dependencies.resolveModel ?? resolveBtwModelForCommand;
|
|
3163
3918
|
const runThread = dependencies.runThread ?? runBtwThread;
|
|
3164
3919
|
const runFullscreen = dependencies.runFullscreen ?? runBtwFullscreen;
|
|
3920
|
+
const subscribeMainThreadUpdates = registerBtwMainThreadUpdates(pi);
|
|
3165
3921
|
const resumableThreads = /* @__PURE__ */ new Map();
|
|
3166
3922
|
let nextThreadNumber = 1;
|
|
3167
3923
|
const listResumeThreads = () => [...resumableThreads.values()].reverse().filter((state) => state.thread.turns.length > 0 && state.title).sort((first, second) => second.updatedAt - first.updatedAt || second.createdAt - first.createdAt).map((state) => ({
|
|
@@ -3250,6 +4006,10 @@ function btw(pi, dependencies = {}) {
|
|
|
3250
4006
|
},
|
|
3251
4007
|
{
|
|
3252
4008
|
copyOnSelect: effectiveFullscreenCopyOnSelect(settings),
|
|
4009
|
+
layout: effectiveBtwLayout(settings),
|
|
4010
|
+
sidePaneRatio: effectiveBtwSidePaneRatio(settings),
|
|
4011
|
+
persistSidePaneRatio: (ratio, signal) => updateBtwSettings({ sidePaneRatio: ratio }, { signal }).then(() => void 0),
|
|
4012
|
+
subscribeMainThreadUpdates: (listener) => subscribeMainThreadUpdates(ctx.sessionManager, listener),
|
|
3253
4013
|
...settings.keybindings ? { keybindings: settings.keybindings } : {}
|
|
3254
4014
|
}
|
|
3255
4015
|
);
|
|
@@ -3323,7 +4083,7 @@ async function runBtwThread({
|
|
|
3323
4083
|
write = Promise.resolve().then(() => persistThinkingLevel(level)).then(() => void 0).catch((error) => {
|
|
3324
4084
|
notifySafely3(
|
|
3325
4085
|
ctx,
|
|
3326
|
-
`Thinking level changed to ${level}, but could not be remembered in pi-btw.json: ${
|
|
4086
|
+
`Thinking level changed to ${level}, but could not be remembered in pi-btw.json: ${formatError6(error)}`,
|
|
3327
4087
|
"warning"
|
|
3328
4088
|
);
|
|
3329
4089
|
}).finally(() => pendingWrites.delete(write));
|
|
@@ -3659,50 +4419,6 @@ async function showThreadComposer(thread, startAtBottom, ctx, initialQuestion, t
|
|
|
3659
4419
|
})
|
|
3660
4420
|
);
|
|
3661
4421
|
}
|
|
3662
|
-
function buildConversationContext(entries) {
|
|
3663
|
-
const sections = [];
|
|
3664
|
-
for (const entry of entries) {
|
|
3665
|
-
if (entry.type !== "message" || !entry.message?.role) continue;
|
|
3666
|
-
const role = entry.message.role;
|
|
3667
|
-
if (role !== "user" && role !== "assistant") continue;
|
|
3668
|
-
const contentLines = extractContentLines(entry.message.content);
|
|
3669
|
-
if (contentLines.length === 0) continue;
|
|
3670
|
-
const label = role === "user" ? "User" : "Assistant";
|
|
3671
|
-
const status = entry.message.stopReason && entry.message.stopReason !== "stop" ? ` (${entry.message.stopReason})` : "";
|
|
3672
|
-
sections.push(`${label}${status}: ${contentLines.join("\n")}`);
|
|
3673
|
-
}
|
|
3674
|
-
return truncateFromStart(sections.join("\n\n"), MAX_CONTEXT_CHARS);
|
|
3675
|
-
}
|
|
3676
|
-
function extractContentLines(content) {
|
|
3677
|
-
if (typeof content === "string") return [content.trim()].filter(Boolean);
|
|
3678
|
-
if (!Array.isArray(content)) return [];
|
|
3679
|
-
const lines = [];
|
|
3680
|
-
for (const part of content) {
|
|
3681
|
-
if (!part || typeof part !== "object") continue;
|
|
3682
|
-
const block = part;
|
|
3683
|
-
if (block.type === "text" && typeof block.text === "string") {
|
|
3684
|
-
lines.push(block.text.trim());
|
|
3685
|
-
} else if (block.type === "toolCall" && typeof block.name === "string") {
|
|
3686
|
-
lines.push(`Tool call: ${block.name}(${formatJson(block.arguments)})`);
|
|
3687
|
-
} else if (block.type === "toolResult" && typeof block.name === "string") {
|
|
3688
|
-
lines.push(`Tool result from ${block.name}: ${formatJson(block.result)}`);
|
|
3689
|
-
}
|
|
3690
|
-
}
|
|
3691
|
-
return lines.filter(Boolean);
|
|
3692
|
-
}
|
|
3693
|
-
function formatJson(value) {
|
|
3694
|
-
if (value === void 0) return "";
|
|
3695
|
-
try {
|
|
3696
|
-
return JSON.stringify(value);
|
|
3697
|
-
} catch {
|
|
3698
|
-
return String(value);
|
|
3699
|
-
}
|
|
3700
|
-
}
|
|
3701
|
-
function truncateFromStart(text, maxChars) {
|
|
3702
|
-
if (text.length <= maxChars) return text;
|
|
3703
|
-
return `[Earlier context omitted; showing the last ${maxChars} characters.]
|
|
3704
|
-
${text.slice(-maxChars)}`;
|
|
3705
|
-
}
|
|
3706
4422
|
export {
|
|
3707
4423
|
btw as default
|
|
3708
4424
|
};
|