1#![cfg_attr(target_os = "windows", allow(unused, dead_code))]
2
3pub mod assistant_panel;
4pub mod assistant_settings;
5mod context;
6pub mod context_store;
7mod inline_assistant;
8mod patch;
9mod prompt_library;
10mod prompts;
11mod slash_command;
12pub(crate) mod slash_command_picker;
13pub mod slash_command_settings;
14mod slash_command_working_set;
15mod streaming_diff;
16mod terminal_inline_assistant;
17
18use crate::slash_command::project_command::ProjectSlashCommandFeatureFlag;
19pub use crate::slash_command_working_set::{SlashCommandId, SlashCommandWorkingSet};
20pub use assistant_panel::{AssistantPanel, AssistantPanelEvent};
21use assistant_settings::AssistantSettings;
22use assistant_slash_command::SlashCommandRegistry;
23use client::{proto, Client};
24use command_palette_hooks::CommandPaletteFilter;
25pub use context::*;
26pub use context_store::*;
27use feature_flags::FeatureFlagAppExt;
28use fs::Fs;
29use gpui::impl_actions;
30use gpui::{actions, AppContext, Global, SharedString, UpdateGlobal};
31pub(crate) use inline_assistant::*;
32use language_model::{
33 LanguageModelId, LanguageModelProviderId, LanguageModelRegistry, LanguageModelResponseMessage,
34};
35pub use patch::*;
36pub use prompts::PromptBuilder;
37use prompts::PromptLoadingParams;
38use semantic_index::{CloudEmbeddingProvider, SemanticDb};
39use serde::{Deserialize, Serialize};
40use settings::{Settings, SettingsStore};
41use slash_command::search_command::SearchSlashCommandFeatureFlag;
42use slash_command::{
43 auto_command, cargo_workspace_command, default_command, delta_command, diagnostics_command,
44 docs_command, fetch_command, file_command, now_command, project_command, prompt_command,
45 search_command, selection_command, symbols_command, tab_command, terminal_command,
46};
47use std::path::PathBuf;
48use std::sync::Arc;
49pub(crate) use streaming_diff::*;
50use util::ResultExt;
51
52use crate::slash_command::streaming_example_command;
53use crate::slash_command_settings::SlashCommandSettings;
54
55actions!(
56 assistant,
57 [
58 Assist,
59 Edit,
60 Split,
61 CopyCode,
62 CycleMessageRole,
63 QuoteSelection,
64 InsertIntoEditor,
65 ToggleFocus,
66 InsertActivePrompt,
67 DeployHistory,
68 DeployPromptLibrary,
69 ConfirmCommand,
70 NewContext,
71 ToggleModelSelector,
72 CycleNextInlineAssist,
73 CyclePreviousInlineAssist
74 ]
75);
76
77#[derive(PartialEq, Clone, Deserialize)]
78pub enum InsertDraggedFiles {
79 ProjectPaths(Vec<PathBuf>),
80 ExternalFiles(Vec<PathBuf>),
81}
82
83impl_actions!(assistant, [InsertDraggedFiles]);
84
85const DEFAULT_CONTEXT_LINES: usize = 50;
86
87#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
88pub struct MessageId(clock::Lamport);
89
90impl MessageId {
91 pub fn as_u64(self) -> u64 {
92 self.0.as_u64()
93 }
94}
95
96#[derive(Deserialize, Debug)]
97pub struct LanguageModelUsage {
98 pub prompt_tokens: u32,
99 pub completion_tokens: u32,
100 pub total_tokens: u32,
101}
102
103#[derive(Deserialize, Debug)]
104pub struct LanguageModelChoiceDelta {
105 pub index: u32,
106 pub delta: LanguageModelResponseMessage,
107 pub finish_reason: Option<String>,
108}
109
110#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
111pub enum MessageStatus {
112 Pending,
113 Done,
114 Error(SharedString),
115 Canceled,
116}
117
118impl MessageStatus {
119 pub fn from_proto(status: proto::ContextMessageStatus) -> MessageStatus {
120 match status.variant {
121 Some(proto::context_message_status::Variant::Pending(_)) => MessageStatus::Pending,
122 Some(proto::context_message_status::Variant::Done(_)) => MessageStatus::Done,
123 Some(proto::context_message_status::Variant::Error(error)) => {
124 MessageStatus::Error(error.message.into())
125 }
126 Some(proto::context_message_status::Variant::Canceled(_)) => MessageStatus::Canceled,
127 None => MessageStatus::Pending,
128 }
129 }
130
131 pub fn to_proto(&self) -> proto::ContextMessageStatus {
132 match self {
133 MessageStatus::Pending => proto::ContextMessageStatus {
134 variant: Some(proto::context_message_status::Variant::Pending(
135 proto::context_message_status::Pending {},
136 )),
137 },
138 MessageStatus::Done => proto::ContextMessageStatus {
139 variant: Some(proto::context_message_status::Variant::Done(
140 proto::context_message_status::Done {},
141 )),
142 },
143 MessageStatus::Error(message) => proto::ContextMessageStatus {
144 variant: Some(proto::context_message_status::Variant::Error(
145 proto::context_message_status::Error {
146 message: message.to_string(),
147 },
148 )),
149 },
150 MessageStatus::Canceled => proto::ContextMessageStatus {
151 variant: Some(proto::context_message_status::Variant::Canceled(
152 proto::context_message_status::Canceled {},
153 )),
154 },
155 }
156 }
157}
158
159/// The state pertaining to the Assistant.
160#[derive(Default)]
161struct Assistant {
162 /// Whether the Assistant is enabled.
163 enabled: bool,
164}
165
166impl Global for Assistant {}
167
168impl Assistant {
169 const NAMESPACE: &'static str = "assistant";
170
171 fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
172 if self.enabled == enabled {
173 return;
174 }
175
176 self.enabled = enabled;
177
178 if !enabled {
179 CommandPaletteFilter::update_global(cx, |filter, _cx| {
180 filter.hide_namespace(Self::NAMESPACE);
181 });
182
183 return;
184 }
185
186 CommandPaletteFilter::update_global(cx, |filter, _cx| {
187 filter.show_namespace(Self::NAMESPACE);
188 });
189 }
190}
191
192pub fn init(
193 fs: Arc<dyn Fs>,
194 client: Arc<Client>,
195 stdout_is_a_pty: bool,
196 cx: &mut AppContext,
197) -> Arc<PromptBuilder> {
198 cx.set_global(Assistant::default());
199 AssistantSettings::register(cx);
200 SlashCommandSettings::register(cx);
201
202 cx.spawn(|mut cx| {
203 let client = client.clone();
204 async move {
205 let is_search_slash_command_enabled = cx
206 .update(|cx| cx.wait_for_flag::<SearchSlashCommandFeatureFlag>())?
207 .await;
208 let is_project_slash_command_enabled = cx
209 .update(|cx| cx.wait_for_flag::<ProjectSlashCommandFeatureFlag>())?
210 .await;
211
212 if !is_search_slash_command_enabled && !is_project_slash_command_enabled {
213 return Ok(());
214 }
215
216 let embedding_provider = CloudEmbeddingProvider::new(client.clone());
217 let semantic_index = SemanticDb::new(
218 paths::embeddings_dir().join("semantic-index-db.0.mdb"),
219 Arc::new(embedding_provider),
220 &mut cx,
221 )
222 .await?;
223
224 cx.update(|cx| cx.set_global(semantic_index))
225 }
226 })
227 .detach();
228
229 context_store::init(&client.clone().into());
230 prompt_library::init(cx);
231 init_language_model_settings(cx);
232 assistant_slash_command::init(cx);
233 assistant_tool::init(cx);
234 assistant_panel::init(cx);
235 context_server::init(cx);
236
237 let prompt_builder = prompts::PromptBuilder::new(Some(PromptLoadingParams {
238 fs: fs.clone(),
239 repo_path: stdout_is_a_pty
240 .then(|| std::env::current_dir().log_err())
241 .flatten(),
242 cx,
243 }))
244 .log_err()
245 .map(Arc::new)
246 .unwrap_or_else(|| Arc::new(prompts::PromptBuilder::new(None).unwrap()));
247 register_slash_commands(Some(prompt_builder.clone()), cx);
248 inline_assistant::init(
249 fs.clone(),
250 prompt_builder.clone(),
251 client.telemetry().clone(),
252 cx,
253 );
254 terminal_inline_assistant::init(
255 fs.clone(),
256 prompt_builder.clone(),
257 client.telemetry().clone(),
258 cx,
259 );
260 indexed_docs::init(cx);
261
262 CommandPaletteFilter::update_global(cx, |filter, _cx| {
263 filter.hide_namespace(Assistant::NAMESPACE);
264 });
265 Assistant::update_global(cx, |assistant, cx| {
266 let settings = AssistantSettings::get_global(cx);
267
268 assistant.set_enabled(settings.enabled, cx);
269 });
270 cx.observe_global::<SettingsStore>(|cx| {
271 Assistant::update_global(cx, |assistant, cx| {
272 let settings = AssistantSettings::get_global(cx);
273 assistant.set_enabled(settings.enabled, cx);
274 });
275 })
276 .detach();
277
278 prompt_builder
279}
280
281fn init_language_model_settings(cx: &mut AppContext) {
282 update_active_language_model_from_settings(cx);
283
284 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
285 .detach();
286 cx.subscribe(
287 &LanguageModelRegistry::global(cx),
288 |_, event: &language_model::Event, cx| match event {
289 language_model::Event::ProviderStateChanged
290 | language_model::Event::AddedProvider(_)
291 | language_model::Event::RemovedProvider(_) => {
292 update_active_language_model_from_settings(cx);
293 }
294 _ => {}
295 },
296 )
297 .detach();
298}
299
300fn update_active_language_model_from_settings(cx: &mut AppContext) {
301 let settings = AssistantSettings::get_global(cx);
302 let provider_name = LanguageModelProviderId::from(settings.default_model.provider.clone());
303 let model_id = LanguageModelId::from(settings.default_model.model.clone());
304 let inline_alternatives = settings
305 .inline_alternatives
306 .iter()
307 .map(|alternative| {
308 (
309 LanguageModelProviderId::from(alternative.provider.clone()),
310 LanguageModelId::from(alternative.model.clone()),
311 )
312 })
313 .collect::<Vec<_>>();
314 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
315 registry.select_active_model(&provider_name, &model_id, cx);
316 registry.select_inline_alternative_models(inline_alternatives, cx);
317 });
318}
319
320fn register_slash_commands(prompt_builder: Option<Arc<PromptBuilder>>, cx: &mut AppContext) {
321 let slash_command_registry = SlashCommandRegistry::global(cx);
322
323 slash_command_registry.register_command(file_command::FileSlashCommand, true);
324 slash_command_registry.register_command(delta_command::DeltaSlashCommand, true);
325 slash_command_registry.register_command(symbols_command::OutlineSlashCommand, true);
326 slash_command_registry.register_command(tab_command::TabSlashCommand, true);
327 slash_command_registry
328 .register_command(cargo_workspace_command::CargoWorkspaceSlashCommand, true);
329 slash_command_registry.register_command(prompt_command::PromptSlashCommand, true);
330 slash_command_registry.register_command(selection_command::SelectionCommand, true);
331 slash_command_registry.register_command(default_command::DefaultSlashCommand, false);
332 slash_command_registry.register_command(terminal_command::TerminalSlashCommand, true);
333 slash_command_registry.register_command(now_command::NowSlashCommand, false);
334 slash_command_registry.register_command(diagnostics_command::DiagnosticsSlashCommand, true);
335 slash_command_registry.register_command(fetch_command::FetchSlashCommand, true);
336
337 if let Some(prompt_builder) = prompt_builder {
338 cx.observe_flag::<project_command::ProjectSlashCommandFeatureFlag, _>({
339 let slash_command_registry = slash_command_registry.clone();
340 move |is_enabled, _cx| {
341 if is_enabled {
342 slash_command_registry.register_command(
343 project_command::ProjectSlashCommand::new(prompt_builder.clone()),
344 true,
345 );
346 }
347 }
348 })
349 .detach();
350 }
351
352 cx.observe_flag::<auto_command::AutoSlashCommandFeatureFlag, _>({
353 let slash_command_registry = slash_command_registry.clone();
354 move |is_enabled, _cx| {
355 if is_enabled {
356 // [#auto-staff-ship] TODO remove this when /auto is no longer staff-shipped
357 slash_command_registry.register_command(auto_command::AutoCommand, true);
358 }
359 }
360 })
361 .detach();
362
363 cx.observe_flag::<streaming_example_command::StreamingExampleSlashCommandFeatureFlag, _>({
364 let slash_command_registry = slash_command_registry.clone();
365 move |is_enabled, _cx| {
366 if is_enabled {
367 slash_command_registry.register_command(
368 streaming_example_command::StreamingExampleSlashCommand,
369 false,
370 );
371 }
372 }
373 })
374 .detach();
375
376 update_slash_commands_from_settings(cx);
377 cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
378 .detach();
379
380 cx.observe_flag::<search_command::SearchSlashCommandFeatureFlag, _>({
381 let slash_command_registry = slash_command_registry.clone();
382 move |is_enabled, _cx| {
383 if is_enabled {
384 slash_command_registry.register_command(search_command::SearchSlashCommand, true);
385 }
386 }
387 })
388 .detach();
389}
390
391fn update_slash_commands_from_settings(cx: &mut AppContext) {
392 let slash_command_registry = SlashCommandRegistry::global(cx);
393 let settings = SlashCommandSettings::get_global(cx);
394
395 if settings.docs.enabled {
396 slash_command_registry.register_command(docs_command::DocsSlashCommand, true);
397 } else {
398 slash_command_registry.unregister_command(docs_command::DocsSlashCommand);
399 }
400
401 if settings.cargo_workspace.enabled {
402 slash_command_registry
403 .register_command(cargo_workspace_command::CargoWorkspaceSlashCommand, true);
404 } else {
405 slash_command_registry
406 .unregister_command(cargo_workspace_command::CargoWorkspaceSlashCommand);
407 }
408}
409
410pub fn humanize_token_count(count: usize) -> String {
411 match count {
412 0..=999 => count.to_string(),
413 1000..=9999 => {
414 let thousands = count / 1000;
415 let hundreds = (count % 1000 + 50) / 100;
416 if hundreds == 0 {
417 format!("{}k", thousands)
418 } else if hundreds == 10 {
419 format!("{}k", thousands + 1)
420 } else {
421 format!("{}.{}k", thousands, hundreds)
422 }
423 }
424 _ => format!("{}k", (count + 500) / 1000),
425 }
426}
427
428#[cfg(test)]
429#[ctor::ctor]
430fn init_logger() {
431 if std::env::var("RUST_LOG").is_ok() {
432 env_logger::init();
433 }
434}