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/// Creates a new conversation thread, optionally based on an existing thread.
134#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
135#[action(namespace = agent)]
136#[serde(deny_unknown_fields)]
137pub struct NewThread;
138
139/// Creates a new external agent conversation thread.
140#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
141#[action(namespace = agent)]
142#[serde(deny_unknown_fields)]
143pub struct NewExternalAgentThread {
144    /// Which agent to use for the conversation.
145    agent: Option<ExternalAgent>,
146}
147
148#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
149#[action(namespace = agent)]
150#[serde(deny_unknown_fields)]
151pub struct NewNativeAgentThreadFromSummary {
152    from_session_id: agent_client_protocol::SessionId,
153}
154
155// TODO unify this with AgentType
156#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
157#[serde(rename_all = "snake_case")]
158pub enum ExternalAgent {
159    Gemini,
160    ClaudeCode,
161    Codex,
162    NativeAgent,
163    Custom {
164        name: SharedString,
165        command: AgentServerCommand,
166    },
167}
168
169fn placeholder_command() -> AgentServerCommand {
170    AgentServerCommand {
171        path: "/placeholder".into(),
172        args: vec![],
173        env: None,
174    }
175}
176
177impl ExternalAgent {
178    pub fn parse_built_in(server: &dyn agent_servers::AgentServer) -> Option<Self> {
179        match server.telemetry_id() {
180            "gemini-cli" => Some(Self::Gemini),
181            "claude-code" => Some(Self::ClaudeCode),
182            "codex" => Some(Self::Codex),
183            "zed" => Some(Self::NativeAgent),
184            _ => None,
185        }
186    }
187
188    pub fn server(
189        &self,
190        fs: Arc<dyn fs::Fs>,
191        history: Entity<agent::HistoryStore>,
192    ) -> Rc<dyn agent_servers::AgentServer> {
193        match self {
194            Self::Gemini => Rc::new(agent_servers::Gemini),
195            Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
196            Self::Codex => Rc::new(agent_servers::Codex),
197            Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, history)),
198            Self::Custom { name, command: _ } => {
199                Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
200            }
201        }
202    }
203}
204
205/// Opens the profile management interface for configuring agent tools and settings.
206#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
207#[action(namespace = agent)]
208#[serde(deny_unknown_fields)]
209pub struct ManageProfiles {
210    #[serde(default)]
211    pub customize_tools: Option<AgentProfileId>,
212}
213
214impl ManageProfiles {
215    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
216        Self {
217            customize_tools: Some(profile_id),
218        }
219    }
220}
221
222#[derive(Clone)]
223pub(crate) enum ModelUsageContext {
224    InlineAssistant,
225}
226
227impl ModelUsageContext {
228    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
229        match self {
230            Self::InlineAssistant => {
231                LanguageModelRegistry::read_global(cx).inline_assistant_model()
232            }
233        }
234    }
235
236    pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
237        self.configured_model(cx)
238            .map(|configured_model| configured_model.model)
239    }
240}
241
242/// Initializes the `agent` crate.
243pub fn init(
244    fs: Arc<dyn Fs>,
245    client: Arc<Client>,
246    prompt_builder: Arc<PromptBuilder>,
247    language_registry: Arc<LanguageRegistry>,
248    is_eval: bool,
249    cx: &mut App,
250) {
251    AgentSettings::register(cx);
252
253    assistant_text_thread::init(client.clone(), cx);
254    rules_library::init(cx);
255    if !is_eval {
256        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
257        // we're not running inside of the eval.
258        init_language_model_settings(cx);
259    }
260    assistant_slash_command::init(cx);
261    agent_panel::init(cx);
262    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
263    TextThreadEditor::init(cx);
264
265    register_slash_commands(cx);
266    inline_assistant::init(
267        fs.clone(),
268        prompt_builder.clone(),
269        client.telemetry().clone(),
270        cx,
271    );
272    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
273    cx.observe_new(move |workspace, window, cx| {
274        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
275    })
276    .detach();
277    cx.observe_new(ManageProfilesModal::register).detach();
278
279    // Update command palette filter based on AI settings
280    update_command_palette_filter(cx);
281
282    // Watch for settings changes
283    cx.observe_global::<SettingsStore>(|app_cx| {
284        // When settings change, update the command palette filter
285        update_command_palette_filter(app_cx);
286    })
287    .detach();
288}
289
290fn update_command_palette_filter(cx: &mut App) {
291    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
292    CommandPaletteFilter::update_global(cx, |filter, _| {
293        if disable_ai {
294            filter.hide_namespace("agent");
295            filter.hide_namespace("assistant");
296            filter.hide_namespace("copilot");
297            filter.hide_namespace("supermaven");
298            filter.hide_namespace("zed_predict_onboarding");
299            filter.hide_namespace("edit_prediction");
300
301            use editor::actions::{
302                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
303                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
304            };
305            let edit_prediction_actions = [
306                TypeId::of::<AcceptEditPrediction>(),
307                TypeId::of::<AcceptPartialEditPrediction>(),
308                TypeId::of::<ShowEditPrediction>(),
309                TypeId::of::<NextEditPrediction>(),
310                TypeId::of::<PreviousEditPrediction>(),
311                TypeId::of::<ToggleEditPrediction>(),
312            ];
313            filter.hide_action_types(&edit_prediction_actions);
314            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
315        } else {
316            filter.show_namespace("agent");
317            filter.show_namespace("assistant");
318            filter.show_namespace("copilot");
319            filter.show_namespace("zed_predict_onboarding");
320
321            filter.show_namespace("edit_prediction");
322
323            use editor::actions::{
324                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
325                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
326            };
327            let edit_prediction_actions = [
328                TypeId::of::<AcceptEditPrediction>(),
329                TypeId::of::<AcceptPartialEditPrediction>(),
330                TypeId::of::<ShowEditPrediction>(),
331                TypeId::of::<NextEditPrediction>(),
332                TypeId::of::<PreviousEditPrediction>(),
333                TypeId::of::<ToggleEditPrediction>(),
334            ];
335            filter.show_action_types(edit_prediction_actions.iter());
336
337            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
338        }
339    });
340}
341
342fn init_language_model_settings(cx: &mut App) {
343    update_active_language_model_from_settings(cx);
344
345    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
346        .detach();
347    cx.subscribe(
348        &LanguageModelRegistry::global(cx),
349        |_, event: &language_model::Event, cx| match event {
350            language_model::Event::ProviderStateChanged(_)
351            | language_model::Event::AddedProvider(_)
352            | language_model::Event::RemovedProvider(_) => {
353                update_active_language_model_from_settings(cx);
354            }
355            _ => {}
356        },
357    )
358    .detach();
359}
360
361fn update_active_language_model_from_settings(cx: &mut App) {
362    let settings = AgentSettings::get_global(cx);
363
364    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
365        language_model::SelectedModel {
366            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
367            model: LanguageModelId::from(selection.model.clone()),
368        }
369    }
370
371    let default = settings.default_model.as_ref().map(to_selected_model);
372    let inline_assistant = settings
373        .inline_assistant_model
374        .as_ref()
375        .map(to_selected_model);
376    let commit_message = settings
377        .commit_message_model
378        .as_ref()
379        .map(to_selected_model);
380    let thread_summary = settings
381        .thread_summary_model
382        .as_ref()
383        .map(to_selected_model);
384    let inline_alternatives = settings
385        .inline_alternatives
386        .iter()
387        .map(to_selected_model)
388        .collect::<Vec<_>>();
389
390    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
391        registry.select_default_model(default.as_ref(), cx);
392        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
393        registry.select_commit_message_model(commit_message.as_ref(), cx);
394        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
395        registry.select_inline_alternative_models(inline_alternatives, cx);
396    });
397}
398
399fn register_slash_commands(cx: &mut App) {
400    let slash_command_registry = SlashCommandRegistry::global(cx);
401
402    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
403    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
404    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
405    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
406    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
407    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
408    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
409    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
410    slash_command_registry
411        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
412    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
413
414    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
415        move |is_enabled, _cx| {
416            if is_enabled {
417                slash_command_registry.register_command(
418                    assistant_slash_commands::StreamingExampleSlashCommand,
419                    false,
420                );
421            }
422        }
423    })
424    .detach();
425}