UNPKG

@mariozechner/pi-coding-agent

Version:

Coding agent CLI with read, bash, edit, write tools and session management

1 lines 199 kB
{"version":3,"file":"interactive-mode.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-mode.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH,OAAO,KAAK,EAAoB,YAAY,EAAmC,MAAM,qBAAqB,CAAC;AAwC3G,OAAO,EAAE,KAAK,mBAAmB,EAAkC,MAAM,qCAAqC,CAAC;AAoH/G;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACtC,gEAAgE;IAChE,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC7B,4DAA4D;IAC5D,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;IA0H1B,OAAO,CAAC,OAAO;IAzHhB,OAAO,CAAC,WAAW,CAAsB;IACzC,OAAO,CAAC,EAAE,CAAM;IAChB,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,oBAAoB,CAA2C;IACvE,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,eAAe,CAAY;IACnC,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,kBAAkB,CAAqB;IAE/C,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,eAAe,CAAC,CAAyB;IACj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AAC,4BAA4B;IAmBpC,OAAO,CAAC,6BAA6B;IAqBrC,OAAO,CAAC,sBAAsB;IAQ9B,OAAO,CAAC,kBAAkB;YAUZ,oBAAoB;IA6ElC,6DAA6D;IAC7D,OAAO,CAAC,0BAA0B;IAYlC;;;OAGG;IACH,OAAO,CAAC,YAAY;IAapB,OAAO,CAAC,oBAAoB;YA0Id,kBAAkB;YAwBlB,mBAAmB;YAKnB,kBAAkB;YAclB,4BAA4B;YAM5B,uCAAuC;IA6BrD,OAAO,CAAC,iBAAiB;YAgCX,kBAAkB;IA6EhC,OAAO,CAAC,uBAAuB;YA0CjB,kBAAkB;IAuBhC,OAAO,CAAC,gBAAgB;IAiIxB,OAAO,CAAC,mBAAmB;YAmCb,mBAAmB;YAkCnB,iBAAiB;YA+CjB,eAAe;YAwIf,mBAAmB;YAgFnB,mBAAmB;IAgBjC,OAAO,CAAC,sBAAsB;YA6BhB,mBAAmB;YAoDnB,kBAAkB;YA8FlB,iBAAiB;IAe/B,OAAO,CAAC,iBAAiB;IAqBzB,OAAO,CAAC,oBAAoB;IAqC5B,OAAO,CAAC,sBAAsB;IAqB9B;;OAEG;IACH,OAAO,CAAC,aAAa;IAYrB;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAIxB;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,oBAAoB;YAmHd,kBAAkB;IAqBhC,OAAO,CAAC,kBAAkB;IAiC1B,OAAO,CAAC,iBAAiB;IAMzB,OAAO,CAAC,oBAAoB;IAM5B,OAAO,CAAC,aAAa;IAMrB,OAAO,CAAC,qBAAqB;YAMf,iBAAiB;YAuFjB,oBAAoB;IAsBlC,IAAI,IAAI,IAAI,CAgBX;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 \"@mariozechner/pi-agent-core\";\nimport type { AssistantMessage, ImageContent, Message, Model, OAuthProviderId } from \"@mariozechner/pi-ai\";\nimport type {\n\tAutocompleteItem,\n\tEditorComponent,\n\tEditorTheme,\n\tKeybinding,\n\tKeyId,\n\tMarkdownTheme,\n\tOverlayHandle,\n\tOverlayOptions,\n\tSlashCommand,\n} from \"@mariozechner/pi-tui\";\nimport {\n\tCombinedAutocompleteProvider,\n\ttype Component,\n\tContainer,\n\tfuzzyFilter,\n\tLoader,\n\ttype LoaderIndicatorOptions,\n\tMarkdown,\n\tmatchesKey,\n\tProcessTerminal,\n\tSpacer,\n\tsetKeybindings,\n\tText,\n\tTruncatedText,\n\tTUI,\n\tvisibleWidth,\n} from \"@mariozechner/pi-tui\";\nimport { spawn, spawnSync } from \"child_process\";\nimport {\n\tAPP_NAME,\n\tgetAgentDir,\n\tgetAuthPath,\n\tgetDebugLogPath,\n\tgetShareViewerUrl,\n\tgetUpdateInstruction,\n\tVERSION,\n} from \"../../config.js\";\nimport { type AgentSession, type AgentSessionEvent, parseSkillBlock } from \"../../core/agent-session.js\";\nimport { type AgentSessionRuntime, SessionImportFileNotFoundError } from \"../../core/agent-session-runtime.js\";\nimport type {\n\tExtensionContext,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n} from \"../../core/extensions/index.js\";\nimport { FooterDataProvider, type ReadonlyFooterDataProvider } from \"../../core/footer-data-provider.js\";\nimport { type AppKeybinding, KeybindingsManager } from \"../../core/keybindings.js\";\nimport { createCompactionSummaryMessage } from \"../../core/messages.js\";\nimport { defaultModelPerProvider, findExactModelReferenceMatch, resolveModelScope } from \"../../core/model-resolver.js\";\nimport { DefaultPackageManager } from \"../../core/package-manager.js\";\nimport type { ResourceDiagnostic } from \"../../core/resource-loader.js\";\nimport { formatMissingSessionCwdPrompt, MissingSessionCwdError } from \"../../core/session-cwd.js\";\nimport { type SessionContext, SessionManager } from \"../../core/session-manager.js\";\nimport { BUILTIN_SLASH_COMMANDS } from \"../../core/slash-commands.js\";\nimport type { SourceInfo } from \"../../core/source-info.js\";\nimport { isInstallTelemetryEnabled } from \"../../core/telemetry.js\";\nimport type { TruncationResult } from \"../../core/tools/truncate.js\";\nimport { getChangelogPath, getNewEntries, parseChangelog } from \"../../utils/changelog.js\";\nimport { copyToClipboard } from \"../../utils/clipboard.js\";\nimport { extensionForImageMimeType, readClipboardImage } from \"../../utils/clipboard-image.js\";\nimport { parseGitUrl } from \"../../utils/git.js\";\nimport { killTrackedDetachedChildren } from \"../../utils/shell.js\";\nimport { ensureTool } from \"../../utils/tools-manager.js\";\nimport { ArminComponent } from \"./components/armin.js\";\nimport { AssistantMessageComponent } from \"./components/assistant-message.js\";\nimport { BashExecutionComponent } from \"./components/bash-execution.js\";\nimport { BorderedLoader } from \"./components/bordered-loader.js\";\nimport { BranchSummaryMessageComponent } from \"./components/branch-summary-message.js\";\nimport { CompactionSummaryMessageComponent } from \"./components/compaction-summary-message.js\";\nimport { CountdownTimer } from \"./components/countdown-timer.js\";\nimport { CustomEditor } from \"./components/custom-editor.js\";\nimport { CustomMessageComponent } from \"./components/custom-message.js\";\nimport { DaxnutsComponent } from \"./components/daxnuts.js\";\nimport { DynamicBorder } from \"./components/dynamic-border.js\";\nimport { EarendilAnnouncementComponent } from \"./components/earendil-announcement.js\";\nimport { ExtensionEditorComponent } from \"./components/extension-editor.js\";\nimport { ExtensionInputComponent } from \"./components/extension-input.js\";\nimport { ExtensionSelectorComponent } from \"./components/extension-selector.js\";\nimport { FooterComponent } from \"./components/footer.js\";\nimport { keyHint, keyText, rawKeyHint } from \"./components/keybinding-hints.js\";\nimport { LoginDialogComponent } from \"./components/login-dialog.js\";\nimport { ModelSelectorComponent } from \"./components/model-selector.js\";\nimport { OAuthSelectorComponent } from \"./components/oauth-selector.js\";\nimport { ScopedModelsSelectorComponent } from \"./components/scoped-models-selector.js\";\nimport { SessionSelectorComponent } from \"./components/session-selector.js\";\nimport { SettingsSelectorComponent } from \"./components/settings-selector.js\";\nimport { SkillInvocationMessageComponent } from \"./components/skill-invocation-message.js\";\nimport { ToolExecutionComponent } from \"./components/tool-execution.js\";\nimport { TreeSelectorComponent } from \"./components/tree-selector.js\";\nimport { UserMessageComponent } from \"./components/user-message.js\";\nimport { UserMessageSelectorComponent } from \"./components/user-message-selector.js\";\nimport {\n\tgetAvailableThemes,\n\tgetAvailableThemesWithPaths,\n\tgetEditorTheme,\n\tgetMarkdownTheme,\n\tgetThemeByName,\n\tinitTheme,\n\tonThemeChange,\n\tsetRegisteredThemes,\n\tsetTheme,\n\tsetThemeInstance,\n\tstopThemeWatcher,\n\tTheme,\n\ttype ThemeColor,\n\ttheme,\n} from \"./theme/theme.js\";\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\tconstructor(\n\t\tprivate readonly getCollapsedText: () => string,\n\t\tprivate readonly getExpandedText: () => 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}\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\nconst ANTHROPIC_SUBSCRIPTION_AUTH_WARNING =\n\t\"Anthropic subscription auth is active. Third-party usage now draws from extra usage and is billed per token, not your Claude plan limits. Manage extra usage at https://claude.ai/settings/usage.\";\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 hasDefaultModelProvider(providerId: string): providerId is keyof typeof defaultModelPerProvider {\n\treturn providerId in defaultModelPerProvider;\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/** 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 chatContainer: Container;\n\tprivate pendingMessagesContainer: Container;\n\tprivate statusContainer: Container;\n\tprivate defaultEditor: CustomEditor;\n\tprivate editor: EditorComponent;\n\tprivate autocompleteProvider: CombinedAutocompleteProvider | undefined;\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 loadingAnimation: Loader | undefined = undefined;\n\tprivate pendingWorkingMessage: string | undefined = undefined;\n\tprivate workingIndicatorOptions: LoaderIndicatorOptions | 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// Track first user message to avoid leading spacer at top of chat\n\tprivate isFirstUserMessage = true;\n\n\t// Tool output expansion state\n\tprivate toolOutputExpanded = false;\n\n\t// Thinking block visibility state\n\tprivate hideThinkingBlock = false;\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 autoCompactionLoader: Loader | undefined = undefined;\n\tprivate autoCompactionEscapeHandler?: () => void;\n\n\t// Auto-retry state\n\tprivate retryLoader: Loader | undefined = undefined;\n\tprivate retryCountdown: CountdownTimer | undefined = undefined;\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\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(\n\t\truntimeHost: AgentSessionRuntime,\n\t\tprivate options: InteractiveModeOptions = {},\n\t) {\n\t\tthis.runtimeHost = runtimeHost;\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.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\n\t\t// Register themes from resource loader and initialize\n\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\tinitTheme(this.settingsManager.getTheme(), true);\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 setupAutocomplete(fdPath: string | undefined): void {\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}));\n\n\t\tconst modelCommand = slashCommands.find((command) => command.name === \"model\");\n\t\tif (modelCommand) {\n\t\t\tmodelCommand.getArgumentCompletions = (prefix: string): 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: this.session.modelRegistry.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\tlabel: `${m.provider}/${m.id}`,\n\t\t\t\t}));\n\n\t\t\t\t// Fuzzy filter by model ID + provider (allows \"opus anthropic\" to match)\n\t\t\t\tconst filtered = fuzzyFilter(items, prefix, (item) => `${item.id} ${item.provider}`);\n\n\t\t\t\tif (filtered.length === 0) return null;\n\n\t\t\t\treturn filtered.map((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\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\t// Setup autocomplete\n\t\tthis.autocompleteProvider = new CombinedAutocompleteProvider(\n\t\t\t[...slashCommands, ...templateCommands, ...extensionCommands, ...skillCommandList],\n\t\t\tthis.sessionManager.getCwd(),\n\t\t\tfdPath,\n\t\t);\n\t\tthis.defaultEditor.setAutocompleteProvider(this.autocompleteProvider);\n\t\tif (this.editor !== this.defaultEditor) {\n\t\t\tthis.editor.setAutocompleteProvider?.(this.autocompleteProvider);\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\t// Add header container as first child\n\t\tthis.ui.addChild(this.headerContainer);\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\"),\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\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\t// Initialize extensions first so resources are shown before messages\n\t\tawait this.bindCurrentSessionExtensions();\n\n\t\t// Render initial messages AFTER showing loaded resources\n\t\tthis.renderInitialMessages();\n\n\t\t// Set terminal title\n\t\tthis.updateTerminalTitle();\n\n\t\t// Subscribe to agent events\n\t\tthis.subscribeToAgent();\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(`π - ${sessionName} - ${cwdBasename}`);\n\t\t} else {\n\t\t\tthis.ui.terminal.setTitle(`π - ${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\tthis.checkForNewVersion().then((newVersion) => {\n\t\t\tif (newVersion) {\n\t\t\t\tthis.showNewVersionNotification(newVersion);\n\t\t\t}\n\t\t});\n\n\t\t// Start package update check asynchronously\n\t\tthis.checkForPackageUpdates().then((updates) => {\n\t\t\tif (updates.length > 0) {\n\t\t\t\tthis.showPackageUpdateNotification(updates);\n\t\t\t}\n\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.modelRegistry.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\t/**\n\t * Check npm registry for a newer version.\n\t */\n\tprivate async checkForNewVersion(): Promise<string | undefined> {\n\t\tif (process.env.PI_SKIP_VERSION_CHECK || process.env.PI_OFFLINE) return undefined;\n\n\t\ttry {\n\t\t\tconst response = await fetch(\"https://registry.npmjs.org/@mariozechner/pi-coding-agent/latest\", {\n\t\t\t\tsignal: AbortSignal.timeout(10000),\n\t\t\t});\n\t\t\tif (!response.ok) return undefined;\n\n\t\t\tconst data = (await response.json()) as { version?: string };\n\t\t\tconst latestVersion = data.version;\n\n\t\t\tif (latestVersion && latestVersion !== this.version) {\n\t\t\t\treturn latestVersion;\n\t\t\t}\n\n\t\t\treturn undefined;\n\t\t} catch {\n\t\t\treturn undefined;\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) => e.content).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/install?version=${encodeURIComponent(version)}`, {\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 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 = path.relative(cwd, absolutePath);\n\t\tconst isInsideCwd =\n\t\t\trelativePath === \"\" ||\n\t\t\t(!relativePath.startsWith(\"..\") &&\n\t\t\t\t!relativePath.startsWith(`..${path.sep}`) &&\n\t\t\t\t!path.isAbsolute(relativePath));\n\n\t\tif (isInsideCwd) {\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.match(/git\\/[^/]+\\/[^/]+\\/(.*)/);\n\t\tif (gitMatch && source.startsWith(\"git:\")) {\n\t\t\treturn gitMatch[1];\n\t\t}\n\n\t\treturn this.formatDisplayPath(fullPath);\n\t}\n\n\tprivate getCompactPathLabel(resourcePath: string, sourceInfo?: SourceInfo): string {\n\t\tconst shortPath = this.getShortPath(resourcePath, sourceInfo);\n\t\tconst normalizedPath = shortPath.replace(/\\\\/g, \"/\");\n\t\tconst segments = normalizedPath.split(\"/\").filter((segment) => segment.length > 0 && segment !== \"~\");\n\t\tif (segments.length > 0) {\n\t\t\treturn segments[segments.length - 1]!;\n\t\t}\n\t\treturn shortPath;\n\t}\n\n\tprivate getCompactPackageSourceLabel(sourceInfo?: SourceInfo): string {\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\treturn source.slice(\"npm:\".length) || source;\n\t\t}\n\n\t\tconst gitSource = parseGitUrl(source);\n\t\tif (gitSource) {\n\t\t\treturn gitSource.path || source;\n\t\t}\n\n\t\treturn source;\n\t}\n\n\tprivate getCompactExtensionLabel(resourcePath: string, sourceInfo?: SourceInfo): string {\n\t\tif (!this.isPackageSource(sourceInfo)) {\n\t\t\treturn this.getCompactPathLabel(resourcePath, sourceInfo);\n\t\t}\n\n\t\tconst sourceLabel = this.getCompactPackageSourceLabel(sourceInfo);\n\t\tif (!sourceLabel) {\n\t\t\treturn this.getCompactPathLabel(resourcePath, sourceInfo);\n\t\t}\n\n\t\tconst shortPath = this.getShortPath(resourcePath, sourceInfo).replace(/\\\\/g, \"/\");\n\t\tconst packagePath = shortPath.startsWith(\"extensions/\") ? shortPath.slice(\"extensions/\".length) : shortPath;\n\t\tconst parsedPath = path.posix.parse(packagePath);\n\n\t\tif (parsedPath.name === \"index\") {\n\t\t\treturn !parsedPath.dir || parsedPath.dir === \".\" ? sourceLabel : `${sourceLabel}:${parsedPath.dir}`;\n\t\t}\n\n\t\treturn `${sourceLabel}:${packagePath}`;\n\t}\n\n\tprivate getCompactDisplayPathSegments(resourcePath: string): string[] {\n\t\treturn this.formatDisplayPath(resourcePath)\n\t\t\t.replace(/\\\\/g, \"/\")\n\t\t\t.split(\"/\")\n\t\t\t.filter((segment) => segment.length > 0 && segment !== \"~\");\n\t}\n\n\tprivate getCompactNonPackageExtensionLabel(\n\t\tresourcePath: string,\n\t\tindex: number,\n\t\tallPaths: Array<{ path: string; segments: string[] }>,\n\t): string {\n\t\tconst segments = allPaths[index]?.segments;\n\t\tif (!segments || segments.length === 0) {\n\t\t\treturn this.getCompactPathLabel(resourcePath);\n\t\t}\n\n\t\tfor (let segmentCount = 1; segmentCount <= segments.length; segmentCount += 1) {\n\t\t\tconst candidate = segments.slice(-segmentCount).join(\"/\");\n\t\t\tconst isUnique = allPaths.every((item, itemIndex) => {\n\t\t\t\tif (itemIndex === index) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn item.segments.slice(-segmentCount).join(\"/\") !== candidate;\n\t\t\t});\n\n\t\t\tif (isUnique) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\n\t\treturn segments.join(\"/\");\n\t}\n\n\tprivate getCompactExtensionLabels(extensions: Array<{ path: string; sourceInfo?: SourceInfo }>): string[] {\n\t\tconst nonPackageExtensions = extensions\n\t\t\t.map((extension) => ({\n\t\t\t\tpath: extension.path,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\tsegments: this.getCompactDisplayPathSegments(extension.path),\n\t\t\t}))\n\t\t\t.filter((extension) => !this.isPackageSource(extension.sourceInfo));\n\n\t\treturn extensions.map((extension) => {\n\t\t\tif (this.isPackageSource(extension.sourceInfo)) {\n\t\t\t\treturn this.getCompactExtensionLabel(extension.path, extension.sourceInfo);\n\t\t\t}\n\n\t\t\tconst nonPackageIndex = nonPackageExtensions.findIndex((item) => item.path === extension.path);\n\t\t\tif (nonPackageIndex === -1) {\n\t\t\t\treturn this.getCompactPathLabel(extension.path, extension.sourceInfo);\n\t\t\t}\n\n\t\t\treturn this.getCompactNonPackageExtensionLabel(extension.path, nonPackageIndex, nonPackageExtensions);\n\t\t});\n\t}\n\n\tprivate getDisplaySourceInfo(sourceInfo?: SourceInfo): {\n\t\tlabel: string;\n\t\tscopeLabel?: string;\n\t\tcolor: \"accent\" | \"muted\";\n\t} {\n\t\tconst source = sourceInfo?.source ?? \"local\";\n\t\tconst scope = sourceInfo?.scope ?? \"project\";\n\t\tif (source === \"local\") {\n\t\t\tif (scope === \"user\") {\n\t\t\t\treturn { label: \"user\", color: \"muted\" };\n\t\t\t}\n\t\t\tif (scope === \"project\") {\n\t\t\t\treturn { label: \"project\", color: \"muted\" };\n\t\t\t}\n\t\t\tif (scope === \"temporary\") {\n\t\t\t\treturn { label: \"path\", scopeLabel: \"temp\", color: \"muted\" };\n\t\t\t}\n\t\t\treturn { label: \"path\", color: \"muted\" };\n\t\t}\n\n\t\tif (source === \"cli\") {\n\t\t\treturn { label: \"path\", scopeLabel: scope === \"temporary\" ? \"temp\" : undefined, color: \"muted\" };\n\t\t}\n\n\t\tconst scopeLabel =\n\t\t\tscope === \"user\" ? \"user\" : scope === \"project\" ? \"project\" : scope === \"temporary\" ? \"temp\" : undefined;\n\t\treturn { label: source, scopeLabel, color: \"accent\" };\n\t}\n\n\tprivate getScopeGroup(sourceInfo?: SourceInfo): \"user\" | \"project\" | \"path\" {\n\t\tconst source = sourceInfo?.source ?? \"local\";\n\t\tconst scope = sourceInfo?.scope ?? \"project\";\n\t\tif (source === \"cli\" || scope === \"temporary\") return \"path\";\n\t\tif (scope === \"user\") return \"user\";\n\t\tif (scope === \"project\") return \"project\";\n\t\treturn \"path\";\n\t}\n\n\tprivate isPackageSource(sourceInfo?: SourceInfo): boolean {\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\treturn source.startsWith(\"npm:\") || source.startsWith(\"git:\");\n\t}\n\n\tprivate buildScopeGroups(items: Array<{ path: string; sourceInfo?: SourceInfo }>): Array<{\n\t\tscope: \"user\" | \"project\" | \"path\";\n\t\tpaths: Array<{ path: string; sourceInfo?: SourceInfo }>;\n\t\tpackages: Map<string, Array<{ path: string; sourceInfo?: SourceInfo }>>;\n\t}> {\n\t\tconst groups: Record<\n\t\t\t\"user\" | \"project\" | \"path\",\n\t\t\t{\n\t\t\t\tscope: \"user\" | \"project\" | \"path\";\n\t\t\t\tpaths: Array<{ path: string; sourceInfo?: SourceInfo }>;\n\t\t\t\tpackages: Map<string, Array<{ path: string; sourceInfo?: SourceInfo }>>;\n\t\t\t}\n\t\t> = {\n\t\t\tuser: { scope: \"user\", paths: [], packages: new Map() },\n\t\t\tproject: { scope: \"project\", paths: [], packages: new Map() },\n\t\t\tpath: { scope: \"path\", paths: [], packages: new Map() },\n\t\t};\n\n\t\tfor (const item of items) {\n\t\t\tconst groupKey = this.getScopeGroup(item.sourceInfo);\n\t\t\tconst group = groups[groupKey];\n\t\t\tconst source = item.sourceInfo?.source ?? \"local\";\n\n\t\t\tif (this.isPackageSource(item.sourceInfo)) {\n\t\t\t\tconst list = group.packages.get(source) ?? [];\n\t\t\t\tlist.push(item);\n\t\t\t\tgroup.packages.set(source, list);\n\t\t\t} else {\n\t\t\t\tgroup.paths.push(item);\n\t\t\t}\n\t\t}\n\n\t\treturn [groups.project, groups.user, groups.path].filter(\n\t\t\t(group) => group.paths.length > 0 || group.packages.size > 0,\n\t\t);\n\t}\n\n\tprivate formatScopeGroups(\n\t\tgroups: Array<{\n\t\t\tscope: \"user\" | \"project\" | \"path\";\n\t\t\tpaths: Array<{ path: string; sourceInfo?: SourceInfo }>;\n\t\t\tpackages: Map<string, Array<{ path: string; sourceInfo?: SourceInfo }>>;\n\t\t}>,\n\t\toptions: {\n\t\t\tformatPath: (item: { path: string; sourceInfo?: SourceInfo }) => string;\n\t\t\tformatPackagePath: (item: { path: string; sourceInfo?: SourceInfo }, source: string) => string;\n\t\t},\n\t): string {\n\t\tconst lines: string[] = [];\n\n\t\tfor (const group of groups) {\n\t\t\tlines.push(` ${theme.fg(\"accent\", group.scope)}`);\n\n\t\t\tconst sortedPaths = [...group.paths].sort((a, b) => a.path.localeCompare(b.path));\n\t\t\tfor (const item of sortedPaths) {\n\t\t\t\tlines.push(theme.fg(\"dim\", ` ${options.formatPath(item)}`));\n\t\t\t}\n\n\t\t\tconst sortedPackages = Array.from(group.packages.entries()).sort(([a], [b]) => a.localeCompare(b));\n\t\t\tfor (const [source, items] of sortedPackages) {\n\t\t\t\tlines.push(` ${theme.fg(\"mdLink\", source)}`);\n\t\t\t\tconst sortedPackagePaths = [...items].sort((a, b) => a.path.localeCompare(b.path));\n\t\t\t\tfor (const item of sortedPackagePaths) {\n\t\t\t\t\tlines.push(theme.fg(\"dim\", ` ${options.formatPackagePath(item, source)}`));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tprivate findSourceInfoForPath(p: string, sourceInfos: Map<string, SourceInfo>): SourceInfo | undefined {\n\t\tcon