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