oxi-ai 0.5.0

Unified LLM API — multi-provider streaming interface for AI coding assistants
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
//! Environment variable-based API key resolution
//!
//! Provides comprehensive environment variable detection for various AI providers.
//! Provides comprehensive environment variable detection for various AI providers.

use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::env;
use std::fs;

/// Cache for Vertex ADC credentials check (expensive fs check)
static VERTEX_ADC_CHECK: Lazy<bool> = Lazy::new(check_vertex_adc_credentials);

/// Check if Vertex AI Application Default Credentials exist
fn check_vertex_adc_credentials() -> bool {
    // Check GOOGLE_APPLICATION_CREDENTIALS env var first
    if let Ok(path) = env::var("GOOGLE_APPLICATION_CREDENTIALS") {
        return fs::metadata(&path).is_ok();
    }

    // Fall back to default ADC path
    let default_path =
        dirs::home_dir().map(|h| h.join(".config/gcloud/application_default_credentials.json"));

    default_path
        .map(|p| fs::metadata(p).is_ok())
        .unwrap_or(false)
}

/// Get a value from environment, supporting both std::env and /proc/self/environ fallback
/// for sandboxed environments (e.g., Bun compiled binaries on Linux)
fn get_env(key: &str) -> Option<String> {
    env::var(key).ok().or_else(|| get_proc_env(key))
}

/// Bun/Linux sandbox fallback: read from /proc/self/environ
#[allow(dead_code)]
fn get_proc_env(_key: &str) -> Option<String> {
    #[allow(unused_imports)]
    use std::os::unix::ffi::OsStrExt;

    // Only try this on Linux where Bun sandbox may empty process.env
    #[cfg(target_os = "linux")]
    {
        // If process.env has entries, no need for /proc fallback
        if !env::var("PATH").is_ok() || std::env::vars().count() > 0 {
            return None;
        }

        let Ok(contents) = fs::read_to_string("/proc/self/environ") else {
            return None;
        };

        for segment in contents.split('\0') {
            if let Some(pos) = segment.find('=') {
                let k = segment[..pos].as_bytes();
                let v = &segment[pos + 1..];
                if k == key.as_bytes() {
                    return Some(v.to_string());
                }
            }
        }
    }

    None
}

/// Get environment variables that can provide an API key for a provider
pub fn find_env_keys(provider: &str) -> Option<Vec<&'static str>> {
    let keys = match provider {
        // GitHub Copilot: multiple possible env vars
        "github-copilot" | "copilot" => vec!["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"],

        // Anthropic: OAuth token takes precedence over API key
        "anthropic" => vec!["ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_API_KEY"],

        // OpenAI variants
        "openai" | "openai-responses" => vec![
            "OPENAI_API_KEY",
            "AZURE_OPENAI_API_KEY", // Some deployments use this
        ],

        // Google/Gemini
        "google" | "gemini" => vec!["GEMINI_API_KEY", "GOOGLE_API_KEY"],

        // Google Vertex AI
        "vertex" | "google-vertex" => vec!["GOOGLE_CLOUD_API_KEY"],

        // Azure
        "azure" | "azure-openai" => vec!["AZURE_OPENAI_API_KEY"],

        // Groq
        "groq" => vec!["GROQ_API_KEY"],

        // Cerebras
        "cerebras" => vec!["CEREBRAS_API_KEY"],

        // xAI / Grok
        "xai" => vec!["XAI_API_KEY"],

        // OpenRouter
        "openrouter" => vec!["OPENROUTER_API_KEY"],

        // Vercel AI Gateway
        "vercel-ai-gateway" => vec!["AI_GATEWAY_API_KEY"],

        // ZAI
        "zai" => vec!["ZAI_API_KEY"],

        // Mistral
        "mistral" => vec!["MISTRAL_API_KEY"],

        // MiniMax (China)
        "minimax" | "minimax-cn" => vec!["MINIMAX_API_KEY", "MINIMAX_CN_API_KEY"],

        // Moonshot AI / Kimi (China)
        "moonshotai" | "moonshotai-cn" | "kimi" | "kimi-coding" => {
            vec!["MOONSHOT_API_KEY", "KIMI_API_KEY"]
        }

        // Hugging Face
        "huggingface" | "hf" => vec!["HF_TOKEN", "HUGGINGFACE_TOKEN"],

        // Fireworks AI
        "fireworks" => vec!["FIREWORKS_API_KEY"],

        // DeepSeek
        "deepseek" => vec!["DEEPSEEK_API_KEY"],

        // OpenCode
        "opencode" => vec!["OPENCODE_API_KEY"],

        // Xiaomi
        "xiaomi" => vec!["XIAOMI_API_KEY"],

        // Cloudflare Workers AI
        "cloudflare" | "cloudflare-workers-ai" | "cloudflare-ai-gateway" => {
            vec!["CLOUDFLARE_API_KEY", "CLOUDFLARE_AI_GATEWAY_API_KEY"]
        }

        _ => return None,
    };

    Some(keys)
}

/// Check if any environment variable is set for a provider
pub fn has_env_key(provider: &str) -> bool {
    find_env_keys(provider)
        .map(|keys| keys.iter().any(|k| get_env(k).is_some()))
        .unwrap_or(false)
}

/// Get first available environment variable value for a provider
fn first_of(keys: &[&str]) -> Option<String> {
    for key in keys {
        if let Some(value) = get_env(key) {
            if !value.is_empty() {
                return Some(value);
            }
        }
    }
    None
}

/// Get API key from environment variables for a provider
///
/// Returns `Some("<authenticated>")` for providers that support ambient credentials
/// (e.g., AWS IAM roles, Google ADC) rather than explicit API keys.
pub fn get_env_api_key(provider: &str) -> Option<String> {
    let keys = find_env_keys(provider)?;
    let key = first_of(&keys)?;

    // Filter out placeholder values
    if key == "<authenticated>" || key.starts_with("sk-") && key.len() < 10 {
        return None;
    }

    Some(key)
}

/// Check Vertex AI-specific ambient credentials
///
/// Vertex AI supports Application Default Credentials (ADC) configured via:
/// - `gcloud auth application-default login`
/// - `GOOGLE_APPLICATION_CREDENTIALS` pointing to service account JSON
///
/// Returns true if all required ADC components are present.
pub fn has_vertex_adc() -> bool {
    *VERTEX_ADC_CHECK
}

/// Check if Vertex AI has all required components for ADC authentication
pub fn has_vertex_adc_full() -> bool {
    // Check credentials file exists
    let has_creds = has_vertex_adc();

    // Check project ID
    let has_project = get_env("GOOGLE_CLOUD_PROJECT")
        .or_else(|| get_env("GCLOUD_PROJECT"))
        .is_some();

    // Check location
    let has_location = get_env("GOOGLE_CLOUD_LOCATION").is_some();

    has_creds && has_project && has_location
}

/// Check Amazon Bedrock ambient credentials
///
/// Bedrock supports multiple credential sources:
/// 1. AWS_PROFILE - named profile from ~/.aws/credentials
/// 2. AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY - standard IAM keys
/// 3. AWS_BEARER_TOKEN_BEDROCK - Bedrock bearer token
/// 4. AWS_CONTAINER_CREDENTIALS_RELATIVE_URI - ECS task roles
/// 5. AWS_CONTAINER_CREDENTIALS_FULL_URI - ECS task roles (full URI)
/// 6. AWS_WEB_IDENTITY_TOKEN_FILE - IRSA (IAM Roles for Service Accounts)
pub fn has_bedrock_creds() -> bool {
    // Explicit API key scenario
    if get_env("AWS_ACCESS_KEY_ID").is_some() && get_env("AWS_SECRET_ACCESS_KEY").is_some() {
        return true;
    }

    // Named profile
    if get_env("AWS_PROFILE").is_some() {
        return true;
    }

    // Bedrock bearer token
    if get_env("AWS_BEARER_TOKEN_BEDROCK").is_some() {
        return true;
    }

    // ECS container credentials (IRSA)
    if get_env("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI").is_some()
        || get_env("AWS_CONTAINER_CREDENTIALS_FULL_URI").is_some()
    {
        return true;
    }

    // Web identity token (IRSA)
    if get_env("AWS_WEB_IDENTITY_TOKEN_FILE").is_some() {
        return true;
    }

    false
}

/// Check if Bedrock has full credential configuration
pub fn has_bedrock_creds_full() -> bool {
    // For explicit API key auth, need both key ID and secret
    if get_env("AWS_ACCESS_KEY_ID").is_some() && get_env("AWS_SECRET_ACCESS_KEY").is_some() {
        return true;
    }

    // For profile-based auth, just need the profile
    if get_env("AWS_PROFILE").is_some() {
        return true;
    }

    // For ECS/IRSA, we need the credential endpoint/file
    if get_env("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI").is_some()
        || get_env("AWS_CONTAINER_CREDENTIALS_FULL_URI").is_some()
        || get_env("AWS_WEB_IDENTITY_TOKEN_FILE").is_some()
    {
        return true;
    }

    // Bearer token
    if get_env("AWS_BEARER_TOKEN_BEDROCK").is_some() {
        return true;
    }

    false
}

/// Get all providers with environment variable credentials
pub fn get_all_env_keys() -> HashMap<String, String> {
    let mut result = HashMap::new();

    // Map provider names to their possible env vars
    let mappings: [(&str, fn() -> Option<String>); 17] = [
        ("anthropic", || {
            first_of(&["ANTHROPIC_API_KEY", "ANTHROPIC_OAUTH_TOKEN"])
        }),
        ("openai", || first_of(&["OPENAI_API_KEY"])),
        ("github-copilot", || {
            first_of(&["GITHUB_TOKEN", "GH_TOKEN", "COPILOT_GITHUB_TOKEN"])
        }),
        ("google", || first_of(&["GEMINI_API_KEY"])),
        ("vertex", || first_of(&["GOOGLE_CLOUD_API_KEY"])),
        ("groq", || first_of(&["GROQ_API_KEY"])),
        ("cerebras", || first_of(&["CEREBRAS_API_KEY"])),
        ("xai", || first_of(&["XAI_API_KEY"])),
        ("openrouter", || first_of(&["OPENROUTER_API_KEY"])),
        ("mistral", || first_of(&["MISTRAL_API_KEY"])),
        ("deepseek", || first_of(&["DEEPSEEK_API_KEY"])),
        ("azure", || first_of(&["AZURE_OPENAI_API_KEY"])),
        ("cloudflare", || first_of(&["CLOUDFLARE_API_KEY"])),
        ("huggingface", || first_of(&["HF_TOKEN"])),
        ("fireworks", || first_of(&["FIREWORKS_API_KEY"])),
        ("moonshotai", || first_of(&["MOONSHOT_API_KEY"])),
        ("bedrock", || {
            first_of(&["AWS_ACCESS_KEY_ID", "AWS_PROFILE"])
        }),
    ];

    for (provider, get_key) in mappings.iter() {
        if let Some(value) = get_key() {
            result.insert(provider.to_string(), value);
        }
    }

    result
}

/// Check if a provider supports OAuth tokens via environment
pub fn supports_oauth_env(provider: &str) -> bool {
    matches!(provider, "anthropic")
}

/// Get OAuth token from environment (for providers that support it)
pub fn get_oauth_env_token(provider: &str) -> Option<String> {
    match provider {
        "anthropic" => get_env("ANTHROPIC_OAUTH_TOKEN"),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;

    #[test]
    fn test_find_env_keys_anthropic() {
        let keys = find_env_keys("anthropic").unwrap();
        assert!(keys.contains(&"ANTHROPIC_API_KEY"));
        assert!(keys.contains(&"ANTHROPIC_OAUTH_TOKEN"));
    }

    #[test]
    fn test_find_env_keys_copilot() {
        let keys = find_env_keys("github-copilot").unwrap();
        assert!(keys.contains(&"COPILOT_GITHUB_TOKEN"));
        assert!(keys.contains(&"GH_TOKEN"));
        assert!(keys.contains(&"GITHUB_TOKEN"));
    }

    #[test]
    fn test_find_env_keys_unknown() {
        assert!(find_env_keys("unknown-provider").is_none());
    }

    #[test]
    fn test_first_of_returns_first() {
        env::set_var("TEST_FIRST_OF_1", "value1");
        env::set_var("TEST_FIRST_OF_2", "value2");

        let result = first_of(&["TEST_FIRST_OF_1", "TEST_FIRST_OF_2"]);
        assert_eq!(result, Some("value1".to_string()));

        env::remove_var("TEST_FIRST_OF_1");
        env::remove_var("TEST_FIRST_OF_2");
    }

    #[test]
    fn test_first_of_skips_empty() {
        env::set_var("TEST_FIRST_OF_SKIP", "");
        env::set_var("TEST_FIRST_OF_SECOND", "second");

        let result = first_of(&["TEST_FIRST_OF_SKIP", "TEST_FIRST_OF_SECOND"]);
        assert_eq!(result, Some("second".to_string()));

        env::remove_var("TEST_FIRST_OF_SKIP");
        env::remove_var("TEST_FIRST_OF_SECOND");
    }

    #[test]
    fn test_get_env_api_key() {
        env::set_var("ANTHROPIC_API_KEY", "sk-test-key-123");

        // Provider with known keys
        let result = get_env_api_key("anthropic");
        assert_eq!(result, Some("sk-test-key-123".to_string()));

        env::remove_var("ANTHROPIC_API_KEY");
    }

    #[test]
    fn test_has_env_key() {
        env::set_var("DEEPSEEK_API_KEY", "test-value");

        // Check that deepseek has an env key
        let result = has_env_key("deepseek"); // DEEPSEEK_API_KEY
        assert!(result);

        env::remove_var("DEEPSEEK_API_KEY");
    }

    #[test]
    fn test_vertex_adc_check_lazy() {
        // The lazy static should be evaluated on first access
        let result = *VERTEX_ADC_CHECK;
        // Just ensure it doesn't panic
        assert!(result == true || result == false);
    }

    #[test]
    fn test_get_all_env_keys() {
        // Use a unique key to avoid race conditions in parallel test runs
        let key = "OXI_TEST_GET_ALL_ENV_KEYS";
        env::set_var(key, "test-value");

        // Verify the function runs without panic and returns a map
        let all = get_all_env_keys();
        // The map may or may not contain entries depending on the test runner's
        // environment, but it should always be a valid HashMap
        assert!(all.len() <= 17); // max number of providers in the mapping

        env::remove_var(key);
    }

    #[test]
    fn test_oauth_env_token() {
        env::set_var("ANTHROPIC_OAUTH_TOKEN", "oauth-token-123");

        let result = get_oauth_env_token("anthropic");
        assert_eq!(result, Some("oauth-token-123".to_string()));

        let not_oauth = get_oauth_env_token("openai");
        assert!(not_oauth.is_none());

        env::remove_var("ANTHROPIC_OAUTH_TOKEN");
    }

    #[test]
    fn test_bedrock_creds_check() {
        // Without AWS credentials set, should return false
        let result = has_bedrock_creds();
        // Either true (if credentials exist) or false
        assert!(result == true || result == false);
    }

    #[test]
    fn test_supports_oauth_env() {
        assert!(supports_oauth_env("anthropic"));
        assert!(!supports_oauth_env("openai"));
        assert!(!supports_oauth_env("deepseek"));
    }

    #[test]
    fn test_google_legacy_alias() {
        // "google" should map to GEMINI_API_KEY
        let keys = find_env_keys("google");
        assert!(keys.is_some());
        assert!(keys.unwrap().contains(&"GEMINI_API_KEY"));
    }

    #[test]
    fn test_moonshotai_aliases() {
        let keys = find_env_keys("moonshotai");
        assert!(keys.is_some());
        assert!(keys.unwrap().contains(&"MOONSHOT_API_KEY"));

        let kimi = find_env_keys("kimi");
        assert!(kimi.is_some());
        assert!(kimi.unwrap().contains(&"KIMI_API_KEY"));
    }
}