@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
8,868 lines • 438 kB
JavaScript
/**
* Interactive mode for the coding agent.
* Handles TUI rendering and user interaction, delegating business logic to AgentSession.
*/
import * as fs from "node:fs";
import { resolveSecretInputTimeout } from "../../core/extensions/secret-input.js";
import * as os from "node:os";
import * as path from "node:path";
import { contentText, legacyProviderIdRejection, modelsAreEqual, } from "@earendil-works/pi-ai";
import * as TuiLayouts from "@earendil-works/pi-tui";
import { CombinedAutocompleteProvider, Container, decodeKittyPrintable, encodeProgramStatus, fuzzyFilter, getCapabilities, hyperlink, Markdown, matchesKey, outerKittyGraphicsMode, SelectList, Spacer, sanitizeTerminalLabel, setCapabilityOverrides, setKeybindings, Text, TruncatedText, TuiAltScreen, TuiMainScreen, visibleWidth, } from "@earendil-works/pi-tui";
import chalk from "chalk";
import { spawn } from "child_process";
import { APP_COMMAND, APP_NAME, APP_TITLE, BRAND, CONFIG_DIR_NAME, DISPLAY_VERSION, expandTildePath, getAgentDir, getAuthPath, getDebugLogPath, getDocsPath, getShareViewerBase, isShareDisabledByEnvironment, } from "../../config.js";
import { parseSkillBlock, } from "../../core/agent-session.js";
import { SessionImportFileNotFoundError } from "../../core/agent-session-runtime.js";
import { formatNoModelsAvailableMessage } from "../../core/auth-guidance.js";
import { isApiKeyLoginProvider, loginRowStatus } from "../../core/auth-providers.js";
import { describeCredentialReplacement } from "../../core/auth-storage.js";
import { markModeCrashHandler } from "../../core/bootstrap-crash-listeners.js";
import { envValue } from "../../core/brand.js";
import { CACHE_TTL_MS, collectCacheMisses, computeCacheWaste, detectCacheMiss, } from "../../core/cache-stats.js";
import { resolveChangelogSource } from "../../core/changelog-source.js";
import { collectEntriesForBranchSummary } from "../../core/compaction/branch-summarization.js";
import { findExtensionStackMatches } from "../../core/crash-log.js";
import { AssistantEditError, assistantTextEquals } from "../../core/edited-assistant-message.js";
import { subscribeProviderAccountEvents } from "../../core/extensions/builtin/anthropic-subscription/account-events.js";
import { getSessionClaudeAccountPin, resolveClaudeAccountPin, } from "../../core/extensions/builtin/anthropic-subscription/account-command.js";
import { loadAnthropicSubscriptionProviderSettingsFromDisk } from "../../core/extensions/builtin/anthropic-subscription/settings.js";
import { formatAccountFailoverNotice } from "./account-failover-notice.js";
import { askUserAnswerDisplayText, formatUserMessage, showsPartialAnswers, } from "../../core/extensions/builtin/ask-user/format.js";
import { askUserRenderers } from "../../core/extensions/builtin/ask-user/render.js";
import { buildNoticeBox } from "../../core/extensions/notice/index.js";
import { emitUserActivity } from "../../core/extensions/user-activity.js";
import { FooterDataProvider } from "../../core/footer-data-provider.js";
import { checkSessionHolders, describeSessionHolders, SESSION_HOLDER_LOOKUP_FAILED, sessionHolderWarning, stopSessionHolders, takeOverRefusal, } from "../../core/foreign-session-holders.js";
import { appendUncaughtCrashLog, appendUnhandledRejectionLog } from "../../core/hidden-stdout-log.js";
import { buildHighReasoningWarning } from "../../core/high-reasoning-warning.js";
import { configureHttpDispatcher, formatHttpIdleTimeoutMs } from "../../core/http-dispatcher.js";
import { KeybindingsManager } from "../../core/keybindings.js";
import { isManualContinueSubmission } from "../../core/manual-continue.js";
import { attachMcpGrantPresentation } from "../../core/mcp-grant-presentations.js";
import { registerMcpMrtrPresentation } from "../../core/mcp-mrtr-presentations.js";
import { markMcpFormPresented } from "../../core/mcp-form-types.js";
import { registerLocalMcpPresenter } from "./mcp-local-presenter.js";
import { raceTerminalSecretInput } from "./terminal-sealed-secrets.js";
import { createCompactionSummaryMessage, createCustomMessage } from "../../core/messages.js";
import { defaultModelPerProvider, findExactModelReferenceMatch, resolveModelScope, resolveModelScopeFromModels, resolveModelScopeWithDiagnostics, } from "../../core/model-resolver.js";
import { CredentialSynchronizationError } from "../../core/model-runtime.js";
import { formatProviderFailure } from "../../core/provider-failure.js";
import { failureAlreadyDescribed, headNoticeShownElsewhere } from "./provider-error-description.js";
import { describeFallbackExhaustion } from "../../core/retry-fallback/exhaustion.js";
import { usageLimitCause } from "../../core/retry-fallback/usage-limit.js";
import { formatMissingSessionCwdPrompt, MissingSessionCwdError } from "../../core/session-cwd.js";
import { createSessionLogger } from "../../core/session-log.js";
import { SessionManager, sessionEntryToContextMessages } from "../../core/session-manager.js";
import { checkGhAuth, uploadSecretGist } from "../../core/share/share-gh.js";
import { currentShareRedactionContext } from "../../core/share/share-redaction.js";
import { runShare } from "../../core/share/share-session.js";
import { BUILTIN_SLASH_COMMANDS } from "../../core/slash-commands.js";
import { containStaleExtensionError } from "../../core/stale-extension-containment.js";
import { isInstallTelemetryEnabled } from "../../core/telemetry.js";
import { formatThinkingClampWarning } from "../../core/thinking-levels.js";
import { formatTimings, resetTimings, time } from "../../core/timings.js";
import { withBuiltInRenderers } from "../../core/tools/renderers/index.js";
import { hasTrustRequiringProjectResources, ProjectTrustStore } from "../../core/trust-manager.js";
import { UnknownCommandError } from "../../core/unknown-command.js";
import { getUsageCostBreakdown } from "../../core/usage-totals.js";
import { consumeEarlyInspectorVmImportRecoveries, INSPECTOR_VM_IMPORT_WARNING, isRecoverableInspectorVmImportError, } from "../../inspector-policy.js";
import { getNewEntries, normalizeChangelogLinks, parseChangelog } from "../../utils/changelog.js";
import { signalSpawnedChild } from "../../utils/child-signal.js";
import { copyToClipboard, readClipboardFilePaths, readClipboardText } from "../../utils/clipboard.js";
import { readClipboardImage } from "../../utils/clipboard-image.js";
import { parseGitUrl } from "../../utils/git.js";
import { processImage } from "../../utils/image-process.js";
import { getCwdRelativePath } from "../../utils/paths.js";
import { getPiUserAgent } from "../../utils/pi-user-agent.js";
import { killTrackedDetachedChildren } from "../../utils/shell.js";
import { ensureTool } from "../../utils/tools-manager.js";
import { checkForNewPiVersion, getReleaseChangelogUrl } from "../../utils/version-check.js";
import { abortedMessageForRendering, unrunToolCallText } from "./aborted-error-label.js";
import { createChatViewport } from "./chat-viewport.js";
import { transferCompactionQueue, waitForPromptDisposition, } from "./compaction-queue-transfer.js";
import { ArminComponent } from "./components/armin.js";
import { getAskUserAnswerHeaders, parseAskUserAnswerFrame } from "./components/ask-user-answer-chip.js";
import { matchesAskUserAnswerKey } from "./components/ask-user-answer-key.js";
import { ASK_USER_WIDGET_KEY, AskUserAsyncWidget, buildAnsweredResponse, buildCommentResponse, buildTimedOutResponse, unansweredIds, } from "./components/ask-user-async-widget.js";
import { AskUserQuestionComponent } from "./components/ask-user-question.js";
import { formatCountdownLabel } from "./components/ask-user-question-state.js";
import { AssistantMessageComponent } from "./components/assistant-message.js";
import { BashExecutionComponent } from "./components/bash-execution.js";
import { BorderedLoader } from "./components/bordered-loader.js";
import { BranchSummaryMessageComponent } from "./components/branch-summary-message.js";
import { CompactionSummaryMessageComponent } from "./components/compaction-summary-message.js";
import { ContinuityNoticeTracker } from "./components/continuity-notice.js";
import { CustomEditor } from "./components/custom-editor.js";
import { CustomEntryComponent, replacedEntryCardIndex } from "./components/custom-entry.js";
import { CustomMessageComponent } from "./components/custom-message.js";
import { DaxnutsComponent } from "./components/daxnuts.js";
import { DynamicBorder } from "./components/dynamic-border.js";
import { EarendilAnnouncementComponent } from "./components/earendil-announcement.js";
import { ExplorationTranscriptContainer } from "./components/exploration-transcript-container.js";
import { ExtensionEditorComponent } from "./components/extension-editor.js";
import { ExtensionInputComponent } from "./components/extension-input.js";
import { ExtensionSelectorComponent } from "./components/extension-selector.js";
import { FavoriteModelsSelectorComponent } from "./components/favorite-models-selector.js";
import { FooterComponent, formatTokens } from "./components/footer.js";
import { formatKeyText, keyDisplayText, keyHint, keyText, rawKeyHint } from "./components/keybinding-hints.js";
import { LoadedResourceSection } from "./components/loaded-resource-section.js";
import { LoginDialogComponent } from "./components/login-dialog.js";
import { createMermaidMarkdownTransformer } from "./components/mermaid.js";
import { createMessagePathLinkTransformer } from "./components/message-path-links.js";
import { getModelFullId, mergeFavoritePatternsForPersist, } from "./components/model-favorites.js";
import { ModelSelectorComponent } from "./components/model-selector.js";
import { formatAuthSelectorProviderType, OAuthSelectorComponent, } from "./components/oauth-selector.js";
import { DEFAULT_TAIL_BUDGET, DEFAULT_WARM_CHUNK_SIZE, defaultHistoryMarker, } from "./components/progressive-transcript-container.js";
import { builtInMessageRenderer } from "./components/remote-delivery-message.js";
import { ScopedModelsSelectorComponent } from "./components/scoped-models-selector.js";
import { SessionSelectorComponent } from "./components/session-selector.js";
import { SettingsSelectorComponent } from "./components/settings-selector.js";
import { classifyEditorInput, ShortcutOverlay, shouldShowShortcutOverlay } from "./components/shortcut-overlay.js";
import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js";
import { BranchSummaryStatusIndicator, CompactionStatusIndicator, IdleStatus, RetryStatusIndicator, WorkingStatusIndicator, } from "./components/status-indicator.js";
import { ThemedText } from "./components/themed-text.js";
import { ThinkingSelectorComponent } from "./components/thinking-selector.js";
import { ToolExecutionComponent } from "./components/tool-execution.js";
import { TreeSelectorComponent } from "./components/tree-selector.js";
import { TrustSelectorComponent } from "./components/trust-selector.js";
import { UserMessageComponent } from "./components/user-message.js";
import { UserMessageSelectorComponent } from "./components/user-message-selector.js";
import { insertProgrammaticComposerInput, observeComposerActivity } from "./composer-user-activity.js";
import { expandEditorSubmission, expandSubmittedText, transferEditorContent } from "./editor-paste-transfer.js";
import { formatExtensionErrorHeadline, sanitizeTuiErrorMessage } from "./extension-error-format.js";
import { editFileInExternalEditor, editInExternalEditor } from "./external-editor.js";
import { GrokChrome } from "./grok/chrome.js";
import { prepareInteractiveStderrCapture, restoreInteractiveStderr, takeOverInteractiveStderr, } from "./interactive-stderr-guard.js";
import { applyKeybindingsFileEdit, seedKeybindingsFile } from "./keybindings-command.js";
import { LIFECYCLE_STATUS_KEY, LifecycleStatus } from "./lifecycle-status.js";
import { buildResourceScopeGroups, formatResourceScopeGroups, getDisplaySourceInfo, getScopeAutocompleteTag, isPackageSourceInfo, isSystemResource, } from "./loaded-resource-scopes.js";
import { describeLoginFailure } from "./login-outcome.js";
import { refreshModelCatalogs } from "./model-catalog-refresh.js";
import { liveModelChangeNotice, parseModelCommandArgument, replayedModelChangeNotice, } from "./model-change-notice.js";
import { getModelSearchText } from "./model-search.js";
import { PAUSE_STATUS_KEY, pauseFooterText, resumeCommandTarget } from "./pause-footer.js";
import { episodeOwnsFailure, isNetworkProviderError, isRetryableProviderError, isRetryableProviderMessage, ProviderErrorPresentation, } from "./provider-error-presentation.js";
import { providerErrorReason } from "./provider-error-reason.js";
import { replayAssistantTools } from "./replay-assistant-tools.js";
import { interactiveErrorText } from "./required-compaction-wording.js";
import { allScopeSessions, chooseResumePath, currentScopeSessions } from "./resume-rebind.js";
import { isRiskyMainModel, RISKY_MAIN_MODEL_WARNING } from "./risky-main-model-warning.js";
import { maybeShowRuntimeNotice } from "./runtime-notice-presenter.js";
import { TuiSessionControlHost } from "./session-control-host.js";
import { formatSessionFailureInfo } from "./session-failure-info.js";
import { DEFAULT_SMOOTH_FPS, StreamingRevealController } from "./streaming-reveal.js";
import { getAvailableThemes, getAvailableThemesWithPaths, getEditorTheme, getMarkdownTheme, getSelectListTheme, getThemeByName, onThemeChange, SYSTEM_THEME_NAME, setRegisteredThemes, stopThemeWatcher, Theme, theme, } from "./theme/theme.js";
import { InteractiveThemeController } from "./theme/theme-controller.js";
import { buildFavoriteCycleStatusMessage } from "./tips/favorite-messages.js";
import { recordTipShown } from "./tips/history-writer.js";
import { TIP_DEFINITIONS } from "./tips/registry.js";
import { appendStartupHeader } from "./tips/startup-header.js";
import { resolveStartupTips } from "./tips/startup-tips.js";
import { appendTipLine } from "./tips/tip-line.js";
import { resolveWorkingTipLine, WorkingTipCache } from "./tips/working-tip.js";
import { buildTmuxSetupWarning } from "./tmux-setup.js";
import { ToolArgsRevealController } from "./tool-args-reveal.js";
import { readToolProgress } from "./tool-progress.js";
import { ToolResultRevealController } from "./tool-result-reveal.js";
import { createInteractiveTui, createInteractiveTuiReference } from "./tui-renderer.js";
import { reportUnknownCommand, submitsCommandAsText } from "./unknown-command-feedback.js";
import { formatDisplayVersion } from "./version-label.js";
import { blendWorkingStatusShimmerRgbColor, formatActiveToolWorkingLabel, formatToolHookStatusMessageFrame, formatWorkingStatusMessageFrame, largeSessionWorkingStatusInterval, sanitizeWorkingStatusPlainText, } from "./working-status.js";
/** Footer statuses the host owns: an extension UI reset (e.g. /reload) keeps them. */
const HOST_STATUS_KEYS = new Set([LIFECYCLE_STATUS_KEY]);
export { createInteractiveTui, createInteractiveTuiReference } from "./tui-renderer.js";
/** Copy the default editor's action handlers (clear, suspend, model switching, etc.) onto a custom editor. */
function adoptDefaultEditorActions(defaultEditor, editor) {
if (editor === defaultEditor || !("actionHandlers" in editor) || !(editor.actionHandlers instanceof Map))
return;
for (const [action, handler] of defaultEditor.actionHandlers)
editor.actionHandlers.set(action, handler);
}
/**
* Run a submission parked during startup once the real submit path is installed (senpi#5731). The person
* already pressed Enter, so the parked text is submitted unless they edited it since. A free function, like
* `adoptDefaultEditorActions`, so `init()` gains no new `this` dependency.
*/
export function replayStartupSubmission(parked, editor, defaultEditor) {
if (parked === undefined || editor.getText() !== parked.text)
return;
editor.setText("");
void defaultEditor?.onSubmit?.(parked.text, parked.details);
}
function isWorkingStatusEditor(editor) {
return ("embedWorkingStatus" in editor &&
editor.embedWorkingStatus === true &&
"setWorkingStatusIndicator" in editor &&
typeof editor.setWorkingStatusIndicator === "function");
}
/**
* Hand the active status indicator to the editor border. Returns whether it was embedded; when it
* was not, the caller keeps the indicator in the standalone status row. The base editor may be
* absent on renderer-only hosts and the active editor may be an extension editor that never opts
* in, so both are probed instead of assumed.
*/
function embedStatusIndicatorInEditor(defaultEditor, editor, indicator) {
if (defaultEditor && isWorkingStatusEditor(defaultEditor))
defaultEditor.setWorkingStatusIndicator(undefined);
if (!editor || !isWorkingStatusEditor(editor))
return false;
editor.setWorkingStatusIndicator(indicator);
return true;
}
function isBareSkillNamespace(text) {
return text === "/skill" || text === "/skill:";
}
function isExpandable(obj) {
return typeof obj === "object" && obj !== null && "setExpanded" in obj && typeof obj.setExpanded === "function";
}
class ExpandableText extends ThemedText {
constructor(getCollapsedText, getExpandedText, expanded = false, paddingX = 0, paddingY = 0) {
const state = { expanded };
super(() => (state.expanded ? getExpandedText() : getCollapsedText()), paddingX, paddingY);
this.state = state;
}
setExpanded(expanded) {
this.state.expanded = expanded;
this.invalidate();
}
}
export function shouldShowRetryIndicator(delayMs, fallbackApplied) {
return delayMs !== 0 || !fallbackApplied;
}
function getStreamingToolCallPartialJson(content) {
if (typeof content !== "object" || content === null || !("partialJson" in content))
return undefined;
return typeof content.partialJson === "string" ? content.partialJson : undefined;
}
function formatToolHookTerminalTitle(event) {
const hookName = sanitizeWorkingStatusPlainText(event.hookName) || "hook";
const statusMessage = sanitizeWorkingStatusPlainText(event.statusMessage);
return `${APP_TITLE} - ${hookName}: ${statusMessage}`;
}
function isModelChangeNotice(item) {
return "type" in item && item.type === "model_change_notice";
}
function isCustomSessionEntry(item) {
return "type" in item && item.type === "custom";
}
function isCompactionCostNotice(item) {
return "type" in item && item.type === "compaction_cost";
}
const DEAD_TERMINAL_ERROR_CODES = new Set(["EIO", "EPIPE", "ENOTCONN"]);
// Bun's macOS tty shim can report a dead terminal as raw positive errno 5 without a string code.
const EIO_ERRNO = 5;
const DEFAULT_RETRY_STATUS_REFRESH_INTERVAL_MS = 80;
const LARGE_SESSION_RETRY_STATUS_REFRESH_INTERVAL_MS = 60_000;
const DEFAULT_WORKING_STATUS_REFRESH_INTERVAL_MS = 600;
const DEFAULT_WORKING_STATUS_MESSAGE_ANIMATION_INTERVAL_MS = 32;
const LARGE_SESSION_WORKING_STATUS_REFRESH_INTERVAL_MS = 60_000;
const LARGE_SESSION_WORKING_STATUS_MESSAGE_INTERVAL_MS = 1_000;
const FALLBACK_STATUS_KEY = "fallback";
const RGB_FOREGROUND_PATTERN = /\x1b\[38;2;(\d+);(\d+);(\d+)m/;
const DARK_DEFAULT_WORKING_TEXT_RGB = {
r: 229,
g: 229,
b: 231,
};
const LIGHT_DEFAULT_WORKING_TEXT_RGB = {
r: 17,
g: 17,
b: 17,
};
const DARK_DEFAULT_WORKING_BASE_RGB = {
r: 102,
g: 102,
b: 102,
};
const LIGHT_DEFAULT_WORKING_BASE_RGB = {
r: 118,
g: 118,
b: 118,
};
function parseAnsiRgbForeground(ansi) {
const match = RGB_FOREGROUND_PATTERN.exec(ansi);
const red = match?.[1];
const green = match?.[2];
const blue = match?.[3];
if (red === undefined || green === undefined || blue === undefined) {
return undefined;
}
return {
r: Number.parseInt(red, 10),
g: Number.parseInt(green, 10),
b: Number.parseInt(blue, 10),
};
}
function isWorkingLightTheme() {
return theme.name?.toLowerCase().includes("light") ?? false;
}
function formatWorkingStatusShimmerText(text, intensity) {
if (theme.getColorMode() !== "truecolor") {
if (intensity < 0.2) {
return theme.fg("dim", text);
}
if (intensity < 0.6) {
return theme.fg("text", text);
}
return theme.bold(theme.fg("text", text));
}
const lightTheme = isWorkingLightTheme();
const highlight = parseAnsiRgbForeground(theme.getFgAnsi("dim")) ??
(lightTheme ? LIGHT_DEFAULT_WORKING_BASE_RGB : DARK_DEFAULT_WORKING_BASE_RGB);
const base = parseAnsiRgbForeground(theme.getFgAnsi("text")) ??
(lightTheme ? LIGHT_DEFAULT_WORKING_TEXT_RGB : DARK_DEFAULT_WORKING_TEXT_RGB);
const color = blendWorkingStatusShimmerRgbColor(highlight, base, intensity * 0.9);
return `\x1b[1m\x1b[38;2;${color.r};${color.g};${color.b}m${text}\x1b[39m\x1b[22m`;
}
function isDeadTerminalError(error) {
if (!error || typeof error !== "object") {
return false;
}
if ("code" in error) {
const code = error.code;
if (code !== undefined && DEAD_TERMINAL_ERROR_CODES.has(code)) {
return true;
}
}
if ("errno" in error) {
const errno = error.errno;
return errno === EIO_ERRNO || errno === -EIO_ERRNO;
}
return false;
}
function storageWriteCrashMessage(error) {
if (!error || typeof error !== "object" || !("code" in error)) {
return undefined;
}
const code = error.code;
if (code === "EDQUOT") {
return "Disk quota exceeded (EDQUOT). Free space or quota on the filesystem, then retry.";
}
if (code === "ENOSPC") {
return "Disk full (ENOSPC). Free space on the filesystem, then retry.";
}
return undefined;
}
export function formatCrashExtensionHint(extensionMatches) {
const matches = Array.isArray(extensionMatches)
? extensionMatches.filter((match) => typeof match === "string" && match.length > 0)
: [];
if (matches.length === 0)
return undefined;
const quoted = matches.map((match) => `\`${match}\``);
const labels = quoted.length === 1
? quoted[0]
: quoted.length === 2
? quoted.join(" and ")
: `${quoted.slice(0, -1).join(", ")}, and ${quoted[quoted.length - 1]}`;
const noun = matches.length === 1 ? "extension" : "extensions";
const pronoun = matches.length === 1 ? "it" : "them";
return `A stack frame came from loaded ${noun} ${labels}, which may be involved. Try disabling ${pronoun} with \`${APP_NAME} config\`, or run \`${APP_NAME} -ne\` to confirm.`;
}
const ANTHROPIC_SUBSCRIPTION_AUTH_WARNING = "Anthropic subscription auth is active. Third-party harness usage draws from extra usage and is billed per token, not your Claude plan limits. Manage extra usage at https://claude.ai/settings/usage. Disable this warning in /settings.";
function isUnknownModel(model) {
return !!model && model.provider === "unknown" && model.id === "unknown" && model.api === "unknown";
}
function quoteIfNeeded(value) {
if (value.length > 0 && !/[^a-zA-Z0-9_\-./~:@]/.test(value)) {
return value;
}
return `'${value.replace(/'/g, `'\\''`)}'`;
}
export function formatResumeCommand(sessionManager) {
if (!process.stdout.isTTY)
return undefined;
if (!sessionManager.isPersisted())
return undefined;
const sessionFile = sessionManager.getSessionFile();
if (!sessionFile || !fs.existsSync(sessionFile))
return undefined;
const args = [APP_COMMAND];
if (!sessionManager.usesDefaultSessionDir()) {
args.push("--session-dir", quoteIfNeeded(sessionManager.getSessionDir()));
}
args.push("--session", sessionManager.getSessionId());
return args.join(" ");
}
function hasDefaultModelProvider(providerId) {
return providerId in defaultModelPerProvider;
}
// isApiKeyLoginProvider now lives in core/auth-providers.ts so RPC clients and
// the classic selectors share ONE source of truth. Re-exported here to keep the
// existing public import (test/oauth-selector.test.ts) working, and used
// locally by getLoginProviderOptions below.
export { isApiKeyLoginProvider };
/** Startup header (logo, version, key hints): hidden only by quietStartup: true, unless verbose. */
export function showsStartupHeader(verbose, quietStartup) {
return verbose === true || quietStartup !== true;
}
/** Startup details (model scope, loaded resources): hidden by quietStartup: true or "header", unless verbose. */
export function showsStartupDetails(verbose, quietStartup) {
return verbose === true || quietStartup === false;
}
const AUTH_TYPE_ORDER = { oauth: 0, api_key: 1 };
function createFuzzyAutocompleteItems(items, prefix, getSearchText, toAutocompleteItem) {
const filtered = fuzzyFilter(items, prefix, getSearchText);
if (filtered.length === 0)
return null;
return filtered.map(toAutocompleteItem);
}
function getLoginProviderCompletionOptions(providerOptions) {
const byId = new Map();
for (const provider of providerOptions) {
const existing = byId.get(provider.id);
if (existing) {
if (!existing.authTypes.includes(provider.authType)) {
existing.authTypes.push(provider.authType);
existing.authTypes.sort((a, b) => AUTH_TYPE_ORDER[a] - AUTH_TYPE_ORDER[b]);
}
continue;
}
byId.set(provider.id, {
id: provider.id,
name: provider.name,
authTypes: [provider.authType],
});
}
return Array.from(byId.values()).sort((a, b) => a.name.localeCompare(b.name));
}
function getLoginProviderSearchText(provider) {
const authTypes = provider.authTypes
.map((authType) => `${authType} ${formatAuthSelectorProviderType(authType)}`)
.join(" ");
return `${provider.id} ${provider.name} ${authTypes}`;
}
function formatLoginProviderCompletionDescription(provider) {
const authTypes = provider.authTypes.map((authType) => formatAuthSelectorProviderType(authType)).join("/");
return provider.name === provider.id ? authTypes : `${provider.name} · ${authTypes}`;
}
/**
* Content the streaming component owns: everything through the FIRST toolCall.
* Text painted between tool cards lives in persistent per-segment components
* below the cards (regression 1064), so the head must never reabsorb it.
*/
function assistantStreamingHeadMessage(message) {
const firstToolIndex = message.content.findIndex((block) => block.type === "toolCall");
if (firstToolIndex === -1)
return message;
return { ...message, content: message.content.slice(0, firstToolIndex + 1) };
}
/** Coordinates render-only user echoes with AgentSession's canonical input lifecycle. */
export class OptimisticUserEchoController {
constructor(render) {
this.nextId = 0;
this.pending = [];
this.render = render;
}
begin(text) {
const id = `pending-user-${++this.nextId}`;
this.pending.push({ id, handle: this.render(text), eligibleForCanonicalStart: false });
return id;
}
/** `undefined` means nothing was painted for this submission; every callback then resolves to a no-op. */
promptOptions(id) {
return {
preflightResult: (success) => {
if (!success)
this.reject(id);
},
promptDisposition: (disposition) => {
const record = this.pending.find((candidate) => candidate.id === id);
if (!record)
return;
// Only a prompt that actually STARTED keeps its optimistic echo; queued
// (steer/follow-up) input must render as the pending-queue waiting state,
// matching upstream pi where user messages appear only at canonical
// message_start and queued text lives in the pending display.
if (disposition === "started")
record.eligibleForCanonicalStart = true;
else
this.reject(id);
},
};
}
reject(id) {
if (id === undefined)
return;
const index = this.pending.findIndex((record) => record.id === id);
if (index === -1)
return;
const [record] = this.pending.splice(index, 1);
record?.handle.remove();
}
remove(id) {
this.reject(id);
}
replaceNext(message) {
const first = this.pending[0];
if (!first?.eligibleForCanonicalStart)
return false;
const [record] = this.pending.splice(0, 1);
if (!record)
return false;
record.handle.replace(message);
return true;
}
}
/** Local copy of pi-tui's image-marker pattern so submission scanning never mutates a shared /g regex. */
const IMAGE_MARKER_PATTERN = /\[Image #([1-9]\d*)\]/g;
/**
* Attach a clipboard bitmap as an in-memory image behind an atomic
* `[Image #N]` marker. Returns false when the paste was unhandled, so the caller
* falls through to the plain-text clipboard path.
*
* The bytes deliberately never touch the filesystem: writing a temp file and
* inserting its path as literal text (the previous behavior) shipped an
* unreadable `/var/folders/.../pi-clipboard-<uuid>.png` string to the model and
* attached no image at all.
*/
async function attachClipboardImage(deps, image) {
if (deps.settings.getBlockImages()) {
// Pinned behavior: nothing is attached and nothing is inserted, but the
// paste is never a silent no-op - the user must learn why their screenshot
// vanished, and which setting to flip.
deps.showStatus("Image paste blocked by the images.blockImages setting");
return false;
}
if (!deps.editor.insertImageMarker) {
// A marker-unaware editor cannot keep the marker atomic, and a dead literal
// `[Image #N]` with a live payload behind it would misnumber every other
// attachment at submit.
deps.showStatus("Image paste is not supported by the active editor");
return false;
}
if (deps.isCompacting()) {
// The compaction queue carries text only; an attachment queued behind
// compaction would be silently lost at delivery, so drop it here with a
// visible status. Consume the paste as dropped - the clipboard holds a
// bitmap, so the plain-text fallback has nothing useful to insert.
deps.showStatus("Image paste dropped: messages sent during compaction cannot carry images - paste again after compaction finishes");
return "dropped";
}
const processed = await processImage(image.bytes, image.mimeType, {
autoResizeImages: deps.settings.getImageAutoResize(),
});
if (!processed.ok) {
deps.showStatus(processed.message);
return false;
}
// insertImageMarker fires onImageMarkersChanged (with the pre-renumber
// ids) synchronously and only then returns the marker's FINAL canonical id,
// whose slot the reconcile pass just vacated - so this write can neither
// land in an orphaned map (reconcile mutates pendingImages in place) nor
// overwrite a surviving payload (the new marker had no payload when the
// reconcile ran, so nothing was keyed onto its slot).
const id = deps.editor.insertImageMarker();
deps.pendingImages.set(id, {
type: "image",
data: processed.data,
mimeType: processed.mimeType,
});
deps.requestRender();
return "attached";
}
const SHARE_UPLOAD = "Upload";
const SHARE_REVIEW = "Review the exact file first";
const SHARE_EXCLUDE = "Leave tool outputs out";
const SHARE_CANCEL = "Cancel";
export class InteractiveMode {
static confirmsRefusedUnknownCommand(host, text) {
const confirmed = host.refusedUnknownCommandText === text;
host.refusedUnknownCommandText = undefined;
return confirmed;
}
static restoreCompactionEscapeOverride(host) {
if (!host.compactionEscapeOverrideActive)
return;
host.defaultEditor.onEscape = host.autoCompactionEscapeHandler;
host.autoCompactionEscapeHandler = undefined;
host.compactionEscapeOverrideActive = false;
}
requestStreamingRender() {
this.ui.requestRender();
}
applySmoothStreamingRenderFps() {
const fps = this.settingsManager.getSmoothStreaming()
? this.settingsManager.getSmoothStreamingFps()
: DEFAULT_SMOOTH_FPS;
this.ui.setMaxRenderFps(fps);
}
get shownQuestion() {
return this.shownQuestionId === undefined ? undefined : this.pendingQuestions.get(this.shownQuestionId);
}
// Convenience accessors
get session() {
return this.runtimeHost?.session;
}
get sessionManager() {
return this.session.sessionManager;
}
get settingsManager() {
return this.session.settingsManager;
}
constructor(runtimeHost, options = {}) {
this.sessionShownTipIds = new Set();
this.lastEditorText = "";
this.startupProviderGuidanceShown = false;
this.lastInputWasPaste = false;
this.continuityNotices = new ContinuityNoticeTracker();
this.turnWorkingTip = new WorkingTipCache();
this.autocompleteProviderWrappers = [];
this.isInitialized = false;
this.pendingUserInputs = [];
this.agentIdle = false;
// One unsaved-turn notice per run, however many of its messages the session file refused.
this.transcriptWriteNoticeShown = false;
/**
* Clipboard images pasted into the composer, keyed by their visible
* `[Image #N]` marker number. The editor stores marker ids only, so these
* bytes must live here (and survive an editor swap, which discards the
* editor instance). Kept aligned with the displayed numbers by
* {@link reconcilePendingImages}.
*/
this.pendingImages = new Map();
/** Lets an extension expose this session on a control endpoint; the endpoint module loads on first use. */
this.sessionControlHost = new TuiSessionControlHost(() => this.sessionControlContext());
this.activeStatusIndicator = undefined;
this.activeWorkingIndicatorEmbedded = false;
this.idleStatus = new IdleStatus();
this.workingMessage = undefined;
this.workingVisible = true;
this.workingIndicatorOptions = undefined;
this.workingStartedAt = undefined;
this.defaultWorkingMessage = "Working";
this.defaultHiddenThinkingLabel = "Thinking...";
this.hiddenThinkingLabel = this.defaultHiddenThinkingLabel;
this.activeToolExecutions = new Map();
this.activeToolExecutionTerminalTitle = undefined;
this.workingMessageBeforeActiveTool = undefined;
this.activeToolHooks = new Map();
this.hookStatusIntervalId = undefined;
this.activeToolTerminalTitle = undefined;
this.extensionTerminalTitle = undefined;
/** The OSC 7501 report last written while a status is active; undefined once cleared. */
this.programStatusSequence = undefined;
this.programStatusClosed = false;
this.lastSigintTime = 0;
this.lastEscapeTime = 0;
this.changelogMarkdown = undefined;
this.startupNoticesShown = false;
this.anthropicSubscriptionWarningShown = false;
this.copilotToolLimitNoticeSessionId = undefined;
// Status line tracking (for mutating immediately-sequential status updates)
this.lastStatusSpacer = undefined;
this.lastStatusText = undefined;
this.lastStatusMessage = "";
this.managedToolStatusStarted = false;
// Streaming message tracking
this.streamingComponent = undefined;
this.assistantTextSegments = new Map();
this.entriesRenderedByBoundaryCompaction = new Set();
this.streamingMessage = undefined;
// Tool execution tracking: toolCallId -> component
this.pendingTools = new Map();
// Tool output expansion state
this.toolOutputExpanded = false;
// Thinking block visibility state
this.hideThinkingBlock = false;
this.outputPad = 1;
this.mermaidMarkdownTransformer = createMermaidMarkdownTransformer({
getMode: () => this.settingsManager.getMermaidRenderingMode(),
theme,
});
this.messagePathLinkTransformer = createMessagePathLinkTransformer(() => this.sessionManager.getCwd());
// Skill commands: command name -> skill file path
this.skillCommands = new Map();
this.agentSubscriptionGeneration = 0;
this.lifecycleStatus = new LifecycleStatus();
this.signalCleanupHandlers = [];
// Track if editor is in bash mode (text starts with !)
this.isBashMode = false;
// Track current bash execution component
this.bashComponent = undefined;
// Track pending bash components (shown in pending area, moved to chat on submit)
this.pendingBashComponents = [];
this.compactionEscapeOverrideActive = false;
/**
* One-time notice guard for the external-owner compaction delegation episode
* (e.g. the Claude Agent SDK owning compaction). Armed while true; re-armed by
* a successful compaction, a model switch, or a session rebind.
*/
this.externalOwnerCompactionNoticeShown = false;
this.autoCompactionProgressText = "";
this.fallbackAppliedBeforeRetryStart = false;
this.pendingZeroDelayRetryIndicator = undefined;
// Messages queued while compaction is running
this.compactionQueuedMessages = [];
this.compactionInFlightMessages = [];
this.compactionTransferAbortControllers = new Map();
this.compactionQueueGeneration = 0;
// Shutdown state
this.shutdownRequested = false;
// Extension UI state
this.extensionSelector = undefined;
this.extensionInput = undefined;
this.extensionEditor = undefined;
this.askUserQuestion = undefined;
this.pendingQuestions = new Map();
this.pendingOrder = [];
this.questionSurface = "collapsed";
this.composerDestination = { kind: "chat" };
this.wantsMouseLease = false;
this.questionMousePaused = false;
this.extensionTerminalInputSubscriptions = new Set();
// Extension widgets (components rendered above/below the editor)
this.extensionWidgetsAbove = new Map();
this.extensionWidgetsBelow = new Map();
// Custom footer from extension (undefined = use built-in footer)
this.customFooter = undefined;
// Built-in header (logo + keybinding hints + changelog)
this.builtInHeader = undefined;
// Custom header from extension (undefined = use built-in header)
this.customHeader = undefined;
this.onRightClickPaste = () => {
void this.handleRightClickPaste();
};
/**
* Gracefully shutdown the agent.
* Stops the TUI before emitting shutdown events so extension UI cleanup cannot
* repaint the final frame while the process is exiting.
*/
this.isShuttingDown = false;
this.runtimeHost = runtimeHost;
this.optimisticUserEchoes = new OptimisticUserEchoController((text) => this.renderPendingUserEcho(text));
const tuiMode = options.tuiMode ?? this.settingsManager.getTuiMode();
this.options = { ...options, tuiMode };
this.chrome = options.chrome === "grok" ? new GrokChrome() : options.chrome;
this.autoTrustOnReloadCwd = options.autoTrustOnReloadCwd;
this.runtimeHost.setBeforeSessionInvalidate(() => {
InteractiveMode.restoreCompactionEscapeOverride(this);
this.resetExtensionUI();
});
this.runtimeHost.setRebindSession(async () => {
await this.rebindCurrentSession({ renderBeforeBind: true });
this.themeController.applyFromSettings();
});
this.version = DISPLAY_VERSION;
this.renderer = createInteractiveTui({
tuiMode,
showHardwareCursor: this.settingsManager.getShowHardwareCursor(),
logDirectory: getAgentDir(),
terminal: options.terminal,
onRightClickPaste: this.onRightClickPaste,
fullscreenCopyOnSelect: this.settingsManager.getFullscreenCopyOnSelect?.() ?? true,
fullscreenWheelScrollLines: this.settingsManager.getFullscreenWheelScrollLines?.() ?? "auto",
mouse: this.terminalMouseMode !== "off",
});
this.ui = createInteractiveTuiReference(() => this.renderer);
this.streamingReveal = new StreamingRevealController({
getSmoothStreaming: () => this.settingsManager.getSmoothStreaming(),
getSmoothStreamingFps: () => this.settingsManager.getSmoothStreamingFps(),
getHideThinkingBlock: () => this.hideThinkingBlock,
requestRender: () => this.ui.requestRender(),
});
this.toolArgsReveal = new ToolArgsRevealController({
getSmoothStreaming: () => this.settingsManager.getSmoothStreaming(),
getSmoothStreamingFps: () => this.settingsManager.getSmoothStreamingFps(),
requestRender: () => this.ui.requestRender(),
});
this.toolResultReveal = new ToolResultRevealController({
getSmoothStreaming: () => this.settingsManager.getSmoothStreaming(),
getSmoothStreamingFps: () => this.settingsManager.getSmoothStreamingFps(),
requestRender: () => this.ui.requestRender(),
});
this.applySmoothStreamingRenderFps();
this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());
this.headerContainer = new Container();
this.loadedResourcesContainer = new Container();
// Resuming a long session paints a bounded, fully-styled tail first and warms
// the earlier history in background chunks, so /resume is not blocked on
// Markdown-rendering every persisted message before the first frame.
this.chatContainer = new ExplorationTranscriptContainer({
tailBudget: DEFAULT_TAIL_BUDGET,
warmChunkSize: DEFAULT_WARM_CHUNK_SIZE,
requestRender: () => this.ui.requestRender(),
historyMarker: (hidden) => theme.fg("muted", ` ${defaultHistoryMarker(hidden)}`),
});
this.documentContainer = new Container();
this.documentContainer.addChild(this.headerContainer);
this.documentContainer.addChild(this.loadedResourcesContainer);
this.documentContainer.addChild(this.chatContainer);
this.pendingMessagesContainer = new Container();
this.statusContainer = new Container();
this.hookStatusContainer = new Container();
this.widgetContainerAbove = new Container();
this.widgetContainerBelow = new Container();
this.keybindings = KeybindingsManager.create();
setKeybindings(this.keybindings);
const editorPaddingX = this.settingsManager.getEditorPaddingX();
const autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();
if (this.chrome) {
this.defaultEditor = this.chrome.createBaseEditor({
ui: this.ui,
keybindings: this.keybindings,
editorOptions: { paddingX: editorPaddingX, autocompleteMaxVisible },
});
}
else {
this.defaultEditor = new CustomEditor(this.ui, getEditorTheme(), this.keybindings, {
paddingX: editorPaddingX,
autocompleteMaxVisible,
embedWorkingStatus: true,
});
}
this.editor = this.defaultEditor;
observeComposerActivity(this.defaultEditor, () => emitUserActivity(this.session, "draft"));
this.editorContainer = new Container();
this.editorContainer.addChild(this.editor);
this.footerDataProvider = new FooterDataProvider(this.sessionManager.getCwd());
this.footer = this.chrome
? this.chrome.createFooter(this.session, this.footerDataProvider)
: new FooterComponent(this.session, this.footerDataProvider, {
// CLI > settings > stored pin, resolved per render so a
// mid-session /claude-account pin or settings change is
// picked up (senpi#5983); the stored pin stays the
// fallback inside accountFooterSuffix.
resolveAccountPin: (sessionId) => resolveClaudeAccountPin(getSessionClaudeAccountPin(sessionId), loadAnthropicSubscriptionProviderSettingsFromDisk(this.sessionManager.getCwd()).pinnedAccount, undefined),
});
this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);
this.footerContainer = new Container();
this.footerContainer.addChild(this.footer);
// Load hide thinking block setting
this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
this.outputPad = this.settingsManager.getOutputPad();
// Register themes from resource loader and initialize
setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
this.themeController = new InteractiveThemeController(this.ui, {
getSettingsManager: () => this.settingsManager,
showError: (message) => this.showError(message),
onChanged: () => this.updateEditorBorderColor(),
initialThemeSetting: options.initialThemeSetting,
});
}
getAutocompleteSourceTag(sourceInfo) {
// Built-in extension commands are untagged, like built-in commands; fork system-scoped resources
// (the bundled builtin registry) keep their `[s]` tag.
if (!sourceInfo || (sourceInfo.source === "builtin" && sourceInfo.scope !== "system")) {
return undefined;
}
const scopePrefix = getScopeAutocompleteTag(sourceInfo.scope);
const source = sourceInfo.source.trim();
if (source === "auto" || source === "local" || source === "cli") {
return scopePrefix;
}
if (source.startsWith("npm:")) {
return `${scopePrefix}:${source}`;
}
const gitSource = parseGitUrl(source);
if (gitSource) {
const ref = gitSource.ref ? `@${gitSource.ref}` : "";
return `${scopePrefix}:git:${gitSource.host}/${gitSource.path}${ref}`;
}
return scopePrefix;
}
prefixAutocompleteDescription(description, sourceInfo) {
const sourceTag = this.getAutocompleteSourceTag(sourceInfo);
if (!sourceTag) {
return description;
}
return description ? `[${sourceTag}] ${description}` : `[${sourceTag}]`;
}
getBuiltInCommandConflictDiagnostics(extensionRunner) {
const builtinNames = new Set(BUILTIN_SLASH_COMMANDS.map((command) => command.name));
return extensionRunner
.getRegisteredCommands()
.filter((command) => builtinNames.has(command.name))
.map((command) => ({
type: "warning",
message: command.invocationName === command.name
? `Extension command '/${command.name}' conflicts with built-in interactive command. Skipping in autocomplete.`
: `Extension command '/${command.name}' conflicts with built-in interactive command. Available as '/${command.invocationName}'.`,
path: command.sourceInfo.path,
}));
}
createBaseAutocompleteProvider() {
// Define commands for autocomplete
const slashCommands = BUILTIN_SLASH_COMMANDS.map((command) => ({
name: command.name,
description: command.description,
...(command.argumentHint && { argumentHint: command.argumentHint }),
...(command.requiresArguments !== undefined && { requiresArguments: command.requiresArguments }),
}));
const modelCommand = slashCommands.find((command) => command.name === "model");
if (modelCommand) {
modelCommand.getArgumentCompletions = (prefix) => {
const models = this.session.scopedModels.length > 0
? this.session.scopedModels.map((s) => s.model)
: this.session.modelRuntime.getAvailableSnapshot();
if (models.length === 0)
return null;
// Create items with provider/id format
const items = models.map((m) => ({
id: m.id,
provider: m.provider,
name: m.name,
label: `${m.provider}/${m.id}`,
}));
return createFuzzyAutocompleteItems(items, prefix, getModelSearchText, (item) => ({
value: item.label,
label: item.id,
description: item.provider,
}));
};
}
const loginCommand = slashCommands.find((command) => command.name === "login");
if (loginCommand) {
loginCommand.getArgumentCompletions = (prefix) => {
const providers = getLoginProviderCompletionOptions(this.getLoginProviderOptions());
return createFuzzyAutocompleteItems(providers, prefix, getLoginProviderSearchText, (provider) => ({
value: provider.id,
label: provider.id,
description: formatLoginProviderCompletionDescription(provider),
}));
};
}
const thinkingCommand = slashCommands.find((command) => command.name === "thinking");
if (thinkingCommand) {
thinkingCommand.getArgumentCompletions = async (prefix) => {
const levels = this.session.getAvailableThinkingLevels();
return createFuzzyAutocompleteItems(levels, prefix, (level) => level, (level) => ({ value: level, label: level }));
};
}
// Convert prompt templates to SlashCommand format for autocomplete
const templateCommands = this.session.promptTemplates.map((cmd) => ({
name: cmd.name,
description: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),
...(cmd.argumentHint && { argumentHint: cmd.argumentHint }),
...(cmd.requiresArguments !== undefined && { requiresArguments: cmd.requiresArguments }),
}));
// Convert extension commands to SlashCommand format
const builtinCommandNames = new Set(slashCommands.map((c) => c.name));
const extensionCommands = this.session.extensionRunner
.getRegisteredCommands()
.filter((cmd) => !builtinCommandNames.has(cmd.name))
.map((cmd) => ({
name: cmd.invocationName,
description: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),
...(cmd.argumentHint && { argumentHint: cmd.argumentHint }),
...(cmd.requiresArguments !== undefined && { requiresArguments: cmd.requiresArguments }),
getArgumentCompletions: cmd.getArgumentCompletions,
}));
// Build skill commands from session.skills (if enabled)
this.skillCommands.clear();
const skillCommandList = [];
if (this.settingsManager.getEnableSkillCommands()) {
for (const skill of this.session.resourceLoader.getSkills().skills) {
const commandName = `skill:${skill.name}`;
this.skillCommands.set(commandName, skill.filePath);
skillCommandList.push({
name: commandName,
description: this.prefixAutocompleteDescription(skill.description, skill.sourceInfo),
...(skill.argumentHint && { argumentHint: skill.argumentHint }),
...(skill.requiresArguments !== undefined && { requiresArguments: skill.requiresArguments }),
});
}
}
return new CombinedAutocompleteProvider([...slashCommands, ...templateCommands, ...extensionCommands, ...skillCommandList], this.sessionManager.getCwd(), this.fdPath);
}
setupAutocompleteProvider() {
let provider = this.createBaseAutocompleteProvider();
const triggerCharacters = [];
for (const wrapProvider of this.autocompleteProviderWrappers) {
provider = wrapProvider(provider);
triggerCharacters.push(...(provider.triggerCharacters ?? []));
}
if (triggerCharacters.length > 0) {
provider.triggerCharacters = [...new Set(triggerCharacters)];
}
this.autocompleteProvider = provider;
this.defaultEditor.setAutocompleteProvider(provider);
if (this.editor !== this.defaultEditor) {
this.editor.setAutocompleteProvider?.(provider);
}
}
showStartupNoticesIfNeeded() {
if (this.startupNoticesShown) {
return;
}
this.startupNoticesShown = true;
if (!this.changelogMarkdown) {
return;
}
if (this.chatContainer.children.length > 0) {
this.chatContainer.addChild(new Spacer(1));
}
this.chatContainer.addChild(new DynamicBorder());
if (this.settingsManager.getCollapseChangelog()) {
const versionMatch = this.changelogMarkdown.match(/##\s+\[?(\d+\.\d+\.\d+)\]?/);
const latestVersion = versionMatch ? versionMatch[1] : this.version;
const condensedText = `Updated to v${latestVersion}. Use ${theme.bold("/changelog")} to view full changelog.`;
this.chatContainer.addChild(new Text(condensedText, 1, 0));
}
else {
this.chatContainer.addChild(new ThemedText(() => theme.bold(theme.fg("accent", "What's New")), 1, 0));
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new Markdown(this.changelogMarkdown.trim(), 1, 0, this.getMarkdownThemeWithSettings()));
this.chatContainer.addChild(new Spacer(1));
}
this.chatContainer.addChild(new DynamicBorder());
}
get terminalMouseMode() {
// Renderer-only embedding hosts may omit the session settings facade.
return this.runtimeHost?.session?.settingsManager?.getTerminalMouse?.() ?? "whilePending";
}
syncQuestionMouseCapture() {
this.wantsMouseLease = (this.pendingQuestions?.size ?? 0) > 0 || Boolean(this.askUserQuestion);
const enabled = !this.questionMousePaused && this.terminalMouseMode !== "off";
if (enabled && this.wantsMouseLease)
this.releaseMouseLease ??= this.ui.acquireMouseCapture("pending-question");
else {
this.releaseMouseLease?.();
this.releaseMouseLease = undefined;
}
if (enabled && this.terminalMouseMode === "always" && this.ui.mode === "regular") {
this.releaseAlwaysMouseLease ??= this.ui.acquireMouseCapture("always");
}
else {
this.releaseAlwaysMouseLease?.();
this.releaseAlwaysMouseLease = undefined;
}
}
pauseQuestionMouseCapture() {
this.questionMousePaused = true;
this.releaseMouseLease?.();
this.releaseMouseLease = undefined;
this.releaseAlwaysMouseLease?.();
this.releaseAlwaysMouseLease = undefined;
}
resumeQuestionMouseCapture() {
this.questionMousePaused = false;
this.syncQuestionMouseCapture();
}
mountInteractiveTui(tui, components) {
for (const component of components)
tui.addChild(component);
if (TuiLayouts.isViewportTUI(tui)) {
if (!this.fullscreenLayoutRoot)
throw new Error("Fullscreen layout is not initialized");
tui.setLayoutRoot(this.fullscreenLayoutRoot);
}
}
stopInteractiveTui(fullscreenExitOutput) {
if (this.renderer.mode === "fullscreen" && fullscreenExitOutput === "transcript") {
while (this.renderer.hasOverlayEntries)
this.renderer.hideOverlay();
this.switchTuiMode("regular", false, false);
this.renderer.renderNow();
}
this.pauseQuestionMouseCapture();
this.ui.stop({ preserveScreen: this.renderer.mode === "fullscreen" });
}
switchTuiMode(mode, restoreProgress = true, startRenderer = true, recreate = false) {
const previousUi = this.renderer;
if (mode === previousUi.mode && !recreate)
return true;
if (previousUi.hasOverlayEntries)
return false;
const components = [...previousUi.children];
const focus = previousUi.getFocusedComponent();
const terminal = previousUi.terminal;
const showHardwareCursor = previousUi.getShowHardwareCursor();
const clearOnShrink = previousUi.getClearOnShrink();
const onDebug = previousUi.onDebug;
if (previousUi instanceof TuiMainScreen) {
this.mainScreenRenderState = previousUi.captureRenderState();
}
this.pauseQuestionMouseCapture();
previousUi.stop({ preserveScreen: true });
previousUi.setFocus(null);
// Detach, not clear: the same live components (spinners, reveals, extension
// widgets) are remounted on nextUi below. clear() would dispose them,
// killing every interval they own while they keep rendering static frames
// forever — the TUI then never self-repaints until an input event forces one.
previousUi.detachAll();
if (TuiLayouts.isViewportTUI(previousUi))
previousUi.setLayoutRoot(undefined);
const nextUi = createInteractiveTui({
tuiMode: mode,
showHardwareCursor,
logDirectory: getAgentDir(),
terminal,
onRightClickPaste: this.onRightClickPaste,
fullscreenCopyOnSelect: this.runtimeHost?.session?.settingsManager?.getFullscreenCopyOnSelect?.() ?? true,
fullscreenWheelScrollLines: this.runtimeHost?.session?.settingsManager?.getFullscreenWheelScrollLines?.() ?? "auto",
mouse: this.terminalMouseMode !== "off",
});
nextUi.setClearOnShrink(clearOnShrink);
nextUi.onDebug = onDebug;
if (nextUi instanceof TuiMainScreen && this.mainScreenRenderState) {
nextUi.restoreRenderState(this.mainScreenRenderState);
}
this.renderer = nextUi;
this.options.tuiMode = mode;
this.mountInteractiveTui(nextUi, components);
nextUi.invalidate();
nextUi.setFocus(focus);
if (!startRenderer)
return true;
nextUi.start();
this.resumeQuestionMouseCapture();
this.themeController.rebindTui();
this.rebindExtensionTerminalInputListeners();
if (restoreProgress &&
this.settingsManager.getShowTerminalProgress() &&
(this.session.isStreaming || this.session.isCompacting)) {
terminal.setProgress(true);
}
return true;
}
async init() {
if (this.isInitialized)
return;
// This method is the single largest startup phase, and `main.ts` measures it as one opaque
// number. The "tui" namespace splits it at the seams that own real work, so the next round
// budgets against measurements instead of guesses.
resetTimings("tui");
this.registerSignalHandlers();
// Load changelog (only show new entries, skip for resumed sessions)
this.changelogMarkdown = this.getChangelogForDisplay();
time("changelog", "tui");
if (this.session.scopedModels.length > 0 &&
showsStartupDetails(this.options.verbose, this.settingsManager.getQuietStartup())) {
const modelList = this.session.scopedModels
.map((sm) => {
const thinkingStr = sm.thinkingLevel ? `:${sm.thinkingLevel}` : "";
return `${sm.model.id}${thinkingStr}`;
})
.join(", ");
const cycleKeys = this.keybindings.getKeys("app.model.cycleForward");
const cycleHint = cycleKeys.length > 0
? theme.fg("muted", ` (${formatKeyText(cycleKeys.join("/"), { capitalize: true })} to cycle)`)
: "";
console.log(theme.fg("dim", `Model scope: ${modelList}${cycleHint}`));
}
// Keep one component tree and remount it when changing renderers.
this.renderWidgets(); // Initialize with default spacer
const viewport = createChatViewport({
document: this.documentContainer,
pendingMessages: this.pendingMessagesContainer,
status: this.statusContainer,
hookStatus: this.hookStatusContainer,
widgetsAbove: this.widgetContainerAbove,
editor: this.editorContainer,
widgetsBelow: this.widgetContainerBelow,
footer: this.footerContainer,
scrollbar: this.settingsManager.getFullscreenScrollbar(),
scrollbarTrackStyle: (text) => theme.fg("scrollbarTrack", text),
scrollbarThumbStyle: (text) => theme.fg("scrollbarThumb", text),
});
this.transcriptScrollView = viewport.transcript;
this.fullscreenLayoutRoot = viewport.root;
const rootComponents = [
this.documentContainer,
this.pendingMessagesContainer,
this.statusContainer,
this.hookStatusContainer,
this.widgetContainerAbove,
this.editorContainer,
this.widgetContainerBelow,
this.footerContainer,
];
if (this.chrome) {
for (const component of this.chrome.arrangeRoot(rootComponents, this.ui))
this.renderer.addChild(component);
}
else {
this.mountInteractiveTui(this.renderer, rootComponents);
}
// Accept text while startup completes, but only enable interrupt, exit, and submission feedback.
// Renderer-only lifecycle hosts may mount the chrome tree without constructing the base editor.
if (this.defaultEditor) {
this.defaultEditor.onAction("app.clear", () => this.handleCtrlC());
this.defaultEditor.onCtrlD = () => this.handleCtrlD();
this.defaultEditor.onSubmit = (text, details) => this.handleStartupSubmit(text, details);
}
this.ui.setFocus(this.editor);
// Start the UI before initializing extensions so session_start handlers can use interactive dialogs
await prepareInteractiveStderrCapture();
try {
takeOverInteractiveStderr();
this.ui.start();
this.resumeQuestionMouseCapture();
}
catch (error) {
restoreInteractiveStderr();
throw error;
}
this.isInitialized = true;
time("componentTree+uiStart", "tui");
this.themeController.applyFromSettings();
// The header and startup notices bake theme colors into their text, so build them once the terminal
// reported its colors. This ends at the terminal's DA1 reply, or after 100 ms if it answers nothing.
await this.themeController.waitForTerminalColors();
time("theme", "tui");
// Add header with keybindings from config (unless silenced)
if (this.chrome) {
this.builtInHeader = this.chrome.createWelcomeContent(APP_NAME, this.version);
this.headerContainer.addChild(new Spacer(1));
this.headerContainer.addChild(this.builtInHeader);
this.headerContainer.addChild(new Spacer(1));
}
else if (showsStartupHeader(this.options.verbose, this.settingsManager.getQuietStartup())) {
const showDetails = showsStartupDetails(this.options.verbose, this.settingsManager.getQuietStartup());
// Built on demand so the header follows theme changes (the system theme recolors once the
// terminal reports its colors).
const logo = () => theme.bold(theme.fg("accent", APP_NAME)) + theme.fg("dim", ` ${formatDisplayVersion(this.version)}`);
// Build startup instructions using keybinding hint helpers
const hint = (keybinding, description) => keyHint(keybinding, description);
const expandedInstructions = () => [
hint("app.interrupt", "to interrupt"),
hint("app.clear", "to clear"),
rawKeyHint(`${keyText("app.clear")} twice`, "to exit"),
hint("app.exit", "to exit (empty)"),
hint("app.suspend", "to suspend"),
keyHint("tui.editor.deleteToLineEnd", "to delete to end"),
hint("app.thinking.cycle", "to cycle thinking level"),
rawKeyHint(`${keyText("app.model.cycleForward")}/${keyText("app.model.cycleBackward")}`, "to cycle models"),
hint("app.model.select", "to select model"),
hint("app.tools.expand", "to expand tools"),
hint("app.thinking.toggle", "to expand thinking"),
hint("app.editor.external", "for external editor"),
rawKeyHint("/", "for commands"),
rawKeyHint("!", "to run bash"),
rawKeyHint("!!", "to run bash (no context)"),
hint("app.message.followUp", "to queue follow-up"),
hint("app.message.dequeue", "to edit all queued messages"),
hint("app.clipboard.pasteImage", "to paste files on macOS, images, or text"),
rawKeyHint("drop files", "to attach"),
].join("\n");
const compactInstructions = () => [
hint("app.interrupt", "interrupt"),
rawKeyHint(`${keyText("app.clear")}/${keyText("app.exit")}`, "clear/exit"),
rawKeyHint("/", "commands"),
rawKeyHint("!", "bash"),
hint("app.tools.expand", "more"),
].join(theme.fg("muted", " · "));
const compactOnboarding = () => theme.fg("dim", `Press ${keyText("app.tools.expand")} to show full startup help${showDetails ? " and loaded resources" : ""}.`);
const startupTips = resolveStartupTips({
settings: this.settingsManager,
now: Date.now(),
modelReasoning: () => this.session.state.model?.reasoning === true,
hasCommand: (command) => this.hasRegisteredCommand(command),
keys: keyText,
displayKeys: keyDisplayText,
});
for (const tipId of startupTips?.tipIds ?? [])
this.sessionShownTipIds.add(tipId);
const tipLine = startupTips ? theme.fg("dim", startupTips.text) : undefined;
const onboarding = () => theme.fg("dim", `Pi can explain its own features and look up its docs. Ask it how to use or extend Pi.`);
this.builtInHeader = new ExpandableText(() => `${logo()}\n${compactInstructions()}\n${compactOnboarding()}\n\n${onboarding()}`, () => `${logo()}\n${expandedInstructions()}\n\n${onboarding()}`, this.getStartupExpansionState(), 1, 0);
appendStartupHeader(this.headerContainer, this.builtInHeader, tipLine);
}
else {
// Minimal header when silenced
this.builtInHeader = new Text("", 0, 0);
this.headerContainer.addChild(this.builtInHeader);
}
this.ui.requestRender();
// Ensure fd and rg are available after mounting the TUI (downloads if missing, adds to PATH via getBinDir)
// so slow downloads do not make startup appear frozen.
// Both are needed: fd for autocomplete, rg for grep tool and bash commands.
const [fdPath] = await Promise.all([
ensureTool("fd", (status) => this.showManagedToolStatus(status)),
ensureTool("rg", (status) => this.showManagedToolStatus(status)),
]);
this.fdPath = fdPath;
time("ensureTools", "tui");
// Initialize extensions first so resources are shown before messages
await this.rebindCurrentSession();
time("rebindSession", "tui");
// Render initial messages AFTER showing loaded resources
this.renderInitialMessages();
this.session.releaseSettledSessionMemory();
time("renderInitial", "tui");
// Enable the remaining input handlers only once the restored transcript is rendered (senpi#4826): a
// submit accepted earlier painted its echo above the history that startup appended afterwards.
this.setupKeyHandlers();
this.setupEditorSubmitHandler();
this.sessionControlHost?.attachEditor(this.defaultEditor, () => this.hasComposerDraft());
adoptDefaultEditorActions(this.defaultEditor, this.editor);
const parkedSubmission = this.startupParkedSubmission;
this.startupParkedSubmission = undefined;
replayStartupSubmission(parkedSubmission, this.editor, this.defaultEditor);
this.ui.requestRender();
time("keyHandlers", "tui");
// Set up theme file watcher
onThemeChange(() => {
this.ui.invalidate();
this.updateEditorBorderColor();
this.ui.requestRender();
});
// Set up git branch watcher (uses provider instead of footer)
this.footerDataProvider.onBranchChange(() => {
this.ui.requestRender();
});
// Initialize available provider count for footer display
this.updateAvailableProviderCount();
}
/**
* Update terminal title with session name and cwd.
*/
getNormalTerminalTitle() {
const cwdBasename = path.basename(this.sessionManager.getCwd());
const sessionName = this.sessionManager.getSessionName();
if (sessionName) {
return `${APP_TITLE} - ${sessionName} - ${cwdBasename}`;
}
return `${APP_TITLE} - ${cwdBasename}`;
}
applyTerminalTitle() {
const questionHeader = this.shownQuestion?.request.questions[0]?.header ?? this.blockingQuestionHeader;
this.ui.terminal.setTitle(this.activeToolTerminalTitle ??
this.activeToolExecutionTerminalTitle ??
(questionHeader === undefined ? undefined : `? ${questionHeader}`) ??
this.extensionTerminalTitle ??
this.getNormalTerminalTitle());
}
updateTerminalTitle() {
this.applyTerminalTitle();
}
setProgramStatus(status) {
if (this.programStatusClosed)
return;
const sequence = encodeProgramStatus(status, APP_COMMAND);
if (status === undefined ? this.programStatusSequence === undefined : sequence === this.programStatusSequence)
return;
this.programStatusSequence = status === undefined ? undefined : sequence;
if (process.stdout.isTTY)
this.ui.terminal.write(sequence);
}
/**
* Run the interactive mode. This is the main entry point.
* Initializes the UI, shows warnings, processes initial messages, and starts the interactive loop.
*/
async run() {
await this.init();
if (!envValue("OFFLINE")) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 15_000);
void refreshModelCatalogs(this.session.modelRuntime, controller.signal)
.then(() => {
this.updateAvailableProviderCount();
this.ui.requestRender();
})
.catch(() => { })
.finally(() => clearTimeout(timeout));
}
// Start version check asynchronously
checkForNewPiVersion(this.version).then((newVersion) => {
if (newVersion) {
this.showNewVersionNotification(newVersion.version);
}
});
// Start package update check asynchronously
this.checkForPackageUpdates()
.then((updates) => {
if (updates.length > 0) {
this.showPackageUpdateNotification(updates);
}
})
.finally(() => {
// On Windows, npm can overwrite the shared console title while checking
// extension package versions. Restore Pi's title after the startup check.
if (process.platform === "win32" && this.isInitialized) {
this.updateTerminalTitle();
}
});
// Check tmux setup asynchronously
this.checkTmuxSetup().then((warning) => {
if (warning) {
this.showWarning(warning);
}
});
// Show startup warnings
const { migratedProviders, legacyPiEditNotice, startupDiagnostics, authNotices, modelFallbackMessage, initialMessage, initialImages, initialMessages, initialTitlePrompt, } = this.options;
if (migratedProviders && migratedProviders.length > 0) {
this.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(", ")}`);
}
if (legacyPiEditNotice) {
this.showWarning(legacyPiEditNotice);
}
for (const diagnostic of startupDiagnostics ?? []) {
if (diagnostic.type === "warning")
this.showWarning(diagnostic.message);
else if (diagnostic.type === "error")
this.showError(diagnostic.message);
}
if (authNotices && authNotices.messages.length > 0) {
for (const message of authNotices.messages)
this.showWarning(message);
authNotices.markSeen();
}
const modelsJsonError = this.session.modelRuntime.getError();
if (modelsJsonError) {
this.showError(`models.json error: ${modelsJsonError}`);
}
const modelRuntimeWarnings = this.session.modelRuntime.getWarnings();
// Fold repeated warnings only in quiet startup; a hand-built context without getQuietStartup
// is treated as not-quiet so full detail shows (the safe default, and what the old path did).
const getQuietStartup = this.settingsManager?.getQuietStartup?.bind(this.settingsManager);
const quietStartup = getQuietStartup ? getQuietStartup() : false;
if (showsStartupDetails(this.options.verbose, quietStartup)) {
for (const warning of modelRuntimeWarnings) {
this.showWarning(warning);
}
}
else if (modelRuntimeWarnings.length === 1) {
this.showWarning(modelRuntimeWarnings[0]);
}
else if (modelRuntimeWarnings.length > 1) {
this.showNoticeBox({
title: `${modelRuntimeWarnings.length} model warnings`,
tone: "warning",
why: modelRuntimeWarnings[0],
extra: modelRuntimeWarnings.slice(1).map((text) => ({ text })),
});
}
if (modelFallbackMessage) {
this.showWarning(modelFallbackMessage);
if (modelFallbackMessage === formatNoModelsAvailableMessage())
this.startupProviderGuidanceShown = true;
}
for (const warning of this.session.fallbackValidationWarnings) {
this.showWarning(warning);
}
const startupThinkingClamp = this.session.startupThinkingClamp;
if (startupThinkingClamp) {
this.showWarning(formatThinkingClampWarning(startupThinkingClamp));
}
this.showRiskyMainModelWarning(this.session.model);
void this.maybeWarnAboutAnthropicSubscriptionAuth();
maybeShowRuntimeNotice((spec) => this.showNoticeBox(spec));
// Process initial messages
if (initialMessage) {
try {
await this.session.prompt(initialMessage, {
images: initialImages,
sessionTitlePrompt: initialTitlePrompt ?? false,
});
}
catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
this.showError(errorMessage);
}
}
if (initialMessages) {
for (const message of initialMessages) {
try {
await this.session.prompt(message);
}
catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
this.showError(errorMessage);
}
}
}
// Main interactive loop
while (true) {
const userInput = await this.getUserInput();
try {
await this.session.prompt(userInput.text, this.buildMainLoopPromptOptions(userInput));
}
catch (error) {
this.optimisticUserEchoes.reject(userInput.pendingEchoId);
this.clearStatusIndicator("working");
if (error instanceof UnknownCommandError && this.reportUnknownCommandRejection(error, userInput.text))
continue;
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
this.showError(errorMessage);
}
finally {
userInput.ticket?.release();
}
}
}
async checkForPackageUpdates() {
return [];
}
async checkTmuxSetup() {
return this.checkTmuxKeyboardSetup();
}
async checkTmuxKeyboardSetup() {
if (!process.env.TMUX)
return undefined;
const runTmux = (args) => {
return new Promise((resolve) => {
const proc = spawn("tmux", args, {
stdio: ["ignore", "pipe", "ignore"],
});
let stdout = "";
const timer = setTimeout(() => {
signalSpawnedChild(proc);
resolve(undefined);
}, 2000);
proc.stdout?.on("data", (data) => {
stdout += data.toString();
});
proc.on("error", () => {
clearTimeout(timer);
resolve(undefined);
});
proc.on("close", (code) => {
clearTimeout(timer);
resolve(code === 0 ? stdout.trim() : undefined);
});
});
};
const [extendedKeys, extendedKeysFormat, clientTermname, allowPassthrough, focusEvents, version] = await Promise.all([
runTmux(["show", "-gv", "extended-keys"]),
runTmux(["show", "-gv", "extended-keys-format"]),
runTmux(["display-message", "-p", "#{client_termname}"]),
runTmux(["show", "-gv", "allow-passthrough"]),
runTmux(["show", "-gv", "focus-events"]),
runTmux(["display-message", "-p", "#{version}"]),
]);
// If we couldn't query tmux (timeout, sandbox, etc.), don't warn
if (extendedKeys === undefined)
return undefined;
return buildTmuxSetupWarning({
extendedKeys,
extendedKeysFormat,
imagesEnabled: getCapabilities().tmuxPassthrough === true,
outerKittyCapable: outerKittyGraphicsMode(clientTermname ?? "") !== null,
allowPassthrough,
focusEvents,
version,
});
}
/**
* Get changelog entries to display on startup.
* Only shows new entries since last seen version, skips for resumed sessions.
*/
getChangelogForDisplay() {
// Skip changelog for resumed/continued sessions (already have messages)
if (this.session.state.messages.length > 0) {
return undefined;
}
const source = resolveChangelogSource();
if (!source.version)
return undefined;
const lastVersion = this.settingsManager.getChangelogSeen(source.id);
const changelogPath = source.path;
const entries = parseChangelog(changelogPath);
if (!lastVersion) {
// Fresh install - record the version, send telemetry, don't show changelog
this.settingsManager.setChangelogSeen(source.id, source.version);
this.reportInstallTelemetry(source.version);
return undefined;
}
const newEntries = getNewEntries(entries, lastVersion, source.version);
if (newEntries.length > 0) {
this.settingsManager.setChangelogSeen(source.id, source.version);
this.reportInstallTelemetry(source.version);
return newEntries
.map((e) => (source.rewriteLinks ? normalizeChangelogLinks(e.content, e) : e.content))
.join("\n\n");
}
return undefined;
}
reportInstallTelemetry(version) {
if (BRAND)
return;
if (envValue("OFFLINE")) {
return;
}
if (!isInstallTelemetryEnabled(this.settingsManager)) {
return;
}
void fetch(`https://pi.dev/api/report-install?version=${encodeURIComponent(version)}`, {
headers: {
"User-Agent": getPiUserAgent(version),
},
signal: AbortSignal.timeout(5000),
})
.then(() => undefined)
.catch(() => undefined);
}
getMarkdownThemeWithSettings() {
return {
...getMarkdownTheme(),
codeBlockIndent: this.settingsManager.getCodeBlockIndent(),
};
}
// =========================================================================
// Extension System
// =========================================================================
getBuiltinExtensionDisplayName(extensionId) {
return extensionId === "todowrite" ? "todo" : extensionId;
}
getBuiltinExtensionNameFromPath(p) {
const builtinMatch = p.match(/^<builtin:([^>]+)>$/);
if (!builtinMatch) {
return undefined;
}
return this.getBuiltinExtensionDisplayName(builtinMatch[1]);
}
formatDisplayPath(p) {
const builtinName = this.getBuiltinExtensionNameFromPath(p);
if (builtinName) {
return `builtin/${builtinName}`;
}
const home = os.homedir();
let result = p;
// Replace home directory with ~
if (result.startsWith(home)) {
result = `~${result.slice(home.length)}`;
}
return result;
}
formatExtensionDisplayPath(path) {
let result = this.formatDisplayPath(path);
result = result.replace(/\/index\.ts$/, "").replace(/\/index\.js$/, "");
return result;
}
formatContextPath(p) {
const cwd = path.resolve(this.sessionManager.getCwd());
const absolutePath = path.isAbsolute(p) ? path.resolve(p) : path.resolve(cwd, p);
const relativePath = getCwdRelativePath(absolutePath, cwd);
if (relativePath !== undefined) {
return relativePath;
}
return this.formatDisplayPath(absolutePath);
}
getStartupExpansionState() {
return this.options.verbose || this.toolOutputExpanded;
}
async handleKeybindingsCommand() {
const configPath = path.join(getAgentDir(), "keybindings.json");
const editorCommand = process.env.VISUAL || process.env.EDITOR;
if (!editorCommand) {
this.showError(`Set $EDITOR or $VISUAL to edit ${configPath}.`);
return;
}
const seeded = seedKeybindingsFile(configPath, this.keybindings);
const edit = await this.withTerminalHandedOver(() => editFileInExternalEditor({
command: editorCommand,
path: configPath,
}));
if (edit.status === "launch-failed") {
// The editor never ran, so a file we just seeded carries no user content.
if (seeded)
fs.rmSync(configPath, { force: true });
this.showError(`Could not open ${configPath} with "${editorCommand}".`);
return;
}
if (edit.status === "exited") {
// The editor ran and may have written the file; keep whatever is on disk.
this.showError(`"${editorCommand}" exited with code ${edit.code}; keybindings were not reloaded.`);
return;
}
const applied = applyKeybindingsFileEdit(configPath, this.keybindings);
if (applied.status === "invalid") {
this.showError(`Keybindings not reloaded - ${configPath} is not valid JSON: ${applied.message}`);
return;
}
this.showStatus("Keybindings reloaded");
}
updateShortcutOverlay(nextText) {
const previousText = this.lastEditorText;
this.lastEditorText = nextText;
const inputKind = classifyEditorInput(previousText, nextText, this.lastInputWasPaste);
this.lastInputWasPaste = false;
if (shouldShowShortcutOverlay(previousText, nextText, inputKind)) {
if (!this.shortcutOverlay) {
this.shortcutOverlay = new ShortcutOverlay();
this.headerContainer.addChild(this.shortcutOverlay);
this.ui.requestRender();
}
return;
}
this.hideShortcutOverlay();
}
hideShortcutOverlay() {
if (!this.shortcutOverlay)
return;
this.headerContainer.removeChild(this.shortcutOverlay);
this.shortcutOverlay = undefined;
this.ui.requestRender();
}
recordShownTip(tipId) {
this.sessionShownTipIds.add(tipId);
const next = recordTipShown(this.settingsManager.getTipsHistory(), tipId, Date.now());
this.settingsManager.setTipShown(tipId, next[tipId] ?? Date.now());
}
/**
* Get a short path relative to the package root for display.
*/
getShortPath(fullPath, sourceInfo) {
const normalizedFullPath = fullPath.replace(/\\/g, "/");
const baseDir = sourceInfo?.baseDir;
if (baseDir && this.isPackageSource(sourceInfo)) {
const normalizedBaseDir = baseDir.replace(/\\/g, "/");
const npmRootMatch = normalizedBaseDir.match(/^(.*\/node_modules)\/(@?[^/]+(?:\/[^/]+)?)$/);
// If fullPath is under the same node_modules root as baseDir, preserve that relative topology.
if (npmRootMatch?.[1] && normalizedFullPath.startsWith(`${npmRootMatch[1]}/`)) {
return path.posix.relative(normalizedBaseDir, normalizedFullPath);
}
const relativePath = path.relative(path.resolve(baseDir), path.resolve(fullPath));
if (relativePath &&
relativePath !== "." &&
!relativePath.startsWith("..") &&
!relativePath.startsWith(`..${path.sep}`) &&
!path.isAbsolute(relativePath)) {
return relativePath.replace(/\\/g, "/");
}
}
const source = sourceInfo?.source ?? "";
const npmMatch = normalizedFullPath.match(/node_modules\/(@?[^/]+(?:\/[^/]+)?)\/(.*)/);
if (npmMatch && source.startsWith("npm:")) {
return npmMatch[2];
}
const gitMatch = normalizedFullPath.match(/git\/[^/]+\/[^/]+\/(.*)/);
if (gitMatch && source.startsWith("git:")) {
return gitMatch[1];
}
return this.formatDisplayPath(fullPath);
}
getCompactPathLabel(resourcePath, sourceInfo) {
const shortPath = this.getShortPath(resourcePath, sourceInfo);
const normalizedPath = shortPath.replace(/\\/g, "/");
const segments = normalizedPath.split("/").filter((segment) => segment.length > 0 && segment !== "~");
if (segments.length > 0) {
return segments[segments.length - 1];
}
return shortPath;
}
getCompactPackageSourceLabel(sourceInfo) {
const source = sourceInfo?.source ?? "";
if (source.startsWith("npm:")) {
return source.slice("npm:".length) || source;
}
const gitSource = parseGitUrl(source);
if (gitSource) {
return gitSource.path || source;
}
return source;
}
getCompactExtensionLabel(resourcePath, sourceInfo) {
if (!this.isPackageSource(sourceInfo)) {
return this.getCompactPathLabel(resourcePath, sourceInfo);
}
const sourceLabel = this.getCompactPackageSourceLabel(sourceInfo);
if (!sourceLabel) {
return this.getCompactPathLabel(resourcePath, sourceInfo);
}
const shortPath = this.getShortPath(resourcePath, sourceInfo).replace(/\\/g, "/");
const packagePath = shortPath.startsWith("extensions/") ? shortPath.slice("extensions/".length) : shortPath;
const parsedPath = path.posix.parse(packagePath);
if (parsedPath.name === "index") {
return !parsedPath.dir || parsedPath.dir === "." ? sourceLabel : `${sourceLabel}:${parsedPath.dir}`;
}
return `${sourceLabel}:${packagePath}`;
}
getCompactDisplayPathSegments(resourcePath) {
return this.formatDisplayPath(resourcePath)
.replace(/\\/g, "/")
.split("/")
.filter((segment) => segment.length > 0 && segment !== "~");
}
getCompactNonPackageExtensionLabel(resourcePath, index, allPaths) {
const segments = allPaths[index]?.segments;
if (!segments || segments.length === 0) {
return this.getCompactPathLabel(resourcePath);
}
for (let segmentCount = 1; segmentCount <= segments.length; segmentCount += 1) {
const candidate = segments.slice(-segmentCount).join("/");
const isUnique = allPaths.every((item, itemIndex) => {
if (itemIndex === index) {
return true;
}
return item.segments.slice(-segmentCount).join("/") !== candidate;
});
if (isUnique) {
return candidate;
}
}
return segments.join("/");
}
getCompactExtensionLabels(extensions) {
const nonPackageExtensions = extensions
.map((extension) => {
const segments = this.getCompactDisplayPathSegments(extension.path);
const lastSegment = segments[segments.length - 1];
if (segments.length > 1 && (lastSegment === "index.ts" || lastSegment === "index.js")) {
segments.pop();
}
return {
path: extension.path,
sourceInfo: extension.sourceInfo,
segments,
};
})
.filter((extension) => !this.isPackageSource(extension.sourceInfo));
return extensions.map((extension) => {
if (this.isPackageSource(extension.sourceInfo)) {
return this.getCompactExtensionLabel(extension.path, extension.sourceInfo);
}
const nonPackageIndex = nonPackageExtensions.findIndex((item) => item.path === extension.path);
if (nonPackageIndex === -1) {
return this.getCompactPathLabel(extension.path, extension.sourceInfo);
}
return this.getCompactNonPackageExtensionLabel(extension.path, nonPackageIndex, nonPackageExtensions);
});
}
getDisplaySourceInfo(sourceInfo) {
return getDisplaySourceInfo(sourceInfo);
}
isPackageSource(sourceInfo) {
return isPackageSourceInfo(sourceInfo);
}
buildScopeGroups(items) {
return buildResourceScopeGroups(items);
}
formatScopeGroups(groups, options) {
return formatResourceScopeGroups(groups, options);
}
findSourceInfoForPath(p, sourceInfos) {
const exact = sourceInfos.get(p);
if (exact)
return exact;
let current = p;
while (current.includes("/")) {
current = current.substring(0, current.lastIndexOf("/"));
const parent = sourceInfos.get(current);
if (parent)
return parent;
}
return undefined;
}
formatPathWithSource(p, sourceInfo) {
if (sourceInfo) {
const shortPath = this.getShortPath(p, sourceInfo);
const { label, scopeLabel } = this.getDisplaySourceInfo(sourceInfo);
const labelText = scopeLabel ? `${label} (${scopeLabel})` : label;
return `${labelText} ${shortPath}`;
}
return this.formatDisplayPath(p);
}
formatDiagnostics(diagnostics, sourceInfos) {
const lines = [];
// Group collision diagnostics by name
const collisions = new Map();
const otherDiagnostics = [];
for (const d of diagnostics) {
if (d.type === "collision" && d.collision) {
const list = collisions.get(d.collision.name) ?? [];
list.push(d);
collisions.set(d.collision.name, list);
}
else {
otherDiagnostics.push(d);
}
}
// Format collision diagnostics grouped by name
for (const [name, collisionList] of collisions) {
const first = collisionList[0]?.collision;
if (!first)
continue;
lines.push({ text: ` "${name}" collision:`, tone: "warning" });
lines.push({
text: ` ✓ ${this.formatPathWithSource(first.winnerPath, this.findSourceInfoForPath(first.winnerPath, sourceInfos))}`,
tone: "warning",
});
for (const d of collisionList) {
if (d.collision) {
lines.push({
text: ` ✗ ${this.formatPathWithSource(d.collision.loserPath, this.findSourceInfoForPath(d.collision.loserPath, sourceInfos))} (skipped)`,
tone: "warning",
});
}
}
}
for (const d of otherDiagnostics) {
const tone = d.type === "error" ? "error" : "warning";
if (d.path) {
const formattedPath = this.formatPathWithSource(d.path, this.findSourceInfoForPath(d.path, sourceInfos));
lines.push({ text: ` ${formattedPath}`, tone });
lines.push({ text: ` ${d.message}`, tone });
}
else {
lines.push({ text: ` ${d.message}`, tone });
}
}
return lines;
}
showLoadedResources(options) {
// Resource rendering is idempotent; chat clears no longer clear this separate container.
this.loadedResourcesContainer.clear();
const showListing = options?.force || showsStartupDetails(this.options.verbose, this.settingsManager.getQuietStartup());
const showDiagnostics = showListing || options?.showDiagnosticsWhenQuiet === true;
if (!showListing && !showDiagnostics) {
return;
}
const sectionHeader = (name, color = "mdHeading") => theme.fg(color, `[${name}]`);
const formatCompactList = (items, options) => {
const labels = items.map((item) => item.trim()).filter((item) => item.length > 0);
if (labels.length === 0) {
return "";
}
if (options?.sort !== false) {
labels.sort((a, b) => a.localeCompare(b));
}
// A short listing fits on one line and shows in full; a long one (dozens of skills) is
// what flooded the first screen on a narrow terminal, so it truncates to a few names
// with a +N more hint. The full list is one Ctrl+O away.
const shown = labels.length <= 8 ? labels : labels.slice(0, 3);
const hidden = labels.length - shown.length;
const more = hidden > 0 ? theme.fg("muted", ` +${hidden} more (${keyText("app.tools.expand")})`) : "";
return theme.fg("dim", ` ${shown.join(", ")}`) + more;
};
// System resources are left out of the compact body; a section with nothing else to show stays
// hidden until the listing is expanded, where the system group lists them. Bodies are built on
// demand so the listing follows theme changes.
const addLoadedSection = (name, collapsedBody, expandedBody = collapsedBody, color = "mdHeading") => {
const section = new LoadedResourceSection(() => {
const body = collapsedBody();
return body.length === 0 ? "" : `${sectionHeader(name, color)}\n${body}`;
}, () => `${sectionHeader(name, color)}\n${expandedBody()}`, this.getStartupExpansionState());
this.loadedResourcesContainer.addChild(section);
};
const skillsResult = this.session.resourceLoader.getSkills();
const promptsResult = this.session.resourceLoader.getPrompts();
const themesResult = this.session.resourceLoader.getThemes();
const extensions = options?.extensions ??
this.session.resourceLoader
.getExtensions()
.extensions.filter((extension) => !extension.hidden)
.map((extension) => ({
path: extension.path,
sourceInfo: extension.sourceInfo,
}));
const sourceInfos = new Map();
for (const extension of extensions) {
if (extension.sourceInfo) {
sourceInfos.set(extension.path, extension.sourceInfo);
}
}
for (const skill of skillsResult.skills) {
if (skill.sourceInfo) {
sourceInfos.set(skill.filePath, skill.sourceInfo);
}
}
for (const prompt of promptsResult.prompts) {
if (prompt.sourceInfo) {
sourceInfos.set(prompt.filePath, prompt.sourceInfo);
}
}
for (const loadedTheme of themesResult.themes) {
if (loadedTheme.sourcePath && loadedTheme.sourceInfo) {
sourceInfos.set(loadedTheme.sourcePath, loadedTheme.sourceInfo);
}
}
if (showListing) {
const systemPromptSource = this.session.resourceLoader.getSystemPromptSource();
const contextFiles = [
...(systemPromptSource ? [systemPromptSource] : []),
...this.session.resourceLoader.getAppendSystemPromptSources(),
...this.session.resourceLoader.getAgentsFiles().agentsFiles,
];
if (contextFiles.length > 0) {
this.loadedResourcesContainer.addChild(new Spacer(1));
const contextList = () => contextFiles.map((f) => theme.fg("dim", ` ${this.formatDisplayPath(f.path)}`)).join("\n");
const contextCompactList = () => formatCompactList(contextFiles.map((contextFile) => this.formatContextPath(contextFile.path)), { sort: false });
addLoadedSection("Context", contextCompactList, contextList);
}
const skills = skillsResult.skills;
if (skills.length > 0) {
const groups = this.buildScopeGroups(skills.map((skill) => ({
path: skill.filePath,
sourceInfo: skill.sourceInfo,
})));
const skillList = () => this.formatScopeGroups(groups, {
formatPath: (item) => this.formatDisplayPath(item.path),
formatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),
});
const skillCompactList = () => formatCompactList(skills.filter((skill) => !isSystemResource(skill.sourceInfo)).map((skill) => skill.name));
addLoadedSection("Skills", skillCompactList, skillList);
}
const templates = this.session.promptTemplates;
if (templates.length > 0) {
const groups = this.buildScopeGroups(templates.map((template) => ({
path: template.filePath,
sourceInfo: template.sourceInfo,
})));
const templateByPath = new Map(templates.map((t) => [t.filePath, t]));
const templateList = () => this.formatScopeGroups(groups, {
formatPath: (item) => {
const template = templateByPath.get(item.path);
return template ? `/${template.name}` : this.formatDisplayPath(item.path);
},
formatPackagePath: (item) => {
const template = templateByPath.get(item.path);
return template ? `/${template.name}` : this.formatDisplayPath(item.path);
},
});
const promptCompactList = () => formatCompactList(templates
.filter((template) => !isSystemResource(template.sourceInfo))
.map((template) => `/${template.name}`));
addLoadedSection("Prompts", promptCompactList, templateList);
}
if (extensions.length > 0) {
const groups = this.buildScopeGroups(extensions);
const extList = () => this.formatScopeGroups(groups, {
formatPath: (item) => this.formatExtensionDisplayPath(item.path),
formatPackagePath: (item) => this.formatExtensionDisplayPath(this.getShortPath(item.path, item.sourceInfo)),
});
const extensionLabels = this.getCompactExtensionLabels(extensions.filter((extension) => !isSystemResource(extension.sourceInfo)));
const extensionCompactList = () => formatCompactList(extensionLabels);
addLoadedSection("Extensions", extensionCompactList, extList, "mdHeading");
}
}
if (showDiagnostics) {
const addDiagnosticNotice = (title, diagnostics, why = "Conflicting or invalid loaded resources were found.") => {
this.loadedResourcesContainer.addChild(buildNoticeBox({
title,
tone: "warning",
why,
extra: this.formatDiagnostics(diagnostics, sourceInfos),
}, { expanded: this.toolOutputExpanded }, theme));
this.loadedResourcesContainer.addChild(new Spacer(1));
};
const contextDiagnostics = [
...(this.session.resourceLoader.getAgentsFiles().diagnostics ?? []),
...skillsResult.diagnostics.filter((diagnostic) => diagnostic.category === "size-limit"),
];
if (contextDiagnostics.length > 0) {
addDiagnosticNotice("Context size limits", contextDiagnostics, "Context files or skill catalogs were limited to keep requests bounded.");
}
const ignoredSkillDiagnostics = skillsResult.diagnostics.filter((diagnostic) => diagnostic.category === "skill-ignored");
if (ignoredSkillDiagnostics.length > 0) {
addDiagnosticNotice("Skills hidden by ignore files", ignoredSkillDiagnostics, "An ignore file in a skills folder lists these skill folders, so they did not load.");
}
const skillDiagnostics = skillsResult.diagnostics.filter((diagnostic) => diagnostic.category !== "size-limit" &&
diagnostic.category !== "skill-link-blocked" &&
diagnostic.category !== "skill-ignored");
if (skillDiagnostics.length > 0) {
addDiagnosticNotice("Skill conflicts", skillDiagnostics);
}
const promptDiagnostics = promptsResult.diagnostics;
if (promptDiagnostics.length > 0) {
addDiagnosticNotice("Prompt conflicts", promptDiagnostics);
}
const extensionDiagnostics = [];
const extensionsResult = this.session.resourceLoader.getExtensions();
for (const error of extensionsResult.errors) {
extensionDiagnostics.push({ type: "error", message: error.error, path: error.path });
}
for (const warning of extensionsResult.warnings ?? []) {
extensionDiagnostics.push({ type: "warning", message: warning.warning, path: warning.path });
}
const commandDiagnostics = this.session.extensionRunner.getCommandDiagnostics();
extensionDiagnostics.push(...commandDiagnostics);
extensionDiagnostics.push(...this.getBuiltInCommandConflictDiagnostics(this.session.extensionRunner));
const shortcutDiagnostics = this.session.extensionRunner.getShortcutDiagnostics();
extensionDiagnostics.push(...shortcutDiagnostics);
if (extensionDiagnostics.length > 0) {
addDiagnosticNotice("Extension issues", extensionDiagnostics);
}
const themeDiagnostics = themesResult.diagnostics;
if (themeDiagnostics.length > 0) {
addDiagnosticNotice("Theme conflicts", themeDiagnostics);
}
}
}
async bindCurrentSessionExtensions() {
this.mcpMrtrPresentationLifetime?.abort();
this.mcpMrtrPresentationLifetime = new AbortController();
this.mcpLocalPresenter = undefined;
await this.sessionControlHost?.disposeActive();
this.session.setControlEndpointHost?.(this.sessionControlHost);
const uiContext = this.createExtensionUIContext();
this.detachMcpGrantPresentation?.();
this.detachMcpGrantPresentation = attachMcpGrantPresentation(this.session.sessionId, (title, choices, opts) => uiContext.select(title, choices, opts));
this.unsubscribeSecurityNotices?.();
this.unsubscribeSecurityNotices = this.session.securityNotices?.subscribe((snapshot) => {
for (const notice of snapshot.notices)
uiContext.notify(notice.message, "warning");
});
await this.session.bindExtensions({
uiContext,
mode: "tui",
abortHandler: () => {
this.restoreQueuedMessagesToEditor({ abort: true });
},
commandContextActions: {
waitForIdle: () => this.session.waitForIdle(),
newSession: async (options) => {
this.clearStatusIndicator();
try {
return await this.runtimeHost.newSession(options);
}
catch (error) {
return this.handleFatalRuntimeError("Failed to create session", error);
}
},
fork: async (entryId, options) => {
try {
const result = await this.runtimeHost.fork(entryId, options);
if (!result.cancelled) {
this.editor.setText(result.selectedText ?? "");
this.showStatus("Forked to new session");
}
return { cancelled: result.cancelled };
}
catch (error) {
return this.handleFatalRuntimeError("Failed to fork session", error);
}
},
navigateTree: async (targetId, options) => {
const result = await this.session.navigateTree(targetId, {
summarize: options?.summarize,
customInstructions: options?.customInstructions,
replaceInstructions: options?.replaceInstructions,
label: options?.label,
expectedLeafId: options?.expectedLeafId,
});
if (result.cancelled) {
return { cancelled: true };
}
this.chatContainer.clear();
this.renderInitialMessages();
if (result.editorText && !this.editor.getText().trim()) {
this.editor.setText(result.editorText);
}
this.showStatus("Navigated to selected point");
void this.flushCompactionQueue({ willRetry: false });
return { cancelled: false };
},
editAssistantMessage: async (entryId, text, options) => {
const result = await this.session.editAssistantMessage(entryId, text, {
summarize: options?.summarize,
customInstructions: options?.customInstructions,
expectedLeafId: options?.expectedLeafId,
});
if (result.cancelled || result.unchanged) {
return { cancelled: result.cancelled, unchanged: result.unchanged };
}
this.chatContainer.clear();
this.renderInitialMessages();
this.showStatus("Replaced assistant response");
void this.flushCompactionQueue({ willRetry: false });
return { cancelled: false, entryId: result.entryId };
},
editUserMessage: async (entryId, text, options) => {
const result = await this.session.editUserMessage(entryId, text, {
summarize: options?.summarize,
customInstructions: options?.customInstructions,
expectedLeafId: options?.expectedLeafId,
});
if (result.cancelled || result.unchanged) {
return { cancelled: result.cancelled, unchanged: result.unchanged };
}
this.chatContainer.clear();
this.renderInitialMessages();
this.showStatus("Replaced user prompt");
void this.flushCompactionQueue({ willRetry: false });
return { cancelled: false, entryId: result.entryId };
},
switchSession: async (sessionPath, options) => {
return this.handleResumeSession(sessionPath, options);
},
reload: async () => {
await this.handleReloadCommand();
},
},
shutdownHandler: () => {
this.shutdownRequested = true;
if (this.session.isIdle) {
void this.shutdown();
}
},
onError: (error) => {
this.showExtensionError(error);
},
});
this.setExtensionStatus(PAUSE_STATUS_KEY, pauseFooterText(this.session));
setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
this.setupAutocompleteProvider();
const extensionRunner = this.session.extensionRunner;
this.setupExtensionShortcuts(extensionRunner);
this.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });
this.showStartupNoticesIfNeeded();
}
applyFullscreenScrollbarSetting() {
this.transcriptScrollView?.setScrollbar(this.settingsManager.getFullscreenScrollbar());
}
applyRuntimeSettings() {
setCapabilityOverrides(this.settingsManager.getTerminalCapabilityOverrides());
configureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs());
this.applyFullscreenScrollbarSetting();
if (this.renderer instanceof TuiAltScreen) {
this.renderer.setCopyOnSelect(this.settingsManager.getFullscreenCopyOnSelect?.() ?? true);
this.renderer.setWheelScrollLines(this.settingsManager.getFullscreenWheelScrollLines?.() ?? "auto");
}
this.footer.setSession(this.session);
this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);
this.footerDataProvider.setCwd(this.sessionManager.getCwd());
this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
this.outputPad = this.settingsManager.getOutputPad();
this.applySmoothStreamingRenderFps();
this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());
const clearOnShrink = this.settingsManager.getClearOnShrink();
this.ui.setClearOnShrink(clearOnShrink);
if (!clearOnShrink && !this.activeStatusIndicator) {
this.statusContainer.clear();
}
const editorPaddingX = this.settingsManager.getEditorPaddingX();
const autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();
this.defaultEditor.setPaddingX(editorPaddingX);
this.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);
if (this.editor !== this.defaultEditor) {
this.editor.setPaddingX?.(editorPaddingX);
this.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);
}
}
async rebindCurrentSession(options = {}) {
InteractiveMode.restoreCompactionEscapeOverride(this);
// A session switch/reset ends any external-owner delegation episode.
this.externalOwnerCompactionNoticeShown = false;
this.footer?.setCompactionDelegated?.(false);
const session = this.session;
this.agentSubscriptionGeneration++;
this.unsubscribe?.();
this.unsubscribe = undefined;
this.applyRuntimeSettings();
if (options.renderBeforeBind) {
this.renderCurrentSessionState();
this.subscribeToAgent();
time("render", "switch");
}
await this.bindCurrentSessionExtensions();
time("bindExtensions", "switch");
if (this.session !== session) {
return;
}
if (!options.renderBeforeBind) {
this.subscribeToAgent();
}
this.updateAvailableProviderCount();
this.updateEditorBorderColor();
this.updateTerminalTitle();
}
async handleFatalRuntimeError(prefix, error) {
const message = error instanceof Error ? error.message : String(error);
this.showError(`${prefix}: ${message}`);
const extensionHint = this.getCrashExtensionHint(error);
if (extensionHint) {
this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", extensionHint), this.outputPad, 0));
}
stopThemeWatcher();
this.stop("transcript");
process.exit(1);
}
getCrashExtensionHint(error) {
try {
return formatCrashExtensionHint(findExtensionStackMatches(error instanceof Error ? error.stack : undefined, this.session.resourceLoader.getExtensions().extensions));
}
catch {
return undefined;
}
}
renderCurrentSessionState() {
this.loadedResourcesContainer.clear();
this.chatContainer.clear();
this.pendingMessagesContainer.clear();
for (const controller of this.compactionTransferAbortControllers.values())
controller.abort();
this.compactionQueueGeneration += 1;
this.compactionQueueFlushTail = undefined;
this.compactionQueuedMessages = [];
this.compactionInFlightMessages = [];
this.compactionTransferAbortControllers.clear();
this.streamingReveal.stop();
this.toolResultReveal.stop();
this.streamingComponent = undefined;
this.streamingMessage = undefined;
this.assistantTextSegments.clear();
this.clearPendingTools();
this.clearToolHookStatuses();
this.renderInitialMessages();
}
/**
* Extension-registered definition, falling back to the built-in one. The renderer components take
* whatever this returns, so they never reach into the tool registry themselves.
*/
getRegisteredToolDefinition(toolName) {
// A question card can stream while a reload is in flight, when the registry no longer holds the
// ask-user tools and session_start has not re-synchronized them yet. Its renderers do not depend
// on the registration, so fall back to them instead of dumping the raw arguments.
return withBuiltInRenderers(toolName, this.session.getToolDefinition(toolName) ?? askUserRenderers(toolName));
}
getMarkdownTransformers() {
return [
this.mermaidMarkdownTransformer,
this.messagePathLinkTransformer,
...this.session.extensionRunner.getMarkdownTransformers(),
];
}
/**
* Set up keyboard shortcuts registered by extensions.
*/
setupExtensionShortcuts(extensionRunner) {
const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());
// Create a context for shortcut handlers
const createContext = () => ({
ui: this.createExtensionUIContext(),
mode: "tui",
hasUI: true,
cwd: this.sessionManager.getCwd(),
agentDir: this.session.agentDir,
sessionManager: this.sessionManager,
modelRegistry: extensionRunner.getModelRegistry(),
model: this.session.model,
serviceTier: this.session.serviceTier,
effectiveServiceTier: this.session.effectiveServiceTier,
scopedModels: this.session.scopedModels,
thinkingLevel: this.session.thinkingLevel,
isIdle: () => this.session.isIdle,
isProjectTrusted: () => this.settingsManager.isProjectTrusted(),
signal: this.session.agent.signal,
abort: () => this.session.abort(),
hasPendingMessages: () => this.session.pendingMessageCount > 0,
requestReload: () => this.handleReloadCommand(),
isCompacting: () => this.session.isCompacting,
shutdown: () => {
this.requestExtensionShutdown();
},
getContextUsage: () => this.session.getContextUsage(),
getCompactionSettings: () => this.settingsManager.getCompactionSettings(this.session.model),
getPromptCacheSafeWaitSeconds: () => this.session.resolvePromptCacheSafeWaitSeconds(),
getPromptCacheGoalBackstopMaxSeconds: () => this.settingsManager.getPromptCacheGoalBackstopMaxSeconds(),
getLookAtSettings: () => {
const global = this.settingsManager.getGlobalSettings().lookAt;
const project = this.settingsManager.getProjectSettings().lookAt;
return {
enabled: project?.enabled ?? global?.enabled ?? true,
models: project?.models ?? global?.models,
};
},
getImageSettings: () => ({
autoResize: this.settingsManager.getImageAutoResize(),
blockImages: this.settingsManager.getBlockImages(),
}),
sessionSettings: extensionRunner.createContext().sessionSettings,
compact: (options) => {
void (async () => {
try {
const result = await this.session.compact(options?.customInstructions);
options?.onComplete?.(result);
}
catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
options?.onError?.(err);
}
})();
},
getMessageRevision: () => this.session.getMessageRevision(),
applyCompaction: (precomputed, options) => this.session.applyCompaction(precomputed, options),
getSystemPrompt: () => this.session.systemPrompt,
});
// Set up the extension shortcut handler on the default editor
this.defaultEditor.onExtensionShortcut = (data) => {
if (this.handleAskUserShortcut(data))
return true;
for (const [shortcutStr, shortcut] of shortcuts) {
// Cast to KeyId - extension shortcuts use the same format
if (matchesKey(data, shortcutStr)) {
// Run handler async, don't block input
Promise.resolve(shortcut.handler(createContext())).catch((err) => {
this.showError(`Shortcut handler error: ${err instanceof Error ? err.message : String(err)}`);
});
return true;
}
}
return false;
};
}
async withBlockedHostDialog(id, label, show, opts) {
if (opts?.ephemeral) {
if (opts.signal?.aborted)
return undefined;
return await show();
}
// A dialog about a tool call is a permission request (ExtensionUIDialogOptions.toolCallId).
const kind = opts?.toolCallId === undefined ? {} : { kind: "permission" };
this.session.emitExtensionEvent("herdr:blocked", { active: true, label, id, ...kind });
try {
return await show();
}
finally {
this.session.emitExtensionEvent("herdr:blocked", { active: false, id });
}
}
/**
* Set extension status text in the footer.
*/
setExtensionStatus(key, text) {
this.footerDataProvider.setExtensionStatus(key, text);
this.ui.requestRender();
}
startToolHookStatusTimer() {
if (this.hookStatusIntervalId) {
return;
}
const intervalMs = largeSessionWorkingStatusInterval(this.sessionManager.getEntryCount(), DEFAULT_WORKING_STATUS_MESSAGE_ANIMATION_INTERVAL_MS, LARGE_SESSION_WORKING_STATUS_MESSAGE_INTERVAL_MS);
this.hookStatusIntervalId = setInterval(() => {
this.refreshToolHookStatuses();
}, intervalMs);
this.hookStatusIntervalId.unref();
}
stopToolHookStatusTimer() {
if (this.hookStatusIntervalId) {
clearInterval(this.hookStatusIntervalId);
this.hookStatusIntervalId = undefined;
}
}
refreshToolHookStatuses() {
this.hookStatusContainer.clear();
if (this.activeToolHooks.size === 0) {
this.stopToolHookStatusTimer();
this.ui.requestRender();
return;
}
const now = Date.now();
for (const hook of this.activeToolHooks.values()) {
const elapsedMs = Math.max(0, now - hook.startedAt);
const elapsedSeconds = Math.floor(elapsedMs / 1000);
this.hookStatusContainer.addChild(new Text(formatToolHookStatusMessageFrame(hook.hookName, hook.statusMessage, elapsedSeconds, elapsedMs, {
base: (text) => theme.fg("dim", text),
glow: (text) => theme.fg("text", text),
highlight: (text) => theme.bold(theme.fg("text", text)),
shimmer: formatWorkingStatusShimmerText,
suffix: (text) => theme.fg("dim", text),
}), 1, 0));
}
this.ui.requestRender();
}
handleToolHookStatusEvent(event) {
if (event.phase === "start") {
this.activeToolHooks.set(event.hookRunId, event);
this.activeToolTerminalTitle = formatToolHookTerminalTitle(event);
if (this.ui.terminal) {
this.applyTerminalTitle();
}
this.startToolHookStatusTimer();
this.refreshToolHookStatuses();
return;
}
if (event.phase === "update") {
const existing = this.activeToolHooks.get(event.hookRunId);
if (!existing) {
return;
}
const updated = { ...existing, statusMessage: event.statusMessage };
this.activeToolHooks.set(event.hookRunId, updated);
this.activeToolTerminalTitle = formatToolHookTerminalTitle(updated);
if (this.ui.terminal) {
this.applyTerminalTitle();
}
this.refreshToolHookStatuses();
return;
}
this.activeToolHooks.delete(event.hookRunId);
const nextHook = this.activeToolHooks.values().next().value;
this.activeToolTerminalTitle = nextHook ? formatToolHookTerminalTitle(nextHook) : undefined;
if (this.ui.terminal) {
this.applyTerminalTitle();
}
this.refreshToolHookStatuses();
}
handleToolExecutionStart(event) {
const label = formatActiveToolWorkingLabel(event.toolName, event.args);
if (this.activeToolExecutions.size === 0) {
this.workingMessageBeforeActiveTool = this.workingMessage;
}
this.activeToolExecutions.set(event.toolCallId, label);
this.workingMessage = label;
this.activeToolExecutionTerminalTitle = `${APP_TITLE} - ${label}`;
this.refreshWorkingLoaderMessage();
this.applyTerminalTitle();
}
handleToolExecutionEnd(event) {
if (!this.activeToolExecutions.delete(event.toolCallId)) {
return;
}
const nextExecution = this.activeToolExecutions.values().next();
if (!nextExecution.done) {
this.workingMessage = nextExecution.value;
this.activeToolExecutionTerminalTitle = `${APP_TITLE} - ${nextExecution.value}`;
}
else {
this.workingMessage = this.workingMessageBeforeActiveTool;
this.workingMessageBeforeActiveTool = undefined;
this.activeToolExecutionTerminalTitle = undefined;
}
this.refreshWorkingLoaderMessage();
this.applyTerminalTitle();
}
stopChatToolAnimations() {
for (const child of this.chatContainer.children) {
if (child instanceof ToolExecutionComponent)
child.stopAnimation();
}
}
clearPendingTools() {
this.toolArgsReveal.flushAll();
for (const component of this.pendingTools.values()) {
component.stopAnimation();
}
this.pendingTools.clear();
}
clearActiveToolExecutionStatus() {
if (this.activeToolExecutions.size === 0 &&
this.activeToolExecutionTerminalTitle === undefined &&
this.workingMessageBeforeActiveTool === undefined) {
return;
}
this.activeToolExecutions.clear();
this.activeToolExecutionTerminalTitle = undefined;
this.workingMessage = this.workingMessageBeforeActiveTool;
this.workingMessageBeforeActiveTool = undefined;
this.refreshWorkingLoaderMessage();
this.applyTerminalTitle();
}
clearToolHookStatuses() {
this.activeToolHooks.clear();
this.activeToolTerminalTitle = undefined;
if (this.ui.terminal) {
this.applyTerminalTitle();
}
this.hookStatusContainer.clear();
this.stopToolHookStatusTimer();
}
getWorkingElapsedSeconds() {
if (this.workingStartedAt === undefined) {
return 0;
}
return Math.max(0, Math.floor((Date.now() - this.workingStartedAt) / 1000));
}
getWorkingLoaderMessage() {
return this.workingMessage ?? this.defaultWorkingMessage;
}
refreshWorkingLoaderMessage() {
if (this.activeStatusIndicator?.kind === "working") {
this.activeStatusIndicator.setMessage(this.getWorkingLoaderMessage());
return;
}
const legacyLoader = this.loadingAnimation;
legacyLoader?.setMessage(this.getWorkingLoaderMessage());
}
getWorkingIndicatorOptions() {
if (this.workingIndicatorOptions !== undefined) {
return this.workingIndicatorOptions;
}
const sessionEntryCount = this.sessionManager.getEntryCount();
return {
frames: theme.getColorMode() === "truecolor" ? ["•"] : [theme.fg("accent", "•"), theme.fg("muted", "◦")],
intervalMs: largeSessionWorkingStatusInterval(sessionEntryCount, DEFAULT_WORKING_STATUS_REFRESH_INTERVAL_MS, LARGE_SESSION_WORKING_STATUS_REFRESH_INTERVAL_MS),
indicatorFormatter: theme.getColorMode() === "truecolor"
? (frame, elapsedMs) => formatWorkingStatusShimmerText(frame, elapsedMs)
: undefined,
messageFormatter: (message, animationElapsedMs) => formatWorkingStatusMessageFrame(message, this.getWorkingElapsedSeconds(), keyText("app.interrupt"), animationElapsedMs, {
base: (text) => theme.fg("dim", text),
glow: (text) => theme.fg("text", text),
highlight: (text) => theme.bold(theme.fg("text", text)),
shimmer: formatWorkingStatusShimmerText,
suffix: (text) => theme.fg("dim", text),
}),
messageIntervalMs: largeSessionWorkingStatusInterval(sessionEntryCount, DEFAULT_WORKING_STATUS_MESSAGE_ANIMATION_INTERVAL_MS, LARGE_SESSION_WORKING_STATUS_MESSAGE_INTERVAL_MS),
};
}
showStatusIndicator(indicator) {
if (indicator.kind === "working") {
this.workingStartedAt = Date.now();
}
this.activeStatusIndicator?.dispose();
this.activeStatusIndicator = indicator;
this.statusContainer.clear();
const embedded = embedStatusIndicatorInEditor(this.defaultEditor, this.editor, indicator);
this.activeWorkingIndicatorEmbedded = embedded;
// The spinner lives in the editor border when the editor opts in; the status row
// then only carries the optional working tip instead of a second spinner line.
const workingTip = indicator.kind === "working" ? this.resolveTurnWorkingTip() : undefined;
if (embedded) {
if (workingTip)
appendTipLine(this.statusContainer, theme.fg("dim", workingTip.line));
return;
}
if (!workingTip) {
this.statusContainer.addChild(indicator);
return;
}
const wrapper = new Container();
wrapper.addChild(indicator);
appendTipLine(wrapper, theme.fg("dim", workingTip.line));
this.statusContainer.addChild(wrapper);
}
resolveTurnWorkingTip() {
return this.turnWorkingTip.resolve(() => resolveWorkingTipLine({
tipsEnabled: this.settingsManager.getTipsEnabled(),
history: this.settingsManager.getTipsHistory(),
sessionShownTipIds: this.sessionShownTipIds,
now: Date.now(),
definitions: TIP_DEFINITIONS,
keys: keyText,
hasCommand: (command) => this.hasRegisteredCommand(command),
}), (tip) => this.recordShownTip(tip.tipId));
}
updateWorkingIndicatorMessage() {
if (this.activeStatusIndicator?.kind === "working") {
this.activeStatusIndicator.setMessage(this.workingMessage ?? this.defaultWorkingMessage);
}
}
clearStatusIndicator(kind) {
if (kind && this.activeStatusIndicator?.kind !== kind) {
return;
}
const hadActiveStatusIndicator = this.activeStatusIndicator !== undefined;
const isClearingWorking = this.activeStatusIndicator?.kind === "working";
const clearedIndicatorWasEmbedded = this.activeWorkingIndicatorEmbedded;
const shouldReserveHeight = hadActiveStatusIndicator && this.options.tuiMode === "regular" && this.ui.getClearOnShrink();
const renderedHeight = shouldReserveHeight ? this.statusContainer.render(this.ui.terminal.columns).length : 0;
this.activeStatusIndicator?.dispose();
this.activeStatusIndicator = undefined;
if (isClearingWorking) {
this.workingStartedAt = undefined;
}
this.activeWorkingIndicatorEmbedded = false;
this.statusContainer.clear();
embedStatusIndicatorInEditor(this.defaultEditor, this.editor, undefined);
// An embedded spinner occupied no status row, so only a rendered tip line is worth
// reserving; otherwise the placeholder would add rows that were never on screen.
if (shouldReserveHeight && (!clearedIndicatorWasEmbedded || renderedHeight > 0)) {
const idleHeight = Math.min(this.ui.terminal.rows, Math.max(1, renderedHeight || 2));
this.idleStatus.setHeight(idleHeight);
this.statusContainer.addChild(this.idleStatus);
}
}
showWorkingStatusIndicator() {
const colorFn = isWorkingStatusEditor(this.editor)
? (text) => (this.editor.borderColor ?? theme.getThinkingBorderColor(this.session.thinkingLevel || "off"))(text)
: undefined;
this.showStatusIndicator(new WorkingStatusIndicator(this.ui, this.workingMessage ?? this.defaultWorkingMessage, this.getWorkingIndicatorOptions(), colorFn));
}
setWorkingVisible(visible) {
this.workingVisible = visible;
if (!visible) {
this.clearStatusIndicator("working");
this.ui.requestRender();
return;
}
if (this.session.isStreaming && this.activeStatusIndicator?.kind !== "working") {
this.showStatusIndicator(this.chrome
? this.chrome.createWorkingIndicator(this.ui, this.workingMessage ?? this.defaultWorkingMessage, this.getWorkingIndicatorOptions())
: new WorkingStatusIndicator(this.ui, this.workingMessage ?? this.defaultWorkingMessage, this.getWorkingIndicatorOptions()));
}
this.ui.requestRender();
}
setWorkingIndicator(options) {
this.workingIndicatorOptions = options;
if (this.activeStatusIndicator?.kind === "working") {
this.activeStatusIndicator.setIndicator(this.getWorkingIndicatorOptions());
}
this.ui.requestRender();
}
setHiddenThinkingLabel(label) {
this.hiddenThinkingLabel = label ?? this.defaultHiddenThinkingLabel;
for (const child of this.chatContainer.children) {
if (child instanceof AssistantMessageComponent) {
child.setHiddenThinkingLabel(this.hiddenThinkingLabel);
}
}
if (this.streamingComponent) {
this.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel);
}
this.ui.requestRender();
}
/**
* Set an extension widget (string array or custom component).
*/
setExtensionWidget(key, content, options) {
const placement = options?.placement ?? "aboveEditor";
const targetMap = placement === "belowEditor" ? this.extensionWidgetsBelow : this.extensionWidgetsAbove;
const otherMap = placement === "belowEditor" ? this.extensionWidgetsAbove : this.extensionWidgetsBelow;
const removeFrom = (map) => {
const existing = map.get(key);
if (existing?.dispose)
existing.dispose();
map.delete(key);
};
removeFrom(otherMap);
if (content === undefined) {
removeFrom(targetMap);
this.renderWidgets();
return;
}
let component;
if (Array.isArray(content)) {
// Wrap string array in a Container with Text components
const container = new Container();
const shown = content.slice(0, InteractiveMode.MAX_WIDGET_LINES);
const actions = options?.actions ?? [];
for (const [index, line] of shown.entries()) {
if (index === shown.length - 1 && actions.length > 0) {
// The TUI cannot click, so each choice names the command that runs it, on the widget's last line.
const choices = actions.map((action) => `${action.label}: ${action.command}`).join(" · ");
container.addChild(new ThemedText(() => `${line} ${theme.fg("muted", choices)}`, 1, 0));
}
else {
container.addChild(new Text(line, 1, 0));
}
}
if (content.length > InteractiveMode.MAX_WIDGET_LINES) {
container.addChild(new ThemedText(() => theme.fg("muted", "... (widget truncated)"), 1, 0));
}
component = container;
}
else {
// Factory function - create component
component = content(this.ui, theme);
}
// Map.set on an existing key keeps its insertion position, so a refreshing widget stays
// put instead of moving past its neighbours and reshuffling the stacking order each paint.
const existing = targetMap.get(key);
if (existing?.dispose)
existing.dispose();
targetMap.set(key, component);
this.renderWidgets();
}
clearExtensionWidgets() {
for (const widget of this.extensionWidgetsAbove.values()) {
widget.dispose?.();
}
for (const widget of this.extensionWidgetsBelow.values()) {
widget.dispose?.();
}
this.extensionWidgetsAbove.clear();
this.extensionWidgetsBelow.clear();
this.renderWidgets();
}
resetExtensionUI() {
if (this.extensionSelector) {
this.hideExtensionSelector();
}
if (this.extensionInput) {
this.hideExtensionInput();
}
if (this.extensionEditor) {
this.hideExtensionEditor();
}
if (this.askUserQuestion) {
this.hideQuestionOverlay();
}
for (const state of this.pendingQuestions.values()) {
state.finish({
status: "cancelled",
answers: {},
unanswered: state.request.questions.map((question) => question.id),
});
}
this.ui.hideOverlay();
this.clearExtensionTerminalInputListeners();
this.setExtensionFooter(undefined);
this.setExtensionHeader(undefined);
this.clearExtensionWidgets();
this.footerDataProvider.clearExtensionStatuses(HOST_STATUS_KEYS);
this.footer.invalidate();
this.autocompleteProviderWrappers = [];
this.setCustomEditorComponent(undefined);
this.setupAutocompleteProvider();
this.defaultEditor.onExtensionShortcut = undefined;
this.activeToolExecutions.clear();
this.activeToolExecutionTerminalTitle = undefined;
this.workingMessageBeforeActiveTool = undefined;
this.extensionTerminalTitle = undefined;
this.updateTerminalTitle();
this.workingMessage = undefined;
this.workingVisible = true;
this.setWorkingIndicator();
this.updateWorkingIndicatorMessage();
this.setHiddenThinkingLabel();
this.clearToolHookStatuses();
}
// Maximum total widget lines to prevent viewport overflow
static { this.MAX_WIDGET_LINES = 10; }
/**
* Render all extension widgets to the widget container.
*/
renderWidgets() {
if (!this.widgetContainerAbove || !this.widgetContainerBelow)
return;
this.renderWidgetContainer(this.widgetContainerAbove, this.extensionWidgetsAbove, true, true);
this.renderWidgetContainer(this.widgetContainerBelow, this.extensionWidgetsBelow, false, false);
this.ui.requestRender();
}
renderWidgetContainer(container, widgets, spacerWhenEmpty, leadingSpacer) {
container.clear();
if (widgets.size === 0) {
if (spacerWhenEmpty) {
container.addChild(new Spacer(1));
}
return;
}
if (leadingSpacer) {
container.addChild(new Spacer(1));
}
for (const component of widgets.values()) {
container.addChild(component);
}
}
/**
* Set a custom footer component, or restore the built-in footer.
*/
setExtensionFooter(factory) {
// Dispose existing custom footer
if (this.customFooter?.dispose) {
this.customFooter.dispose();
}
this.footerContainer.clear();
if (factory) {
// Create and add custom footer, passing the data provider
this.customFooter = factory(this.ui, theme, this.footerDataProvider);
this.footerContainer.addChild(this.customFooter);
}
else {
// Restore built-in footer
this.customFooter = undefined;
this.footerContainer.addChild(this.footer);
}
this.ui.requestRender();
}
/**
* Set a custom header component, or restore the built-in header.
*/
setExtensionHeader(factory) {
// Header may not be initialized yet if called during early initialization
if (!this.builtInHeader) {
return;
}
// Dispose existing custom header
if (this.customHeader?.dispose) {
this.customHeader.dispose();
}
// Find the index of the current header in the header container
const currentHeader = this.customHeader || this.builtInHeader;
const index = this.headerContainer.children.indexOf(currentHeader);
if (factory) {
// Create and add custom header
this.customHeader = factory(this.ui, theme);
if (isExpandable(this.customHeader)) {
this.customHeader.setExpanded(this.toolOutputExpanded);
}
if (index !== -1) {
this.headerContainer.children[index] = this.customHeader;
}
else {
// If not found (e.g. builtInHeader was never added), add at the top
this.headerContainer.children.unshift(this.customHeader);
}
}
else {
// Restore built-in header
this.customHeader = undefined;
if (isExpandable(this.builtInHeader)) {
this.builtInHeader.setExpanded(this.toolOutputExpanded);
}
if (index !== -1) {
this.headerContainer.children[index] = this.builtInHeader;
}
}
this.ui.requestRender();
}
addExtensionTerminalInputListener(handler) {
const subscription = {
handler,
unsubscribe: this.ui.addInputListener((data) => (this.extensionInput?.secret ? undefined : handler(data))),
};
this.extensionTerminalInputSubscriptions.add(subscription);
return () => {
subscription.unsubscribe();
this.extensionTerminalInputSubscriptions.delete(subscription);
};
}
rebindExtensionTerminalInputListeners() {
for (const subscription of this.extensionTerminalInputSubscriptions) {
subscription.unsubscribe();
subscription.unsubscribe = this.ui.addInputListener((data) => this.extensionInput?.secret ? undefined : subscription.handler(data));
}
}
clearExtensionTerminalInputListeners() {
for (const subscription of this.extensionTerminalInputSubscriptions)
subscription.unsubscribe();
this.extensionTerminalInputSubscriptions.clear();
}
/**
* Create the ExtensionUIContext for extensions.
*/
createProjectTrustContext(cwd) {
const ui = this.createExtensionUIContext();
return {
cwd,
mode: "tui",
hasUI: true,
ui: {
select: ui.select,
confirm: ui.confirm,
input: ui.input,
notify: ui.notify,
},
};
}
createExtensionUIContext() {
this.mcpMrtrPresentationLifetime ??= new AbortController();
if (this.isShuttingDown)
this.mcpMrtrPresentationLifetime.abort();
const context = {
capabilities: { secretInput: true },
select: (title, options, opts) => this.withBlockedHostDialog(crypto.randomUUID(), title, () => this.showExtensionSelector(title, options, opts), opts),
confirm: async (title, message, opts) => (await this.withBlockedHostDialog(crypto.randomUUID(), title, () => this.showExtensionConfirm(title, message, opts), opts)) ?? false,
input: (title, placeholder, opts) => this.withBlockedHostDialog(crypto.randomUUID(), title, () => raceTerminalSecretInput(this.mcpLocalPresenter?.sealed, (local) => this.showExtensionInput(title, placeholder, local), title, placeholder, opts), opts?.secret ? { ...opts, ephemeral: true } : opts),
// Async answers are delivered by the ask-user extension, not here: the
// widget only resolves the question, so the model sees exactly one
// framed user message no matter which surface answered.
question: (request, opts) => request.waitForAnswer ? this.showQuestionOverlay(request, opts) : this.showAsyncQuestion(request, opts),
notify: (message, type) => this.showExtensionNotify(message, type),
onTerminalInput: (handler) => this.addExtensionTerminalInputListener(handler),
// The host owns the lifecycle status; an extension cannot overwrite or clear it.
setStatus: (key, text) => {
if (key !== LIFECYCLE_STATUS_KEY)
this.setExtensionStatus(key, text);
},
setSubagentCost: (costUsd) => {
this.footerDataProvider.setSubagentCost(costUsd);
this.ui.requestRender();
},
setWorkingMessage: (message) => {
this.workingMessage = message;
this.updateWorkingIndicatorMessage();
},
setWorkingVisible: (visible) => this.setWorkingVisible(visible),
setWorkingIndicator: (options) => this.setWorkingIndicator(options),
setHiddenThinkingLabel: (label) => this.setHiddenThinkingLabel(label),
setWidget: (key, content, options) => this.setExtensionWidget(key, content, options),
setFooter: (factory) => this.setExtensionFooter(factory),
setHeader: (factory) => this.setExtensionHeader(factory),
setTitle: (title) => {
this.extensionTerminalTitle = title;
this.applyTerminalTitle();
},
setProgramStatus: (status) => this.setProgramStatus(status),
custom: (factory, options) => this.showExtensionCustom(factory, options),
pasteToEditor: (text) => insertProgrammaticComposerInput(this.editor, `\x1b[200~${text}\x1b[201~`),
setEditorText: (text) => this.editor.setText(text),
getEditorText: () => this.getExpandedEditorText(),
editor: (title, prefill) => this.withBlockedHostDialog(crypto.randomUUID(), title, () => this.showExtensionEditor(title, prefill)),
addAutocompleteProvider: (factory) => {
this.autocompleteProviderWrappers.push(factory);
this.setupAutocompleteProvider();
},
setEditorComponent: (factory) => this.setCustomEditorComponent(factory),
getEditorComponent: () => this.editorComponentFactory,
get theme() {
return theme;
},
getAllThemes: () => getAvailableThemesWithPaths(),
getTheme: (name) => getThemeByName(name),
setTheme: (themeOrName) => {
if (themeOrName instanceof Theme) {
return this.themeController.setThemeInstance(themeOrName);
}
const result = this.themeController.setThemeName(themeOrName);
if (result.success) {
if (this.settingsManager.getTheme() !== themeOrName) {
this.settingsManager.setTheme(themeOrName);
}
}
return result;
},
getToolsExpanded: () => this.toolOutputExpanded,
setToolsExpanded: (expanded) => this.setToolsExpanded(expanded),
};
const presenterSession = this.session;
const privateForms = this.options?.mcpPresenterEnforcement === true
? (this.mcpLocalPresenter ??= registerLocalMcpPresenter(context, presenterSession.sessionId, this.mcpMrtrPresentationLifetime.signal, () => presenterSession.admitHumanAnswer()))
: undefined;
return registerMcpMrtrPresentation(context, this.mcpMrtrPresentationLifetime.signal, undefined, privateForms);
}
/**
* Show a selector for extensions.
*/
showExtensionSelector(title, options, opts) {
return new Promise((resolve) => {
if (opts?.signal?.aborted) {
resolve(undefined);
return;
}
const onAbort = () => {
this.hideExtensionSelector();
resolve(undefined);
};
opts?.signal?.addEventListener("abort", onAbort, { once: true });
this.extensionSelector = new ExtensionSelectorComponent(title, options, (option) => {
if (!opts?.ephemeral || !this.options?.mcpPresenterEnforcement)
this.session.admitHumanAnswer();
opts?.signal?.removeEventListener("abort", onAbort);
this.hideExtensionSelector();
resolve(option);
}, () => {
opts?.signal?.removeEventListener("abort", onAbort);
this.hideExtensionSelector();
resolve(undefined);
}, {
tui: this.ui,
timeout: opts?.timeout,
onToggleToolsExpanded: () => this.toggleToolOutputExpansion(),
});
this.disposeActiveSelector();
this.editorContainer.clear();
this.editorContainer.addChild(this.extensionSelector);
this.ui.setFocus(this.extensionSelector);
if (opts?.ephemeral && this.options?.mcpPresenterEnforcement) {
this.ui.renderNow();
markMcpFormPresented(opts);
}
else
this.ui.requestRender();
});
}
/**
* Hide the extension selector.
*/
hideExtensionSelector() {
this.extensionSelector?.dispose();
this.editorContainer.clear();
this.editorContainer.addChild(this.editor);
this.extensionSelector = undefined;
this.ui.setFocus(this.editor);
this.ui.requestRender();
}
/**
* Show a confirmation dialog for extensions.
*/
async showExtensionConfirm(title, message, opts) {
const result = await this.showExtensionSelector(`${title}\n${message}`, ["Yes", "No"], opts);
return result === "Yes";
}
async promptForMissingSessionCwd(error) {
const confirmed = await this.showExtensionConfirm("Session cwd not found", formatMissingSessionCwdPrompt(error.issue));
return confirmed ? error.issue.fallbackCwd : undefined;
}
/**
* Show a text input for extensions.
*/
showExtensionInput(title, placeholder, opts) {
const timeout = opts?.secret && !opts.signal?.aborted ? resolveSecretInputTimeout(opts) : opts?.timeout;
if (this.extensionInput?.secret)
this.hideExtensionInput();
return new Promise((resolve) => {
if (opts?.signal?.aborted) {
resolve(undefined);
return;
}
const onAbort = () => {
this.secretInputCleanup = undefined;
this.hideExtensionInput();
resolve(undefined);
};
opts?.signal?.addEventListener("abort", onAbort, { once: true });
this.extensionInput = new ExtensionInputComponent(title, placeholder, (value) => {
if (!opts?.ephemeral || !this.options?.mcpPresenterEnforcement)
this.session.admitHumanAnswer();
opts?.signal?.removeEventListener("abort", onAbort);
this.secretInputCleanup = undefined;
this.hideExtensionInput();
resolve(value);
}, () => {
opts?.signal?.removeEventListener("abort", onAbort);
this.secretInputCleanup = undefined;
this.hideExtensionInput();
resolve(undefined);
}, { tui: this.ui, timeout, secret: opts?.secret });
this.disposeActiveSelector();
if (opts?.secret)
this.secretInputCleanup = () => {
opts.signal?.removeEventListener("abort", onAbort);
resolve(undefined);
};
this.editorContainer.clear();
this.editorContainer.addChild(this.extensionInput);
this.ui.setFocus(this.extensionInput);
this.ui.requestRender();
});
}
/**
* Hide the extension input.
*/
hideExtensionInput() {
const cleanup = this.secretInputCleanup;
this.secretInputCleanup = undefined;
this.extensionInput?.dispose();
cleanup?.();
this.editorContainer.clear();
this.editorContainer.addChild(this.editor);
this.extensionInput = undefined;
this.ui.setFocus(this.editor);
this.ui.requestRender();
}
/**
* Show a multi-line editor for extensions (with Ctrl+G support).
*/
showExtensionEditor(title, prefill) {
return new Promise((resolve) => {
this.extensionEditor = new ExtensionEditorComponent(this.ui, this.keybindings, title, prefill, (value) => {
this.session.admitHumanAnswer();
this.hideExtensionEditor();
resolve(value);
}, () => {
this.hideExtensionEditor();
resolve(undefined);
}, undefined, this.settingsManager.getExternalEditorCommand());
this.disposeActiveSelector();
this.editorContainer.clear();
this.editorContainer.addChild(this.extensionEditor);
this.ui.setFocus(this.extensionEditor);
this.ui.requestRender();
});
}
/**
* Hide the extension editor.
*/
hideExtensionEditor() {
this.editorContainer.clear();
this.editorContainer.addChild(this.editor);
this.extensionEditor = undefined;
this.ui.setFocus(this.editor);
this.ui.requestRender();
}
/**
* Show the ask-user multi-question overlay in place of the editor.
*/
showQuestionOverlay(request, opts) {
return new Promise((resolve) => {
let settled = false;
const previousWorkingMessage = this.workingMessage;
const finish = (response) => {
if (settled)
return;
if (request.waitForAnswer && opts?.deliver !== "user-message" && response.resolvedBy === "local_ui")
this.session.admitHumanAnswer();
settled = true;
opts?.signal?.removeEventListener("abort", onAbort);
this.workingMessage = previousWorkingMessage;
this.updateWorkingIndicatorMessage();
this.blockingQuestionHeader = undefined;
this.applyTerminalTitle();
this.hideQuestionOverlay();
resolve(response);
};
const onAbort = () => {
finish({
status: "cancelled",
answers: {},
unanswered: request.questions.map((question) => question.id),
});
};
if (opts?.signal?.aborted) {
resolve({
status: "cancelled",
answers: {},
unanswered: request.questions.map((question) => question.id),
});
return;
}
opts?.signal?.addEventListener("abort", onAbort, { once: true });
this.blockingQuestionHeader = request.questions[0]?.header;
this.applyTerminalTitle();
if (this.settingsManager.getAskUserSettings().bell)
this.ui.terminal.write("\x07");
this.workingMessage = "Waiting for your answer";
this.updateWorkingIndicatorMessage();
this.askUserQuestion = new AskUserQuestionComponent(request, (response) => finish(response), {
tui: this.ui,
timeoutMs: opts?.timeout ?? request.timeoutMs,
getDeadlineAtMs: opts?.getDeadlineAtMs,
initialDraft: opts?.initialDraft,
onProgress: opts?.onProgress,
});
this.disposeActiveSelector();
this.editorContainer.clear();
this.editorContainer.addChild(this.askUserQuestion);
this.syncQuestionMouseCapture();
this.ui.setFocus(this.askUserQuestion);
this.ui.requestRender();
});
}
/**
* Hide the ask-user question overlay and restore the editor.
*/
hideQuestionOverlay() {
this.askUserQuestion?.dispose();
this.askUserQuestion = undefined;
this.syncQuestionMouseCapture();
this.questionSurface = "collapsed";
this.editorContainer.clear();
this.editorContainer.addChild(this.editor);
this.ui.setFocus(this.editor);
this.ui.requestRender();
}
/** Queue an async request without replacing another request or taking editor focus. */
showAsyncQuestion(request, opts) {
const existing = this.pendingQuestions.get(request.requestId);
if (existing)
return existing.completion;
const cancelled = () => ({
status: "cancelled",
answers: {},
unanswered: request.questions.map((question) => question.id),
});
if (opts?.signal?.aborted)
return Promise.resolve(cancelled());
const completion = Promise.withResolvers();
const onAbort = () => state.finish(cancelled());
const state = {
request,
timeoutMs: opts?.timeout ?? request.timeoutMs,
askedAtMs: Date.now(),
completion: completion.promise,
getDeadlineAtMs: opts?.getDeadlineAtMs,
onProgress: opts?.onProgress,
draft: opts?.initialDraft ?? { answers: {} },
finish: (response) => {
if (this.pendingQuestions.get(request.requestId) !== state)
return;
this.pendingQuestions.delete(request.requestId);
this.pendingOrder = this.pendingOrder.filter((id) => id !== request.requestId);
opts?.signal?.removeEventListener("abort", onAbort);
if (this.composerDestination.kind === "answer" &&
this.composerDestination.requestId === request.requestId) {
this.setComposerReply();
if (this.editor.getText() !== "")
this.showStatus("That question is no longer pending");
}
if (this.pendingOrder.length === 0 && this.questionSurface === "list") {
this.ui.hideOverlay();
this.questionSurface = "collapsed";
}
if (this.shownQuestionId === request.requestId) {
if (this.questionSurface === "expanded")
this.hideQuestionOverlay();
this.shownQuestionId = this.pendingOrder[0];
}
this.refreshAsyncWidget();
completion.resolve(response);
},
};
this.pendingQuestions.set(request.requestId, state);
this.pendingOrder.push(request.requestId);
this.shownQuestionId ??= request.requestId;
if (this.settingsManager.getAskUserSettings().bell)
this.ui.terminal.write("\x07");
opts?.signal?.addEventListener("abort", onAbort, { once: true });
this.refreshAsyncWidget();
return completion.promise;
}
sessionControlContext() {
const account = this.options?.presenterAccountAuthority;
return {
...(this.mcpLocalPresenter && {
mcpPresenter: { local: this.mcpLocalPresenter, ...(account && { account }) },
}),
session: this.session,
agentDir: this.session.agentDir,
surface: {
submissionInFlight: () => this.sessionControlHost.submissionInFlight(),
hasDraft: () => this.hasComposerDraft(),
blockingQuestion: () => this.askUserQuestion !== undefined,
pendingQuestionIds: () => [...this.pendingQuestions.keys()],
pendingQuestion: (requestId) => this.pendingQuestions.get(requestId)?.request,
answerQuestion: (requestId, response) => {
const state = this.pendingQuestions.get(requestId);
state?.finish(response);
return state !== undefined;
},
notice: (line) => this.showWarning(line),
selectModel: (model) => InteractiveMode.applyModelSelection(this, model, { source: "control" }),
selectThinkingLevel: (level, remember) => InteractiveMode.applyThinkingLevel(this, level, remember),
interruptTurn: async () => {
await this.abortAndFireQueuedMessages();
},
// After the close's answer is on its way: the quit path disposes the endpoint that sends it.
closeSession: () => setImmediate(() => void this.shutdown()),
},
};
}
/** Whether the user is composing (non-blank text or pending images); a delivery never waits for it (senpi#7043). */
hasComposerDraft() {
return this.pendingImages.size > 0 || this.editor.getText().trim() !== "";
}
/** Only the visible surface ticks; extension deadlines remain authoritative. */
refreshAsyncWidget() {
this.sessionControlHost?.questionsChanged();
this.syncQuestionMouseCapture();
this.applyTerminalTitle();
const state = this.shownQuestion;
if (!state || this.questionSurface === "expanded") {
this.setExtensionWidget(ASK_USER_WIDGET_KEY, undefined);
return;
}
this.setExtensionWidget(ASK_USER_WIDGET_KEY, (tui) => new AskUserAsyncWidget({
request: state.request,
draft: state.draft,
timeoutMs: state.timeoutMs,
getDeadlineAtMs: state.getDeadlineAtMs,
pendingCount: this.pendingOrder.length,
tui,
mouseCaptureActive: this.terminalMouseMode !== "off",
onExpandClick: () => this.expandPendingQuestion(state.request.requestId),
onNextQuestion: () => this.cyclePendingQuestion(),
onOptionClick: (index) => this.clickPendingQuestion(state, index),
onOwnAnswerClick: () => this.clickPendingQuestion(state, "own-answer"),
onExpire: () => state.finish(buildTimedOutResponse(state.request, state.draft, Date.now() - state.askedAtMs)),
}));
}
cyclePendingQuestion() {
if (this.pendingOrder.length < 2)
return;
const index = this.pendingOrder.indexOf(this.shownQuestionId);
this.shownQuestionId = this.pendingOrder[(index + 1) % this.pendingOrder.length];
this.refreshAsyncWidget();
}
clickPendingQuestion(state, option) {
const unanswered = unansweredIds(state.request, state.draft);
const index = state.request.questions.findIndex((question) => question.id === unanswered[0]);
// Nothing left to answer: the click submits the draft instead of re-answering a question.
if (index < 0) {
state.finish(buildAnsweredResponse(state.request, state.draft));
return;
}
if (!this.expandPendingQuestion(state.request.requestId, index))
return;
if (option === "own-answer")
this.askUserQuestion.openOwnAnswer();
else
this.askUserQuestion.clickOption(option, true);
}
/** Intercept question chords and first typed input before the editor inserts it. */
handleAskUserShortcut(data) {
const state = this.shownQuestion;
if (!state ||
this.askUserQuestion ||
this.ui.hasOverlay() ||
this.extensionSelector ||
this.extensionInput ||
this.extensionEditor)
return false;
if (matchesAskUserAnswerKey(data))
return this.expandPendingQuestion();
if (this.editor.getText() !== "" ||
this.ui.getFocusedComponent() !== this.editor ||
this.defaultEditor.isShowingAutocomplete())
return false;
if (this.keybindings.matches(data, "app.question.next")) {
if (this.pendingOrder.length < 2)
return false;
this.cyclePendingQuestion();
return true;
}
const unanswered = unansweredIds(state.request, state.draft);
const questionIndex = state.request.questions.findIndex((question) => question.id === unanswered[0]);
const question = state.request.questions[questionIndex];
if (/^[1-9]$/.test(data) && question?.options[Number(data) - 1]) {
this.expandPendingQuestion(state.request.requestId, questionIndex, data);
return true;
}
const printable = decodeKittyPrintable(data) ?? data;
if (data.startsWith("\x1b[200~") ||
(printable !== "" && !/[\x00-\x1f\x7f]/.test(printable) && !/^[/!]/.test(printable))) {
this.setComposerReply(state.request.requestId);
}
return false;
}
setComposerReply(requestId) {
this.composerDestination = requestId === undefined ? { kind: "chat" } : { kind: "answer", requestId };
const state = requestId === undefined ? undefined : this.pendingQuestions.get(requestId);
this.defaultEditor.setReplyLabel(state
? theme.fg("muted", `↳ reply to ${state.request.questions[0].header} · ${keyText("app.message.followUp")} sends as message`)
: undefined);
this.ui.requestRender();
}
async handleAnswerCommand(argument) {
const state = this.shownQuestion;
if (!state) {
this.showStatus("No question is pending.");
return;
}
if (argument === "skip") {
const response = {
status: "cancelled",
cancelOrigin: "user",
answers: state.draft.answers ?? {},
unanswered: unansweredIds(state.request, state.draft),
};
state.finish(response);
await state.completion;
this.showStatus("The user dismissed the question.");
// The builtin delivers the partial answers of a cancel the user chose; sending them here too
// would reach the model twice. With nothing answered the builtin stays silent, so this
// explicit command acknowledges the dismissal, including on host bridges.
if (showsPartialAnswers(response))
return;
await this.session.sendUserMessage(formatUserMessage(response, state.request.requestId, state.request.questions, state.request.required === true), {
deliverAs: this.session.isStreaming ? "steer" : "followUp",
});
return;
}
if (argument !== "") {
const id = /^[1-9]\d*$/.test(argument) ? this.pendingOrder[Number(argument) - 1] : undefined;
if (id === undefined) {
this.showStatus("Choose a pending question number or /answer skip.");
return;
}
this.expandPendingQuestion(id);
return;
}
if (this.pendingOrder.length === 1) {
this.expandPendingQuestion();
return;
}
const list = new SelectList(this.pendingOrder.map((id) => {
const pending = this.pendingQuestions.get(id);
const remaining = (pending.getDeadlineAtMs?.() ?? pending.askedAtMs + pending.timeoutMs) - Date.now();
return {
value: id,
label: `${pending.request.questions[0].header} · ${formatCountdownLabel(Date.now() - pending.askedAtMs)} ago · ${formatCountdownLabel(remaining)} remaining`,
};
}), 10, getSelectListTheme());
const close = () => {
this.ui.hideOverlay();
this.questionSurface = "collapsed";
};
list.onCancel = close;
list.onSelect = ({ value }) => {
close();
this.expandPendingQuestion(value);
};
this.questionSurface = "list";
this.ui.showOverlay(list, { width: "80%", anchor: "bottom-center" });
}
/**
* Key-free entry into the pending async question (empty Enter, /answer):
* mounts the full component in place of the editor. Returns false when
* nothing is pending or the component is already open.
*/
expandPendingQuestion(requestId = this.shownQuestionId, initialQuestionIndex, initialInput) {
const state = requestId === undefined ? undefined : this.pendingQuestions.get(requestId);
if (!state || this.askUserQuestion)
return false;
this.shownQuestionId = state.request.requestId;
const component = new AskUserQuestionComponent(state.request, (response) => {
if (this.pendingQuestions.get(state.request.requestId) !== state)
return;
if (response.status !== "cancelled") {
state.finish(response);
return;
}
// Esc collapses back to the widget; the question stays pending.
this.hideQuestionOverlay();
this.refreshAsyncWidget();
}, {
tui: this.ui,
timeoutMs: state.timeoutMs,
getDeadlineAtMs: state.getDeadlineAtMs,
initialDraft: state.draft,
initialQuestionIndex,
onProgress: (draft) => {
state.draft = draft;
state.onProgress?.(draft);
},
});
this.askUserQuestion = component;
this.questionSurface = "expanded";
this.refreshAsyncWidget();
this.disposeActiveSelector();
this.editorContainer.clear();
this.editorContainer.addChild(component);
this.ui.setFocus(component);
this.ui.requestRender();
if (initialInput !== undefined)
component.handleInput(initialInput);
return true;
}
/**
* Ordinary composer text while an async question is pending is the comment
* answer: resolve the question with it and let the framed message replace
* the raw text. Returns false when nothing is pending.
*/
submitAsyncQuestionComment(text) {
const destination = this.composerDestination;
const state = destination.kind === "answer" ? this.pendingQuestions.get(destination.requestId) : undefined;
if (!state)
return false;
this.setComposerReply();
this.editor.addToHistory?.(text);
this.editor.setText("");
state.finish(buildCommentResponse(state.request, state.draft, text));
return true;
}
/**
* Full editor text with paste markers expanded. Prefers the editor's own
* getExpandedText(); falls back to expanding from the paste snapshot when
* only getPasteState() is implemented, then to the raw text (an editor
* with neither capability never had expandable markers).
*/
getExpandedEditorText() {
return expandEditorSubmission(this.editor, this.editor.getText());
}
/**
* Set a custom editor component from an extension.
* Pass undefined to restore the default editor.
*/
setCustomEditorComponent(factory) {
this.editorComponentFactory = factory;
if (!factory && this.editor === this.defaultEditor)
return;
// Save text from current editor before switching. Paste markers must not
// be transferred as raw text alone: the destination editor instance has no
// paste registry, so a bare marker would become dead literal text and the
// pasted content would be silently lost on submit. When both editors
// support the paste-state API, transfer the registry so markers stay
// collapsed; otherwise fall back to the expanded text.
this.disposeActiveSelector();
this.editorContainer.clear();
if (factory) {
// Create the custom editor with tui, theme, and keybindings
const newEditor = factory(this.ui, this.chrome ? this.chrome.getEditorTheme() : getEditorTheme(), this.keybindings);
// Wire up callbacks from the default editor
newEditor.onSubmit = (text) => {
this.defaultEditor.onSubmit?.(expandSubmittedText(newEditor, text));
};
newEditor.onChange = (text) => this.defaultEditor.onChange?.(text);
observeComposerActivity(newEditor, () => emitUserActivity(this.session, "draft"));
// Copy text (and any collapsed paste/image markers) from previous editor.
// Image payloads live on this instance, so they must be dropped when the
// destination cannot own their markers.
if (!transferEditorContent(this.editor, newEditor).imageMarkersTransferred) {
this.pendingImages.clear();
}
this.subscribeImageMarkers(newEditor);
// Copy appearance settings if supported
if (newEditor.borderColor !== undefined) {
newEditor.borderColor = this.defaultEditor.borderColor;
}
if (newEditor.setPaddingX !== undefined) {
newEditor.setPaddingX(this.defaultEditor.getPaddingX());
}
if (newEditor.setAutocompleteMaxVisible !== undefined) {
newEditor.setAutocompleteMaxVisible(this.defaultEditor.getAutocompleteMaxVisible());
}
// Set autocomplete if supported
if (newEditor.setAutocompleteProvider && this.autocompleteProvider) {
newEditor.setAutocompleteProvider(this.autocompleteProvider);
}
const customEditor = newEditor;
if ("actionHandlers" in customEditor && customEditor.actionHandlers instanceof Map) {
if (!customEditor.onEscape) {
customEditor.onEscape = () => this.defaultEditor.onEscape?.();
}
if (!customEditor.onCtrlD) {
customEditor.onCtrlD = () => this.defaultEditor.onCtrlD?.();
}
if (!customEditor.onPasteImage) {
customEditor.onPasteImage = () => this.defaultEditor.onPasteImage?.();
}
if (!customEditor.onExtensionShortcut) {
customEditor.onExtensionShortcut = (data) => this.defaultEditor.onExtensionShortcut?.(data);
}
adoptDefaultEditorActions(this.defaultEditor, customEditor);
}
this.editor = newEditor;
}
else {
// Restore default editor with text from custom editor. Skip the
// transfer when the default editor is already active (e.g.
// resetExtensionUI() calls this unconditionally): there is no
// hand-off, and a setText round-trip would be pure churn on the
// user's draft.
if (this.editor !== this.defaultEditor) {
if (!transferEditorContent(this.editor, this.defaultEditor).imageMarkersTransferred) {
this.pendingImages.clear();
}
this.subscribeImageMarkers(this.defaultEditor);
}
this.editor = this.defaultEditor;
}
this.editorContainer.addChild(this.editor);
if (this.activeStatusIndicator) {
this.statusContainer.clear();
this.activeWorkingIndicatorEmbedded = embedStatusIndicatorInEditor(this.defaultEditor, this.editor, this.activeStatusIndicator);
if (!this.activeWorkingIndicatorEmbedded) {
this.statusContainer.addChild(this.activeStatusIndicator);
}
}
this.ui.setFocus(this.editor);
this.ui.requestRender();
}
/**
* Show a notification for extensions.
*/
showExtensionNotify(message, type) {
if (type === "error") {
this.showError(message);
}
else if (type === "warning") {
this.showWarning(message);
}
else {
this.showStatus(message);
}
}
/** Show a custom component with keyboard focus. Overlay mode renders on top of existing content. */
async showExtensionCustom(factory, options) {
const savedText = this.editor.getText();
const isOverlay = options?.overlay ?? false;
const restoreEditor = () => {
this.editorContainer.clear();
this.editorContainer.addChild(this.editor);
this.editor.setText(savedText);
this.ui.setFocus(this.editor);
this.ui.requestRender();
};
return new Promise((resolve, reject) => {
let component;
let closed = false;
const close = (result) => {
if (closed)
return;
closed = true;
if (isOverlay)
this.ui.hideOverlay();
else
restoreEditor();
// Note: both branches above already call requestRender
resolve(result);
try {
component?.dispose?.();
}
catch {
/* ignore dispose errors */
}
};
Promise.resolve(factory(this.ui, theme, this.keybindings, close))
.then((c) => {
if (closed)
return;
component = c;
if (isOverlay) {
// Resolve overlay options - can be static or dynamic function
const resolveOptions = () => {
if (options?.overlayOptions) {
const opts = typeof options.overlayOptions === "function"
? options.overlayOptions()
: options.overlayOptions;
return opts;
}
// Fallback: use component's width property if available
const w = component.width;
return w ? { width: w } : undefined;
};
const overlayOptions = resolveOptions();
const handle = this.ui.showOverlay(component, overlayOptions);
// Expose handle to caller for visibility control
options?.onHandle?.(handle);
}
else {
this.disposeActiveSelector();
this.editorContainer.clear();
this.editorContainer.addChild(component);
this.ui.setFocus(component);
this.ui.requestRender();
}
})
.catch((err) => {
if (closed)
return;
if (!isOverlay)
restoreEditor();
reject(err);
});
});
}
/**
* Show an extension error in the UI.
*/
showExtensionError(error) {
const errorMsg = formatExtensionErrorHeadline(error);
const errorText = new ThemedText(() => theme.fg("error", errorMsg), 1, 0);
this.chatContainer.addChild(errorText);
if (error.stack) {
// Show stack trace in dim color, indented
const stackLines = error.stack.split("\n").slice(1); // Skip first line (duplicates error message)
if (stackLines.length > 0) {
const renderStack = () => stackLines.map((line) => theme.fg("dim", ` ${line.trim()}`)).join("\n");
this.chatContainer.addChild(new ThemedText(renderStack, 1, 0));
}
}
this.ui.requestRender();
}
// =========================================================================
// Key Handlers
// =========================================================================
setupKeyHandlers() {
// Set up handlers on defaultEditor - they use this.editor for text access
// so they work correctly regardless of which editor is active
this.defaultEditor.onEscape = () => {
this.refusedUnknownCommandText = undefined;
if (this.session.isStreaming || this.session.retryAttempt > 0) {
void this.abortAndFireQueuedMessages().catch((error) => this.showError(error instanceof Error ? error.message : String(error)));
}
else if (this.session.isBashRunning) {
this.session.abortBash();
}
else if (this.isBashMode) {
this.editor.setText("");
this.isBashMode = false;
this.updateEditorBorderColor();
}
else if (!this.editor.getText().trim()) {
// Double-escape with empty editor triggers /tree, /fork, or nothing based on setting
const action = this.settingsManager.getDoubleEscapeAction();
if (action !== "none") {
const now = Date.now();
if (now - this.lastEscapeTime < 500) {
if (action === "tree") {
this.showTreeSelector();
}
else {
void this.showUserMessageSelector().catch((error) => this.showError(error instanceof Error ? error.message : String(error)));
}
this.lastEscapeTime = 0;
}
else {
this.lastEscapeTime = now;
}
}
}
};
// Register app action handlers
this.defaultEditor.onAction("app.clear", () => this.handleCtrlC());
this.defaultEditor.onCtrlD = () => this.handleCtrlD();
this.defaultEditor.onAction("app.suspend", () => this.handleCtrlZ());
this.defaultEditor.onAction("app.thinking.cycle", () => {
void this.cycleThinkingLevel().catch((error) => this.showError(error instanceof Error ? error.message : String(error)));
});
this.defaultEditor.onAction("app.model.cycleForward", () => this.cycleModel("forward"));
this.defaultEditor.onAction("app.model.cycleBackward", () => this.cycleModel("backward"));
// Global debug handler on TUI (works regardless of focus)
this.ui.onDebug = () => this.handleDebugCommand();
this.defaultEditor.onAction("app.model.select", () => this.showModelSelector());
this.defaultEditor.onAction("app.history.search", async () => {
try {
await this.session.prompt("/history");
}
catch (error) {
this.showError(`Failed to open history search: ${error instanceof Error ? error.message : String(error)}`);
}
});
this.defaultEditor.onAction("app.tools.expand", () => this.toggleToolOutputExpansion());
this.defaultEditor.onAction("app.thinking.toggle", () => this.toggleThinkingBlockVisibility());
this.defaultEditor.onAction("app.editor.external", () => void this.handleOpenExternalEditor());
this.defaultEditor.onAction("app.message.copy", () => void this.handleCopyCommand({ flashConfirmation: true, preferSelection: true }));
this.defaultEditor.onAction("app.message.followUp", () => this.handleFollowUp());
this.defaultEditor.onAction("app.message.dequeue", () => this.handleDequeue());
this.defaultEditor.onAction("app.session.new", () => this.handleClearCommand());
this.defaultEditor.onAction("app.session.tree", () => this.showTreeSelector());
this.defaultEditor.onAction("app.session.fork", () => void this.showUserMessageSelector().catch((error) => this.showError(error instanceof Error ? error.message : String(error))));
this.defaultEditor.onAction("app.session.resume", () => this.showSessionSelector());
this.defaultEditor.onAction("app.session.renameCurrent", () => this.showSessionRenameInput());
this.defaultEditor.onChange = (text) => {
const wasBashMode = this.isBashMode;
this.isBashMode = text.trimStart().startsWith("!");
if (wasBashMode !== this.isBashMode) {
this.updateEditorBorderColor();
}
this.updateShortcutOverlay(text);
};
// Keep pendingImages aligned with the markers the editor displays.
this.subscribeImageMarkers(this.defaultEditor);
// Handle clipboard paste (triggered on Ctrl+V). Copied files use their original paths, images are
// attached in memory behind an atomic `[Image #N]` marker, and plain text is the final fallback.
this.defaultEditor.onPasteImage = () => {
this.lastInputWasPaste = true;
void this.handleClipboardPaste();
};
const previousEscapeHandler = this.defaultEditor.onEscape;
this.defaultEditor.onEscape = () => {
this.hideShortcutOverlay();
previousEscapeHandler?.();
};
}
async handleRightClickPaste() {
const target = this.renderer.getFocusedComponent();
const handleInput = target?.handleInput;
if (!target || !handleInput)
return;
try {
const text = await readClipboardText();
if (!text || this.renderer.getFocusedComponent() !== target)
return;
handleInput.call(target, `\x1b[200~${text}\x1b[201~`);
this.ui.requestRender();
}
catch {
// Silently ignore clipboard errors (may not have permission, etc.)
}
}
async handleClipboardPaste() {
try {
const filePaths = await readClipboardFilePaths();
if (filePaths) {
if (filePaths.some((filePath) => /\p{Cc}/u.test(filePath))) {
throw new Error("Clipboard file path contains control characters");
}
const paths = this.isBashMode ? filePaths.map(quoteIfNeeded).join(" ") : filePaths.join("\n");
const cursor = this.editor.getCursor?.();
const currentLine = cursor ? (this.editor.getText().split("\n")[cursor.line] ?? "") : "";
const characterBeforeCursor = cursor && cursor.col > 0 ? currentLine[cursor.col - 1] : "";
const characterAfterCursor = cursor ? currentLine[cursor.col] : "";
const leadingSpace = characterBeforeCursor && !/\s/.test(characterBeforeCursor) ? " " : "";
const trailingSpace = characterAfterCursor && !/\s/.test(characterAfterCursor) ? " " : "";
this.editor.insertTextAtCursor?.(`${leadingSpace}${paths}${trailingSpace}`);
emitUserActivity(this.session, "draft");
this.ui.requestRender();
return;
}
const image = await readClipboardImage();
const attached = image &&
(await attachClipboardImage({
editor: this.editor,
pendingImages: this.pendingImages,
settings: this.settingsManager,
isCompacting: () => this.session?.isCompacting === true,
showStatus: (message) => this.showStatus(message),
requestRender: () => this.ui.requestRender(),
}, image));
if (attached) {
if (attached === "attached")
emitUserActivity(this.session, "draft");
return;
}
const text = await readClipboardText();
if (text) {
this.editor.insertTextAtCursor?.(text);
emitUserActivity(this.session, "draft");
this.ui.requestRender();
}
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
// `?.` guards keep this handler callable on a minimal borrowed receiver
// ({ editor, ui }) - the contract upstream's clipboard tests pin; a full
// InteractiveMode instance still logs to the session log and shows the
// status line.
this.getSessionLogger?.().warn("clipboard_error", {
op: "paste",
error: message,
});
this.showStatus?.(`Clipboard paste failed: ${sanitizeTuiErrorMessage(message)}`);
}
}
/** Route an editor's image-marker changes into {@link reconcilePendingImages}. */
subscribeImageMarkers(editor) {
if (!editor.insertImageMarker)
return;
editor.onImageMarkersChanged = (order) => this.reconcilePendingImages(order);
// The editor's undo stack restores marker TEXT and registry ids, but the
// payloads live HERE; mirror them into every undo snapshot so undo restores
// both halves of the pairing. Without this, deleting a marker re-keys the
// survivors onto its number and a later undo re-displays the deleted marker
// with no (or the wrong) payload behind it.
editor.snapshotAttachmentState = () => new Map(this.pendingImages);
editor.restoreAttachmentState = (state) => {
if (!(state instanceof Map))
return;
this.pendingImages.clear();
for (const [key, image] of state) {
this.pendingImages.set(key, image);
}
};
}
/**
* Re-key {@link pendingImages} onto the marker numbers the editor now
* displays. `order` lists the SURVIVING marker ids (pre-renumber, i.e. the
* keys the payloads currently sit under) in text reading order, and the
* editor keeps the visible numbers canonical 1..k in reading order, so a
* payload's new key is its position in that list. Ids absent from `order`
* are dropped; reported ids with no payload (a hand-typed marker) are skipped
* without consuming anyone else's slot.
*
* The map is mutated IN PLACE, never replaced: handleClipboardPaste hands
* this.pendingImages by reference into attachClipboardImage's deps, and a
* fresh identity would orphan that reference - the second paste in a turn
* then wrote into the dead map and silently destroyed its image.
*/
reconcilePendingImages(order) {
if (this.pendingImages.size === 0)
return;
const reconciled = new Map();
order.forEach((id, index) => {
const image = this.pendingImages.get(id);
if (image)
reconciled.set(index + 1, image);
});
this.pendingImages.clear();
for (const [key, image] of reconciled) {
this.pendingImages.set(key, image);
}
}
/**
* Resolve the `[Image #N]` markers in `submittedText` (in READING order)
* into the image array submitted alongside it, then clear
* {@link pendingImages}.
*
* Reads ONLY the submitted text plus pendingImages - never live editor
* state: pi-tui's `Editor.submitValue()` resets the editor and clears its
* registries BEFORE `onSubmit` fires. A marker with no pending payload (a
* hand-typed `[Image #N]`, or the second half of a kill/yank duplicate) is
* passed through untouched and consumes no slot; a payload-bearing
* marker's FIRST occurrence wins. Slots are assigned 1..k in reading
* order, so the Nth marker in the final text is `images[N-1]`.
*/
takeSubmissionImages(submittedText) {
const images = [];
const consumed = new Set();
for (const match of submittedText.matchAll(IMAGE_MARKER_PATTERN)) {
const id = Number.parseInt(match[1] ?? "0", 10);
if (consumed.has(id))
continue;
consumed.add(id);
const image = this.pendingImages.get(id);
if (image)
images.push(image);
}
this.pendingImages.clear();
return images;
}
getSessionLogger() {
this.sessionLogger ??= createSessionLogger(this.runtimeHost.services.agentDir);
return this.sessionLogger;
}
handleStartupSubmit(text, details) {
// Quit is a control action, not a prompt: honor it even while managed-tool setup
// is still running. Parking it in the editor would also disable the Ctrl+D quit
// escape, which CustomEditor only forwards while the editor is empty.
if (text.trim() === "/quit" || text.trim() === "/exit") {
this.editor.setText("");
void this.shutdown();
return;
}
this.startupParkedSubmission = { text, ...(details === undefined ? {} : { details }) };
this.editor.setText(text);
this.showStatus("Startup is still in progress");
}
/**
* Paint the render-only echo for a submission, unless it is the bare "."
* manual-continue shortcut. The session routes that "." as a hidden
* continuation, so painting it would leave a user bubble the transcript never
* receives; `undefined` tells the echo callbacks nothing was painted.
*/
beginUserEcho(text, images) {
if (isManualContinueSubmission({
text,
hasMessages: this.session.messages.length > 0,
hasImages: (images?.length ?? 0) > 0,
})) {
return undefined;
}
return this.optimisticUserEchoes.begin(text);
}
setupEditorSubmitHandler() {
this.defaultEditor.onSubmit = async (text, details) => {
try {
// Capture-then-clear BEFORE any branch: handleFollowUp's non-streaming
// path pre-resolves images and hands off here, but slash / extension /
// bash submissions return before the consuming branches below. Clearing
// only after use would leak a stale array into a later ordinary
// submission whose text never references it.
const preResolvedImages = this.preResolvedSubmissionImages;
this.preResolvedSubmissionImages = undefined;
this.hideShortcutOverlay();
this.lastEditorText = "";
text = text.trim();
const unknownCommandAsText = InteractiveMode.confirmsRefusedUnknownCommand(this, text) || submitsCommandAsText(text, details);
if (!text) {
// Enter on an empty editor opens the pending async question; it needs
// no chord, so it works under every terminal and keymap.
this.expandPendingQuestion();
return;
}
// Only an explicitly bound reply claims ordinary text; pre-arrival drafts and history stay chat.
if (!text.startsWith("/") && !text.startsWith("!") && this.submitAsyncQuestionComment(text))
return;
// Handle commands
if (text === "/settings") {
await this.showSettingsSelector();
this.editor.setText("");
return;
}
if (text === "/favorite-models") {
this.editor.setText("");
await this.showFavoriteModelsSelector();
return;
}
if (text === "/scoped-models") {
this.editor.setText("");
this.showScopedModelsSelector();
return;
}
if (text === "/model" || text.startsWith("/model ")) {
const searchTerm = text.startsWith("/model ") ? text.slice(7).trim() : undefined;
this.editor.setText("");
await this.handleModelCommand(searchTerm);
return;
}
if (text === "/thinking" || text.startsWith("/thinking ")) {
const searchTerm = text.startsWith("/thinking ") ? text.slice(10).trim() : undefined;
this.editor.setText("");
await this.handleThinkingCommand(searchTerm);
return;
}
if (text === "/export" || text.startsWith("/export ")) {
await this.handleExportCommand(text);
this.editor.setText("");
return;
}
if (text === "/import" || text.startsWith("/import ")) {
await this.handleImportCommand(text);
this.editor.setText("");
return;
}
if (text === "/share") {
await this.handleShareCommand();
this.editor.setText("");
return;
}
if (text === "/copy") {
await this.handleCopyCommand();
this.editor.setText("");
return;
}
if (text === "/rename" || text.startsWith("/rename ") || text === "/name" || text.startsWith("/name ")) {
await this.handleRenameCommand(text);
this.editor.setText("");
return;
}
if (text === "/session") {
await this.handleSessionCommand();
this.editor.setText("");
return;
}
if (text === "/changelog") {
this.handleChangelogCommand();
this.editor.setText("");
return;
}
if (text === "/keybindings") {
this.editor.setText("");
await this.handleKeybindingsCommand();
return;
}
if (text === "/answer" || text.startsWith("/answer ")) {
this.editor.setText("");
// `/answer skip` submits its text after an await: hold deliveries until it has.
const hold = this.session.externalAdmission?.beginInput({ command: true });
try {
await this.handleAnswerCommand(text.slice("/answer".length).trim());
}
finally {
hold?.end();
}
return;
}
if (text === "/hotkeys") {
this.handleHotkeysCommand();
this.editor.setText("");
return;
}
if (text === "/fork") {
await this.showUserMessageSelector();
this.editor.setText("");
return;
}
if (text === "/clone") {
this.editor.setText("");
await this.handleCloneCommand();
return;
}
if (text === "/tree") {
this.showTreeSelector();
this.editor.setText("");
return;
}
if (text === "/trust") {
this.showTrustSelector();
this.editor.setText("");
return;
}
if (text === "/login" || text.startsWith("/login ")) {
const providerRef = text.startsWith("/login ") ? text.slice(7).trim() : undefined;
this.editor.setText("");
await this.handleLoginCommand(providerRef);
return;
}
if (text === "/logout") {
this.showOAuthSelector("logout");
this.editor.setText("");
return;
}
if (text === "/new") {
this.editor.setText("");
await this.handleClearCommand();
return;
}
if (text === "/compact" || text.startsWith("/compact ")) {
const customInstructions = text.startsWith("/compact ") ? text.slice(9).trim() : undefined;
this.editor.setText("");
await this.handleCompactCommand(customInstructions);
return;
}
if (text === "/reload") {
this.editor.setText("");
await this.handleReloadCommand();
return;
}
if (text === "/debug") {
this.handleDebugCommand();
this.editor.setText("");
return;
}
if (text === "/arminsayshi") {
this.handleArminSaysHi();
this.editor.setText("");
return;
}
if (text === "/dementedelves") {
this.handleDementedDelves();
this.editor.setText("");
return;
}
if (text === "/resume" && resumeCommandTarget(this.session) === "resume_session") {
this.editor.setText("");
await this.session.resumeSession();
return;
}
if (text === "/resume" || text === "/sessions") {
this.showSessionSelector();
this.editor.setText("");
return;
}
if (text === "/quit" || text === "/exit") {
this.editor.setText("");
await this.shutdown();
return;
}
if (isBareSkillNamespace(text)) {
this.openSkillPickerForBareNamespace();
return;
}
if (this.isExtensionCommand(text)) {
// No optimistic echo: the command runs inside AgentSession.prompt() and
// never becomes a canonical user message, so the bubble would only sit
// next to the command's own UI (e.g. the /btw panel) until the handler
// resolved, then vanish. Matches handleFollowUp's command dispatch.
this.editor.addToHistory?.(text);
this.editor.setText("");
await this.session.prompt(text);
return;
}
// Handle bash command (! for normal, !! for excluded from context)
if (text.startsWith("!")) {
const isExcluded = text.startsWith("!!");
const command = isExcluded ? text.slice(2).trim() : text.slice(1).trim();
if (command) {
if (this.session.isBashRunning) {
this.showWarning("A bash command is already running. Press Esc to cancel it first.");
this.editor.setText(text);
return;
}
this.editor.addToHistory?.(text);
await this.handleBashCommand(command, isExcluded);
this.isBashMode = false;
this.updateEditorBorderColor();
return;
}
}
// Queue non-command input during compaction.
// Extension commands short-circuit at the isExtensionCommand branch above and
// dispatch immediately inside AgentSession.prompt(), so the only text that
// reaches this compaction branch is non-command user input, which is queued
// for delivery after compaction settles.
//
// Note: the isExtensionCommand re-check below is already unreachable today
// (the branch above returns first) and stays harmless after the
// immediate-dispatch hoist in prompt().
if (this.session.isCompacting) {
if (this.isExtensionCommand(text)) {
this.editor.addToHistory?.(text);
this.editor.setText("");
await this.session.prompt(text);
}
else {
this.queueCompactionSubmission(text, "steer", unknownCommandAsText);
}
return;
}
// If streaming, use prompt() with steer behavior.
// Extension commands are dispatched immediately by AgentSession.prompt()
// (short-circuited at the isExtensionCommand branch above); the steer
// behavior here applies only to ordinary text, prompt template expansion,
// and queueing.
if (this.session.isStreaming) {
const ticket = this.sessionControlHost?.claimHandoff();
// Resolve BEFORE setText(""): the editor's prune chain fires
// onImageMarkersChanged([]) and destroys pendingImages.
const images = preResolvedImages ?? this.takeSubmissionImages(text);
this.editor.addToHistory?.(text);
this.editor.setText("");
const pendingEchoId = this.beginUserEcho(text, images);
const echoOptions = this.optimisticUserEchoes.promptOptions(pendingEchoId);
try {
await this.session.prompt(text, {
streamingBehavior: "steer",
...(images.length > 0 ? { images } : {}),
...(unknownCommandAsText ? { unknownCommandAsText } : {}),
...echoOptions,
promptDisposition: (disposition) => {
echoOptions.promptDisposition(disposition);
ticket?.release();
},
});
}
catch (error) {
this.optimisticUserEchoes.reject(pendingEchoId);
if (error instanceof UnknownCommandError && this.reportUnknownCommandRejection(error, text))
return;
throw error;
}
finally {
ticket?.release();
}
this.updatePendingMessagesDisplay();
this.ui.requestRender();
return;
}
// Normal message submission
// First, move any pending bash components to chat
this.flushPendingBashComponents();
const images = preResolvedImages ?? this.takeSubmissionImages(text);
const pendingEchoId = this.beginUserEcho(text, images);
const ticket = this.sessionControlHost?.claimHandoff();
const submission = {
text,
pendingEchoId,
...(images.length > 0 ? { images } : {}),
...(unknownCommandAsText ? { unknownCommandAsText } : {}),
...(ticket ? { ticket } : {}),
};
if (this.onInputCallback) {
this.onInputCallback(submission);
}
else {
this.pendingUserInputs.push(submission);
}
this.editor.addToHistory?.(text);
}
catch (error) {
if (typeof this.showError === "function") {
this.showError(error instanceof Error ? error.message : String(error));
}
else {
throw error;
}
}
};
}
showLifecycleStatus(session) {
this.lifecycleStatus.bind(session.sessionId, session.lifecycle);
this.setExtensionStatus(LIFECYCLE_STATUS_KEY, this.lifecycleStatus.text());
}
subscribeToAgent() {
this.unsubscribe?.();
const session = this.session;
const generation = ++this.agentSubscriptionGeneration;
this.showLifecycleStatus(session);
this.unsubscribe = session.subscribe(async (event) => {
if (generation !== this.agentSubscriptionGeneration || session !== this.session)
return;
if (event.type === "session_lifecycle") {
if (event.sessionId !== session.sessionId)
return;
if (!this.lifecycleStatus.owns(event.lifecycle))
this.lifecycleStatus.bind(session.sessionId, session.lifecycle);
this.lifecycleStatus.accept(event.lifecycle);
const text = this.lifecycleStatus.text();
if (this.footerDataProvider.getExtensionStatuses().get(LIFECYCLE_STATUS_KEY) !== text)
this.setExtensionStatus(LIFECYCLE_STATUS_KEY, text);
return;
}
await this.handleEvent(event);
});
}
async handleEvent(event) {
if (!this.isInitialized) {
await this.init();
}
this.footer.invalidate();
switch (event.type) {
case "agent_start":
this.agentIdle = false;
// Keep a scrolled-up reader in place for this turn: rows re-laid out above the viewport are not
// replayed until the next key press (#2836). No catch-up here: a turn nobody typed (auto-retry,
// an extension's triggerTurn) can start while the reader is still scrolled up, and a turn the user
// started already caught up on their Enter key.
this.ui.setScrollbackReplayHold(true);
this.transcriptWriteNoticeShown = false;
this.clearPendingTools();
this.clearActiveToolExecutionStatus();
this.clearToolHookStatuses();
// Turn boundary: pick a fresh working tip next time the indicator shows.
this.turnWorkingTip.resetForNewTurn();
if (this.settingsManager.getShowTerminalProgress()) {
this.ui.terminal.setProgress(true);
}
this.pendingTools?.clear();
// Restore main escape handler if retry handler is still active
// (retry success event fires later, but we need main handler now)
if (this.retryEscapeHandler) {
this.defaultEditor.onEscape = this.retryEscapeHandler;
this.retryEscapeHandler = undefined;
}
break;
case "turn_start":
if (this.settingsManager.getShowTerminalProgress() && this.ui.terminal) {
this.ui.terminal.setProgress(true);
}
if (this.workingVisible) {
this.showWorkingStatusIndicator();
}
else {
this.clearStatusIndicator();
}
this.ui.requestRender();
break;
case "queue_update":
this.updatePendingMessagesDisplay();
this.ui.requestRender();
break;
case "system_prompt_change":
this.showStatus(event.systemPromptName ? `System prompt: ${event.systemPromptName}` : "System prompt changed");
break;
case "entry_appended":
if (this.entriesRenderedByBoundaryCompaction.delete(event.entry.id))
break;
if (event.entry.type === "custom") {
this.addCustomEntryToChat(event.entry);
this.ui.requestRender();
}
else if (event.entry.type === "custom_message" && event.entry.display) {
this.addMessageToChat(createCustomMessage(event.entry.customType, event.entry.content, event.entry.display, event.entry.details, event.entry.timestamp));
this.ui.requestRender();
}
else if (event.entry.type === "compaction") {
const entries = this.sessionManager.buildContextEntries();
if (entries[0]?.id !== event.entry.id)
break;
this.chatContainer.clear();
const branch = this.sessionManager.getBranch();
const compactionIndex = branch.findIndex((entry) => entry.id === event.entry.id);
const entriesAfterCompaction = new Set(branch.slice(compactionIndex + 1).map((entry) => entry.id));
const retainedEntries = entries.slice(1);
this.renderSessionEntries(retainedEntries.filter((entry) => !entriesAfterCompaction.has(entry.id)));
this.addMessageToChat(createCompactionSummaryMessage(event.entry.summary, event.entry.tokensBefore, event.entry.timestamp));
if (event.entry.usage) {
this.addCompactionCostNotice({
type: "compaction_cost",
kind: "compaction",
usage: event.entry.usage,
});
}
this.renderSessionEntries(retainedEntries.filter((entry) => entriesAfterCompaction.has(entry.id)));
for (const entryId of entriesAfterCompaction)
this.entriesRenderedByBoundaryCompaction.add(entryId);
this.footer.invalidate();
this.ui.requestRender();
}
break;
case "session_info_changed":
this.updateTerminalTitle();
this.footer.invalidate();
this.ui.requestRender();
break;
case "thinking_level_changed":
this.footer.invalidate();
this.updateEditorBorderColor();
this.showStatus(`Thinking level: ${event.level}`);
break;
case "model_change_skipped":
this.showWarning(`Skipped ${event.model.name || event.model.id}: current context needs ${event.shortfallTokens.toLocaleString()} ` +
`more tokens for its ${event.contextWindow.toLocaleString()}-token window ` +
`(${event.safetyMarginProfile} usability budget).`);
break;
case "model_change_pending":
this.showWarning(event.notice);
this.footer.invalidate();
this.ui.requestRender();
break;
case "model_change_cancelled":
// The footer carried the held target (senpi#6092); a hold that ends without landing takes it back off.
this.footer.invalidate();
this.ui.requestRender();
break;
case "high_reasoning_warning":
this.showHighReasoningWarning(event);
break;
case "thinking_level_clamped":
this.showWarning(formatThinkingClampWarning(event));
break;
case "resume_compaction_required":
this.showWarning(event.notice);
break;
case "resume_context_reduced":
this.showWarning(event.notice);
break;
case "provider_required":
// The first notice repeats the startup "No models available" warning (same /login guidance), so it
// is absorbed by it; the session emits again only after a turn was admitted in between.
if (this.startupProviderGuidanceShown) {
this.startupProviderGuidanceShown = false;
break;
}
this.showWarning(event.notice);
break;
case "settings_source_selected":
this.showSettingsSourceSelected(event);
break;
case "message_start":
if (event.message.role === "custom") {
this.addMessageToChat(event.message);
this.ui.requestRender();
}
else if (event.message.role === "user") {
this.providerErrors?.newTurn();
if (!this.optimisticUserEchoes.replaceNext(event.message))
this.addMessageToChat(event.message);
this.updatePendingMessagesDisplay();
this.ui.requestRender();
}
else if (event.message.role === "assistant") {
this.streamingComponent = new AssistantMessageComponent(undefined, this.hideThinkingBlock, this.getMarkdownThemeWithSettings(), this.hiddenThinkingLabel, this.outputPad, this.getMarkdownTransformers());
this.streamingComponent.setExpanded(this.toolOutputExpanded);
this.streamingMessage = event.message;
this.chatContainer.addChild(this.streamingComponent);
this.streamingReveal.begin(this.streamingComponent, assistantStreamingHeadMessage(this.streamingMessage));
this.requestStreamingRender();
}
break;
case "message_update":
if (this.streamingComponent && event.message.role === "assistant") {
if (event.message.content.some((part) => part.type === "text" && part.text.trim())) {
this.providerErrors?.clear();
this.clearStatusIndicator("retry");
}
this.streamingMessage = event.message;
this.streamingReveal.setTarget(assistantStreamingHeadMessage(event.message));
for (const content of this.streamingMessage.content) {
if (content.type === "toolCall") {
let component = this.pendingTools.get(content.id);
if (!component) {
component = this.createToolExecutionComponent(content.name, content.id, content.arguments);
component.setExpanded(this.toolOutputExpanded);
this.chatContainer.addChild(component);
this.pendingTools.set(content.id, component);
}
const partialJson = getStreamingToolCallPartialJson(content);
if (partialJson && this.settingsManager.getSmoothStreaming()) {
this.toolArgsReveal.update(content.id, component, partialJson);
}
else {
this.toolArgsReveal.finish(content.id);
component.updateArgs(content.arguments);
}
}
}
this.syncTrailingAssistantText(event.message);
this.ui.requestRender();
}
break;
case "message_end":
if (event.message.role === "user")
break;
if (this.streamingComponent && event.message.role === "assistant") {
this.streamingMessage = event.message;
this.streamingReveal.stop();
for (const content of this.streamingMessage.content) {
if (content.type !== "toolCall")
continue;
const component = this.pendingTools.get(content.id);
if (component && !this.toolArgsReveal.flush(content.id, content.arguments)) {
component.updateArgs(content.arguments);
}
}
this.toolArgsReveal.flushAll();
const renderedMessage = abortedMessageForRendering(this.streamingMessage, this.session.retryAttempt, this.session.currentAbortSource);
if (isRetryableProviderMessage(renderedMessage, this.session)) {
this.getProviderErrors().record(renderedMessage.errorMessage ?? "", this.toolOutputExpanded);
}
else if (renderedMessage.stopReason === "stop" || renderedMessage.stopReason === "toolUse") {
this.providerErrors?.clear();
this.clearStatusIndicator("retry");
}
this.syncTrailingAssistantText(renderedMessage);
this.assistantTextSegments.clear();
this.addContinuityNotice(renderedMessage);
if (this.streamingMessage.stopReason === "aborted" || this.streamingMessage.stopReason === "error") {
const text = unrunToolCallText(renderedMessage);
for (const [, component] of this.pendingTools.entries()) {
component.updateResult({
content: [{ type: "text", text }],
isError: true,
});
}
this.clearPendingTools();
}
else {
// Args are now complete - trigger diff computation for edit tools
for (const [, component] of this.pendingTools.entries()) {
component.setArgsComplete();
}
this.maybeShowAssistantDiagnostics(this.streamingMessage);
this.maybeShowCacheMissNotice(this.streamingMessage);
}
this.streamingComponent = undefined;
this.streamingMessage = undefined;
this.footer.invalidate();
}
this.ui.requestRender();
break;
case "bash_execution_update":
// The bash execution callback handles TUI output rendering.
break;
case "tool_execution_start": {
// Nested calls (made through ctx.executeTool()) are shown inside their parent's row.
if (event.parentToolCallId)
break;
this.handleToolExecutionStart(event);
let component = this.pendingTools.get(event.toolCallId);
if (!component) {
component = this.createToolExecutionComponent(event.toolName, event.toolCallId, event.args);
component.setExpanded(this.toolOutputExpanded);
this.chatContainer.addChild(component);
this.pendingTools.set(event.toolCallId, component);
}
if (!this.toolArgsReveal.flush(event.toolCallId, event.args)) {
component.updateArgs(event.args);
}
component.markExecutionStarted();
this.ui.requestRender();
break;
}
case "tool_hook_status":
this.handleToolHookStatusEvent(event);
break;
case "tool_execution_update": {
const component = this.pendingTools.get(event.toolCallId);
if (component) {
if (!this.toolResultReveal.update(event.toolCallId, component, event.partialResult)) {
component.updateResult({ ...event.partialResult, isError: false }, true);
}
const activity = readToolProgress(event.partialResult.details)?.activity;
if (activity) {
const label = formatActiveToolWorkingLabel(event.toolName, {
command: activity,
});
this.activeToolExecutions.set(event.toolCallId, label);
this.workingMessage = label;
this.activeToolExecutionTerminalTitle = `${APP_TITLE} - ${label}`;
this.refreshWorkingLoaderMessage();
this.applyTerminalTitle();
}
this.requestStreamingRender();
}
break;
}
case "tool_execution_end": {
if (event.parentToolCallId)
break;
this.handleToolExecutionEnd(event);
this.toolArgsReveal.finish(event.toolCallId);
let component = this.pendingTools.get(event.toolCallId);
if (!component) {
component = this.createToolExecutionComponent(event.toolName, event.toolCallId, {});
component.setExpanded(this.toolOutputExpanded);
this.chatContainer.addChild(component);
this.pendingTools.set(event.toolCallId, component);
}
this.toolResultReveal.finish(event.toolCallId);
component.updateResult({ ...event.result, isError: event.isError });
this.pendingTools.delete(event.toolCallId);
this.ui.requestRender();
break;
}
case "agent_end":
if (this.settingsManager.getShowTerminalProgress() && this.ui.terminal) {
this.ui.terminal.setProgress(false);
}
// Keep holding until the next key press: a replay at turn end would snap a reader who is scrolled up.
this.ui.setScrollbackReplayHold("until-input");
this.clearActiveToolExecutionStatus();
this.clearToolHookStatuses();
this.streamingReveal.stop();
this.toolResultReveal.stop();
if (this.streamingComponent) {
this.chatContainer.removeChild(this.streamingComponent);
this.streamingComponent = undefined;
this.streamingMessage = undefined;
}
this.detachAssistantTextSegments();
this.clearPendingTools();
// A failure the quiet episode owns gets its one final notice when the episode finishes (senpi#6012).
if (event.failure !== undefined &&
!event.willRetry &&
!failureAlreadyDescribed(event.messages) &&
!episodeOwnsFailure(event.messages, this.providerErrors, this.session))
this.showError(formatProviderFailure(event.failure));
this.ui.requestRender();
break;
case "agent_idle":
this.agentIdle = true;
this.providerErrors?.finish();
if (this.pendingUserInputs.length === 0) {
this.clearStatusIndicator("working");
}
this.ui.requestRender();
// After the settle-time extension handlers drained, not at agent_settled while they may still run (omo#11419).
await this.checkShutdownRequested();
break;
case "session_recovered":
this.showWarning(sanitizeTerminalLabel(event.notice));
break;
case "continuation_error":
this.showError(sanitizeTerminalLabel(event.errorMessage));
break;
case "offload_module_stuck":
this.showWarning(sanitizeTerminalLabel(event.notice));
break;
case "transcript_write_failed": {
if (this.transcriptWriteNoticeShown)
break;
this.transcriptWriteNoticeShown = true;
const reason = /^[A-Z][A-Z0-9_]+(?=:)/.exec(event.errorMessage)?.[0] ?? sanitizeTerminalLabel(event.errorMessage);
this.showWarning(`This turn was not saved to the session file (${reason}); the model will not see it after the next prompt.`);
break;
}
case "session_abort":
this.providerErrors?.clear();
this.clearStatusIndicator("retry");
this.pendingZeroDelayRetryIndicator = undefined;
this.ui.requestRender();
break;
case "compaction_start": {
if (this.settingsManager.getShowTerminalProgress() && this.ui.terminal) {
this.ui.terminal.setProgress(true);
}
// Keep editor active; submissions are queued during compaction.
if (!this.compactionEscapeOverrideActive) {
this.autoCompactionEscapeHandler = this.defaultEditor.onEscape;
this.compactionEscapeOverrideActive = true;
}
this.defaultEditor.onEscape = () => {
this.session.abortCompaction();
};
const indicator = new CompactionStatusIndicator(this.ui, event.reason);
this.activeStatusIndicator?.dispose();
this.activeStatusIndicator = indicator;
this.statusContainer.clear();
this.statusContainer.addChild(indicator);
this.autoCompactionProgressText = "";
this.ui.requestRender();
break;
}
case "compaction_progress": {
if (this.activeStatusIndicator?.kind !== "compaction")
break;
const nextText = event.text !== undefined ? event.text : `${this.autoCompactionProgressText}${event.delta ?? ""}`;
if (!nextText)
break;
this.autoCompactionProgressText = nextText;
const preview = nextText.length > 4_000 ? `...${nextText.slice(nextText.length - 4_000)}` : nextText;
this.activeStatusIndicator.setProgressText(sanitizeTerminalLabel(preview));
this.ui.requestRender();
break;
}
case "compaction_end": {
if (this.settingsManager.getShowTerminalProgress() && this.ui.terminal) {
this.ui.terminal.setProgress(false);
}
InteractiveMode.restoreCompactionEscapeOverride(this);
this.clearStatusIndicator("compaction");
this.autoCompactionProgressText = "";
// Checked before `aborted`: production external-owner rejections are
// emitted via `_rejectCompaction(..., true, reason)` and carry
// `aborted: true`, so this branch must win for auto reasons or the
// delegation state renders as a per-turn red error.
if (event.rejectionCause === "external-owner" && event.reason !== "manual") {
// Auto compaction is delegated to an external owner (Claude Agent SDK).
// This is expected state, not an error: surface it at most once per
// delegation episode as a muted informational line and mark the footer
// so the saturated context meter reads as "handled natively".
if (!this.externalOwnerCompactionNoticeShown) {
this.externalOwnerCompactionNoticeShown = true;
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new Text(theme.fg("muted", "The Claude Agent SDK manages and compacts this session's context natively."), 1, 0));
}
this.footer?.setCompactionDelegated?.(true);
}
else if (event.aborted) {
// Prefer the extension-provided reason over the generic "cancelled"
// label so per-turn-cap / circuit-breaker / provider-error cancels are
// no longer indistinguishable from a user-triggered abort.
const cancelMessage = sanitizeTerminalLabel(event.errorMessage ?? "Compaction cancelled");
if (event.reason === "manual") {
this.showError(cancelMessage);
}
else if (event.errorMessage) {
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new Text(theme.fg("error", cancelMessage), 1, 0));
}
else {
this.showStatus("Auto-compaction cancelled");
}
}
else if (event.result) {
// A successful compaction ends the retry episode: no finish is owed, so a later
// never-retried terminal failure must not reopen the banner.
this.providerErrors?.clear();
// Compaction event consumers in the fork are session-backed and do not
// necessarily expose InteractiveMode's SessionManager convenience getter.
// Keep the structural fallback for focused handler consumers while using
// the session-owned manager on the real TUI path.
const sessionManager = this.session.sessionManager ?? this.sessionManager;
let entries = sessionManager?.buildContextEntries?.() ?? [];
if (entries[0]?.type !== "compaction") {
try {
sessionManager?.reloadFromDisk?.();
entries = sessionManager?.buildContextEntries?.() ?? entries;
}
catch {
// Retain existing entries on reload error
}
}
this.chatContainer.clear();
const summaryMessage = createCompactionSummaryMessage(sanitizeTerminalLabel(event.result.summary), event.result.tokensBefore, new Date().toISOString(), event.result.details);
if (typeof this.renderSessionEntries === "function") {
// The latest compaction is prepended for model context; append it below at its chronological position.
const entriesToRender = entries[0]?.type === "compaction"
? entries.slice(1)
: entries.filter((e) => e.type !== "compaction");
this.renderSessionEntries(entriesToRender);
this.addMessageToChat(summaryMessage);
if (event.result.usage) {
this.addCompactionCostNotice({
type: "compaction_cost",
kind: "compaction",
usage: event.result.usage,
});
}
}
else {
// Fork-owned compaction consumers expose the established rebuild helper,
// not InteractiveMode's private entry renderer.
this.rebuildChatFromMessages();
this.addMessageToChat(summaryMessage);
}
this.footer.invalidate();
// A real compaction landed: the delegation episode (if any) is over.
this.externalOwnerCompactionNoticeShown = false;
this.footer?.setCompactionDelegated?.(false);
}
else if (event.errorMessage) {
const errorMessage = sanitizeTerminalLabel(event.errorMessage);
// The quiet provider-retry banner's finish() closes out a retry recorded in the CURRENT
// episode. A terminal compaction failure after an episode that already finished (or one
// that never retried) must always surface as an error, even when its message looks
// transient ("timeout", "truncated generator").
if (isRetryableProviderError(errorMessage) && this.providerErrors?.awaitingRetryFinish === true) {
this.getProviderErrors().finish(errorMessage);
}
else if (event.reason === "manual") {
this.showError(errorMessage);
}
else {
this.chatContainer.addChild(new Text(theme.fg("error", errorMessage), 1, 0));
}
}
else if (event.accepted === false) {
// Exhaustive fallback per plan Section 1: compaction_end must never fall
// through silently. Rejection events without an errorMessage still name
// the rejectionCause so the user knows /compact did nothing on purpose.
const cause = event.rejectionCause ?? "unknown";
const message = `Compaction failed (no result); cause: ${cause}`;
if (event.reason === "manual") {
this.showError(message);
}
else {
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new ThemedText(() => theme.fg("error", message), 1, 0));
}
}
// Every terminal compaction_end resolves the TUI compaction queue.
// Accepted compactions deliver through prompt admission. Retryable
// failures route through the native steer/followUp queues so submitted
// input rides along with the retry instead of being silently parked
// (field bug: messages typed during a failing compaction were held
// forever and lost on session switch). Terminal failures hand the input
// back to the editable composer: retrying delivery against the same
// over-threshold context would just repeat the failure.
const compactionSucceeded = event.accepted === true || event.result !== undefined;
if (compactionSucceeded) {
void this.flushCompactionQueue({
willRetry: event.willRetry,
deferAdmission: false,
});
}
else if (event.willRetry === true) {
const heldCount = this.compactionQueuedMessages.length;
if (heldCount > 0) {
const failureCause = event.errorMessage ?? event.rejectionCause ?? (event.aborted ? "aborted" : "no-result");
this.getSessionLogger().warn("compaction_queue_deferred", {
count: heldCount,
cause: failureCause,
});
this.showStatus(`${heldCount} queued message${heldCount === 1 ? "" : "s"} will send with the next turn (compaction will retry)`);
}
void this.flushCompactionQueue({
willRetry: true,
deferAdmission: true,
});
}
else {
const restoredCount = this.restoreQueuedMessagesToEditor();
if (restoredCount > 0) {
const failureCause = event.errorMessage ?? event.rejectionCause ?? (event.aborted ? "aborted" : "no-result");
this.getSessionLogger().warn("compaction_queue_restored", {
restored: restoredCount,
cause: failureCause,
});
this.showStatus(`${restoredCount} queued message${restoredCount === 1 ? "" : "s"} restored to the editor (compaction did not complete)`);
}
}
this.ui.requestRender();
break;
}
case "model_changed": {
// The new model must not inherit the previous model's
// SDK-delegation episode (post-#1188 core emits no repeat rejection to
// self-heal a stale marker).
this.externalOwnerCompactionNoticeShown = false;
this.footer?.setCompactionDelegated?.(false);
const notice = liveModelChangeNotice(event);
if (notice !== undefined)
this.addModelChangeNotice(notice);
break;
}
case "session_paused":
case "session_resumed":
case "session_notice":
this.setExtensionStatus(PAUSE_STATUS_KEY, pauseFooterText(this.session));
break;
case "retry_fallback_applied": {
if (this.pendingZeroDelayRetryIndicator) {
this.pendingZeroDelayRetryIndicator.fallbackApplied = true;
}
else {
this.fallbackAppliedBeforeRetryStart = true;
}
this.showNoticeBox({
title: `⇄ Model fallback · ${event.from} → ${event.to}`,
tone: "warning",
why: `${usageLimitCause(event.from, event.limit) ?? `Retry switched models (${event.reason})`}; the turn continues on ${event.to}.`,
});
this.setExtensionStatus(FALLBACK_STATUS_KEY, `fallback: ${event.to}`);
// Provider/model failover ends any external-owner delegation episode:
// the fallback model does not inherit SDK-owned compaction state.
this.externalOwnerCompactionNoticeShown = false;
this.footer?.setCompactionDelegated?.(false);
break;
}
case "retry_fallback_succeeded":
this.showNoticeBox({
title: `✓ Fallback model responded · ${event.model}`,
tone: "success",
why: "The fallback chain answered; the session stays on it until the revert policy fires.",
});
break;
case "retry_fallback_reverted":
this.showNoticeBox({
title: `⇄ Reverted to ${event.to}`,
tone: "accent",
why: event.cause === "fallback-unusable"
? `${event.from} cannot serve right now (its account hit a billing or usage limit), so the session is back on the original model.`
: "The original model is back after its cooldown lapsed.",
});
this.setExtensionStatus(FALLBACK_STATUS_KEY, undefined);
break;
case "retry_fallback_exhausted": {
if (event.refusals !== undefined && event.refusals.length > 0) {
this.showNoticeBox({
title: `✕ Fallback refused for context budget · ${event.chainKey}`,
tone: "error",
why: [describeFallbackExhaustion(event), ...event.refusals.map((refusal) => refusal.detail)].join("\n"),
});
this.setExtensionStatus(FALLBACK_STATUS_KEY, undefined);
break;
}
// A walk that started on another failure must lead with it, not the last rung's (senpi#4084).
const startedElsewhere = (event.failures?.length ?? 0) > 1;
if (isRetryableProviderError(event.lastError) && !startedElsewhere) {
this.getProviderErrors().finish(event.lastError);
this.setExtensionStatus(FALLBACK_STATUS_KEY, undefined);
break;
}
if (isRetryableProviderError(event.lastError))
this.getProviderErrors().clear();
this.showNoticeBox({
title: `✕ Fallback chain exhausted · ${event.chainKey}`,
tone: "error",
why: describeFallbackExhaustion(event),
});
this.setExtensionStatus(FALLBACK_STATUS_KEY, undefined);
break;
}
case "server_fallback_aborted":
this.showNoticeBox({
title: `⚠ Server fallback aborted · ${event.from} → ${event.to}`,
tone: "warning",
why: event.chainConfigured
? "Retrying on your configured fallback chain."
: "No fallback chain configured: set one with /fallback.",
});
break;
case "auto_retry_start": {
if (isRetryableProviderError(event.errorMessage)) {
this.getProviderErrors().retrying(event.errorMessage, this.toolOutputExpanded);
}
// During retry waits, isStreaming flips false between attempts. The main Esc handler
// keys off both isStreaming and retryAttempt so we keep the same close-out path here;
// no separate retry-only handler is installed (the prior one only called
// session.abortRetry() and left queued steering messages stranded).
this.retryEscapeHandler = undefined;
const fallbackApplied = this.fallbackAppliedBeforeRetryStart;
this.fallbackAppliedBeforeRetryStart = false;
if (event.delayMs === 0) {
const pending = { fallbackApplied };
this.pendingZeroDelayRetryIndicator = pending;
queueMicrotask(() => {
if (this.pendingZeroDelayRetryIndicator !== pending)
return;
this.pendingZeroDelayRetryIndicator = undefined;
if (shouldShowRetryIndicator(event.delayMs, pending.fallbackApplied)) {
this.showRetryStatusIndicator(event);
}
});
}
else {
this.showRetryStatusIndicator(event);
}
break;
}
case "auto_retry_end": {
this.pendingZeroDelayRetryIndicator = undefined;
this.fallbackAppliedBeforeRetryStart = false;
// Restore escape handler
if (this.retryEscapeHandler) {
this.defaultEditor.onEscape = this.retryEscapeHandler;
this.retryEscapeHandler = undefined;
}
this.clearStatusIndicator("retry");
// Show error only on final failure (success shows normal response)
if (event.success || event.finalError === "Retry cancelled") {
this.providerErrors?.clear();
}
else if (isRetryableProviderError(event.finalError)) {
this.getProviderErrors().finish(event.finalError, event.attempt);
}
else {
this.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError || "Unknown error"}`);
}
this.ui.requestRender();
break;
}
case "summarization_retry_scheduled": {
if (isRetryableProviderError(event.errorMessage)) {
this.getProviderErrors().retrying(event.errorMessage, this.toolOutputExpanded);
}
else {
this.showError(event.errorMessage);
}
this.showSummarizationRetryStatusIndicator(event);
break;
}
case "summarization_retry_attempt_start": {
this.clearStatusIndicator("retry");
if (event.source === "branchSummary") {
this.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui));
}
else {
this.showStatusIndicator(new CompactionStatusIndicator(this.ui, event.reason));
}
this.ui.requestRender();
break;
}
case "summarization_retry_finished": {
this.providerErrors?.clearTransient();
this.clearStatusIndicator("retry");
this.ui.requestRender();
break;
}
case "retry_probe_scheduled": {
const secondsAway = Math.max(0, Math.round((event.atMs - Date.now()) / 1000));
this.showStatus(`Probing ${sanitizeTerminalLabel(event.selector)} at +${secondsAway}s (#${event.probeIndex})`);
this.ui.requestRender();
break;
}
case "retry_probe_result": {
if (event.ok) {
this.showStatus(`Recovered ${sanitizeTerminalLabel(event.selector)} - will restore on next turn`);
}
else if (event.errorMessage === "auth-unavailable") {
this.showStatus(`Probe for ${sanitizeTerminalLabel(event.selector)} skipped - auth unavailable, staying on fallback`);
}
else {
this.showStatus(`Probe for ${sanitizeTerminalLabel(event.selector)} failed - staying on fallback`);
}
this.ui.requestRender();
break;
}
}
}
showRetryStatusIndicator(event) {
this.showRetryStatusIndicatorWithCadence(event);
}
showSummarizationRetryStatusIndicator(event) {
this.showRetryStatusIndicatorWithCadence(event);
}
showRetryStatusIndicatorWithCadence(event) {
const refreshIntervalMs = largeSessionWorkingStatusInterval(this.sessionManager.getEntryCount(), DEFAULT_RETRY_STATUS_REFRESH_INTERVAL_MS, LARGE_SESSION_RETRY_STATUS_REFRESH_INTERVAL_MS);
const indicator = refreshIntervalMs === DEFAULT_RETRY_STATUS_REFRESH_INTERVAL_MS ? undefined : { intervalMs: refreshIntervalMs };
this.showStatusIndicator(new RetryStatusIndicator(this.ui, event.attempt, event.maxAttempts, event.delayMs, indicator, isRetryableProviderError(event.errorMessage), providerErrorReason(event.errorMessage)));
this.ui.requestRender();
}
/** Extract text content from a user message */
getUserMessageText(message) {
if (message.role !== "user")
return "";
const textBlocks = typeof message.content === "string"
? [{ type: "text", text: message.content }]
: message.content.filter((content) => content.type === "text");
return textBlocks.map((content) => content.text).join("");
}
/** Show a managed-tool status update in the chat. */
showManagedToolStatus(status) {
if (!this.managedToolStatusStarted) {
this.chatContainer.addChild(new Spacer(1));
this.managedToolStatusStarted = true;
}
const message = status.type === "warning" ? `Warning: ${status.message}` : status.message;
const color = status.type === "warning" ? "warning" : "dim";
this.chatContainer.addChild(new ThemedText(() => theme.fg(color, message), 1, 0));
this.lastStatusSpacer = undefined;
this.lastStatusText = undefined;
this.ui.requestRender();
}
/**
* Show a status message in the chat.
*
* If multiple status messages are emitted back-to-back (without anything else being added to the chat),
* we update the previous status line instead of appending new ones to avoid log spam.
*/
showStatus(message) {
const children = this.chatContainer.children;
// While a turn streams, a notice goes above the live message, like a custom entry does. Appended
// after it, a notice taller than the screen pushed the live output above the viewport, and every
// streamed delta then replayed the whole scrollback: the view kept jumping to the top (#2836).
const streamingIndex = this.streamingComponent ? children.indexOf(this.streamingComponent) : -1;
const end = streamingIndex >= 0 ? streamingIndex : children.length;
const last = end > 0 ? children[end - 1] : undefined;
const secondLast = end > 1 ? children[end - 2] : undefined;
this.lastStatusMessage = message;
// Each row owns its content, even if its first render or a theme invalidation happens after another notice.
const text = new ThemedText(() => theme.fg("dim", message), 1, 0);
if (last && secondLast && last === this.lastStatusText && secondLast === this.lastStatusSpacer) {
children[end - 1] = text;
this.lastStatusText = text;
this.ui.requestRender();
return;
}
const spacer = new Spacer(1);
if (streamingIndex >= 0) {
children.splice(streamingIndex, 0, spacer, text);
}
else {
this.chatContainer.addChild(spacer);
this.chatContainer.addChild(text);
}
this.lastStatusSpacer = spacer;
this.lastStatusText = text;
this.ui.requestRender();
}
addCustomEntryToChat(entry) {
const renderer = this.session.extensionRunner.getEntryRenderer(entry.customType);
if (!renderer) {
return;
}
const component = new CustomEntryComponent(entry, renderer);
component.setExpanded(this.toolOutputExpanded);
if (!component.hasContent()) {
return;
}
const children = this.chatContainer.children;
const streamingIndex = this.streamingComponent ? children.indexOf(this.streamingComponent) : -1;
const insertIndex = streamingIndex >= 0 ? streamingIndex : children.length;
const options = this.session.extensionRunner.getEntryRendererOptions(entry.customType);
const replacedIndex = replacedEntryCardIndex(children, insertIndex, entry, options, (child) => child === this.lastStatusText || child === this.lastStatusSpacer);
if (replacedIndex >= 0) {
children.splice(replacedIndex, 1, component);
return;
}
if (streamingIndex >= 0) {
children.splice(streamingIndex, 0, component);
return;
}
this.chatContainer.addChild(component);
}
renderPendingUserEcho(text) {
const spacer = this.chatContainer.children.length > 0 ? new Spacer(1) : undefined;
if (spacer)
this.chatContainer.addChild(spacer);
const component = new UserMessageComponent(text, this.getMarkdownThemeWithSettings(), this.outputPad, this.getMarkdownTransformers());
this.chatContainer.addChild(component);
this.ui.requestRender();
const removePending = () => {
const componentIndex = this.chatContainer.children.indexOf(component);
if (componentIndex === -1) {
return this.chatContainer.children.length;
}
const spacerIndex = spacer ? this.chatContainer.children.indexOf(spacer) : -1;
const insertionIndex = spacerIndex >= 0 ? spacerIndex : componentIndex;
if (spacerIndex >= 0 && spacer)
this.chatContainer.removeChild(spacer);
this.chatContainer.removeChild(component);
return insertionIndex;
};
return {
replace: (message) => {
const insertionIndex = removePending();
const appendIndex = this.chatContainer.children.length;
this.addMessageToChat(message);
const canonicalChildren = this.chatContainer.children.splice(appendIndex);
if (!spacer && canonicalChildren[0] instanceof Spacer)
canonicalChildren.shift()?.dispose?.();
this.chatContainer.children.splice(insertionIndex, 0, ...canonicalChildren);
this.ui.requestRender();
},
remove: () => {
removePending();
this.ui.requestRender();
},
};
}
addMessageToChat(message, options) {
if (message.role === "user")
this.providerErrors?.newTurn();
switch (message.role) {
case "bashExecution": {
const component = new BashExecutionComponent(message.command, this.ui, message.excludeFromContext);
if (message.output) {
component.appendOutput(message.output);
}
component.setComplete(message.exitCode, message.cancelled, message.truncated ? { truncated: true } : undefined, message.fullOutputPath);
this.chatContainer.addChild(component);
break;
}
case "custom": {
if (message.display) {
const renderer = this.session.extensionRunner.getMessageRenderer(message.customType) ??
builtInMessageRenderer(message.customType);
const component = new CustomMessageComponent(message, renderer, this.getMarkdownThemeWithSettings(), this.outputPad);
component.setExpanded(this.toolOutputExpanded);
this.chatContainer.addChild(component);
}
break;
}
case "compactionSummary": {
this.chatContainer.addChild(new Spacer(1));
const component = new CompactionSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());
component.setExpanded(this.toolOutputExpanded);
this.chatContainer.addChild(component);
break;
}
case "branchSummary": {
this.chatContainer.addChild(new Spacer(1));
const component = new BranchSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());
component.setExpanded(this.toolOutputExpanded);
this.chatContainer.addChild(component);
break;
}
case "system":
break;
case "user": {
const textContent = askUserAnswerDisplayText(message.content) ?? this.getUserMessageText(message);
if (textContent) {
if (this.chatContainer.children.length > 0) {
this.chatContainer.addChild(new Spacer(1));
}
const skillBlock = parseSkillBlock(textContent);
if (skillBlock) {
// Render skill block (collapsible)
const component = new SkillInvocationMessageComponent(skillBlock, this.getMarkdownThemeWithSettings());
component.setExpanded(this.toolOutputExpanded);
this.chatContainer.addChild(component);
// Render user message separately if present
if (skillBlock.userMessage) {
this.chatContainer.addChild(new Spacer(1));
const userComponent = new UserMessageComponent(skillBlock.userMessage, this.getMarkdownThemeWithSettings(), this.outputPad, this.getMarkdownTransformers());
this.chatContainer.addChild(userComponent);
}
}
else {
const answer = parseAskUserAnswerFrame(textContent);
const userComponent = new UserMessageComponent(textContent, this.getMarkdownThemeWithSettings(), this.outputPad, this.getMarkdownTransformers(), answer ? getAskUserAnswerHeaders(this.sessionManager.getBranch(), answer.requestId) : undefined);
this.chatContainer.addChild(userComponent);
}
if (options?.populateHistory) {
this.editor.addToHistory?.(textContent);
}
}
break;
}
case "assistant": {
if (isRetryableProviderMessage(message, this.session)) {
this.getProviderErrors().record(message.errorMessage ?? "", this.toolOutputExpanded);
this.providerErrors?.finish();
}
else if (message.stopReason === "stop" || message.stopReason === "toolUse") {
this.providerErrors?.clear();
}
const assistantComponent = new AssistantMessageComponent(message, this.hideThinkingBlock, this.getMarkdownThemeWithSettings(), this.hiddenThinkingLabel, this.outputPad, this.getMarkdownTransformers());
assistantComponent.setExpanded(this.toolOutputExpanded);
assistantComponent.setProviderErrorOwned(isRetryableProviderMessage(message, this.session));
if (options?.replayOwnsTurnNotice === true)
assistantComponent.setOwnsTurnNotice(true);
if (options?.replayOwnsTurnNotice === false)
assistantComponent.setProviderErrorOwned(true);
this.chatContainer.addChild(assistantComponent);
break;
}
case "toolResult": {
// Tool results are rendered inline with tool calls, handled separately
break;
}
case "configurationUpdate": {
break;
}
default: {
const exhaustive = message;
void exhaustive;
}
}
}
syncTrailingAssistantText(message) {
if (!this.streamingComponent)
return;
this.streamingComponent.setProviderErrorOwned(isRetryableProviderMessage(message, this.session) || headNoticeShownElsewhere(message));
const head = assistantStreamingHeadMessage(message);
// Single writer: while smooth streaming paces the head (no toolCall block),
// streamingReveal owns the streaming component. Overwriting the full head
// here makes the next reveal tick repaint a shorter prefix (dual-write
// flicker). Once the reveal has stopped (message_end), it no longer paces
// and the final full paint below still lands.
if (!this.streamingReveal?.isPacingHead(head)) {
this.streamingComponent.updateContent(head, true);
}
const content = message.content;
const firstToolIndex = content.findIndex((block) => block.type === "toolCall");
if (firstToolIndex === -1) {
this.detachAssistantTextSegments();
return;
}
let index = firstToolIndex + 1;
while (index < content.length) {
if (content[index]?.type === "toolCall") {
index += 1;
continue;
}
const runStart = index;
const runBlocks = [];
while (index < content.length && content[index]?.type !== "toolCall") {
const runBlock = content[index];
if (runBlock)
runBlocks.push(runBlock);
index += 1;
}
const runMessage = { ...message, content: runBlocks };
// Only the run that ends the message shows the turn's error; earlier runs repeat it otherwise (senpi#4954).
const errorShownElsewhere = isRetryableProviderMessage(message, this.session) || index < content.length;
const existing = this.assistantTextSegments.get(runStart);
if (existing) {
existing.setProviderErrorOwned(errorShownElsewhere);
existing.updateContent(runMessage, true);
continue;
}
const segment = new AssistantMessageComponent(runMessage, this.hideThinkingBlock, this.getMarkdownThemeWithSettings(), this.hiddenThinkingLabel, this.outputPad, this.getMarkdownTransformers());
segment.setExpanded(this.toolOutputExpanded);
segment.setProviderErrorOwned(errorShownElsewhere);
this.assistantTextSegments.set(runStart, segment);
const followingToolCall = content.slice(index).find((block) => block.type === "toolCall");
const followingToolCallId = followingToolCall?.type === "toolCall" ? followingToolCall.id : undefined;
const followingToolComponent = followingToolCallId ? this.pendingTools.get(followingToolCallId) : undefined;
const anchorIndex = followingToolComponent ? this.chatContainer.children.indexOf(followingToolComponent) : -1;
if (anchorIndex >= 0)
this.chatContainer.children.splice(anchorIndex, 0, segment);
else
this.chatContainer.addChild(segment);
}
for (const [runStart, segment] of this.assistantTextSegments) {
if (runStart >= content.length || content[runStart]?.type === "toolCall") {
this.chatContainer.detachChild(segment);
this.assistantTextSegments.delete(runStart);
}
}
}
detachAssistantTextSegments() {
for (const segment of this.assistantTextSegments.values()) {
this.chatContainer.detachChild(segment);
}
this.assistantTextSegments.clear();
}
createToolExecutionComponent(requestedName, toolCallId, args) {
// A call the agent resolves to another tool (gateway namespace, recasing) renders as that tool from its first frame.
const toolName = this.session.resolveToolCallName(requestedName);
if (this.chrome) {
return new ToolExecutionComponent(toolName, toolCallId, args, {
showImages: this.settingsManager.getShowImages(),
imageWidthCells: this.settingsManager.getImageWidthCells(),
}, this.getRegisteredToolDefinition(toolName), this.ui, this.sessionManager.getCwd(), this.chrome.toolPresentation);
}
return new ToolExecutionComponent(toolName, toolCallId, args, {
showImages: this.settingsManager.getShowImages(),
imageWidthCells: this.settingsManager.getImageWidthCells(),
}, this.getRegisteredToolDefinition(toolName), this.ui, this.sessionManager.getCwd());
}
renderSessionItems(items, options = {}) {
this.providerErrors = undefined;
this.copilotToolLimitNoticeSessionId = undefined;
this.clearPendingTools();
// The rebuilt transcript re-derives continuity notices from persisted
// messages, so the tracker's suppression state must not survive the
// rebuild (or a session switch) — otherwise the first disabled notice
// would silently disappear from the rebuilt transcript.
// Optional-chained: renderSessionItems is exercised by tests with a
// minimal `this` that has no tracker instance.
this.continuityNotices?.reset?.();
const renderedPendingTools = new Map();
// Cache-miss notices are not persisted; re-derive them from the full entry
// list and re-inject them after the assistant messages that paid for them.
const cacheMisses = this.settingsManager.getShowCacheMissNotices()
? collectCacheMisses(this.sessionManager.getEntries(), this.session.modelRuntime)
: new Map();
if (options.updateFooter) {
this.footer.invalidate();
this.updateEditorBorderColor();
}
for (const item of items) {
if (isCustomSessionEntry(item)) {
this.addCustomEntryToChat(item);
continue;
}
if (isCompactionCostNotice(item)) {
this.addCompactionCostNotice(item);
continue;
}
if (isModelChangeNotice(item)) {
this.addModelChangeNotice(item);
continue;
}
const message = item;
// Assistant messages need special handling for tool calls
if (message.role === "assistant") {
replayAssistantTools(message, {
expanded: this.toolOutputExpanded,
addMessage: (part, ownsTurnNotice) => this.addMessageToChat(part, { replayOwnsTurnNotice: ownsTurnNotice }),
addChild: (component) => this.chatContainer.addChild(component),
createTool: (name, id, args) => this.createToolExecutionComponent(name, id, args),
pending: renderedPendingTools,
});
if (message.stopReason !== "aborted" && message.stopReason !== "error") {
this.maybeShowAssistantDiagnostics?.(message, { replay: true });
const miss = cacheMisses.get(message);
if (miss)
this.addCacheMissNotice(miss);
}
// Continuity notices are not persisted either; re-inject them while
// rendering persisted assistant messages the same way the live
// streaming path does. Optional-chained for minimal-`this` tests.
this.addContinuityNotice?.(message);
}
else if (message.role === "toolResult") {
// Match tool results to pending tool components
const component = renderedPendingTools.get(message.toolCallId);
if (component) {
component.updateResult(message);
renderedPendingTools.delete(message.toolCallId);
}
}
else {
// All other messages use standard rendering
this.addMessageToChat(message, options);
}
}
for (const [toolCallId, component] of renderedPendingTools) {
this.pendingTools.set(toolCallId, component);
}
this.ui.requestRender();
}
/**
* Render session entries to chat. Used for initial load and rebuild after compaction.
* @param entries Compaction-aware session entries to render
* @param options.updateFooter Update footer state
* @param options.populateHistory Add user messages to editor history
*/
renderSessionEntries(entries, options = {}) {
const items = entries.flatMap((entry) => {
if (entry.type === "custom") {
return [entry];
}
if (entry.type === "model_change") {
const notice = replayedModelChangeNotice(entry);
return notice === undefined ? [] : [notice];
}
const messages = sessionEntryToContextMessages(entry);
if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage && messages.length > 0) {
return [...messages, { type: "compaction_cost", kind: entry.type, usage: entry.usage }];
}
return messages;
});
this.renderSessionItems(items, options);
}
/**
* Render billing usage for a compaction or branch summary. The notice is derived
* from persisted summary usage and is not stored as a separate session entry.
*/
addModelChangeNotice(notice) {
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", notice.text), 1, 0));
}
addCompactionCostNotice(notice) {
if (!this.settingsManager.getShowCacheMissNotices())
return;
const { usage } = notice;
const tokens = usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
const cost = usage.cost.total >= 0.01 ? ` (~$${usage.cost.total.toFixed(2)})` : "";
const label = notice.kind === "compaction" ? "Compaction" : "Branch summary";
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", `${label}: ${formatTokens(tokens)} tokens billed${cost}`), 1, 0));
}
maybeShowAssistantDiagnostics(message, options) {
for (const diagnostic of message.diagnostics ?? []) {
if (diagnostic.type !== "github_copilot_tool_limit")
continue;
const notice = diagnostic.details?.message;
const sessionId = this.sessionManager.getSessionId();
if (typeof notice !== "string" || this.copilotToolLimitNoticeSessionId === sessionId)
continue;
this.copilotToolLimitNoticeSessionId = sessionId;
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", notice), 1, 0));
}
// Thinking-drop notices are live-only: on replay the branch's last assistant message is not the
// previous response the dedupe compares against. `?.` keeps this callable on a borrowed receiver.
if (!options?.replay)
this.maybeShowThinkingDropNotice?.(message);
}
static countDroppedThinkingBlocks(message) {
let count = 0;
for (const diagnostic of message.diagnostics ?? []) {
if (diagnostic.type !== "anthropic_input_transformations")
continue;
const transformations = diagnostic.details?.transformations;
if (!Array.isArray(transformations))
continue;
count += transformations.filter((transformation) => typeof transformation === "object" &&
transformation !== null &&
transformation.type === "thinking_dropped").length;
}
return count;
}
maybeShowThinkingDropNotice(message) {
if (!this.settingsManager.getShowCacheMissNotices())
return;
const droppedCount = InteractiveMode.countDroppedThinkingBlocks(message);
if (droppedCount === 0)
return;
let previousDroppedCount = 0;
// message_end reaches the UI before the current message is persisted,
// so the branch's last assistant message is the previous response.
const branch = this.sessionManager.getBranch();
for (let i = branch.length - 1; i >= 0; i--) {
const entry = branch[i];
if (entry.type === "message" && entry.message.role === "assistant") {
previousDroppedCount = InteractiveMode.countDroppedThinkingBlocks(entry.message);
break;
}
}
if (droppedCount <= previousDroppedCount)
return;
const noun = droppedCount === 1 ? "thinking block" : "thinking blocks";
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", `Anthropic dropped ${droppedCount} ${noun} (details in session)`), 1, 0));
}
/**
* Show a transcript notice when a completed assistant message paid for a
* significant cache miss. Only states observable facts: the miss itself,
* a model switch, or an idle gap past the cache TTL.
*/
/** Muted single-line notice for degraded session continuity; healthy turns stay silent. */
addContinuityNotice(message) {
const notice = this.continuityNotices.noticeFor(message);
if (!notice)
return;
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new Text(notice, 1, 0));
}
maybeShowCacheMissNotice(message) {
if (!this.settingsManager.getShowCacheMissNotices())
return;
// Entries don't contain `message` yet: message_end fires before persistence.
const miss = detectCacheMiss(this.sessionManager.getEntries(), message, this.session.modelRuntime);
if (miss)
this.addCacheMissNotice(miss);
}
addCacheMissNotice(miss) {
if (miss.missedTokens < 20_000 && miss.missedCost < 0.1)
return;
const cost = miss.missedCost >= 0.01 ? ` (~$${miss.missedCost.toFixed(2)})` : "";
const reBilled = `${formatTokens(miss.missedTokens)} tokens re-billed${cost}`;
let label = "Cache miss";
if (miss.modelChanged) {
label = "Cache miss after model switch";
}
else if (miss.idleMs >= CACHE_TTL_MS) {
label = `Cache miss after ${Math.round(miss.idleMs / 60_000)}m idle`;
}
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", `${label}: ${reBilled}`), 1, 0));
}
renderInitialMessages() {
// Any full transcript rerender ends the external-owner delegation episode:
// the rendered notice is gone, so the guard must re-arm and the footer
// marker must not persist as stale state.
this.externalOwnerCompactionNoticeShown = false;
this.footer?.setCompactionDelegated?.(false);
const entries = this.sessionManager.buildContextEntries();
this.renderSessionEntries(entries, {
updateFooter: true,
populateHistory: true,
});
this.renderProjectTrustWarningIfNeeded();
// Show compaction info if session was compacted
const compactionCount = this.sessionManager.countCompactions();
if (compactionCount > 0) {
const times = compactionCount === 1 ? "1 time" : `${compactionCount} times`;
this.showStatus(`Session compacted ${times}`);
}
}
renderProjectTrustWarningIfNeeded() {
if (this.settingsManager.isProjectTrusted() || !hasTrustRequiringProjectResources(this.sessionManager.getCwd())) {
return;
}
if (this.chatContainer.children.length > 0) {
this.chatContainer.addChild(new Spacer(1));
}
this.chatContainer.addChild(new ThemedText(() => 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));
}
async getUserInput() {
const queuedInput = this.pendingUserInputs.shift();
if (queuedInput !== undefined) {
return queuedInput;
}
return new Promise((resolve) => {
this.onInputCallback = (input) => {
this.onInputCallback = undefined;
resolve(input);
};
});
}
// Build the session.prompt options for a main-loop submission. The optimistic echo
// keeps only a prompt that actually started; a buffered prompt consumed by an input
// extension with action "handled" clears the retained working dock, but only once
// agent_idle has fired (the agentIdle latch) so a settlement-deferred continuation
// still in admission keeps its dock.
buildMainLoopPromptOptions(userInput) {
const echoOptions = this.optimisticUserEchoes.promptOptions(userInput.pendingEchoId);
return {
streamingBehavior: "steer",
...(userInput.images ? { images: userInput.images } : {}),
...(userInput.unknownCommandAsText ? { unknownCommandAsText: true } : {}),
preflightResult: echoOptions.preflightResult,
promptDisposition: (disposition) => {
echoOptions.promptDisposition(disposition);
userInput.ticket?.release();
// Clear the retained dock on a handled prompt only when it was the last
// buffered input; a still-queued follow-up remounts it on agent_start, so
// clearing here would bounce the editor/footer.
if (disposition === "handled" && this.agentIdle && this.pendingUserInputs.length === 0) {
this.clearStatusIndicator("working");
this.ui.requestRender();
}
},
};
}
rebuildChatFromMessages() {
try {
this.sessionManager?.reloadFromDisk?.();
}
catch {
// Keep in-memory entries if file reload is unavailable
}
this.chatContainer.clear();
this.renderSessionEntries(this.sessionManager.buildContextEntries());
}
// =========================================================================
// Key handlers
// =========================================================================
handleCtrlC() {
const now = Date.now();
if (now - this.lastSigintTime < 500) {
void this.shutdown();
}
else {
this.clearEditor();
this.lastSigintTime = now;
}
}
handleCtrlD() {
// Only called when editor is empty (enforced by CustomEditor)
void this.shutdown();
}
async shutdown(options) {
if (this.isShuttingDown)
return;
this.isShuttingDown = true;
this.mcpMrtrPresentationLifetime?.abort();
// Keep signal handlers registered until terminal cleanup has completed.
// `signal-exit` checks the listener list during the same SIGTERM/SIGHUP
// dispatch and re-sends the signal if only its own listeners remain.
if (options?.fromSignal) {
// Signal-triggered shutdown (SIGTERM/SIGHUP). Emit extension cleanup
// (session_shutdown) BEFORE touching the terminal. Extension teardown
// such as removing sockets does not write to the tty, so it must not be
// skipped if a later terminal-restore write fails on a dead or stalled
// terminal. If the terminal is gone, the restore writes below emit EIO,
// which the stdout/stderr error handler turns into emergencyTerminalExit;
// the render loop is already idle, so this cannot hot-spin (see #4144).
await this.sessionControlHost?.disposeActive();
await this.runtimeHost.dispose({ processExit: true, endActiveRun: true });
this.themeController.disableAutoSync();
await this.ui.terminal.drainInput(1000);
this.stop();
process.exit(0);
}
// Interactive quit (Ctrl+D, Ctrl+C, /quit, extension shutdown()). Stop the
// TUI before emitting shutdown events so extension UI cleanup cannot repaint
// the final frame while the process is exiting.
// Drain any in-flight Kitty key release events before stopping.
// This prevents escape sequences from leaking to the parent shell over slow SSH.
this.themeController.disableAutoSync();
await this.ui.terminal.drainInput(1000);
this.stop({ restoreStderr: false });
try {
await this.sessionControlHost?.disposeActive();
await this.runtimeHost.dispose({ processExit: true, endActiveRun: true });
}
finally {
restoreInteractiveStderr();
}
const resumeCommand = formatResumeCommand(this.sessionManager);
if (resumeCommand) {
process.stdout.write(`${chalk.dim("To resume this session:")} ${resumeCommand}\n`);
}
process.exit(0);
}
emergencyTerminalExit(crash) {
this.isShuttingDown = true;
// This exit is silent by design (the terminal is gone, so a banner would go
// nowhere), which makes the debug log the ONLY surface that can record this
// crash class — exactly the EIO case that left the 2026-08-26 diagnosis with no
// evidence. Write before the cleanup below, which is unguarded and could throw.
// A logging failure must never alter the exit path.
try {
appendUncaughtCrashLog(crash.origin, crash.error);
}
catch { }
this.unregisterSignalHandlers();
killTrackedDetachedChildren();
// The terminal is gone. Do not run normal shutdown because TUI and
// extension cleanup can write restore sequences and re-trigger EIO.
process.exit(129);
}
/**
* Last-resort handler for uncaught exceptions. The TUI puts stdin into raw
* mode and hides the cursor; without this handler, an uncaught throw from
* anywhere (e.g. an extension's async `ChildProcess.on("exit")` callback)
* tears down the process while leaving the terminal in raw mode with no
* cursor, requiring `stty sane && reset` to recover.
*
* Unlike emergencyTerminalExit, the terminal is still alive here, so we
* call ui.stop() to restore cooked mode, the cursor, and disable bracketed
* paste / Kitty / modifyOtherKeys sequences.
*/
uncaughtCrash(error, origin) {
if (this.isShuttingDown) {
process.exit(1);
}
if (isDeadTerminalError(error)) {
// The terminal died under the session (e.g. an stdin read EIO after
// the controlling terminal vanished or this pgrp lost the tty
// foreground). Same handling as terminal write errors: exit silently
// instead of printing a crash banner to a terminal that is gone.
this.emergencyTerminalExit({ origin: `dead-terminal ${origin}`, error });
}
if (isRecoverableInspectorVmImportError(error, origin)) {
this.showWarning(INSPECTOR_VM_IMPORT_WARNING);
return;
}
if (containStaleExtensionError(error, origin))
return;
this.isShuttingDown = true;
try {
this.unregisterSignalHandlers();
}
catch { }
try {
killTrackedDetachedChildren();
}
catch { }
try {
this.pauseQuestionMouseCapture();
this.ui.stop();
}
catch { }
// Record the crash before the terminal handoff: the banner below only reaches
// terminal scrollback, which is gone when the terminal is closed or is itself
// the thing that failed. A logging failure must never alter the crash path.
let logged = false;
try {
appendUncaughtCrashLog(origin, error);
logged = true;
}
catch { }
restoreInteractiveStderr();
const storageMessage = storageWriteCrashMessage(error);
if (storageMessage !== undefined) {
console.error(storageMessage);
}
// The full stack lives in the debug log; the restored terminal gets one readable line and
// where to look. Only a failed log write falls back to printing the whole error.
const summary = (error instanceof Error ? `${error.name}: ${error.message}` : String(error)).split("\n")[0];
console.error(`${APP_NAME} exiting due to uncaughtException: ${summary}`);
if (logged)
console.error(`Details: ${getDebugLogPath()}`);
else
console.error(error);
// A stack frame from a loaded extension points the user at the likely culprit.
const extensionHint = this.getCrashExtensionHint?.(error);
if (extensionHint)
console.error(`\n${extensionHint}`);
process.exit(1);
}
/**
* An unhandled rejection is a bug, not something the user can act on, and Bun keeps the
* process running after one. It goes to the debug log and never to the terminal the TUI is
* drawing on (#2284).
*/
unhandledRejection(reason) {
if (isDeadTerminalError(reason)) {
this.emergencyTerminalExit({ origin: "dead-terminal unhandledRejection", error: reason });
}
if (isRecoverableInspectorVmImportError(reason, "unhandledRejection")) {
this.showWarning(INSPECTOR_VM_IMPORT_WARNING);
return;
}
try {
appendUnhandledRejectionLog(reason);
}
catch { }
}
/**
* Record an extension shutdown request and honor it as soon as it is safe to do so.
*
* An idle session emits no further `agent_settled`, and that event is the only
* consumer of the deferred flag, so an idle request must shut down here or it
* strands until the user happens to run another turn.
*/
requestExtensionShutdown() {
this.shutdownRequested = true;
if (this.session.isIdle) {
void this.shutdown();
}
}
/**
* Check if shutdown was requested and perform shutdown if so.
*/
async checkShutdownRequested() {
if (!this.shutdownRequested)
return;
await this.shutdown();
}
registerSignalHandlers() {
this.unregisterSignalHandlers();
const signals = ["SIGTERM"];
if (process.platform !== "win32") {
signals.push("SIGHUP");
}
for (const signal of signals) {
const handler = () => {
// SIGHUP no longer hard-exits: graceful shutdown emits session_shutdown
// first, then attempts terminal restore. A genuinely dead terminal
// surfaces as an EIO on the restore writes, which the stdout/stderr
// error handler converts into emergencyTerminalExit (see #4144, #5080).
killTrackedDetachedChildren();
void this.shutdown({ fromSignal: true });
};
process.prependListener(signal, handler);
this.signalCleanupHandlers.push(() => process.off(signal, handler));
}
const terminalErrorHandler = (error) => {
if (isDeadTerminalError(error)) {
this.emergencyTerminalExit({ origin: "dead-terminal stdio error", error });
}
throw error;
};
process.stdout.on("error", terminalErrorHandler);
process.stderr.on("error", terminalErrorHandler);
this.signalCleanupHandlers.push(() => process.stdout.off("error", terminalErrorHandler));
this.signalCleanupHandlers.push(() => process.stderr.off("error", terminalErrorHandler));
// Restore the terminal before the process dies on any uncaught throw.
// Without this, an unhandled exception from extension code (or anywhere
// in pi) leaves the terminal in raw mode with no cursor.
const uncaughtExceptionHandler = (error, origin) => this.uncaughtCrash(error, origin);
markModeCrashHandler(uncaughtExceptionHandler);
process.prependListener("uncaughtException", uncaughtExceptionHandler);
this.signalCleanupHandlers.push(() => process.off("uncaughtException", uncaughtExceptionHandler));
const unhandledRejectionHandler = (reason) => this.unhandledRejection(reason);
markModeCrashHandler(unhandledRejectionHandler);
process.prependListener("unhandledRejection", unhandledRejectionHandler);
this.signalCleanupHandlers.push(() => process.off("unhandledRejection", unhandledRejectionHandler));
this.signalCleanupHandlers.push(subscribeProviderAccountEvents((event) => {
if (event.type === "failover")
this.showStatus(formatAccountFailoverNotice(event));
}));
// Surface Inspector rejections that the early bootstrap seam recovered before this
// handler (and the TUI warning surface) existed.
if (consumeEarlyInspectorVmImportRecoveries() > 0) {
this.showWarning(INSPECTOR_VM_IMPORT_WARNING);
}
}
unregisterSignalHandlers() {
for (const cleanup of this.signalCleanupHandlers) {
cleanup();
}
this.signalCleanupHandlers = [];
}
handleCtrlZ() {
if (process.platform === "win32") {
this.showStatus("Suspend to background is not supported on Windows");
return;
}
// Keep the event loop alive while suspended. Without this, stopping the TUI
// can leave Node with no ref'ed handles, causing the process to exit on fg
// before the SIGCONT handler gets a chance to restore the terminal.
const suspendKeepAlive = setInterval(() => { }, 2 ** 30);
// Ignore SIGINT while suspended so Ctrl+C in the terminal does not
// kill the backgrounded process. The handler is removed on resume.
const ignoreSigint = () => { };
process.on("SIGINT", ignoreSigint);
// Set up handler to restore TUI when resumed
process.once("SIGCONT", () => {
clearInterval(suspendKeepAlive);
process.removeListener("SIGINT", ignoreSigint);
takeOverInteractiveStderr();
this.ui.start();
this.resumeQuestionMouseCapture();
this.ui.requestRender(true);
});
try {
// Stop the TUI (restore terminal to normal mode)
restoreInteractiveStderr();
this.pauseQuestionMouseCapture();
this.ui.stop();
// Send SIGTSTP to process group (pid=0 means all processes in group)
process.kill(0, "SIGTSTP");
}
catch (error) {
clearInterval(suspendKeepAlive);
process.removeListener("SIGINT", ignoreSigint);
throw error;
}
}
async handleFollowUp() {
this.setComposerReply();
const rawText = this.getExpandedEditorText();
const text = rawText.trim();
if (!text)
return;
const unknownCommandAsText = submitsCommandAsText(text, { rawText });
if (isBareSkillNamespace(text)) {
this.openSkillPickerForBareNamespace();
return;
}
// Queue non-command input during compaction; dispatch extension commands.
// This is the Alt+Enter path (bound directly to app.message.followUp), which
// does NOT pass through onSubmit, so the isExtensionCommand check below is the
// live dispatch point here: commands go straight to AgentSession.prompt(),
// which runs them immediately even while compaction is active, while ordinary
// text is queued for delivery after compaction settles. Image attachments
// are consumed and dropped VISIBLY inside queueCompactionSubmission - the
// queue is text-only, so resolving them here and queueing the text with a
// dead marker would lose the images without telling the user.
if (this.session.isCompacting) {
if (this.isExtensionCommand(text)) {
this.editor.addToHistory?.(text);
this.editor.setText("");
await this.session.prompt(text);
}
else {
this.queueCompactionSubmission(text, "followUp", InteractiveMode.confirmsRefusedUnknownCommand(this, text) || unknownCommandAsText);
}
return;
}
// Resolve attachments BEFORE any setText("") below: the editor's prune
// chain fires onImageMarkersChanged([]) and the reconciler destroys
// pendingImages, so resolving after the clear would ship a literal
// `[Image #N]` with no attachment behind it.
const images = this.takeSubmissionImages(text);
// Alt+Enter queues a follow-up message (waits until agent finishes).
// Extension commands are dispatched without an optimistic echo here too,
// mirroring the Enter path: the command runs inside AgentSession.prompt()
// immediately and renders its own UI (e.g. the /btw panel), so an echo
// bubble would duplicate it. The followUp echo applies only to ordinary
// text, prompt template expansion, and queueing.
if (this.session.isStreaming) {
this.editor.addToHistory?.(text);
this.editor.setText("");
if (this.isExtensionCommand(text)) {
await this.session.prompt(text);
return;
}
const pendingEchoId = this.beginUserEcho(text, images);
const followUpAsText = InteractiveMode.confirmsRefusedUnknownCommand(this, text) || unknownCommandAsText;
try {
await this.session.prompt(text, {
streamingBehavior: "followUp",
...(images.length > 0 ? { images } : {}),
...(followUpAsText ? { unknownCommandAsText: true } : {}),
...this.optimisticUserEchoes.promptOptions(pendingEchoId),
});
}
catch (error) {
this.optimisticUserEchoes.reject(pendingEchoId);
if (error instanceof UnknownCommandError && this.reportUnknownCommandRejection(error, text))
return;
throw error;
}
this.updatePendingMessagesDisplay();
this.ui.requestRender();
}
// If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)
else if (this.editor.onSubmit) {
// The public `onSubmit(text: string)` API cannot be widened, so hand
// the pre-resolved images over out-of-band; the submit handler
// captures-and-clears the field at entry and delivers them through the
// widened main-loop channel.
this.preResolvedSubmissionImages = images.length > 0 ? images : undefined;
this.editor.setText("");
this.editor.onSubmit(text, { rawText });
}
}
handleDequeue() {
const restored = this.restoreQueuedMessagesToEditor();
if (restored === 0) {
this.showStatus("No queued messages to restore");
}
else {
this.showStatus(`Restored ${restored} queued message${restored > 1 ? "s" : ""} to editor`);
}
}
updateEditorBorderColor() {
if (this.chrome) {
this.editor.borderColor = this.chrome.getEditorBorderColor({
isBashMode: this.isBashMode,
thinkingLevel: this.session.thinkingLevel || "off",
});
}
else if (this.isBashMode) {
this.editor.borderColor = theme.getBashModeBorderColor();
}
else {
const level = this.session.thinkingLevel || "off";
this.editor.borderColor = theme.getThinkingBorderColor(level);
}
this.activeStatusIndicator?.invalidate();
this.ui.requestRender();
}
async cycleThinkingLevel() {
// The level itself is rendered from the thinking_level_changed event; the
// returned value only distinguishes "model does not support thinking".
const newLevel = this.session.cycleThinkingLevel();
if (newLevel === undefined) {
this.showStatus("Current model does not support thinking");
}
}
async cycleModel(direction) {
try {
const result = await this.session.cycleModel(direction, { persistDefault: false });
if (result === undefined) {
const msg = this.session.favoriteModels.length > 0
? buildFavoriteCycleStatusMessage("single")
: buildFavoriteCycleStatusMessage("empty");
this.showStatus(msg);
}
else {
if ((result.skippedModels?.length ?? 0) > 0 && modelsAreEqual(result.model, this.session.model)) {
this.showStatus("No favorite model can fit the current context. Compact the session or start a new one.");
return;
}
this.footer.invalidate();
// A model switch ends any external-owner delegation episode.
this.externalOwnerCompactionNoticeShown = false;
this.footer?.setCompactionDelegated?.(false);
this.updateEditorBorderColor();
const thinkingStr = result.model.reasoning && result.thinkingLevel !== "off" ? ` (thinking: ${result.thinkingLevel})` : "";
const systemPromptStr = result.systemPromptChange?.systemPromptName
? `, optimized system prompt applied: ${result.systemPromptChange.systemPromptName}`
: "";
this.showStatus(`Switched to ${result.model.name || result.model.id}${thinkingStr}${systemPromptStr}`);
this.showRiskyMainModelWarning(result.model);
void this.maybeWarnAboutAnthropicSubscriptionAuth(result.model);
}
}
catch (error) {
this.showError(error instanceof Error ? error.message : String(error));
}
}
toggleToolOutputExpansion() {
this.setToolsExpanded(!this.toolOutputExpanded);
}
setToolsExpanded(expanded) {
if (expanded === this.toolOutputExpanded)
return;
this.toolOutputExpanded = expanded;
const activeHeader = this.customHeader ?? this.builtInHeader;
if (isExpandable(activeHeader)) {
activeHeader.setExpanded(expanded);
}
for (const container of [this.loadedResourcesContainer, this.chatContainer]) {
for (const child of container.children) {
if (isExpandable(child)) {
child.setExpanded(expanded);
}
}
}
this.showStatus(`Tool output: ${expanded ? "expanded" : "collapsed"}`);
}
toggleThinkingBlockVisibility() {
this.hideThinkingBlock = !this.hideThinkingBlock;
this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);
// Rebuild chat from session messages when the full mode is available. Test
// and embedding fakes may omit the rebuild seam; preserve their live chat.
if (this.rebuildChatFromMessages) {
this.chatContainer.clear();
this.rebuildChatFromMessages();
}
// If streaming, re-add the streaming component with updated visibility and re-render
if (this.streamingComponent && this.streamingMessage) {
this.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock);
this.streamingReveal.resyncVisibility();
this.chatContainer.addChild(this.streamingComponent);
}
this.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? "hidden" : "visible"}`);
}
async handleOpenExternalEditor() {
const editorCmd = this.settingsManager.getExternalEditorCommand();
const content = this.getExpandedEditorText();
const result = await this.withTerminalHandedOver(() => editInExternalEditor({
command: editorCmd,
content,
}));
if (result.status === "complete") {
this.editor.setText(result.content);
}
}
/**
* Runs `work` (an external program that draws on the terminal itself) with the terminal handed
* back: the TUI stops, fd 1 and fd 2 point at the terminal again, and both are taken over again
* afterwards. An editor launched without this would draw into the debug log (#2815).
*/
async withTerminalHandedOver(work) {
this.pauseQuestionMouseCapture();
this.ui.stop();
restoreInteractiveStderr();
try {
return await work();
}
finally {
takeOverInteractiveStderr();
this.ui.start();
this.resumeQuestionMouseCapture();
this.ui.requestRender(true);
}
}
// =========================================================================
// UI helpers
// =========================================================================
clearEditor() {
this.editor.setText("");
this.ui.requestRender();
}
showError(errorMessage) {
if (isNetworkProviderError(errorMessage, true)) {
this.getProviderErrors().record(errorMessage, this.toolOutputExpanded);
this.ui.requestRender();
return;
}
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new ThemedText(() => theme.fg("error", `Error: ${sanitizeTuiErrorMessage(interactiveErrorText(errorMessage))}`), 1, 0));
this.ui.requestRender();
}
getProviderErrors() {
this.providerErrors ??= new ProviderErrorPresentation(this.chatContainer);
return this.providerErrors;
}
showNoticeBox(spec) {
const sanitized = {
...spec,
title: sanitizeTuiErrorMessage(spec.title),
why: sanitizeTuiErrorMessage(spec.why),
...(spec.extra === undefined
? {}
: {
extra: spec.extra.map((line) => ({
...line,
text: sanitizeTuiErrorMessage(line.text),
})),
}),
...(spec.expandedLine === undefined ? {} : { expandedLine: sanitizeTuiErrorMessage(spec.expandedLine) }),
};
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(buildNoticeBox(sanitized, { expanded: this.toolOutputExpanded }, theme));
this.ui.requestRender();
}
showWarning(warningMessage) {
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", `Warning: ${warningMessage}`), 1, 0));
this.ui.requestRender();
}
showNewVersionNotification(newVersion) {
const action = BRAND?.update?.command ?? `${APP_NAME} update`;
const changelogUrl = getReleaseChangelogUrl(newVersion);
const changelogLink = getCapabilities().hyperlinks ? hyperlink(changelogUrl, changelogUrl) : changelogUrl;
this.showNoticeBox({
title: "Update Available",
tone: "warning",
why: `New version ${newVersion} is available.`,
extra: [{ text: action }, { text: `Changelog: ${changelogLink}`, tone: "accent" }],
});
}
showRiskyMainModelWarning(model) {
if (!model || !isRiskyMainModel(model))
return;
this.showNoticeBox({ title: "Risky model warning", tone: "error", why: RISKY_MAIN_MODEL_WARNING });
}
showSettingsSourceSelected(event) {
this.showStatus(`Settings: ${path.basename(event.path)} (${event.format.toUpperCase()})`);
}
showHighReasoningWarning(event) {
const { title, body } = buildHighReasoningWarning({ id: event.modelId, provider: event.provider }, event.thinkingLevel);
this.showNoticeBox({
title,
tone: "error",
why: body[0] ?? "High reasoning may affect reliability or cost.",
extra: body.slice(1).map((text) => ({ text, tone: "error" })),
});
}
showPackageUpdateNotification(packages) {
this.showNoticeBox({
title: "Package Updates Available",
tone: "warning",
why: `Package updates are available. Run ${APP_NAME} update --extensions`,
extra: [
{ text: "Packages:", tone: "dim" },
...packages.map((pkg) => ({ text: `- ${pkg}`, tone: "dim" })),
],
});
}
/**
* Get all queued messages (read-only).
* Combines session queue and compaction queue.
*/
getAllQueuedMessages() {
return {
steering: [
...this.session.getSteeringMessages(),
...this.compactionInFlightMessages.filter((msg) => msg.mode === "steer").map((msg) => msg.text),
...this.compactionQueuedMessages.filter((msg) => msg.mode === "steer").map((msg) => msg.text),
],
followUp: [
...this.session.getFollowUpMessages(),
...this.compactionInFlightMessages.filter((msg) => msg.mode === "followUp").map((msg) => msg.text),
...this.compactionQueuedMessages.filter((msg) => msg.mode === "followUp").map((msg) => msg.text),
],
};
}
/**
* Clear all queued messages and return their contents.
* Clears both session queue and compaction queue.
*/
clearAllQueues(options = { abortWillFollow: false }) {
const clearedNative = this.session.clearQueue(options);
const { steering, followUp } = clearedNative;
const nativeMessages = clearedNative.ordered ?? [
...steering.map((text, enqueueOrder) => ({
text,
mode: "steer",
enqueueOrder,
})),
...followUp.map((text, index) => ({
text,
mode: "followUp",
enqueueOrder: steering.length + index,
})),
];
const compactionMessages = [...this.compactionInFlightMessages, ...this.compactionQueuedMessages];
const compactionSteering = compactionMessages.filter((msg) => msg.mode === "steer").map((msg) => msg.text);
const compactionFollowUp = compactionMessages.filter((msg) => msg.mode === "followUp").map((msg) => msg.text);
for (const controller of this.compactionTransferAbortControllers.values())
controller.abort();
this.compactionInFlightMessages = [];
this.compactionTransferAbortControllers.clear();
this.compactionQueuedMessages = [];
for (const message of compactionMessages) {
if (message.pendingEchoId)
this.optimisticUserEchoes?.remove(message.pendingEchoId);
}
const fallbackOrder = nativeMessages.reduce((maximum, message) => Math.max(maximum, message.enqueueOrder), 0);
const ordered = [
...nativeMessages,
...compactionMessages.map((message, index) => ({
...message,
enqueueOrder: message.enqueueOrder ?? fallbackOrder + index + 1,
})),
].sort((a, b) => a.enqueueOrder - b.enqueueOrder);
const cleared = {
steering: [...steering, ...compactionSteering],
followUp: [...followUp, ...compactionFollowUp],
};
Object.defineProperty(cleared, "ordered", {
value: ordered,
enumerable: false,
});
return cleared;
}
updatePendingMessagesDisplay() {
this.sessionControlHost?.noteBufferedElsewhere(this.compactionQueuedMessages.length + this.compactionInFlightMessages.length > 0);
this.pendingMessagesContainer.clear();
const { steering: steeringMessages, followUp: followUpMessages } = this.getAllQueuedMessages();
if (steeringMessages.length > 0 || followUpMessages.length > 0) {
this.pendingMessagesContainer.addChild(new Spacer(1));
for (const message of steeringMessages) {
const text = theme.fg("dim", `Steering: ${message}`);
this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));
}
for (const message of followUpMessages) {
const text = theme.fg("dim", `Follow-up: ${message}`);
this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));
}
const dequeueHint = this.getAppKeyDisplay("app.message.dequeue");
const hintText = theme.fg("dim", `↳ ${dequeueHint} to edit all queued messages`);
this.pendingMessagesContainer.addChild(new TruncatedText(hintText, 1, 0));
}
}
restoreQueuedMessagesToEditor(options) {
const { steering, followUp, ordered } = this.clearAllQueues({
abortWillFollow: options?.abort === true,
});
const allQueued = ordered?.map((message) => message.text) ?? [...steering, ...followUp];
if (allQueued.length === 0) {
this.updatePendingMessagesDisplay();
if (options?.abort) {
void this.session.abort();
}
return 0;
}
const queuedText = allQueued.join("\n\n");
const currentText = options?.currentText ?? this.editor.getText();
const combinedText = [queuedText, currentText].filter((t) => t.trim()).join("\n\n");
this.editor.setText(combinedText);
this.updatePendingMessagesDisplay();
if (options?.abort) {
void this.session.abort();
}
return allQueued.length;
}
/**
* User-abort path that drains the queue, aborts the active run (and any in-flight retry),
* waits for settle, then restores queued messages to the editor.
*
* Behavior contract:
* - clearAllQueues() is called synchronously so the pending-messages display empties immediately.
* - `await session.abort()` ensures the previous run is fully idle before touching the draft.
* - The helper never auto-prompts restored queue text; the user decides whether to send it.
*/
async abortAndFireQueuedMessages() {
const { steering, followUp, ordered } = this.clearAllQueues({
abortWillFollow: true,
});
const allQueued = ordered?.map((message) => message.text) ?? [...steering, ...followUp];
this.updatePendingMessagesDisplay();
await this.session.stop();
if (allQueued.length === 0) {
return 0;
}
const queuedText = allQueued.join("\n\n");
const currentText = this.editor.getText();
const combinedText = [queuedText, currentText].filter((t) => t.trim()).join("\n\n");
this.editor.setText(combinedText);
return allQueued.length;
}
/** Restore an unknown-command submission to the editor with a warning; `false` for any other error. */
reportUnknownCommandRejection(error, submittedText) {
const sendAgain = `${keyDisplayText("tui.input.submit")} again sends it as a message`;
return reportUnknownCommand(error, submittedText, {
editor: this.editor,
armConfirmation: (text) => {
this.refusedUnknownCommandText = text;
},
confirmHint: this.session.isStreaming
? `${sendAgain}.`
: `${sendAgain}; ${keyDisplayText("app.interrupt")} keeps editing.`,
showWarning: (message) => this.showWarning(message),
});
}
queueCompactionMessage(text, mode, droppedImageCount = 0, unknownCommandAsText = false) {
// No optimistic echo here: compaction-queued input is waiting state and must
// render only in the pending-messages display until it is actually delivered.
this.compactionQueuedMessages.push({
text,
mode,
enqueueOrder: this.session.reserveQueuedInputOrder(),
...(unknownCommandAsText ? { unknownCommandAsText } : {}),
});
this.getSessionLogger().debug("compaction_queue_enqueue", {
mode,
count: this.compactionQueuedMessages.length,
});
this.editor.addToHistory?.(text);
this.editor.setText("");
this.updatePendingMessagesDisplay();
this.showStatus(droppedImageCount > 0
? `Queued message for after compaction; dropped ${droppedImageCount} image${droppedImageCount > 1 ? "s" : ""}: messages sent during compaction cannot carry images - paste again after compaction finishes`
: "Queued message for after compaction");
}
/**
* Queue a user submission for delivery after compaction. The compaction
* queue carries text only, so pasted attachments are dropped here -
* VISIBLY, never silently, mirroring attachClipboardImage's paste-time
* contract - and their `[Image #N]` markers are stripped, because a queued
* literal marker has no payload behind it and would ship an unreadable
* `[Image #N]` string to the model once the queue drains.
*/
queueCompactionSubmission(text, mode, unknownCommandAsText = false) {
const images = this.takeSubmissionImages(text);
if (images.length === 0) {
this.queueCompactionMessage(text, mode, 0, unknownCommandAsText);
return;
}
const queued = text.replace(IMAGE_MARKER_PATTERN, "").trim();
if (queued) {
this.queueCompactionMessage(queued, mode, images.length, unknownCommandAsText);
return;
}
this.showStatus(`Dropped ${images.length} image${images.length > 1 ? "s" : ""}: messages sent during compaction cannot carry images - paste again after compaction finishes`);
}
hasRegisteredCommand(command) {
return !!this.session.extensionRunner.getCommand(command);
}
/**
* `/skill` and `/skill:` name the skill namespace, not a skill, so they never reach the model:
* the editor is reset to `/skill:` with the skill list open, or a warning explains why it is empty.
*/
openSkillPickerForBareNamespace() {
if (!this.settingsManager.getEnableSkillCommands()) {
this.showWarning("Skill commands are disabled (enableSkillCommands setting).");
this.editor.setText("");
return;
}
if (this.session.resourceLoader.getSkills().skills.length === 0) {
this.showWarning("No skills are loaded.");
this.editor.setText("");
return;
}
this.editor.setText("/skill:");
this.editor.openAutocomplete?.();
}
isExtensionCommand(text) {
if (!text.startsWith("/"))
return false;
const extensionRunner = this.session.extensionRunner;
const spaceIndex = text.indexOf(" ");
const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
return !!extensionRunner.getCommand(commandName);
}
async flushCompactionQueue(options) {
const session = this.session;
const generation = this.compactionQueueGeneration ?? 0;
const previousFlush = this.compactionQueueFlushTail;
const runTransfer = async () => {
if ((this.compactionQueueGeneration ?? 0) !== generation || this.session !== session)
return;
await transferCompactionQueue({
takeBatch: () => {
const batch = this.compactionQueuedMessages;
this.compactionQueuedMessages = [];
this.compactionInFlightMessages.push(...batch);
for (const message of batch) {
this.compactionTransferAbortControllers.set(message, new AbortController());
}
this.updatePendingMessagesDisplay();
return batch;
},
commitAccepted: (message) => {
const index = this.compactionInFlightMessages.indexOf(message);
if (index === -1)
return false;
this.compactionInFlightMessages.splice(index, 1);
this.compactionTransferAbortControllers.delete(message);
this.updatePendingMessagesDisplay();
return true;
},
restoreUndelivered: (messages) => {
const restorable = messages.filter((message) => this.compactionInFlightMessages.includes(message));
const restorableSet = new Set(restorable);
this.compactionInFlightMessages = this.compactionInFlightMessages.filter((message) => !restorableSet.has(message));
for (const message of restorable)
this.compactionTransferAbortControllers.delete(message);
this.compactionQueuedMessages = [...restorable, ...this.compactionQueuedMessages];
this.updatePendingMessagesDisplay();
return restorable.length;
},
isCommand: (message) => this.isExtensionCommand(message.text),
deliverCommand: async (message) => {
const pendingEchoId = message.pendingEchoId;
try {
await session.prompt(message.text, pendingEchoId ? this.optimisticUserEchoes.promptOptions(pendingEchoId) : undefined);
}
catch (error) {
if (pendingEchoId)
this.optimisticUserEchoes.reject(pendingEchoId);
throw error;
}
},
deliverFirstPrompt: (message) => waitForPromptDisposition((preflightResult, promptDisposition) => {
const echoOptions = message.pendingEchoId
? this.optimisticUserEchoes.promptOptions(message.pendingEchoId)
: undefined;
return session.prompt(message.text, {
streamingBehavior: message.mode,
...(message.unknownCommandAsText ? { unknownCommandAsText: true } : {}),
preflightResult: (success) => {
echoOptions?.preflightResult(success);
preflightResult(success);
},
promptDisposition: (disposition) => {
echoOptions?.promptDisposition(disposition);
promptDisposition(disposition);
},
signal: this.compactionTransferAbortControllers.get(message)?.signal,
});
}, (error) => {
if ((this.compactionQueueGeneration ?? 0) !== generation || this.session !== session)
return;
this.showError(`Queued prompt failed after acceptance: ${error instanceof Error ? error.message : String(error)}`);
}).catch((error) => {
// A rejected unknown command is consumed here, so it cannot block the queue behind it.
if (error instanceof UnknownCommandError &&
this.reportUnknownCommandRejection(error, message.text))
return "handled";
throw error;
}),
deliverQueued: (message) => {
if (message.enqueueOrder === undefined) {
return message.mode === "followUp" ? session.followUp(message.text) : session.steer(message.text);
}
return message.mode === "followUp"
? session.followUp(message.text, undefined, {
enqueueOrder: message.enqueueOrder,
})
: session.steer(message.text, undefined, {
enqueueOrder: message.enqueueOrder,
});
},
reportFailure: (error, undeliveredCount) => {
this.showError(`Failed to send queued message${undeliveredCount === 1 ? "" : "s"}: ${error instanceof Error ? error.message : String(error)}`);
},
}, options);
this.updatePendingMessagesDisplay();
};
const currentFlush = previousFlush ? previousFlush.then(runTransfer, runTransfer) : runTransfer();
const settledFlush = currentFlush.catch(() => undefined);
this.compactionQueueFlushTail = settledFlush;
try {
await currentFlush;
}
finally {
if (this.compactionQueueFlushTail === settledFlush)
this.compactionQueueFlushTail = undefined;
}
}
/** Move pending bash components from pending area to chat */
flushPendingBashComponents() {
for (const component of this.pendingBashComponents) {
this.pendingMessagesContainer.removeChild(component);
this.chatContainer.addChild(component);
}
this.pendingBashComponents = [];
}
// =========================================================================
// Selectors
// =========================================================================
disposeActiveSelector() {
if (this.secretInputCleanup)
this.hideExtensionInput();
const dispose = this.activeSelectorDispose;
this.activeSelectorToken = undefined;
this.activeSelectorDispose = undefined;
dispose?.();
}
/**
* Shows a selector component in place of the editor.
* @param create Factory that receives a `done` callback and returns the component and focus target
*/
showSelector(create) {
const token = {};
let dispose;
const done = () => {
dispose?.();
if (this.activeSelectorToken !== token)
return;
this.activeSelectorToken = undefined;
this.activeSelectorDispose = undefined;
this.editorContainer.clear();
this.editorContainer.addChild(this.editor);
this.ui.setFocus(this.editor);
};
const created = create(done);
dispose = created.dispose;
this.disposeActiveSelector();
this.activeSelectorToken = token;
this.activeSelectorDispose = dispose;
this.editorContainer.clear();
this.editorContainer.addChild(created.component);
this.ui.setFocus(created.focus);
this.ui.requestRender();
}
async showSettingsSelector() {
const availableThinkingLevels = this.session.getAvailableThinkingLevels();
this.showSelector((done) => {
// oxlint-disable-next-line eslint/prefer-const -- a closure reads it; const would throw in the TDZ if that closure ran before the assignment, so the rewrite is reviewed separately
let selector;
selector = new SettingsSelectorComponent({
autoCompact: this.session.autoCompactionEnabled,
showImages: this.settingsManager.getShowImages(),
imageWidthCells: this.settingsManager.getImageWidthCells(),
autoResizeImages: this.settingsManager.getImageAutoResize(),
blockImages: this.settingsManager.getBlockImages(),
enableSkillCommands: this.settingsManager.getEnableSkillCommands(),
steeringMode: this.session.steeringMode,
followUpMode: this.session.followUpMode,
transport: this.settingsManager.getTransport(),
httpIdleTimeoutMs: this.settingsManager.getHttpIdleTimeoutMs(),
thinkingLevel: this.session.thinkingLevel,
availableThinkingLevels,
currentTheme: this.themeController.getThemeSelection() || SYSTEM_THEME_NAME,
terminalTheme: this.themeController.getTerminalTheme(),
availableThemes: getAvailableThemes(),
hideThinkingBlock: this.hideThinkingBlock,
smoothStreaming: this.settingsManager.getSmoothStreaming(),
smoothStreamingFps: this.settingsManager.getSmoothStreamingFps(),
mermaidRenderingMode: this.settingsManager.getMermaidRenderingMode(),
collapseChangelog: this.settingsManager.getCollapseChangelog(),
enableInstallTelemetry: this.settingsManager.getEnableInstallTelemetry(),
doubleEscapeAction: this.settingsManager.getDoubleEscapeAction(),
treeFilterMode: this.settingsManager.getTreeFilterMode(),
showHardwareCursor: this.settingsManager.getShowHardwareCursor(),
showCacheMissNotices: this.settingsManager.getShowCacheMissNotices(),
defaultProjectTrust: this.settingsManager.getDefaultProjectTrust(),
editorPaddingX: this.settingsManager.getEditorPaddingX(),
outputPad: this.settingsManager.getOutputPad(),
autocompleteMaxVisible: this.settingsManager.getAutocompleteMaxVisible(),
quietStartup: this.settingsManager.getQuietStartup(),
clearOnShrink: this.settingsManager.getClearOnShrink(),
showTerminalProgress: this.settingsManager.getShowTerminalProgress(),
tuiMode: this.ui.mode,
fullscreenExitOutput: this.settingsManager.getFullscreenExitOutput(),
fullscreenScrollbar: this.settingsManager.getFullscreenScrollbar(),
fullscreenCopyOnSelect: this.settingsManager.getFullscreenCopyOnSelect?.() ?? true,
terminalMouse: this.settingsManager.getTerminalMouse(),
fullscreenWheelScrollLines: this.settingsManager.getFullscreenWheelScrollLines?.() ?? "auto",
warnings: this.settingsManager.getWarnings(),
}, {
onAutoCompactChange: (enabled) => {
this.settingsManager.setCompactionEnabled(enabled);
this.session.setAutoCompactionEnabled(enabled);
this.footer.setAutoCompactEnabled(enabled);
},
onShowImagesChange: (enabled) => {
this.settingsManager.setShowImages(enabled);
for (const child of this.chatContainer.children) {
if (child instanceof ToolExecutionComponent) {
child.setShowImages(enabled);
}
}
},
onImageWidthCellsChange: (width) => {
this.settingsManager.setImageWidthCells(width);
for (const child of this.chatContainer.children) {
if (child instanceof ToolExecutionComponent) {
child.setImageWidthCells(width);
}
}
},
onAutoResizeImagesChange: (enabled) => {
this.settingsManager.setImageAutoResize(enabled);
},
onBlockImagesChange: (blocked) => {
this.settingsManager.setBlockImages(blocked);
},
onEnableSkillCommandsChange: (enabled) => {
this.settingsManager.setEnableSkillCommands(enabled);
this.setupAutocompleteProvider();
},
onSteeringModeChange: (mode) => {
this.session.setSteeringMode(mode);
},
onFollowUpModeChange: (mode) => {
this.session.setFollowUpMode(mode);
},
onTransportChange: (transport) => {
this.settingsManager.setTransport(transport);
this.session.agent.transport = transport;
},
onHttpIdleTimeoutMsChange: (timeoutMs) => {
this.settingsManager.setHttpIdleTimeoutMs(timeoutMs);
configureHttpDispatcher(timeoutMs);
this.session.agent.timeoutMs = this.settingsManager.getAgentStreamIdleTimeoutMs();
this.session.agent.streamStartTimeoutMs = this.settingsManager.getAgentStreamStartTimeoutMs();
this.showStatus(`HTTP idle timeout: ${formatHttpIdleTimeoutMs(timeoutMs)}`);
},
onThinkingLevelChange: (level) => {
this.session.setThinkingLevel(level);
if (this.session.thinkingLevel !== "off" || this.session.supportsThinking()) {
this.settingsManager.setDefaultThinkingLevel(this.session.thinkingLevel);
}
this.footer.invalidate();
this.updateEditorBorderColor();
},
onThemeChange: (themeSetting) => {
this.settingsManager.setTheme(themeSetting);
this.themeController.setThemeSetting(themeSetting);
},
onThemePreview: (themeName) => this.themeController.preview(themeName),
onHideThinkingBlockChange: (hidden) => {
this.hideThinkingBlock = hidden;
this.settingsManager.setHideThinkingBlock(hidden);
for (const child of this.chatContainer.children) {
if (child instanceof AssistantMessageComponent) {
child.setHideThinkingBlock(hidden);
}
}
this.chatContainer.clear();
this.rebuildChatFromMessages();
if (this.streamingComponent && this.streamingMessage) {
this.streamingComponent.setHideThinkingBlock(hidden);
this.streamingReveal.resyncVisibility();
this.chatContainer.addChild(this.streamingComponent);
}
this.ui.requestRender();
},
onSmoothStreamingChange: (enabled) => {
this.settingsManager.setSmoothStreaming(enabled);
this.applySmoothStreamingRenderFps();
this.toolArgsReveal.refresh();
this.toolResultReveal.refresh();
if (this.streamingMessage) {
this.streamingReveal.setTarget(this.streamingMessage);
}
this.ui.requestRender();
},
onSmoothStreamingFpsChange: (fps) => {
this.settingsManager.setSmoothStreamingFps(fps);
this.toolArgsReveal.refresh();
this.toolResultReveal.refresh();
if (this.settingsManager.getSmoothStreaming()) {
this.applySmoothStreamingRenderFps();
if (this.streamingMessage) {
this.streamingReveal.setTarget(this.streamingMessage);
}
}
},
onMermaidRenderingModeChange: (mode) => {
this.settingsManager.setMermaidRenderingMode(mode);
this.chatContainer.invalidate();
this.ui.requestRender();
},
onShowCacheMissNoticesChange: (shown) => {
this.settingsManager.setShowCacheMissNotices(shown);
this.rebuildChatFromMessages();
},
onCollapseChangelogChange: (collapsed) => {
this.settingsManager.setCollapseChangelog(collapsed);
},
onEnableInstallTelemetryChange: (enabled) => {
this.settingsManager.setEnableInstallTelemetry(enabled);
},
onQuietStartupChange: (quiet) => {
this.settingsManager.setQuietStartup(quiet);
},
onDefaultProjectTrustChange: (defaultProjectTrust) => {
this.settingsManager.setDefaultProjectTrust(defaultProjectTrust);
},
onDoubleEscapeActionChange: (action) => {
this.settingsManager.setDoubleEscapeAction(action);
},
onTreeFilterModeChange: (mode) => {
this.settingsManager.setTreeFilterMode(mode);
},
onShowHardwareCursorChange: (enabled) => {
this.settingsManager.setShowHardwareCursor(enabled);
this.ui.setShowHardwareCursor(enabled);
},
onEditorPaddingXChange: (padding) => {
this.settingsManager.setEditorPaddingX(padding);
this.defaultEditor.setPaddingX(padding);
if (this.editor !== this.defaultEditor && this.editor.setPaddingX !== undefined) {
this.editor.setPaddingX(padding);
}
},
onOutputPadChange: (padding) => {
this.settingsManager.setOutputPad(padding);
this.outputPad = padding;
if (this.streamingComponent || this.session.isStreaming) {
for (const child of this.chatContainer.children) {
if (child instanceof AssistantMessageComponent ||
child instanceof CustomMessageComponent ||
child instanceof UserMessageComponent) {
child.setOutputPad(padding);
}
}
if (this.streamingComponent) {
this.streamingComponent.setOutputPad(padding);
}
this.ui.requestRender();
return;
}
this.rebuildChatFromMessages();
},
onAutocompleteMaxVisibleChange: (maxVisible) => {
this.settingsManager.setAutocompleteMaxVisible(maxVisible);
this.defaultEditor.setAutocompleteMaxVisible(maxVisible);
if (this.editor !== this.defaultEditor && this.editor.setAutocompleteMaxVisible !== undefined) {
this.editor.setAutocompleteMaxVisible(maxVisible);
}
},
onClearOnShrinkChange: (enabled) => {
this.settingsManager.setClearOnShrink(enabled);
this.ui.setClearOnShrink(enabled);
if (!enabled && !this.activeStatusIndicator) {
this.statusContainer.clear();
}
},
onShowTerminalProgressChange: (enabled) => {
this.settingsManager.setShowTerminalProgress(enabled);
},
onTerminalMouseChange: (mode) => {
if (this.renderer.hasOverlayEntries) {
selector?.getSettingsList().updateValue("terminal-mouse", this.terminalMouseMode);
this.showStatus("Close active overlays before changing mouse capture");
return;
}
this.settingsManager.setTerminalMouse(mode);
this.switchTuiMode(this.renderer.mode, true, true, true);
this.refreshAsyncWidget();
},
onTuiModeChange: (mode) => {
if (!this.switchTuiMode(mode)) {
selector?.getSettingsList().updateValue("tui-mode", this.ui.mode);
this.showStatus("Close active overlays before changing TUI mode");
return;
}
this.settingsManager.setTuiMode(mode);
if (!this.activeStatusIndicator)
this.statusContainer.clear();
this.showStatus(`TUI mode: ${mode}`);
},
onFullscreenExitOutputChange: (output) => {
this.settingsManager.setFullscreenExitOutput(output);
},
onFullscreenScrollbarChange: (mode) => {
this.settingsManager.setFullscreenScrollbar(mode);
this.applyFullscreenScrollbarSetting();
},
onFullscreenCopyOnSelectChange: (enabled) => {
this.settingsManager.setFullscreenCopyOnSelect(enabled);
if (this.renderer instanceof TuiAltScreen)
this.renderer.setCopyOnSelect(enabled);
},
onFullscreenWheelScrollLinesChange: (lines) => {
this.settingsManager.setFullscreenWheelScrollLines(lines);
if (this.renderer instanceof TuiAltScreen)
this.renderer.setWheelScrollLines(lines);
},
onWarningsChange: (warnings) => {
this.settingsManager.setWarnings(warnings);
},
onCancel: () => {
done();
this.ui.requestRender();
},
});
return { component: selector, focus: selector.getSettingsList() };
});
}
async handleThinkingCommand(searchTerm) {
if (!searchTerm) {
await this.showThinkingSelector();
return;
}
const availableLevels = this.session.getAvailableThinkingLevels();
const normalized = searchTerm.trim().toLowerCase();
const level = availableLevels.find((candidate) => candidate.toLowerCase() === normalized);
if (!level) {
this.showError(`Unknown thinking level "${searchTerm}". Available levels: ${availableLevels.join(", ")}.`);
return;
}
this.selectThinkingLevel(level, false);
}
/**
* `persist: false` scopes the level to this session; `persist: true` also
* records it as the model's remembered level (the Ctrl+S path of the selector).
*/
selectThinkingLevel(level, persist) {
try {
InteractiveMode.applyThinkingLevel(this, level, persist);
}
catch (error) {
this.showError(error instanceof Error ? error.message : String(error));
}
}
/**
* The level switch itself; the control endpoint's `set_thinking_level` runs it too.
* Static and called through the class, so a handler invoked on a partial `this`
* reaches exactly the members the switch uses.
*/
static applyThinkingLevel(mode, level, persist) {
if (persist) {
mode.session.setThinkingLevel(level);
if (mode.session.thinkingLevel !== "off" || mode.session.supportsThinking()) {
mode.settingsManager.setDefaultThinkingLevel(mode.session.thinkingLevel);
}
}
else
mode.session.setSessionThinkingLevel(level);
mode.footer.invalidate();
mode.updateEditorBorderColor();
mode.showStatus(persist ? `Default thinking level: ${level}` : `Thinking level: ${level}`);
}
async showThinkingSelector() {
const availableLevels = this.session.getAvailableThinkingLevels();
this.showSelector((done) => {
const selectLevel = (level, persist) => {
this.selectThinkingLevel(level, persist);
done();
};
const selector = new ThinkingSelectorComponent(this.session.thinkingLevel, availableLevels, (level) => selectLevel(level, false), () => {
done();
this.ui.requestRender();
}, (level) => selectLevel(level, true), this.settingsManager.getDefaultThinkingLevel());
return { component: selector, focus: selector };
});
}
async handleModelCommand(argument) {
const { searchTerm, asDefault } = parseModelCommandArgument(argument);
// --default needs the model it names; in the picker, the save chord does the same (senpi#2870).
if (asDefault && !searchTerm) {
this.showWarning("/model --default needs a model: /model <provider/id> --default, or Ctrl+S in the picker.");
this.showModelSelector();
return;
}
if (!searchTerm) {
this.showModelSelector();
return;
}
const model = await this.findExactModelMatch(searchTerm);
if (model) {
await this.selectModelFromUi(model, undefined, { origin: { source: "command" }, persistDefault: asDefault });
return;
}
if (asDefault)
this.showWarning(`No exact model match for "${searchTerm}"; pick one and press Ctrl+S to also make it the default.`);
this.showModelSelector(searchTerm);
}
async findExactModelMatch(searchTerm) {
const cachedModels = this.session.scopedModels.length > 0
? this.session.scopedModels.map((scoped) => scoped.model)
: [...this.session.modelRuntime.getAvailableSnapshot()];
const cachedMatch = findExactModelReferenceMatch(searchTerm, cachedModels);
if (cachedMatch || this.session.scopedModels.length > 0)
return cachedMatch;
this.showStatus("Refreshing model catalogs…");
const controller = new AbortController();
let timedOut = false;
const timeout = setTimeout(() => {
timedOut = true;
controller.abort();
}, 15_000);
try {
const result = await refreshModelCatalogs(this.session.modelRuntime, controller.signal);
if (result.aborted && timedOut) {
this.showWarning("Model refresh timed out; searching cached models.");
}
else if (result.errors.size > 0) {
this.showWarning(`Could not refresh ${[...result.errors.keys()].join(", ")}; searching cached models.`);
}
}
catch (error) {
this.showWarning(timedOut
? "Model refresh timed out; searching cached models."
: `Could not refresh model catalogs: ${error instanceof Error ? error.message : String(error)}`);
}
finally {
clearTimeout(timeout);
}
return findExactModelReferenceMatch(searchTerm, [...this.session.modelRuntime.getAvailableSnapshot()]);
}
async selectModelFromUi(model, done, selection) {
// The selector overlay is already disposed on Enter, so releasing it only
// after setModel resolves leaves a stale frozen frame for the whole provider
// auth round trip. Release and repaint first, then apply the switch.
done?.();
this.ui?.requestRender();
try {
await InteractiveMode.applyModelSelection(this, model, selection.origin, selection.persistDefault);
}
catch (error) {
this.showError(error instanceof Error ? error.message : String(error));
}
}
/**
* The `/model` switch itself; the control endpoint's `set_model` runs it too, and reports a throw.
* Static and called through the class for the same reason as `applyThinkingLevel`.
*/
static async applyModelSelection(mode, model, origin, persistDefault = false) {
// A selection applies to this session; only an explicit request changes the default for new sessions (senpi#2870).
const systemPromptChange = persistDefault
? await mode.session.setModel(model, origin)
: await mode.session.setSessionModel(model, origin);
mode.footer.invalidate();
// A model switch ends any external-owner delegation episode.
mode.externalOwnerCompactionNoticeShown = false;
mode.footer?.setCompactionDelegated?.(false);
mode.updateEditorBorderColor();
const systemPromptStr = systemPromptChange?.systemPromptName
? ` (optimized system prompt applied: ${systemPromptChange.systemPromptName})`
: "";
const held = mode.session.pendingModelSwitch?.model;
const isHeld = held !== undefined && held.provider === model.provider && held.id === model.id;
const tail = isHeld
? persistDefault
? " · after the next compaction, then the default model for new sessions"
: " · after the next compaction"
: persistDefault
? " · now the default model for new sessions"
: "";
mode.showStatus(`Model: ${model.id}${systemPromptStr}${tail}`);
mode.showRiskyMainModelWarning(model);
void mode.maybeWarnAboutAnthropicSubscriptionAuth(model);
mode.checkDaxnutsEasterEgg(model);
return systemPromptChange;
}
async resolveFavoriteModelsForUi(patterns, candidateModels) {
const candidateIds = new Set(candidateModels.map(getModelFullId));
const warnings = [];
const resolvedModels = await resolveModelScope(patterns, this.session.modelRuntime, {
onWarning: (message) => warnings.push(message),
});
for (const warning of warnings) {
this.showWarning(warning);
}
return resolvedModels.filter((resolved) => candidateIds.has(getModelFullId(resolved.model)));
}
async getFavoriteModelIdsForUi(candidateModels) {
const candidateIds = new Set(candidateModels.map(getModelFullId));
const sessionFavoriteIds = this.session.favoriteModels
.map((favorite) => getModelFullId(favorite.model))
.filter((id) => candidateIds.has(id));
if (sessionFavoriteIds.length > 0)
return sessionFavoriteIds;
const patterns = this.settingsManager.getFavoriteModels() ?? [];
if (patterns.length === 0)
return [];
const favoriteModels = await this.resolveFavoriteModelsForUi(patterns, candidateModels);
return favoriteModels.map((favorite) => getModelFullId(favorite.model));
}
async captureFavoritePatternSnapshot() {
const storedPatterns = this.settingsManager.getFavoriteModels() ?? [];
const { patternResolutions } = await resolveModelScopeWithDiagnostics(storedPatterns, this.session.modelRuntime);
return { storedPatterns, patternResolutions };
}
async applyFavoriteSelection(favoriteIds, candidateModels, persist, patternSnapshot) {
const { storedPatterns, patternResolutions } = patternSnapshot;
const mergedPatterns = mergeFavoritePatternsForPersist({
storedPatterns,
patternResolutions,
selectedIds: favoriteIds,
candidateIds: candidateModels.map(getModelFullId),
});
const newFavoriteModels = mergedPatterns
? await resolveModelScope(mergedPatterns, this.session.modelRuntime)
: [];
this.session.setFavoriteModels(newFavoriteModels.map((favorite) => ({
model: favorite.model,
thinkingLevel: favorite.thinkingLevel,
serviceTier: favorite.serviceTier,
})));
if (persist)
this.settingsManager.setFavoriteModels(mergedPatterns);
this.ui.requestRender();
}
/** Update the footer's available provider count from the current snapshot without refreshing catalogs. */
updateAvailableProviderCount() {
const models = this.session.scopedModels.length > 0
? this.session.scopedModels.map((scoped) => scoped.model)
: this.session.modelRuntime.getAvailableSnapshot();
const uniqueProviders = new Set(models.map((model) => model.provider));
this.footerDataProvider.setAvailableProviderCount(uniqueProviders.size);
}
async maybeWarnAboutAnthropicSubscriptionAuth(model = this.session.model) {
if (this.settingsManager.getWarnings().anthropicExtraUsage === false) {
return;
}
if (this.anthropicSubscriptionWarningShown) {
return;
}
if (model?.provider !== "anthropic") {
return;
}
try {
if ((await this.session.modelRuntime.checkAuth("anthropic"))?.type !== "oauth") {
return;
}
this.anthropicSubscriptionWarningShown = true;
this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);
}
catch {
// Ignore auth lookup failures for warning-only checks.
}
}
async maybeSaveImplicitProjectTrustAfterReload() {
const cwd = this.sessionManager.getCwd();
if (this.autoTrustOnReloadCwd !== cwd) {
return false;
}
if (!this.settingsManager.isProjectTrusted() || !hasTrustRequiringProjectResources(cwd)) {
return false;
}
const trustStore = new ProjectTrustStore(this.runtimeHost.services.agentDir);
try {
if (trustStore.get(cwd) !== null) {
this.autoTrustOnReloadCwd = undefined;
return false;
}
await trustStore.set(cwd, true);
this.autoTrustOnReloadCwd = undefined;
return true;
}
catch (error) {
this.showWarning(`Could not save project trust after reload: ${error instanceof Error ? error.message : String(error)}`);
return false;
}
}
showTrustSelector() {
const cwd = this.sessionManager.getCwd();
const trustStore = new ProjectTrustStore(this.runtimeHost.services.agentDir);
const savedDecision = trustStore.getEntry(cwd);
this.showSelector((done) => {
const selector = new TrustSelectorComponent({
cwd,
savedDecision,
projectTrusted: this.settingsManager.isProjectTrusted(),
onSelect: (selection) => {
done();
trustStore.setMany(selection.updates).then(() => this.showStatus(`Saved trust decision: ${selection.trusted ? "trusted" : "untrusted"}. Restart ${APP_NAME} for this to take effect.`), (error) => this.showWarning(`Could not save trust decision: ${error instanceof Error ? error.message : String(error)}`));
},
onCancel: () => {
done();
this.ui.requestRender();
},
});
return { component: selector, focus: selector };
});
}
showModelSelector(initialSearchInput) {
const favoritePatternSnapshot = this.captureFavoritePatternSnapshot();
this.showSelector((done) => {
const favoriteModelIds = this.session.favoriteModels.map((favorite) => getModelFullId(favorite.model));
const selector = new ModelSelectorComponent(this.ui, this.session.model, this.settingsManager, this.session.modelRuntime, this.session.scopedModels, (model, selection) => {
void this.selectModelFromUi(model, done, {
origin: { source: "picker", actor: "model-selector" },
persistDefault: selection.asDefault,
});
}, () => {
done();
this.ui.requestRender();
}, initialSearchInput, {
favoriteModelIds,
onFavoriteChange: async (favoriteIds, allModels) => {
await this.applyFavoriteSelection(favoriteIds, allModels, true, await favoritePatternSnapshot);
},
});
return {
component: selector,
focus: selector,
dispose: () => selector.dispose(),
};
});
}
async showFavoriteModelsSelector() {
const allModels = [...this.session.modelRuntime.getAvailableSnapshot()];
if (allModels.length === 0) {
this.showStatus("No models available");
return;
}
const currentFavoriteIds = await this.getFavoriteModelIdsForUi(allModels);
const favoritePatternSnapshot = await this.captureFavoritePatternSnapshot();
this.showSelector((done) => {
const selector = new FavoriteModelsSelectorComponent({
allModels,
favoriteModelIds: currentFavoriteIds,
currentModel: this.session.model,
}, {
onChange: async (favoriteIds) => {
await this.applyFavoriteSelection(favoriteIds, allModels, false, favoritePatternSnapshot);
},
onPersist: (favoriteIds) => {
void this.applyFavoriteSelection(favoriteIds, allModels, true, favoritePatternSnapshot).then(() => {
this.showStatus("Favorite models saved to settings");
});
},
onSelect: (model) => {
void this.selectModelFromUi(model, done, {
origin: { source: "picker", actor: "favorites" },
persistDefault: false,
});
},
onCancel: () => {
done();
this.ui.requestRender();
},
});
return { component: selector, focus: selector };
});
}
showScopedModelsSelector() {
let availableModels = [...this.session.modelRuntime.getAvailableSnapshot()];
let availableModelIds = new Set(availableModels.map((model) => `${model.provider}/${model.id}`));
const configuredPatterns = this.settingsManager.getEnabledModels();
const sessionScopedModels = this.session.scopedModels;
const configuredEnabledIds = (models) => {
if (!configuredPatterns?.length)
return null;
const resolved = resolveModelScopeFromModels(configuredPatterns, models);
const ids = resolved.scopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);
for (const diagnostic of resolved.diagnostics) {
if (diagnostic.code === "no-match" && !ids.includes(diagnostic.pattern))
ids.push(diagnostic.pattern);
}
return ids;
};
let currentEnabledIds = sessionScopedModels.length > 0
? sessionScopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`)
: configuredEnabledIds(availableModels);
let selectionChanged = false;
const updateSessionModels = (enabledIds) => {
currentEnabledIds = enabledIds === null ? null : [...enabledIds];
const hasEnabledAvailableModel = enabledIds?.some((id) => availableModelIds.has(id)) ?? false;
const allAvailableModelsEnabled = enabledIds !== null && [...availableModelIds].every((id) => enabledIds.includes(id));
if (enabledIds && hasEnabledAvailableModel && !allAvailableModelsEnabled) {
const newScopedModels = resolveModelScopeFromModels(enabledIds, availableModels).scopedModels;
this.session.setScopedModels(newScopedModels.map((scoped) => ({
model: scoped.model,
thinkingLevel: scoped.thinkingLevel,
})));
}
else {
this.session.setScopedModels([]);
}
this.updateAvailableProviderCount();
this.ui.requestRender();
};
this.showSelector((done) => {
let disposed = false;
let timedOut = false;
const controller = new AbortController();
const timeout = setTimeout(() => {
timedOut = true;
controller.abort();
}, 15_000);
const selector = new ScopedModelsSelectorComponent({
allModels: availableModels,
enabledModelIds: currentEnabledIds,
refreshStatus: "Refreshing model catalogs…",
}, {
onChange: (enabledIds) => {
selectionChanged = true;
updateSessionModels(enabledIds);
},
onPersist: (enabledIds) => {
const allEnabled = enabledIds !== null &&
enabledIds.length === availableModels.length &&
enabledIds.every((id) => availableModelIds.has(id));
const newPatterns = enabledIds === null || allEnabled ? undefined : enabledIds;
this.settingsManager.setEnabledModels(newPatterns ? [...newPatterns] : undefined);
this.showStatus("Model selection saved to settings");
},
onCancel: () => {
done();
this.ui.requestRender();
},
});
void refreshModelCatalogs(this.session.modelRuntime, controller.signal)
.then((result) => {
if (disposed)
return;
availableModels = [...this.session.modelRuntime.getAvailableSnapshot()];
availableModelIds = new Set(availableModels.map((model) => `${model.provider}/${model.id}`));
if (!selectionChanged && sessionScopedModels.length === 0) {
currentEnabledIds = configuredEnabledIds(availableModels);
selector.updateModels(availableModels, currentEnabledIds);
}
else {
selector.updateModels(availableModels);
}
if (currentEnabledIds !== null)
updateSessionModels(currentEnabledIds);
if (result.aborted && timedOut) {
selector.setRefreshStatus("Model refresh timed out; showing cached models.", "warning");
}
else if (result.errors.size > 0) {
selector.setRefreshStatus(`Could not refresh ${[...result.errors.keys()].join(", ")}; showing cached models.`, "warning");
}
else {
selector.setRefreshStatus("Model catalogs refreshed.", "success");
}
this.ui.requestRender();
})
.catch((error) => {
if (disposed)
return;
selector.setRefreshStatus(timedOut
? "Model refresh timed out; showing cached models."
: `Could not refresh model catalogs: ${error instanceof Error ? error.message : String(error)}`, "warning");
this.ui.requestRender();
})
.finally(() => clearTimeout(timeout));
return {
component: selector,
focus: selector,
dispose: () => {
disposed = true;
clearTimeout(timeout);
controller.abort();
},
};
});
}
async showUserMessageSelector() {
const userMessages = this.session.getUserMessagesForForking();
if (userMessages.length === 0) {
this.showStatus("No messages to fork from");
return;
}
const initialSelectedId = userMessages[userMessages.length - 1]?.entryId;
this.showSelector((done) => {
const selector = new UserMessageSelectorComponent(userMessages.map((m) => ({ id: m.entryId, text: m.text })), async (entryId) => {
done();
try {
const result = await this.runtimeHost.fork(entryId);
if (result.cancelled) {
this.ui.requestRender();
return;
}
this.editor.setText(result.selectedText ?? "");
this.showStatus("Forked to new session");
}
catch (error) {
this.showError(error instanceof Error ? error.message : String(error));
}
}, () => {
done();
this.ui.requestRender();
}, initialSelectedId);
return { component: selector, focus: selector.getMessageList() };
});
}
async handleCloneCommand() {
const leafId = this.sessionManager.getLeafId();
if (!leafId) {
this.showStatus("Nothing to clone yet");
return;
}
try {
const result = await this.runtimeHost.fork(leafId, { position: "at" });
if (result.cancelled) {
this.ui.requestRender();
return;
}
this.editor.setText("");
this.showStatus("Cloned to new session");
}
catch (error) {
this.showError(error instanceof Error ? error.message : String(error));
}
}
showTreeSelector(initialSelectedId) {
const tree = this.sessionManager.getTree();
const realLeafId = this.sessionManager.getLeafId();
const initialFilterMode = this.settingsManager.getTreeFilterMode();
if (tree.length === 0) {
this.showStatus("No entries in session");
return;
}
this.showSelector((done) => {
const selector = new TreeSelectorComponent(tree, realLeafId, this.ui.terminal.rows, async (entryId) => {
// Selecting the current leaf is a no-op (already there)
if (entryId === this.sessionManager.getLeafId()) {
done();
this.showStatus("Already at this point");
return;
}
done(); // Close selector first
await this.runTreeNavigation(entryId, {
promptForSummary: true,
navigate: (options) => this.session.navigateTree(entryId, options),
successStatus: "Navigated to selected point",
});
}, () => {
done();
this.ui.requestRender();
}, (entryId, label) => {
this.sessionManager.appendLabelChange(entryId, label);
this.ui.requestRender();
}, initialSelectedId, initialFilterMode);
selector.onCopy = async (text) => {
if (!text) {
this.showError("Selected entry has no text to copy");
return;
}
try {
await copyToClipboard(text);
this.showStatus("Copied selected message to clipboard");
}
catch (error) {
this.showError(error instanceof Error ? error.message : String(error));
}
};
selector.onEditMessage = (entryId) => {
done();
void this.editAssistantMessageFromTree(entryId);
};
return { component: selector, focus: selector };
});
}
async editAssistantMessageFromTree(entryId) {
const entry = this.sessionManager.getEntry(entryId);
if (entry?.type !== "message" || entry.message.role !== "assistant") {
this.showError("Only assistant responses can be edited here");
return;
}
const message = entry.message;
// The leaf seen when the editor opens is the token the edit is checked against.
const expectedLeafId = this.sessionManager.getLeafId() ?? undefined;
const dropsToolCalls = message.content.some((block) => block.type === "toolCall");
const title = dropsToolCalls
? "Edit assistant response (its tool calls will be dropped)"
: "Edit assistant response";
const edited = await this.showExtensionEditor(title, contentText(message.content, ""));
if (edited === undefined) {
this.showTreeSelector(entryId);
return;
}
if (!edited.trim()) {
this.showError("Assistant response cannot be empty");
this.showTreeSelector(entryId);
return;
}
if (assistantTextEquals(message, edited)) {
this.showStatus("Assistant response unchanged");
return;
}
await this.runTreeNavigation(entryId, {
promptForSummary: this.treeNavigationAbandonsConversation(entryId),
navigate: async (options) => {
try {
return await this.session.editAssistantMessage(entryId, edited, { ...options, expectedLeafId });
}
catch (error) {
if (error instanceof AssistantEditError && error.reason === "stale-leaf") {
throw new Error("The session changed while you were editing; reopen /tree and try again");
}
throw error;
}
},
successStatus: "Replaced assistant response with your edit",
});
}
/** Bookkeeping entries after the target (thinking level, labels, custom state) leave nothing to summarize. */
treeNavigationAbandonsConversation(targetId) {
const { entries } = collectEntriesForBranchSummary(this.sessionManager, this.sessionManager.getLeafId(), targetId);
return entries.some((entry) => entry.type === "message" ||
entry.type === "custom_message" ||
entry.type === "compaction" ||
entry.type === "branch_summary");
}
async promptBranchSummaryChoice() {
while (true) {
const summaryChoice = await this.showExtensionSelector("Summarize branch?", [
"No summary",
"Summarize",
"Summarize with custom prompt",
]);
if (summaryChoice === undefined) {
return undefined;
}
if (summaryChoice !== "Summarize with custom prompt") {
return { summarize: summaryChoice !== "No summary" };
}
const customInstructions = await this.showExtensionEditor("Custom summarization instructions");
if (customInstructions !== undefined) {
return { summarize: true, customInstructions };
}
}
}
async runTreeNavigation(entryId, flow) {
let wantsSummary = false;
let customInstructions;
if (flow.promptForSummary && !this.settingsManager.getBranchSummarySkipPrompt()) {
const choice = await this.promptBranchSummaryChoice();
if (choice === undefined) {
// User pressed escape - re-show tree selector with same selection
this.showTreeSelector(entryId);
return;
}
wantsSummary = choice.summarize;
customInstructions = choice.customInstructions;
}
// The user committed to navigating: stop the active response first.
if (this.session.isStreaming) {
this.restoreQueuedMessagesToEditor();
await this.session.abort();
}
// Recheck after the dialogs and streaming abort, before replacing another operation's UI.
if (this.session.isCompacting) {
this.showError("Wait for the current compaction or tree navigation to finish before navigating the session tree.");
return;
}
// Set up escape handler and status indicator if summarizing
let showingSummaryIndicator = false;
const originalOnEscape = this.defaultEditor.onEscape;
if (wantsSummary) {
this.defaultEditor.onEscape = () => {
this.session.abortBranchSummary();
};
this.chatContainer.addChild(new Spacer(1));
this.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui));
showingSummaryIndicator = true;
this.ui.requestRender();
}
try {
const result = await flow.navigate({ summarize: wantsSummary, customInstructions });
if (result.aborted) {
// Summarization aborted - re-show tree selector with same selection
this.showStatus("Branch summarization cancelled");
this.showTreeSelector(entryId);
return;
}
if (result.cancelled) {
this.showStatus("Navigation cancelled");
return;
}
// Update UI
this.chatContainer.clear();
this.renderInitialMessages();
if (result.editorText && !this.editor.getText().trim()) {
this.editor.setText(result.editorText);
}
this.showStatus(flow.successStatus);
void this.flushCompactionQueue({ willRetry: false });
}
catch (error) {
this.showError(error instanceof Error ? error.message : String(error));
}
finally {
if (showingSummaryIndicator) {
this.clearStatusIndicator("branchSummary");
}
this.defaultEditor.onEscape = originalOnEscape;
}
}
showSessionSelector() {
this.showSelector((done) => {
const selector = new SessionSelectorComponent((onProgress, signal) => currentScopeSessions(this.sessionManager, onProgress, signal), (onProgress, signal) => allScopeSessions(this.sessionManager, onProgress, signal), async (sessionPath) => {
done();
const target = await chooseResumePath(sessionPath, this.sessionManager, {
confirm: (title, message) => this.showExtensionConfirm(title, message),
showError: (message) => this.showError(message),
});
if (target !== undefined)
await this.handleResumeSession(target);
}, () => {
done();
this.ui.requestRender();
}, () => {
void this.shutdown();
}, () => this.ui.requestRender(), {
renameSession: async (sessionFilePath, nextName) => {
const next = (nextName ?? "").trim();
if (!next)
return;
const mgr = SessionManager.open(sessionFilePath);
mgr.appendSessionInfo(next);
},
showRenameHint: true,
keybindings: this.keybindings,
}, this.sessionManager.getSessionFile());
return { component: selector, focus: selector };
});
}
async handleResumeSession(sessionPath, options) {
this.clearStatusIndicator();
// A session another live process holds must not get a second writer here (senpi#5744): the restored
// lifecycle would read that process's live run as interrupted and the next input would run it again.
const holderCheck = await checkSessionHolders(sessionPath);
if ("holders" in holderCheck && holderCheck.holders.length > 0) {
const takeOver = "Take over (stop it there)";
const refusal = takeOverRefusal(holderCheck.holders);
const choice = await this.showExtensionSelector(`This session is open in another process (${describeSessionHolders(holderCheck.holders)}).\nResuming it here while it runs would start a second run of the same session.${refusal === undefined ? "" : `\n${refusal}`}`, refusal === undefined ? ["Cancel", takeOver] : ["Cancel"]);
if (choice !== takeOver) {
this.showStatus("Not resumed: the session is open in another process");
return { cancelled: true };
}
let stopped;
try {
stopped = await stopSessionHolders(sessionPath, holderCheck.holders);
}
catch (error) {
this.showWarning(`Not resumed: could not stop the other process (${error instanceof Error ? error.message : String(error)}).`);
return { cancelled: true };
}
if (!stopped) {
this.showWarning("Not resumed: the session is still open in another process; quit it there, then /resume again.");
return { cancelled: true };
}
}
try {
const result = await this.runtimeHost.switchSession(sessionPath, {
withSession: options?.withSession,
projectTrustContextFactory: (cwd) => this.createProjectTrustContext(cwd),
});
if (result.cancelled) {
return result;
}
const warning = "lookupFailed" in holderCheck
? SESSION_HOLDER_LOOKUP_FAILED
: await sessionHolderWarning(this.sessionManager.getSessionFile(), this.sessionManager.getSessionId());
if (warning !== undefined)
this.showWarning(warning);
const switchTimings = formatTimings("switch");
this.showStatus(switchTimings === undefined ? "Resumed session" : `Resumed session | switch timings: ${switchTimings}`);
return result;
}
catch (error) {
if (error instanceof MissingSessionCwdError) {
const selectedCwd = await this.promptForMissingSessionCwd(error);
if (!selectedCwd) {
this.showStatus("Resume cancelled");
return { cancelled: true };
}
const result = await this.runtimeHost.switchSession(sessionPath, {
cwdOverride: selectedCwd,
withSession: options?.withSession,
projectTrustContextFactory: (cwd) => this.createProjectTrustContext(cwd),
});
if (result.cancelled) {
return result;
}
const warning = "lookupFailed" in holderCheck
? SESSION_HOLDER_LOOKUP_FAILED
: await sessionHolderWarning(this.sessionManager.getSessionFile(), this.sessionManager.getSessionId());
if (warning !== undefined)
this.showWarning(warning);
this.showStatus("Resumed session in current cwd");
return result;
}
return this.handleFatalRuntimeError("Failed to resume session", error);
}
}
getLoginProviderOptions(authType) {
const options = [];
for (const provider of this.session.modelRuntime.getProviders()) {
if ((!authType || authType === "oauth") && provider.auth.oauth) {
options.push({
id: provider.id,
name: provider.name,
authType: "oauth",
method: provider.auth.oauth,
status: loginRowStatus(this.session.modelRegistry, provider, "oauth"),
});
}
if ((!authType || authType === "api_key") && provider.auth.apiKey) {
options.push({
id: provider.id,
name: provider.name,
authType: "api_key",
method: provider.auth.apiKey,
status: loginRowStatus(this.session.modelRegistry, provider, "api_key"),
});
}
}
return options.sort((a, b) => a.name.localeCompare(b.name));
}
async getLogoutProviderOptions() {
return (await this.session.modelRuntime.listCredentials({
signal: AbortSignal.timeout(15_000),
}))
.map(({ providerId, type }) => ({
id: providerId,
name: this.session.modelRuntime.getProvider(providerId)?.name ?? providerId,
authType: type,
status: { type, source: "stored credential" },
}))
.sort((a, b) => a.name.localeCompare(b.name));
}
findLoginProviderOptions(providerRef) {
const normalizedProviderRef = providerRef.trim().toLowerCase();
if (!normalizedProviderRef) {
return [];
}
return this.getLoginProviderOptions().filter((provider) => provider.id.toLowerCase() === normalizedProviderRef ||
provider.name.toLowerCase() === normalizedProviderRef);
}
async handleLoginCommand(providerRef) {
if (!providerRef) {
this.showLoginAuthTypeSelector();
return;
}
// A TYPED legacy provider id (or its old display name) is rejected by name
// so the user learns the new id (senpi#1989). Without this it falls through
// to a filtered selector that matches nothing, which reads as "this provider
// vanished" rather than "it was renamed". Ids read from disk are normalized
// instead and never reach here.
const rejection = legacyProviderIdRejection(providerRef);
if (rejection) {
this.showError(rejection);
return;
}
const providerOptions = this.findLoginProviderOptions(providerRef);
if (providerOptions.length === 1) {
await this.startProviderLogin(providerOptions[0]);
return;
}
if (providerOptions.length > 1) {
const providerIds = new Set(providerOptions.map((provider) => provider.id));
if (providerIds.size === 1) {
this.showLoginAuthTypeSelector(providerOptions);
return;
}
}
this.showLoginProviderSelector(undefined, providerRef);
}
async startProviderLogin(providerOption) {
if (providerOption.authType === "oauth") {
await this.showLoginDialog(providerOption.id, providerOption.name);
}
else if (providerOption.method?.login) {
await this.showApiKeyLoginDialog(providerOption.id, providerOption.name);
}
else {
this.showAmbientAuthDialog(providerOption);
}
}
showLoginAuthTypeSelector(providerOptions) {
const oauthProvider = providerOptions?.find((provider) => provider.authType === "oauth");
const oauthLoginLabel = oauthProvider?.method && "loginLabel" in oauthProvider.method ? oauthProvider.method.loginLabel : undefined;
const subscriptionLabel = oauthLoginLabel ?? "Sign in with an account";
const apiKeyLabel = "Sign in with an API key";
const availableAuthTypes = providerOptions
? new Set(providerOptions.map((provider) => provider.authType))
: new Set(["oauth", "api_key"]);
const options = [];
if (availableAuthTypes.has("oauth")) {
options.push(subscriptionLabel);
}
if (availableAuthTypes.has("api_key")) {
options.push(apiKeyLabel);
}
if (options.length === 0) {
this.showStatus("No login methods available.");
return;
}
if (providerOptions && options.length === 1) {
const providerOption = providerOptions[0];
if (providerOption) {
void this.startProviderLogin(providerOption);
}
return;
}
const title = providerOptions?.[0]
? `Select authentication method for ${providerOptions[0].name}:`
: "Select authentication method:";
this.showSelector((done) => {
const selector = new ExtensionSelectorComponent(title, options, (option) => {
done();
const authType = option === subscriptionLabel ? "oauth" : "api_key";
if (providerOptions) {
const providerOption = providerOptions.find((provider) => provider.authType === authType);
if (providerOption) {
void this.startProviderLogin(providerOption);
}
return;
}
this.showLoginProviderSelector(authType);
}, () => {
done();
this.ui.requestRender();
});
return { component: selector, focus: selector };
});
}
showLoginProviderSelector(authType, initialSearchInput) {
const providerOptions = this.getLoginProviderOptions(authType);
if (providerOptions.length === 0) {
const message = authType === "oauth"
? "No subscription providers available."
: authType === "api_key"
? "No API key providers available."
: "No login providers available.";
this.showStatus(message);
return;
}
this.showSelector((done) => {
const selector = new OAuthSelectorComponent("login", providerOptions, async (providerId, selectedAuthType) => {
done();
const providerOption = providerOptions.find((provider) => provider.id === providerId && provider.authType === selectedAuthType);
if (!providerOption) {
return;
}
await this.startProviderLogin(providerOption);
}, () => {
done();
if (authType) {
this.showLoginAuthTypeSelector();
}
else {
this.ui.requestRender();
}
}, initialSearchInput);
return { component: selector, focus: selector };
});
}
async showOAuthSelector(mode) {
if (mode === "login") {
this.showLoginAuthTypeSelector();
return;
}
let providerOptions;
try {
providerOptions = await this.getLogoutProviderOptions();
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.showError(`Could not read your saved sign-ins: ${message}${/[.!?]$/.test(message) ? "" : "."} Restart senpi; if it happens again, run /login to sign in again.`);
return;
}
if (providerOptions.length === 0) {
this.showStatus("No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.");
return;
}
this.showSelector((done) => {
const selector = new OAuthSelectorComponent(mode, providerOptions, async (providerId) => {
done();
const providerOption = providerOptions.find((provider) => provider.id === providerId);
if (!providerOption) {
return;
}
try {
const { notices, revocation } = await this.session.modelRuntime.logoutProvider(providerOption.id, {
signal: AbortSignal.timeout(15_000),
});
this.updateAvailableProviderCount();
const message = providerOption.authType === "oauth"
? `Logged out of ${providerOption.name}`
: `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;
const revocationNotice = revocation?.status === "remote_revocation_unconfirmed"
? ["Remote revocation was not confirmed; disconnect the app in ChatGPT Settings."]
: [];
this.showStatus([message, ...notices, ...revocationNotice].join(" "));
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.showError(error instanceof CredentialSynchronizationError
? `Credentials removed for ${providerOption.name}, but local model state could not be synchronized: ${message}`
: `Logout failed: ${message}`);
}
}, () => {
done();
this.ui.requestRender();
});
return { component: selector, focus: selector };
});
}
async completeProviderAuthentication(providerId, providerName, authType, previousModel) {
const actionLabel = authType === "oauth" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;
const session = this.session;
// Dynamic catalogs may be empty until the first authenticated network refresh.
const deferSelection = isUnknownModel(previousModel) &&
hasDefaultModelProvider(providerId) &&
!session.modelRuntime
.getAvailableSnapshot()
.some((model) => model.provider === providerId && model.id === defaultModelPerProvider[providerId]);
const finishAuthentication = async () => {
let selectedModel;
let systemPromptName;
let selectionError;
if (isUnknownModel(previousModel)) {
const availableModels = this.session.modelRuntime.getAvailableSnapshot();
const providerModels = availableModels.filter((model) => model.provider === providerId);
if (!hasDefaultModelProvider(providerId)) {
selectionError = `${actionLabel}, but no default model is configured for provider "${providerId}". Use /model to select a model.`;
}
else if (providerModels.length === 0) {
selectionError = `${actionLabel}, but no models are available for that provider. Use /model to select a model.`;
}
else {
const defaultModelId = defaultModelPerProvider[providerId];
// Radius catalogs vary by account; prefer balanced, then use catalog order.
selectedModel =
providerModels.find((model) => model.id === defaultModelId) ??
(providerId === "radius" ? providerModels[0] : undefined);
if (!selectedModel) {
selectionError = `${actionLabel}, but its default model "${defaultModelId}" is not available. Use /model to select a model.`;
}
else {
try {
systemPromptName = (await this.session.setModel(selectedModel, { source: "provider-login" }))
?.systemPromptName;
}
catch (error) {
selectedModel = undefined;
const errorMessage = error instanceof Error ? error.message : String(error);
selectionError = `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`;
}
}
}
}
this.updateAvailableProviderCount();
this.footer.invalidate();
this.updateEditorBorderColor();
if (selectedModel) {
const systemPromptStr = systemPromptName ? ` System prompt: ${systemPromptName}.` : "";
this.showStatus(`${actionLabel}. Selected ${selectedModel.id}.${systemPromptStr} Credentials saved to ${getAuthPath()}`);
this.showRiskyMainModelWarning(selectedModel);
void this.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel);
this.checkDaxnutsEasterEgg(selectedModel);
}
else {
this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`);
if (selectionError) {
this.showError(selectionError);
}
else {
void this.maybeWarnAboutAnthropicSubscriptionAuth();
}
}
};
if (deferSelection) {
this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}. Refreshing model catalog…`);
}
else {
await finishAuthentication();
}
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 15_000);
const refreshProviders = providerId === "cursor" ? [providerId, "cursor-cli-oauth"] : [providerId];
void session.modelRuntime
.refresh({
allowNetwork: true,
providers: refreshProviders,
signal: controller.signal,
})
.then(async (result) => {
if (result.aborted) {
this.showWarning(`${actionLabel}, but its model catalog refresh timed out; using cached models.`);
}
else if (result.errors.size > 0) {
this.showWarning(`${actionLabel}, but its model catalog could not be refreshed; using cached models.`);
}
// Do not replace a model or session selected while the refresh was running.
if (deferSelection && this.session === session && session.model === previousModel) {
await finishAuthentication();
}
this.updateAvailableProviderCount();
this.footer.invalidate();
this.ui.requestRender();
})
.catch((error) => {
this.showWarning(`${actionLabel}, but its model catalog could not be refreshed: ${error instanceof Error ? error.message : String(error)}`);
})
.finally(() => clearTimeout(timeout));
}
showAmbientAuthDialog(providerOption) {
const restoreEditor = () => {
this.editorContainer.clear();
this.editorContainer.addChild(this.editor);
this.ui.setFocus(this.editor);
this.ui.requestRender();
};
const dialog = new LoginDialogComponent(this.ui, providerOption.id, () => restoreEditor(), providerOption.name, `${providerOption.name} setup`);
dialog.showInfo(`${providerOption.method?.name ?? "Authentication"} is configured outside ${APP_NAME}.`, [], true);
this.editorContainer.clear();
this.editorContainer.addChild(dialog);
this.ui.setFocus(dialog);
this.ui.requestRender();
}
async showApiKeyLoginDialog(providerId, providerName) {
const previousModel = this.session.model;
const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => {
// Completion handled below
}, providerName);
if (providerId === "amazon-bedrock") {
dialog.showDetails([
theme.fg("text", "You can also use an AWS profile, IAM keys, or role-based credentials."),
theme.fg("muted", "See:"),
theme.fg("accent", ` ${path.join(getDocsPath(), "providers.md")}`),
]);
}
this.editorContainer.clear();
this.editorContainer.addChild(dialog);
this.ui.setFocus(dialog);
this.ui.requestRender();
const restoreEditor = () => {
this.editorContainer.clear();
this.editorContainer.addChild(this.editor);
this.ui.setFocus(this.editor);
this.ui.requestRender();
};
try {
await this.loginProvider(dialog, providerId, "api_key");
restoreEditor();
await this.completeProviderAuthentication(providerId, providerName, "api_key", previousModel);
}
catch (error) {
restoreEditor();
this.showLoginFailure(describeLoginFailure(error, providerName, "api_key"));
}
}
showAuthSelect(dialog, prompt) {
return new Promise((resolve, reject) => {
const restoreDialog = () => {
this.editorContainer.clear();
this.editorContainer.addChild(dialog);
this.ui.setFocus(dialog);
this.ui.requestRender();
};
const labels = prompt.options.map((option) => option.label);
const selector = new ExtensionSelectorComponent(prompt.message, labels, (optionLabel) => {
restoreDialog();
const id = prompt.options.find((option) => option.label === optionLabel)?.id;
if (id)
resolve(id);
else
reject(new Error("Login cancelled"));
}, () => {
restoreDialog();
reject(new Error("Login cancelled"));
});
this.editorContainer.clear();
this.editorContainer.addChild(selector);
this.ui.setFocus(selector);
this.ui.requestRender();
});
}
async showAuthPrompt(dialog, prompt) {
if (prompt.type === "secret") {
try {
const value = await this.showExtensionInput(prompt.message, prompt.placeholder, {
secret: true,
signal: prompt.signal,
});
if (value === undefined)
throw new Error("Login cancelled");
return value;
}
finally {
this.editorContainer.clear();
this.editorContainer.addChild(dialog);
this.ui.setFocus(dialog);
this.ui.requestRender();
}
}
let response;
if (prompt.type === "select") {
response = this.showAuthSelect(dialog, prompt);
}
else if (prompt.type === "manual_code") {
response = dialog.showManualInput(prompt.message);
}
else {
response = dialog.showPrompt(prompt.message, prompt.placeholder);
}
if (!prompt.signal)
return response;
if (prompt.signal.aborted)
throw new Error("Login cancelled");
const signal = prompt.signal;
let onAbort;
const aborted = new Promise((_resolve, reject) => {
onAbort = () => reject(new Error("Login cancelled"));
signal.addEventListener("abort", onAbort, { once: true });
});
try {
return await Promise.race([response, aborted]);
}
finally {
if (onAbort)
signal.removeEventListener("abort", onAbort);
}
}
notifyAuthDialog(dialog, event) {
if (event.type === "auth_url") {
dialog.showAuth(event.url, event.instructions);
}
else if (event.type === "device_code") {
dialog.showDeviceCode(event);
dialog.showWaiting("Waiting for authentication...");
}
else if (event.type === "info") {
dialog.showInfo(event.message, event.links);
}
else {
dialog.showProgress(event.message);
}
}
async loginProvider(dialog, providerId, method) {
// A replacement recorded by another login path must not be reported as this one's.
this.session.modelRegistry.authStorage.takeReplacement(providerId);
await this.session.modelRuntime.login(providerId, method, {
signal: dialog.signal,
prompt: (prompt) => this.showAuthPrompt(dialog, prompt),
notify: (event) => this.notifyAuthDialog(dialog, event),
}, { getDeviceId: () => this.settingsManager.getOrCreateDeviceId() });
// A login of the other kind replaced the stored one: say where it went (senpi#3448).
const replacement = this.session.modelRegistry.authStorage.takeReplacement(providerId);
if (replacement)
this.showWarning(describeCredentialReplacement(providerId, replacement));
}
async showLoginDialog(providerId, providerName) {
const previousModel = this.session.model;
const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => { }, providerName);
this.editorContainer.clear();
this.editorContainer.addChild(dialog);
this.ui.setFocus(dialog);
this.ui.requestRender();
const restoreEditor = () => {
this.editorContainer.clear();
this.editorContainer.addChild(this.editor);
this.ui.setFocus(this.editor);
this.ui.requestRender();
};
try {
await this.loginProvider(dialog, providerId, "oauth");
restoreEditor();
await this.completeProviderAuthentication(providerId, providerName, "oauth", previousModel);
}
catch (error) {
restoreEditor();
this.showLoginFailure(describeLoginFailure(error, providerName, "oauth"));
}
}
/** #1542: a cancelled login is a neutral status line; only a genuine failure is an error. */
showLoginFailure(notice) {
if (notice.level === "status")
this.showStatus(notice.message);
else
this.showError(notice.message);
}
// =========================================================================
// Command handlers
// =========================================================================
async handleReloadCommand() {
if (this.session.isStreaming) {
this.showWarning("Wait for the current response to finish before reloading.");
return;
}
if (this.session.isCompacting) {
this.showWarning("Wait for compaction to finish before reloading.");
return;
}
// Pre-check the extension veto (session_before_reload) so a blocked reload
// warns without flashing the reload box or stealing editor focus. reload()
// re-checks internally, so the race window below is still covered.
const veto = await this.session.checkReloadVeto();
if (veto.cancelled) {
this.showWarning(veto.reason ?? "Reload blocked by an extension.");
return;
}
const reloadBox = new Container();
const borderColor = (s) => theme.fg("border", s);
reloadBox.addChild(new DynamicBorder(borderColor));
reloadBox.addChild(new Spacer(1));
reloadBox.addChild(new ThemedText(() => theme.fg("muted", "Reloading keybindings, extensions, skills, prompts, themes, and context files..."), 1, 0));
reloadBox.addChild(new Spacer(1));
reloadBox.addChild(new DynamicBorder(borderColor));
const previousEditor = this.editor;
this.editorContainer.clear();
this.editorContainer.addChild(reloadBox);
this.ui.setFocus(reloadBox);
this.ui.requestRender(true);
await new Promise((resolve) => process.nextTick(resolve));
const dismissReloadBox = (editor) => {
this.editorContainer.clear();
this.editorContainer.addChild(editor);
this.ui.setFocus(editor);
this.ui.requestRender();
};
let chatRestoredBeforeSessionStart = false;
let reloadBoxDismissed = false;
const restoreChatBeforeSessionStart = () => {
if (chatRestoredBeforeSessionStart) {
return;
}
// Reset extension UI only once the reload is actually proceeding (this
// callback runs after reload()'s internal veto re-check, right before the
// new runner's session_start re-registers extension UI). Resetting before
// reload() destroyed live extension footers/widgets/tickers on a vetoed
// or failed reload with nothing left to restore them, so the TUI stopped
// self-repainting until an input event forced a frame.
this.resetExtensionUI();
this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
this.outputPad = this.settingsManager.getOutputPad();
// Reload replaces the session runner: a genuine ownership boundary, so the
// external-owner delegation episode ends here (settings-only rebuilds below
// go through rebuildChatFromMessages and must NOT reset it — post-#1188 core
// emits no repeat rejection event to restore cleared state).
this.externalOwnerCompactionNoticeShown = false;
this.footer?.setCompactionDelegated?.(false);
this.rebuildChatFromMessages();
time("chatRebuild", "reload");
chatRestoredBeforeSessionStart = true;
};
try {
const reloadResult = await this.session.reload({
beforeSessionStart: restoreChatBeforeSessionStart,
});
if (reloadResult.cancelled) {
dismissReloadBox(previousEditor);
reloadBoxDismissed = true;
this.showWarning(reloadResult.reason ?? "Reload blocked by an extension.");
return;
}
restoreChatBeforeSessionStart();
this.keybindings.reload();
const activeHeader = this.customHeader ?? this.builtInHeader;
if (isExpandable(activeHeader)) {
activeHeader.setExpanded(this.toolOutputExpanded);
}
setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
this.applyRuntimeSettings();
this.themeController.applyFromSettings();
this.setupAutocompleteProvider();
const runner = this.session.extensionRunner;
this.setupExtensionShortcuts(runner);
this.showLoadedResources({
force: false,
showDiagnosticsWhenQuiet: true,
});
const savedImplicitProjectTrust = await this.maybeSaveImplicitProjectTrustAfterReload();
const modelsJsonError = this.session.modelRuntime.getError();
if (modelsJsonError) {
this.showError(`models.json error: ${modelsJsonError}`);
}
const reloadedMessage = savedImplicitProjectTrust
? "Reloaded keybindings, extensions, skills, prompts, themes, and context files; saved project trust"
: "Reloaded keybindings, extensions, skills, prompts, themes, and context files";
const reloadTimings = formatTimings("reload");
this.showStatus(reloadTimings === undefined ? reloadedMessage : `${reloadedMessage} | reload timings: ${reloadTimings}`);
dismissReloadBox(this.editor);
reloadBoxDismissed = true;
}
catch (error) {
if (!reloadBoxDismissed) {
dismissReloadBox(previousEditor);
}
this.showError(`Reload failed: ${error instanceof Error ? error.message : String(error)}`);
}
}
async handleExportCommand(text) {
const outputPath = this.getPathCommandArgument(text, "/export");
try {
if (outputPath?.endsWith(".jsonl")) {
const filePath = await this.session.exportToJsonl(outputPath);
this.showStatus(`Session exported to: ${filePath}`);
}
else {
const filePath = await this.session.exportToHtml(outputPath, {
themeName: theme.name,
});
this.showStatus(`Session exported to: ${filePath}`);
}
}
catch (error) {
this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);
}
}
getPathCommandArgument(text, command) {
if (text === command) {
return undefined;
}
if (!text.startsWith(`${command} `)) {
return undefined;
}
const argsString = text.slice(command.length + 1).trimStart();
if (!argsString) {
return undefined;
}
const firstChar = argsString[0];
if (firstChar === '"' || firstChar === "'") {
const closingQuoteIndex = argsString.indexOf(firstChar, 1);
if (closingQuoteIndex < 0) {
return undefined;
}
return expandTildePath(argsString.slice(1, closingQuoteIndex));
}
const firstWhitespaceIndex = argsString.search(/\s/);
if (firstWhitespaceIndex < 0) {
return expandTildePath(argsString);
}
return expandTildePath(argsString.slice(0, firstWhitespaceIndex));
}
async handleImportCommand(text) {
const inputPath = this.getPathCommandArgument(text, "/import");
if (!inputPath) {
this.showError("Usage: /import <path.jsonl>");
return;
}
const confirmed = await this.showExtensionConfirm("Import session", `Replace current session with ${inputPath}?`);
if (!confirmed) {
this.showStatus("Import cancelled");
return;
}
try {
this.clearStatusIndicator();
const result = await this.runtimeHost.importFromJsonl(inputPath);
if (result.cancelled) {
this.showStatus("Import cancelled");
return;
}
this.showStatus(`Session imported from: ${inputPath}`);
}
catch (error) {
if (error instanceof MissingSessionCwdError) {
const selectedCwd = await this.promptForMissingSessionCwd(error);
if (!selectedCwd) {
this.showStatus("Import cancelled");
return;
}
const result = await this.runtimeHost.importFromJsonl(inputPath, selectedCwd);
if (result.cancelled) {
this.showStatus("Import cancelled");
return;
}
this.showStatus(`Session imported from: ${inputPath}`);
return;
}
if (error instanceof SessionImportFileNotFoundError) {
this.showError(`Failed to import session: ${error.message}`);
return;
}
await this.handleFatalRuntimeError("Failed to import session", error);
}
}
async handleShareCommand() {
const outcome = await runShare({
disabledReason: () => isShareDisabledByEnvironment()
? "Sharing is turned off on this machine (DISABLE_SHARE)."
: this.settingsManager.getEnableSessionShare()
? undefined
: "Sharing is turned off in settings (enableSessionShare: false).",
checkGh: checkGhAuth,
render: (sanitize) => this.session.renderToHtml({ themeName: theme.name, sanitize }),
context: currentShareRedactionContext(),
ask: async (preview, { omittedOutputs, includesOutputs }) => {
const include = `Include tool outputs (${omittedOutputs})`;
const toggle = includesOutputs ? [SHARE_EXCLUDE] : omittedOutputs > 0 ? [include] : [];
const options = [SHARE_UPLOAD, ...toggle, SHARE_REVIEW, SHARE_CANCEL];
const choice = await this.showExtensionSelector(preview, options);
if (choice === SHARE_UPLOAD)
return "upload";
if (choice === include)
return "include-outputs";
if (choice === SHARE_EXCLUDE)
return "exclude-outputs";
return choice === SHARE_REVIEW ? "review" : "cancel";
},
showReviewCopy: (reviewPath) => this.showStatus(`Exact file to be uploaded: ${reviewPath}\nIt is deleted when this share finishes.`),
upload: (html) => this.uploadShareWithLoader(html),
viewerBase: getShareViewerBase(),
});
switch (outcome.kind) {
case "disabled":
this.showError(outcome.reason);
return;
case "gh-missing":
this.showError("GitHub CLI (gh) is not installed. Install it from https://cli.github.com/");
return;
case "gh-logged-out":
this.showError("GitHub CLI is not logged in. Run 'gh auth login' first.");
return;
case "export-failed":
this.showError(`Failed to export session: ${outcome.message}`);
return;
case "cancelled":
this.showStatus("Share cancelled; nothing was uploaded");
return;
case "upload-failed":
this.showError(`Failed to create gist: ${outcome.message}`);
return;
case "shared":
this.showStatus(outcome.viewerUrl === undefined
? `Gist: ${outcome.gistUrl}`
: `Share URL: ${outcome.viewerUrl}\nGist: ${outcome.gistUrl}`);
return;
}
}
async uploadShareWithLoader(html) {
const loader = new BorderedLoader(this.ui, theme, "Creating gist...");
this.editorContainer.clear();
this.editorContainer.addChild(loader);
this.ui.setFocus(loader);
this.ui.requestRender();
try {
return await uploadSecretGist(html, `${APP_NAME}-session.html`, loader.signal);
}
finally {
loader.dispose();
this.editorContainer.clear();
this.editorContainer.addChild(this.editor);
this.ui.setFocus(this.editor);
this.ui.requestRender();
}
}
async handleCopyCommand(options = {}) {
if (options.preferSelection &&
this.ui instanceof TuiAltScreen &&
!this.ui.getCopyOnSelect() &&
this.ui.hasActiveSelection()) {
await this.ui.copyActiveSelectionToClipboard();
return;
}
const text = this.session.getLastAssistantText();
if (!text) {
this.showError("No agent messages to copy yet.");
return;
}
try {
await copyToClipboard(text);
if (options.flashConfirmation && this.ui instanceof TuiAltScreen) {
this.ui.flash("Copied!");
}
else {
this.showStatus("Copied last agent message to clipboard");
}
}
catch (error) {
this.showError(error instanceof Error ? error.message : String(error));
}
}
/** `/rename [name]` and its `/name` alias: a bare command opens the inline editor. */
async handleRenameCommand(text) {
const name = text.replace(/^\/(?:rename|name)\s*/, "").trim();
if (!name) {
this.showSessionRenameInput();
return;
}
await this.applySessionName(name);
}
/** Store the display name and report the value the session kept. */
async applySessionName(name) {
await this.session.setSessionName(name);
const sessionName = this.session.sessionName;
if (sessionName !== name) {
this.showWarning(`Session name was normalized from ${JSON.stringify(name)} to ${JSON.stringify(sessionName)}`);
}
this.chatContainer.addChild(new Spacer(1));
const displayName = sessionName ?? name;
this.chatContainer.addChild(new ThemedText(() => theme.fg("dim", `Session name set: ${displayName}`), 1, 0));
this.ui.requestRender();
}
/** Swap the composer for a single-line input prefilled with the current name. */
showSessionRenameInput() {
this.extensionInput = new ExtensionInputComponent("Rename session", undefined, (value) => {
this.hideExtensionInput();
void this.commitSessionRename(value);
}, () => this.hideExtensionInput(), { tui: this.ui, initialValue: this.sessionManager.getSessionName() ?? "" });
this.editorContainer.clear();
this.editorContainer.addChild(this.extensionInput);
this.ui.setFocus(this.extensionInput);
this.ui.requestRender();
}
async commitSessionRename(value) {
const name = value.trim();
if (!name) {
this.showWarning("Session name cannot be empty");
return;
}
if (name === this.sessionManager.getSessionName())
return;
await this.applySessionName(name);
}
async handleSessionCommand() {
const stats = this.session.getSessionStats();
const sessionName = this.session.sessionName;
const entries = this.sessionManager.getEntries();
const cacheWaste = computeCacheWaste(entries, this.session.modelRuntime);
// Cost/token totals per provider/model actually used (e.g. OpenRouter `auto`
// resolves to a concrete responseModel). Usage without model attribution is
// grouped separately so the breakdown reconciles with the session total.
const usageBreakdown = getUsageCostBreakdown(entries);
// Snapshot the stats; the text is built on demand so it follows theme changes.
const model = this.session.model;
const selectedModelKey = `${model?.provider}/${model?.id}`;
const renderInfo = () => {
let info = `${theme.bold("Session Info")}\n\n`;
if (sessionName) {
info += `${theme.fg("dim", "Name:")} ${sessionName}\n`;
}
info += `${theme.fg("dim", "File:")} ${stats.sessionFile ?? "In-memory"}\n`;
info += `${theme.fg("dim", "ID:")} ${stats.sessionId}\n\n`;
info += `${theme.bold("Messages")}\n`;
info += `${theme.fg("dim", "Total:")} ${stats.totalMessages}\n`;
info += `${theme.fg("dim", "User:")} ${stats.userMessages}\n`;
info += `${theme.fg("dim", "Assistant:")} ${stats.assistantMessages}\n`;
info += `${theme.fg("dim", "Tools:")} ${stats.toolCalls} calls, ${stats.toolResults} results\n\n`;
info += `${theme.bold("Tokens")}\n`;
// "Input" is the full prompt volume. With cache activity, split it into
// cached (served from cache) vs uncached (everything else) - the only
// provider-independent split. Cache writes, where reported, are a detail
// of the uncached portion.
const { input, cacheRead, cacheWrite } = stats.tokens;
const promptTokens = input + cacheRead + cacheWrite;
info += `${theme.fg("dim", "Input:")} ${promptTokens.toLocaleString()}\n`;
if (promptTokens > 0 && (cacheRead > 0 || cacheWrite > 0)) {
const hitRate = theme.fg("dim", `(${((cacheRead / promptTokens) * 100).toFixed(1)}%)`);
info += ` ${theme.fg("dim", "Cached:")} ${cacheRead.toLocaleString()} ${hitRate}\n`;
const written = cacheWrite > 0 ? ` ${theme.fg("dim", `(${cacheWrite.toLocaleString()} written to cache)`)}` : "";
info += ` ${theme.fg("dim", "Uncached:")} ${(input + cacheWrite).toLocaleString()}${written}\n`;
}
info += `${theme.fg("dim", "Output:")} ${stats.tokens.output.toLocaleString()}\n`;
info += `${theme.fg("dim", "Total:")} ${stats.tokens.total.toLocaleString()}\n`;
if (stats.cost > 0 || cacheWaste.missedTokens > 0) {
info += `\n${theme.bold("Cost")}\n`;
info += `${theme.fg("dim", "Total:")} $${stats.cost.toFixed(3)}${stats.costUnknown ? theme.fg("dim", " + unpriced turns") : ""}`;
// A single entry repeats the total, unless it names a model other than the selected one.
if (usageBreakdown.length > 1 || usageBreakdown[0]?.key !== selectedModelKey) {
for (const entry of usageBreakdown) {
info += `\n ${theme.fg("dim", `${entry.key}:`)} $${entry.cost.toFixed(3)}${entry.costUnknown ? theme.fg("dim", " + unpriced turns") : ""} ${theme.fg("dim", `(${formatTokens(entry.tokens)} tokens)`)}`;
}
}
if (cacheWaste.missedTokens > 0) {
const missLabel = cacheWaste.missCount === 1 ? "1 miss" : `${cacheWaste.missCount} misses`;
const detail = `${cacheWaste.missedTokens.toLocaleString()} tokens, ${missLabel}`;
info +=
cacheWaste.missedCost >= 0.0001
? `\n${theme.fg("dim", "Cache Re-billed:")} $${cacheWaste.missedCost.toFixed(3)} ${theme.fg("dim", `(${detail})`)}`
: `\n${theme.fg("dim", "Cache Re-billed:")} ${detail}`;
}
}
info += formatSessionFailureInfo(stats.failures);
return info;
};
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new ThemedText(renderInfo, 1, 0));
this.ui.requestRender();
}
handleChangelogCommand() {
const source = resolveChangelogSource();
const changelogPath = source.path;
const allEntries = parseChangelog(changelogPath);
const changelogMarkdown = allEntries.length > 0
? allEntries
.reverse()
.map((e) => (source.rewriteLinks ? normalizeChangelogLinks(e.content, e) : e.content))
.join("\n\n")
: "No changelog entries found.";
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new DynamicBorder());
this.chatContainer.addChild(new ThemedText(() => theme.bold(theme.fg("accent", "What's New")), 1, 0));
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, this.getMarkdownThemeWithSettings()));
this.chatContainer.addChild(new DynamicBorder());
this.ui.requestRender();
}
/**
* Get capitalized display string for an app keybinding action.
*/
getAppKeyDisplay(action) {
return keyDisplayText(action);
}
/**
* Get capitalized display string for an editor keybinding action.
*/
getEditorKeyDisplay(action) {
return keyDisplayText(action);
}
handleHotkeysCommand() {
// Navigation keybindings
const cursorUp = this.getEditorKeyDisplay("tui.editor.cursorUp");
const cursorDown = this.getEditorKeyDisplay("tui.editor.cursorDown");
const cursorLeft = this.getEditorKeyDisplay("tui.editor.cursorLeft");
const cursorRight = this.getEditorKeyDisplay("tui.editor.cursorRight");
const cursorWordLeft = this.getEditorKeyDisplay("tui.editor.cursorWordLeft");
const cursorWordRight = this.getEditorKeyDisplay("tui.editor.cursorWordRight");
const cursorLineStart = this.getEditorKeyDisplay("tui.editor.cursorLineStart");
const cursorLineEnd = this.getEditorKeyDisplay("tui.editor.cursorLineEnd");
const jumpForward = this.getEditorKeyDisplay("tui.editor.jumpForward");
const jumpBackward = this.getEditorKeyDisplay("tui.editor.jumpBackward");
const pageUp = this.getEditorKeyDisplay("tui.editor.pageUp");
const pageDown = this.getEditorKeyDisplay("tui.editor.pageDown");
// Editing keybindings
const submit = this.getEditorKeyDisplay("tui.input.submit");
const newLine = this.getEditorKeyDisplay("tui.input.newLine");
const deleteWordBackward = this.getEditorKeyDisplay("tui.editor.deleteWordBackward");
const deleteWordForward = this.getEditorKeyDisplay("tui.editor.deleteWordForward");
const deleteToLineStart = this.getEditorKeyDisplay("tui.editor.deleteToLineStart");
const deleteToLineEnd = this.getEditorKeyDisplay("tui.editor.deleteToLineEnd");
const yank = this.getEditorKeyDisplay("tui.editor.yank");
const yankPop = this.getEditorKeyDisplay("tui.editor.yankPop");
const undo = this.getEditorKeyDisplay("tui.editor.undo");
const tab = this.getEditorKeyDisplay("tui.input.tab");
// App keybindings
const interrupt = this.getAppKeyDisplay("app.interrupt");
const clear = this.getAppKeyDisplay("app.clear");
const exit = this.getAppKeyDisplay("app.exit");
const suspend = this.getAppKeyDisplay("app.suspend");
const cycleThinkingLevel = this.getAppKeyDisplay("app.thinking.cycle");
const cycleModelForward = this.getAppKeyDisplay("app.model.cycleForward");
const selectModel = this.getAppKeyDisplay("app.model.select");
const expandTools = this.getAppKeyDisplay("app.tools.expand");
const toggleThinking = this.getAppKeyDisplay("app.thinking.toggle");
const externalEditor = this.getAppKeyDisplay("app.editor.external");
const cycleModelBackward = this.getAppKeyDisplay("app.model.cycleBackward");
const copyMessage = this.getAppKeyDisplay("app.message.copy");
const followUp = this.getAppKeyDisplay("app.message.followUp");
const dequeue = this.getAppKeyDisplay("app.message.dequeue");
const answerQuestion = this.getAppKeyDisplay("app.question.answer");
const nextQuestion = this.getAppKeyDisplay("app.question.next");
const pasteImage = this.getAppKeyDisplay("app.clipboard.pasteImage");
let hotkeys = `
**Navigation**
| Key | Action |
|-----|--------|
| \`${cursorUp}\` / \`${cursorDown}\` / \`${cursorLeft}\` / \`${cursorRight}\` | Move cursor / browse history |
| \`${cursorWordLeft}\` / \`${cursorWordRight}\` | Move by word |
| \`${cursorLineStart}\` | Start of line |
| \`${cursorLineEnd}\` | End of line |
| \`${jumpForward}\` | Jump forward to character |
| \`${jumpBackward}\` | Jump backward to character |
| \`${pageUp}\` / \`${pageDown}\` | Scroll by page |
**Editing**
| Key | Action |
|-----|--------|
| \`${submit}\` | Send message |
| \`${newLine}\` | New line${process.platform === "win32" ? " (Ctrl+Enter on Windows Terminal)" : ""} |
| \`${deleteWordBackward}\` | Delete word backwards |
| \`${deleteWordForward}\` | Delete word forwards |
| \`${deleteToLineStart}\` | Delete to start of line |
| \`${deleteToLineEnd}\` | Delete to end of line |
| \`${yank}\` | Paste the most-recently-deleted text |
| \`${yankPop}\` | Cycle through the deleted text after pasting |
| \`${undo}\` | Undo |
**Other**
| Key | Action |
|-----|--------|
| \`${tab}\` | Path completion / accept autocomplete |
| \`${interrupt}\` | Cancel autocomplete / abort streaming |
| \`${clear}\` | Clear editor (first) / exit (second) |
| \`${exit}\` | Exit (when editor is empty) |
| \`${suspend}\` | Suspend to background |
| \`${cycleThinkingLevel}\` | Cycle thinking level |
| \`${cycleModelForward}\` / \`${cycleModelBackward}\` | Cycle models |
| \`${selectModel}\` | Open model selector |
| \`${expandTools}\` | Toggle tool output expansion |
| \`${toggleThinking}\` | Toggle thinking block visibility |
| \`${externalEditor}\` | Edit message in external editor |
| \`${copyMessage}\` | Copy selection or last assistant message |
| \`${followUp}\` | Queue follow-up message |
| \`${dequeue}\` | Restore queued messages |
| \`${answerQuestion}\` | Open the pending question before dequeue (also: empty Enter; /answer lists requests) |
| \`${nextQuestion}\` | Cycle pending questions from an empty composer |
| \`${pasteImage}\` | Paste files on macOS, images, or text from clipboard |
| \`/\` | Slash commands |
| \`!\` | Run bash command |
| \`!!\` | Run bash command (excluded from context) |
`;
// Add extension-registered shortcuts
const extensionRunner = this.session.extensionRunner;
const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());
if (shortcuts.size > 0) {
hotkeys += `
**Extensions**
| Key | Action |
|-----|--------|
`;
for (const [key, shortcut] of shortcuts) {
const description = shortcut.description ?? shortcut.extensionPath;
const keyDisplay = formatKeyText(key, { capitalize: true });
hotkeys += `| \`${keyDisplay}\` | ${description} |\n`;
}
}
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new DynamicBorder());
this.chatContainer.addChild(new ThemedText(() => theme.bold(theme.fg("accent", "Keyboard Shortcuts")), 1, 0));
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new Markdown(hotkeys.trim(), 1, 1, this.getMarkdownThemeWithSettings()));
this.chatContainer.addChild(new DynamicBorder());
this.ui.requestRender();
}
async handleClearCommand() {
this.clearStatusIndicator();
try {
const result = await this.runtimeHost.newSession();
if (result.cancelled) {
return;
}
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new ThemedText(() => theme.fg("accent", "✓ New session started"), 1, 1));
this.ui.requestRender();
}
catch (error) {
await this.handleFatalRuntimeError("Failed to create session", error);
}
}
handleDebugCommand() {
const width = this.ui.terminal.columns;
const height = this.ui.terminal.rows;
const allLines = this.ui.render(width);
const debugLogPath = getDebugLogPath();
const debugData = [
`Debug output at ${new Date().toISOString()}`,
`Terminal: ${width}x${height}`,
`Total lines: ${allLines.length}`,
"",
"=== All rendered lines with visible widths ===",
...allLines.map((line, idx) => {
const vw = visibleWidth(line);
const escaped = JSON.stringify(line);
return `[${idx}] (w=${vw}) ${escaped}`;
}),
"",
"=== Agent messages (JSONL) ===",
...this.session.messages.map((msg) => JSON.stringify(msg)),
"",
].join("\n");
fs.mkdirSync(path.dirname(debugLogPath), { recursive: true });
fs.writeFileSync(debugLogPath, debugData);
this.showNoticeBox({ title: "✓ Debug log written", tone: "success", why: debugLogPath });
}
handleArminSaysHi() {
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new ArminComponent(this.ui));
this.ui.requestRender();
}
handleDementedDelves() {
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new EarendilAnnouncementComponent());
this.ui.requestRender();
}
handleDaxnuts() {
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new DaxnutsComponent(this.ui));
this.ui.requestRender();
}
checkDaxnutsEasterEgg(model) {
if (model.provider === "opencode" && model.id.toLowerCase().includes("kimi-k2.5")) {
this.handleDaxnuts();
}
}
async handleBashCommand(command, excludeFromContext = false) {
const extensionRunner = this.session.extensionRunner;
// Emit user_bash event to let extensions intercept
let eventResult;
try {
eventResult = await extensionRunner.emitUserBash({
type: "user_bash",
command,
excludeFromContext,
cwd: this.sessionManager.getCwd(),
});
}
catch {
// The extension runner already reported the error. Do not fall back to local execution.
return;
}
// If extension returned a full result, use it directly
if (eventResult?.result) {
const result = eventResult.result;
// Create UI component for display
this.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);
if (this.session.isStreaming) {
this.pendingMessagesContainer.addChild(this.bashComponent);
this.pendingBashComponents.push(this.bashComponent);
}
else {
this.chatContainer.addChild(this.bashComponent);
}
// Show output and complete
if (result.output) {
this.bashComponent.appendOutput(result.output);
}
this.bashComponent.setComplete(result.exitCode, result.cancelled, result.truncated ? { truncated: true, content: result.output } : undefined, result.fullOutputPath);
// Record the result in session
void this.session.recordBashResult(command, result, { excludeFromContext });
this.bashComponent = undefined;
this.ui.requestRender();
return;
}
// Normal execution path (possibly with custom operations)
const isDeferred = this.session.isStreaming;
this.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);
if (isDeferred) {
// Show in pending area when agent is streaming
this.pendingMessagesContainer.addChild(this.bashComponent);
this.pendingBashComponents.push(this.bashComponent);
}
else {
// Show in chat immediately when agent is idle
this.chatContainer.addChild(this.bashComponent);
}
this.ui.requestRender();
try {
const result = await this.session.executeBash(command, (chunk) => {
if (this.bashComponent) {
this.bashComponent.appendOutput(chunk);
this.ui.requestRender();
}
}, { excludeFromContext, operations: eventResult?.operations });
if (this.bashComponent) {
this.bashComponent.setComplete(result.exitCode, result.cancelled, result.truncated ? { truncated: true, content: result.output } : undefined, result.fullOutputPath);
}
}
catch (error) {
if (this.bashComponent) {
this.bashComponent.setComplete(undefined, false);
}
this.showError(`Bash command failed: ${error instanceof Error ? error.message : "Unknown error"}`);
}
this.bashComponent = undefined;
this.ui.requestRender();
}
async handleCompactCommand(customInstructions) {
const entries = this.sessionManager.getEntries();
const messageCount = entries.filter((e) => e.type === "message").length;
if (messageCount < 2) {
this.showWarning("Nothing to compact (no messages yet)");
return;
}
this.clearStatusIndicator();
try {
await this.session.compact(customInstructions);
}
catch {
// Ignore, will be emitted as an event
}
}
stop(options) {
const fullscreenExitOutput = typeof options === "string" ? options : undefined;
const restoreStderr = typeof options === "string" || options?.restoreStderr !== false;
InteractiveMode.restoreCompactionEscapeOverride(this);
this.streamingReveal.stop();
this.toolResultReveal.stop();
this.disposeActiveSelector();
if (this.settingsManager.getShowTerminalProgress()) {
this.ui.terminal.setProgress(false);
}
// The terminal drops working/blocked records only when the process exits; clear before handing it back.
this.setProgramStatus(undefined);
this.programStatusClosed = true;
this.clearStatusIndicator();
this.clearPendingTools();
this.stopChatToolAnimations();
this.clearActiveToolExecutionStatus();
this.clearToolHookStatuses();
this.themeController.disableAutoSync();
this.clearExtensionTerminalInputListeners();
this.footer.dispose();
this.footerDataProvider.dispose();
this.agentSubscriptionGeneration++;
// The footer is disposed: clear the data without scheduling a frame.
this.footerDataProvider.setExtensionStatus(LIFECYCLE_STATUS_KEY, undefined);
if (this.unsubscribe) {
this.unsubscribe();
}
if (this.isInitialized) {
try {
this.stopInteractiveTui(fullscreenExitOutput ?? this.settingsManager.getFullscreenExitOutput());
}
finally {
this.isInitialized = false;
if (restoreStderr)
restoreInteractiveStderr();
}
}
else if (restoreStderr) {
restoreInteractiveStderr();
}
this.unregisterSignalHandlers();
}
}
//# sourceMappingURL=interactive-mode.js.map