1use crate::{
2 DebugEvent, EditPredictionFinishedDebugEvent, EditPredictionId, EditPredictionModelInput,
3 EditPredictionStartedDebugEvent, open_ai_response::text_from_response,
4 prediction::EditPredictionResult, zeta1::compute_edits,
5};
6use anyhow::{Context as _, Result};
7use cloud_llm_client::EditPredictionRejectReason;
8use futures::AsyncReadExt as _;
9use gpui::{
10 App, AppContext as _, Entity, Global, SharedString, Task,
11 http_client::{self, AsyncBody, HttpClient, Method},
12};
13use language::{OffsetRangeExt as _, ToOffset, ToPoint as _};
14use language_model::{ApiKeyState, EnvVar, env_var};
15use release_channel::AppVersion;
16use serde::Serialize;
17use std::{mem, ops::Range, path::Path, sync::Arc, time::Instant};
18
19use zeta_prompt::ZetaPromptInput;
20
21const MERCURY_API_URL: &str = "https://api.inceptionlabs.ai/v1/edit/completions";
22const MAX_REWRITE_TOKENS: usize = 150;
23const MAX_CONTEXT_TOKENS: usize = 350;
24
25pub struct Mercury {
26 pub api_token: Entity<ApiKeyState>,
27}
28
29impl Mercury {
30 pub fn new(cx: &mut App) -> Self {
31 Mercury {
32 api_token: mercury_api_token(cx),
33 }
34 }
35
36 pub(crate) fn request_prediction(
37 &self,
38 EditPredictionModelInput {
39 buffer,
40 snapshot,
41 position,
42 events,
43 related_files,
44 debug_tx,
45 ..
46 }: EditPredictionModelInput,
47 cx: &mut App,
48 ) -> Task<Result<Option<EditPredictionResult>>> {
49 self.api_token.update(cx, |key_state, cx| {
50 _ = key_state.load_if_needed(MERCURY_CREDENTIALS_URL, |s| s, cx);
51 });
52 let Some(api_token) = self.api_token.read(cx).key(&MERCURY_CREDENTIALS_URL) else {
53 return Task::ready(Ok(None));
54 };
55 let full_path: Arc<Path> = snapshot
56 .file()
57 .map(|file| file.full_path(cx))
58 .unwrap_or_else(|| "untitled".into())
59 .into();
60
61 let http_client = cx.http_client();
62 let cursor_point = position.to_point(&snapshot);
63 let buffer_snapshotted_at = Instant::now();
64 let active_buffer = buffer.clone();
65
66 let result = cx.background_spawn(async move {
67 let (editable_range, context_range) =
68 crate::cursor_excerpt::editable_and_context_ranges_for_cursor_position(
69 cursor_point,
70 &snapshot,
71 MAX_CONTEXT_TOKENS,
72 MAX_REWRITE_TOKENS,
73 );
74
75 let related_files = crate::filter_redundant_excerpts(
76 related_files,
77 full_path.as_ref(),
78 context_range.start.row..context_range.end.row,
79 );
80
81 let context_offset_range = context_range.to_offset(&snapshot);
82 let context_start_row = context_range.start.row;
83
84 let editable_offset_range = editable_range.to_offset(&snapshot);
85
86 let inputs = zeta_prompt::ZetaPromptInput {
87 events,
88 related_files,
89 cursor_offset_in_excerpt: cursor_point.to_offset(&snapshot)
90 - context_offset_range.start,
91 cursor_path: full_path.clone(),
92 cursor_excerpt: snapshot
93 .text_for_range(context_range)
94 .collect::<String>()
95 .into(),
96 editable_range_in_excerpt: (editable_offset_range.start
97 - context_offset_range.start)
98 ..(editable_offset_range.end - context_offset_range.start),
99 excerpt_start_row: Some(context_start_row),
100 excerpt_ranges: None,
101 preferred_model: None,
102 in_open_source_repo: false,
103 };
104
105 let prompt = build_prompt(&inputs);
106
107 if let Some(debug_tx) = &debug_tx {
108 debug_tx
109 .unbounded_send(DebugEvent::EditPredictionStarted(
110 EditPredictionStartedDebugEvent {
111 buffer: active_buffer.downgrade(),
112 prompt: Some(prompt.clone()),
113 position,
114 },
115 ))
116 .ok();
117 }
118
119 let request_body = open_ai::Request {
120 model: "mercury-coder".into(),
121 messages: vec![open_ai::RequestMessage::User {
122 content: open_ai::MessageContent::Plain(prompt),
123 }],
124 stream: false,
125 max_completion_tokens: None,
126 stop: vec![],
127 temperature: None,
128 tool_choice: None,
129 parallel_tool_calls: None,
130 tools: vec![],
131 prompt_cache_key: None,
132 reasoning_effort: None,
133 };
134
135 let buf = serde_json::to_vec(&request_body)?;
136 let body: AsyncBody = buf.into();
137
138 let request = http_client::Request::builder()
139 .uri(MERCURY_API_URL)
140 .header("Content-Type", "application/json")
141 .header("Authorization", format!("Bearer {}", api_token))
142 .header("Connection", "keep-alive")
143 .method(Method::POST)
144 .body(body)
145 .context("Failed to create request")?;
146
147 let mut response = http_client
148 .send(request)
149 .await
150 .context("Failed to send request")?;
151
152 let mut body: Vec<u8> = Vec::new();
153 response
154 .body_mut()
155 .read_to_end(&mut body)
156 .await
157 .context("Failed to read response body")?;
158
159 let response_received_at = Instant::now();
160 if !response.status().is_success() {
161 anyhow::bail!(
162 "Request failed with status: {:?}\nBody: {}",
163 response.status(),
164 String::from_utf8_lossy(&body),
165 );
166 };
167
168 let mut response: open_ai::Response =
169 serde_json::from_slice(&body).context("Failed to parse response")?;
170
171 let id = mem::take(&mut response.id);
172 let response_str = text_from_response(response).unwrap_or_default();
173
174 if let Some(debug_tx) = &debug_tx {
175 debug_tx
176 .unbounded_send(DebugEvent::EditPredictionFinished(
177 EditPredictionFinishedDebugEvent {
178 buffer: active_buffer.downgrade(),
179 model_output: Some(response_str.clone()),
180 position,
181 },
182 ))
183 .ok();
184 }
185
186 let response_str = response_str.strip_prefix("```\n").unwrap_or(&response_str);
187 let response_str = response_str.strip_suffix("\n```").unwrap_or(&response_str);
188
189 let mut edits = Vec::new();
190 const NO_PREDICTION_OUTPUT: &str = "None";
191
192 if response_str != NO_PREDICTION_OUTPUT {
193 let old_text = snapshot
194 .text_for_range(editable_offset_range.clone())
195 .collect::<String>();
196 edits = compute_edits(
197 old_text,
198 &response_str,
199 editable_offset_range.start,
200 &snapshot,
201 );
202 }
203
204 anyhow::Ok((id, edits, snapshot, response_received_at, inputs))
205 });
206
207 cx.spawn(async move |cx| {
208 let (id, edits, old_snapshot, response_received_at, inputs) =
209 result.await.context("Mercury edit prediction failed")?;
210 anyhow::Ok(Some(
211 EditPredictionResult::new(
212 EditPredictionId(id.into()),
213 &buffer,
214 &old_snapshot,
215 edits.into(),
216 None,
217 buffer_snapshotted_at,
218 response_received_at,
219 inputs,
220 cx,
221 )
222 .await,
223 ))
224 })
225 }
226}
227
228fn build_prompt(inputs: &ZetaPromptInput) -> String {
229 const RECENTLY_VIEWED_SNIPPETS_START: &str = "<|recently_viewed_code_snippets|>\n";
230 const RECENTLY_VIEWED_SNIPPETS_END: &str = "<|/recently_viewed_code_snippets|>\n";
231 const RECENTLY_VIEWED_SNIPPET_START: &str = "<|recently_viewed_code_snippet|>\n";
232 const RECENTLY_VIEWED_SNIPPET_END: &str = "<|/recently_viewed_code_snippet|>\n";
233 const CURRENT_FILE_CONTENT_START: &str = "<|current_file_content|>\n";
234 const CURRENT_FILE_CONTENT_END: &str = "<|/current_file_content|>\n";
235 const CODE_TO_EDIT_START: &str = "<|code_to_edit|>\n";
236 const CODE_TO_EDIT_END: &str = "<|/code_to_edit|>\n";
237 const EDIT_DIFF_HISTORY_START: &str = "<|edit_diff_history|>\n";
238 const EDIT_DIFF_HISTORY_END: &str = "<|/edit_diff_history|>\n";
239 const CURSOR_TAG: &str = "<|cursor|>";
240 const CODE_SNIPPET_FILE_PATH_PREFIX: &str = "code_snippet_file_path: ";
241 const CURRENT_FILE_PATH_PREFIX: &str = "current_file_path: ";
242
243 let mut prompt = String::new();
244
245 push_delimited(
246 &mut prompt,
247 RECENTLY_VIEWED_SNIPPETS_START..RECENTLY_VIEWED_SNIPPETS_END,
248 |prompt| {
249 for related_file in inputs.related_files.iter() {
250 for related_excerpt in &related_file.excerpts {
251 push_delimited(
252 prompt,
253 RECENTLY_VIEWED_SNIPPET_START..RECENTLY_VIEWED_SNIPPET_END,
254 |prompt| {
255 prompt.push_str(CODE_SNIPPET_FILE_PATH_PREFIX);
256 prompt.push_str(related_file.path.to_string_lossy().as_ref());
257 prompt.push('\n');
258 prompt.push_str(related_excerpt.text.as_ref());
259 },
260 );
261 }
262 }
263 },
264 );
265
266 push_delimited(
267 &mut prompt,
268 CURRENT_FILE_CONTENT_START..CURRENT_FILE_CONTENT_END,
269 |prompt| {
270 prompt.push_str(CURRENT_FILE_PATH_PREFIX);
271 prompt.push_str(inputs.cursor_path.as_os_str().to_string_lossy().as_ref());
272 prompt.push('\n');
273
274 prompt.push_str(&inputs.cursor_excerpt[0..inputs.editable_range_in_excerpt.start]);
275 push_delimited(prompt, CODE_TO_EDIT_START..CODE_TO_EDIT_END, |prompt| {
276 prompt.push_str(
277 &inputs.cursor_excerpt
278 [inputs.editable_range_in_excerpt.start..inputs.cursor_offset_in_excerpt],
279 );
280 prompt.push_str(CURSOR_TAG);
281 prompt.push_str(
282 &inputs.cursor_excerpt
283 [inputs.cursor_offset_in_excerpt..inputs.editable_range_in_excerpt.end],
284 );
285 });
286 prompt.push_str(&inputs.cursor_excerpt[inputs.editable_range_in_excerpt.end..]);
287 },
288 );
289
290 push_delimited(
291 &mut prompt,
292 EDIT_DIFF_HISTORY_START..EDIT_DIFF_HISTORY_END,
293 |prompt| {
294 for event in inputs.events.iter() {
295 zeta_prompt::write_event(prompt, &event);
296 }
297 },
298 );
299
300 prompt
301}
302
303fn push_delimited(prompt: &mut String, delimiters: Range<&str>, cb: impl FnOnce(&mut String)) {
304 prompt.push_str(delimiters.start);
305 cb(prompt);
306 prompt.push('\n');
307 prompt.push_str(delimiters.end);
308}
309
310pub const MERCURY_CREDENTIALS_URL: SharedString =
311 SharedString::new_static("https://api.inceptionlabs.ai/v1/edit/completions");
312pub const MERCURY_CREDENTIALS_USERNAME: &str = "mercury-api-token";
313pub static MERCURY_TOKEN_ENV_VAR: std::sync::LazyLock<EnvVar> = env_var!("MERCURY_AI_TOKEN");
314
315struct GlobalMercuryApiKey(Entity<ApiKeyState>);
316
317impl Global for GlobalMercuryApiKey {}
318
319pub fn mercury_api_token(cx: &mut App) -> Entity<ApiKeyState> {
320 if let Some(global) = cx.try_global::<GlobalMercuryApiKey>() {
321 return global.0.clone();
322 }
323 let entity =
324 cx.new(|_| ApiKeyState::new(MERCURY_CREDENTIALS_URL, MERCURY_TOKEN_ENV_VAR.clone()));
325 cx.set_global(GlobalMercuryApiKey(entity.clone()));
326 entity
327}
328
329pub fn load_mercury_api_token(cx: &mut App) -> Task<Result<(), language_model::AuthenticateError>> {
330 mercury_api_token(cx).update(cx, |key_state, cx| {
331 key_state.load_if_needed(MERCURY_CREDENTIALS_URL, |s| s, cx)
332 })
333}
334
335const FEEDBACK_API_URL: &str = "https://api-feedback.inceptionlabs.ai/feedback";
336
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
338#[serde(rename_all = "snake_case")]
339enum MercuryUserAction {
340 Accept,
341 Reject,
342 Ignore,
343}
344
345#[derive(Serialize)]
346struct FeedbackRequest {
347 request_id: SharedString,
348 provider_name: &'static str,
349 user_action: MercuryUserAction,
350 provider_version: String,
351}
352
353pub(crate) fn edit_prediction_accepted(
354 prediction_id: EditPredictionId,
355 http_client: Arc<dyn HttpClient>,
356 cx: &App,
357) {
358 send_feedback(prediction_id, MercuryUserAction::Accept, http_client, cx);
359}
360
361pub(crate) fn edit_prediction_rejected(
362 prediction_id: EditPredictionId,
363 was_shown: bool,
364 reason: EditPredictionRejectReason,
365 http_client: Arc<dyn HttpClient>,
366 cx: &App,
367) {
368 if !was_shown {
369 return;
370 }
371 let action = match reason {
372 EditPredictionRejectReason::Rejected => MercuryUserAction::Reject,
373 EditPredictionRejectReason::Discarded => MercuryUserAction::Ignore,
374 _ => return,
375 };
376 send_feedback(prediction_id, action, http_client, cx);
377}
378
379fn send_feedback(
380 prediction_id: EditPredictionId,
381 action: MercuryUserAction,
382 http_client: Arc<dyn HttpClient>,
383 cx: &App,
384) {
385 let request_id = prediction_id.0;
386 let app_version = AppVersion::global(cx);
387 cx.background_spawn(async move {
388 let body = FeedbackRequest {
389 request_id,
390 provider_name: "zed",
391 user_action: action,
392 provider_version: app_version.to_string(),
393 };
394
395 let request = http_client::Request::builder()
396 .uri(FEEDBACK_API_URL)
397 .method(Method::POST)
398 .header("Content-Type", "application/json")
399 .body(AsyncBody::from(serde_json::to_vec(&body)?))?;
400
401 let response = http_client.send(request).await?;
402 if !response.status().is_success() {
403 anyhow::bail!("Feedback API returned status: {}", response.status());
404 }
405
406 log::debug!(
407 "Mercury feedback sent: request_id={}, action={:?}",
408 body.request_id,
409 body.user_action
410 );
411
412 anyhow::Ok(())
413 })
414 .detach_and_log_err(cx);
415}