link-assistant-router 0.18.0

Link.Assistant.Router — Claude MAX OAuth proxy and token gateway for Anthropic APIs
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
//! Command-line interface for the router.
//!
//! Issue #7 R3 mandates a `lino-arguments`-based CLI on top of clap. This
//! module defines the subcommands and exposes a single [`Cli`] entry-point
//! parsed by [`lino_arguments::Parser`] (which is a clap-compatible drop-in
//! that additionally reads `.lenv` files at startup).
//!
//! Subcommands:
//!
//! - `serve` (default) — start the HTTP server.
//! - `tokens issue|list|revoke|expire|show` — manage persistent tokens
//!   without going through the HTTP layer (useful for ops scripts).
//! - `accounts list` — show configured accounts and their health.
//! - `doctor` — report on environment, OAuth credential discoverability,
//!   storage paths, and other config.

// The CLI struct intentionally has many independent boolean toggles
// (`--disable-openai-api`, `--disable-anthropic-api`, etc.). Refactoring
// into enums would obscure the 1:1 mapping with the documented flags.
#![allow(clippy::struct_excessive_bools)]

use std::path::PathBuf;
use std::time::Duration;

use clap::Subcommand;
use lino_arguments::Parser as LinoParser;

use crate::config::{
    default_activitypub_public_key_pem, default_data_dir, ApiFormat, BuildArgs, Config,
    ConfigError, RoutingMode, StoragePolicy, UpstreamProvider,
};

/// Top-level CLI parser.
#[derive(Debug, LinoParser)]
#[command(
    name = "link-assistant-router",
    about = "Claude MAX OAuth proxy and token gateway for Anthropic APIs",
    version
)]
pub struct Cli {
    /// Subcommand to run. Defaults to `serve` when omitted.
    #[command(subcommand)]
    pub command: Option<Command>,

    /// Address to bind the HTTP server to (legacy --host).
    #[arg(long, env = "ROUTER_HOST", default_value = "0.0.0.0", global = true)]
    pub host: String,

    /// Port to bind the HTTP server to.
    #[arg(long, env = "ROUTER_PORT", default_value = "8080", global = true)]
    pub port: u16,

    /// Verbose logging.
    #[arg(long, env = "VERBOSE", global = true)]
    pub verbose: bool,

    /// JWT signing secret (or `TOKEN_SECRET` env).
    #[arg(long, env = "TOKEN_SECRET", global = true)]
    pub token_secret: Option<String>,

    /// Claude Code home directory (primary account credentials).
    #[arg(long, env = "CLAUDE_CODE_HOME", global = true)]
    pub claude_code_home: Option<String>,

    /// Upstream base URL.
    #[arg(
        long,
        env = "UPSTREAM_BASE_URL",
        default_value = "https://api.anthropic.com",
        global = true
    )]
    pub upstream_base_url: String,

    /// Restrict the proxy to a specific upstream API format.
    #[arg(long, env = "UPSTREAM_API_FORMAT", global = true)]
    pub api_format: Option<String>,

    /// Routing mode: direct, cli, hybrid.
    #[arg(long, env = "ROUTING_MODE", default_value = "direct", global = true)]
    pub routing_mode: String,

    /// Storage policy: memory, text, binary, both.
    #[arg(long, env = "STORAGE_POLICY", default_value = "both", global = true)]
    pub storage_policy: String,

    /// Data directory for the persistent token store.
    #[arg(long, env = "DATA_DIR", global = true)]
    pub data_dir: Option<PathBuf>,

    /// Path to the local Claude CLI binary used by the CLI backend.
    #[arg(long, env = "CLAUDE_CLI_BIN", global = true)]
    pub claude_cli_bin: Option<PathBuf>,

    /// Upstream provider: anthropic, gonka, crater, or openai-compatible.
    #[arg(
        long,
        env = "UPSTREAM_PROVIDER",
        default_value = "anthropic",
        global = true
    )]
    pub upstream_provider: String,

    /// Gonka private key used for request signing.
    #[arg(long, env = "GONKA_PRIVATE_KEY", global = true)]
    pub gonka_private_key: Option<String>,

    /// Gonka source node URL.
    #[arg(
        long,
        env = "GONKA_SOURCE_URL",
        default_value = "https://node4.gonka.ai",
        global = true
    )]
    pub gonka_source_url: String,

    /// Default Gonka model for OpenAI-compatible requests without `model`.
    #[arg(
        long,
        env = "GONKA_MODEL",
        default_value = "Qwen/Qwen3-235B-A22B-Instruct-2507-FP8",
        global = true
    )]
    pub gonka_model: String,

    /// Remote `ForgeFed` inbox for the crater provider.
    #[arg(long, env = "CRATER_FORGEFED_INBOX", global = true)]
    pub crater_forgefed_inbox: Option<String>,

    /// Local actor URI used by the crater provider.
    #[arg(long, env = "CRATER_FORGEFED_ACTOR", global = true)]
    pub crater_forgefed_actor: Option<String>,

    /// Remote ticket tracker or project URI used as the `ForgeFed` `Offer` target.
    #[arg(long, env = "CRATER_FORGEFED_TARGET", global = true)]
    pub crater_forgefed_target: Option<String>,

    /// Delay between crater task-resolution polls.
    #[arg(
        long,
        env = "CRATER_POLL_INTERVAL_MS",
        default_value_t = 1000,
        global = true
    )]
    pub crater_poll_interval_ms: u64,

    /// Maximum seconds to wait for crater task resolution.
    #[arg(
        long,
        env = "CRATER_POLL_TIMEOUT_SECS",
        default_value_t = 120,
        global = true
    )]
    pub crater_poll_timeout_secs: u64,

    /// Stored provider name for generic OpenAI-compatible upstream routing.
    #[arg(
        long,
        env = "OPENAI_COMPATIBLE_PROVIDER_NAME",
        default_value = "litellm",
        global = true
    )]
    pub openai_compatible_provider_name: String,

    /// Generic OpenAI-compatible upstream API base URL, usually ending in /v1.
    #[arg(
        long,
        env = "OPENAI_COMPATIBLE_BASE_URL",
        default_value = "http://localhost:4000/v1",
        global = true
    )]
    pub openai_compatible_base_url: String,

    /// Generic OpenAI-compatible upstream API key. Prefer provider DB import
    /// for long-lived deployments so the key is encrypted at rest.
    #[arg(long, env = "OPENAI_COMPATIBLE_API_KEY", global = true)]
    pub openai_compatible_api_key: Option<String>,

    /// Environment variable that contains the OpenAI-compatible upstream key.
    #[arg(long, env = "OPENAI_COMPATIBLE_API_KEY_ENV", global = true)]
    pub openai_compatible_api_key_env: Option<String>,

    /// Default model for OpenAI-compatible upstream requests without `model`.
    #[arg(long, env = "OPENAI_COMPATIBLE_MODEL", global = true)]
    pub openai_compatible_model: Option<String>,

    /// Comma-separated models exposed for the OpenAI-compatible provider.
    #[arg(
        long,
        env = "OPENAI_COMPATIBLE_MODELS",
        value_delimiter = ',',
        global = true
    )]
    pub openai_compatible_models: Vec<String>,

    /// Public base URL for the `ActivityPub` actor.
    #[arg(long, env = "ACTIVITYPUB_ACTOR_BASE_URL", global = true)]
    pub activitypub_actor_base_url: Option<String>,

    /// Public key PEM advertised by the `ActivityPub` actor.
    #[arg(long, env = "ACTIVITYPUB_PUBLIC_KEY_PEM", global = true)]
    pub activitypub_public_key_pem: Option<String>,

    /// Disable the OpenAI-compatible API surface.
    #[arg(long, env = "DISABLE_OPENAI_API", global = true)]
    pub disable_openai_api: bool,

    /// Disable the Anthropic (direct) proxy surface.
    #[arg(long, env = "DISABLE_ANTHROPIC_API", global = true)]
    pub disable_anthropic_api: bool,

    /// Disable `/metrics`, `/v1/usage` and `/v1/accounts` endpoints.
    #[arg(long, env = "DISABLE_METRICS", global = true)]
    pub disable_metrics: bool,

    /// Comma-separated list of additional account credential directories.
    #[arg(
        long,
        env = "ADDITIONAL_ACCOUNT_DIRS",
        value_delimiter = ',',
        global = true
    )]
    pub additional_account_dirs: Vec<PathBuf>,

    /// Enable experimental compatibility shims (XML history, spoofing, …).
    #[arg(long, env = "EXPERIMENTAL_COMPATIBILITY", global = true)]
    pub experimental_compatibility: bool,

    /// Bearer key required by `/api/tokens` and admin endpoints.
    #[arg(long, env = "TOKEN_ADMIN_KEY", global = true)]
    pub admin_key: Option<String>,

    /// Enable MPP 402 charge challenges on OpenAI-compatible endpoints.
    #[arg(long, env = "MPP_ENABLE", global = true)]
    pub mpp_enable: bool,

    /// Per-request MPP charge amount for OpenAI-compatible endpoints.
    #[arg(long, env = "MPP_AMOUNT", default_value = "0.00", global = true)]
    pub mpp_amount: String,

    /// Currency or asset for MPP `OpenAI` endpoint charges.
    #[arg(long, env = "MPP_CURRENCY", default_value = "USD", global = true)]
    pub mpp_currency: String,

    /// Recipient wallet, merchant account, or payment address for MPP charges.
    #[arg(long, env = "MPP_RECIPIENT", global = true)]
    pub mpp_recipient: Option<String>,

    /// Optional MPP payment method identifier, such as tempo or stripe.
    #[arg(long, env = "MPP_METHOD", global = true)]
    pub mpp_method: Option<String>,
}

/// Subcommands.
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Start the HTTP server (default if no subcommand given).
    Serve,
    /// Token-management subcommands.
    Tokens {
        #[command(subcommand)]
        op: TokenOp,
    },
    /// Account-management subcommands.
    Accounts {
        #[command(subcommand)]
        op: AccountOp,
    },
    /// Provider-management subcommands.
    Providers {
        #[command(subcommand)]
        op: ProviderOp,
    },
    /// Print environment + config diagnostics.
    Doctor,
}

#[derive(Debug, Subcommand)]
pub enum TokenOp {
    /// Issue a new token and print it to stdout.
    Issue {
        #[arg(long, default_value_t = 24)]
        ttl_hours: i64,
        #[arg(long, default_value = "")]
        label: String,
        #[arg(long)]
        account: Option<String>,
    },
    /// List all known tokens.
    List,
    /// Revoke a token by id.
    Revoke { id: String },
    /// Mark a token as expired immediately (revoke alias).
    Expire { id: String },
    /// Show metadata for one token.
    Show { id: String },
}

#[derive(Debug, Subcommand)]
pub enum AccountOp {
    /// List configured accounts and their health.
    List,
}

#[derive(Debug, Subcommand)]
pub enum ProviderOp {
    /// List configured upstream providers.
    List,
    /// Add or replace an OpenAI-compatible provider.
    Add {
        #[arg(long)]
        name: String,
        #[arg(long, default_value = "openai-compatible")]
        kind: String,
        #[arg(long)]
        base_url: String,
        #[arg(long)]
        model: Option<String>,
        #[arg(long, value_delimiter = ',')]
        models: Vec<String>,
        #[arg(long)]
        api_key: Option<String>,
        #[arg(long)]
        api_key_env: Option<String>,
        #[arg(long, default_value_t = true)]
        enabled: bool,
    },
    /// Show one provider with secret material redacted.
    Show { name: String },
    /// Remove one provider.
    Remove { name: String },
    /// Import providers from JSON, `.lenv`, or indented Links-style config.
    Import { path: PathBuf },
}

impl Cli {
    /// Build a [`Config`] from the parsed CLI / env / `.lenv` values.
    pub fn into_config(&self) -> Result<Config, ConfigError> {
        let port = self.port.to_string();
        let token_secret = self.token_secret.clone();
        let claude_home = self.claude_code_home.clone().unwrap_or_else(|| {
            std::env::var("HOME")
                .map_or_else(|_| "/root/.claude".to_string(), |h| format!("{h}/.claude"))
        });
        let api_format = self.api_format.as_deref().and_then(ApiFormat::from_str_opt);
        let routing_mode =
            RoutingMode::from_str_opt(&self.routing_mode).ok_or(ConfigError::InvalidRoutingMode)?;
        let upstream_provider = UpstreamProvider::from_str_opt(&self.upstream_provider)
            .unwrap_or(UpstreamProvider::Anthropic);
        let storage_policy = StoragePolicy::from_str_opt(&self.storage_policy).unwrap_or_default();
        let data_dir = self.data_dir.clone().unwrap_or_else(default_data_dir);
        let activitypub_actor_base_url = self
            .activitypub_actor_base_url
            .clone()
            .unwrap_or_else(|| format!("http://{}:{}", self.host, self.port));
        let crater_actor = self
            .crater_forgefed_actor
            .clone()
            .filter(|value| !value.is_empty())
            .unwrap_or_else(|| {
                format!(
                    "{}/actor/code",
                    activitypub_actor_base_url.trim_end_matches('/')
                )
            });
        let crater = crate::crater::CraterConfig::new(
            self.crater_forgefed_inbox
                .clone()
                .filter(|value| !value.is_empty()),
            &crater_actor,
            self.crater_forgefed_target
                .clone()
                .filter(|value| !value.is_empty()),
            Duration::from_millis(self.crater_poll_interval_ms),
            Duration::from_secs(self.crater_poll_timeout_secs),
        );
        let activitypub_public_key_pem = self
            .activitypub_public_key_pem
            .clone()
            .unwrap_or_else(default_activitypub_public_key_pem);
        let openai_compatible = crate::providers::OpenAICompatibleConfig {
            provider_name: self.openai_compatible_provider_name.clone(),
            base_url: self.openai_compatible_base_url.clone(),
            api_key: self
                .openai_compatible_api_key
                .clone()
                .filter(|s| !s.is_empty()),
            api_key_env: self
                .openai_compatible_api_key_env
                .clone()
                .filter(|s| !s.is_empty()),
            default_model: self
                .openai_compatible_model
                .clone()
                .filter(|s| !s.is_empty()),
            models: self.openai_compatible_models.clone(),
        };
        Config::build(BuildArgs {
            host: &self.host,
            port: &port,
            token_secret: token_secret.as_deref(),
            claude_code_home: &claude_home,
            upstream_base_url: &self.upstream_base_url,
            verbose: self.verbose,
            api_format,
            routing_mode,
            storage_policy,
            data_dir,
            claude_cli_bin: self.claude_cli_bin.clone(),
            upstream_provider,
            gonka_private_key: self.gonka_private_key.clone().filter(|s| !s.is_empty()),
            gonka_source_url: self.gonka_source_url.clone(),
            gonka_model: self.gonka_model.clone(),
            crater,
            openai_compatible,
            activitypub_actor_base_url,
            activitypub_public_key_pem,
            enable_openai_api: !self.disable_openai_api,
            enable_anthropic_api: !self.disable_anthropic_api,
            enable_metrics: !self.disable_metrics,
            additional_account_dirs: self.additional_account_dirs.clone(),
            experimental_compatibility: self.experimental_compatibility,
            admin_key: self.admin_key.clone().filter(|s| !s.is_empty()),
            mpp: crate::mpp::MppConfig {
                enabled: self.mpp_enable,
                amount: self.mpp_amount.clone(),
                currency: self.mpp_currency.clone(),
                recipient: self.mpp_recipient.clone().unwrap_or_default(),
                method: self.mpp_method.clone().filter(|s| !s.is_empty()),
            },
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{
        default_gonka_model, default_gonka_source_url, default_openai_compatible_base_url,
    };

    #[test]
    fn cli_defaults_round_trip_to_config() {
        let cli = Cli {
            command: None,
            host: "127.0.0.1".into(),
            port: 9090,
            verbose: false,
            token_secret: Some("k".into()),
            claude_code_home: Some("/tmp/c".into()),
            upstream_base_url: "https://api.anthropic.com".into(),
            api_format: None,
            routing_mode: "direct".into(),
            storage_policy: "memory".into(),
            data_dir: Some(std::path::PathBuf::from("/tmp/d")),
            claude_cli_bin: None,
            upstream_provider: "anthropic".into(),
            gonka_private_key: None,
            gonka_source_url: default_gonka_source_url(),
            gonka_model: default_gonka_model(),
            crater_forgefed_inbox: None,
            crater_forgefed_actor: None,
            crater_forgefed_target: None,
            crater_poll_interval_ms: 1000,
            crater_poll_timeout_secs: 120,
            openai_compatible_provider_name: "litellm".into(),
            openai_compatible_base_url: default_openai_compatible_base_url(),
            openai_compatible_api_key: None,
            openai_compatible_api_key_env: None,
            openai_compatible_model: None,
            openai_compatible_models: vec![],
            activitypub_actor_base_url: Some("https://router.example".into()),
            activitypub_public_key_pem: None,
            disable_openai_api: false,
            disable_anthropic_api: false,
            disable_metrics: false,
            additional_account_dirs: vec![],
            experimental_compatibility: false,
            admin_key: None,
            mpp_enable: false,
            mpp_amount: "0.00".into(),
            mpp_currency: "USD".into(),
            mpp_recipient: None,
            mpp_method: None,
        };
        let cfg = cli.into_config().unwrap();
        assert_eq!(cfg.listen_addr.port(), 9090);
        assert_eq!(cfg.routing_mode, RoutingMode::Direct);
        assert_eq!(cfg.storage_policy, StoragePolicy::Memory);
        assert!(cfg.enable_openai_api);
        assert!(cfg.enable_anthropic_api);
        assert!(cfg.enable_metrics);
    }

    #[test]
    fn cli_invalid_routing_mode_rejected() {
        let cli = Cli {
            command: None,
            host: "0.0.0.0".into(),
            port: 8080,
            verbose: false,
            token_secret: Some("k".into()),
            claude_code_home: Some("/tmp/c".into()),
            upstream_base_url: "https://api.anthropic.com".into(),
            api_format: None,
            routing_mode: "bogus".into(),
            storage_policy: "memory".into(),
            data_dir: None,
            claude_cli_bin: None,
            upstream_provider: "anthropic".into(),
            gonka_private_key: None,
            gonka_source_url: default_gonka_source_url(),
            gonka_model: default_gonka_model(),
            crater_forgefed_inbox: None,
            crater_forgefed_actor: None,
            crater_forgefed_target: None,
            crater_poll_interval_ms: 1000,
            crater_poll_timeout_secs: 120,
            openai_compatible_provider_name: "litellm".into(),
            openai_compatible_base_url: default_openai_compatible_base_url(),
            openai_compatible_api_key: None,
            openai_compatible_api_key_env: None,
            openai_compatible_model: None,
            openai_compatible_models: vec![],
            activitypub_actor_base_url: None,
            activitypub_public_key_pem: None,
            disable_openai_api: false,
            disable_anthropic_api: false,
            disable_metrics: false,
            additional_account_dirs: vec![],
            experimental_compatibility: false,
            admin_key: None,
            mpp_enable: false,
            mpp_amount: "0.00".into(),
            mpp_currency: "USD".into(),
            mpp_recipient: None,
            mpp_method: None,
        };
        let r = cli.into_config();
        assert!(matches!(r, Err(ConfigError::InvalidRoutingMode)));
    }
}