Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T01:50:57.652Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

terminal_inline_assistant.rs

468 lines · 16.1 KB · rust
1use crate::{
2    context::load_context,
3    inline_prompt_editor::{
4        CodegenStatus, PromptEditor, PromptEditorEvent, TerminalInlineAssistId,
5    },
6    terminal_codegen::{CLEAR_INPUT, CodegenEvent, TerminalCodegen},
7};
8use agent::ThreadStore;
9use agent_settings::AgentSettings;
10use anyhow::{Context as _, Result};
11
12use collections::{HashMap, VecDeque};
13use editor::{MultiBuffer, actions::SelectAll};
14use fs::Fs;
15use gpui::{App, Entity, Focusable, Global, Subscription, Task, UpdateGlobal, WeakEntity};
16use language::Buffer;
17use language_model::{
18    CompletionIntent, ConfiguredModel, LanguageModelRegistry, LanguageModelRequest,
19    LanguageModelRequestMessage, Role,
20};
21use language_models::provider::anthropic::telemetry::{
22    AnthropicCompletionType, AnthropicEventData, AnthropicEventType, report_anthropic_event,
23};
24use project::Project;
25use prompt_store::PromptBuilder;
26use std::sync::Arc;
27use terminal_view::TerminalView;
28use ui::prelude::*;
29use util::ResultExt;
30use uuid::Uuid;
31use workspace::{Toast, Workspace, notifications::NotificationId};
32
33pub fn init(fs: Arc<dyn Fs>, prompt_builder: Arc<PromptBuilder>, cx: &mut App) {
34    cx.set_global(TerminalInlineAssistant::new(fs, prompt_builder));
35}
36
37const DEFAULT_CONTEXT_LINES: usize = 50;
38const PROMPT_HISTORY_MAX_LEN: usize = 20;
39
40pub struct TerminalInlineAssistant {
41    next_assist_id: TerminalInlineAssistId,
42    assists: HashMap<TerminalInlineAssistId, TerminalInlineAssist>,
43    prompt_history: VecDeque<String>,
44    fs: Arc<dyn Fs>,
45    prompt_builder: Arc<PromptBuilder>,
46}
47
48impl Global for TerminalInlineAssistant {}
49
50impl TerminalInlineAssistant {
51    pub fn new(fs: Arc<dyn Fs>, prompt_builder: Arc<PromptBuilder>) -> Self {
52        Self {
53            next_assist_id: TerminalInlineAssistId::default(),
54            assists: HashMap::default(),
55            prompt_history: VecDeque::default(),
56            fs,
57            prompt_builder,
58        }
59    }
60
61    pub fn assist(
62        &mut self,
63        terminal_view: &Entity<TerminalView>,
64        workspace: WeakEntity<Workspace>,
65        project: WeakEntity<Project>,
66        thread_store: Entity<ThreadStore>,
67        initial_prompt: Option<String>,
68        window: &mut Window,
69        cx: &mut App,
70    ) {
71        let terminal = terminal_view.read(cx).terminal().clone();
72        let assist_id = self.next_assist_id.post_inc();
73        let session_id = Uuid::new_v4();
74        let prompt_buffer = cx.new(|cx| {
75            MultiBuffer::singleton(
76                cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx)),
77                cx,
78            )
79        });
80        let codegen = cx.new(|_| TerminalCodegen::new(terminal, session_id));
81
82        let prompt_editor = cx.new(|cx| {
83            PromptEditor::new_terminal(
84                assist_id,
85                self.prompt_history.clone(),
86                prompt_buffer.clone(),
87                codegen,
88                session_id,
89                self.fs.clone(),
90                thread_store.clone(),
91                project.clone(),
92                workspace.clone(),
93                window,
94                cx,
95            )
96        });
97        let prompt_editor_render = prompt_editor.clone();
98        let block = terminal_view::BlockProperties {
99            height: 4,
100            render: Box::new(move |_| prompt_editor_render.clone().into_any_element()),
101        };
102        terminal_view.update(cx, |terminal_view, cx| {
103            terminal_view.set_block_below_cursor(block, window, cx);
104        });
105
106        let terminal_assistant = TerminalInlineAssist::new(
107            assist_id,
108            terminal_view,
109            prompt_editor,
110            workspace.clone(),
111            window,
112            cx,
113        );
114
115        self.assists.insert(assist_id, terminal_assistant);
116
117        self.focus_assist(assist_id, window, cx);
118    }
119
120    fn focus_assist(
121        &mut self,
122        assist_id: TerminalInlineAssistId,
123        window: &mut Window,
124        cx: &mut App,
125    ) {
126        let assist = &self.assists[&assist_id];
127        if let Some(prompt_editor) = assist.prompt_editor.as_ref() {
128            prompt_editor.update(cx, |this, cx| {
129                this.editor.update(cx, |editor, cx| {
130                    window.focus(&editor.focus_handle(cx), cx);
131                    editor.select_all(&SelectAll, window, cx);
132                });
133            });
134        }
135    }
136
137    fn handle_prompt_editor_event(
138        &mut self,
139        prompt_editor: Entity<PromptEditor<TerminalCodegen>>,
140        event: &PromptEditorEvent,
141        window: &mut Window,
142        cx: &mut App,
143    ) {
144        let assist_id = prompt_editor.read(cx).id();
145        match event {
146            PromptEditorEvent::StartRequested => {
147                self.start_assist(assist_id, cx);
148            }
149            PromptEditorEvent::StopRequested => {
150                self.stop_assist(assist_id, cx);
151            }
152            PromptEditorEvent::ConfirmRequested { execute } => {
153                self.finish_assist(assist_id, false, *execute, window, cx);
154            }
155            PromptEditorEvent::CancelRequested => {
156                self.finish_assist(assist_id, true, false, window, cx);
157            }
158            PromptEditorEvent::Resized { height_in_lines } => {
159                self.insert_prompt_editor_into_terminal(assist_id, *height_in_lines, window, cx);
160            }
161        }
162    }
163
164    fn start_assist(&mut self, assist_id: TerminalInlineAssistId, cx: &mut App) {
165        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
166            assist
167        } else {
168            return;
169        };
170
171        let Some(user_prompt) = assist
172            .prompt_editor
173            .as_ref()
174            .map(|editor| editor.read(cx).prompt(cx))
175        else {
176            return;
177        };
178
179        self.prompt_history.retain(|prompt| *prompt != user_prompt);
180        self.prompt_history.push_back(user_prompt);
181        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
182            self.prompt_history.pop_front();
183        }
184
185        assist
186            .terminal
187            .update(cx, |terminal, cx| {
188                terminal
189                    .terminal()
190                    .update(cx, |terminal, _| terminal.input(CLEAR_INPUT.as_bytes()));
191            })
192            .log_err();
193
194        let codegen = assist.codegen.clone();
195        let Some(request_task) = self.request_for_inline_assist(assist_id, cx).log_err() else {
196            return;
197        };
198
199        codegen.update(cx, |codegen, cx| codegen.start(request_task, cx));
200    }
201
202    fn stop_assist(&mut self, assist_id: TerminalInlineAssistId, cx: &mut App) {
203        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
204            assist
205        } else {
206            return;
207        };
208
209        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
210    }
211
212    fn request_for_inline_assist(
213        &self,
214        assist_id: TerminalInlineAssistId,
215        cx: &mut App,
216    ) -> Result<Task<LanguageModelRequest>> {
217        let ConfiguredModel { model, .. } = LanguageModelRegistry::read_global(cx)
218            .inline_assistant_model()
219            .context("No inline assistant model")?;
220
221        let assist = self.assists.get(&assist_id).context("invalid assist")?;
222
223        let shell = std::env::var("SHELL").ok();
224        let (latest_output, working_directory) = assist
225            .terminal
226            .update(cx, |terminal, cx| {
227                let terminal = terminal.entity().read(cx);
228                let latest_output = terminal.last_n_non_empty_lines(DEFAULT_CONTEXT_LINES);
229                let working_directory = terminal
230                    .working_directory()
231                    .map(|path| path.to_string_lossy().into_owned());
232                (latest_output, working_directory)
233            })
234            .ok()
235            .unwrap_or_default();
236
237        let prompt_editor = assist.prompt_editor.clone().context("invalid assist")?;
238
239        let prompt = self.prompt_builder.generate_terminal_assistant_prompt(
240            &prompt_editor.read(cx).prompt(cx),
241            shell.as_deref(),
242            working_directory.as_deref(),
243            &latest_output,
244        )?;
245
246        let temperature = AgentSettings::temperature_for_model(&model, cx);
247
248        let mention_set = prompt_editor.read(cx).mention_set().clone();
249        let load_context_task = load_context(&mention_set, cx);
250
251        Ok(cx.background_spawn(async move {
252            let mut request_message = LanguageModelRequestMessage {
253                role: Role::User,
254                content: vec![],
255                cache: false,
256                reasoning_details: None,
257            };
258
259            if let Some(context) = load_context_task.await {
260                context.add_to_request_message(&mut request_message);
261            }
262
263            request_message.content.push(prompt.into());
264
265            LanguageModelRequest {
266                thread_id: None,
267                prompt_id: None,
268                intent: Some(CompletionIntent::TerminalInlineAssist),
269                messages: vec![request_message],
270                tools: Vec::new(),
271                tool_choice: None,
272                stop: Vec::new(),
273                temperature,
274                thinking_allowed: false,
275                thinking_effort: None,
276                speed: None,
277                compact_at_tokens: None,
278            }
279        }))
280    }
281
282    fn finish_assist(
283        &mut self,
284        assist_id: TerminalInlineAssistId,
285        undo: bool,
286        execute: bool,
287        window: &mut Window,
288        cx: &mut App,
289    ) {
290        self.dismiss_assist(assist_id, window, cx);
291
292        if let Some(assist) = self.assists.remove(&assist_id) {
293            assist
294                .terminal
295                .update(cx, |this, cx| {
296                    this.clear_block_below_cursor(cx);
297                    this.focus_handle(cx).focus(window, cx);
298                })
299                .log_err();
300
301            if let Some(ConfiguredModel { model, .. }) =
302                LanguageModelRegistry::read_global(cx).inline_assistant_model()
303            {
304                let codegen = assist.codegen.read(cx);
305                let session_id = codegen.session_id();
306                let message_id = codegen.message_id.clone();
307                let model_telemetry_id = model.telemetry_id();
308                let model_provider_id = model.provider_id().to_string();
309
310                let (phase, event_type, anthropic_event_type) = if undo {
311                    (
312                        "rejected",
313                        "Assistant Response Rejected",
314                        AnthropicEventType::Reject,
315                    )
316                } else {
317                    (
318                        "accepted",
319                        "Assistant Response Accepted",
320                        AnthropicEventType::Accept,
321                    )
322                };
323
324                // Fire Zed telemetry
325                telemetry::event!(
326                    event_type,
327                    kind = "inline_terminal",
328                    phase = phase,
329                    model = model_telemetry_id,
330                    model_provider = model_provider_id,
331                    message_id = message_id,
332                    session_id = session_id,
333                );
334
335                report_anthropic_event(
336                    &model,
337                    AnthropicEventData {
338                        completion_type: AnthropicCompletionType::Terminal,
339                        event: anthropic_event_type,
340                        language_name: None,
341                        message_id,
342                    },
343                    cx,
344                );
345            }
346
347            assist.codegen.update(cx, |codegen, cx| {
348                if undo {
349                    codegen.undo(cx);
350                } else if execute {
351                    codegen.complete(cx);
352                }
353            });
354        }
355    }
356
357    fn dismiss_assist(
358        &mut self,
359        assist_id: TerminalInlineAssistId,
360        window: &mut Window,
361        cx: &mut App,
362    ) -> bool {
363        let Some(assist) = self.assists.get_mut(&assist_id) else {
364            return false;
365        };
366        if assist.prompt_editor.is_none() {
367            return false;
368        }
369        assist.prompt_editor = None;
370        assist
371            .terminal
372            .update(cx, |this, cx| {
373                this.clear_block_below_cursor(cx);
374                this.focus_handle(cx).focus(window, cx);
375            })
376            .is_ok()
377    }
378
379    fn insert_prompt_editor_into_terminal(
380        &mut self,
381        assist_id: TerminalInlineAssistId,
382        height: u8,
383        window: &mut Window,
384        cx: &mut App,
385    ) {
386        if let Some(assist) = self.assists.get_mut(&assist_id)
387            && let Some(prompt_editor) = assist.prompt_editor.as_ref().cloned()
388        {
389            assist
390                .terminal
391                .update(cx, |terminal, cx| {
392                    terminal.clear_block_below_cursor(cx);
393                    let block = terminal_view::BlockProperties {
394                        height,
395                        render: Box::new(move |_| prompt_editor.clone().into_any_element()),
396                    };
397                    terminal.set_block_below_cursor(block, window, cx);
398                })
399                .log_err();
400        }
401    }
402}
403
404struct TerminalInlineAssist {
405    terminal: WeakEntity<TerminalView>,
406    prompt_editor: Option<Entity<PromptEditor<TerminalCodegen>>>,
407    codegen: Entity<TerminalCodegen>,
408    workspace: WeakEntity<Workspace>,
409    _subscriptions: Vec<Subscription>,
410}
411
412impl TerminalInlineAssist {
413    pub fn new(
414        assist_id: TerminalInlineAssistId,
415        terminal: &Entity<TerminalView>,
416        prompt_editor: Entity<PromptEditor<TerminalCodegen>>,
417        workspace: WeakEntity<Workspace>,
418        window: &mut Window,
419        cx: &mut App,
420    ) -> Self {
421        let codegen = prompt_editor.read(cx).codegen().clone();
422        Self {
423            terminal: terminal.downgrade(),
424            prompt_editor: Some(prompt_editor.clone()),
425            codegen: codegen.clone(),
426            workspace,
427            _subscriptions: vec![
428                window.subscribe(&prompt_editor, cx, |prompt_editor, event, window, cx| {
429                    TerminalInlineAssistant::update_global(cx, |this, cx| {
430                        this.handle_prompt_editor_event(prompt_editor, event, window, cx)
431                    })
432                }),
433                window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
434                    TerminalInlineAssistant::update_global(cx, |this, cx| match event {
435                        CodegenEvent::Finished => {
436                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
437                                assist
438                            } else {
439                                return;
440                            };
441
442                            if let CodegenStatus::Error(error) = &codegen.read(cx).status
443                                && assist.prompt_editor.is_none()
444                                && let Some(workspace) = assist.workspace.upgrade()
445                            {
446                                let error = format!("Terminal inline assistant error: {}", error);
447                                workspace.update(cx, |workspace, cx| {
448                                    struct InlineAssistantError;
449
450                                    let id = NotificationId::composite::<InlineAssistantError>(
451                                        assist_id.0,
452                                    );
453
454                                    workspace.show_toast(Toast::new(id, error), cx);
455                                })
456                            }
457
458                            if assist.prompt_editor.is_none() {
459                                this.finish_assist(assist_id, false, false, window, cx);
460                            }
461                        }
462                    })
463                }),
464            ],
465        }
466    }
467}
468
Served at tenant.openagents/omega Member data and write actions are omitted.