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