agentix 0.24.0

Multi-provider LLM client for Rust — streaming, non-streaming, tool calls, MCP, DeepSeek, OpenAI, Anthropic, Gemini, Mimo
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
//! `agentix` CLI — Anthropic Messages-compatible HTTP proxy with fallback.
//!
//! Each `-i <upstream>` flag opens a new upstream spec; trailing
//! `--token / --model / --base-url` flags bind to the most recent `-i`.
//! Repeated `-i` defines an ordered fallback chain.
//!
//! ```text
//! agentix -i claude-code \
//!         -i https://api.deepseek.com/chat/completions --token $DEEPSEEK_API_KEY \
//!         --listen 127.0.0.1:7878
//! ```

use std::process::ExitCode;
use std::time::Duration;

use agentix::Provider;
use agentix::server::{AnthropicServer, UpstreamSpec};

const DEFAULT_LISTEN: &str = "127.0.0.1:7878";
const DEFAULT_PRE_COMMIT_TIMEOUT: Duration = Duration::from_secs(30);

#[derive(Debug, Default)]
struct Cli {
    upstreams: Vec<UpstreamDraft>,
    listen: Option<String>,
    print_help: bool,
    print_version: bool,
}

#[derive(Debug)]
struct UpstreamDraft {
    /// Either a provider shortname (e.g. `deepseek`) or a URL (e.g.
    /// `https://api.deepseek.com/chat/completions`).
    target: String,
    token: Option<String>,
    model: Option<String>,
    base_url: Option<String>,
}

#[derive(Debug)]
enum ParseError {
    UnknownFlag(String),
    MissingValue(String),
    OrphanFlag(String),
    BadUpstream(String),
    EmptyChain,
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ParseError::UnknownFlag(s) => write!(f, "unknown flag: {s}"),
            ParseError::MissingValue(s) => write!(f, "flag {s} requires a value"),
            ParseError::OrphanFlag(s) => {
                write!(f, "flag {s} must follow an `-i <upstream>` declaration")
            }
            ParseError::BadUpstream(s) => write!(f, "could not parse upstream: {s}"),
            ParseError::EmptyChain => write!(f, "at least one `-i <upstream>` required"),
        }
    }
}

/// Walk argv. Each `-i <value>` opens a new draft. Trailing
/// `--token | --model | --base-url` (with `=value` or next-arg form) binds to
/// the most recent draft. `--listen | -l` is global. `-h | --help`,
/// `-V | --version` are recognized.
fn parse(args: impl IntoIterator<Item = String>) -> Result<Cli, ParseError> {
    let mut iter = args.into_iter();
    // Skip argv[0] when present.
    let mut peeked: Option<String> = iter.next();
    let mut cli = Cli::default();

    let mut next = move || {
        if let Some(v) = peeked.take() {
            return Some(v);
        }
        iter.next()
    };

    // First call discards argv[0]; we only do that once.
    let _ = next();

    while let Some(arg) = next() {
        if arg == "-h" || arg == "--help" {
            cli.print_help = true;
            continue;
        }
        if arg == "-V" || arg == "--version" {
            cli.print_version = true;
            continue;
        }

        if let Some(value) = strip_eq(&arg, &["-i", "--in", "--inbound"]) {
            cli.upstreams.push(new_draft(value));
            continue;
        }
        if matches!(arg.as_str(), "-i" | "--in" | "--inbound") {
            let value = next().ok_or_else(|| ParseError::MissingValue(arg.clone()))?;
            cli.upstreams.push(new_draft(value));
            continue;
        }

        if let Some(value) = strip_eq(&arg, &["-l", "--listen"]) {
            cli.listen = Some(value);
            continue;
        }
        if matches!(arg.as_str(), "-l" | "--listen") {
            cli.listen = Some(next().ok_or_else(|| ParseError::MissingValue(arg.clone()))?);
            continue;
        }

        // Per-upstream trailing flags.
        let bind_to_last = |cli: &mut Cli, flag: &str, value: String| {
            let last = cli
                .upstreams
                .last_mut()
                .ok_or_else(|| ParseError::OrphanFlag(flag.to_string()))?;
            match flag {
                "--token" | "-k" => last.token = Some(value),
                "--model" | "-m" => last.model = Some(value),
                "--base-url" | "-u" => last.base_url = Some(value),
                _ => return Err(ParseError::UnknownFlag(flag.to_string())),
            }
            Ok::<_, ParseError>(())
        };

        if let Some((flag, value)) = split_eq(&arg)
            && matches!(flag, "--token" | "-k" | "--model" | "-m" | "--base-url" | "-u")
        {
            bind_to_last(&mut cli, flag, value)?;
            continue;
        }

        if matches!(
            arg.as_str(),
            "--token" | "-k" | "--model" | "-m" | "--base-url" | "-u"
        ) {
            let value = next().ok_or_else(|| ParseError::MissingValue(arg.clone()))?;
            bind_to_last(&mut cli, &arg, value)?;
            continue;
        }

        return Err(ParseError::UnknownFlag(arg));
    }

    Ok(cli)
}

fn new_draft(target: String) -> UpstreamDraft {
    UpstreamDraft {
        target,
        token: None,
        model: None,
        base_url: None,
    }
}

fn split_eq(arg: &str) -> Option<(&str, String)> {
    let (flag, value) = arg.split_once('=')?;
    Some((flag, value.to_string()))
}

fn strip_eq(arg: &str, flags: &[&str]) -> Option<String> {
    for f in flags {
        if let Some(rest) = arg.strip_prefix(f)
            && let Some(v) = rest.strip_prefix('=')
        {
            return Some(v.to_string());
        }
    }
    None
}

/// Materialize one [`UpstreamDraft`] into a [`UpstreamSpec`]. URLs are
/// recognized and routed via [`Provider::OpenRouter`] (agentix's catch-all
/// for OAI-compat endpoints) with the URL's host portion as `base_url`.
fn finalize_upstream(draft: UpstreamDraft) -> Result<UpstreamSpec, ParseError> {
    if draft.target.starts_with("http://") || draft.target.starts_with("https://") {
        let token = resolve_token(&draft, "OPENROUTER_API_KEY");
        let base = draft
            .base_url
            .clone()
            .unwrap_or_else(|| strip_trailing_chat_completions(&draft.target));
        let mut spec = UpstreamSpec::new(Provider::OpenRouter, token);
        spec = spec.with_base_url(base);
        if let Some(m) = draft.model {
            spec = spec.with_model(m);
        }
        spec.pre_commit_timeout = DEFAULT_PRE_COMMIT_TIMEOUT;
        return Ok(spec);
    }

    let provider = match draft.target.as_str() {
        "deepseek" => Provider::DeepSeek,
        "openai" => Provider::OpenAI,
        "anthropic" => Provider::Anthropic,
        "gemini" => Provider::Gemini,
        "kimi" => Provider::Kimi,
        "glm" => Provider::Glm,
        "minimax" => Provider::Minimax,
        "mimo" => Provider::Mimo,
        "grok" => Provider::Grok,
        "openrouter" => Provider::OpenRouter,
        #[cfg(feature = "claude-code")]
        "claude-code" | "claudecode" => Provider::ClaudeCode,
        other => return Err(ParseError::BadUpstream(other.to_string())),
    };

    let token_env = match provider {
        Provider::DeepSeek => "DEEPSEEK_API_KEY",
        Provider::OpenAI => "OPENAI_API_KEY",
        Provider::Anthropic => "ANTHROPIC_API_KEY",
        Provider::Gemini => "GEMINI_API_KEY",
        Provider::Kimi => "KIMI_API_KEY",
        Provider::Glm => "GLM_API_KEY",
        Provider::Minimax => "MINIMAX_API_KEY",
        Provider::Mimo => "MIMO_API_KEY",
        Provider::Grok => "GROK_API_KEY",
        Provider::OpenRouter => "OPENROUTER_API_KEY",
        #[cfg(feature = "claude-code")]
        Provider::ClaudeCode => "", // no key required
    };

    let token = resolve_token(&draft, token_env);
    let mut spec = UpstreamSpec::new(provider, token);
    if let Some(b) = draft.base_url {
        spec = spec.with_base_url(b);
    }
    if let Some(m) = draft.model {
        spec = spec.with_model(m);
    }
    spec.pre_commit_timeout = DEFAULT_PRE_COMMIT_TIMEOUT;
    Ok(spec)
}

fn resolve_token(draft: &UpstreamDraft, env_var: &str) -> String {
    if let Some(t) = &draft.token {
        return t.clone();
    }
    if !env_var.is_empty()
        && let Ok(t) = std::env::var(env_var)
    {
        return t;
    }
    String::new()
}

/// `https://api.deepseek.com/chat/completions` → `https://api.deepseek.com`.
/// Otherwise returns the URL unchanged.
fn strip_trailing_chat_completions(url: &str) -> String {
    let url = url.trim_end_matches('/');
    if let Some(stripped) = url.strip_suffix("/chat/completions") {
        return stripped.to_string();
    }
    url.to_string()
}

const HELP: &str = "\
agentix — Anthropic Messages-compatible HTTP proxy with fallback chain.

USAGE:
    agentix -i <upstream> [--token T] [--model M] [--base-url U]
            [-i <upstream2> [--token T2] ...] ...
            [--listen ADDR]

UPSTREAMS:
    Each `-i <upstream>` opens a new upstream. Trailing per-upstream flags
    (`--token`, `--model`, `--base-url`) bind to the most recently declared
    `-i`. Repeated `-i` declarations form a fallback chain — earlier entries
    are tried first; on any error before the upstream emits its first event,
    the next entry is tried.

    <upstream> is either:
      • a provider shortname: claude-code, anthropic, deepseek, openai,
        gemini, kimi, glm, minimax, mimo, grok, openrouter
      • a URL ending in /chat/completions — routed via Provider::OpenRouter
        with the URL host as base_url

OPTIONS:
    -i, --in <UPSTREAM>          Add an upstream to the fallback chain
    -k, --token <KEY>            API key for the most recent upstream
                                  (falls back to <PROVIDER>_API_KEY env var)
    -m, --model <MODEL>          Override the client's model field upstream
    -u, --base-url <URL>         Override the upstream's base URL
    -l, --listen <ADDR>          Bind address (default: 127.0.0.1:7878)
    -h, --help                   Show this help
    -V, --version                Show version

EXAMPLE:
    # Use Claude Code as primary, DeepSeek as fallback.
    agentix \\
        -i claude-code \\
        -i https://api.deepseek.com/chat/completions --token $DEEPSEEK_API_KEY \\
        --listen 127.0.0.1:7878
";

fn print_version() {
    println!("agentix {}", env!("CARGO_PKG_VERSION"));
}

#[tokio::main]
async fn main() -> ExitCode {
    init_tracing();

    let args: Vec<String> = std::env::args().collect();
    let cli = match parse(args) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}\n\n{HELP}");
            return ExitCode::from(2);
        }
    };

    if cli.print_help {
        println!("{HELP}");
        return ExitCode::SUCCESS;
    }
    if cli.print_version {
        print_version();
        return ExitCode::SUCCESS;
    }

    if cli.upstreams.is_empty() {
        eprintln!("{}\n\n{HELP}", ParseError::EmptyChain);
        return ExitCode::from(2);
    }

    let mut chain = Vec::with_capacity(cli.upstreams.len());
    for d in cli.upstreams {
        match finalize_upstream(d) {
            Ok(spec) => chain.push(spec),
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::from(2);
            }
        }
    }

    let listen = cli.listen.unwrap_or_else(|| DEFAULT_LISTEN.to_string());
    let server = AnthropicServer::new(chain);
    if let Err(e) = server.listen(listen.as_str()).await {
        eprintln!("server error: {e}");
        return ExitCode::FAILURE;
    }
    ExitCode::SUCCESS
}

#[cfg(feature = "cli")]
fn init_tracing() {
    use tracing_subscriber::{EnvFilter, fmt};
    let filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new("info,agentix=info"));
    let _ = fmt().with_env_filter(filter).try_init();
}

#[cfg(not(feature = "cli"))]
fn init_tracing() {}

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

    fn parse_args(args: &[&str]) -> Result<Cli, ParseError> {
        let v: Vec<String> = std::iter::once("agentix")
            .chain(args.iter().copied())
            .map(String::from)
            .collect();
        parse(v)
    }

    #[test]
    fn two_upstreams_with_token_on_second() {
        let cli = parse_args(&[
            "-i",
            "claude-code",
            "-i",
            "https://api.deepseek.com/chat/completions",
            "--token",
            "sk-x",
            "--listen",
            "127.0.0.1:7878",
        ])
        .unwrap();
        assert_eq!(cli.upstreams.len(), 2);
        assert_eq!(cli.upstreams[0].target, "claude-code");
        assert!(cli.upstreams[0].token.is_none());
        assert_eq!(cli.upstreams[1].target, "https://api.deepseek.com/chat/completions");
        assert_eq!(cli.upstreams[1].token.as_deref(), Some("sk-x"));
        assert_eq!(cli.listen.as_deref(), Some("127.0.0.1:7878"));
    }

    #[test]
    fn token_eq_form() {
        let cli = parse_args(&["-i", "deepseek", "--token=sk-x"]).unwrap();
        assert_eq!(cli.upstreams[0].token.as_deref(), Some("sk-x"));
    }

    #[test]
    fn orphan_flag_rejected() {
        let err = parse_args(&["--token", "sk-x"]).unwrap_err();
        assert!(matches!(err, ParseError::OrphanFlag(_)));
    }

    #[test]
    fn url_strip_chat_completions() {
        assert_eq!(
            strip_trailing_chat_completions("https://api.deepseek.com/chat/completions"),
            "https://api.deepseek.com"
        );
        assert_eq!(
            strip_trailing_chat_completions("https://api.example.com/v1"),
            "https://api.example.com/v1"
        );
    }

    #[test]
    fn unknown_flag() {
        let err = parse_args(&["--bogus"]).unwrap_err();
        assert!(matches!(err, ParseError::UnknownFlag(_)));
    }

    #[test]
    fn listen_position_independent() {
        let cli =
            parse_args(&["--listen", "0.0.0.0:9999", "-i", "deepseek", "--token", "x"]).unwrap();
        assert_eq!(cli.listen.as_deref(), Some("0.0.0.0:9999"));
        assert_eq!(cli.upstreams.len(), 1);
        assert_eq!(cli.upstreams[0].token.as_deref(), Some("x"));
    }
}