aix-rs 1.0.0

Manage AI gateway profiles and launch AI coding tools with the right credentials
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
mod report;

use crate::commands::env::resolve_profile;
use crate::commands::gate::report::GateReport;
use crate::commands::ProfileSelection;
use crate::config::{self, Config};
use crate::error::{AixError, GateFailureCategory};
use crate::gateway::OpenAiClient;
use color_eyre::Result;
use serde_json::{json, Value};
use std::path::PathBuf;
use std::time::Duration;

pub(crate) struct GateOptions {
    pub(crate) selection: ProfileSelection,
    pub(crate) explicit_profile: Option<String>,
    pub(crate) timeout: Duration,
    pub(crate) config_path: Option<PathBuf>,
    pub(crate) policy: String,
    pub(crate) json: bool,
}

pub(crate) async fn run(options: GateOptions) -> Result<()> {
    let preflight = preflight(options).await;
    let failure_category = preflight.report.failure_category;
    report::print_report(&preflight.report, preflight.json)?;

    match failure_category {
        Some(category) => Err(AixError::GateChecksFailed { category }.into()),
        None => Ok(()),
    }
}

struct PreflightReport {
    report: GateReport,
    json: bool,
}

enum ModelDiscovery {
    Available(Vec<String>),
    Configured(Vec<String>),
    Invalid,
    Unavailable,
}

enum ModelRequirement {
    PolicyUnavailable,
    Unrestricted,
    ProfileUnavailable,
    Required(Vec<String>),
}

async fn preflight(options: GateOptions) -> PreflightReport {
    let GateOptions {
        selection,
        explicit_profile,
        timeout,
        config_path,
        policy: policy_name,
        json: json_output,
    } = options;
    let mut report = GateReport::new();

    let config_path = match config::find_config_path(config_path.as_deref()) {
        Ok(Some(path)) => path,
        Ok(None) => {
            report.fail(
                "config",
                "no config file could be resolved",
                None,
                GateFailureCategory::Config,
            );
            skip_after_config(&mut report);
            return PreflightReport {
                report,
                json: json_output,
            };
        }
        Err(_) => {
            report.fail(
                "config",
                "config path resolution failed",
                None,
                GateFailureCategory::Config,
            );
            skip_after_config(&mut report);
            return PreflightReport {
                report,
                json: json_output,
            };
        }
    };

    let cfg = match config::load(&config_path) {
        Ok(cfg) => cfg,
        Err(_) => {
            report.fail(
                "config",
                "config file could not be loaded",
                None,
                GateFailureCategory::Config,
            );
            skip_after_config(&mut report);
            return PreflightReport {
                report,
                json: json_output,
            };
        }
    };
    if config::validate(&cfg).is_err() {
        report.fail(
            "config",
            "config failed structural validation",
            None,
            GateFailureCategory::Config,
        );
        skip_after_config(&mut report);
        return PreflightReport {
            report,
            json: json_output,
        };
    }
    if config::load_env_files(&cfg).is_err() {
        report.fail(
            "config",
            "a configured environment file could not be loaded",
            None,
            GateFailureCategory::Config,
        );
        skip_after_config(&mut report);
        return PreflightReport {
            report,
            json: json_output,
        };
    }
    report.pass(
        "config",
        "config loaded, validated, and env files loaded",
        None,
    );

    let policy = cfg.run_policies.get(&policy_name);
    if policy.is_some() {
        report.pass("policy", "named run policy exists", None);
    } else {
        report.fail(
            "policy",
            "named run policy is not defined in the config",
            Some(json!({ "name": policy_name })),
            GateFailureCategory::Config,
        );
    }

    let policy_profile = policy.and_then(|policy| policy.profile.clone());
    let profile_conflict = policy_profile
        .as_deref()
        .zip(explicit_profile.as_deref())
        .is_some_and(|(policy_profile, selected)| policy_profile != selected);
    let selected_profile = policy_profile.or(selection.profile);
    let resolved_profile = resolve_profile(
        ProfileSelection {
            profile: selected_profile,
            non_interactive: true,
        },
        &cfg,
    )
    .ok()
    .and_then(|name| cfg.profiles.get(&name).map(|profile| (name, profile)));

    if let Some((profile_name, _)) = &resolved_profile {
        if profile_conflict {
            report.fail(
                "profile",
                "selected profile conflicts with the policy's fixed profile",
                Some(json!({ "effective_profile": profile_name })),
                GateFailureCategory::Config,
            );
        } else {
            report.pass(
                "profile",
                "effective profile resolved without prompting",
                Some(json!({ "name": profile_name })),
            );
        }
    } else {
        report.fail(
            "profile",
            "effective profile could not be resolved without prompting",
            None,
            GateFailureCategory::Config,
        );
    }

    let chatgpt_profile = resolved_profile
        .as_ref()
        .is_some_and(|(_, profile)| profile.auth.is_chatgpt());
    let (api_key, base_url) = match &resolved_profile {
        Some((profile_name, profile)) if profile.auth.is_chatgpt() => {
            let auth_status = crate::auth::AuthService::new(timeout)
                .and_then(|service| service.status(profile_name, &profile.auth));
            match auth_status {
                Ok(status)
                    if status.connected && status.chatgpt_plan_usage_enabled == Some(true) =>
                {
                    report.pass(
                        "credentials",
                        "ChatGPT profile is connected with plan usage enabled",
                        Some(json!({
                            "auth_type": "chatgpt",
                            "state": status.state,
                            "connected": status.connected,
                            "plan_usage_enabled": status.chatgpt_plan_usage_enabled,
                        })),
                    );
                }
                Ok(status) => report.fail(
                    "credentials",
                    "ChatGPT profile is signed out or does not have plan usage enabled",
                    Some(json!({
                        "auth_type": "chatgpt",
                        "state": status.state,
                        "connected": status.connected,
                        "plan_usage_enabled": status.chatgpt_plan_usage_enabled,
                    })),
                    GateFailureCategory::Authentication,
                ),
                Err(_) => report.fail(
                    "credentials",
                    "ChatGPT authentication status could not be read",
                    Some(json!({ "auth_type": "chatgpt" })),
                    GateFailureCategory::Secret,
                ),
            }
            (None, None)
        }
        Some((_, profile)) => {
            let api_key = profile
                .resolve_api_key()
                .ok()
                .filter(|value| !value.expose_secret().trim().is_empty());
            let base_url = config::resolve_base_url(profile, &cfg.endpoint)
                .ok()
                .filter(|value| !value.expose_secret().trim().is_empty());
            let details = json!({
                "api_key": if api_key.is_some() { "resolved" } else { "unavailable" },
                "base_url": if base_url.is_some() { "resolved" } else { "unavailable" }
            });
            if api_key.is_some() && base_url.is_some() {
                report.pass(
                    "credentials",
                    "profile API key and base URL resolved",
                    Some(details),
                );
            } else {
                report.fail(
                    "credentials",
                    "profile API key or base URL could not be resolved",
                    Some(details),
                    GateFailureCategory::Secret,
                );
            }
            (api_key, base_url)
        }
        None => {
            report.skipped("credentials", "effective profile did not resolve");
            (None, None)
        }
    };

    let model_requirement = match (policy, resolved_profile.as_ref()) {
        (None, _) => ModelRequirement::PolicyUnavailable,
        (Some(policy), _) if policy.allowed_models.is_none() => ModelRequirement::Unrestricted,
        (Some(_), None) => ModelRequirement::ProfileUnavailable,
        (Some(policy), Some((_, profile))) => {
            let models = policy
                .allowed_models
                .as_ref()
                .expect("unrestricted policies returned above");
            let mut resolved = Vec::with_capacity(models.len());
            for model in models {
                let model = config::resolve_model(Some(model), &cfg, profile)
                    .expect("validated model names always resolve");
                if !resolved.contains(&model) {
                    resolved.push(model);
                }
            }
            ModelRequirement::Required(resolved)
        }
    };

    let local_model_enforcement_required =
        policy.is_some_and(|policy| policy.allowed_models.is_some());
    let chatgpt_model_enforcement_required =
        policy.is_some_and(|policy| policy.allowed_models.is_some());
    let discovered_models = if chatgpt_profile {
        if has_chatgpt_local_responses_adapter(&cfg) {
            report.pass(
                "gateway",
                "configured ChatGPT local Responses adapter is available for local policy enforcement",
                None,
            );
        } else if chatgpt_model_enforcement_required {
            report.fail(
                "gateway",
                "ChatGPT run policies require a configured local Responses adapter",
                None,
                GateFailureCategory::Config,
            );
        } else {
            report.not_applicable(
                "gateway",
                "no local model restriction requires a specific ChatGPT tool path",
            );
        }
        ModelDiscovery::Available(
            crate::commands::launch::chatgpt_model_ids()
                .iter()
                .map(|model| (*model).to_string())
                .collect(),
        )
    } else if local_model_enforcement_required {
        if api_key.is_some() && base_url.is_some() {
            report.pass(
                "gateway",
                "profile credentials resolve for local request-time model enforcement",
                None,
            );
            match &model_requirement {
                ModelRequirement::Required(required) => {
                    ModelDiscovery::Configured(required.clone())
                }
                _ => ModelDiscovery::Unavailable,
            }
        } else {
            report.skipped("gateway", "profile credentials did not resolve");
            ModelDiscovery::Unavailable
        }
    } else {
        match (&api_key, &base_url) {
            (Some(api_key), Some(base_url)) => {
                match OpenAiClient::with_timeout(
                    base_url.expose_secret(),
                    api_key.expose_secret(),
                    timeout,
                )
                .models()
                .await
                {
                    Ok(response) => {
                        report.pass(
                            "gateway",
                            "authenticated model-discovery request reached the gateway",
                            None,
                        );
                        match crate::commands::models::extract_models(response) {
                            Ok(models) => ModelDiscovery::Available(
                                models.into_iter().map(|model| model.id).collect(),
                            ),
                            Err(_) => ModelDiscovery::Invalid,
                        }
                    }
                    Err(AixError::GatewayProtocolError(_)) => {
                        report.pass(
                            "gateway",
                            "authenticated model-discovery request reached the gateway",
                            None,
                        );
                        ModelDiscovery::Invalid
                    }
                    Err(error) => {
                        let (category, message, details) = gateway_failure(&error);
                        report.fail("gateway", message, details, category);
                        ModelDiscovery::Unavailable
                    }
                }
            }
            _ => {
                report.skipped("gateway", "profile credentials did not resolve");
                ModelDiscovery::Unavailable
            }
        }
    };

    match &model_requirement {
        ModelRequirement::PolicyUnavailable => {
            report.skipped("models", "named run policy did not resolve")
        }
        ModelRequirement::Unrestricted => {
            report.not_applicable("models", "policy does not restrict the allowed model set")
        }
        ModelRequirement::ProfileUnavailable => {
            report.skipped("models", "effective profile did not resolve")
        }
        ModelRequirement::Required(required) => match &discovered_models {
            ModelDiscovery::Unavailable => {
                report.skipped("models", "gateway request could not be completed")
            }
            ModelDiscovery::Invalid => report.fail(
                "models",
                "gateway returned an invalid model-discovery response",
                Some(json!({ "required": required })),
                GateFailureCategory::Network,
            ),
            ModelDiscovery::Available(available) | ModelDiscovery::Configured(available) => {
                let missing: Vec<_> = required
                    .iter()
                    .filter(|model| !available.contains(model))
                    .cloned()
                    .collect();
                let details = json!({ "required": required, "missing": missing });
                if missing.is_empty() {
                    match &discovered_models {
                        ModelDiscovery::Configured(_) => report.pass(
                            "models",
                            format!(
                                "{} configured model ID(s) resolve for local request-time enforcement",
                                required.len()
                            ),
                            Some(json!({ "required": required })),
                        ),
                        _ => report.pass(
                            "models",
                            format!("{} required model(s) are available", required.len()),
                            Some(details),
                        ),
                    }
                } else {
                    report.fail(
                        "models",
                        format!("{} required model(s) are unavailable", missing.len()),
                        Some(details),
                        GateFailureCategory::Budget,
                    );
                }
            }
        },
    }

    match policy {
        None => report.skipped("duration", "named run policy did not resolve"),
        Some(policy) => {
            let can_set_deadline = crate::duration::to_std_duration(&policy.max_duration)
                .is_some_and(|duration| std::time::Instant::now().checked_add(duration).is_some());
            if can_set_deadline {
                report.pass(
                    "duration",
                    "managed run process and local gateway can enforce the maximum duration",
                    Some(json!({ "max_duration": policy.max_duration })),
                );
            } else {
                report.fail(
                    "duration",
                    "maximum duration cannot be enforced by the managed run process",
                    None,
                    GateFailureCategory::Config,
                );
            }
        }
    }

    if !local_model_enforcement_required {
        report.not_applicable(
            "local_gateway",
            "policy does not require local allowed-model enforcement",
        );
    } else if chatgpt_profile {
        if has_chatgpt_local_responses_adapter(&cfg) {
            report.pass(
                "local_gateway",
                "configured ChatGPT local Responses adapter can enforce allowed models",
                None,
            );
        } else {
            report.fail(
                "local_gateway",
                "no configured ChatGPT local Responses adapter can enforce allowed models",
                None,
                GateFailureCategory::Config,
            );
        }
    } else if has_api_key_local_gateway_tool(&cfg) {
        report.pass(
            "local_gateway",
            "a configured local-gateway tool can enforce allowed models at request time",
            None,
        );
    } else {
        report.fail(
            "local_gateway",
            "allowed-model policy requires a configured local-gateway tool",
            None,
            GateFailureCategory::Config,
        );
    }

    PreflightReport {
        report,
        json: json_output,
    }
}

fn skip_after_config(report: &mut GateReport) {
    report.skipped("policy", "config did not pass");
    report.skipped("profile", "config did not pass");
    report.skipped("credentials", "config did not pass");
    report.skipped("gateway", "config did not pass");
    report.skipped("models", "config did not pass");
    report.skipped("duration", "config did not pass");
    report.skipped("local_gateway", "config did not pass");
}

fn has_chatgpt_local_responses_adapter(config: &Config) -> bool {
    config
        .tools
        .iter()
        .any(|(name, tool)| tool.chatgpt_responses_adapter(name).is_some())
}

fn has_api_key_local_gateway_tool(config: &Config) -> bool {
    config.tools.values().any(|tool| {
        tool.local_gateway
            && (tool.api_format.supports_openai() || tool.api_format.supports_anthropic())
    })
}

fn gateway_failure(error: &AixError) -> (GateFailureCategory, String, Option<Value>) {
    match error {
        AixError::GatewayError { status, .. } | AixError::GatewayRequestFailed { status } => {
            if matches!(status, 401 | 403) {
                (
                    GateFailureCategory::Authentication,
                    format!("gateway rejected authentication (HTTP {status})"),
                    Some(json!({ "http_status": status })),
                )
            } else {
                (
                    if *status == 402 {
                        GateFailureCategory::Budget
                    } else {
                        GateFailureCategory::Network
                    },
                    format!("gateway returned HTTP {status}"),
                    Some(json!({ "http_status": status })),
                )
            }
        }
        AixError::HttpError(error) if error.is_timeout() => (
            GateFailureCategory::Network,
            "gateway model-discovery request timed out".to_string(),
            None,
        ),
        _ => (
            GateFailureCategory::Network,
            "gateway model-discovery request failed".to_string(),
            None,
        ),
    }
}

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

    #[test]
    fn budget_rejection_from_gateway_retains_budget_exit_category() {
        let (category, message, _) =
            gateway_failure(&AixError::GatewayRequestFailed { status: 402 });
        assert!(matches!(category, GateFailureCategory::Budget));
        assert!(message.contains("402"));
    }
}