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