import { ChatAgent, ChatHierarchyBranch, ChatModel, ChatRequestModel, ChatService, ChatRequestParser, ChatMode, ChatSession } from '@theia/ai-chat'; import { ChatAgentService } from '@theia/ai-chat/lib/common/chat-agent-service'; import { ParsedChatRequest } from '@theia/ai-chat/lib/common/parsed-chat-request'; import { GenericCapabilitySelections, AIVariableResolutionRequest, ParsedCapability, FrontendLanguageModelRegistry, LanguageModel, ReasoningLevel, ReasoningSettings, ReasoningSupport, ServerToolDescriptor } from '@theia/ai-core'; import { ChangeSetDecoratorService } from '@theia/ai-chat/lib/browser/change-set-decorator-service'; import { ImageContextVariable } from '@theia/ai-chat/lib/common/image-context-variable'; import { AIActivationService, FavoriteModelsService, FrontendVariableService } from '@theia/ai-core/lib/browser'; import { AISettingsService, LanguageModelAliasRegistry, PromptService } from '@theia/ai-core/lib/common'; import { CommandService, DisposableCollection, Emitter, InMemoryResources, MessageService, URI, Disposable, ILogger } from '@theia/core'; import { ContextMenuRenderer, HoverService, LabelProvider, Message, OpenerService, ReactWidget } from '@theia/core/lib/browser'; import { ContextKey, ContextKeyService } from '@theia/core/lib/browser/context-key-service'; import { KeybindingRegistry } from '@theia/core/lib/browser/keybinding'; import { Deferred } from '@theia/core/lib/common/promise-util'; import * as React from '@theia/core/shared/react'; import { IMouseEvent } from '@theia/monaco-editor-core'; import { MonacoEditorProvider } from '@theia/monaco/lib/browser/monaco-editor-provider'; import { SimpleMonacoEditor } from '@theia/monaco/lib/browser/simple-monaco-editor'; import { ChangeSetActionService } from './change-set-actions/change-set-action-service.js'; import { ContextVariablePicker } from './context-variable-picker.js'; import { ChatInputHistoryService, ChatInputNavigationState } from './chat-input-history.js'; import { ContextFileValidationService, FileValidationResult } from '@theia/ai-chat/lib/browser/context-file-validation-service'; import { PendingImageRegistry } from '@theia/ai-chat/lib/browser/pending-image-registry'; import { ChatCapabilitiesService } from './chat-capabilities-service.js'; import { ChatInputFocusService } from './chat-input-focus-service.js'; import { AvailableGenericCapabilities, GenericCapabilitiesService } from './generic-capabilities-service.js'; import { ServerToolsSection } from './generic-capabilities-tree.js'; import { PreferenceService } from '@theia/core/lib/common/preferences'; type Query = (query: string, mode?: string, capabilityOverrides?: Record, genericCapabilitySelections?: GenericCapabilitySelections, serverToolSelections?: Record) => Promise; type Unpin = () => void; type Cancel = (requestModel: ChatRequestModel) => void; type DeleteChangeSet = (requestModel: ChatRequestModel) => void; type DeleteChangeSetElement = (requestModel: ChatRequestModel, index: number) => void; export declare const AIChatInputConfiguration: unique symbol; export interface AIChatInputConfiguration { showContext?: boolean; showPinnedAgent?: boolean; showChangeSet?: boolean; showSuggestions?: boolean; showCapabilities?: boolean; enablePromptHistory?: boolean; } export declare class AIChatInputWidget extends ReactWidget { static ID: string; static readonly CONTEXT_MENU: string[]; protected readonly editorProvider: MonacoEditorProvider; protected readonly resources: InMemoryResources; protected readonly contextMenuRenderer: ContextMenuRenderer; protected readonly configuration: AIChatInputConfiguration | undefined; protected readonly variableService: FrontendVariableService; protected readonly labelProvider: LabelProvider; protected readonly contextVariablePicker: ContextVariablePicker; protected readonly changeSetActionService: ChangeSetActionService; protected readonly changeSetDecoratorService: ChangeSetDecoratorService; protected readonly openerService: OpenerService; protected readonly chatService: ChatService; protected readonly chatAgentService: ChatAgentService; protected readonly aiActivationService: AIActivationService; protected readonly historyService: ChatInputHistoryService; protected readonly chatRequestParser: ChatRequestParser; protected readonly validationService: ContextFileValidationService | undefined; protected readonly logger: ILogger; protected readonly pendingImageRegistry: PendingImageRegistry; protected readonly capabilitiesService: ChatCapabilitiesService; protected readonly genericCapabilitiesService: GenericCapabilitiesService | undefined; protected fileValidationState: Map; protected readonly contextKeyService: ContextKeyService; protected readonly keybindingRegistry: KeybindingRegistry; protected readonly hoverService: HoverService; protected readonly chatInputFocusService: ChatInputFocusService; protected readonly aiSettingsService: AISettingsService; protected readonly promptService: PromptService; protected readonly languageModelRegistry: FrontendLanguageModelRegistry; protected readonly favoriteModels: FavoriteModelsService; protected readonly aliasRegistry: LanguageModelAliasRegistry; protected readonly preferenceService: PreferenceService | undefined; protected readonly messageService: MessageService; protected readonly commandService: CommandService; protected tokenUsageEnabled: boolean; /** Sessions we have already notified for the current warning cycle (re-armed when usage drops below the threshold). */ protected readonly notifiedSessions: Set; protected navigationState: ChatInputNavigationState; protected editorRef: SimpleMonacoEditor | undefined; protected readonly editorReady: Deferred; get editor(): SimpleMonacoEditor | undefined; get inputConfiguration(): AIChatInputConfiguration | undefined; getPreviousPrompt(currentInput: string): string | undefined; getNextPrompt(): string | undefined; toggleCapabilities(): void; protected getKeybindingHint(commandId: string): string | undefined; protected getCapabilitiesKeybindingHint(): string | undefined; protected getModeKeybindingHint(): string | undefined; cycleMode(): void; protected handleModeChange: (mode: string) => Promise; /** Monotonic token for the latest async {@link updateReasoningSupport} run; older, out-of-order runs discard their results when this changes. */ protected reasoningStateGeneration: number; /** Monotonic token for the latest async {@link updateResolvedDefaultModel} run; older, out-of-order runs discard their results when this changes. */ protected resolvedDefaultGeneration: number; /** Reasoning capability of the model the receiving agent would currently use; undefined hides the selector. */ protected currentReasoningSupport?: ReasoningSupport; /** Id (`provider/model`) of the model that backs {@link currentReasoningSupport}; used to resolve preference defaults. */ protected currentLanguageModelId?: string; /** Context window (max input tokens) of the receiving agent's primary model; falls back to {@link CHAT_CONTEXT_WINDOW_SIZE_FALLBACK} when unknown. */ protected currentMaxInputTokens?: number; /** Saved reasoning selection for the receiving agent (loaded from {@link AISettingsService}); kept in sync with the persisted value. */ protected savedReasoning?: ReasoningSettings; /** Server tools declared by the receiving agent's primary model; undefined/empty hides the server tools category. */ protected currentServerTools?: ServerToolDescriptor[]; /** Vendor of the receiving agent's primary model; used to key server tool selections. */ protected currentModelVendor?: string; protected handleReasoningChange: (level: ReasoningLevel) => Promise; /** * Resolves the reasoning level to display in the selector. Priority: session override → * persisted per-agent selection (from {@link AISettingsService}) → * `ai-features.reasoning.defaults` preference entry matching the current model/agent → * model's declared default → `'off'`. The result is clamped to the model's supported levels, matching * what the frontend language model service sends. */ protected getCurrentReasoningLevel(): ReasoningLevel | undefined; protected resolvePreferenceReasoningLevel(): ReasoningLevel | undefined; protected updateReasoningSupport(agentId: string | undefined): Promise; protected handleCapabilityChange: (fragmentId: string, enabled: boolean) => void; protected handleGenericCapabilityChange: (type: keyof GenericCapabilitySelections, ids: string[]) => void; protected handleResetGenericCapabilities: () => void; protected handleServerToolChange: (ids: string[]) => void; protected updateCapabilitiesForAgent(agentId: string, modeId?: string, preserveOverrides?: boolean): Promise; /** Updates the active chat session's `commonSettings.reasoning`; pass `undefined` to clear. */ /** * Re-reads the persisted per-agent reasoning selection and mirrors it into the session, so a change made * outside this widget (the agent detail's Reasoning row, or its reset) shows up in the selector instead of * only taking effect on the next session. */ protected refreshSavedReasoning(agentId: string | undefined): Promise; /** * Re-reads persisted capability overrides, adopting them only when there are no unsaved local edits. * Always updates the saved baseline so change detection reflects the stored settings. */ protected refreshSavedCapabilityOverrides(agentId: string | undefined): Promise; /** * Re-reads the persisted server tool selections, which the agent detail can change too. Adopts them into * the live selection only while the user has none of their own pending here, so an external change never * discards edits that are waiting to be saved; the baseline is updated either way, so the "unsaved * changes" state stays measured against what is actually stored. */ protected refreshSavedServerTools(agentId: string | undefined): Promise; /** * Re-reads the persisted generic capability selections, which the agent detail can change too, adopting * them the same way {@link refreshSavedServerTools} does. */ protected refreshSavedGenericCapabilities(agentId: string | undefined): Promise; protected applyReasoningToSession(reasoning: ReasoningSettings | undefined): void; /** Language models available for the per-session model selector; refreshed on registry changes. */ protected availableModels: LanguageModel[]; /** Concrete model id the agent default currently resolves to (e.g. what `default/code` points at); falls back to the identifier. */ protected resolvedDefaultLabel?: string; protected loadAvailableModels(): Promise; /** * Resolves the model a new session would use for this agent, honoring the per-agent override * configured in the AI configuration (via {@link AISettingsService}) and following aliases, so * the selector's "Default" reflects the effective, resolved target. */ protected updateResolvedDefaultModel(): Promise; /** The per-session model override id for the active session, if any. */ protected getSessionModelOverride(): string | undefined; /** * Opens the Models page of the AI Configuration view, which is where the models this list shows are * chosen. The target is the id of that view's Models category (`AiConfigurationCategoryId.MODELS`), * passed as a string because this package does not depend on the package that declares it. */ protected openModelConfiguration: () => void; /** Sets (or clears, with `undefined`) the per-session model override for the active session. */ protected handleSessionModelChange: (modelId: string | undefined) => void; /** * The models the selector offers: the favorites, i.e. the newest models of each provider plus * whatever the user starred, and the session's own model even when it is neither. Discovery * registers every release a provider offers, which is a list far too long to pick from here; the * provider's page in the AI Configuration view is where the rest can be browsed and starred. */ protected getSelectableModels(currentModelId: string | undefined): LanguageModel[]; /** Builds the props for the per-session model selector. */ protected getModelSelectorProps(): ModelSelectorWidgetProps; protected updateAvailableGenericCapabilities(): Promise; /** * Extracts capability overrides from the last request in the chat model. * Used to restore user's capability choices when switching sessions or on reload. */ protected getLastCapabilityOverridesFromModel(chatModel: ChatModel): Map; /** * Extracts the mode ID from the last request in the chat model. * Used to restore the user's selected mode when switching sessions or on reload. */ protected getLastModeIdFromModel(chatModel: ChatModel): string | undefined; /** * Extracts generic capability selections from the last request in the chat model. * Used to restore user's selections when switching sessions or on reload. */ protected getLastGenericCapabilitySelectionsFromModel(chatModel: ChatModel): GenericCapabilitySelections; /** * Extracts server tool selections from the last request in the chat model. * Used to restore the user's selections when switching sessions or on reload. */ protected getLastServerToolSelectionsFromModel(chatModel: ChatModel): Record; /** * Builds the server tools section for the capabilities panel, or `undefined` if the current * model declares no server tools. */ protected getServerToolsSection(): ServerToolsSection | undefined; protected getProviderDisplayName(vendor: string): string; /** * Refreshes capabilities for the current receiving agent. * Called when prompt fragments change to ensure capabilities reflect the latest template. */ protected refreshCapabilities(): Promise; /** * Checks if current capability overrides differ from saved settings. */ protected hasCapabilityChangesFromSaved(): boolean; /** * Compares two string arrays for equality (order-independent). */ protected arraysEqualUnordered(a: string[], b: string[]): boolean; /** Returns true if any vendor has at least one selected server tool. */ protected serverToolSelectionsHaveAny(selections: Record): boolean; /** * Checks if current generic capability selections differ from saved settings. */ protected hasGenericCapabilityChangesFromSaved(): boolean; /** * Checks if current server tool selections differ from saved settings (across all vendors). */ protected hasServerToolChangesFromSaved(): boolean; /** * Checks if there are any unsaved changes (capability overrides, generic selections, or server tools). * Reasoning is auto-persisted in {@link handleReasoningChange} and is intentionally excluded. */ hasAnyChangesFromSaved(): boolean; /** * Saves current capability selections to settings. * Reasoning is auto-persisted via {@link handleReasoningChange} and is not part of this flow. */ saveCurrentSelectionsToSettings(): Promise; protected chatInputFocusKey: ContextKey; protected chatInputFirstLineKey: ContextKey; protected chatInputLastLineKey: ContextKey; protected chatInputReceivingAgentKey: ContextKey; protected chatInputHasModesKey: ContextKey; protected capabilitiesOpen: boolean; protected isEnabled: boolean; protected heightInLines: number; protected updateReceivingAgentTimeout: number | undefined; protected forceCapabilitiesRefresh: boolean; protected receivingAgent: { agentId: string; modes: ChatMode[]; currentModeId?: string; } | undefined; /** * Tracks the default enabled state for each capability. * This is initialized from the agent's capabilities and used to display the initial chip state. */ protected capabilityDefaults: ParsedCapability[]; /** * Tracks user's generic capability selections from the dropdowns. */ protected genericCapabilitySelections: GenericCapabilitySelections; /** * Tracks user's server tool selections, keyed by model vendor to keep selections provider-specific. */ protected serverToolSelections: Record; /** * Stores the saved server tool selections loaded from settings, for unsaved-change detection. */ protected savedServerToolSelections: Record | undefined; /** * Available generic capabilities from all sources. */ protected availableGenericCapabilities: AvailableGenericCapabilities; /** * Generic capabilities that are already used in the agent's prompt (should be disabled). */ protected disabledGenericCapabilities: GenericCapabilitySelections; /** * Tracks user's explicit capability overrides for the current chat input session. * Only contains capabilities the user has explicitly changed from their defaults. * These overrides are not persisted but reset when the receiving agent changes or a new chat is started. * Or restored when an existing chat session can provide a previous capability override from the last request. */ protected userCapabilityOverrides: Map; /** * Stores the saved capability overrides loaded from settings. * Used to compare against current selections to detect unsaved changes. */ protected savedCapabilityOverrides: Record | undefined; /** * Stores the saved generic capability selections loaded from settings. * Used to compare against current selections to detect unsaved changes. */ protected savedGenericCapabilitySelections: GenericCapabilitySelections | undefined; protected _branch?: ChatHierarchyBranch; set branch(branch: ChatHierarchyBranch | undefined); protected _onQuery: Query; /** Suppresses capability updates while a query is in flight to prevent race conditions */ protected queryInFlight: boolean; set onQuery(query: Query); protected _onUnpin: Unpin; set onUnpin(unpin: Unpin); protected _onCancel: Cancel; set onCancel(cancel: Cancel); protected _onDeleteChangeSet: DeleteChangeSet; set onDeleteChangeSet(deleteChangeSet: DeleteChangeSet); protected _onDeleteChangeSetElement: DeleteChangeSetElement; set onDeleteChangeSetElement(deleteChangeSetElement: DeleteChangeSetElement); protected _initialValue?: string; set initialValue(value: string | undefined); protected onDisposeForChatModel: DisposableCollection; protected _chatModel: ChatModel; /** * Disposables for pending image registrations, keyed by short ID. * These are cleared after the message is sent. */ protected pendingImageDisposables: Map; set chatModel(chatModel: ChatModel); protected _pinnedAgent: ChatAgent | undefined; set pinnedAgent(pinnedAgent: ChatAgent | undefined); protected onDidResizeEmitter: Emitter; readonly onDidResize: import("@theia/core").Event; protected init(): void; protected initializeContextKeys(): void; updateCursorPositionKeys(): void; protected getContextWindowSize(): number; /** Converts the percentage-based preference to an absolute token count. */ protected getTokenUsageWarningThreshold(): number; protected getTokenUsageWarningThresholdPercentage(): number; protected isTokenUsageWarningEnabled(): boolean; /** * Called after a response changes on the currently attached session. Shows a * warning the first time the total crosses the threshold, and re-arms when * usage drops back below it. */ protected evaluateTokenUsageWarning(chatModel: ChatModel): void; protected showTokenUsageWarning(): Promise; protected scheduleUpdateReceivingAgent(): void; protected updateReceivingAgent(): Promise; /** * Resolves the agent to use for the given parsed request. * If a session is provided, uses session-based logic including pinned agents. * Otherwise, delegates to ChatAgentService. */ protected resolveAgentFromParsedRequest(parsedRequest: ParsedChatRequest, session?: ChatSession): ChatAgent | undefined; /** * Updates the receiving agent state and triggers re-render if the agent changed. */ protected updateAgentState(agent: ChatAgent | undefined): Promise; /** * Syncs the selected mode in the UI with the agent's current default mode. * Called when the default mode changes externally (e.g. via AI Configuration). */ protected syncSelectedModeWithDefault(): void; protected setupEditorEventListeners(): void; protected onActivateRequest(msg: Message): void; protected getResourceUri(): URI; protected render(): React.ReactNode; protected onDragOver(event: React.DragEvent): void; protected onDrop(event: React.DragEvent): void; protected onPaste(event: ClipboardEvent): void; /** * Paste images from the clipboard using the async Clipboard API. * Called from the keybinding contribution when Ctrl+V is pressed in the chat input, * because Electron/Theia's paste command (document.execCommand('paste')) does not * produce a DOM paste event for image clipboard content. * @returns true if images were found and pasted, false otherwise. */ pasteFromClipboard(): Promise; protected processPasteResult(result: { variables: AIVariableResolutionRequest[]; text?: string; }): void; protected clipboardDataHasImages(clipboardData: DataTransfer | null): boolean; protected onEscape(): void; protected openContextElement(request: AIVariableResolutionRequest): Promise; setEnabled(enabled: boolean): void; protected addContextElement(): void; protected handleContextMenu(event: IMouseEvent): void; addContext(variable: AIVariableResolutionRequest): void; /** * Get the scope URI used for registering pending images. * Uses the chat model ID for scoping, not the editor URI. */ protected getScopeUri(): string; /** * Register a pending image attachment with a short ID. * @returns The short ID that can be used in the text. */ registerPendingImage(variable: AIVariableResolutionRequest): string; /** * Clear all pending image attachments. Called after a message is sent. */ clearPendingImageAttachments(): void; /** * Get a meaningful base name for an image variable. * For dropped files (with wsRelativePath), use the workspace-relative path (like file variables). * For pasted images, use "pasted_image". */ protected getImageBaseName(imageVariable: ImageContextVariable): string; /** * Get all variables to be sent with the request. * Note: Image variables in text use short IDs that get resolved via the pending image registry. */ getAllVariablesForRequest(): AIVariableResolutionRequest[]; protected getContext(): readonly AIVariableResolutionRequest[]; /** * Delete a context element by index. */ protected deleteContextElement(index: number): void; } /** Props for the per-session language model selector. */ interface ModelSelectorWidgetProps { show: boolean; /** Models available to switch to. */ models: LanguageModel[]; /** The session's current model override id, if any (undefined = use the agent default). */ currentModelId?: string; /** Human-readable label of the model/alias new sessions use by default. */ defaultLabel: string; /** Set the session override (or clear it with `undefined`). */ onModelChange: (modelId: string | undefined) => void; /** Opens the page that decides which models this list shows. */ onConfigure: () => void; } /** * Aligns the input editor with the enabled state of the widget. A disabled editor neither accepts text nor focus: * it is read-only, removed from the tab order, and gives up the focus it may still hold from before being disabled. * Should an edit still be attempted, Monaco reports why the input is disabled instead of its generic read-only wording. */ export declare const applyEditorEnabledState: (editor: SimpleMonacoEditor | undefined, isEnabled: boolean | undefined) => void; export {}; //# sourceMappingURL=chat-input-widget.d.ts.map