@daniel156161/prism 0.2.81 → 0.2.82

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.
Files changed (35) hide show
  1. package/dist/prism-extensions/integrations/ai-memory-errors.d.ts +13 -0
  2. package/dist/prism-extensions/integrations/ai-memory-errors.js +54 -0
  3. package/dist/prism-extensions/integrations/ai-memory-errors.js.map +1 -1
  4. package/dist/prism-extensions/integrations/ai-memory-http.d.ts +28 -0
  5. package/dist/prism-extensions/integrations/ai-memory-http.js +92 -0
  6. package/dist/prism-extensions/integrations/ai-memory-http.js.map +1 -0
  7. package/dist/prism-extensions/integrations/ai-memory-system.d.ts +2 -0
  8. package/dist/prism-extensions/integrations/ai-memory-system.js +49 -127
  9. package/dist/prism-extensions/integrations/ai-memory-system.js.map +1 -1
  10. package/dist/prism-extensions/integrations/ai-memory-write-preview.d.ts +36 -0
  11. package/dist/prism-extensions/integrations/ai-memory-write-preview.js +67 -0
  12. package/dist/prism-extensions/integrations/ai-memory-write-preview.js.map +1 -0
  13. package/dist/prism-extensions/ui/collapsed-text-rendering.d.ts +4 -2
  14. package/dist/prism-extensions/ui/collapsed-text-rendering.js +12 -7
  15. package/dist/prism-extensions/ui/collapsed-text-rendering.js.map +1 -1
  16. package/node_modules/@earendil-works/pi-coding-agent/dist/cli.js +1 -1
  17. package/node_modules/@earendil-works/pi-coding-agent/dist/config.js +11 -6
  18. package/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session-services.js +1 -1
  19. package/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.js +0 -5
  20. package/node_modules/@earendil-works/pi-coding-agent/dist/core/auth-storage.js +1 -1
  21. package/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/loader.js +1 -3
  22. package/node_modules/@earendil-works/pi-coding-agent/dist/core/project-trust.js +1 -1
  23. package/node_modules/@earendil-works/pi-coding-agent/dist/core/sdk.js +1 -1
  24. package/node_modules/@earendil-works/pi-coding-agent/dist/core/session-manager.js +37 -39
  25. package/node_modules/@earendil-works/pi-coding-agent/dist/core/system-prompt.js +16 -20
  26. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/session-selector.js +0 -4
  27. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/interactive-mode.js +2376 -234
  28. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.js +1 -1
  29. package/package.json +3 -3
  30. package/src/prism-extensions/integrations/ai-memory-errors.ts +59 -0
  31. package/src/prism-extensions/integrations/ai-memory-http.ts +114 -0
  32. package/src/prism-extensions/integrations/ai-memory-system.ts +60 -135
  33. package/src/prism-extensions/integrations/ai-memory-write-preview.ts +83 -0
  34. package/src/prism-extensions/ui/collapsed-text-rendering.ts +14 -8
  35. package/node_modules/@earendil-works/pi-coding-agent/dist/core/prism-session-db.js +0 -128
@@ -464,15 +464,12 @@ export class InteractiveMode {
464
464
  }));
465
465
  // Convert extension commands to SlashCommand format
466
466
  const builtinCommandNames = new Set(slashCommands.map((c) => c.name));
467
- const prismInternalCommandExtensions = new Set(["caveman-mode.ts", "clear-session.ts", "git-commit.ts", "plan-command.ts", "voice-command.ts", "obsidian-memory.ts", "logseq-memory.ts", "honcho-memory.ts", "research-tools.ts", "ai-memory-system.ts", "rp-memory.ts", "manifest-provider.ts", "ollama-provider.ts", "toolbox.ts", "context-usage.ts", "prism-status.ts", "toolbar.ts", "pi-mcp-adapter"]);
468
- const prismInternalCommandNpmPackages = new Set(["pi-mcp-adapter"]);
469
- const isPrismInternalCommand = (cmd) => (() => { const prismExtensionPath = String(cmd.sourceInfo?.path || "").replaceAll("\\", "/"); const prismExtensionSource = String(cmd.sourceInfo?.source || ""); return prismInternalCommandExtensions.has(path.basename(prismExtensionPath)) || Array.from(prismInternalCommandNpmPackages).some((pkg) => prismExtensionSource === "npm:" + pkg || prismExtensionPath.includes("/node_modules/" + pkg + "/")); })();
470
467
  const extensionCommands = this.session.extensionRunner
471
468
  .getRegisteredCommands()
472
469
  .filter((cmd) => !builtinCommandNames.has(cmd.name))
473
470
  .map((cmd) => ({
474
471
  name: cmd.invocationName,
475
- description: isPrismInternalCommand(cmd) ? cmd.description : this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),
472
+ description: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),
476
473
  getArgumentCompletions: cmd.getArgumentCompletions,
477
474
  }));
478
475
  // Build skill commands from session.skills (if enabled)
@@ -661,7 +658,7 @@ export class InteractiveMode {
661
658
  await this.themeController.applyFromSettings();
662
659
  // Add header with keybindings from config (unless silenced)
663
660
  if (this.options.verbose || !this.settingsManager.getQuietStartup()) {
664
- const logo = " \u001b[38;5;196mp\u001b[38;5;202mr\u001b[38;5;226mi\u001b[38;5;46ms\u001b[38;5;51mm\u001b[0m v0.2.81";
661
+ const logo = theme.bold(theme.fg("accent", APP_NAME)) + theme.fg("dim", ` v${this.version}`);
665
662
  // Build startup instructions using keybinding hint helpers
666
663
  const hint = (keybinding, description) => keyHint(keybinding, description);
667
664
  const expandedInstructions = [
@@ -693,7 +690,7 @@ export class InteractiveMode {
693
690
  hint("app.tools.expand", "more"),
694
691
  ].join(theme.fg("muted", " · "));
695
692
  const compactOnboarding = theme.fg("dim", `Press ${keyText("app.tools.expand")} to show full startup help and loaded resources.`);
696
- const onboarding = theme.fg("dim", `Prism can explain its own features and look up its docs. Ask it how to use or extend Prism.`);
693
+ const onboarding = theme.fg("dim", `Pi can explain its own features and look up its docs. Ask it how to use or extend Pi.`);
697
694
  this.builtInHeader = new ExpandableText(() => `${logo}\n${compactInstructions}\n${compactOnboarding}\n\n${onboarding}`, () => `${logo}\n${expandedInstructions}\n\n${onboarding}`, this.getStartupExpansionState(), 1, 0);
698
695
  // Setup UI layout
699
696
  this.headerContainer.addChild(new Spacer(1));
@@ -730,10 +727,10 @@ export class InteractiveMode {
730
727
  const cwdBasename = path.basename(this.sessionManager.getCwd());
731
728
  const sessionName = this.sessionManager.getSessionName();
732
729
  if (sessionName) {
733
- this.ui.terminal.setTitle(`▲ - ${sessionName} - ${cwdBasename}`);
730
+ this.ui.terminal.setTitle(`${APP_TITLE} - ${sessionName} - ${cwdBasename}`);
734
731
  }
735
732
  else {
736
- this.ui.terminal.setTitle(`▲ - ${cwdBasename}`);
733
+ this.ui.terminal.setTitle(`${APP_TITLE} - ${cwdBasename}`);
737
734
  }
738
735
  }
739
736
  /**
@@ -797,7 +794,6 @@ export class InteractiveMode {
797
794
  }
798
795
  catch (error) {
799
796
  const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
800
- errorMessage = this.humanizeUsageLimitError(errorMessage);
801
797
  this.showError(errorMessage);
802
798
  }
803
799
  }
@@ -808,8 +804,7 @@ export class InteractiveMode {
808
804
  }
809
805
  catch (error) {
810
806
  const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
811
- errorMessage = this.humanizeUsageLimitError(errorMessage);
812
- this.showError(errorMessage);
807
+ this.showError(errorMessage);
813
808
  }
814
809
  }
815
810
  }
@@ -821,7 +816,6 @@ export class InteractiveMode {
821
816
  }
822
817
  catch (error) {
823
818
  const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
824
- errorMessage = this.humanizeUsageLimitError(errorMessage);
825
819
  this.showError(errorMessage);
826
820
  }
827
821
  }
@@ -898,19 +892,14 @@ export class InteractiveMode {
898
892
  const entries = parseChangelog(changelogPath);
899
893
  if (!lastVersion) {
900
894
  // Fresh install - record the version, send telemetry, don't show changelog
901
- this.settingsManager.setLastChangelogVersion("0.84.1");
902
- this.reportInstallTelemetry("0.84.1");
895
+ this.settingsManager.setLastChangelogVersion(VERSION);
896
+ this.reportInstallTelemetry(VERSION);
903
897
  return undefined;
904
898
  }
905
899
  const newEntries = getNewEntries(entries, lastVersion);
906
- if (entries.length > 0 && newEntries.length === entries.length) {
907
- this.settingsManager.setLastChangelogVersion("0.84.1");
908
- this.reportInstallTelemetry("0.84.1");
909
- return normalizeChangelogLinks(entries[0].content, entries[0]);
910
- }
911
900
  if (newEntries.length > 0) {
912
- this.settingsManager.setLastChangelogVersion("0.84.1");
913
- this.reportInstallTelemetry("0.84.1");
901
+ this.settingsManager.setLastChangelogVersion(VERSION);
902
+ this.reportInstallTelemetry(VERSION);
914
903
  return newEntries.map((e) => normalizeChangelogLinks(e.content, e)).join("\n\n");
915
904
  }
916
905
  return undefined;
@@ -1248,7 +1237,7 @@ export class InteractiveMode {
1248
1237
  const skillsResult = this.session.resourceLoader.getSkills();
1249
1238
  const promptsResult = this.session.resourceLoader.getPrompts();
1250
1239
  const themesResult = this.session.resourceLoader.getThemes();
1251
- let extensions = options?.extensions ??
1240
+ const extensions = options?.extensions ??
1252
1241
  this.session.resourceLoader
1253
1242
  .getExtensions()
1254
1243
  .extensions.filter((extension) => !extension.hidden)
@@ -1319,9 +1308,6 @@ export class InteractiveMode {
1319
1308
  const promptCompactList = formatCompactList(templates.map((template) => `/${template.name}`));
1320
1309
  addLoadedSection("Prompts", promptCompactList, templateList);
1321
1310
  }
1322
- const prismInternalExtensions = new Set(["caveman-mode.ts", "clear-session.ts", "git-commit.ts", "plan-command.ts", "voice-command.ts", "obsidian-memory.ts", "logseq-memory.ts", "honcho-memory.ts", "research-tools.ts", "ai-memory-system.ts", "rp-memory.ts", "manifest-provider.ts", "ollama-provider.ts", "toolbox.ts", "context-usage.ts", "prism-status.ts", "toolbar.ts", "pi-mcp-adapter"]);
1323
- const prismInternalNpmPackages = new Set(["pi-mcp-adapter"]);
1324
- extensions = extensions.filter((extension) => !(() => { const prismExtensionPath = String(extension.path || "").replaceAll("\\", "/"); const prismExtensionSource = String(extension.sourceInfo?.source || ""); return prismInternalExtensions.has(path.basename(prismExtensionPath)) || Array.from(prismInternalNpmPackages).some((pkg) => prismExtensionSource === "npm:" + pkg || prismExtensionPath.includes("/node_modules/" + pkg + "/")); })());
1325
1311
  if (extensions.length > 0) {
1326
1312
  const groups = this.buildScopeGroups(extensions);
1327
1313
  const extList = this.formatScopeGroups(groups, {
@@ -1333,8 +1319,7 @@ export class InteractiveMode {
1333
1319
  }
1334
1320
  // Show loaded themes (excluding built-in)
1335
1321
  const loadedThemes = themesResult.themes;
1336
- const prismInternalThemes = new Set(["soft-green"]);
1337
- const customThemes = loadedThemes.filter((t) => t.sourcePath && !prismInternalThemes.has(t.name));
1322
+ const customThemes = loadedThemes.filter((t) => t.sourcePath);
1338
1323
  if (customThemes.length > 0) {
1339
1324
  const groups = this.buildScopeGroups(customThemes.map((loadedTheme) => ({
1340
1325
  path: loadedTheme.sourcePath,
@@ -2410,27 +2395,6 @@ export class InteractiveMode {
2410
2395
  await this.handleCompactCommand(customInstructions);
2411
2396
  return;
2412
2397
  }
2413
- if (text === "/plan" || text.startsWith("/plan ")) {
2414
- const task = text.startsWith("/plan ") ? text.slice(6).trim() : "";
2415
- this.editor.setText("");
2416
- await this.startPrismPlanMode(task);
2417
- return;
2418
- }
2419
- if (text === "/plan:approve") {
2420
- this.editor.setText("");
2421
- await this.approvePrismPlan();
2422
- return;
2423
- }
2424
- if (text === "/plan:reject") {
2425
- this.editor.setText("");
2426
- this.rejectPrismPlan();
2427
- return;
2428
- }
2429
- if (text === "/plan:cancel") {
2430
- this.editor.setText("");
2431
- this.cancelPrismPlan();
2432
- return;
2433
- }
2434
2398
  if (text === "/reload") {
2435
2399
  this.editor.setText("");
2436
2400
  await this.handleReloadCommand();
@@ -2695,8 +2659,6 @@ export class InteractiveMode {
2695
2659
  break;
2696
2660
  case "agent_settled":
2697
2661
  await this.checkShutdownRequested();
2698
- void this.maybeShowUsageLimitRecoveryMenu(event);
2699
- void this.maybeShowPrismPlanApprovalMenu(event);
2700
2662
  break;
2701
2663
  case "compaction_start": {
2702
2664
  if (this.settingsManager.getShowTerminalProgress()) {
@@ -2795,189 +2757,6 @@ export class InteractiveMode {
2795
2757
  }
2796
2758
  }
2797
2759
  }
2798
- formatUsageLimitDuration(ms) {
2799
- const totalMinutes = Math.ceil(ms / 60000);
2800
- const hours = Math.floor(totalMinutes / 60);
2801
- const minutes = totalMinutes % 60;
2802
- const parts = [];
2803
- if (hours > 0) parts.push(hours + "h");
2804
- if (minutes > 0 || parts.length === 0) parts.push(minutes + "min");
2805
- return parts.join(" ");
2806
- }
2807
- humanizeUsageLimitError(errorMessage) {
2808
- return String(errorMessage || "").replace(/(~|about\s*)?(\d+)\s*min\b/gi, (_match, prefix, minutes) => {
2809
- return (prefix || "") + this.formatUsageLimitDuration(Number(minutes) * 60 * 1000);
2810
- });
2811
- }
2812
- extractUsageLimitWaitMs(errorMessage) {
2813
- const text = String(errorMessage || "");
2814
- const parsedSeconds = text.match(/"(?:resets_in_seconds|X-Codex-Primary-Reset-After-Seconds|Retry-After)"\s*:?\s*"?(\d+)"?/i)?.[1];
2815
- if (parsedSeconds) return Number(parsedSeconds) * 1000;
2816
- const resetAt = text.match(/"(?:resets_at|X-Codex-Primary-Reset-At)"\s*:?\s*"?(\d+)"?/i)?.[1];
2817
- if (resetAt) {
2818
- const resetMs = Number(resetAt) * 1000 - Date.now();
2819
- if (Number.isFinite(resetMs) && resetMs > 0) return resetMs;
2820
- }
2821
- const hours = text.match(/(?:~|about\s*)?(\d+)\s*h(?:our)?/i)?.[1];
2822
- if (hours) return Number(hours) * 60 * 60 * 1000;
2823
- const minutes = text.match(/(?:~|about\s*)?(\d+)\s*min/i)?.[1];
2824
- if (minutes) return Number(minutes) * 60 * 1000;
2825
- const seconds = text.match(/(?:~|about\s*)?(\d+)\s*s(?:ec|econd)?/i)?.[1];
2826
- if (seconds) return Number(seconds) * 1000;
2827
- return 5 * 60 * 1000;
2828
- }
2829
- getUsageLimitError(event) {
2830
- const last = event?.messages?.[event.messages.length - 1];
2831
- let errorMessage = last?.errorMessage || last?.content?.find?.((block) => block?.type === "text")?.text || "";
2832
- if (last?.role !== "assistant" || last?.stopReason !== "error") return undefined;
2833
- errorMessage = this.humanizeUsageLimitError(errorMessage);
2834
- return /usage limit|try again in/i.test(errorMessage) ? String(errorMessage) : undefined;
2835
- }
2836
- removeLastAssistantErrorFromState() {
2837
- const messages = this.agent.state.messages;
2838
- const last = messages[messages.length - 1];
2839
- if (last?.role === "assistant" && last?.stopReason === "error") this.agent.state.messages = messages.slice(0, -1);
2840
- }
2841
- async continueAfterUsageLimitRecovery() {
2842
- try {
2843
- await this.agent.continue();
2844
- } catch (error) {
2845
- this.showError(error instanceof Error ? error.message : String(error));
2846
- }
2847
- }
2848
- maybeShowUsageLimitRecoveryMenu(event) {
2849
- const errorMessage = this.getUsageLimitError(event);
2850
- if (!errorMessage) return;
2851
- const delayMs = this.extractUsageLimitWaitMs(errorMessage);
2852
- const waitLabel = "Wait " + this.formatUsageLimitDuration(delayMs) + " then retry";
2853
- this.showSelector((done) => {
2854
- const selector = new ExtensionSelectorComponent("Usage limit hit", [waitLabel, "Change model and retry", "Cancel"], async (selected) => {
2855
- done();
2856
- if (selected === "Cancel") return;
2857
- this.removeLastAssistantErrorFromState();
2858
- if (selected === waitLabel) {
2859
- const endTime = Date.now() + delayMs;
2860
- const updateCountdown = () => {
2861
- const remaining = Math.max(0, endTime - Date.now());
2862
- this.showStatus("Waiting " + this.formatUsageLimitDuration(remaining) + " for usage limit, then retrying...");
2863
- this.ui.requestRender();
2864
- };
2865
- updateCountdown();
2866
- const countdownInterval = setInterval(updateCountdown, 60000);
2867
- setTimeout(() => { clearInterval(countdownInterval); void this.continueAfterUsageLimitRecovery(); }, delayMs);
2868
- return;
2869
- }
2870
- this.showUsageLimitModelSelector();
2871
- }, () => {
2872
- done();
2873
- this.ui.requestRender();
2874
- }, { tui: this.ui });
2875
- return { component: selector, focus: selector };
2876
- });
2877
- }
2878
- showUsageLimitModelSelector(initialSearchInput) {
2879
- this.showSelector((done) => {
2880
- const selector = new ModelSelectorComponent(this.ui, this.session.model, this.settingsManager, this.session.modelRegistry, this.session.scopedModels, async (model) => {
2881
- try {
2882
- await this.session.setModel(model);
2883
- this.footer.invalidate();
2884
- this.updateEditorBorderColor();
2885
- done();
2886
- this.showStatus("Model: " + model.id + "; retrying...");
2887
- void this.maybeWarnAboutAnthropicSubscriptionAuth(model);
2888
- this.checkDaxnutsEasterEgg(model);
2889
- void this.continueAfterUsageLimitRecovery();
2890
- } catch (error) {
2891
- done();
2892
- this.showError(error instanceof Error ? error.message : String(error));
2893
- }
2894
- }, () => {
2895
- done();
2896
- this.ui.requestRender();
2897
- }, initialSearchInput);
2898
- return { component: selector, focus: selector };
2899
- });
2900
- }
2901
- getPrismReadOnlyToolNames() {
2902
- const readOnly = new Set(["read", "grep", "find", "ls", "obsidian_memory_read", "obsidian_memory_search", "obsidian_memory_list", "web_search", "web_fetch"]);
2903
- return this.session.getActiveToolNames().filter((name) => readOnly.has(name));
2904
- }
2905
- setPrismPlanStatus(enabled) {
2906
- this.prismPlanMode = enabled;
2907
- this.setExtensionStatus("prism-mode", enabled ? "[Plan]" : undefined);
2908
- this.footer.invalidate();
2909
- }
2910
- async startPrismPlanMode(task) {
2911
- if (!this.prismPlanPreviousTools) this.prismPlanPreviousTools = this.session.getActiveToolNames();
2912
- if (this.prismPlanLeafId === undefined) this.prismPlanLeafId = this.session.sessionManager.getLeafId();
2913
- this.session.setActiveToolsByName(this.getPrismReadOnlyToolNames());
2914
- this.setPrismPlanStatus(true);
2915
- globalThis.__PRISM_MANIFEST_TIER_OVERRIDE__ = "plan";
2916
- const prompt = "PLAN MODE ACTIVE. You must only inspect and plan. Do not modify files or run mutating commands. Ask concise clarification questions if needed. When ready, write the full implementation plan, then end with exactly: /plan:ready\n\nTask: " + (task || "Create an implementation plan for the user's next change.");
2917
- await this.session.prompt(prompt);
2918
- }
2919
- getPrismLastAssistantText(event) {
2920
- const last = event?.messages?.[event.messages.length - 1];
2921
- if (last?.role !== "assistant") return "";
2922
- return (last.content || []).map((block) => block?.type === "text" ? block.text || "" : "").join("\n");
2923
- }
2924
- maybeShowPrismPlanApprovalMenu(event) {
2925
- if (!this.prismPlanMode) return;
2926
- const text = this.getPrismLastAssistantText(event);
2927
- if (!text.includes("/plan:ready")) return;
2928
- this.prismPlanText = text.replace("/plan:ready", "").trim();
2929
- this.showSelector((done) => {
2930
- const selector = new ExtensionSelectorComponent("Plan ready", ["Approve -> make changes", "Reject -> add more context", "Cancel plan"], async (selected) => {
2931
- done();
2932
- if (selected.startsWith("Approve")) return void this.approvePrismPlan();
2933
- if (selected.startsWith("Reject")) return this.rejectPrismPlan();
2934
- this.cancelPrismPlan();
2935
- }, () => {
2936
- done();
2937
- this.ui.requestRender();
2938
- }, { tui: this.ui });
2939
- return { component: selector, focus: selector };
2940
- });
2941
- }
2942
- restorePrismPlanTools() {
2943
- if (this.prismPlanPreviousTools) this.session.setActiveToolsByName(this.prismPlanPreviousTools);
2944
- this.prismPlanPreviousTools = undefined;
2945
- if (globalThis.__PRISM_MANIFEST_TIER_OVERRIDE__ === "plan") globalThis.__PRISM_MANIFEST_TIER_OVERRIDE__ = undefined;
2946
- this.setPrismPlanStatus(false);
2947
- }
2948
- restorePrismPlanBranch() {
2949
- if (this.prismPlanLeafId === undefined) return;
2950
- if (this.prismPlanLeafId === null) {
2951
- this.session.sessionManager.resetLeaf();
2952
- } else {
2953
- this.session.sessionManager.branch(this.prismPlanLeafId);
2954
- }
2955
- this.agent.state.messages = this.session.sessionManager.buildSessionContext().messages;
2956
- this.prismPlanLeafId = undefined;
2957
- }
2958
- async approvePrismPlan() {
2959
- if (!this.prismPlanMode) return this.showWarning("No active plan to approve.");
2960
- const planText = this.prismPlanText || "";
2961
- this.prismPlanText = undefined;
2962
- this.restorePrismPlanBranch();
2963
- this.restorePrismPlanTools();
2964
- await this.session.prompt("Implement this plan:\n\n" + planText);
2965
- }
2966
- rejectPrismPlan() {
2967
- if (!this.prismPlanMode) return this.showWarning("No active plan to reject.");
2968
- this.prismPlanText = undefined;
2969
- this.editor.setText("/plan ");
2970
- this.showStatus("Add more context after /plan and submit.");
2971
- this.ui.requestRender();
2972
- }
2973
- cancelPrismPlan() {
2974
- if (!this.prismPlanMode) return this.showWarning("No active plan to cancel.");
2975
- this.restorePrismPlanBranch();
2976
- this.prismPlanText = undefined;
2977
- this.restorePrismPlanTools();
2978
- this.showStatus("Plan cancelled");
2979
- this.ui.requestRender();
2980
- }
2981
2760
  /** Extract text content from a user message */
2982
2761
  getUserMessageText(message) {
2983
2762
  if (message.role !== "user")
@@ -3242,4 +3021,2367 @@ export class InteractiveMode {
3242
3021
  if (this.settingsManager.isProjectTrusted() || !hasTrustRequiringProjectResources(this.sessionManager.getCwd())) {
3243
3022
  return;
3244
3023
  }
3245
- if (this.chatContainer.children.length >
3024
+ if (this.chatContainer.children.length > 0) {
3025
+ this.chatContainer.addChild(new Spacer(1));
3026
+ }
3027
+ this.chatContainer.addChild(new Text(theme.fg("warning", `This project is not trusted. Project ${CONFIG_DIR_NAME} resources and packages are ignored. Use /trust to save a trust decision, then restart pi.`), 1, 0));
3028
+ }
3029
+ async getUserInput() {
3030
+ const queuedInput = this.pendingUserInputs.shift();
3031
+ if (queuedInput !== undefined) {
3032
+ return queuedInput;
3033
+ }
3034
+ return new Promise((resolve) => {
3035
+ this.onInputCallback = (text) => {
3036
+ this.onInputCallback = undefined;
3037
+ resolve(text);
3038
+ };
3039
+ });
3040
+ }
3041
+ rebuildChatFromMessages() {
3042
+ this.chatContainer.clear();
3043
+ this.renderSessionEntries(this.sessionManager.buildContextEntries());
3044
+ }
3045
+ // =========================================================================
3046
+ // Key handlers
3047
+ // =========================================================================
3048
+ handleCtrlC() {
3049
+ const now = Date.now();
3050
+ if (now - this.lastSigintTime < 500) {
3051
+ void this.shutdown();
3052
+ }
3053
+ else {
3054
+ this.clearEditor();
3055
+ this.lastSigintTime = now;
3056
+ }
3057
+ }
3058
+ handleCtrlD() {
3059
+ // Only called when editor is empty (enforced by CustomEditor)
3060
+ void this.shutdown();
3061
+ }
3062
+ /**
3063
+ * Gracefully shutdown the agent.
3064
+ * Stops the TUI before emitting shutdown events so extension UI cleanup cannot
3065
+ * repaint the final frame while the process is exiting.
3066
+ */
3067
+ isShuttingDown = false;
3068
+ async shutdown(options) {
3069
+ if (this.isShuttingDown)
3070
+ return;
3071
+ this.isShuttingDown = true;
3072
+ // Keep signal handlers registered until terminal cleanup has completed.
3073
+ // `signal-exit` checks the listener list during the same SIGTERM/SIGHUP
3074
+ // dispatch and re-sends the signal if only its own listeners remain.
3075
+ if (options?.fromSignal) {
3076
+ // Signal-triggered shutdown (SIGTERM/SIGHUP). Emit extension cleanup
3077
+ // (session_shutdown) BEFORE touching the terminal. Extension teardown
3078
+ // such as removing sockets does not write to the tty, so it must not be
3079
+ // skipped if a later terminal-restore write fails on a dead or stalled
3080
+ // terminal. If the terminal is gone, the restore writes below emit EIO,
3081
+ // which the stdout/stderr error handler turns into emergencyTerminalExit;
3082
+ // the render loop is already idle, so this cannot hot-spin (see #4144).
3083
+ await this.runtimeHost.dispose();
3084
+ this.themeController.disableAutoSync();
3085
+ await this.ui.terminal.drainInput(1000);
3086
+ this.stop();
3087
+ process.exit(0);
3088
+ }
3089
+ // Interactive quit (Ctrl+D, Ctrl+C, /quit, extension shutdown()). Stop the
3090
+ // TUI before emitting shutdown events so extension UI cleanup cannot repaint
3091
+ // the final frame while the process is exiting.
3092
+ // Drain any in-flight Kitty key release events before stopping.
3093
+ // This prevents escape sequences from leaking to the parent shell over slow SSH.
3094
+ this.themeController.disableAutoSync();
3095
+ await this.ui.terminal.drainInput(1000);
3096
+ this.stop();
3097
+ await this.runtimeHost.dispose();
3098
+ const resumeCommand = formatResumeCommand(this.sessionManager);
3099
+ if (resumeCommand) {
3100
+ process.stdout.write(`${chalk.dim("To resume this session:")} ${resumeCommand}\n`);
3101
+ }
3102
+ process.exit(0);
3103
+ }
3104
+ emergencyTerminalExit() {
3105
+ this.isShuttingDown = true;
3106
+ this.unregisterSignalHandlers();
3107
+ killTrackedDetachedChildren();
3108
+ // The terminal is gone. Do not run normal shutdown because TUI and
3109
+ // extension cleanup can write restore sequences and re-trigger EIO.
3110
+ process.exit(129);
3111
+ }
3112
+ /**
3113
+ * Last-resort handler for uncaught exceptions. The TUI puts stdin into raw
3114
+ * mode and hides the cursor; without this handler, an uncaught throw from
3115
+ * anywhere (e.g. an extension's async `ChildProcess.on("exit")` callback)
3116
+ * tears down the process while leaving the terminal in raw mode with no
3117
+ * cursor, requiring `stty sane && reset` to recover.
3118
+ *
3119
+ * Unlike emergencyTerminalExit, the terminal is still alive here, so we
3120
+ * call ui.stop() to restore cooked mode, the cursor, and disable bracketed
3121
+ * paste / Kitty / modifyOtherKeys sequences.
3122
+ */
3123
+ uncaughtCrash(error) {
3124
+ if (this.isShuttingDown) {
3125
+ process.exit(1);
3126
+ }
3127
+ this.isShuttingDown = true;
3128
+ try {
3129
+ this.unregisterSignalHandlers();
3130
+ }
3131
+ catch { }
3132
+ try {
3133
+ killTrackedDetachedChildren();
3134
+ }
3135
+ catch { }
3136
+ try {
3137
+ this.ui.stop();
3138
+ }
3139
+ catch { }
3140
+ console.error("pi exiting due to uncaughtException:");
3141
+ console.error(error);
3142
+ process.exit(1);
3143
+ }
3144
+ /**
3145
+ * Check if shutdown was requested and perform shutdown if so.
3146
+ */
3147
+ async checkShutdownRequested() {
3148
+ if (!this.shutdownRequested)
3149
+ return;
3150
+ await this.shutdown();
3151
+ }
3152
+ registerSignalHandlers() {
3153
+ this.unregisterSignalHandlers();
3154
+ const signals = ["SIGTERM"];
3155
+ if (process.platform !== "win32") {
3156
+ signals.push("SIGHUP");
3157
+ }
3158
+ for (const signal of signals) {
3159
+ const handler = () => {
3160
+ // SIGHUP no longer hard-exits: graceful shutdown emits session_shutdown
3161
+ // first, then attempts terminal restore. A genuinely dead terminal
3162
+ // surfaces as an EIO on the restore writes, which the stdout/stderr
3163
+ // error handler converts into emergencyTerminalExit (see #4144, #5080).
3164
+ killTrackedDetachedChildren();
3165
+ void this.shutdown({ fromSignal: true });
3166
+ };
3167
+ process.prependListener(signal, handler);
3168
+ this.signalCleanupHandlers.push(() => process.off(signal, handler));
3169
+ }
3170
+ const terminalErrorHandler = (error) => {
3171
+ if (isDeadTerminalError(error)) {
3172
+ this.emergencyTerminalExit();
3173
+ }
3174
+ throw error;
3175
+ };
3176
+ process.stdout.on("error", terminalErrorHandler);
3177
+ process.stderr.on("error", terminalErrorHandler);
3178
+ this.signalCleanupHandlers.push(() => process.stdout.off("error", terminalErrorHandler));
3179
+ this.signalCleanupHandlers.push(() => process.stderr.off("error", terminalErrorHandler));
3180
+ // Restore the terminal before the process dies on any uncaught throw.
3181
+ // Without this, an unhandled exception from extension code (or anywhere
3182
+ // in pi) leaves the terminal in raw mode with no cursor.
3183
+ const uncaughtExceptionHandler = (error) => this.uncaughtCrash(error);
3184
+ process.prependListener("uncaughtException", uncaughtExceptionHandler);
3185
+ this.signalCleanupHandlers.push(() => process.off("uncaughtException", uncaughtExceptionHandler));
3186
+ }
3187
+ unregisterSignalHandlers() {
3188
+ for (const cleanup of this.signalCleanupHandlers) {
3189
+ cleanup();
3190
+ }
3191
+ this.signalCleanupHandlers = [];
3192
+ }
3193
+ handleCtrlZ() {
3194
+ if (process.platform === "win32") {
3195
+ this.showStatus("Suspend to background is not supported on Windows");
3196
+ return;
3197
+ }
3198
+ // Keep the event loop alive while suspended. Without this, stopping the TUI
3199
+ // can leave Node with no ref'ed handles, causing the process to exit on fg
3200
+ // before the SIGCONT handler gets a chance to restore the terminal.
3201
+ const suspendKeepAlive = setInterval(() => { }, 2 ** 30);
3202
+ // Ignore SIGINT while suspended so Ctrl+C in the terminal does not
3203
+ // kill the backgrounded process. The handler is removed on resume.
3204
+ const ignoreSigint = () => { };
3205
+ process.on("SIGINT", ignoreSigint);
3206
+ // Set up handler to restore TUI when resumed
3207
+ process.once("SIGCONT", () => {
3208
+ clearInterval(suspendKeepAlive);
3209
+ process.removeListener("SIGINT", ignoreSigint);
3210
+ this.ui.start();
3211
+ this.ui.requestRender(true);
3212
+ });
3213
+ try {
3214
+ // Stop the TUI (restore terminal to normal mode)
3215
+ this.ui.stop();
3216
+ // Send SIGTSTP to process group (pid=0 means all processes in group)
3217
+ process.kill(0, "SIGTSTP");
3218
+ }
3219
+ catch (error) {
3220
+ clearInterval(suspendKeepAlive);
3221
+ process.removeListener("SIGINT", ignoreSigint);
3222
+ throw error;
3223
+ }
3224
+ }
3225
+ async handleFollowUp() {
3226
+ const text = (this.editor.getExpandedText?.() ?? this.editor.getText()).trim();
3227
+ if (!text)
3228
+ return;
3229
+ // Queue input during compaction (extension commands execute immediately)
3230
+ if (this.session.isCompacting) {
3231
+ if (this.isExtensionCommand(text)) {
3232
+ this.editor.addToHistory?.(text);
3233
+ this.editor.setText("");
3234
+ await this.session.prompt(text);
3235
+ }
3236
+ else {
3237
+ this.queueCompactionMessage(text, "followUp");
3238
+ }
3239
+ return;
3240
+ }
3241
+ // Alt+Enter queues a follow-up message (waits until agent finishes)
3242
+ // This handles extension commands (execute immediately), prompt template expansion, and queueing
3243
+ if (this.session.isStreaming) {
3244
+ this.editor.addToHistory?.(text);
3245
+ this.editor.setText("");
3246
+ await this.session.prompt(text, { streamingBehavior: "followUp" });
3247
+ this.updatePendingMessagesDisplay();
3248
+ this.ui.requestRender();
3249
+ }
3250
+ // If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)
3251
+ else if (this.editor.onSubmit) {
3252
+ this.editor.setText("");
3253
+ this.editor.onSubmit(text);
3254
+ }
3255
+ }
3256
+ handleDequeue() {
3257
+ const restored = this.restoreQueuedMessagesToEditor();
3258
+ if (restored === 0) {
3259
+ this.showStatus("No queued messages to restore");
3260
+ }
3261
+ else {
3262
+ this.showStatus(`Restored ${restored} queued message${restored > 1 ? "s" : ""} to editor`);
3263
+ }
3264
+ }
3265
+ updateEditorBorderColor() {
3266
+ if (this.isBashMode) {
3267
+ this.editor.borderColor = theme.getBashModeBorderColor();
3268
+ }
3269
+ else {
3270
+ const level = this.session.thinkingLevel || "off";
3271
+ this.editor.borderColor = theme.getThinkingBorderColor(level);
3272
+ }
3273
+ this.ui.requestRender();
3274
+ }
3275
+ cycleThinkingLevel() {
3276
+ const newLevel = this.session.cycleThinkingLevel();
3277
+ if (newLevel === undefined) {
3278
+ this.showStatus("Current model does not support thinking");
3279
+ }
3280
+ else {
3281
+ this.footer.invalidate();
3282
+ this.updateEditorBorderColor();
3283
+ this.showStatus(`Thinking level: ${newLevel}`);
3284
+ }
3285
+ }
3286
+ async cycleModel(direction) {
3287
+ try {
3288
+ const result = await this.session.cycleModel(direction);
3289
+ if (result === undefined) {
3290
+ const msg = this.session.scopedModels.length > 0 ? "Only one model in scope" : "Only one model available";
3291
+ this.showStatus(msg);
3292
+ }
3293
+ else {
3294
+ this.footer.invalidate();
3295
+ this.updateEditorBorderColor();
3296
+ const thinkingStr = result.model.reasoning && result.thinkingLevel !== "off" ? ` (thinking: ${result.thinkingLevel})` : "";
3297
+ this.showStatus(`Switched to ${result.model.name || result.model.id}${thinkingStr}`);
3298
+ void this.maybeWarnAboutAnthropicSubscriptionAuth(result.model);
3299
+ }
3300
+ }
3301
+ catch (error) {
3302
+ this.showError(error instanceof Error ? error.message : String(error));
3303
+ }
3304
+ }
3305
+ toggleToolOutputExpansion() {
3306
+ this.setToolsExpanded(!this.toolOutputExpanded);
3307
+ }
3308
+ setToolsExpanded(expanded) {
3309
+ if (expanded === this.toolOutputExpanded)
3310
+ return;
3311
+ this.toolOutputExpanded = expanded;
3312
+ const activeHeader = this.customHeader ?? this.builtInHeader;
3313
+ if (isExpandable(activeHeader)) {
3314
+ activeHeader.setExpanded(expanded);
3315
+ }
3316
+ for (const container of [this.loadedResourcesContainer, this.chatContainer]) {
3317
+ for (const child of container.children) {
3318
+ if (isExpandable(child)) {
3319
+ child.setExpanded(expanded);
3320
+ }
3321
+ }
3322
+ }
3323
+ this.showStatus(`Tool output: ${expanded ? "expanded" : "collapsed"}`);
3324
+ }
3325
+ toggleThinkingBlockVisibility() {
3326
+ this.hideThinkingBlock = !this.hideThinkingBlock;
3327
+ this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);
3328
+ // Rebuild chat from session messages
3329
+ this.chatContainer.clear();
3330
+ this.rebuildChatFromMessages();
3331
+ // If streaming, re-add the streaming component with updated visibility and re-render
3332
+ if (this.streamingComponent && this.streamingMessage) {
3333
+ this.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock);
3334
+ this.streamingComponent.updateContent(this.streamingMessage);
3335
+ this.chatContainer.addChild(this.streamingComponent);
3336
+ }
3337
+ this.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? "hidden" : "visible"}`);
3338
+ }
3339
+ async handleOpenExternalEditor() {
3340
+ const editorCmd = this.settingsManager.getExternalEditorCommand();
3341
+ const content = this.editor.getExpandedText?.() ?? this.editor.getText();
3342
+ this.ui.stop();
3343
+ try {
3344
+ const result = await editInExternalEditor({
3345
+ command: editorCmd,
3346
+ content,
3347
+ });
3348
+ if (result.status === "complete") {
3349
+ this.editor.setText(result.content);
3350
+ }
3351
+ }
3352
+ finally {
3353
+ this.ui.start();
3354
+ this.ui.requestRender(true);
3355
+ }
3356
+ }
3357
+ // =========================================================================
3358
+ // UI helpers
3359
+ // =========================================================================
3360
+ clearEditor() {
3361
+ this.editor.setText("");
3362
+ this.ui.requestRender();
3363
+ }
3364
+ showError(errorMessage) {
3365
+ this.chatContainer.addChild(new Spacer(1));
3366
+ this.chatContainer.addChild(new Text(theme.fg("error", `Error: ${errorMessage}`), this.outputPad, 0));
3367
+ this.ui.requestRender();
3368
+ }
3369
+ showWarning(warningMessage) {
3370
+ this.chatContainer.addChild(new Spacer(1));
3371
+ this.chatContainer.addChild(new Text(theme.fg("warning", `Warning: ${warningMessage}`), 1, 0));
3372
+ this.ui.requestRender();
3373
+ }
3374
+ showNewVersionNotification(release) {
3375
+ const action = theme.fg("accent", `${APP_NAME} update`);
3376
+ const updateInstruction = theme.fg("muted", `New version ${release.version} is available. Run `) + action;
3377
+ const changelogUrl = "https://pi.dev/changelog";
3378
+ const changelogLink = getCapabilities().hyperlinks
3379
+ ? hyperlink(theme.fg("accent", changelogUrl), changelogUrl)
3380
+ : theme.fg("accent", changelogUrl);
3381
+ const changelogLine = theme.fg("muted", "Changelog: ") + changelogLink;
3382
+ const note = release.note?.trim();
3383
+ this.chatContainer.addChild(new Spacer(1));
3384
+ this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
3385
+ this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning", "Update Available"))}\n${updateInstruction}`, 1, 0));
3386
+ if (note) {
3387
+ this.chatContainer.addChild(new Spacer(1));
3388
+ this.chatContainer.addChild(new Markdown(note, 1, 0, this.getMarkdownThemeWithSettings(), {
3389
+ color: (text) => theme.fg("muted", text),
3390
+ }));
3391
+ this.chatContainer.addChild(new Spacer(1));
3392
+ }
3393
+ this.chatContainer.addChild(new Text(changelogLine, 1, 0));
3394
+ this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
3395
+ this.ui.requestRender();
3396
+ }
3397
+ showPackageUpdateNotification(packages) {
3398
+ const action = theme.fg("accent", `${APP_NAME} update --extensions`);
3399
+ const updateInstruction = theme.fg("muted", "Package updates are available. Run ") + action;
3400
+ const packageLines = packages.map((pkg) => `- ${pkg}`).join("\n");
3401
+ this.chatContainer.addChild(new Spacer(1));
3402
+ this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
3403
+ this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning", "Package Updates Available"))}\n${updateInstruction}\n${theme.fg("muted", "Packages:")}\n${packageLines}`, 1, 0));
3404
+ this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
3405
+ this.ui.requestRender();
3406
+ }
3407
+ /**
3408
+ * Get all queued messages (read-only).
3409
+ * Combines session queue and compaction queue.
3410
+ */
3411
+ getAllQueuedMessages() {
3412
+ return {
3413
+ steering: [
3414
+ ...this.session.getSteeringMessages(),
3415
+ ...this.compactionQueuedMessages.filter((msg) => msg.mode === "steer").map((msg) => msg.text),
3416
+ ],
3417
+ followUp: [
3418
+ ...this.session.getFollowUpMessages(),
3419
+ ...this.compactionQueuedMessages.filter((msg) => msg.mode === "followUp").map((msg) => msg.text),
3420
+ ],
3421
+ };
3422
+ }
3423
+ /**
3424
+ * Clear all queued messages and return their contents.
3425
+ * Clears both session queue and compaction queue.
3426
+ */
3427
+ clearAllQueues() {
3428
+ const { steering, followUp } = this.session.clearQueue();
3429
+ const compactionSteering = this.compactionQueuedMessages
3430
+ .filter((msg) => msg.mode === "steer")
3431
+ .map((msg) => msg.text);
3432
+ const compactionFollowUp = this.compactionQueuedMessages
3433
+ .filter((msg) => msg.mode === "followUp")
3434
+ .map((msg) => msg.text);
3435
+ this.compactionQueuedMessages = [];
3436
+ return {
3437
+ steering: [...steering, ...compactionSteering],
3438
+ followUp: [...followUp, ...compactionFollowUp],
3439
+ };
3440
+ }
3441
+ updatePendingMessagesDisplay() {
3442
+ this.pendingMessagesContainer.clear();
3443
+ const { steering: steeringMessages, followUp: followUpMessages } = this.getAllQueuedMessages();
3444
+ if (steeringMessages.length > 0 || followUpMessages.length > 0) {
3445
+ this.pendingMessagesContainer.addChild(new Spacer(1));
3446
+ for (const message of steeringMessages) {
3447
+ const text = theme.fg("dim", `Steering: ${message}`);
3448
+ this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));
3449
+ }
3450
+ for (const message of followUpMessages) {
3451
+ const text = theme.fg("dim", `Follow-up: ${message}`);
3452
+ this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));
3453
+ }
3454
+ const dequeueHint = this.getAppKeyDisplay("app.message.dequeue");
3455
+ const hintText = theme.fg("dim", `↳ ${dequeueHint} to edit all queued messages`);
3456
+ this.pendingMessagesContainer.addChild(new TruncatedText(hintText, 1, 0));
3457
+ }
3458
+ }
3459
+ restoreQueuedMessagesToEditor(options) {
3460
+ const { steering, followUp } = this.clearAllQueues();
3461
+ const allQueued = [...steering, ...followUp];
3462
+ if (allQueued.length === 0) {
3463
+ this.updatePendingMessagesDisplay();
3464
+ if (options?.abort) {
3465
+ this.agent.abort();
3466
+ }
3467
+ return 0;
3468
+ }
3469
+ const queuedText = allQueued.join("\n\n");
3470
+ const currentText = options?.currentText ?? this.editor.getText();
3471
+ const combinedText = [queuedText, currentText].filter((t) => t.trim()).join("\n\n");
3472
+ this.editor.setText(combinedText);
3473
+ this.updatePendingMessagesDisplay();
3474
+ if (options?.abort) {
3475
+ this.agent.abort();
3476
+ }
3477
+ return allQueued.length;
3478
+ }
3479
+ queueCompactionMessage(text, mode) {
3480
+ this.compactionQueuedMessages.push({ text, mode });
3481
+ this.editor.addToHistory?.(text);
3482
+ this.editor.setText("");
3483
+ this.updatePendingMessagesDisplay();
3484
+ this.showStatus("Queued message for after compaction");
3485
+ }
3486
+ isExtensionCommand(text) {
3487
+ if (!text.startsWith("/"))
3488
+ return false;
3489
+ const extensionRunner = this.session.extensionRunner;
3490
+ const spaceIndex = text.indexOf(" ");
3491
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
3492
+ return !!extensionRunner.getCommand(commandName);
3493
+ }
3494
+ async flushCompactionQueue(options) {
3495
+ if (this.compactionQueuedMessages.length === 0) {
3496
+ return;
3497
+ }
3498
+ const queuedMessages = [...this.compactionQueuedMessages];
3499
+ this.compactionQueuedMessages = [];
3500
+ this.updatePendingMessagesDisplay();
3501
+ const restoreQueue = (error) => {
3502
+ this.session.clearQueue();
3503
+ this.compactionQueuedMessages = queuedMessages;
3504
+ this.updatePendingMessagesDisplay();
3505
+ this.showError(`Failed to send queued message${queuedMessages.length > 1 ? "s" : ""}: ${error instanceof Error ? error.message : String(error)}`);
3506
+ };
3507
+ try {
3508
+ if (options?.willRetry) {
3509
+ // When retry is pending, queue messages for the retry turn
3510
+ for (const message of queuedMessages) {
3511
+ if (this.isExtensionCommand(message.text)) {
3512
+ await this.session.prompt(message.text);
3513
+ }
3514
+ else if (message.mode === "followUp") {
3515
+ await this.session.followUp(message.text);
3516
+ }
3517
+ else {
3518
+ await this.session.steer(message.text);
3519
+ }
3520
+ }
3521
+ this.updatePendingMessagesDisplay();
3522
+ return;
3523
+ }
3524
+ // Find first non-extension-command message to use as prompt
3525
+ const firstPromptIndex = queuedMessages.findIndex((message) => !this.isExtensionCommand(message.text));
3526
+ if (firstPromptIndex === -1) {
3527
+ // All extension commands - execute them all
3528
+ for (const message of queuedMessages) {
3529
+ await this.session.prompt(message.text);
3530
+ }
3531
+ return;
3532
+ }
3533
+ // Execute any extension commands before the first prompt
3534
+ const preCommands = queuedMessages.slice(0, firstPromptIndex);
3535
+ const firstPrompt = queuedMessages[firstPromptIndex];
3536
+ const rest = queuedMessages.slice(firstPromptIndex + 1);
3537
+ for (const message of preCommands) {
3538
+ await this.session.prompt(message.text);
3539
+ }
3540
+ // Start a prompt when idle, or queue it into a run still finishing compaction.
3541
+ const promptPromise = this.session
3542
+ .prompt(firstPrompt.text, { streamingBehavior: firstPrompt.mode })
3543
+ .catch((error) => {
3544
+ restoreQueue(error);
3545
+ });
3546
+ // Queue remaining messages
3547
+ for (const message of rest) {
3548
+ if (this.isExtensionCommand(message.text)) {
3549
+ await this.session.prompt(message.text);
3550
+ }
3551
+ else if (message.mode === "followUp") {
3552
+ await this.session.followUp(message.text);
3553
+ }
3554
+ else {
3555
+ await this.session.steer(message.text);
3556
+ }
3557
+ }
3558
+ this.updatePendingMessagesDisplay();
3559
+ void promptPromise;
3560
+ }
3561
+ catch (error) {
3562
+ restoreQueue(error);
3563
+ }
3564
+ }
3565
+ /** Move pending bash components from pending area to chat */
3566
+ flushPendingBashComponents() {
3567
+ for (const component of this.pendingBashComponents) {
3568
+ this.pendingMessagesContainer.removeChild(component);
3569
+ this.chatContainer.addChild(component);
3570
+ }
3571
+ this.pendingBashComponents = [];
3572
+ }
3573
+ // =========================================================================
3574
+ // Selectors
3575
+ // =========================================================================
3576
+ disposeActiveSelector() {
3577
+ const dispose = this.activeSelectorDispose;
3578
+ this.activeSelectorToken = undefined;
3579
+ this.activeSelectorDispose = undefined;
3580
+ dispose?.();
3581
+ }
3582
+ /**
3583
+ * Shows a selector component in place of the editor.
3584
+ * @param create Factory that receives a `done` callback and returns the component and focus target
3585
+ */
3586
+ showSelector(create) {
3587
+ const token = {};
3588
+ let dispose;
3589
+ const done = () => {
3590
+ dispose?.();
3591
+ if (this.activeSelectorToken !== token)
3592
+ return;
3593
+ this.activeSelectorToken = undefined;
3594
+ this.activeSelectorDispose = undefined;
3595
+ this.editorContainer.clear();
3596
+ this.editorContainer.addChild(this.editor);
3597
+ this.ui.setFocus(this.editor);
3598
+ };
3599
+ const created = create(done);
3600
+ dispose = created.dispose;
3601
+ this.disposeActiveSelector();
3602
+ this.activeSelectorToken = token;
3603
+ this.activeSelectorDispose = dispose;
3604
+ this.editorContainer.clear();
3605
+ this.editorContainer.addChild(created.component);
3606
+ this.ui.setFocus(created.focus);
3607
+ this.ui.requestRender();
3608
+ }
3609
+ showSettingsSelector() {
3610
+ this.showSelector((done) => {
3611
+ let selector;
3612
+ selector = new SettingsSelectorComponent({
3613
+ autoCompact: this.session.autoCompactionEnabled,
3614
+ showImages: this.settingsManager.getShowImages(),
3615
+ imageWidthCells: this.settingsManager.getImageWidthCells(),
3616
+ autoResizeImages: this.settingsManager.getImageAutoResize(),
3617
+ blockImages: this.settingsManager.getBlockImages(),
3618
+ enableSkillCommands: this.settingsManager.getEnableSkillCommands(),
3619
+ steeringMode: this.session.steeringMode,
3620
+ followUpMode: this.session.followUpMode,
3621
+ transport: this.settingsManager.getTransport(),
3622
+ httpIdleTimeoutMs: this.settingsManager.getHttpIdleTimeoutMs(),
3623
+ thinkingLevel: this.session.thinkingLevel,
3624
+ availableThinkingLevels: this.session.getAvailableThinkingLevels(),
3625
+ currentTheme: this.settingsManager.getThemeSetting() || "dark",
3626
+ terminalTheme: this.themeController.getTerminalTheme(),
3627
+ availableThemes: getAvailableThemes(),
3628
+ hideThinkingBlock: this.hideThinkingBlock,
3629
+ mermaidRenderingMode: this.settingsManager.getMermaidRenderingMode(),
3630
+ collapseChangelog: this.settingsManager.getCollapseChangelog(),
3631
+ enableInstallTelemetry: this.settingsManager.getEnableInstallTelemetry(),
3632
+ doubleEscapeAction: this.settingsManager.getDoubleEscapeAction(),
3633
+ treeFilterMode: this.settingsManager.getTreeFilterMode(),
3634
+ showHardwareCursor: this.settingsManager.getShowHardwareCursor(),
3635
+ showCacheMissNotices: this.settingsManager.getShowCacheMissNotices(),
3636
+ defaultProjectTrust: this.settingsManager.getDefaultProjectTrust(),
3637
+ editorPaddingX: this.settingsManager.getEditorPaddingX(),
3638
+ outputPad: this.settingsManager.getOutputPad(),
3639
+ autocompleteMaxVisible: this.settingsManager.getAutocompleteMaxVisible(),
3640
+ quietStartup: this.settingsManager.getQuietStartup(),
3641
+ clearOnShrink: this.settingsManager.getClearOnShrink(),
3642
+ showTerminalProgress: this.settingsManager.getShowTerminalProgress(),
3643
+ tuiMode: this.ui.mode,
3644
+ fullscreenScrollbar: this.settingsManager.getFullscreenScrollbar(),
3645
+ warnings: this.settingsManager.getWarnings(),
3646
+ }, {
3647
+ onAutoCompactChange: (enabled) => {
3648
+ this.session.setAutoCompactionEnabled(enabled);
3649
+ this.footer.setAutoCompactEnabled(enabled);
3650
+ },
3651
+ onShowImagesChange: (enabled) => {
3652
+ this.settingsManager.setShowImages(enabled);
3653
+ for (const child of this.chatContainer.children) {
3654
+ if (child instanceof ToolExecutionComponent) {
3655
+ child.setShowImages(enabled);
3656
+ }
3657
+ }
3658
+ },
3659
+ onImageWidthCellsChange: (width) => {
3660
+ this.settingsManager.setImageWidthCells(width);
3661
+ for (const child of this.chatContainer.children) {
3662
+ if (child instanceof ToolExecutionComponent) {
3663
+ child.setImageWidthCells(width);
3664
+ }
3665
+ }
3666
+ },
3667
+ onAutoResizeImagesChange: (enabled) => {
3668
+ this.settingsManager.setImageAutoResize(enabled);
3669
+ },
3670
+ onBlockImagesChange: (blocked) => {
3671
+ this.settingsManager.setBlockImages(blocked);
3672
+ },
3673
+ onEnableSkillCommandsChange: (enabled) => {
3674
+ this.settingsManager.setEnableSkillCommands(enabled);
3675
+ this.setupAutocompleteProvider();
3676
+ },
3677
+ onSteeringModeChange: (mode) => {
3678
+ this.session.setSteeringMode(mode);
3679
+ },
3680
+ onFollowUpModeChange: (mode) => {
3681
+ this.session.setFollowUpMode(mode);
3682
+ },
3683
+ onTransportChange: (transport) => {
3684
+ this.settingsManager.setTransport(transport);
3685
+ this.session.agent.transport = transport;
3686
+ },
3687
+ onHttpIdleTimeoutMsChange: (timeoutMs) => {
3688
+ this.settingsManager.setHttpIdleTimeoutMs(timeoutMs);
3689
+ configureHttpDispatcher(timeoutMs);
3690
+ this.showStatus(`HTTP idle timeout: ${formatHttpIdleTimeoutMs(timeoutMs)}`);
3691
+ },
3692
+ onThinkingLevelChange: (level) => {
3693
+ this.session.setThinkingLevel(level);
3694
+ this.footer.invalidate();
3695
+ this.updateEditorBorderColor();
3696
+ },
3697
+ onThemeChange: (themeSetting) => {
3698
+ this.settingsManager.setTheme(themeSetting);
3699
+ void this.themeController.applyFromSettings();
3700
+ },
3701
+ onThemePreview: (themeName) => this.themeController.preview(themeName),
3702
+ onHideThinkingBlockChange: (hidden) => {
3703
+ this.hideThinkingBlock = hidden;
3704
+ this.settingsManager.setHideThinkingBlock(hidden);
3705
+ for (const child of this.chatContainer.children) {
3706
+ if (child instanceof AssistantMessageComponent) {
3707
+ child.setHideThinkingBlock(hidden);
3708
+ }
3709
+ }
3710
+ this.chatContainer.clear();
3711
+ this.rebuildChatFromMessages();
3712
+ },
3713
+ onMermaidRenderingModeChange: (mode) => {
3714
+ this.settingsManager.setMermaidRenderingMode(mode);
3715
+ this.chatContainer.invalidate();
3716
+ this.ui.requestRender();
3717
+ },
3718
+ onShowCacheMissNoticesChange: (shown) => {
3719
+ this.settingsManager.setShowCacheMissNotices(shown);
3720
+ this.rebuildChatFromMessages();
3721
+ },
3722
+ onCollapseChangelogChange: (collapsed) => {
3723
+ this.settingsManager.setCollapseChangelog(collapsed);
3724
+ },
3725
+ onEnableInstallTelemetryChange: (enabled) => {
3726
+ this.settingsManager.setEnableInstallTelemetry(enabled);
3727
+ },
3728
+ onQuietStartupChange: (enabled) => {
3729
+ this.settingsManager.setQuietStartup(enabled);
3730
+ },
3731
+ onDefaultProjectTrustChange: (defaultProjectTrust) => {
3732
+ this.settingsManager.setDefaultProjectTrust(defaultProjectTrust);
3733
+ },
3734
+ onDoubleEscapeActionChange: (action) => {
3735
+ this.settingsManager.setDoubleEscapeAction(action);
3736
+ },
3737
+ onTreeFilterModeChange: (mode) => {
3738
+ this.settingsManager.setTreeFilterMode(mode);
3739
+ },
3740
+ onShowHardwareCursorChange: (enabled) => {
3741
+ this.settingsManager.setShowHardwareCursor(enabled);
3742
+ this.ui.setShowHardwareCursor(enabled);
3743
+ },
3744
+ onEditorPaddingXChange: (padding) => {
3745
+ this.settingsManager.setEditorPaddingX(padding);
3746
+ this.defaultEditor.setPaddingX(padding);
3747
+ if (this.editor !== this.defaultEditor && this.editor.setPaddingX !== undefined) {
3748
+ this.editor.setPaddingX(padding);
3749
+ }
3750
+ },
3751
+ onOutputPadChange: (padding) => {
3752
+ this.settingsManager.setOutputPad(padding);
3753
+ this.outputPad = padding;
3754
+ if (this.streamingComponent || this.session.isStreaming) {
3755
+ for (const child of this.chatContainer.children) {
3756
+ if (child instanceof AssistantMessageComponent ||
3757
+ child instanceof CustomMessageComponent ||
3758
+ child instanceof UserMessageComponent) {
3759
+ child.setOutputPad(padding);
3760
+ }
3761
+ }
3762
+ if (this.streamingComponent) {
3763
+ this.streamingComponent.setOutputPad(padding);
3764
+ }
3765
+ this.ui.requestRender();
3766
+ return;
3767
+ }
3768
+ this.rebuildChatFromMessages();
3769
+ },
3770
+ onAutocompleteMaxVisibleChange: (maxVisible) => {
3771
+ this.settingsManager.setAutocompleteMaxVisible(maxVisible);
3772
+ this.defaultEditor.setAutocompleteMaxVisible(maxVisible);
3773
+ if (this.editor !== this.defaultEditor && this.editor.setAutocompleteMaxVisible !== undefined) {
3774
+ this.editor.setAutocompleteMaxVisible(maxVisible);
3775
+ }
3776
+ },
3777
+ onClearOnShrinkChange: (enabled) => {
3778
+ this.settingsManager.setClearOnShrink(enabled);
3779
+ this.ui.setClearOnShrink(enabled);
3780
+ if (!enabled && !this.activeStatusIndicator) {
3781
+ this.statusContainer.clear();
3782
+ }
3783
+ },
3784
+ onShowTerminalProgressChange: (enabled) => {
3785
+ this.settingsManager.setShowTerminalProgress(enabled);
3786
+ },
3787
+ onTuiModeChange: (mode) => {
3788
+ if (!this.switchTuiMode(mode)) {
3789
+ selector?.getSettingsList().updateValue("tui-mode", this.ui.mode);
3790
+ this.showStatus("Close active overlays before changing TUI mode");
3791
+ return;
3792
+ }
3793
+ this.settingsManager.setTuiMode(mode);
3794
+ if (!this.activeStatusIndicator)
3795
+ this.statusContainer.clear();
3796
+ this.showStatus(`TUI mode: ${mode}`);
3797
+ },
3798
+ onFullscreenScrollbarChange: (mode) => {
3799
+ this.settingsManager.setFullscreenScrollbar(mode);
3800
+ this.applyFullscreenScrollbarSetting();
3801
+ },
3802
+ onWarningsChange: (warnings) => {
3803
+ this.settingsManager.setWarnings(warnings);
3804
+ },
3805
+ onCancel: () => {
3806
+ done();
3807
+ this.ui.requestRender();
3808
+ },
3809
+ });
3810
+ return { component: selector, focus: selector.getSettingsList() };
3811
+ });
3812
+ }
3813
+ async handleModelCommand(searchTerm) {
3814
+ if (!searchTerm) {
3815
+ this.showModelSelector();
3816
+ return;
3817
+ }
3818
+ const model = await this.findExactModelMatch(searchTerm);
3819
+ if (model) {
3820
+ try {
3821
+ await this.session.setModel(model);
3822
+ this.footer.invalidate();
3823
+ this.updateEditorBorderColor();
3824
+ this.showStatus(`Model: ${model.id}`);
3825
+ void this.maybeWarnAboutAnthropicSubscriptionAuth(model);
3826
+ this.checkDaxnutsEasterEgg(model);
3827
+ }
3828
+ catch (error) {
3829
+ this.showError(error instanceof Error ? error.message : String(error));
3830
+ }
3831
+ return;
3832
+ }
3833
+ this.showModelSelector(searchTerm);
3834
+ }
3835
+ async findExactModelMatch(searchTerm) {
3836
+ const cachedModels = this.session.scopedModels.length > 0
3837
+ ? this.session.scopedModels.map((scoped) => scoped.model)
3838
+ : [...this.session.modelRuntime.getAvailableSnapshot()];
3839
+ const cachedMatch = findExactModelReferenceMatch(searchTerm, cachedModels);
3840
+ if (cachedMatch || this.session.scopedModels.length > 0)
3841
+ return cachedMatch;
3842
+ this.showStatus("Refreshing model catalogs…");
3843
+ const controller = new AbortController();
3844
+ let timedOut = false;
3845
+ const timeout = setTimeout(() => {
3846
+ timedOut = true;
3847
+ controller.abort();
3848
+ }, 15_000);
3849
+ try {
3850
+ const result = await this.session.modelRuntime.refresh({ signal: controller.signal });
3851
+ if (result.aborted && timedOut) {
3852
+ this.showWarning("Model refresh timed out; searching cached models.");
3853
+ }
3854
+ else if (result.errors.size > 0) {
3855
+ this.showWarning(`Could not refresh ${[...result.errors.keys()].join(", ")}; searching cached models.`);
3856
+ }
3857
+ }
3858
+ catch (error) {
3859
+ this.showWarning(timedOut
3860
+ ? "Model refresh timed out; searching cached models."
3861
+ : `Could not refresh model catalogs: ${error instanceof Error ? error.message : String(error)}`);
3862
+ }
3863
+ finally {
3864
+ clearTimeout(timeout);
3865
+ }
3866
+ return findExactModelReferenceMatch(searchTerm, [...this.session.modelRuntime.getAvailableSnapshot()]);
3867
+ }
3868
+ /** Update the footer's available provider count from the current snapshot without refreshing catalogs. */
3869
+ updateAvailableProviderCount() {
3870
+ const models = this.session.scopedModels.length > 0
3871
+ ? this.session.scopedModels.map((scoped) => scoped.model)
3872
+ : this.session.modelRuntime.getAvailableSnapshot();
3873
+ const uniqueProviders = new Set(models.map((model) => model.provider));
3874
+ this.footerDataProvider.setAvailableProviderCount(uniqueProviders.size);
3875
+ }
3876
+ async maybeWarnAboutAnthropicSubscriptionAuth(model = this.session.model) {
3877
+ if (this.settingsManager.getWarnings().anthropicExtraUsage === false) {
3878
+ return;
3879
+ }
3880
+ if (this.anthropicSubscriptionWarningShown) {
3881
+ return;
3882
+ }
3883
+ if (!model || model.provider !== "anthropic") {
3884
+ return;
3885
+ }
3886
+ try {
3887
+ if ((await this.session.modelRuntime.checkAuth("anthropic"))?.type === "oauth") {
3888
+ this.anthropicSubscriptionWarningShown = true;
3889
+ this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);
3890
+ return;
3891
+ }
3892
+ const apiKey = (await this.session.modelRuntime.getAuth(model.provider))?.auth.apiKey;
3893
+ if (!isAnthropicSubscriptionAuthKey(apiKey)) {
3894
+ return;
3895
+ }
3896
+ this.anthropicSubscriptionWarningShown = true;
3897
+ this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);
3898
+ }
3899
+ catch {
3900
+ // Ignore auth lookup failures for warning-only checks.
3901
+ }
3902
+ }
3903
+ maybeSaveImplicitProjectTrustAfterReload() {
3904
+ const cwd = this.sessionManager.getCwd();
3905
+ if (this.autoTrustOnReloadCwd !== cwd) {
3906
+ return false;
3907
+ }
3908
+ if (!this.settingsManager.isProjectTrusted() || !hasTrustRequiringProjectResources(cwd)) {
3909
+ return false;
3910
+ }
3911
+ const trustStore = new ProjectTrustStore(this.runtimeHost.services.agentDir);
3912
+ try {
3913
+ if (trustStore.get(cwd) !== null) {
3914
+ this.autoTrustOnReloadCwd = undefined;
3915
+ return false;
3916
+ }
3917
+ trustStore.set(cwd, true);
3918
+ this.autoTrustOnReloadCwd = undefined;
3919
+ return true;
3920
+ }
3921
+ catch (error) {
3922
+ this.showWarning(`Could not save project trust after reload: ${error instanceof Error ? error.message : String(error)}`);
3923
+ return false;
3924
+ }
3925
+ }
3926
+ showTrustSelector() {
3927
+ const cwd = this.sessionManager.getCwd();
3928
+ const trustStore = new ProjectTrustStore(this.runtimeHost.services.agentDir);
3929
+ const savedDecision = trustStore.getEntry(cwd);
3930
+ this.showSelector((done) => {
3931
+ const selector = new TrustSelectorComponent({
3932
+ cwd,
3933
+ savedDecision,
3934
+ projectTrusted: this.settingsManager.isProjectTrusted(),
3935
+ onSelect: (selection) => {
3936
+ trustStore.setMany(selection.updates);
3937
+ done();
3938
+ this.showStatus(`Saved trust decision: ${selection.trusted ? "trusted" : "untrusted"}. Restart pi for this to take effect.`);
3939
+ },
3940
+ onCancel: () => {
3941
+ done();
3942
+ this.ui.requestRender();
3943
+ },
3944
+ });
3945
+ return { component: selector, focus: selector };
3946
+ });
3947
+ }
3948
+ showModelSelector(initialSearchInput) {
3949
+ this.showSelector((done) => {
3950
+ const selector = new ModelSelectorComponent(this.ui, this.session.model, this.settingsManager, this.session.modelRuntime, this.session.scopedModels, async (model) => {
3951
+ try {
3952
+ await this.session.setModel(model);
3953
+ this.footer.invalidate();
3954
+ this.updateEditorBorderColor();
3955
+ done();
3956
+ this.showStatus(`Model: ${model.id}`);
3957
+ void this.maybeWarnAboutAnthropicSubscriptionAuth(model);
3958
+ this.checkDaxnutsEasterEgg(model);
3959
+ }
3960
+ catch (error) {
3961
+ done();
3962
+ this.showError(error instanceof Error ? error.message : String(error));
3963
+ }
3964
+ }, () => {
3965
+ done();
3966
+ this.ui.requestRender();
3967
+ }, initialSearchInput);
3968
+ return { component: selector, focus: selector, dispose: () => selector.dispose() };
3969
+ });
3970
+ }
3971
+ showModelsSelector() {
3972
+ let availableModels = [...this.session.modelRuntime.getAvailableSnapshot()];
3973
+ let availableModelIds = new Set(availableModels.map((model) => `${model.provider}/${model.id}`));
3974
+ const configuredPatterns = this.settingsManager.getEnabledModels();
3975
+ const sessionScopedModels = this.session.scopedModels;
3976
+ const configuredEnabledIds = (models) => {
3977
+ if (!configuredPatterns?.length)
3978
+ return null;
3979
+ const resolved = resolveModelScopeFromModels(configuredPatterns, models);
3980
+ const ids = resolved.scopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);
3981
+ for (const diagnostic of resolved.diagnostics) {
3982
+ if (diagnostic.code === "no-match" && !ids.includes(diagnostic.pattern))
3983
+ ids.push(diagnostic.pattern);
3984
+ }
3985
+ return ids;
3986
+ };
3987
+ let currentEnabledIds = sessionScopedModels.length > 0
3988
+ ? sessionScopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`)
3989
+ : configuredEnabledIds(availableModels);
3990
+ let selectionChanged = false;
3991
+ const updateSessionModels = (enabledIds) => {
3992
+ currentEnabledIds = enabledIds === null ? null : [...enabledIds];
3993
+ const hasEnabledAvailableModel = enabledIds?.some((id) => availableModelIds.has(id)) ?? false;
3994
+ const allAvailableModelsEnabled = enabledIds !== null && [...availableModelIds].every((id) => enabledIds.includes(id));
3995
+ if (enabledIds && hasEnabledAvailableModel && !allAvailableModelsEnabled) {
3996
+ const newScopedModels = resolveModelScopeFromModels(enabledIds, availableModels).scopedModels;
3997
+ this.session.setScopedModels(newScopedModels.map((scoped) => ({
3998
+ model: scoped.model,
3999
+ thinkingLevel: scoped.thinkingLevel,
4000
+ })));
4001
+ }
4002
+ else {
4003
+ this.session.setScopedModels([]);
4004
+ }
4005
+ this.updateAvailableProviderCount();
4006
+ this.ui.requestRender();
4007
+ };
4008
+ this.showSelector((done) => {
4009
+ let disposed = false;
4010
+ let timedOut = false;
4011
+ const controller = new AbortController();
4012
+ const timeout = setTimeout(() => {
4013
+ timedOut = true;
4014
+ controller.abort();
4015
+ }, 15_000);
4016
+ const selector = new ScopedModelsSelectorComponent({
4017
+ allModels: availableModels,
4018
+ enabledModelIds: currentEnabledIds,
4019
+ refreshStatus: "Refreshing model catalogs…",
4020
+ }, {
4021
+ onChange: (enabledIds) => {
4022
+ selectionChanged = true;
4023
+ updateSessionModels(enabledIds);
4024
+ },
4025
+ onPersist: (enabledIds) => {
4026
+ const allEnabled = enabledIds !== null &&
4027
+ enabledIds.length === availableModels.length &&
4028
+ enabledIds.every((id) => availableModelIds.has(id));
4029
+ const newPatterns = enabledIds === null || allEnabled ? undefined : enabledIds;
4030
+ this.settingsManager.setEnabledModels(newPatterns ? [...newPatterns] : undefined);
4031
+ this.showStatus("Model selection saved to settings");
4032
+ },
4033
+ onCancel: () => {
4034
+ done();
4035
+ this.ui.requestRender();
4036
+ },
4037
+ });
4038
+ void this.session.modelRuntime
4039
+ .refresh({ signal: controller.signal })
4040
+ .then((result) => {
4041
+ if (disposed)
4042
+ return;
4043
+ availableModels = [...this.session.modelRuntime.getAvailableSnapshot()];
4044
+ availableModelIds = new Set(availableModels.map((model) => `${model.provider}/${model.id}`));
4045
+ if (!selectionChanged && sessionScopedModels.length === 0) {
4046
+ currentEnabledIds = configuredEnabledIds(availableModels);
4047
+ selector.updateModels(availableModels, currentEnabledIds);
4048
+ }
4049
+ else {
4050
+ selector.updateModels(availableModels);
4051
+ }
4052
+ if (currentEnabledIds !== null)
4053
+ updateSessionModels(currentEnabledIds);
4054
+ if (result.aborted && timedOut) {
4055
+ selector.setRefreshStatus("Model refresh timed out; showing cached models.", "warning");
4056
+ }
4057
+ else if (result.errors.size > 0) {
4058
+ selector.setRefreshStatus(`Could not refresh ${[...result.errors.keys()].join(", ")}; showing cached models.`, "warning");
4059
+ }
4060
+ else {
4061
+ selector.setRefreshStatus("Model catalogs refreshed.", "success");
4062
+ }
4063
+ this.ui.requestRender();
4064
+ })
4065
+ .catch((error) => {
4066
+ if (disposed)
4067
+ return;
4068
+ selector.setRefreshStatus(timedOut
4069
+ ? "Model refresh timed out; showing cached models."
4070
+ : `Could not refresh model catalogs: ${error instanceof Error ? error.message : String(error)}`, "warning");
4071
+ this.ui.requestRender();
4072
+ })
4073
+ .finally(() => clearTimeout(timeout));
4074
+ return {
4075
+ component: selector,
4076
+ focus: selector,
4077
+ dispose: () => {
4078
+ disposed = true;
4079
+ clearTimeout(timeout);
4080
+ controller.abort();
4081
+ },
4082
+ };
4083
+ });
4084
+ }
4085
+ showUserMessageSelector() {
4086
+ const userMessages = this.session.getUserMessagesForForking();
4087
+ if (userMessages.length === 0) {
4088
+ this.showStatus("No messages to fork from");
4089
+ return;
4090
+ }
4091
+ const initialSelectedId = userMessages[userMessages.length - 1]?.entryId;
4092
+ this.showSelector((done) => {
4093
+ const selector = new UserMessageSelectorComponent(userMessages.map((m) => ({ id: m.entryId, text: m.text })), async (entryId) => {
4094
+ done();
4095
+ try {
4096
+ const result = await this.runtimeHost.fork(entryId);
4097
+ if (result.cancelled) {
4098
+ this.ui.requestRender();
4099
+ return;
4100
+ }
4101
+ this.editor.setText(result.selectedText ?? "");
4102
+ this.showStatus("Forked to new session");
4103
+ }
4104
+ catch (error) {
4105
+ this.showError(error instanceof Error ? error.message : String(error));
4106
+ }
4107
+ }, () => {
4108
+ done();
4109
+ this.ui.requestRender();
4110
+ }, initialSelectedId);
4111
+ return { component: selector, focus: selector.getMessageList() };
4112
+ });
4113
+ }
4114
+ async handleCloneCommand() {
4115
+ const leafId = this.sessionManager.getLeafId();
4116
+ if (!leafId) {
4117
+ this.showStatus("Nothing to clone yet");
4118
+ return;
4119
+ }
4120
+ try {
4121
+ const result = await this.runtimeHost.fork(leafId, { position: "at" });
4122
+ if (result.cancelled) {
4123
+ this.ui.requestRender();
4124
+ return;
4125
+ }
4126
+ this.editor.setText("");
4127
+ this.showStatus("Cloned to new session");
4128
+ }
4129
+ catch (error) {
4130
+ this.showError(error instanceof Error ? error.message : String(error));
4131
+ }
4132
+ }
4133
+ showTreeSelector(initialSelectedId) {
4134
+ const tree = this.sessionManager.getTree();
4135
+ const realLeafId = this.sessionManager.getLeafId();
4136
+ const initialFilterMode = this.settingsManager.getTreeFilterMode();
4137
+ if (tree.length === 0) {
4138
+ this.showStatus("No entries in session");
4139
+ return;
4140
+ }
4141
+ this.showSelector((done) => {
4142
+ const selector = new TreeSelectorComponent(tree, realLeafId, this.ui.terminal.rows, async (entryId) => {
4143
+ // Selecting the current leaf is a no-op (already there)
4144
+ if (entryId === this.sessionManager.getLeafId()) {
4145
+ done();
4146
+ this.showStatus("Already at this point");
4147
+ return;
4148
+ }
4149
+ // Ask about summarization
4150
+ done(); // Close selector first
4151
+ // Loop until user makes a complete choice or cancels to tree
4152
+ let wantsSummary = false;
4153
+ let customInstructions;
4154
+ // Check if we should skip the prompt (user preference to always default to no summary)
4155
+ if (!this.settingsManager.getBranchSummarySkipPrompt()) {
4156
+ while (true) {
4157
+ const summaryChoice = await this.showExtensionSelector("Summarize branch?", [
4158
+ "No summary",
4159
+ "Summarize",
4160
+ "Summarize with custom prompt",
4161
+ ]);
4162
+ if (summaryChoice === undefined) {
4163
+ // User pressed escape - re-show tree selector with same selection
4164
+ this.showTreeSelector(entryId);
4165
+ return;
4166
+ }
4167
+ wantsSummary = summaryChoice !== "No summary";
4168
+ if (summaryChoice === "Summarize with custom prompt") {
4169
+ customInstructions = await this.showExtensionEditor("Custom summarization instructions");
4170
+ if (customInstructions === undefined) {
4171
+ // User cancelled - loop back to summary selector
4172
+ continue;
4173
+ }
4174
+ }
4175
+ // User made a complete choice
4176
+ break;
4177
+ }
4178
+ }
4179
+ // The user committed to navigating: stop the active response first.
4180
+ if (this.session.isStreaming) {
4181
+ this.restoreQueuedMessagesToEditor();
4182
+ await this.session.abort();
4183
+ }
4184
+ // Set up escape handler and status indicator if summarizing
4185
+ let showingSummaryIndicator = false;
4186
+ const originalOnEscape = this.defaultEditor.onEscape;
4187
+ if (wantsSummary) {
4188
+ this.defaultEditor.onEscape = () => {
4189
+ this.session.abortBranchSummary();
4190
+ };
4191
+ this.chatContainer.addChild(new Spacer(1));
4192
+ this.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui));
4193
+ showingSummaryIndicator = true;
4194
+ this.ui.requestRender();
4195
+ }
4196
+ try {
4197
+ const result = await this.session.navigateTree(entryId, {
4198
+ summarize: wantsSummary,
4199
+ customInstructions,
4200
+ });
4201
+ if (result.aborted) {
4202
+ // Summarization aborted - re-show tree selector with same selection
4203
+ this.showStatus("Branch summarization cancelled");
4204
+ this.showTreeSelector(entryId);
4205
+ return;
4206
+ }
4207
+ if (result.cancelled) {
4208
+ this.showStatus("Navigation cancelled");
4209
+ return;
4210
+ }
4211
+ // Update UI
4212
+ this.chatContainer.clear();
4213
+ this.renderInitialMessages();
4214
+ if (result.editorText && !this.editor.getText().trim()) {
4215
+ this.editor.setText(result.editorText);
4216
+ }
4217
+ this.showStatus("Navigated to selected point");
4218
+ void this.flushCompactionQueue({ willRetry: false });
4219
+ }
4220
+ catch (error) {
4221
+ this.showError(error instanceof Error ? error.message : String(error));
4222
+ }
4223
+ finally {
4224
+ if (showingSummaryIndicator) {
4225
+ this.clearStatusIndicator("branchSummary");
4226
+ }
4227
+ this.defaultEditor.onEscape = originalOnEscape;
4228
+ }
4229
+ }, () => {
4230
+ done();
4231
+ this.ui.requestRender();
4232
+ }, (entryId, label) => {
4233
+ this.sessionManager.appendLabelChange(entryId, label);
4234
+ this.ui.requestRender();
4235
+ }, initialSelectedId, initialFilterMode);
4236
+ selector.onCopy = async (text) => {
4237
+ if (!text) {
4238
+ this.showError("Selected entry has no text to copy");
4239
+ return;
4240
+ }
4241
+ try {
4242
+ await copyToClipboard(text);
4243
+ this.showStatus("Copied selected message to clipboard");
4244
+ }
4245
+ catch (error) {
4246
+ this.showError(error instanceof Error ? error.message : String(error));
4247
+ }
4248
+ };
4249
+ return { component: selector, focus: selector };
4250
+ });
4251
+ }
4252
+ showSessionSelector() {
4253
+ this.showSelector((done) => {
4254
+ const selector = new SessionSelectorComponent((onProgress) => SessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir(), onProgress), (onProgress) => this.sessionManager.usesDefaultSessionDir()
4255
+ ? SessionManager.listAll(onProgress)
4256
+ : SessionManager.listAll(this.sessionManager.getSessionDir(), onProgress), async (sessionPath) => {
4257
+ done();
4258
+ await this.handleResumeSession(sessionPath);
4259
+ }, () => {
4260
+ done();
4261
+ this.ui.requestRender();
4262
+ }, () => {
4263
+ void this.shutdown();
4264
+ }, () => this.ui.requestRender(), {
4265
+ renameSession: async (sessionFilePath, nextName) => {
4266
+ const next = (nextName ?? "").trim();
4267
+ if (!next)
4268
+ return;
4269
+ const mgr = SessionManager.open(sessionFilePath);
4270
+ mgr.appendSessionInfo(next);
4271
+ },
4272
+ showRenameHint: true,
4273
+ keybindings: this.keybindings,
4274
+ }, this.sessionManager.getSessionFile());
4275
+ return { component: selector, focus: selector };
4276
+ });
4277
+ }
4278
+ async handleResumeSession(sessionPath, options) {
4279
+ this.clearStatusIndicator();
4280
+ try {
4281
+ const result = await this.runtimeHost.switchSession(sessionPath, {
4282
+ withSession: options?.withSession,
4283
+ projectTrustContextFactory: (cwd) => this.createProjectTrustContext(cwd),
4284
+ });
4285
+ if (result.cancelled) {
4286
+ return result;
4287
+ }
4288
+ this.showStatus("Resumed session");
4289
+ return result;
4290
+ }
4291
+ catch (error) {
4292
+ if (error instanceof MissingSessionCwdError) {
4293
+ const selectedCwd = await this.promptForMissingSessionCwd(error);
4294
+ if (!selectedCwd) {
4295
+ this.showStatus("Resume cancelled");
4296
+ return { cancelled: true };
4297
+ }
4298
+ const result = await this.runtimeHost.switchSession(sessionPath, {
4299
+ cwdOverride: selectedCwd,
4300
+ withSession: options?.withSession,
4301
+ projectTrustContextFactory: (cwd) => this.createProjectTrustContext(cwd),
4302
+ });
4303
+ if (result.cancelled) {
4304
+ return result;
4305
+ }
4306
+ this.showStatus("Resumed session in current cwd");
4307
+ return result;
4308
+ }
4309
+ return this.handleFatalRuntimeError("Failed to resume session", error);
4310
+ }
4311
+ }
4312
+ getLoginProviderOptions(authType) {
4313
+ const options = [];
4314
+ for (const provider of this.session.modelRuntime.getProviders()) {
4315
+ const authStatus = this.session.modelRuntime.getProviderAuthStatus(provider.id);
4316
+ const status = authStatus.configured
4317
+ ? {
4318
+ type: this.session.modelRuntime.isUsingOAuth(provider.id) ? "oauth" : "api_key",
4319
+ source: authStatus.label ?? authStatus.source,
4320
+ }
4321
+ : undefined;
4322
+ if ((!authType || authType === "oauth") && provider.auth.oauth) {
4323
+ options.push({
4324
+ id: provider.id,
4325
+ name: provider.name,
4326
+ authType: "oauth",
4327
+ method: provider.auth.oauth,
4328
+ status,
4329
+ });
4330
+ }
4331
+ if ((!authType || authType === "api_key") && provider.auth.apiKey) {
4332
+ options.push({
4333
+ id: provider.id,
4334
+ name: provider.name,
4335
+ authType: "api_key",
4336
+ method: provider.auth.apiKey,
4337
+ status,
4338
+ });
4339
+ }
4340
+ }
4341
+ return options.sort((a, b) => a.name.localeCompare(b.name));
4342
+ }
4343
+ async getLogoutProviderOptions() {
4344
+ return (await this.session.modelRuntime.listCredentials({ signal: AbortSignal.timeout(15_000) }))
4345
+ .map(({ providerId, type }) => ({
4346
+ id: providerId,
4347
+ name: this.session.modelRuntime.getProvider(providerId)?.name ?? providerId,
4348
+ authType: type,
4349
+ status: { type, source: "stored credential" },
4350
+ }))
4351
+ .sort((a, b) => a.name.localeCompare(b.name));
4352
+ }
4353
+ findLoginProviderOptions(providerRef) {
4354
+ const normalizedProviderRef = providerRef.trim().toLowerCase();
4355
+ if (!normalizedProviderRef) {
4356
+ return [];
4357
+ }
4358
+ return this.getLoginProviderOptions().filter((provider) => provider.id.toLowerCase() === normalizedProviderRef ||
4359
+ provider.name.toLowerCase() === normalizedProviderRef);
4360
+ }
4361
+ async handleLoginCommand(providerRef) {
4362
+ if (!providerRef) {
4363
+ this.showLoginAuthTypeSelector();
4364
+ return;
4365
+ }
4366
+ const providerOptions = this.findLoginProviderOptions(providerRef);
4367
+ if (providerOptions.length === 1) {
4368
+ await this.startProviderLogin(providerOptions[0]);
4369
+ return;
4370
+ }
4371
+ if (providerOptions.length > 1) {
4372
+ const providerIds = new Set(providerOptions.map((provider) => provider.id));
4373
+ if (providerIds.size === 1) {
4374
+ this.showLoginAuthTypeSelector(providerOptions);
4375
+ return;
4376
+ }
4377
+ }
4378
+ this.showLoginProviderSelector(undefined, providerRef);
4379
+ }
4380
+ async startProviderLogin(providerOption) {
4381
+ if (providerOption.authType === "oauth") {
4382
+ await this.showLoginDialog(providerOption.id, providerOption.name);
4383
+ }
4384
+ else if (providerOption.method?.login) {
4385
+ await this.showApiKeyLoginDialog(providerOption.id, providerOption.name);
4386
+ }
4387
+ else {
4388
+ this.showAmbientAuthDialog(providerOption);
4389
+ }
4390
+ }
4391
+ showLoginAuthTypeSelector(providerOptions) {
4392
+ const oauthProvider = providerOptions?.find((provider) => provider.authType === "oauth");
4393
+ const oauthLoginLabel = oauthProvider?.method && "loginLabel" in oauthProvider.method ? oauthProvider.method.loginLabel : undefined;
4394
+ const subscriptionLabel = oauthLoginLabel ?? "Sign in with an account";
4395
+ const apiKeyLabel = "Sign in with an API key";
4396
+ const availableAuthTypes = providerOptions
4397
+ ? new Set(providerOptions.map((provider) => provider.authType))
4398
+ : new Set(["oauth", "api_key"]);
4399
+ const options = [];
4400
+ if (availableAuthTypes.has("oauth")) {
4401
+ options.push(subscriptionLabel);
4402
+ }
4403
+ if (availableAuthTypes.has("api_key")) {
4404
+ options.push(apiKeyLabel);
4405
+ }
4406
+ if (options.length === 0) {
4407
+ this.showStatus("No login methods available.");
4408
+ return;
4409
+ }
4410
+ if (providerOptions && options.length === 1) {
4411
+ const providerOption = providerOptions[0];
4412
+ if (providerOption) {
4413
+ void this.startProviderLogin(providerOption);
4414
+ }
4415
+ return;
4416
+ }
4417
+ const title = providerOptions?.[0]
4418
+ ? `Select authentication method for ${providerOptions[0].name}:`
4419
+ : "Select authentication method:";
4420
+ this.showSelector((done) => {
4421
+ const selector = new ExtensionSelectorComponent(title, options, (option) => {
4422
+ done();
4423
+ const authType = option === subscriptionLabel ? "oauth" : "api_key";
4424
+ if (providerOptions) {
4425
+ const providerOption = providerOptions.find((provider) => provider.authType === authType);
4426
+ if (providerOption) {
4427
+ void this.startProviderLogin(providerOption);
4428
+ }
4429
+ return;
4430
+ }
4431
+ this.showLoginProviderSelector(authType);
4432
+ }, () => {
4433
+ done();
4434
+ this.ui.requestRender();
4435
+ });
4436
+ return { component: selector, focus: selector };
4437
+ });
4438
+ }
4439
+ showLoginProviderSelector(authType, initialSearchInput) {
4440
+ const providerOptions = this.getLoginProviderOptions(authType);
4441
+ if (providerOptions.length === 0) {
4442
+ const message = authType === "oauth"
4443
+ ? "No subscription providers available."
4444
+ : authType === "api_key"
4445
+ ? "No API key providers available."
4446
+ : "No login providers available.";
4447
+ this.showStatus(message);
4448
+ return;
4449
+ }
4450
+ this.showSelector((done) => {
4451
+ const selector = new OAuthSelectorComponent("login", providerOptions, async (providerId, selectedAuthType) => {
4452
+ done();
4453
+ const providerOption = providerOptions.find((provider) => provider.id === providerId && provider.authType === selectedAuthType);
4454
+ if (!providerOption) {
4455
+ return;
4456
+ }
4457
+ await this.startProviderLogin(providerOption);
4458
+ }, () => {
4459
+ done();
4460
+ if (authType) {
4461
+ this.showLoginAuthTypeSelector();
4462
+ }
4463
+ else {
4464
+ this.ui.requestRender();
4465
+ }
4466
+ }, initialSearchInput);
4467
+ return { component: selector, focus: selector };
4468
+ });
4469
+ }
4470
+ async showOAuthSelector(mode) {
4471
+ if (mode === "login") {
4472
+ this.showLoginAuthTypeSelector();
4473
+ return;
4474
+ }
4475
+ let providerOptions;
4476
+ try {
4477
+ providerOptions = await this.getLogoutProviderOptions();
4478
+ }
4479
+ catch (error) {
4480
+ this.showError(`Could not read stored credentials: ${error instanceof Error ? error.message : String(error)}`);
4481
+ return;
4482
+ }
4483
+ if (providerOptions.length === 0) {
4484
+ this.showStatus("No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.");
4485
+ return;
4486
+ }
4487
+ this.showSelector((done) => {
4488
+ const selector = new OAuthSelectorComponent(mode, providerOptions, async (providerId) => {
4489
+ done();
4490
+ const providerOption = providerOptions.find((provider) => provider.id === providerId);
4491
+ if (!providerOption) {
4492
+ return;
4493
+ }
4494
+ try {
4495
+ await this.session.modelRuntime.logout(providerOption.id, {
4496
+ signal: AbortSignal.timeout(15_000),
4497
+ });
4498
+ await this.updateAvailableProviderCount();
4499
+ const message = providerOption.authType === "oauth"
4500
+ ? `Logged out of ${providerOption.name}`
4501
+ : `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;
4502
+ this.showStatus(message);
4503
+ }
4504
+ catch (error) {
4505
+ const message = error instanceof Error ? error.message : String(error);
4506
+ this.showError(error instanceof CredentialSynchronizationError
4507
+ ? `Credentials removed for ${providerOption.name}, but local model state could not be synchronized: ${message}`
4508
+ : `Logout failed: ${message}`);
4509
+ }
4510
+ }, () => {
4511
+ done();
4512
+ this.ui.requestRender();
4513
+ });
4514
+ return { component: selector, focus: selector };
4515
+ });
4516
+ }
4517
+ async completeProviderAuthentication(providerId, providerName, authType, previousModel) {
4518
+ const actionLabel = authType === "oauth" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;
4519
+ let selectedModel;
4520
+ let selectionError;
4521
+ if (isUnknownModel(previousModel)) {
4522
+ const availableModels = this.session.modelRuntime.getAvailableSnapshot();
4523
+ const providerModels = availableModels.filter((model) => model.provider === providerId);
4524
+ if (!hasDefaultModelProvider(providerId)) {
4525
+ selectionError = `${actionLabel}, but no default model is configured for provider "${providerId}". Use /model to select a model.`;
4526
+ }
4527
+ else if (providerModels.length === 0) {
4528
+ selectionError = `${actionLabel}, but no models are available for that provider. Use /model to select a model.`;
4529
+ }
4530
+ else {
4531
+ const defaultModelId = defaultModelPerProvider[providerId];
4532
+ selectedModel = providerModels.find((model) => model.id === defaultModelId);
4533
+ if (!selectedModel) {
4534
+ selectionError = `${actionLabel}, but its default model "${defaultModelId}" is not available. Use /model to select a model.`;
4535
+ }
4536
+ else {
4537
+ try {
4538
+ await this.session.setModel(selectedModel);
4539
+ }
4540
+ catch (error) {
4541
+ selectedModel = undefined;
4542
+ const errorMessage = error instanceof Error ? error.message : String(error);
4543
+ selectionError = `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`;
4544
+ }
4545
+ }
4546
+ }
4547
+ }
4548
+ await this.updateAvailableProviderCount();
4549
+ this.footer.invalidate();
4550
+ this.updateEditorBorderColor();
4551
+ if (selectedModel) {
4552
+ this.showStatus(`${actionLabel}. Selected ${selectedModel.id}. Credentials saved to ${getAuthPath()}`);
4553
+ void this.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel);
4554
+ this.checkDaxnutsEasterEgg(selectedModel);
4555
+ }
4556
+ else {
4557
+ this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`);
4558
+ if (selectionError) {
4559
+ this.showError(selectionError);
4560
+ }
4561
+ else {
4562
+ void this.maybeWarnAboutAnthropicSubscriptionAuth();
4563
+ }
4564
+ }
4565
+ const controller = new AbortController();
4566
+ const timeout = setTimeout(() => controller.abort(), 15_000);
4567
+ void this.session.modelRuntime
4568
+ .refresh({ providers: [providerId], signal: controller.signal })
4569
+ .then((result) => {
4570
+ if (result.aborted) {
4571
+ this.showWarning(`${actionLabel}, but its model catalog refresh timed out; using cached models.`);
4572
+ }
4573
+ else if (result.errors.size > 0) {
4574
+ this.showWarning(`${actionLabel}, but its model catalog could not be refreshed; using cached models.`);
4575
+ }
4576
+ this.updateAvailableProviderCount();
4577
+ this.footer.invalidate();
4578
+ this.ui.requestRender();
4579
+ })
4580
+ .catch((error) => {
4581
+ this.showWarning(`${actionLabel}, but its model catalog could not be refreshed: ${error instanceof Error ? error.message : String(error)}`);
4582
+ })
4583
+ .finally(() => clearTimeout(timeout));
4584
+ }
4585
+ showAmbientAuthDialog(providerOption) {
4586
+ const restoreEditor = () => {
4587
+ this.editorContainer.clear();
4588
+ this.editorContainer.addChild(this.editor);
4589
+ this.ui.setFocus(this.editor);
4590
+ this.ui.requestRender();
4591
+ };
4592
+ const dialog = new LoginDialogComponent(this.ui, providerOption.id, () => restoreEditor(), providerOption.name, `${providerOption.name} setup`);
4593
+ dialog.showInfo(`${providerOption.method?.name ?? "Authentication"} is configured outside pi.`, [], true);
4594
+ this.editorContainer.clear();
4595
+ this.editorContainer.addChild(dialog);
4596
+ this.ui.setFocus(dialog);
4597
+ this.ui.requestRender();
4598
+ }
4599
+ async showApiKeyLoginDialog(providerId, providerName) {
4600
+ const previousModel = this.session.model;
4601
+ const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => {
4602
+ // Completion handled below
4603
+ }, providerName);
4604
+ if (providerId === "amazon-bedrock") {
4605
+ dialog.showDetails([
4606
+ theme.fg("text", "You can also use an AWS profile, IAM keys, or role-based credentials."),
4607
+ theme.fg("muted", "See:"),
4608
+ theme.fg("accent", ` ${path.join(getDocsPath(), "providers.md")}`),
4609
+ ]);
4610
+ }
4611
+ this.editorContainer.clear();
4612
+ this.editorContainer.addChild(dialog);
4613
+ this.ui.setFocus(dialog);
4614
+ this.ui.requestRender();
4615
+ const restoreEditor = () => {
4616
+ this.editorContainer.clear();
4617
+ this.editorContainer.addChild(this.editor);
4618
+ this.ui.setFocus(this.editor);
4619
+ this.ui.requestRender();
4620
+ };
4621
+ try {
4622
+ await this.loginProvider(dialog, providerId, "api_key");
4623
+ restoreEditor();
4624
+ await this.completeProviderAuthentication(providerId, providerName, "api_key", previousModel);
4625
+ }
4626
+ catch (error) {
4627
+ restoreEditor();
4628
+ const errorMsg = error instanceof Error ? error.message : String(error);
4629
+ if (error instanceof CredentialSynchronizationError) {
4630
+ this.showError(`Saved API key for ${providerName}, but local model state could not be synchronized: ${errorMsg}`);
4631
+ }
4632
+ else if (errorMsg !== "Login cancelled") {
4633
+ this.showError(`Failed to save API key for ${providerName}: ${errorMsg}`);
4634
+ }
4635
+ }
4636
+ }
4637
+ showAuthSelect(dialog, prompt) {
4638
+ return new Promise((resolve, reject) => {
4639
+ const restoreDialog = () => {
4640
+ this.editorContainer.clear();
4641
+ this.editorContainer.addChild(dialog);
4642
+ this.ui.setFocus(dialog);
4643
+ this.ui.requestRender();
4644
+ };
4645
+ const labels = prompt.options.map((option) => option.label);
4646
+ const selector = new ExtensionSelectorComponent(prompt.message, labels, (optionLabel) => {
4647
+ restoreDialog();
4648
+ const id = prompt.options.find((option) => option.label === optionLabel)?.id;
4649
+ if (id)
4650
+ resolve(id);
4651
+ else
4652
+ reject(new Error("Login cancelled"));
4653
+ }, () => {
4654
+ restoreDialog();
4655
+ reject(new Error("Login cancelled"));
4656
+ });
4657
+ this.editorContainer.clear();
4658
+ this.editorContainer.addChild(selector);
4659
+ this.ui.setFocus(selector);
4660
+ this.ui.requestRender();
4661
+ });
4662
+ }
4663
+ async showAuthPrompt(dialog, prompt) {
4664
+ let response;
4665
+ if (prompt.type === "select") {
4666
+ response = this.showAuthSelect(dialog, prompt);
4667
+ }
4668
+ else if (prompt.type === "manual_code") {
4669
+ response = dialog.showManualInput(prompt.message);
4670
+ }
4671
+ else {
4672
+ response = dialog.showPrompt(prompt.message, prompt.placeholder);
4673
+ }
4674
+ if (!prompt.signal)
4675
+ return response;
4676
+ if (prompt.signal.aborted)
4677
+ throw new Error("Login cancelled");
4678
+ const signal = prompt.signal;
4679
+ let onAbort;
4680
+ const aborted = new Promise((_resolve, reject) => {
4681
+ onAbort = () => reject(new Error("Login cancelled"));
4682
+ signal.addEventListener("abort", onAbort, { once: true });
4683
+ });
4684
+ try {
4685
+ return await Promise.race([response, aborted]);
4686
+ }
4687
+ finally {
4688
+ if (onAbort)
4689
+ signal.removeEventListener("abort", onAbort);
4690
+ }
4691
+ }
4692
+ notifyAuthDialog(dialog, event) {
4693
+ if (event.type === "auth_url") {
4694
+ dialog.showAuth(event.url, event.instructions);
4695
+ }
4696
+ else if (event.type === "device_code") {
4697
+ dialog.showDeviceCode(event);
4698
+ dialog.showWaiting("Waiting for authentication...");
4699
+ }
4700
+ else if (event.type === "info") {
4701
+ dialog.showInfo(event.message, event.links);
4702
+ }
4703
+ else {
4704
+ dialog.showProgress(event.message);
4705
+ }
4706
+ }
4707
+ async loginProvider(dialog, providerId, method) {
4708
+ await this.session.modelRuntime.login(providerId, method, {
4709
+ signal: dialog.signal,
4710
+ prompt: (prompt) => this.showAuthPrompt(dialog, prompt),
4711
+ notify: (event) => this.notifyAuthDialog(dialog, event),
4712
+ });
4713
+ }
4714
+ async showLoginDialog(providerId, providerName) {
4715
+ const previousModel = this.session.model;
4716
+ const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => { }, providerName);
4717
+ this.editorContainer.clear();
4718
+ this.editorContainer.addChild(dialog);
4719
+ this.ui.setFocus(dialog);
4720
+ this.ui.requestRender();
4721
+ const restoreEditor = () => {
4722
+ this.editorContainer.clear();
4723
+ this.editorContainer.addChild(this.editor);
4724
+ this.ui.setFocus(this.editor);
4725
+ this.ui.requestRender();
4726
+ };
4727
+ try {
4728
+ await this.loginProvider(dialog, providerId, "oauth");
4729
+ restoreEditor();
4730
+ await this.completeProviderAuthentication(providerId, providerName, "oauth", previousModel);
4731
+ }
4732
+ catch (error) {
4733
+ restoreEditor();
4734
+ const errorMsg = error instanceof Error ? error.message : String(error);
4735
+ if (error instanceof CredentialSynchronizationError) {
4736
+ this.showError(`Logged in to ${providerName}, but local model state could not be synchronized: ${errorMsg}`);
4737
+ }
4738
+ else if (errorMsg !== "Login cancelled") {
4739
+ this.showError(`Failed to login to ${providerName}: ${errorMsg}`);
4740
+ }
4741
+ }
4742
+ }
4743
+ // =========================================================================
4744
+ // Command handlers
4745
+ // =========================================================================
4746
+ async handleReloadCommand() {
4747
+ if (this.session.isStreaming) {
4748
+ this.showWarning("Wait for the current response to finish before reloading.");
4749
+ return;
4750
+ }
4751
+ if (this.session.isCompacting) {
4752
+ this.showWarning("Wait for compaction to finish before reloading.");
4753
+ return;
4754
+ }
4755
+ this.resetExtensionUI();
4756
+ const reloadBox = new Container();
4757
+ const borderColor = (s) => theme.fg("border", s);
4758
+ reloadBox.addChild(new DynamicBorder(borderColor));
4759
+ reloadBox.addChild(new Spacer(1));
4760
+ reloadBox.addChild(new Text(theme.fg("muted", "Reloading keybindings, extensions, skills, prompts, themes, and context files..."), 1, 0));
4761
+ reloadBox.addChild(new Spacer(1));
4762
+ reloadBox.addChild(new DynamicBorder(borderColor));
4763
+ const previousEditor = this.editor;
4764
+ this.editorContainer.clear();
4765
+ this.editorContainer.addChild(reloadBox);
4766
+ this.ui.setFocus(reloadBox);
4767
+ this.ui.requestRender(true);
4768
+ await new Promise((resolve) => process.nextTick(resolve));
4769
+ const dismissReloadBox = (editor) => {
4770
+ this.editorContainer.clear();
4771
+ this.editorContainer.addChild(editor);
4772
+ this.ui.setFocus(editor);
4773
+ this.ui.requestRender();
4774
+ };
4775
+ let chatRestoredBeforeSessionStart = false;
4776
+ let reloadBoxDismissed = false;
4777
+ const restoreChatBeforeSessionStart = () => {
4778
+ if (chatRestoredBeforeSessionStart) {
4779
+ return;
4780
+ }
4781
+ this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
4782
+ this.outputPad = this.settingsManager.getOutputPad();
4783
+ this.rebuildChatFromMessages();
4784
+ chatRestoredBeforeSessionStart = true;
4785
+ };
4786
+ try {
4787
+ await this.session.reload({ beforeSessionStart: restoreChatBeforeSessionStart });
4788
+ restoreChatBeforeSessionStart();
4789
+ this.keybindings.reload();
4790
+ const activeHeader = this.customHeader ?? this.builtInHeader;
4791
+ if (isExpandable(activeHeader)) {
4792
+ activeHeader.setExpanded(this.toolOutputExpanded);
4793
+ }
4794
+ setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
4795
+ await this.themeController.applyFromSettings();
4796
+ this.applyRuntimeSettings();
4797
+ this.setupAutocompleteProvider();
4798
+ const runner = this.session.extensionRunner;
4799
+ this.setupExtensionShortcuts(runner);
4800
+ this.showLoadedResources({
4801
+ force: false,
4802
+ showDiagnosticsWhenQuiet: true,
4803
+ });
4804
+ const savedImplicitProjectTrust = this.maybeSaveImplicitProjectTrustAfterReload();
4805
+ const modelsJsonError = this.session.modelRuntime.getError();
4806
+ if (modelsJsonError) {
4807
+ this.showError(`models.json error: ${modelsJsonError}`);
4808
+ }
4809
+ this.showStatus(savedImplicitProjectTrust
4810
+ ? "Reloaded keybindings, extensions, skills, prompts, themes, and context files; saved project trust"
4811
+ : "Reloaded keybindings, extensions, skills, prompts, themes, and context files");
4812
+ dismissReloadBox(this.editor);
4813
+ reloadBoxDismissed = true;
4814
+ }
4815
+ catch (error) {
4816
+ if (!reloadBoxDismissed) {
4817
+ dismissReloadBox(previousEditor);
4818
+ }
4819
+ this.showError(`Reload failed: ${error instanceof Error ? error.message : String(error)}`);
4820
+ }
4821
+ }
4822
+ async handleExportCommand(text) {
4823
+ const outputPath = this.getPathCommandArgument(text, "/export");
4824
+ try {
4825
+ if (outputPath?.endsWith(".jsonl")) {
4826
+ const filePath = this.session.exportToJsonl(outputPath);
4827
+ this.showStatus(`Session exported to: ${filePath}`);
4828
+ }
4829
+ else {
4830
+ const filePath = await this.session.exportToHtml(outputPath);
4831
+ this.showStatus(`Session exported to: ${filePath}`);
4832
+ }
4833
+ }
4834
+ catch (error) {
4835
+ this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);
4836
+ }
4837
+ }
4838
+ getPathCommandArgument(text, command) {
4839
+ if (text === command) {
4840
+ return undefined;
4841
+ }
4842
+ if (!text.startsWith(`${command} `)) {
4843
+ return undefined;
4844
+ }
4845
+ const argsString = text.slice(command.length + 1).trimStart();
4846
+ if (!argsString) {
4847
+ return undefined;
4848
+ }
4849
+ const firstChar = argsString[0];
4850
+ if (firstChar === '"' || firstChar === "'") {
4851
+ const closingQuoteIndex = argsString.indexOf(firstChar, 1);
4852
+ if (closingQuoteIndex < 0) {
4853
+ return undefined;
4854
+ }
4855
+ return argsString.slice(1, closingQuoteIndex);
4856
+ }
4857
+ const firstWhitespaceIndex = argsString.search(/\s/);
4858
+ if (firstWhitespaceIndex < 0) {
4859
+ return argsString;
4860
+ }
4861
+ return argsString.slice(0, firstWhitespaceIndex);
4862
+ }
4863
+ async handleImportCommand(text) {
4864
+ const inputPath = this.getPathCommandArgument(text, "/import");
4865
+ if (!inputPath) {
4866
+ this.showError("Usage: /import <path.jsonl>");
4867
+ return;
4868
+ }
4869
+ const confirmed = await this.showExtensionConfirm("Import session", `Replace current session with ${inputPath}?`);
4870
+ if (!confirmed) {
4871
+ this.showStatus("Import cancelled");
4872
+ return;
4873
+ }
4874
+ try {
4875
+ this.clearStatusIndicator();
4876
+ const result = await this.runtimeHost.importFromJsonl(inputPath);
4877
+ if (result.cancelled) {
4878
+ this.showStatus("Import cancelled");
4879
+ return;
4880
+ }
4881
+ this.showStatus(`Session imported from: ${inputPath}`);
4882
+ }
4883
+ catch (error) {
4884
+ if (error instanceof MissingSessionCwdError) {
4885
+ const selectedCwd = await this.promptForMissingSessionCwd(error);
4886
+ if (!selectedCwd) {
4887
+ this.showStatus("Import cancelled");
4888
+ return;
4889
+ }
4890
+ const result = await this.runtimeHost.importFromJsonl(inputPath, selectedCwd);
4891
+ if (result.cancelled) {
4892
+ this.showStatus("Import cancelled");
4893
+ return;
4894
+ }
4895
+ this.showStatus(`Session imported from: ${inputPath}`);
4896
+ return;
4897
+ }
4898
+ if (error instanceof SessionImportFileNotFoundError) {
4899
+ this.showError(`Failed to import session: ${error.message}`);
4900
+ return;
4901
+ }
4902
+ await this.handleFatalRuntimeError("Failed to import session", error);
4903
+ }
4904
+ }
4905
+ async handleShareCommand() {
4906
+ // Check if gh is available and logged in
4907
+ try {
4908
+ const authResult = spawnSync("gh", ["auth", "status"], { encoding: "utf-8" });
4909
+ if (authResult.status !== 0) {
4910
+ this.showError("GitHub CLI is not logged in. Run 'gh auth login' first.");
4911
+ return;
4912
+ }
4913
+ }
4914
+ catch {
4915
+ this.showError("GitHub CLI (gh) is not installed. Install it from https://cli.github.com/");
4916
+ return;
4917
+ }
4918
+ // Export to a temp file
4919
+ const tmpFile = path.join(os.tmpdir(), "session.html");
4920
+ try {
4921
+ await this.session.exportToHtml(tmpFile);
4922
+ }
4923
+ catch (error) {
4924
+ this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);
4925
+ return;
4926
+ }
4927
+ // Show cancellable loader, replacing the editor
4928
+ const loader = new BorderedLoader(this.ui, theme, "Creating gist...");
4929
+ this.editorContainer.clear();
4930
+ this.editorContainer.addChild(loader);
4931
+ this.ui.setFocus(loader);
4932
+ this.ui.requestRender();
4933
+ const restoreEditor = () => {
4934
+ loader.dispose();
4935
+ this.editorContainer.clear();
4936
+ this.editorContainer.addChild(this.editor);
4937
+ this.ui.setFocus(this.editor);
4938
+ try {
4939
+ fs.unlinkSync(tmpFile);
4940
+ }
4941
+ catch {
4942
+ // Ignore cleanup errors
4943
+ }
4944
+ };
4945
+ // Create a secret gist asynchronously
4946
+ let proc = null;
4947
+ loader.onAbort = () => {
4948
+ proc?.kill();
4949
+ restoreEditor();
4950
+ this.showStatus("Share cancelled");
4951
+ };
4952
+ try {
4953
+ const result = await new Promise((resolve) => {
4954
+ proc = spawn("gh", ["gist", "create", "--public=false", tmpFile]);
4955
+ let stdout = "";
4956
+ let stderr = "";
4957
+ proc.stdout?.on("data", (data) => {
4958
+ stdout += data.toString();
4959
+ });
4960
+ proc.stderr?.on("data", (data) => {
4961
+ stderr += data.toString();
4962
+ });
4963
+ proc.on("close", (code) => resolve({ stdout, stderr, code }));
4964
+ });
4965
+ if (loader.signal.aborted)
4966
+ return;
4967
+ restoreEditor();
4968
+ if (result.code !== 0) {
4969
+ const errorMsg = result.stderr?.trim() || "Unknown error";
4970
+ this.showError(`Failed to create gist: ${errorMsg}`);
4971
+ return;
4972
+ }
4973
+ // Extract gist ID from the URL returned by gh
4974
+ // gh returns something like: https://gist.github.com/username/GIST_ID
4975
+ const gistUrl = result.stdout?.trim();
4976
+ const gistId = gistUrl?.split("/").pop();
4977
+ if (!gistId) {
4978
+ this.showError("Failed to parse gist ID from gh output");
4979
+ return;
4980
+ }
4981
+ // Create the preview URL
4982
+ const previewUrl = getShareViewerUrl(gistId);
4983
+ this.showStatus(`Share URL: ${previewUrl}\nGist: ${gistUrl}`);
4984
+ }
4985
+ catch (error) {
4986
+ if (!loader.signal.aborted) {
4987
+ restoreEditor();
4988
+ this.showError(`Failed to create gist: ${error instanceof Error ? error.message : "Unknown error"}`);
4989
+ }
4990
+ }
4991
+ }
4992
+ async handleCopyCommand(options = {}) {
4993
+ const text = this.session.getLastAssistantText();
4994
+ if (!text) {
4995
+ this.showError("No agent messages to copy yet.");
4996
+ return;
4997
+ }
4998
+ try {
4999
+ await copyToClipboard(text);
5000
+ if (options.flashConfirmation && this.ui instanceof TuiAltScreen) {
5001
+ this.ui.flash("Copied!");
5002
+ }
5003
+ else {
5004
+ this.showStatus("Copied last agent message to clipboard");
5005
+ }
5006
+ }
5007
+ catch (error) {
5008
+ this.showError(error instanceof Error ? error.message : String(error));
5009
+ }
5010
+ }
5011
+ handleNameCommand(text) {
5012
+ const name = text.replace(/^\/name\s*/, "").trim();
5013
+ if (!name) {
5014
+ const currentName = this.sessionManager.getSessionName();
5015
+ if (currentName) {
5016
+ this.chatContainer.addChild(new Spacer(1));
5017
+ this.chatContainer.addChild(new Text(theme.fg("dim", `Session name: ${currentName}`), 1, 0));
5018
+ }
5019
+ else {
5020
+ this.showWarning("Usage: /name <name>");
5021
+ }
5022
+ this.ui.requestRender();
5023
+ return;
5024
+ }
5025
+ this.session.setSessionName(name);
5026
+ const sessionName = this.sessionManager.getSessionName();
5027
+ if (sessionName !== name) {
5028
+ this.showWarning(`Session name was normalized from ${JSON.stringify(name)} to ${JSON.stringify(sessionName)}`);
5029
+ }
5030
+ this.chatContainer.addChild(new Spacer(1));
5031
+ this.chatContainer.addChild(new Text(theme.fg("dim", `Session name set: ${sessionName ?? name}`), 1, 0));
5032
+ this.ui.requestRender();
5033
+ }
5034
+ handleSessionCommand() {
5035
+ const stats = this.session.getSessionStats();
5036
+ const sessionName = this.sessionManager.getSessionName();
5037
+ const entries = this.sessionManager.getEntries();
5038
+ const cacheWaste = computeCacheWaste(entries, this.session.modelRuntime);
5039
+ // Cost/token totals per provider/model actually used (e.g. OpenRouter `auto`
5040
+ // resolves to a concrete responseModel). Usage without model attribution is
5041
+ // grouped separately so the breakdown reconciles with the session total.
5042
+ const usageBreakdown = getUsageCostBreakdown(entries);
5043
+ let info = `${theme.bold("Session Info")}\n\n`;
5044
+ if (sessionName) {
5045
+ info += `${theme.fg("dim", "Name:")} ${sessionName}\n`;
5046
+ }
5047
+ info += `${theme.fg("dim", "File:")} ${stats.sessionFile ?? "In-memory"}\n`;
5048
+ info += `${theme.fg("dim", "ID:")} ${stats.sessionId}\n\n`;
5049
+ info += `${theme.bold("Messages")}\n`;
5050
+ info += `${theme.fg("dim", "Total:")} ${stats.totalMessages}\n`;
5051
+ info += `${theme.fg("dim", "User:")} ${stats.userMessages}\n`;
5052
+ info += `${theme.fg("dim", "Assistant:")} ${stats.assistantMessages}\n`;
5053
+ info += `${theme.fg("dim", "Tools:")} ${stats.toolCalls} calls, ${stats.toolResults} results\n\n`;
5054
+ info += `${theme.bold("Tokens")}\n`;
5055
+ // "Input" is the full prompt volume. With cache activity, split it into
5056
+ // cached (served from cache) vs uncached (everything else) - the only
5057
+ // provider-independent split. Cache writes, where reported, are a detail
5058
+ // of the uncached portion.
5059
+ const { input, cacheRead, cacheWrite } = stats.tokens;
5060
+ const promptTokens = input + cacheRead + cacheWrite;
5061
+ info += `${theme.fg("dim", "Input:")} ${promptTokens.toLocaleString()}\n`;
5062
+ if (promptTokens > 0 && (cacheRead > 0 || cacheWrite > 0)) {
5063
+ const hitRate = theme.fg("dim", `(${((cacheRead / promptTokens) * 100).toFixed(1)}%)`);
5064
+ info += ` ${theme.fg("dim", "Cached:")} ${cacheRead.toLocaleString()} ${hitRate}\n`;
5065
+ const written = cacheWrite > 0 ? ` ${theme.fg("dim", `(${cacheWrite.toLocaleString()} written to cache)`)}` : "";
5066
+ info += ` ${theme.fg("dim", "Uncached:")} ${(input + cacheWrite).toLocaleString()}${written}\n`;
5067
+ }
5068
+ info += `${theme.fg("dim", "Output:")} ${stats.tokens.output.toLocaleString()}\n`;
5069
+ info += `${theme.fg("dim", "Total:")} ${stats.tokens.total.toLocaleString()}\n`;
5070
+ if (stats.cost > 0 || cacheWaste.missedTokens > 0) {
5071
+ info += `\n${theme.bold("Cost")}\n`;
5072
+ info += `${theme.fg("dim", "Total:")} $${stats.cost.toFixed(3)}`;
5073
+ if (usageBreakdown.length > 1) {
5074
+ for (const entry of usageBreakdown) {
5075
+ info += `\n ${theme.fg("dim", `${entry.key}:`)} $${entry.cost.toFixed(3)} ${theme.fg("dim", `(${formatTokens(entry.tokens)} tokens)`)}`;
5076
+ }
5077
+ }
5078
+ if (cacheWaste.missedTokens > 0) {
5079
+ const missLabel = cacheWaste.missCount === 1 ? "1 miss" : `${cacheWaste.missCount} misses`;
5080
+ const detail = `${cacheWaste.missedTokens.toLocaleString()} tokens, ${missLabel}`;
5081
+ info +=
5082
+ cacheWaste.missedCost >= 0.0001
5083
+ ? `\n${theme.fg("dim", "Cache Re-billed:")} $${cacheWaste.missedCost.toFixed(3)} ${theme.fg("dim", `(${detail})`)}`
5084
+ : `\n${theme.fg("dim", "Cache Re-billed:")} ${detail}`;
5085
+ }
5086
+ }
5087
+ this.chatContainer.addChild(new Spacer(1));
5088
+ this.chatContainer.addChild(new Text(info, 1, 0));
5089
+ this.ui.requestRender();
5090
+ }
5091
+ handleChangelogCommand() {
5092
+ const changelogPath = getChangelogPath();
5093
+ const allEntries = parseChangelog(changelogPath);
5094
+ const changelogMarkdown = allEntries.length > 0
5095
+ ? allEntries
5096
+ .reverse()
5097
+ .map((e) => normalizeChangelogLinks(e.content, e))
5098
+ .join("\n\n")
5099
+ : "No changelog entries found.";
5100
+ this.chatContainer.addChild(new Spacer(1));
5101
+ this.chatContainer.addChild(new DynamicBorder());
5102
+ this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0));
5103
+ this.chatContainer.addChild(new Spacer(1));
5104
+ this.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, this.getMarkdownThemeWithSettings()));
5105
+ this.chatContainer.addChild(new DynamicBorder());
5106
+ this.ui.requestRender();
5107
+ }
5108
+ /**
5109
+ * Get capitalized display string for an app keybinding action.
5110
+ */
5111
+ getAppKeyDisplay(action) {
5112
+ return keyDisplayText(action);
5113
+ }
5114
+ /**
5115
+ * Get capitalized display string for an editor keybinding action.
5116
+ */
5117
+ getEditorKeyDisplay(action) {
5118
+ return keyDisplayText(action);
5119
+ }
5120
+ handleHotkeysCommand() {
5121
+ // Navigation keybindings
5122
+ const cursorUp = this.getEditorKeyDisplay("tui.editor.cursorUp");
5123
+ const cursorDown = this.getEditorKeyDisplay("tui.editor.cursorDown");
5124
+ const cursorLeft = this.getEditorKeyDisplay("tui.editor.cursorLeft");
5125
+ const cursorRight = this.getEditorKeyDisplay("tui.editor.cursorRight");
5126
+ const cursorWordLeft = this.getEditorKeyDisplay("tui.editor.cursorWordLeft");
5127
+ const cursorWordRight = this.getEditorKeyDisplay("tui.editor.cursorWordRight");
5128
+ const cursorLineStart = this.getEditorKeyDisplay("tui.editor.cursorLineStart");
5129
+ const cursorLineEnd = this.getEditorKeyDisplay("tui.editor.cursorLineEnd");
5130
+ const jumpForward = this.getEditorKeyDisplay("tui.editor.jumpForward");
5131
+ const jumpBackward = this.getEditorKeyDisplay("tui.editor.jumpBackward");
5132
+ const pageUp = this.getEditorKeyDisplay("tui.editor.pageUp");
5133
+ const pageDown = this.getEditorKeyDisplay("tui.editor.pageDown");
5134
+ // Editing keybindings
5135
+ const submit = this.getEditorKeyDisplay("tui.input.submit");
5136
+ const newLine = this.getEditorKeyDisplay("tui.input.newLine");
5137
+ const deleteWordBackward = this.getEditorKeyDisplay("tui.editor.deleteWordBackward");
5138
+ const deleteWordForward = this.getEditorKeyDisplay("tui.editor.deleteWordForward");
5139
+ const deleteToLineStart = this.getEditorKeyDisplay("tui.editor.deleteToLineStart");
5140
+ const deleteToLineEnd = this.getEditorKeyDisplay("tui.editor.deleteToLineEnd");
5141
+ const yank = this.getEditorKeyDisplay("tui.editor.yank");
5142
+ const yankPop = this.getEditorKeyDisplay("tui.editor.yankPop");
5143
+ const undo = this.getEditorKeyDisplay("tui.editor.undo");
5144
+ const tab = this.getEditorKeyDisplay("tui.input.tab");
5145
+ // App keybindings
5146
+ const interrupt = this.getAppKeyDisplay("app.interrupt");
5147
+ const clear = this.getAppKeyDisplay("app.clear");
5148
+ const exit = this.getAppKeyDisplay("app.exit");
5149
+ const suspend = this.getAppKeyDisplay("app.suspend");
5150
+ const cycleThinkingLevel = this.getAppKeyDisplay("app.thinking.cycle");
5151
+ const cycleModelForward = this.getAppKeyDisplay("app.model.cycleForward");
5152
+ const selectModel = this.getAppKeyDisplay("app.model.select");
5153
+ const expandTools = this.getAppKeyDisplay("app.tools.expand");
5154
+ const toggleThinking = this.getAppKeyDisplay("app.thinking.toggle");
5155
+ const externalEditor = this.getAppKeyDisplay("app.editor.external");
5156
+ const cycleModelBackward = this.getAppKeyDisplay("app.model.cycleBackward");
5157
+ const copyMessage = this.getAppKeyDisplay("app.message.copy");
5158
+ const followUp = this.getAppKeyDisplay("app.message.followUp");
5159
+ const dequeue = this.getAppKeyDisplay("app.message.dequeue");
5160
+ const pasteImage = this.getAppKeyDisplay("app.clipboard.pasteImage");
5161
+ let hotkeys = `
5162
+ **Navigation**
5163
+ | Key | Action |
5164
+ |-----|--------|
5165
+ | \`${cursorUp}\` / \`${cursorDown}\` / \`${cursorLeft}\` / \`${cursorRight}\` | Move cursor / browse history |
5166
+ | \`${cursorWordLeft}\` / \`${cursorWordRight}\` | Move by word |
5167
+ | \`${cursorLineStart}\` | Start of line |
5168
+ | \`${cursorLineEnd}\` | End of line |
5169
+ | \`${jumpForward}\` | Jump forward to character |
5170
+ | \`${jumpBackward}\` | Jump backward to character |
5171
+ | \`${pageUp}\` / \`${pageDown}\` | Scroll by page |
5172
+
5173
+ **Editing**
5174
+ | Key | Action |
5175
+ |-----|--------|
5176
+ | \`${submit}\` | Send message |
5177
+ | \`${newLine}\` | New line${process.platform === "win32" ? " (Ctrl+Enter on Windows Terminal)" : ""} |
5178
+ | \`${deleteWordBackward}\` | Delete word backwards |
5179
+ | \`${deleteWordForward}\` | Delete word forwards |
5180
+ | \`${deleteToLineStart}\` | Delete to start of line |
5181
+ | \`${deleteToLineEnd}\` | Delete to end of line |
5182
+ | \`${yank}\` | Paste the most-recently-deleted text |
5183
+ | \`${yankPop}\` | Cycle through the deleted text after pasting |
5184
+ | \`${undo}\` | Undo |
5185
+
5186
+ **Other**
5187
+ | Key | Action |
5188
+ |-----|--------|
5189
+ | \`${tab}\` | Path completion / accept autocomplete |
5190
+ | \`${interrupt}\` | Cancel autocomplete / abort streaming |
5191
+ | \`${clear}\` | Clear editor (first) / exit (second) |
5192
+ | \`${exit}\` | Exit (when editor is empty) |
5193
+ | \`${suspend}\` | Suspend to background |
5194
+ | \`${cycleThinkingLevel}\` | Cycle thinking level |
5195
+ | \`${cycleModelForward}\` / \`${cycleModelBackward}\` | Cycle models |
5196
+ | \`${selectModel}\` | Open model selector |
5197
+ | \`${expandTools}\` | Toggle tool output expansion |
5198
+ | \`${toggleThinking}\` | Toggle thinking block visibility |
5199
+ | \`${externalEditor}\` | Edit message in external editor |
5200
+ | \`${copyMessage}\` | Copy last assistant message |
5201
+ | \`${followUp}\` | Queue follow-up message |
5202
+ | \`${dequeue}\` | Restore queued messages |
5203
+ | \`${pasteImage}\` | Paste image or text from clipboard |
5204
+ | \`/\` | Slash commands |
5205
+ | \`!\` | Run bash command |
5206
+ | \`!!\` | Run bash command (excluded from context) |
5207
+ `;
5208
+ // Add extension-registered shortcuts
5209
+ const extensionRunner = this.session.extensionRunner;
5210
+ const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());
5211
+ if (shortcuts.size > 0) {
5212
+ hotkeys += `
5213
+ **Extensions**
5214
+ | Key | Action |
5215
+ |-----|--------|
5216
+ `;
5217
+ for (const [key, shortcut] of shortcuts) {
5218
+ const description = shortcut.description ?? shortcut.extensionPath;
5219
+ const keyDisplay = formatKeyText(key, { capitalize: true });
5220
+ hotkeys += `| \`${keyDisplay}\` | ${description} |\n`;
5221
+ }
5222
+ }
5223
+ this.chatContainer.addChild(new Spacer(1));
5224
+ this.chatContainer.addChild(new DynamicBorder());
5225
+ this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "Keyboard Shortcuts")), 1, 0));
5226
+ this.chatContainer.addChild(new Spacer(1));
5227
+ this.chatContainer.addChild(new Markdown(hotkeys.trim(), 1, 1, this.getMarkdownThemeWithSettings()));
5228
+ this.chatContainer.addChild(new DynamicBorder());
5229
+ this.ui.requestRender();
5230
+ }
5231
+ async handleClearCommand() {
5232
+ this.clearStatusIndicator();
5233
+ try {
5234
+ const result = await this.runtimeHost.newSession();
5235
+ if (result.cancelled) {
5236
+ return;
5237
+ }
5238
+ this.chatContainer.addChild(new Spacer(1));
5239
+ this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ New session started")}`, 1, 1));
5240
+ this.ui.requestRender();
5241
+ }
5242
+ catch (error) {
5243
+ await this.handleFatalRuntimeError("Failed to create session", error);
5244
+ }
5245
+ }
5246
+ handleDebugCommand() {
5247
+ const width = this.ui.terminal.columns;
5248
+ const height = this.ui.terminal.rows;
5249
+ const allLines = this.ui.render(width);
5250
+ const debugLogPath = getDebugLogPath();
5251
+ const debugData = [
5252
+ `Debug output at ${new Date().toISOString()}`,
5253
+ `Terminal: ${width}x${height}`,
5254
+ `Total lines: ${allLines.length}`,
5255
+ "",
5256
+ "=== All rendered lines with visible widths ===",
5257
+ ...allLines.map((line, idx) => {
5258
+ const vw = visibleWidth(line);
5259
+ const escaped = JSON.stringify(line);
5260
+ return `[${idx}] (w=${vw}) ${escaped}`;
5261
+ }),
5262
+ "",
5263
+ "=== Agent messages (JSONL) ===",
5264
+ ...this.session.messages.map((msg) => JSON.stringify(msg)),
5265
+ "",
5266
+ ].join("\n");
5267
+ fs.mkdirSync(path.dirname(debugLogPath), { recursive: true });
5268
+ fs.writeFileSync(debugLogPath, debugData);
5269
+ this.chatContainer.addChild(new Spacer(1));
5270
+ this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ Debug log written")}\n${theme.fg("muted", debugLogPath)}`, 1, 1));
5271
+ this.ui.requestRender();
5272
+ }
5273
+ handleArminSaysHi() {
5274
+ this.chatContainer.addChild(new Spacer(1));
5275
+ this.chatContainer.addChild(new ArminComponent(this.ui));
5276
+ this.ui.requestRender();
5277
+ }
5278
+ handleDementedDelves() {
5279
+ this.chatContainer.addChild(new Spacer(1));
5280
+ this.chatContainer.addChild(new EarendilAnnouncementComponent());
5281
+ this.ui.requestRender();
5282
+ }
5283
+ handleDaxnuts() {
5284
+ this.chatContainer.addChild(new Spacer(1));
5285
+ this.chatContainer.addChild(new DaxnutsComponent(this.ui));
5286
+ this.ui.requestRender();
5287
+ }
5288
+ checkDaxnutsEasterEgg(model) {
5289
+ if (model.provider === "opencode" && model.id.toLowerCase().includes("kimi-k2.5")) {
5290
+ this.handleDaxnuts();
5291
+ }
5292
+ }
5293
+ async handleBashCommand(command, excludeFromContext = false) {
5294
+ const extensionRunner = this.session.extensionRunner;
5295
+ // Emit user_bash event to let extensions intercept
5296
+ const eventResult = await extensionRunner.emitUserBash({
5297
+ type: "user_bash",
5298
+ command,
5299
+ excludeFromContext,
5300
+ cwd: this.sessionManager.getCwd(),
5301
+ });
5302
+ // If extension returned a full result, use it directly
5303
+ if (eventResult?.result) {
5304
+ const result = eventResult.result;
5305
+ // Create UI component for display
5306
+ this.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);
5307
+ if (this.session.isStreaming) {
5308
+ this.pendingMessagesContainer.addChild(this.bashComponent);
5309
+ this.pendingBashComponents.push(this.bashComponent);
5310
+ }
5311
+ else {
5312
+ this.chatContainer.addChild(this.bashComponent);
5313
+ }
5314
+ // Show output and complete
5315
+ if (result.output) {
5316
+ this.bashComponent.appendOutput(result.output);
5317
+ }
5318
+ this.bashComponent.setComplete(result.exitCode, result.cancelled, result.truncated ? { truncated: true, content: result.output } : undefined, result.fullOutputPath);
5319
+ // Record the result in session
5320
+ this.session.recordBashResult(command, result, { excludeFromContext });
5321
+ this.bashComponent = undefined;
5322
+ this.ui.requestRender();
5323
+ return;
5324
+ }
5325
+ // Normal execution path (possibly with custom operations)
5326
+ const isDeferred = this.session.isStreaming;
5327
+ this.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);
5328
+ if (isDeferred) {
5329
+ // Show in pending area when agent is streaming
5330
+ this.pendingMessagesContainer.addChild(this.bashComponent);
5331
+ this.pendingBashComponents.push(this.bashComponent);
5332
+ }
5333
+ else {
5334
+ // Show in chat immediately when agent is idle
5335
+ this.chatContainer.addChild(this.bashComponent);
5336
+ }
5337
+ this.ui.requestRender();
5338
+ try {
5339
+ const result = await this.session.executeBash(command, (chunk) => {
5340
+ if (this.bashComponent) {
5341
+ this.bashComponent.appendOutput(chunk);
5342
+ this.ui.requestRender();
5343
+ }
5344
+ }, { excludeFromContext, operations: eventResult?.operations });
5345
+ if (this.bashComponent) {
5346
+ this.bashComponent.setComplete(result.exitCode, result.cancelled, result.truncated ? { truncated: true, content: result.output } : undefined, result.fullOutputPath);
5347
+ }
5348
+ }
5349
+ catch (error) {
5350
+ if (this.bashComponent) {
5351
+ this.bashComponent.setComplete(undefined, false);
5352
+ }
5353
+ this.showError(`Bash command failed: ${error instanceof Error ? error.message : "Unknown error"}`);
5354
+ }
5355
+ this.bashComponent = undefined;
5356
+ this.ui.requestRender();
5357
+ }
5358
+ async handleCompactCommand(customInstructions) {
5359
+ this.clearStatusIndicator();
5360
+ try {
5361
+ await this.session.compact(customInstructions);
5362
+ }
5363
+ catch {
5364
+ // Ignore, will be emitted as an event
5365
+ }
5366
+ }
5367
+ stop() {
5368
+ this.disposeActiveSelector();
5369
+ if (this.settingsManager.getShowTerminalProgress()) {
5370
+ this.ui.terminal.setProgress(false);
5371
+ }
5372
+ this.clearStatusIndicator();
5373
+ this.themeController.disableAutoSync();
5374
+ this.clearExtensionTerminalInputListeners();
5375
+ this.footer.dispose();
5376
+ this.footerDataProvider.dispose();
5377
+ if (this.unsubscribe) {
5378
+ this.unsubscribe();
5379
+ }
5380
+ if (this.isInitialized) {
5381
+ this.stopInteractiveTui();
5382
+ this.isInitialized = false;
5383
+ }
5384
+ this.unregisterSignalHandlers();
5385
+ }
5386
+ }
5387
+ //# sourceMappingURL=interactive-mode.js.map