@daniel156161/prism 0.2.81 → 0.2.83

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