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
use clap::{Args, Parser, Subcommand, ValueEnum};
use std::path::PathBuf;
use std::time::Duration;

#[derive(Parser)]
#[command(
    name = "aix",
    version,
    about = "profile-aware AI gateway client and tool launcher"
)]
pub struct Cli {
    /// Profile to use (overrides AIX_PROFILE env var)
    #[arg(long, short, global = true)]
    pub profile: Option<String>,

    /// Do not open an interactive profile picker
    #[arg(long, global = true)]
    pub non_interactive: bool,

    /// Maximum duration for each aix-owned HTTP request (for example, 750ms or 5s)
    #[arg(long, global = true, value_name = "DURATION", default_value = "30s", value_parser = parse_duration)]
    pub timeout: Duration,

    /// Path to config file (overrides AIX_CONFIG env var)
    #[arg(long, global = true, env = "AIX_CONFIG")]
    pub config: Option<PathBuf>,

    /// Emit a stable JSON envelope when supported by the command
    #[arg(long, global = true)]
    pub json: bool,

    #[command(subcommand)]
    pub command: Command,
}

fn parse_duration(value: &str) -> Result<Duration, String> {
    let (number, unit) = if let Some(number) = value.strip_suffix("ms") {
        (number, "ms")
    } else if let Some(number) = value.strip_suffix('s') {
        (number, "s")
    } else if let Some(number) = value.strip_suffix('m') {
        (number, "m")
    } else {
        return Err("expected a duration such as 750ms, 5s, or 2m".to_string());
    };
    let amount = number
        .parse::<u64>()
        .map_err(|_| "duration must be a positive whole number with ms, s, or m".to_string())?;
    if amount == 0 {
        return Err("duration must be greater than zero".to_string());
    }

    match unit {
        "ms" => Ok(Duration::from_millis(amount)),
        "s" => Ok(Duration::from_secs(amount)),
        "m" => amount
            .checked_mul(60)
            .map(Duration::from_secs)
            .ok_or_else(|| "duration is too large".to_string()),
        _ => unreachable!("unit is selected above"),
    }
}

#[derive(Subcommand)]
pub enum Command {
    /// Print shell code that installs the aix shell wrapper
    Init {
        /// Shell to generate integration code for
        shell: Shell,
    },
    /// Select or clear the active shell profile
    Use {
        /// Profile name to select
        #[arg(required_unless_present = "clear", conflicts_with = "clear")]
        profile: Option<String>,
        /// Unset AIX_PROFILE in the current shell
        #[arg(long)]
        clear: bool,
        /// Shell syntax for the assignment (defaults to sh)
        #[arg(long, value_enum, conflicts_with = "format")]
        shell: Option<Shell>,
        /// Output encoding instead of shell assignment syntax
        #[arg(long, value_enum, conflicts_with = "shell")]
        format: Option<UseFormat>,
    },
    /// Show the effective profile without opening the interactive picker
    Current {
        /// Output format; `short` is the same one-line output as the default
        #[arg(long, value_enum)]
        format: Option<CurrentFormat>,
    },
    /// List available profiles
    Profiles,
    /// List configured run policies
    Policies,
    /// Inspect a configured run policy
    Policy {
        #[command(subcommand)]
        action: PolicyAction,
    },
    /// Print environment variables for the selected profile
    Env {
        /// Profile name (positional; overrides the global --profile flag)
        profile: Option<String>,
        /// Output format
        #[arg(long, value_enum, default_value = "sh")]
        format: EnvFormat,
    },
    /// Launch a shell with profile environment set
    Shell {
        /// Profile name (positional; overrides the global --profile flag)
        profile: Option<String>,
        /// Print the shell command and variable names that would be set, without running
        #[arg(long)]
        dry_run: bool,
        /// Arguments after -- are not accepted; use `aix exec` to run a command directly
        #[arg(last = true, hide = true)]
        extra_args: Vec<String>,
    },
    /// Execute a command with profile environment set
    Exec {
        /// Profile name (positional; overrides the global --profile flag)
        profile: Option<String>,
        /// Print the command and variable names that would be set, without running
        #[arg(long)]
        dry_run: bool,
        /// Command and arguments to run (after --)
        #[arg(last = true)]
        args: Vec<String>,
    },
    /// Manage configuration
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// Manage ChatGPT authentication for a profile
    Auth {
        #[command(subcommand)]
        action: AuthAction,
    },
    /// Show current key spend and budget information from the gateway
    Spend {
        /// Profile name (positional; overrides the global --profile flag)
        profile: Option<String>,
        /// Always fetch fresh data, bypassing the cache (result is still cached)
        #[arg(long)]
        no_cache: bool,
    },
    /// Show profile, gateway connectivity, and budget status
    Status {
        /// Profile name (positional; overrides the global --profile flag)
        profile: Option<String>,
        /// Refresh spend data instead of using a cached response
        #[arg(long)]
        refresh: bool,
    },
    /// Check whether a configured run policy can execute right now
    Gate {
        /// Run policy to preflight
        #[arg(long, required = true)]
        policy: String,
    },
    /// Diagnose config, credentials, gateway capabilities, and cache access
    Doctor {
        /// Profile name (positional; overrides the global --profile flag)
        profile: Option<String>,
    },
    /// List model IDs exposed by the selected OpenAI-compatible gateway
    Models {
        /// Profile name (positional; overrides the global --profile flag)
        profile: Option<String>,
        /// Filter model IDs by a case-insensitive substring
        #[arg(long, value_name = "TEXT")]
        filter: Option<String>,
    },
    /// Show locally observed usage; no upstream history is requested
    Usage {
        /// Profile name (positional; overrides the global --profile flag)
        profile: Option<String>,
        #[command(flatten)]
        date_range: UsageRangeArgs,
        /// Filter usage to an exact model ID
        #[arg(long)]
        model: Option<String>,
        /// Filter local events to an exact API protocol
        #[arg(long)]
        protocol: Option<String>,
        /// Filter local events to an exact logical tool name
        #[arg(long)]
        tool: Option<String>,
        /// Filter local events to an exact run ID
        #[arg(long = "run")]
        run_id: Option<String>,
    },
    /// Send a one-shot text request to the configured AI gateway
    Ask {
        /// Model name, alias, or raw model ID (defaults to the configured model)
        #[arg(long)]
        model: Option<String>,
        /// Optional system message sent before the user content
        #[arg(long)]
        system: Option<String>,
        /// Explicit file to include as context (may be repeated)
        #[arg(long = "file", value_name = "PATH")]
        files: Vec<PathBuf>,
        /// User instruction
        prompt: Option<String>,
    },
    /// Run a configured reusable prompt preset, or list available presets
    Prompt {
        /// Preset name
        #[arg(
            value_name = "NAME",
            required_unless_present = "list",
            conflicts_with = "list"
        )]
        name: Option<String>,
        /// List configured presets without printing their prompt text
        #[arg(long, conflicts_with_all = ["name", "model", "files"])]
        list: bool,
        /// Override the preset model (alias or raw model ID)
        #[arg(long, requires = "name")]
        model: Option<String>,
        /// Explicit file to include as context (may be repeated)
        #[arg(long = "file", value_name = "PATH", requires = "name")]
        files: Vec<PathBuf>,
    },
    /// Run a command with profile credentials and durable run history
    Run {
        /// Apply a declarative run policy with locally enforceable constraints
        #[arg(long)]
        policy: Option<String>,
        /// Optional human-readable run name
        #[arg(long)]
        name: Option<String>,
        /// Workflow label for this invocation
        #[arg(long)]
        workflow: Option<String>,
        /// External task or ticket identifier
        #[arg(long)]
        task_id: Option<String>,
        /// Repeatable run tag
        #[arg(long = "tag")]
        tags: Vec<String>,
        /// Lower the policy's maximum run duration, such as 30m or 2h
        #[arg(long, requires = "policy")]
        duration: Option<String>,
        /// Narrow the policy's allowed model IDs or aliases (repeatable)
        #[arg(long = "allow-model", requires = "policy")]
        allow_models: Vec<String>,
        /// Validate and describe policy enforcement without running the child
        #[arg(long, requires = "policy")]
        dry_run: bool,
        /// Command and arguments to run (after --)
        #[arg(last = true)]
        args: Vec<String>,
    },
    /// Inspect durable run history
    Runs {
        /// Show only the newest N records
        #[arg(long, default_value_t = 20)]
        limit: usize,
        #[command(subcommand)]
        action: Option<RunsAction>,
    },
    /// Manage the local response cache
    Cache {
        #[command(subcommand)]
        action: CacheAction,
    },
    /// Run an AI tool using configured launch wiring or the legacy credential-format fallback.
    /// Usage: aix <tool> [PROFILE] [--dry-run] [-- TOOL_ARGS...]
    /// For the logical `opencode` tool, profiles may select native
    /// `tool_configs.opencode.config_file` and `cli_config_file` sources.
    /// Profile-selected sources are checked against OpenCode v2.0.20; see the
    /// Home Manager option descriptions for path and replacement behavior.
    #[command(external_subcommand)]
    Tool(Vec<String>),
}

#[derive(Args, Default)]
pub struct UsageRangeArgs {
    /// Number of calendar days to include, ending today (for example, 7d)
    #[arg(long, conflicts_with_all = ["start", "end"])]
    pub since: Option<String>,
    /// Inclusive start date in YYYY-MM-DD format (requires --end)
    #[arg(long, requires = "end", conflicts_with = "since")]
    pub start: Option<String>,
    /// Inclusive end date in YYYY-MM-DD format (requires --start)
    #[arg(long, requires = "start", conflicts_with = "since")]
    pub end: Option<String>,
}

impl Command {
    pub fn supports_json(&self) -> bool {
        matches!(
            self,
            Self::Current { .. }
                | Self::Profiles
                | Self::Policies
                | Self::Policy { .. }
                | Self::Spend { .. }
                | Self::Status { .. }
                | Self::Doctor { .. }
                | Self::Gate { .. }
                | Self::Models { .. }
                | Self::Usage { .. }
                | Self::Ask { .. }
                | Self::Prompt { .. }
                | Self::Runs { .. }
                | Self::Auth {
                    action: AuthAction::Status { .. }
                }
        )
    }
}

#[derive(Subcommand)]
pub enum AuthAction {
    /// Sign a ChatGPT account into a profile using the system browser
    Login {
        /// Profile name (positional; overrides global --profile and AIX_PROFILE)
        profile: Option<String>,
    },
    /// Show local authentication state without making network requests
    Status {
        /// Profile name (positional; overrides global --profile and AIX_PROFILE)
        profile: Option<String>,
    },
    /// Revoke and clear ChatGPT credentials for a profile
    Logout {
        /// Profile name (positional; overrides global --profile and AIX_PROFILE)
        profile: Option<String>,
    },
}

#[derive(Clone, Copy, Debug, ValueEnum)]
pub enum Shell {
    Sh,
    Bash,
    Zsh,
    Fish,
    Nu,
    Powershell,
}

#[derive(Clone, Copy, Debug, ValueEnum)]
pub enum UseFormat {
    Json,
}

#[derive(Clone, Copy, Debug, ValueEnum)]
pub enum CurrentFormat {
    Short,
}

#[derive(Subcommand)]
pub enum RunsAction {
    /// Show one complete run record
    Show { run_id: String },
}

#[derive(Subcommand)]
pub enum PolicyAction {
    /// Show the complete configuration for one policy
    Show { name: String },
}

#[derive(Subcommand)]
pub enum ConfigAction {
    /// Print the resolved config file path
    Path,
    /// Validate the config file
    Validate,
}

#[derive(Subcommand)]
pub enum CacheAction {
    /// Delete all cached response files
    Clear,
}

#[derive(ValueEnum, Clone, Debug)]
pub enum EnvFormat {
    Sh,
    Json,
    Nu,
    Fish,
    Powershell,
    Cmd,
}

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

    #[test]
    fn parses_global_timeout_units() {
        let cli = Cli::try_parse_from(["aix", "--timeout", "750ms", "profiles"]).unwrap();
        assert_eq!(cli.timeout, std::time::Duration::from_millis(750));

        let cli = Cli::try_parse_from(["aix", "profiles", "--timeout", "5s"]).unwrap();
        assert_eq!(cli.timeout, std::time::Duration::from_secs(5));
    }

    #[test]
    fn global_timeout_defaults_to_thirty_seconds() {
        let cli = Cli::try_parse_from(["aix", "profiles"]).unwrap();
        assert_eq!(cli.timeout, std::time::Duration::from_secs(30));
    }

    #[test]
    fn timeout_must_be_a_positive_supported_duration() {
        for timeout in ["", "0s", "-1s", "750", "1msx"] {
            assert!(
                Cli::try_parse_from(["aix", "--timeout", timeout, "profiles"]).is_err(),
                "accepted invalid timeout {timeout:?}"
            );
        }
    }

    #[test]
    fn parses_non_interactive_global_flag_before_or_after_command() {
        assert!(
            Cli::try_parse_from(["aix", "--non-interactive", "profiles"])
                .unwrap()
                .non_interactive
        );
        assert!(
            Cli::try_parse_from(["aix", "profiles", "--non-interactive"])
                .unwrap()
                .non_interactive
        );
    }
}