@daniel156161/prism 0.2.78 → 0.2.81

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