agent.rs

  1mod active_thread;
  2mod agent_configuration;
  3mod agent_diff;
  4mod agent_model_selector;
  5mod agent_panel;
  6mod buffer_codegen;
  7mod context;
  8mod context_picker;
  9mod context_server_configuration;
 10mod context_server_tool;
 11mod context_store;
 12mod context_strip;
 13mod debug;
 14mod history_store;
 15mod inline_assistant;
 16mod inline_prompt_editor;
 17mod message_editor;
 18mod profile_selector;
 19mod slash_command_settings;
 20mod terminal_codegen;
 21mod terminal_inline_assistant;
 22mod thread;
 23mod thread_history;
 24mod thread_store;
 25mod tool_compatibility;
 26mod tool_use;
 27mod ui;
 28
 29use std::sync::Arc;
 30
 31use assistant_settings::{AgentProfileId, AssistantSettings, LanguageModelSelection};
 32use assistant_slash_command::SlashCommandRegistry;
 33use client::Client;
 34use feature_flags::FeatureFlagAppExt as _;
 35use fs::Fs;
 36use gpui::{App, actions, impl_actions};
 37use language::LanguageRegistry;
 38use language_model::{LanguageModelId, LanguageModelProviderId, LanguageModelRegistry};
 39use prompt_store::PromptBuilder;
 40use schemars::JsonSchema;
 41use serde::Deserialize;
 42use settings::{Settings as _, SettingsStore};
 43use thread::ThreadId;
 44
 45pub use crate::active_thread::ActiveThread;
 46use crate::agent_configuration::{AddContextServerModal, ManageProfilesModal};
 47pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
 48pub use crate::context::{ContextLoadResult, LoadedContext};
 49pub use crate::inline_assistant::InlineAssistant;
 50use crate::slash_command_settings::SlashCommandSettings;
 51pub use crate::thread::{Message, MessageSegment, Thread, ThreadEvent};
 52pub use crate::thread_store::{SerializedThread, TextThreadStore, ThreadStore};
 53pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 54pub use context_store::ContextStore;
 55pub use ui::preview::{all_agent_previews, get_agent_preview};
 56
 57actions!(
 58    agent,
 59    [
 60        NewTextThread,
 61        ToggleContextPicker,
 62        ToggleNavigationMenu,
 63        ToggleOptionsMenu,
 64        DeleteRecentlyOpenThread,
 65        ToggleProfileSelector,
 66        RemoveAllContext,
 67        ExpandMessageEditor,
 68        OpenHistory,
 69        AddContextServer,
 70        RemoveSelectedThread,
 71        Chat,
 72        ChatWithFollow,
 73        CycleNextInlineAssist,
 74        CyclePreviousInlineAssist,
 75        FocusUp,
 76        FocusDown,
 77        FocusLeft,
 78        FocusRight,
 79        RemoveFocusedContext,
 80        AcceptSuggestedContext,
 81        OpenActiveThreadAsMarkdown,
 82        OpenAgentDiff,
 83        Keep,
 84        Reject,
 85        RejectAll,
 86        KeepAll,
 87        Follow,
 88        ResetTrialUpsell,
 89        ResetTrialEndUpsell,
 90    ]
 91);
 92
 93#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema)]
 94pub struct NewThread {
 95    #[serde(default)]
 96    from_thread_id: Option<ThreadId>,
 97}
 98
 99#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema)]
100pub struct ManageProfiles {
101    #[serde(default)]
102    pub customize_tools: Option<AgentProfileId>,
103}
104
105impl ManageProfiles {
106    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
107        Self {
108            customize_tools: Some(profile_id),
109        }
110    }
111}
112
113impl_actions!(agent, [NewThread, ManageProfiles]);
114
115/// Initializes the `agent` crate.
116pub fn init(
117    fs: Arc<dyn Fs>,
118    client: Arc<Client>,
119    prompt_builder: Arc<PromptBuilder>,
120    language_registry: Arc<LanguageRegistry>,
121    is_eval: bool,
122    cx: &mut App,
123) {
124    AssistantSettings::register(cx);
125    SlashCommandSettings::register(cx);
126
127    assistant_context_editor::init(client.clone(), cx);
128    rules_library::init(cx);
129    if !is_eval {
130        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
131        // we're not running inside of the eval.
132        init_language_model_settings(cx);
133    }
134    assistant_slash_command::init(cx);
135    thread_store::init(cx);
136    agent_panel::init(cx);
137    context_server_configuration::init(language_registry, cx);
138
139    register_slash_commands(cx);
140    inline_assistant::init(
141        fs.clone(),
142        prompt_builder.clone(),
143        client.telemetry().clone(),
144        cx,
145    );
146    terminal_inline_assistant::init(
147        fs.clone(),
148        prompt_builder.clone(),
149        client.telemetry().clone(),
150        cx,
151    );
152    indexed_docs::init(cx);
153    cx.observe_new(AddContextServerModal::register).detach();
154    cx.observe_new(ManageProfilesModal::register).detach();
155}
156
157fn init_language_model_settings(cx: &mut App) {
158    update_active_language_model_from_settings(cx);
159
160    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
161        .detach();
162    cx.subscribe(
163        &LanguageModelRegistry::global(cx),
164        |_, event: &language_model::Event, cx| match event {
165            language_model::Event::ProviderStateChanged
166            | language_model::Event::AddedProvider(_)
167            | language_model::Event::RemovedProvider(_) => {
168                update_active_language_model_from_settings(cx);
169            }
170            _ => {}
171        },
172    )
173    .detach();
174}
175
176fn update_active_language_model_from_settings(cx: &mut App) {
177    let settings = AssistantSettings::get_global(cx);
178
179    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
180        language_model::SelectedModel {
181            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
182            model: LanguageModelId::from(selection.model.clone()),
183        }
184    }
185
186    let default = to_selected_model(&settings.default_model);
187    let inline_assistant = settings
188        .inline_assistant_model
189        .as_ref()
190        .map(to_selected_model);
191    let commit_message = settings
192        .commit_message_model
193        .as_ref()
194        .map(to_selected_model);
195    let thread_summary = settings
196        .thread_summary_model
197        .as_ref()
198        .map(to_selected_model);
199    let inline_alternatives = settings
200        .inline_alternatives
201        .iter()
202        .map(to_selected_model)
203        .collect::<Vec<_>>();
204
205    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
206        registry.select_default_model(Some(&default), cx);
207        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
208        registry.select_commit_message_model(commit_message.as_ref(), cx);
209        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
210        registry.select_inline_alternative_models(inline_alternatives, cx);
211    });
212}
213
214fn register_slash_commands(cx: &mut App) {
215    let slash_command_registry = SlashCommandRegistry::global(cx);
216
217    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
218    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
219    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
220    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
221    slash_command_registry
222        .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
223    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
224    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
225    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
226    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
227    slash_command_registry
228        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
229    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
230
231    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
232        let slash_command_registry = slash_command_registry.clone();
233        move |is_enabled, _cx| {
234            if is_enabled {
235                slash_command_registry.register_command(
236                    assistant_slash_commands::StreamingExampleSlashCommand,
237                    false,
238                );
239            }
240        }
241    })
242    .detach();
243
244    update_slash_commands_from_settings(cx);
245    cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
246        .detach();
247}
248
249fn update_slash_commands_from_settings(cx: &mut App) {
250    let slash_command_registry = SlashCommandRegistry::global(cx);
251    let settings = SlashCommandSettings::get_global(cx);
252
253    if settings.docs.enabled {
254        slash_command_registry.register_command(assistant_slash_commands::DocsSlashCommand, true);
255    } else {
256        slash_command_registry.unregister_command(assistant_slash_commands::DocsSlashCommand);
257    }
258
259    if settings.cargo_workspace.enabled {
260        slash_command_registry
261            .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
262    } else {
263        slash_command_registry
264            .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
265    }
266}