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