1mod acp;
  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_store;
 11mod context_strip;
 12mod inline_assistant;
 13mod inline_prompt_editor;
 14mod language_model_selector;
 15mod message_editor;
 16mod profile_selector;
 17mod slash_command;
 18mod slash_command_picker;
 19mod terminal_codegen;
 20mod terminal_inline_assistant;
 21mod text_thread_editor;
 22mod ui;
 23
 24use std::rc::Rc;
 25use std::sync::Arc;
 26
 27use agent_settings::{AgentProfileId, AgentSettings};
 28use assistant_slash_command::SlashCommandRegistry;
 29use client::Client;
 30use command_palette_hooks::CommandPaletteFilter;
 31use feature_flags::FeatureFlagAppExt as _;
 32use fs::Fs;
 33use gpui::{Action, App, Entity, SharedString, actions};
 34use language::LanguageRegistry;
 35use language_model::{
 36    ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 37};
 38use project::DisableAiSettings;
 39use project::agent_server_store::AgentServerCommand;
 40use prompt_store::PromptBuilder;
 41use schemars::JsonSchema;
 42use serde::{Deserialize, Serialize};
 43use settings::{LanguageModelSelection, Settings as _, SettingsStore};
 44use std::any::TypeId;
 45
 46use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 47pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
 48pub use crate::inline_assistant::InlineAssistant;
 49pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 50pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
 51use zed_actions;
 52
 53actions!(
 54    agent,
 55    [
 56        /// Creates a new text-based conversation thread.
 57        NewTextThread,
 58        /// Toggles the context picker interface for adding files, symbols, or other context.
 59        ToggleContextPicker,
 60        /// Toggles the menu to create new agent threads.
 61        ToggleNewThreadMenu,
 62        /// Toggles the navigation menu for switching between threads and views.
 63        ToggleNavigationMenu,
 64        /// Toggles the options menu for agent settings and preferences.
 65        ToggleOptionsMenu,
 66        /// Deletes the recently opened thread from history.
 67        DeleteRecentlyOpenThread,
 68        /// Toggles the profile or mode selector for switching between agent profiles.
 69        ToggleProfileSelector,
 70        /// Cycles through available session modes.
 71        CycleModeSelector,
 72        /// Removes all added context from the current conversation.
 73        RemoveAllContext,
 74        /// Expands the message editor to full size.
 75        ExpandMessageEditor,
 76        /// Opens the conversation history view.
 77        OpenHistory,
 78        /// Adds a context server to the configuration.
 79        AddContextServer,
 80        /// Removes the currently selected thread.
 81        RemoveSelectedThread,
 82        /// Starts a chat conversation with follow-up enabled.
 83        ChatWithFollow,
 84        /// Cycles to the next inline assist suggestion.
 85        CycleNextInlineAssist,
 86        /// Cycles to the previous inline assist suggestion.
 87        CyclePreviousInlineAssist,
 88        /// Moves focus up in the interface.
 89        FocusUp,
 90        /// Moves focus down in the interface.
 91        FocusDown,
 92        /// Moves focus left in the interface.
 93        FocusLeft,
 94        /// Moves focus right in the interface.
 95        FocusRight,
 96        /// Removes the currently focused context item.
 97        RemoveFocusedContext,
 98        /// Accepts the suggested context item.
 99        AcceptSuggestedContext,
100        /// Opens the active thread as a markdown file.
101        OpenActiveThreadAsMarkdown,
102        /// Opens the agent diff view to review changes.
103        OpenAgentDiff,
104        /// Keeps the current suggestion or change.
105        Keep,
106        /// Rejects the current suggestion or change.
107        Reject,
108        /// Rejects all suggestions or changes.
109        RejectAll,
110        /// Keeps all suggestions or changes.
111        KeepAll,
112        /// Allow this operation only this time.
113        AllowOnce,
114        /// Allow this operation and remember the choice.
115        AllowAlways,
116        /// Reject this operation only this time.
117        RejectOnce,
118        /// Follows the agent's suggestions.
119        Follow,
120        /// Resets the trial upsell notification.
121        ResetTrialUpsell,
122        /// Resets the trial end upsell notification.
123        ResetTrialEndUpsell,
124        /// Continues the current thread.
125        ContinueThread,
126        /// Continues the thread with burn mode enabled.
127        ContinueWithBurnMode,
128        /// Toggles burn mode for faster responses.
129        ToggleBurnMode,
130    ]
131);
132
133#[derive(Clone, Copy, Debug, PartialEq, Eq, Action)]
134#[action(namespace = agent)]
135#[action(deprecated_aliases = ["assistant::QuoteSelection"])]
136/// Quotes the current selection in the agent panel's message editor.
137pub struct QuoteSelection;
138
139/// Creates a new conversation thread, optionally based on an existing thread.
140#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
141#[action(namespace = agent)]
142#[serde(deny_unknown_fields)]
143pub struct NewThread;
144
145/// Creates a new external agent conversation thread.
146#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
147#[action(namespace = agent)]
148#[serde(deny_unknown_fields)]
149pub struct NewExternalAgentThread {
150    /// Which agent to use for the conversation.
151    agent: Option<ExternalAgent>,
152}
153
154#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
155#[action(namespace = agent)]
156#[serde(deny_unknown_fields)]
157pub struct NewNativeAgentThreadFromSummary {
158    from_session_id: agent_client_protocol::SessionId,
159}
160
161// TODO unify this with AgentType
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
163#[serde(rename_all = "snake_case")]
164pub enum ExternalAgent {
165    Gemini,
166    ClaudeCode,
167    Codex,
168    NativeAgent,
169    Custom {
170        name: SharedString,
171        command: AgentServerCommand,
172    },
173}
174
175fn placeholder_command() -> AgentServerCommand {
176    AgentServerCommand {
177        path: "/placeholder".into(),
178        args: vec![],
179        env: None,
180    }
181}
182
183impl ExternalAgent {
184    pub fn parse_built_in(server: &dyn agent_servers::AgentServer) -> Option<Self> {
185        match server.telemetry_id() {
186            "gemini-cli" => Some(Self::Gemini),
187            "claude-code" => Some(Self::ClaudeCode),
188            "codex" => Some(Self::Codex),
189            "zed" => Some(Self::NativeAgent),
190            _ => None,
191        }
192    }
193
194    pub fn server(
195        &self,
196        fs: Arc<dyn fs::Fs>,
197        history: Entity<agent::HistoryStore>,
198    ) -> Rc<dyn agent_servers::AgentServer> {
199        match self {
200            Self::Gemini => Rc::new(agent_servers::Gemini),
201            Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
202            Self::Codex => Rc::new(agent_servers::Codex),
203            Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, history)),
204            Self::Custom { name, command: _ } => {
205                Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
206            }
207        }
208    }
209}
210
211/// Opens the profile management interface for configuring agent tools and settings.
212#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
213#[action(namespace = agent)]
214#[serde(deny_unknown_fields)]
215pub struct ManageProfiles {
216    #[serde(default)]
217    pub customize_tools: Option<AgentProfileId>,
218}
219
220impl ManageProfiles {
221    pub const fn customize_tools(profile_id: AgentProfileId) -> Self {
222        Self {
223            customize_tools: Some(profile_id),
224        }
225    }
226}
227
228#[derive(Clone)]
229pub(crate) enum ModelUsageContext {
230    InlineAssistant,
231}
232
233impl ModelUsageContext {
234    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
235        match self {
236            Self::InlineAssistant => {
237                LanguageModelRegistry::read_global(cx).inline_assistant_model()
238            }
239        }
240    }
241
242    pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
243        self.configured_model(cx)
244            .map(|configured_model| configured_model.model)
245    }
246}
247
248/// Initializes the `agent` crate.
249pub fn init(
250    fs: Arc<dyn Fs>,
251    client: Arc<Client>,
252    prompt_builder: Arc<PromptBuilder>,
253    language_registry: Arc<LanguageRegistry>,
254    is_eval: bool,
255    cx: &mut App,
256) {
257    AgentSettings::register(cx);
258
259    assistant_context::init(client.clone(), cx);
260    rules_library::init(cx);
261    if !is_eval {
262        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
263        // we're not running inside of the eval.
264        init_language_model_settings(cx);
265    }
266    assistant_slash_command::init(cx);
267    agent_panel::init(cx);
268    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
269    TextThreadEditor::init(cx);
270
271    register_slash_commands(cx);
272    inline_assistant::init(
273        fs.clone(),
274        prompt_builder.clone(),
275        client.telemetry().clone(),
276        cx,
277    );
278    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
279    cx.observe_new(move |workspace, window, cx| {
280        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
281    })
282    .detach();
283    cx.observe_new(ManageProfilesModal::register).detach();
284
285    // Update command palette filter based on AI settings
286    update_command_palette_filter(cx);
287
288    // Watch for settings changes
289    cx.observe_global::<SettingsStore>(|app_cx| {
290        // When settings change, update the command palette filter
291        update_command_palette_filter(app_cx);
292    })
293    .detach();
294}
295
296fn update_command_palette_filter(cx: &mut App) {
297    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
298    CommandPaletteFilter::update_global(cx, |filter, _| {
299        if disable_ai {
300            filter.hide_namespace("agent");
301            filter.hide_namespace("assistant");
302            filter.hide_namespace("copilot");
303            filter.hide_namespace("supermaven");
304            filter.hide_namespace("zed_predict_onboarding");
305            filter.hide_namespace("edit_prediction");
306
307            use editor::actions::{
308                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
309                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
310            };
311            let edit_prediction_actions = [
312                TypeId::of::<AcceptEditPrediction>(),
313                TypeId::of::<AcceptPartialEditPrediction>(),
314                TypeId::of::<ShowEditPrediction>(),
315                TypeId::of::<NextEditPrediction>(),
316                TypeId::of::<PreviousEditPrediction>(),
317                TypeId::of::<ToggleEditPrediction>(),
318            ];
319            filter.hide_action_types(&edit_prediction_actions);
320            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
321        } else {
322            filter.show_namespace("agent");
323            filter.show_namespace("assistant");
324            filter.show_namespace("copilot");
325            filter.show_namespace("zed_predict_onboarding");
326
327            filter.show_namespace("edit_prediction");
328
329            use editor::actions::{
330                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
331                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
332            };
333            let edit_prediction_actions = [
334                TypeId::of::<AcceptEditPrediction>(),
335                TypeId::of::<AcceptPartialEditPrediction>(),
336                TypeId::of::<ShowEditPrediction>(),
337                TypeId::of::<NextEditPrediction>(),
338                TypeId::of::<PreviousEditPrediction>(),
339                TypeId::of::<ToggleEditPrediction>(),
340            ];
341            filter.show_action_types(edit_prediction_actions.iter());
342
343            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
344        }
345    });
346}
347
348fn init_language_model_settings(cx: &mut App) {
349    update_active_language_model_from_settings(cx);
350
351    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
352        .detach();
353    cx.subscribe(
354        &LanguageModelRegistry::global(cx),
355        |_, event: &language_model::Event, cx| match event {
356            language_model::Event::ProviderStateChanged(_)
357            | language_model::Event::AddedProvider(_)
358            | language_model::Event::RemovedProvider(_) => {
359                update_active_language_model_from_settings(cx);
360            }
361            _ => {}
362        },
363    )
364    .detach();
365}
366
367fn update_active_language_model_from_settings(cx: &mut App) {
368    let settings = AgentSettings::get_global(cx);
369
370    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
371        language_model::SelectedModel {
372            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
373            model: LanguageModelId::from(selection.model.clone()),
374        }
375    }
376
377    let default = settings.default_model.as_ref().map(to_selected_model);
378    let inline_assistant = settings
379        .inline_assistant_model
380        .as_ref()
381        .map(to_selected_model);
382    let commit_message = settings
383        .commit_message_model
384        .as_ref()
385        .map(to_selected_model);
386    let thread_summary = settings
387        .thread_summary_model
388        .as_ref()
389        .map(to_selected_model);
390    let inline_alternatives = settings
391        .inline_alternatives
392        .iter()
393        .map(to_selected_model)
394        .collect::<Vec<_>>();
395
396    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
397        registry.select_default_model(default.as_ref(), cx);
398        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
399        registry.select_commit_message_model(commit_message.as_ref(), cx);
400        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
401        registry.select_inline_alternative_models(inline_alternatives, cx);
402    });
403}
404
405fn register_slash_commands(cx: &mut App) {
406    let slash_command_registry = SlashCommandRegistry::global(cx);
407
408    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
409    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
410    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
411    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
412    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
413    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
414    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
415    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
416    slash_command_registry
417        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
418    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
419
420    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
421        move |is_enabled, _cx| {
422            if is_enabled {
423                slash_command_registry.register_command(
424                    assistant_slash_commands::StreamingExampleSlashCommand,
425                    false,
426                );
427            }
428        }
429    })
430    .detach();
431}