rab-agent 0.1.7

rab is a lightweight, extensible, Rust-based coding agent.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! GitHub Copilot OAuth provider — matching pi's github-copilot.ts exactly.
//!
//! Uses the device code flow (RFC 8628) to authenticate with GitHub.
//! After login, fetches available models and enables them.

use std::collections::HashMap;

use async_trait::async_trait;
use base64::Engine;

use super::device_code::{PollOptions, PollStatus, poll_device_code_flow};
use super::{DeviceCodeInfo, OAuthCredentials, OAuthLoginCallbacks, OAuthPrompt, OAuthProvider};

const CLIENT_ID_ENCODED: &str = "SXYxLmI1MDdhMDhjODdlY2ZlOTg=";

const COPILOT_HEADERS: &[(&str, &str)] = &[
    ("User-Agent", "GitHubCopilotChat/0.35.0"),
    ("Editor-Version", "vscode/1.107.0"),
    ("Editor-Plugin-Version", "copilot-chat/0.35.0"),
    ("Copilot-Integration-Id", "vscode-chat"),
];
const COPILOT_API_VERSION: &str = "2026-06-01";

fn client_id() -> String {
    String::from_utf8(
        base64::engine::general_purpose::STANDARD
            .decode(CLIENT_ID_ENCODED)
            .expect("valid base64"),
    )
    .expect("valid utf8")
}

#[allow(dead_code)]
fn decode(s: &str) -> String {
    String::from_utf8(
        base64::engine::general_purpose::STANDARD
            .decode(s)
            .unwrap_or_default(),
    )
    .unwrap_or_default()
}

pub fn normalize_domain(input: &str) -> Option<String> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return None;
    }
    let url_str = if trimmed.contains("://") {
        trimmed.to_string()
    } else {
        format!("https://{}", trimmed)
    };
    url::Url::parse(&url_str)
        .ok()
        .map(|u| u.host_str().unwrap_or("").to_string())
}

fn get_urls(domain: &str) -> (String, String, String) {
    (
        format!("https://{}/login/device/code", domain),
        format!("https://{}/login/oauth/access_token", domain),
        format!("https://api.{}/copilot_internal/v2/token", domain),
    )
}

/// Parse the proxy-ep from a Copilot token and convert to API base URL.
fn get_base_url_from_token(token: &str) -> Option<String> {
    for part in token.split(';') {
        if let Some(host) = part.strip_prefix("proxy-ep=") {
            let api_host = host.replacen("proxy.", "api.", 1);
            return Some(format!("https://{}", api_host));
        }
    }
    None
}

/// Get the GitHub Copilot API base URL.
pub fn get_copilot_base_url(token: Option<&str>, enterprise_domain: Option<&str>) -> String {
    if let Some(t) = token
        && let Some(url) = get_base_url_from_token(t)
    {
        return url;
    }
    if let Some(domain) = enterprise_domain {
        return format!("https://copilot-api.{}", domain);
    }
    "https://api.individual.githubcopilot.com".to_string()
}

/// Fetch JSON from a URL with headers.
async fn fetch_json(url: &str, headers: &[(&str, &str)]) -> Result<serde_json::Value, String> {
    let client = reqwest::Client::new();
    let mut req = client.get(url);
    for (k, v) in headers {
        req = req.header(*k, *v);
    }
    let resp = req.send().await.map_err(|e| format!("HTTP error: {}", e))?;
    let status = resp.status();
    if !status.is_success() {
        let text = resp.text().await.unwrap_or_default();
        return Err(format!("HTTP {}: {}", status, text));
    }
    resp.json().await.map_err(|e| format!("JSON error: {}", e))
}

/// Post JSON-encoded body to a URL.
#[allow(dead_code)]
async fn post_json(
    url: &str,
    headers: &[(&str, &str)],
    body: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    let client = reqwest::Client::new();
    let mut req = client.post(url).json(body);
    for (k, v) in headers {
        req = req.header(*k, *v);
    }
    let resp = req.send().await.map_err(|e| format!("HTTP error: {}", e))?;
    let status = resp.status();
    if !status.is_success() {
        let text = resp.text().await.unwrap_or_default();
        return Err(format!("HTTP {}: {}", status, text));
    }
    resp.json().await.map_err(|e| format!("JSON error: {}", e))
}

/// Post form-encoded body to a URL.
async fn post_form(
    url: &str,
    headers: &[(&str, &str)],
    form: &[(&str, &str)],
) -> Result<serde_json::Value, String> {
    let client = reqwest::Client::new();
    let mut req = client.post(url);
    for (k, v) in headers {
        req = req.header(*k, *v);
    }
    let params: Vec<(&str, &str)> = form.to_vec();
    let resp = req
        .form(&params)
        .send()
        .await
        .map_err(|e| format!("HTTP error: {}", e))?;
    let status = resp.status();
    if !status.is_success() {
        let text = resp.text().await.unwrap_or_default();
        return Err(format!("HTTP {}: {}", status, text));
    }
    resp.json().await.map_err(|e| format!("JSON error: {}", e))
}

/// Start the device code flow.
async fn start_device_flow(domain: &str) -> Result<serde_json::Value, String> {
    let (device_code_url, _, _) = get_urls(domain);
    post_form(
        &device_code_url,
        &[
            ("Accept", "application/json"),
            ("User-Agent", "GitHubCopilotChat/0.35.0"),
        ],
        &[("client_id", &client_id()), ("scope", "read:user")],
    )
    .await
}

/// Poll for the GitHub access token.
async fn poll_for_github_access_token(
    domain: &str,
    device_code: &str,
    interval: Option<u32>,
    expires_in: Option<u32>,
    cancel: Option<tokio_util::sync::CancellationToken>,
) -> Result<String, String> {
    let (_, access_token_url, _) = get_urls(domain);
    let client_id = client_id();
    let device_code = device_code.to_string();

    poll_device_code_flow(PollOptions {
        interval_seconds: interval,
        expires_in_seconds: expires_in,
        cancel,
        poll: Box::new(move || {
            let access_token_url = access_token_url.clone();
            let client_id = client_id.clone();
            let device_code = device_code.clone();
            Box::pin(async move {
                let raw = post_form(
                    &access_token_url,
                    &[
                        ("Accept", "application/json"),
                        ("User-Agent", "GitHubCopilotChat/0.35.0"),
                    ],
                    &[
                        ("client_id", &client_id),
                        ("device_code", &device_code),
                        ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
                    ],
                )
                .await?;

                if let Some(token) = raw.get("access_token").and_then(|t| t.as_str()) {
                    return Ok(PollStatus::Complete(token.to_string()));
                }

                if let Some(error) = raw.get("error").and_then(|e| e.as_str()) {
                    match error {
                        "authorization_pending" => return Ok(PollStatus::Pending),
                        "slow_down" => return Ok(PollStatus::SlowDown),
                        _ => {
                            let desc = raw
                                .get("error_description")
                                .and_then(|d| d.as_str())
                                .unwrap_or("");
                            return Ok(PollStatus::Failed(format!(
                                "Device flow failed: {}{}",
                                error,
                                if desc.is_empty() {
                                    String::new()
                                } else {
                                    format!(": {}", desc)
                                }
                            )));
                        }
                    }
                }

                Ok(PollStatus::Failed(
                    "Invalid device token response".to_string(),
                ))
            })
        }),
    })
    .await
}

/// Exchange GitHub access token for a Copilot token.
async fn exchange_for_copilot_token(
    github_token: &str,
    enterprise_domain: Option<&str>,
) -> Result<serde_json::Value, String> {
    let domain = enterprise_domain.unwrap_or("github.com");
    let (_, _, copilot_token_url) = get_urls(domain);

    let auth_val = format!("Bearer {}", github_token);
    let mut headers: Vec<(&str, &str)> =
        vec![("Accept", "application/json"), ("Authorization", &auth_val)];
    for (k, v) in COPILOT_HEADERS {
        headers.push((k, v));
    }

    fetch_json(&copilot_token_url, &headers).await
}

/// Refresh the Copilot token using the refresh token.
async fn refresh_copilot_access_token(
    refresh_token: &str,
    enterprise_domain: Option<&str>,
) -> Result<serde_json::Value, String> {
    let domain = enterprise_domain.unwrap_or("github.com");
    let (_, _, copilot_token_url) = get_urls(domain);

    let auth_val = format!("Bearer {}", refresh_token);
    let mut headers: Vec<(&str, &str)> =
        vec![("Accept", "application/json"), ("Authorization", &auth_val)];
    for (k, v) in COPILOT_HEADERS {
        headers.push((k, v));
    }

    fetch_json(&copilot_token_url, &headers).await
}

/// Fetch available Copilot model IDs.
async fn fetch_available_model_ids(
    copilot_token: &str,
    enterprise_domain: Option<&str>,
) -> Result<Vec<String>, String> {
    let base_url = get_copilot_base_url(Some(copilot_token), enterprise_domain);
    let url = format!("{}/models", base_url);

    let auth_val = format!("Bearer {}", copilot_token);
    let mut headers: Vec<(&str, &str)> =
        vec![("Accept", "application/json"), ("Authorization", &auth_val)];
    for (k, v) in COPILOT_HEADERS {
        headers.push((k, v));
    }
    headers.push(("X-GitHub-Api-Version", COPILOT_API_VERSION));

    let raw = fetch_json(&url, &headers).await?;

    // Parse model list
    let data = raw.get("data").and_then(|d| d.as_array());
    match data {
        Some(items) => {
            let ids: Vec<String> = items
                .iter()
                .filter(|item| {
                    let policy = item.get("policy").and_then(|p| p.as_object());
                    let capabilities = item.get("capabilities").and_then(|c| c.as_object());
                    let supports = capabilities
                        .and_then(|c| c.get("supports"))
                        .and_then(|s| s.as_object());
                    let model_picker_enabled = item
                        .get("model_picker_enabled")
                        .and_then(|v| v.as_bool())
                        .unwrap_or(false);
                    let policy_enabled =
                        policy.and_then(|p| p.get("state")).and_then(|s| s.as_str())
                            != Some("disabled");
                    let supports_tool_calls = supports
                        .and_then(|s| s.get("tool_calls"))
                        .and_then(|v| v.as_bool())
                        .unwrap_or(true);
                    model_picker_enabled && policy_enabled && supports_tool_calls
                })
                .filter_map(|item| {
                    item.get("id")
                        .and_then(|id| id.as_str())
                        .map(|s| s.to_string())
                })
                .collect();
            Ok(ids)
        }
        None => Err("Invalid Copilot models response: missing data array".to_string()),
    }
}

/// Enable a model via the policy endpoint.
async fn enable_model(
    copilot_token: &str,
    model_id: &str,
    enterprise_domain: Option<&str>,
) -> Result<bool, String> {
    let base_url = get_copilot_base_url(Some(copilot_token), enterprise_domain);
    let url = format!("{}/models/{}/policy", base_url, model_id);

    let client = reqwest::Client::new();
    let auth_header = format!("Bearer {}", copilot_token);
    let mut req = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Authorization", &auth_header)
        .header("openai-intent", "chat-policy")
        .header("x-interaction-type", "chat-policy");
    for (k, v) in COPILOT_HEADERS {
        req = req.header(*k, *v);
    }
    let body = serde_json::json!({"state": "enabled"});
    let resp = req.json(&body).send().await;
    Ok(resp.map(|r| r.status().is_success()).unwrap_or(false))
}

/// Enable all known GitHub Copilot models after login.
async fn enable_all_models(
    copilot_token: &str,
    enterprise_domain: Option<&str>,
    on_progress: &mut (dyn FnMut(String, bool) + Send),
) {
    // Known Copilot model IDs from GITHUB_COPILOT_MODELS
    let known_models = [
        "claude-sonnet-4-20250514",
        "claude-sonnet-4.5-preview-20250619",
        "claude-opus-4-20250514",
        "claude-opus-4.5-preview-20250619",
        "claude-haiku-4-20250514",
        "claude-haiku-4.5-preview-20250619",
        "claude-fable-5",
        "claude-haiku-4.5",
        "claude-opus-4.5",
        "claude-sonnet-4",
        "gpt-4o",
        "gpt-4o-mini",
        "o3",
        "o4-mini",
        "gemini-2.5-flash-001",
        "gemini-2.5-pro-001",
    ];

    // Pi-compatible parallel enabling via join_all
    use futures::future::join_all;
    let tasks: Vec<_> = known_models
        .iter()
        .map(|model_id| {
            let token = copilot_token.to_string();
            let domain = enterprise_domain.map(|s| s.to_string());
            let mid = model_id.to_string();
            async move {
                let success = enable_model(&token, &mid, domain.as_deref())
                    .await
                    .unwrap_or(false);
                (mid, success)
            }
        })
        .collect();

    let results = join_all(tasks).await;
    for (model_id, success) in results {
        on_progress(model_id, success);
    }
}

// ── OAuthProvider implementation ───────────────────────────────────

pub struct GitHubCopilotOAuth;

#[async_trait]
impl OAuthProvider for GitHubCopilotOAuth {
    fn id(&self) -> &str {
        "github-copilot"
    }

    fn name(&self) -> &str {
        "GitHub Copilot"
    }

    async fn login(
        &self,
        callbacks: &mut OAuthLoginCallbacks<'_>,
    ) -> Result<OAuthCredentials, String> {
        // 1. Prompt for enterprise domain
        let input = (callbacks.on_prompt)(OAuthPrompt::Text {
            message: "GitHub Enterprise URL/domain (blank for github.com)".to_string(),
            placeholder: Some("company.ghe.com".to_string()),
            allow_empty: true,
        })?;

        if let Some(ref cancel) = callbacks.signal
            && cancel.is_cancelled()
        {
            return Err("Login cancelled".to_string());
        }

        let trimmed = input.trim().to_string();
        let enterprise_domain = if trimmed.is_empty() {
            None
        } else {
            normalize_domain(&trimmed)
        };
        if !trimmed.is_empty() && enterprise_domain.is_none() {
            return Err("Invalid GitHub Enterprise URL/domain".to_string());
        }
        let domain = enterprise_domain
            .clone()
            .unwrap_or_else(|| "github.com".to_string());

        // 2. Start device flow
        let device_resp = start_device_flow(&domain).await?;

        let device_code = device_resp
            .get("device_code")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "Missing device_code in response".to_string())?
            .to_string();
        let user_code = device_resp
            .get("user_code")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "Missing user_code in response".to_string())?
            .to_string();
        let verification_uri = device_resp
            .get("verification_uri")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "Missing verification_uri in response".to_string())?
            .to_string();
        let interval = device_resp
            .get("interval")
            .and_then(|v| v.as_u64())
            .map(|v| v as u32);
        let expires_in = device_resp
            .get("expires_in")
            .and_then(|v| v.as_u64())
            .map(|v| v as u32);

        // Validate verification_uri is a trusted URL
        if let Ok(parsed) = url::Url::parse(&verification_uri) {
            if parsed.scheme() != "https" && parsed.scheme() != "http" {
                return Err("Untrusted verification_uri in device code response".to_string());
            }
        } else {
            return Err("Invalid verification_uri in device code response".to_string());
        }

        // 3. Notify user with device code info
        (callbacks.on_device_code)(DeviceCodeInfo {
            user_code: user_code.clone(),
            verification_uri: verification_uri.clone(),
            interval_seconds: interval,
            expires_in_seconds: expires_in,
        });

        // 4. Poll for GitHub access token
        let cancel = callbacks.signal.clone();
        let github_access_token =
            poll_for_github_access_token(&domain, &device_code, interval, expires_in, cancel)
                .await?;

        // 5. Exchange for Copilot token
        let copilot_resp =
            exchange_for_copilot_token(&github_access_token, enterprise_domain.as_deref()).await?;

        let token = copilot_resp
            .get("token")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "Missing token in Copilot response".to_string())?
            .to_string();
        let expires_at = copilot_resp
            .get("expires_at")
            .and_then(|v| v.as_f64())
            .ok_or_else(|| "Missing expires_at in Copilot response".to_string())?
            as i64;

        // 6. Enable all models
        (callbacks.on_progress)("Enabling models...".to_string());
        enable_all_models(
            &token,
            enterprise_domain.as_deref(),
            &mut |model, success| {
                (callbacks.on_progress)(format!(
                    "Model {}: {}",
                    model,
                    if success { "enabled" } else { "skipped" }
                ));
            },
        )
        .await;

        // 7. Fetch available model IDs
        let available_ids = fetch_available_model_ids(&token, enterprise_domain.as_deref())
            .await
            .unwrap_or_default();

        let mut extra = HashMap::new();
        extra.insert("availableModelIds".to_string(), available_ids.join(","));
        if let Some(ref ed) = enterprise_domain {
            extra.insert("enterpriseUrl".to_string(), ed.clone());
        }

        Ok(OAuthCredentials {
            access: token.clone(),
            refresh: github_access_token,
            expires: (expires_at * 1000) - (5 * 60 * 1000), // 5 min buffer
            enterprise_url: enterprise_domain,
            extra,
        })
    }

    async fn refresh_token(
        &self,
        credentials: &OAuthCredentials,
    ) -> Result<OAuthCredentials, String> {
        let enterprise_domain = credentials.enterprise_url.as_deref();
        let raw = refresh_copilot_access_token(&credentials.refresh, enterprise_domain).await?;

        let token = raw
            .get("token")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "Missing token in Copilot refresh response".to_string())?
            .to_string();
        let expires_at = raw
            .get("expires_at")
            .and_then(|v| v.as_f64())
            .ok_or_else(|| "Missing expires_at in Copilot refresh response".to_string())?
            as i64;

        // Fetch available model IDs
        let available_ids = fetch_available_model_ids(&token, enterprise_domain)
            .await
            .unwrap_or_default();

        let mut extra = credentials.extra.clone();
        extra.insert("availableModelIds".to_string(), available_ids.join(","));

        Ok(OAuthCredentials {
            access: token,
            refresh: credentials.refresh.clone(),
            expires: (expires_at * 1000) - (5 * 60 * 1000),
            enterprise_url: credentials.enterprise_url.clone(),
            extra,
        })
    }

    fn get_api_key<'a>(&self, credentials: &'a OAuthCredentials) -> &'a str {
        &credentials.access
    }
}