1use std::path::PathBuf;
2use std::sync::Arc;
3use std::sync::OnceLock;
4
5use anyhow::{anyhow, Result};
6use chrono::DateTime;
7use fs::Fs;
8use futures::{io::BufReader, stream::BoxStream, AsyncBufReadExt, AsyncReadExt, StreamExt};
9use gpui::{AppContext, AsyncAppContext, Global};
10use http_client::{AsyncBody, HttpClient, Method, Request as HttpRequest};
11use paths::home_dir;
12use serde::{Deserialize, Serialize};
13use settings::watch_config_file;
14use strum::EnumIter;
15use ui::Context;
16
17pub const COPILOT_CHAT_COMPLETION_URL: &str = "https://api.githubcopilot.com/chat/completions";
18pub const COPILOT_CHAT_AUTH_URL: &str = "https://api.github.com/copilot_internal/v2/token";
19
20#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq)]
21#[serde(rename_all = "lowercase")]
22pub enum Role {
23 User,
24 Assistant,
25 System,
26}
27
28#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
29#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, EnumIter)]
30pub enum Model {
31 #[default]
32 #[serde(alias = "gpt-4o", rename = "gpt-4o-2024-05-13")]
33 Gpt4o,
34 #[serde(alias = "gpt-4", rename = "gpt-4")]
35 Gpt4,
36 #[serde(alias = "gpt-3.5-turbo", rename = "gpt-3.5-turbo")]
37 Gpt3_5Turbo,
38 #[serde(alias = "o1-preview", rename = "o1-preview-2024-09-12")]
39 O1Preview,
40 #[serde(alias = "o1-mini", rename = "o1-mini-2024-09-12")]
41 O1Mini,
42 #[serde(alias = "claude-3-5-sonnet", rename = "claude-3.5-sonnet")]
43 Claude3_5Sonnet,
44}
45
46impl Model {
47 pub fn uses_streaming(&self) -> bool {
48 match self {
49 Self::Gpt4o | Self::Gpt4 | Self::Gpt3_5Turbo | Self::Claude3_5Sonnet => true,
50 Self::O1Mini | Self::O1Preview => false,
51 }
52 }
53
54 pub fn from_id(id: &str) -> Result<Self> {
55 match id {
56 "gpt-4o" => Ok(Self::Gpt4o),
57 "gpt-4" => Ok(Self::Gpt4),
58 "gpt-3.5-turbo" => Ok(Self::Gpt3_5Turbo),
59 "o1-preview" => Ok(Self::O1Preview),
60 "o1-mini" => Ok(Self::O1Mini),
61 "claude-3-5-sonnet" => Ok(Self::Claude3_5Sonnet),
62 _ => Err(anyhow!("Invalid model id: {}", id)),
63 }
64 }
65
66 pub fn id(&self) -> &'static str {
67 match self {
68 Self::Gpt3_5Turbo => "gpt-3.5-turbo",
69 Self::Gpt4 => "gpt-4",
70 Self::Gpt4o => "gpt-4o",
71 Self::O1Mini => "o1-mini",
72 Self::O1Preview => "o1-preview",
73 Self::Claude3_5Sonnet => "claude-3-5-sonnet",
74 }
75 }
76
77 pub fn display_name(&self) -> &'static str {
78 match self {
79 Self::Gpt3_5Turbo => "GPT-3.5",
80 Self::Gpt4 => "GPT-4",
81 Self::Gpt4o => "GPT-4o",
82 Self::O1Mini => "o1-mini",
83 Self::O1Preview => "o1-preview",
84 Self::Claude3_5Sonnet => "Claude 3.5 Sonnet",
85 }
86 }
87
88 pub fn max_token_count(&self) -> usize {
89 match self {
90 Self::Gpt4o => 64000,
91 Self::Gpt4 => 32768,
92 Self::Gpt3_5Turbo => 12288,
93 Self::O1Mini => 20000,
94 Self::O1Preview => 20000,
95 Self::Claude3_5Sonnet => 200_000,
96 }
97 }
98}
99
100#[derive(Serialize, Deserialize)]
101pub struct Request {
102 pub intent: bool,
103 pub n: usize,
104 pub stream: bool,
105 pub temperature: f32,
106 pub model: Model,
107 pub messages: Vec<ChatMessage>,
108}
109
110impl Request {
111 pub fn new(model: Model, messages: Vec<ChatMessage>) -> Self {
112 Self {
113 intent: true,
114 n: 1,
115 stream: model.uses_streaming(),
116 temperature: 0.1,
117 model,
118 messages,
119 }
120 }
121}
122
123#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
124pub struct ChatMessage {
125 pub role: Role,
126 pub content: String,
127}
128
129#[derive(Deserialize, Debug)]
130#[serde(tag = "type", rename_all = "snake_case")]
131pub struct ResponseEvent {
132 pub choices: Vec<ResponseChoice>,
133 pub created: u64,
134 pub id: String,
135}
136
137#[derive(Debug, Deserialize)]
138pub struct ResponseChoice {
139 pub index: usize,
140 pub finish_reason: Option<String>,
141 pub delta: Option<ResponseDelta>,
142 pub message: Option<ResponseDelta>,
143}
144
145#[derive(Debug, Deserialize)]
146pub struct ResponseDelta {
147 pub content: Option<String>,
148 pub role: Option<Role>,
149}
150
151#[derive(Deserialize)]
152struct ApiTokenResponse {
153 token: String,
154 expires_at: i64,
155}
156
157#[derive(Clone)]
158struct ApiToken {
159 api_key: String,
160 expires_at: DateTime<chrono::Utc>,
161}
162
163impl ApiToken {
164 pub fn remaining_seconds(&self) -> i64 {
165 self.expires_at
166 .timestamp()
167 .saturating_sub(chrono::Utc::now().timestamp())
168 }
169}
170
171impl TryFrom<ApiTokenResponse> for ApiToken {
172 type Error = anyhow::Error;
173
174 fn try_from(response: ApiTokenResponse) -> Result<Self, Self::Error> {
175 let expires_at = DateTime::from_timestamp(response.expires_at, 0)
176 .ok_or_else(|| anyhow!("invalid expires_at"))?;
177
178 Ok(Self {
179 api_key: response.token,
180 expires_at,
181 })
182 }
183}
184
185struct GlobalCopilotChat(gpui::Model<CopilotChat>);
186
187impl Global for GlobalCopilotChat {}
188
189pub struct CopilotChat {
190 oauth_token: Option<String>,
191 api_token: Option<ApiToken>,
192 client: Arc<dyn HttpClient>,
193}
194
195pub fn init(fs: Arc<dyn Fs>, client: Arc<dyn HttpClient>, cx: &mut AppContext) {
196 let copilot_chat = cx.new_model(|cx| CopilotChat::new(fs, client, cx));
197 cx.set_global(GlobalCopilotChat(copilot_chat));
198}
199
200fn copilot_chat_config_path() -> &'static PathBuf {
201 static COPILOT_CHAT_CONFIG_DIR: OnceLock<PathBuf> = OnceLock::new();
202
203 COPILOT_CHAT_CONFIG_DIR.get_or_init(|| {
204 if cfg!(target_os = "windows") {
205 home_dir().join("AppData").join("Local")
206 } else {
207 home_dir().join(".config")
208 }
209 .join("github-copilot")
210 .join("hosts.json")
211 })
212}
213
214impl CopilotChat {
215 pub fn global(cx: &AppContext) -> Option<gpui::Model<Self>> {
216 cx.try_global::<GlobalCopilotChat>()
217 .map(|model| model.0.clone())
218 }
219
220 pub fn new(fs: Arc<dyn Fs>, client: Arc<dyn HttpClient>, cx: &AppContext) -> Self {
221 let mut config_file_rx = watch_config_file(
222 cx.background_executor(),
223 fs,
224 copilot_chat_config_path().clone(),
225 );
226
227 cx.spawn(|cx| async move {
228 while let Some(contents) = config_file_rx.next().await {
229 let oauth_token = extract_oauth_token(contents);
230
231 cx.update(|cx| {
232 if let Some(this) = Self::global(cx).as_ref() {
233 this.update(cx, |this, cx| {
234 this.oauth_token = oauth_token;
235 cx.notify();
236 });
237 }
238 })?;
239 }
240 anyhow::Ok(())
241 })
242 .detach_and_log_err(cx);
243
244 Self {
245 oauth_token: None,
246 api_token: None,
247 client,
248 }
249 }
250
251 pub fn is_authenticated(&self) -> bool {
252 self.oauth_token.is_some()
253 }
254
255 pub async fn stream_completion(
256 request: Request,
257 mut cx: AsyncAppContext,
258 ) -> Result<BoxStream<'static, Result<ResponseEvent>>> {
259 let Some(this) = cx.update(|cx| Self::global(cx)).ok().flatten() else {
260 return Err(anyhow!("Copilot chat is not enabled"));
261 };
262
263 let (oauth_token, api_token, client) = this.read_with(&cx, |this, _| {
264 (
265 this.oauth_token.clone(),
266 this.api_token.clone(),
267 this.client.clone(),
268 )
269 })?;
270
271 let oauth_token = oauth_token.ok_or_else(|| anyhow!("No OAuth token available"))?;
272
273 let token = match api_token {
274 Some(api_token) if api_token.remaining_seconds() > 5 * 60 => api_token.clone(),
275 _ => {
276 let token = request_api_token(&oauth_token, client.clone()).await?;
277 this.update(&mut cx, |this, cx| {
278 this.api_token = Some(token.clone());
279 cx.notify();
280 })?;
281 token
282 }
283 };
284
285 stream_completion(client.clone(), token.api_key, request).await
286 }
287}
288
289async fn request_api_token(oauth_token: &str, client: Arc<dyn HttpClient>) -> Result<ApiToken> {
290 let request_builder = HttpRequest::builder()
291 .method(Method::GET)
292 .uri(COPILOT_CHAT_AUTH_URL)
293 .header("Authorization", format!("token {}", oauth_token))
294 .header("Accept", "application/json");
295
296 let request = request_builder.body(AsyncBody::empty())?;
297
298 let mut response = client.send(request).await?;
299
300 if response.status().is_success() {
301 let mut body = Vec::new();
302 response.body_mut().read_to_end(&mut body).await?;
303
304 let body_str = std::str::from_utf8(&body)?;
305
306 let parsed: ApiTokenResponse = serde_json::from_str(body_str)?;
307 ApiToken::try_from(parsed)
308 } else {
309 let mut body = Vec::new();
310 response.body_mut().read_to_end(&mut body).await?;
311
312 let body_str = std::str::from_utf8(&body)?;
313
314 Err(anyhow!("Failed to request API token: {}", body_str))
315 }
316}
317
318fn extract_oauth_token(contents: String) -> Option<String> {
319 serde_json::from_str::<serde_json::Value>(&contents)
320 .map(|v| {
321 v["github.com"]["oauth_token"]
322 .as_str()
323 .map(|v| v.to_string())
324 })
325 .ok()
326 .flatten()
327}
328
329async fn stream_completion(
330 client: Arc<dyn HttpClient>,
331 api_key: String,
332 request: Request,
333) -> Result<BoxStream<'static, Result<ResponseEvent>>> {
334 let request_builder = HttpRequest::builder()
335 .method(Method::POST)
336 .uri(COPILOT_CHAT_COMPLETION_URL)
337 .header(
338 "Editor-Version",
339 format!(
340 "Zed/{}",
341 option_env!("CARGO_PKG_VERSION").unwrap_or("unknown")
342 ),
343 )
344 .header("Authorization", format!("Bearer {}", api_key))
345 .header("Content-Type", "application/json")
346 .header("Copilot-Integration-Id", "vscode-chat");
347
348 let is_streaming = request.stream;
349
350 let request = request_builder.body(AsyncBody::from(serde_json::to_string(&request)?))?;
351 let mut response = client.send(request).await?;
352
353 if !response.status().is_success() {
354 let mut body = Vec::new();
355 response.body_mut().read_to_end(&mut body).await?;
356 let body_str = std::str::from_utf8(&body)?;
357 return Err(anyhow!(
358 "Failed to connect to API: {} {}",
359 response.status(),
360 body_str
361 ));
362 }
363
364 if is_streaming {
365 let reader = BufReader::new(response.into_body());
366 Ok(reader
367 .lines()
368 .filter_map(|line| async move {
369 match line {
370 Ok(line) => {
371 let line = line.strip_prefix("data: ")?;
372 if line.starts_with("[DONE]") {
373 return None;
374 }
375
376 match serde_json::from_str::<ResponseEvent>(line) {
377 Ok(response) => {
378 if response.choices.first().is_none()
379 || response.choices.first().unwrap().finish_reason.is_some()
380 {
381 None
382 } else {
383 Some(Ok(response))
384 }
385 }
386 Err(error) => Some(Err(anyhow!(error))),
387 }
388 }
389 Err(error) => Some(Err(anyhow!(error))),
390 }
391 })
392 .boxed())
393 } else {
394 let mut body = Vec::new();
395 response.body_mut().read_to_end(&mut body).await?;
396 let body_str = std::str::from_utf8(&body)?;
397 let response: ResponseEvent = serde_json::from_str(body_str)?;
398
399 Ok(futures::stream::once(async move { Ok(response) }).boxed())
400 }
401}