@earendil-works/pi-coding-agent
Version:
Coding agent CLI with read, bash, edit, write tools and session management
1 lines • 236 kB
Source Map (JSON)
{"version":3,"file":"interactive-mode.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-mode.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAQH,OAAO,KAAK,EAAoB,YAAY,EAAkB,MAAM,8BAA8B,CAAC;AA2CnG,OAAO,EAAE,KAAK,mBAAmB,EAAkC,MAAM,qCAAqC,CAAC;AA4B/G,OAAO,EAAqB,cAAc,EAAiC,MAAM,+BAA+B,CAAC;AAcjH,OAAO,EAAwB,KAAK,eAAe,EAAE,MAAM,8BAA8B,CAAC;AA+H1F,wBAAgB,mBAAmB,CAAC,cAAc,EAAE,cAAc,GAAG,MAAM,GAAG,SAAS,CAatF;AA2DD;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACtC,gEAAgE;IAChE,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC7B,4DAA4D;IAC5D,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,qGAAqG;IACrG,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,qEAAqE;IACrE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,8CAA8C;IAC9C,aAAa,CAAC,EAAE,YAAY,EAAE,CAAC;IAC/B,4DAA4D;IAC5D,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,6DAA6D;IAC7D,OAAO,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,qBAAa,eAAe;IAC3B,OAAO,CAAC,WAAW,CAAsB;IACzC,OAAO,CAAC,EAAE,CAAM;IAChB,OAAO,CAAC,wBAAwB,CAAY;IAC5C,OAAO,CAAC,aAAa,CAAY;IACjC,OAAO,CAAC,wBAAwB,CAAY;IAC5C,OAAO,CAAC,eAAe,CAAY;IACnC,OAAO,CAAC,aAAa,CAAe;IACpC,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,sBAAsB,CAA4B;IA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BAAuB;YAsCjB,kBAAkB;IAqBhC,OAAO,CAAC,gBAAgB;IAuIxB,OAAO,CAAC,mBAAmB;YAsCb,mBAAmB;IAqCjC,OAAO,CAAC,uBAAuB;YAgCjB,wBAAwB;IAWtC,OAAO,CAAC,wBAAwB;YAalB,kBAAkB;YAwBlB,kBAAkB;IAUhC,OAAO,CAAC,yBAAyB;IA0DjC,OAAO,CAAC,yBAAyB;YA2CnB,iBAAiB;YA+CjB,8BAA8B;IAqD5C,OAAO,CAAC,qBAAqB;YAuBf,qBAAqB;IA6CnC,OAAO,CAAC,cAAc;YAiCR,cAAc;IAwB5B,OAAO,CAAC,gBAAgB;YAaV,aAAa;YAYb,eAAe;YAgCf,mBAAmB;YAwGnB,mBAAmB;IAgBjC,OAAO,CAAC,sBAAsB;YA6BhB,mBAAmB;YA4CnB,kBAAkB;YA8FlB,iBAAiB;IAe/B,OAAO,CAAC,iBAAiB;IAwBzB,OAAO,CAAC,oBAAoB;IA4E5B,OAAO,CAAC,sBAAsB;IAqB9B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAIxB;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,oBAAoB;YAqHd,kBAAkB;IAehC,OAAO,CAAC,kBAAkB;IAiC1B,OAAO,CAAC,iBAAiB;IAMzB,OAAO,CAAC,oBAAoB;IAM5B,OAAO,CAAC,aAAa;IAMrB,OAAO,CAAC,qBAAqB;YAMf,iBAAiB;YAuFjB,oBAAoB;IAUlC,IAAI,IAAI,IAAI,CAiBX;CACD","sourcesContent":["/**\n * Interactive mode for the coding agent.\n * Handles TUI rendering and user interaction, delegating business logic to AgentSession.\n */\n\nimport * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AuthEvent, AuthPrompt } from \"@earendil-works/pi-ai\";\nimport type { AssistantMessage, ImageContent, Message, Model } from \"@earendil-works/pi-ai/compat\";\nimport type {\n\tAutocompleteItem,\n\tAutocompleteProvider,\n\tEditorComponent,\n\tKeybinding,\n\tKeyId,\n\tMarkdownTheme,\n\tOverlayHandle,\n\tOverlayOptions,\n\tSlashCommand,\n} from \"@earendil-works/pi-tui\";\nimport {\n\tCombinedAutocompleteProvider,\n\ttype Component,\n\tContainer,\n\tfuzzyFilter,\n\tgetCapabilities,\n\thyperlink,\n\tMarkdown,\n\tmatchesKey,\n\tProcessTerminal,\n\tSpacer,\n\tsetKeybindings,\n\tText,\n\tTruncatedText,\n\tTUI,\n\tvisibleWidth,\n} from \"@earendil-works/pi-tui\";\nimport chalk from \"chalk\";\nimport { spawn, spawnSync } from \"child_process\";\nimport {\n\tAPP_NAME,\n\tAPP_TITLE,\n\tCONFIG_DIR_NAME,\n\tgetAgentDir,\n\tgetAuthPath,\n\tgetDebugLogPath,\n\tgetDocsPath,\n\tgetShareViewerUrl,\n\tVERSION,\n} from \"../../config.ts\";\nimport { type AgentSession, type AgentSessionEvent, parseSkillBlock } from \"../../core/agent-session.ts\";\nimport { type AgentSessionRuntime, SessionImportFileNotFoundError } from \"../../core/agent-session-runtime.ts\";\nimport {\n\tCACHE_TTL_MS,\n\ttype CacheMiss,\n\tcollectCacheMisses,\n\tcomputeCacheWaste,\n\tdetectCacheMiss,\n} from \"../../core/cache-stats.ts\";\nimport type {\n\tAutocompleteProviderFactory,\n\tEditorFactory,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tProjectTrustContext,\n\tWorkingIndicatorOptions,\n} from \"../../core/extensions/index.ts\";\nimport { FooterDataProvider, type ReadonlyFooterDataProvider } from \"../../core/footer-data-provider.ts\";\nimport { configureHttpDispatcher, formatHttpIdleTimeoutMs } from \"../../core/http-dispatcher.ts\";\nimport { type AppKeybinding, KeybindingsManager } from \"../../core/keybindings.ts\";\nimport { createCompactionSummaryMessage } from \"../../core/messages.ts\";\nimport { defaultModelPerProvider, findExactModelReferenceMatch, resolveModelScope } from \"../../core/model-resolver.ts\";\nimport { DefaultPackageManager } from \"../../core/package-manager.ts\";\nimport type { ResourceDiagnostic } from \"../../core/resource-loader.ts\";\nimport { formatMissingSessionCwdPrompt, MissingSessionCwdError } from \"../../core/session-cwd.ts\";\nimport { type SessionEntry, SessionManager, sessionEntryToContextMessages } from \"../../core/session-manager.ts\";\nimport { BUILTIN_SLASH_COMMANDS } from \"../../core/slash-commands.ts\";\nimport type { SourceInfo } from \"../../core/source-info.ts\";\nimport { isInstallTelemetryEnabled } from \"../../core/telemetry.ts\";\nimport type { TruncationResult } from \"../../core/tools/truncate.ts\";\nimport { hasTrustRequiringProjectResources, ProjectTrustStore } from \"../../core/trust-manager.ts\";\nimport { getChangelogPath, getNewEntries, normalizeChangelogLinks, parseChangelog } from \"../../utils/changelog.ts\";\nimport { copyToClipboard, readClipboardText } from \"../../utils/clipboard.ts\";\nimport { extensionForImageMimeType, readClipboardImage } from \"../../utils/clipboard-image.ts\";\nimport { parseGitUrl } from \"../../utils/git.ts\";\nimport { getCwdRelativePath } from \"../../utils/paths.ts\";\nimport { getPiUserAgent } from \"../../utils/pi-user-agent.ts\";\nimport { killTrackedDetachedChildren } from \"../../utils/shell.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport { checkForNewPiVersion, type LatestPiRelease } from \"../../utils/version-check.ts\";\nimport { ArminComponent } from \"./components/armin.ts\";\nimport { AssistantMessageComponent } from \"./components/assistant-message.ts\";\nimport { BashExecutionComponent } from \"./components/bash-execution.ts\";\nimport { BorderedLoader } from \"./components/bordered-loader.ts\";\nimport { BranchSummaryMessageComponent } from \"./components/branch-summary-message.ts\";\nimport { CompactionSummaryMessageComponent } from \"./components/compaction-summary-message.ts\";\nimport { CustomEditor } from \"./components/custom-editor.ts\";\nimport { CustomEntryComponent } from \"./components/custom-entry.ts\";\nimport { CustomMessageComponent } from \"./components/custom-message.ts\";\nimport { DaxnutsComponent } from \"./components/daxnuts.ts\";\nimport { DynamicBorder } from \"./components/dynamic-border.ts\";\nimport { EarendilAnnouncementComponent } from \"./components/earendil-announcement.ts\";\nimport { ExtensionEditorComponent } from \"./components/extension-editor.ts\";\nimport { ExtensionInputComponent } from \"./components/extension-input.ts\";\nimport { ExtensionSelectorComponent } from \"./components/extension-selector.ts\";\nimport { FooterComponent, formatTokens } from \"./components/footer.ts\";\nimport { formatKeyText, keyDisplayText, keyHint, keyText, rawKeyHint } from \"./components/keybinding-hints.ts\";\nimport { LoginDialogComponent } from \"./components/login-dialog.ts\";\nimport { ModelSelectorComponent } from \"./components/model-selector.ts\";\nimport {\n\ttype AuthSelectorProvider,\n\tformatAuthSelectorProviderType,\n\tOAuthSelectorComponent,\n} from \"./components/oauth-selector.ts\";\nimport { ScopedModelsSelectorComponent } from \"./components/scoped-models-selector.ts\";\nimport { SessionSelectorComponent } from \"./components/session-selector.ts\";\nimport { SettingsSelectorComponent } from \"./components/settings-selector.ts\";\nimport { SkillInvocationMessageComponent } from \"./components/skill-invocation-message.ts\";\nimport {\n\tBranchSummaryStatusIndicator,\n\tCompactionStatusIndicator,\n\tIdleStatus,\n\tRetryStatusIndicator,\n\ttype StatusIndicator,\n\tWorkingStatusIndicator,\n} from \"./components/status-indicator.ts\";\nimport { ToolExecutionComponent } from \"./components/tool-execution.ts\";\nimport { TreeSelectorComponent } from \"./components/tree-selector.ts\";\nimport { TrustSelectorComponent } from \"./components/trust-selector.ts\";\nimport { UserMessageComponent } from \"./components/user-message.ts\";\nimport { UserMessageSelectorComponent } from \"./components/user-message-selector.ts\";\nimport { getModelSearchText } from \"./model-search.ts\";\nimport {\n\tgetAvailableThemes,\n\tgetAvailableThemesWithPaths,\n\tgetEditorTheme,\n\tgetMarkdownTheme,\n\tgetThemeByName,\n\tonThemeChange,\n\tsetRegisteredThemes,\n\tstopThemeWatcher,\n\tTheme,\n\ttype ThemeColor,\n\ttheme,\n} from \"./theme/theme.ts\";\nimport { InteractiveThemeController } from \"./theme/theme-controller.ts\";\n\n/** Interface for components that can be expanded/collapsed */\ninterface Expandable {\n\tsetExpanded(expanded: boolean): void;\n}\n\nfunction isExpandable(obj: unknown): obj is Expandable {\n\treturn typeof obj === \"object\" && obj !== null && \"setExpanded\" in obj && typeof obj.setExpanded === \"function\";\n}\n\nclass ExpandableText extends Text implements Expandable {\n\tprivate readonly getCollapsedText: () => string;\n\tprivate readonly getExpandedText: () => string;\n\n\tconstructor(\n\t\tgetCollapsedText: () => string,\n\t\tgetExpandedText: () => string,\n\t\texpanded = false,\n\t\tpaddingX = 0,\n\t\tpaddingY = 0,\n\t) {\n\t\tsuper(expanded ? getExpandedText() : getCollapsedText(), paddingX, paddingY);\n\t\tthis.getCollapsedText = getCollapsedText;\n\t\tthis.getExpandedText = getExpandedText;\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.setText(expanded ? this.getExpandedText() : this.getCollapsedText());\n\t}\n}\n\ntype CompactionQueuedMessage = {\n\ttext: string;\n\tmode: \"steer\" | \"followUp\";\n};\n\ntype RenderSessionItem = AgentMessage | Extract<SessionEntry, { type: \"custom\" }>;\n\nfunction isCustomSessionEntry(item: RenderSessionItem): item is Extract<SessionEntry, { type: \"custom\" }> {\n\treturn \"type\" in item && item.type === \"custom\";\n}\n\nconst DEAD_TERMINAL_ERROR_CODES = new Set([\"EIO\", \"EPIPE\", \"ENOTCONN\"]);\n\nfunction isDeadTerminalError(error: unknown): boolean {\n\tif (!error || typeof error !== \"object\" || !(\"code\" in error)) {\n\t\treturn false;\n\t}\n\tconst code = (error as NodeJS.ErrnoException).code;\n\treturn code !== undefined && DEAD_TERMINAL_ERROR_CODES.has(code);\n}\n\nconst ANTHROPIC_SUBSCRIPTION_AUTH_WARNING =\n\t\"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.\";\n\nfunction isAnthropicSubscriptionAuthKey(apiKey: string | undefined): boolean {\n\treturn typeof apiKey === \"string\" && apiKey.startsWith(\"sk-ant-oat\");\n}\n\nfunction isUnknownModel(model: Model<any> | undefined): boolean {\n\treturn !!model && model.provider === \"unknown\" && model.id === \"unknown\" && model.api === \"unknown\";\n}\n\nfunction quoteIfNeeded(value: string): string {\n\tif (value.length > 0 && !/[^a-zA-Z0-9_\\-./~:@]/.test(value)) {\n\t\treturn value;\n\t}\n\treturn `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\nexport function formatResumeCommand(sessionManager: SessionManager): string | undefined {\n\tif (!process.stdout.isTTY) return undefined;\n\tif (!sessionManager.isPersisted()) return undefined;\n\n\tconst sessionFile = sessionManager.getSessionFile();\n\tif (!sessionFile || !fs.existsSync(sessionFile)) return undefined;\n\n\tconst args = [APP_NAME];\n\tif (!sessionManager.usesDefaultSessionDir()) {\n\t\targs.push(\"--session-dir\", quoteIfNeeded(sessionManager.getSessionDir()));\n\t}\n\targs.push(\"--session\", sessionManager.getSessionId());\n\treturn args.join(\" \");\n}\n\nfunction hasDefaultModelProvider(providerId: string): providerId is keyof typeof defaultModelPerProvider {\n\treturn providerId in defaultModelPerProvider;\n}\n\ntype LoginProviderCompletionOption = {\n\tid: string;\n\tname: string;\n\tauthTypes: AuthSelectorProvider[\"authType\"][];\n};\n\nconst AUTH_TYPE_ORDER = { oauth: 0, api_key: 1 } satisfies Record<AuthSelectorProvider[\"authType\"], number>;\n\nfunction createFuzzyAutocompleteItems<T>(\n\titems: T[],\n\tprefix: string,\n\tgetSearchText: (item: T) => string,\n\ttoAutocompleteItem: (item: T) => AutocompleteItem,\n): AutocompleteItem[] | null {\n\tconst filtered = fuzzyFilter(items, prefix, getSearchText);\n\tif (filtered.length === 0) return null;\n\treturn filtered.map(toAutocompleteItem);\n}\n\nfunction getLoginProviderCompletionOptions(\n\tproviderOptions: readonly AuthSelectorProvider[],\n): LoginProviderCompletionOption[] {\n\tconst byId = new Map<string, LoginProviderCompletionOption>();\n\tfor (const provider of providerOptions) {\n\t\tconst existing = byId.get(provider.id);\n\t\tif (existing) {\n\t\t\tif (!existing.authTypes.includes(provider.authType)) {\n\t\t\t\texisting.authTypes.push(provider.authType);\n\t\t\t\texisting.authTypes.sort((a, b) => AUTH_TYPE_ORDER[a] - AUTH_TYPE_ORDER[b]);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tbyId.set(provider.id, {\n\t\t\tid: provider.id,\n\t\t\tname: provider.name,\n\t\t\tauthTypes: [provider.authType],\n\t\t});\n\t}\n\treturn Array.from(byId.values()).sort((a, b) => a.name.localeCompare(b.name));\n}\n\nfunction getLoginProviderSearchText(provider: LoginProviderCompletionOption): string {\n\tconst authTypes = provider.authTypes\n\t\t.map((authType) => `${authType} ${formatAuthSelectorProviderType(authType)}`)\n\t\t.join(\" \");\n\treturn `${provider.id} ${provider.name} ${authTypes}`;\n}\n\nfunction formatLoginProviderCompletionDescription(provider: LoginProviderCompletionOption): string {\n\tconst authTypes = provider.authTypes.map(formatAuthSelectorProviderType).join(\"/\");\n\treturn provider.name === provider.id ? authTypes : `${provider.name} · ${authTypes}`;\n}\n\n/**\n * Options for InteractiveMode initialization.\n */\nexport interface InteractiveModeOptions {\n\t/** Providers that were migrated to auth.json (shows warning) */\n\tmigratedProviders?: string[];\n\t/** Warning message if session model couldn't be restored */\n\tmodelFallbackMessage?: string;\n\t/** Cwd to trust after reload if it gained a .pi directory during this implicitly trusted session. */\n\tautoTrustOnReloadCwd?: string;\n\t/** Initial message to send on startup (can include @file content) */\n\tinitialMessage?: string;\n\t/** Images to attach to the initial message */\n\tinitialImages?: ImageContent[];\n\t/** Additional messages to send after the initial message */\n\tinitialMessages?: string[];\n\t/** Force verbose startup (overrides quietStartup setting) */\n\tverbose?: boolean;\n}\n\nexport class InteractiveMode {\n\tprivate runtimeHost: AgentSessionRuntime;\n\tprivate ui: TUI;\n\tprivate loadedResourcesContainer: Container;\n\tprivate chatContainer: Container;\n\tprivate pendingMessagesContainer: Container;\n\tprivate statusContainer: Container;\n\tprivate defaultEditor: CustomEditor;\n\tprivate editor: EditorComponent;\n\tprivate editorComponentFactory: EditorFactory | undefined;\n\tprivate autocompleteProvider: AutocompleteProvider | undefined;\n\tprivate autocompleteProviderWrappers: AutocompleteProviderFactory[] = [];\n\tprivate fdPath: string | undefined;\n\tprivate editorContainer: Container;\n\tprivate footer: FooterComponent;\n\tprivate footerDataProvider: FooterDataProvider;\n\t// Stored so the same manager can be injected into custom editors, selectors, and extension UI.\n\tprivate keybindings: KeybindingsManager;\n\tprivate version: string;\n\tprivate isInitialized = false;\n\tprivate onInputCallback?: (text: string) => void;\n\tprivate pendingUserInputs: string[] = [];\n\tprivate activeStatusIndicator: StatusIndicator | undefined = undefined;\n\tprivate readonly idleStatus = new IdleStatus();\n\tprivate workingMessage: string | undefined = undefined;\n\tprivate workingVisible = true;\n\tprivate workingIndicatorOptions: WorkingIndicatorOptions | undefined = undefined;\n\tprivate readonly defaultWorkingMessage = \"Working...\";\n\tprivate readonly defaultHiddenThinkingLabel = \"Thinking...\";\n\tprivate hiddenThinkingLabel = this.defaultHiddenThinkingLabel;\n\n\tprivate lastSigintTime = 0;\n\tprivate lastEscapeTime = 0;\n\tprivate changelogMarkdown: string | undefined = undefined;\n\tprivate startupNoticesShown = false;\n\tprivate anthropicSubscriptionWarningShown = false;\n\n\t// Status line tracking (for mutating immediately-sequential status updates)\n\tprivate lastStatusSpacer: Spacer | undefined = undefined;\n\tprivate lastStatusText: Text | undefined = undefined;\n\n\t// Streaming message tracking\n\tprivate streamingComponent: AssistantMessageComponent | undefined = undefined;\n\tprivate streamingMessage: AssistantMessage | undefined = undefined;\n\n\t// Tool execution tracking: toolCallId -> component\n\tprivate pendingTools = new Map<string, ToolExecutionComponent>();\n\n\t// Tool output expansion state\n\tprivate toolOutputExpanded = false;\n\n\t// Thinking block visibility state\n\tprivate hideThinkingBlock = false;\n\tprivate outputPad = 1;\n\n\t// Skill commands: command name -> skill file path\n\tprivate skillCommands = new Map<string, string>();\n\n\t// Agent subscription unsubscribe function\n\tprivate unsubscribe?: () => void;\n\tprivate signalCleanupHandlers: Array<() => void> = [];\n\n\t// Track if editor is in bash mode (text starts with !)\n\tprivate isBashMode = false;\n\n\t// Track current bash execution component\n\tprivate bashComponent: BashExecutionComponent | undefined = undefined;\n\n\t// Track pending bash components (shown in pending area, moved to chat on submit)\n\tprivate pendingBashComponents: BashExecutionComponent[] = [];\n\n\t// Auto-compaction state\n\tprivate autoCompactionEscapeHandler?: () => void;\n\n\t// Auto-retry state\n\tprivate retryEscapeHandler?: () => void;\n\n\t// Messages queued while compaction is running\n\tprivate compactionQueuedMessages: CompactionQueuedMessage[] = [];\n\n\t// Shutdown state\n\tprivate shutdownRequested = false;\n\n\t// Extension UI state\n\tprivate extensionSelector: ExtensionSelectorComponent | undefined = undefined;\n\tprivate extensionInput: ExtensionInputComponent | undefined = undefined;\n\tprivate extensionEditor: ExtensionEditorComponent | undefined = undefined;\n\tprivate extensionTerminalInputUnsubscribers = new Set<() => void>();\n\n\t// Extension widgets (components rendered above/below the editor)\n\tprivate extensionWidgetsAbove = new Map<string, Component & { dispose?(): void }>();\n\tprivate extensionWidgetsBelow = new Map<string, Component & { dispose?(): void }>();\n\tprivate widgetContainerAbove!: Container;\n\tprivate widgetContainerBelow!: Container;\n\n\t// Custom footer from extension (undefined = use built-in footer)\n\tprivate customFooter: (Component & { dispose?(): void }) | undefined = undefined;\n\n\t// Header container that holds the built-in or custom header\n\tprivate headerContainer: Container;\n\n\t// Built-in header (logo + keybinding hints + changelog)\n\tprivate builtInHeader: Component | undefined = undefined;\n\n\t// Custom header from extension (undefined = use built-in header)\n\tprivate customHeader: (Component & { dispose?(): void }) | undefined = undefined;\n\n\tprivate options: InteractiveModeOptions;\n\tprivate autoTrustOnReloadCwd: string | undefined;\n\tprivate themeController: InteractiveThemeController;\n\n\t// Convenience accessors\n\tprivate get session(): AgentSession {\n\t\treturn this.runtimeHost.session;\n\t}\n\tprivate get agent() {\n\t\treturn this.session.agent;\n\t}\n\tprivate get sessionManager() {\n\t\treturn this.session.sessionManager;\n\t}\n\tprivate get settingsManager() {\n\t\treturn this.session.settingsManager;\n\t}\n\n\tconstructor(runtimeHost: AgentSessionRuntime, options: InteractiveModeOptions = {}) {\n\t\tthis.runtimeHost = runtimeHost;\n\t\tthis.options = options;\n\t\tthis.autoTrustOnReloadCwd = options.autoTrustOnReloadCwd;\n\t\tthis.runtimeHost.setBeforeSessionInvalidate(() => {\n\t\t\tthis.resetExtensionUI();\n\t\t});\n\t\tthis.runtimeHost.setRebindSession(async () => {\n\t\t\tawait this.rebindCurrentSession({ renderBeforeBind: true });\n\t\t});\n\t\tthis.version = VERSION;\n\t\tthis.ui = new TUI(new ProcessTerminal(), this.settingsManager.getShowHardwareCursor());\n\t\tthis.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());\n\t\tthis.headerContainer = new Container();\n\t\tthis.loadedResourcesContainer = new Container();\n\t\tthis.chatContainer = new Container();\n\t\tthis.pendingMessagesContainer = new Container();\n\t\tthis.statusContainer = new Container();\n\t\tthis.widgetContainerAbove = new Container();\n\t\tthis.widgetContainerBelow = new Container();\n\t\tthis.keybindings = KeybindingsManager.create();\n\t\tsetKeybindings(this.keybindings);\n\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\tthis.defaultEditor = new CustomEditor(this.ui, getEditorTheme(), this.keybindings, {\n\t\t\tpaddingX: editorPaddingX,\n\t\t\tautocompleteMaxVisible,\n\t\t});\n\t\tthis.editor = this.defaultEditor;\n\t\tthis.editorContainer = new Container();\n\t\tthis.editorContainer.addChild(this.editor as Component);\n\t\tthis.footerDataProvider = new FooterDataProvider(this.sessionManager.getCwd());\n\t\tthis.footer = new FooterComponent(this.session, this.footerDataProvider);\n\t\tthis.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);\n\n\t\t// Load hide thinking block setting\n\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\n\t\t// Register themes from resource loader and initialize\n\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\tthis.themeController = new InteractiveThemeController(\n\t\t\tthis.ui,\n\t\t\tthis.settingsManager,\n\t\t\t(message) => this.showError(message),\n\t\t\t() => this.updateEditorBorderColor(),\n\t\t);\n\t}\n\n\tprivate getAutocompleteSourceTag(sourceInfo?: SourceInfo): string | undefined {\n\t\tif (!sourceInfo) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst scopePrefix = sourceInfo.scope === \"user\" ? \"u\" : sourceInfo.scope === \"project\" ? \"p\" : \"t\";\n\t\tconst source = sourceInfo.source.trim();\n\n\t\tif (source === \"auto\" || source === \"local\" || source === \"cli\") {\n\t\t\treturn scopePrefix;\n\t\t}\n\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\treturn `${scopePrefix}:${source}`;\n\t\t}\n\n\t\tconst gitSource = parseGitUrl(source);\n\t\tif (gitSource) {\n\t\t\tconst ref = gitSource.ref ? `@${gitSource.ref}` : \"\";\n\t\t\treturn `${scopePrefix}:git:${gitSource.host}/${gitSource.path}${ref}`;\n\t\t}\n\n\t\treturn scopePrefix;\n\t}\n\n\tprivate prefixAutocompleteDescription(description: string | undefined, sourceInfo?: SourceInfo): string | undefined {\n\t\tconst sourceTag = this.getAutocompleteSourceTag(sourceInfo);\n\t\tif (!sourceTag) {\n\t\t\treturn description;\n\t\t}\n\t\treturn description ? `[${sourceTag}] ${description}` : `[${sourceTag}]`;\n\t}\n\n\tprivate getBuiltInCommandConflictDiagnostics(extensionRunner: ExtensionRunner): ResourceDiagnostic[] {\n\t\tconst builtinNames = new Set(BUILTIN_SLASH_COMMANDS.map((command) => command.name));\n\t\treturn extensionRunner\n\t\t\t.getRegisteredCommands()\n\t\t\t.filter((command) => builtinNames.has(command.name))\n\t\t\t.map((command) => ({\n\t\t\t\ttype: \"warning\" as const,\n\t\t\t\tmessage:\n\t\t\t\t\tcommand.invocationName === command.name\n\t\t\t\t\t\t? `Extension command '/${command.name}' conflicts with built-in interactive command. Skipping in autocomplete.`\n\t\t\t\t\t\t: `Extension command '/${command.name}' conflicts with built-in interactive command. Available as '/${command.invocationName}'.`,\n\t\t\t\tpath: command.sourceInfo.path,\n\t\t\t}));\n\t}\n\n\tprivate createBaseAutocompleteProvider(): AutocompleteProvider {\n\t\t// Define commands for autocomplete\n\t\tconst slashCommands: SlashCommand[] = BUILTIN_SLASH_COMMANDS.map((command) => ({\n\t\t\tname: command.name,\n\t\t\tdescription: command.description,\n\t\t\t...(command.argumentHint && { argumentHint: command.argumentHint }),\n\t\t}));\n\n\t\tconst modelCommand = slashCommands.find((command) => command.name === \"model\");\n\t\tif (modelCommand) {\n\t\t\tmodelCommand.getArgumentCompletions = async (prefix: string): Promise<AutocompleteItem[] | null> => {\n\t\t\t\t// Get available models (scoped or from registry)\n\t\t\t\tconst models =\n\t\t\t\t\tthis.session.scopedModels.length > 0\n\t\t\t\t\t\t? this.session.scopedModels.map((s) => s.model)\n\t\t\t\t\t\t: await this.session.modelRuntime.getAvailable();\n\n\t\t\t\tif (models.length === 0) return null;\n\n\t\t\t\t// Create items with provider/id format\n\t\t\t\tconst items = models.map((m) => ({\n\t\t\t\t\tid: m.id,\n\t\t\t\t\tprovider: m.provider,\n\t\t\t\t\tname: m.name,\n\t\t\t\t\tlabel: `${m.provider}/${m.id}`,\n\t\t\t\t}));\n\n\t\t\t\treturn createFuzzyAutocompleteItems(items, prefix, getModelSearchText, (item) => ({\n\t\t\t\t\tvalue: item.label,\n\t\t\t\t\tlabel: item.id,\n\t\t\t\t\tdescription: item.provider,\n\t\t\t\t}));\n\t\t\t};\n\t\t}\n\n\t\tconst loginCommand = slashCommands.find((command) => command.name === \"login\");\n\t\tif (loginCommand) {\n\t\t\tloginCommand.getArgumentCompletions = (prefix: string): AutocompleteItem[] | null => {\n\t\t\t\tconst providers = getLoginProviderCompletionOptions(this.getLoginProviderOptions());\n\t\t\t\treturn createFuzzyAutocompleteItems(providers, prefix, getLoginProviderSearchText, (provider) => ({\n\t\t\t\t\tvalue: provider.id,\n\t\t\t\t\tlabel: provider.id,\n\t\t\t\t\tdescription: formatLoginProviderCompletionDescription(provider),\n\t\t\t\t}));\n\t\t\t};\n\t\t}\n\n\t\t// Convert prompt templates to SlashCommand format for autocomplete\n\t\tconst templateCommands: SlashCommand[] = this.session.promptTemplates.map((cmd) => ({\n\t\t\tname: cmd.name,\n\t\t\tdescription: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),\n\t\t\t...(cmd.argumentHint && { argumentHint: cmd.argumentHint }),\n\t\t}));\n\n\t\t// Convert extension commands to SlashCommand format\n\t\tconst builtinCommandNames = new Set(slashCommands.map((c) => c.name));\n\t\tconst extensionCommands: SlashCommand[] = this.session.extensionRunner\n\t\t\t.getRegisteredCommands()\n\t\t\t.filter((cmd) => !builtinCommandNames.has(cmd.name))\n\t\t\t.map((cmd) => ({\n\t\t\t\tname: cmd.invocationName,\n\t\t\t\tdescription: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),\n\t\t\t\tgetArgumentCompletions: cmd.getArgumentCompletions,\n\t\t\t}));\n\n\t\t// Build skill commands from session.skills (if enabled)\n\t\tthis.skillCommands.clear();\n\t\tconst skillCommandList: SlashCommand[] = [];\n\t\tif (this.settingsManager.getEnableSkillCommands()) {\n\t\t\tfor (const skill of this.session.resourceLoader.getSkills().skills) {\n\t\t\t\tconst commandName = `skill:${skill.name}`;\n\t\t\t\tthis.skillCommands.set(commandName, skill.filePath);\n\t\t\t\tskillCommandList.push({\n\t\t\t\t\tname: commandName,\n\t\t\t\t\tdescription: this.prefixAutocompleteDescription(skill.description, skill.sourceInfo),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn new CombinedAutocompleteProvider(\n\t\t\t[...slashCommands, ...templateCommands, ...extensionCommands, ...skillCommandList],\n\t\t\tthis.sessionManager.getCwd(),\n\t\t\tthis.fdPath,\n\t\t);\n\t}\n\n\tprivate setupAutocompleteProvider(): void {\n\t\tlet provider = this.createBaseAutocompleteProvider();\n\t\tconst triggerCharacters: string[] = [];\n\t\tfor (const wrapProvider of this.autocompleteProviderWrappers) {\n\t\t\tprovider = wrapProvider(provider);\n\t\t\ttriggerCharacters.push(...(provider.triggerCharacters ?? []));\n\t\t}\n\t\tif (triggerCharacters.length > 0) {\n\t\t\tprovider.triggerCharacters = [...new Set(triggerCharacters)];\n\t\t}\n\n\t\tthis.autocompleteProvider = provider;\n\t\tthis.defaultEditor.setAutocompleteProvider(provider);\n\t\tif (this.editor !== this.defaultEditor) {\n\t\t\tthis.editor.setAutocompleteProvider?.(provider);\n\t\t}\n\t}\n\n\tprivate showStartupNoticesIfNeeded(): void {\n\t\tif (this.startupNoticesShown) {\n\t\t\treturn;\n\t\t}\n\t\tthis.startupNoticesShown = true;\n\n\t\tif (!this.changelogMarkdown) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.chatContainer.children.length > 0) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tif (this.settingsManager.getCollapseChangelog()) {\n\t\t\tconst versionMatch = this.changelogMarkdown.match(/##\\s+\\[?(\\d+\\.\\d+\\.\\d+)\\]?/);\n\t\t\tconst latestVersion = versionMatch ? versionMatch[1] : this.version;\n\t\t\tconst condensedText = `Updated to v${latestVersion}. Use ${theme.bold(\"/changelog\")} to view full changelog.`;\n\t\t\tthis.chatContainer.addChild(new Text(condensedText, 1, 0));\n\t\t} else {\n\t\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(\n\t\t\t\tnew Markdown(this.changelogMarkdown.trim(), 1, 0, this.getMarkdownThemeWithSettings()),\n\t\t\t);\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t}\n\n\tasync init(): Promise<void> {\n\t\tif (this.isInitialized) return;\n\n\t\tthis.registerSignalHandlers();\n\n\t\t// Load changelog (only show new entries, skip for resumed sessions)\n\t\tthis.changelogMarkdown = this.getChangelogForDisplay();\n\n\t\t// Ensure fd and rg are available (downloads if missing, adds to PATH via getBinDir)\n\t\t// Both are needed: fd for autocomplete, rg for grep tool and bash commands\n\t\tconst [fdPath] = await Promise.all([ensureTool(\"fd\"), ensureTool(\"rg\")]);\n\t\tthis.fdPath = fdPath;\n\n\t\tif (this.session.scopedModels.length > 0 && (this.options.verbose || !this.settingsManager.getQuietStartup())) {\n\t\t\tconst modelList = this.session.scopedModels\n\t\t\t\t.map((sm) => {\n\t\t\t\t\tconst thinkingStr = sm.thinkingLevel ? `:${sm.thinkingLevel}` : \"\";\n\t\t\t\t\treturn `${sm.model.id}${thinkingStr}`;\n\t\t\t\t})\n\t\t\t\t.join(\", \");\n\t\t\tconst cycleKeys = this.keybindings.getKeys(\"app.model.cycleForward\");\n\t\t\tconst cycleHint =\n\t\t\t\tcycleKeys.length > 0\n\t\t\t\t\t? theme.fg(\"muted\", ` (${formatKeyText(cycleKeys.join(\"/\"), { capitalize: true })} to cycle)`)\n\t\t\t\t\t: \"\";\n\t\t\tconsole.log(theme.fg(\"dim\", `Model scope: ${modelList}${cycleHint}`));\n\t\t}\n\n\t\t// Add header container as first child. Populate it after applying theme settings.\n\t\t// Keep loaded resources before chat so restored session messages never precede them.\n\t\tthis.ui.addChild(this.headerContainer);\n\t\tthis.ui.addChild(this.loadedResourcesContainer);\n\n\t\tthis.ui.addChild(this.chatContainer);\n\t\tthis.ui.addChild(this.pendingMessagesContainer);\n\t\tthis.ui.addChild(this.statusContainer);\n\t\tthis.renderWidgets(); // Initialize with default spacer\n\t\tthis.ui.addChild(this.widgetContainerAbove);\n\t\tthis.ui.addChild(this.editorContainer);\n\t\tthis.ui.addChild(this.widgetContainerBelow);\n\t\tthis.ui.addChild(this.footer);\n\t\tthis.ui.setFocus(this.editor);\n\n\t\tthis.setupKeyHandlers();\n\t\tthis.setupEditorSubmitHandler();\n\n\t\t// Start the UI before initializing extensions so session_start handlers can use interactive dialogs\n\t\tthis.ui.start();\n\t\tthis.isInitialized = true;\n\n\t\tawait this.themeController.applyFromSettings();\n\n\t\t// Add header with keybindings from config (unless silenced)\n\t\tif (this.options.verbose || !this.settingsManager.getQuietStartup()) {\n\t\t\tconst logo = theme.bold(theme.fg(\"accent\", APP_NAME)) + theme.fg(\"dim\", ` v${this.version}`);\n\n\t\t\t// Build startup instructions using keybinding hint helpers\n\t\t\tconst hint = (keybinding: AppKeybinding, description: string) => keyHint(keybinding, description);\n\n\t\t\tconst expandedInstructions = [\n\t\t\t\thint(\"app.interrupt\", \"to interrupt\"),\n\t\t\t\thint(\"app.clear\", \"to clear\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.clear\")} twice`, \"to exit\"),\n\t\t\t\thint(\"app.exit\", \"to exit (empty)\"),\n\t\t\t\thint(\"app.suspend\", \"to suspend\"),\n\t\t\t\tkeyHint(\"tui.editor.deleteToLineEnd\", \"to delete to end\"),\n\t\t\t\thint(\"app.thinking.cycle\", \"to cycle thinking level\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.model.cycleForward\")}/${keyText(\"app.model.cycleBackward\")}`, \"to cycle models\"),\n\t\t\t\thint(\"app.model.select\", \"to select model\"),\n\t\t\t\thint(\"app.tools.expand\", \"to expand tools\"),\n\t\t\t\thint(\"app.thinking.toggle\", \"to expand thinking\"),\n\t\t\t\thint(\"app.editor.external\", \"for external editor\"),\n\t\t\t\trawKeyHint(\"/\", \"for commands\"),\n\t\t\t\trawKeyHint(\"!\", \"to run bash\"),\n\t\t\t\trawKeyHint(\"!!\", \"to run bash (no context)\"),\n\t\t\t\thint(\"app.message.followUp\", \"to queue follow-up\"),\n\t\t\t\thint(\"app.message.dequeue\", \"to edit all queued messages\"),\n\t\t\t\thint(\"app.clipboard.pasteImage\", \"to paste image (with text fallback)\"),\n\t\t\t\trawKeyHint(\"drop files\", \"to attach\"),\n\t\t\t].join(\"\\n\");\n\t\t\tconst compactInstructions = [\n\t\t\t\thint(\"app.interrupt\", \"interrupt\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.clear\")}/${keyText(\"app.exit\")}`, \"clear/exit\"),\n\t\t\t\trawKeyHint(\"/\", \"commands\"),\n\t\t\t\trawKeyHint(\"!\", \"bash\"),\n\t\t\t\thint(\"app.tools.expand\", \"more\"),\n\t\t\t].join(theme.fg(\"muted\", \" · \"));\n\t\t\tconst compactOnboarding = theme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t`Press ${keyText(\"app.tools.expand\")} to show full startup help and loaded resources.`,\n\t\t\t);\n\t\t\tconst onboarding = theme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t`Pi can explain its own features and look up its docs. Ask it how to use or extend Pi.`,\n\t\t\t);\n\t\t\tthis.builtInHeader = new ExpandableText(\n\t\t\t\t() => `${logo}\\n${compactInstructions}\\n${compactOnboarding}\\n\\n${onboarding}`,\n\t\t\t\t() => `${logo}\\n${expandedInstructions}\\n\\n${onboarding}`,\n\t\t\t\tthis.getStartupExpansionState(),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t);\n\n\t\t\t// Setup UI layout\n\t\t\tthis.headerContainer.addChild(new Spacer(1));\n\t\t\tthis.headerContainer.addChild(this.builtInHeader);\n\t\t\tthis.headerContainer.addChild(new Spacer(1));\n\t\t} else {\n\t\t\t// Minimal header when silenced\n\t\t\tthis.builtInHeader = new Text(\"\", 0, 0);\n\t\t\tthis.headerContainer.addChild(this.builtInHeader);\n\t\t}\n\t\tthis.ui.requestRender();\n\n\t\t// Initialize extensions first so resources are shown before messages\n\t\tawait this.rebindCurrentSession();\n\n\t\t// Render initial messages AFTER showing loaded resources\n\t\tthis.renderInitialMessages();\n\n\t\t// Set up theme file watcher\n\t\tonThemeChange(() => {\n\t\t\tthis.ui.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.ui.requestRender();\n\t\t});\n\n\t\t// Set up git branch watcher (uses provider instead of footer)\n\t\tthis.footerDataProvider.onBranchChange(() => {\n\t\t\tthis.ui.requestRender();\n\t\t});\n\n\t\t// Initialize available provider count for footer display\n\t\tawait this.updateAvailableProviderCount();\n\t}\n\n\t/**\n\t * Update terminal title with session name and cwd.\n\t */\n\tprivate updateTerminalTitle(): void {\n\t\tconst cwdBasename = path.basename(this.sessionManager.getCwd());\n\t\tconst sessionName = this.sessionManager.getSessionName();\n\t\tif (sessionName) {\n\t\t\tthis.ui.terminal.setTitle(`${APP_TITLE} - ${sessionName} - ${cwdBasename}`);\n\t\t} else {\n\t\t\tthis.ui.terminal.setTitle(`${APP_TITLE} - ${cwdBasename}`);\n\t\t}\n\t}\n\n\t/**\n\t * Run the interactive mode. This is the main entry point.\n\t * Initializes the UI, shows warnings, processes initial messages, and starts the interactive loop.\n\t */\n\tasync run(): Promise<void> {\n\t\tawait this.init();\n\n\t\t// Start version check asynchronously\n\t\tcheckForNewPiVersion(this.version).then((newRelease) => {\n\t\t\tif (newRelease) {\n\t\t\t\tthis.showNewVersionNotification(newRelease);\n\t\t\t}\n\t\t});\n\n\t\t// Start package update check asynchronously\n\t\tthis.checkForPackageUpdates()\n\t\t\t.then((updates) => {\n\t\t\t\tif (updates.length > 0) {\n\t\t\t\t\tthis.showPackageUpdateNotification(updates);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\t// On Windows, npm can overwrite the shared console title while checking\n\t\t\t\t// extension package versions. Restore Pi's title after the startup check.\n\t\t\t\tif (process.platform === \"win32\" && this.isInitialized) {\n\t\t\t\t\tthis.updateTerminalTitle();\n\t\t\t\t}\n\t\t\t});\n\n\t\t// Check tmux keyboard setup asynchronously\n\t\tthis.checkTmuxKeyboardSetup().then((warning) => {\n\t\t\tif (warning) {\n\t\t\t\tthis.showWarning(warning);\n\t\t\t}\n\t\t});\n\n\t\t// Show startup warnings\n\t\tconst { migratedProviders, modelFallbackMessage, initialMessage, initialImages, initialMessages } = this.options;\n\n\t\tif (migratedProviders && migratedProviders.length > 0) {\n\t\t\tthis.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(\", \")}`);\n\t\t}\n\n\t\tconst modelsJsonError = this.session.modelRuntime.getError();\n\t\tif (modelsJsonError) {\n\t\t\tthis.showError(`models.json error: ${modelsJsonError}`);\n\t\t}\n\n\t\tif (modelFallbackMessage) {\n\t\t\tthis.showWarning(modelFallbackMessage);\n\t\t}\n\n\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth();\n\n\t\t// Process initial messages\n\t\tif (initialMessage) {\n\t\t\ttry {\n\t\t\t\tawait this.session.prompt(initialMessage, { images: initialImages });\n\t\t\t} catch (error: unknown) {\n\t\t\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\t\tthis.showError(errorMessage);\n\t\t\t}\n\t\t}\n\n\t\tif (initialMessages) {\n\t\t\tfor (const message of initialMessages) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.session.prompt(message);\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\t\t\tthis.showError(errorMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Main interactive loop\n\t\twhile (true) {\n\t\t\tconst userInput = await this.getUserInput();\n\t\t\ttry {\n\t\t\t\tawait this.session.prompt(userInput);\n\t\t\t} catch (error: unknown) {\n\t\t\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\t\tthis.showError(errorMessage);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async checkForPackageUpdates(): Promise<string[]> {\n\t\tif (process.env.PI_OFFLINE) {\n\t\t\treturn [];\n\t\t}\n\n\t\ttry {\n\t\t\tconst packageManager = new DefaultPackageManager({\n\t\t\t\tcwd: this.sessionManager.getCwd(),\n\t\t\t\tagentDir: getAgentDir(),\n\t\t\t\tsettingsManager: this.settingsManager,\n\t\t\t});\n\t\t\tconst updates = await packageManager.checkForAvailableUpdates();\n\t\t\treturn updates.map((update) => update.displayName);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\tprivate async checkTmuxKeyboardSetup(): Promise<string | undefined> {\n\t\tif (!process.env.TMUX) return undefined;\n\n\t\tconst runTmuxShow = (option: string): Promise<string | undefined> => {\n\t\t\treturn new Promise((resolve) => {\n\t\t\t\tconst proc = spawn(\"tmux\", [\"show\", \"-gv\", option], {\n\t\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t\t});\n\t\t\t\tlet stdout = \"\";\n\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\tproc.kill();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t}, 2000);\n\n\t\t\t\tproc.stdout?.on(\"data\", (data) => {\n\t\t\t\t\tstdout += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.on(\"error\", () => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t});\n\t\t\t\tproc.on(\"close\", (code) => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(code === 0 ? stdout.trim() : undefined);\n\t\t\t\t});\n\t\t\t});\n\t\t};\n\n\t\tconst [extendedKeys, extendedKeysFormat] = await Promise.all([\n\t\t\trunTmuxShow(\"extended-keys\"),\n\t\t\trunTmuxShow(\"extended-keys-format\"),\n\t\t]);\n\n\t\t// If we couldn't query tmux (timeout, sandbox, etc.), don't warn\n\t\tif (extendedKeys === undefined) return undefined;\n\n\t\tif (extendedKeys !== \"on\" && extendedKeys !== \"always\") {\n\t\t\treturn \"tmux extended-keys is off. Modified Enter keys may not work. Add `set -g extended-keys on` to ~/.tmux.conf and restart tmux.\";\n\t\t}\n\n\t\tif (extendedKeysFormat === \"xterm\") {\n\t\t\treturn \"tmux extended-keys-format is xterm. Pi works best with csi-u. Add `set -g extended-keys-format csi-u` to ~/.tmux.conf and restart tmux.\";\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Get changelog entries to display on startup.\n\t * Only shows new entries since last seen version, skips for resumed sessions.\n\t */\n\tprivate getChangelogForDisplay(): string | undefined {\n\t\t// Skip changelog for resumed/continued sessions (already have messages)\n\t\tif (this.session.state.messages.length > 0) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst lastVersion = this.settingsManager.getLastChangelogVersion();\n\t\tconst changelogPath = getChangelogPath();\n\t\tconst entries = parseChangelog(changelogPath);\n\n\t\tif (!lastVersion) {\n\t\t\t// Fresh install - record the version, send telemetry, don't show changelog\n\t\t\tthis.settingsManager.setLastChangelogVersion(VERSION);\n\t\t\tthis.reportInstallTelemetry(VERSION);\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst newEntries = getNewEntries(entries, lastVersion);\n\t\tif (newEntries.length > 0) {\n\t\t\tthis.settingsManager.setLastChangelogVersion(VERSION);\n\t\t\tthis.reportInstallTelemetry(VERSION);\n\t\t\treturn newEntries.map((e) => normalizeChangelogLinks(e.content, e)).join(\"\\n\\n\");\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate reportInstallTelemetry(version: string): void {\n\t\tif (process.env.PI_OFFLINE) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!isInstallTelemetryEnabled(this.settingsManager)) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid fetch(`https://pi.dev/api/report-install?version=${encodeURIComponent(version)}`, {\n\t\t\theaders: {\n\t\t\t\t\"User-Agent\": getPiUserAgent(version),\n\t\t\t},\n\t\t\tsignal: AbortSignal.timeout(5000),\n\t\t})\n\t\t\t.then(() => undefined)\n\t\t\t.catch(() => undefined);\n\t}\n\n\tprivate getMarkdownThemeWithSettings(): MarkdownTheme {\n\t\treturn {\n\t\t\t...getMarkdownTheme(),\n\t\t\tcodeBlockIndent: this.settingsManager.getCodeBlockIndent(),\n\t\t};\n\t}\n\n\t// =========================================================================\n\t// Extension System\n\t// =========================================================================\n\n\tprivate formatDisplayPath(p: string): string {\n\t\tconst home = os.homedir();\n\t\tlet result = p;\n\n\t\t// Replace home directory with ~\n\t\tif (result.startsWith(home)) {\n\t\t\tresult = `~${result.slice(home.length)}`;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate formatExtensionDisplayPath(path: string): string {\n\t\tlet result = this.formatDisplayPath(path);\n\t\tresult = result.replace(/\\/index\\.ts$/, \"\").replace(/\\/index\\.js$/, \"\");\n\t\treturn result;\n\t}\n\n\tprivate formatContextPath(p: string): string {\n\t\tconst cwd = path.resolve(this.sessionManager.getCwd());\n\t\tconst absolutePath = path.isAbsolute(p) ? path.resolve(p) : path.resolve(cwd, p);\n\t\tconst relativePath = getCwdRelativePath(absolutePath, cwd);\n\t\tif (relativePath !== undefined) {\n\t\t\treturn relativePath;\n\t\t}\n\n\t\treturn this.formatDisplayPath(absolutePath);\n\t}\n\n\tprivate getStartupExpansionState(): boolean {\n\t\treturn this.options.verbose || this.toolOutputExpanded;\n\t}\n\n\t/**\n\t * Get a short path relative to the package root for display.\n\t */\n\tprivate getShortPath(fullPath: string, sourceInfo?: SourceInfo): string {\n\t\tconst baseDir = sourceInfo?.baseDir;\n\t\tif (baseDir && this.isPackageSource(sourceInfo)) {\n\t\t\tconst relativePath = path.relative(path.resolve(baseDir), path.resolve(fullPath));\n\t\t\tif (\n\t\t\t\trelativePath &&\n\t\t\t\trelativePath !== \".\" &&\n\t\t\t\t!relativePath.startsWith(\"..\") &&\n\t\t\t\t!relativePath.startsWith(`..${path.sep}`) &&\n\t\t\t\t!path.isAbsolute(relativePath)\n\t\t\t) {\n\t\t\t\treturn relativePath.replace(/\\\\/g, \"/\");\n\t\t\t}\n\t\t}\n\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\tconst npmMatch = fullPath.match(/node_modules\\/(@?[^/]+(?:\\/[^/]+)?)\\/(.*)/);\n\t\tif (npmMatch && source.startsWith(\"npm:\")) {\n\t\t\treturn npmMatch[2];\n\t\t}\n\n\t\tconst gitMatch = fullPath.mat