link-assistant-router 1.4.3

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
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! `router providers` — manage stored OpenAI-compatible providers.
//!
//! Split from `main.rs` to keep that file within the repository's 1000-line
//! limit.

use std::process::ExitCode;

use crate::cli::ProviderOp;
use crate::config::Config;
use crate::provider_acceptance::{ProviderProvisionFailureKind, ProviderProvisionResponse};
use crate::providers::{ProviderStore, ProviderUpsert};

#[derive(Debug, PartialEq, serde::Serialize)]
struct ProviderImportReport {
    complete: bool,
    results: Vec<serde_json::Value>,
}

fn import_failure(name: &str, outcome: ProviderProvisionFailureKind) -> serde_json::Value {
    serde_json::json!({"name": name, "outcome": outcome})
}

fn remote_failure(body: &serde_json::Value) -> ProviderProvisionFailureKind {
    let outcome = body.pointer("/error/outcome").cloned();
    outcome
        .and_then(|value| serde_json::from_value(value).ok())
        .unwrap_or(ProviderProvisionFailureKind::Unverified)
}

fn print_import_report(report: &ProviderImportReport) {
    println!(
        "{}",
        serde_json::to_string_pretty(report)
            .unwrap_or_else(|_| { r#"{"complete":false,"results":[]}"#.to_string() })
    );
}

async fn local_import_report(
    client: &reqwest::Client,
    store: &ProviderStore,
    inputs: Vec<ProviderUpsert>,
) -> ProviderImportReport {
    let mut report = ProviderImportReport {
        complete: true,
        results: Vec::with_capacity(inputs.len()),
    };
    for input in inputs {
        let name = input.name.clone();
        match crate::provider_acceptance::provision(client, store, input).await {
            Ok(result) => {
                report
                    .results
                    .push(serde_json::to_value(result.response()).unwrap_or_else(|_| {
                        import_failure(&name, ProviderProvisionFailureKind::PersistenceUncertain)
                    }));
            }
            Err(error) => {
                report.complete = false;
                report.results.push(import_failure(&name, error.kind()));
                break;
            }
        }
    }
    report
}

async fn remote_import_report(
    server: &crate::managed_server::ResolvedServer,
    imported: &[ProviderUpsert],
) -> Result<ProviderImportReport, String> {
    let mut report = ProviderImportReport {
        complete: true,
        results: Vec::with_capacity(imported.len()),
    };
    for record in imported {
        let name = record.name.clone();
        let response = crate::auth_remote::post_response(
            server,
            crate::route_contract::route_template(crate::route_contract::RouteId::Providers),
            upsert_body(record)?,
        )
        .await;
        match response {
            Ok((status, body)) if status.is_success() => {
                if let Ok(safe) = serde_json::from_value::<ProviderProvisionResponse>(body) {
                    report
                        .results
                        .push(serde_json::to_value(safe).unwrap_or_else(|_| {
                            import_failure(&name, ProviderProvisionFailureKind::Unverified)
                        }));
                } else {
                    report.complete = false;
                    report.results.push(import_failure(
                        &name,
                        ProviderProvisionFailureKind::Unverified,
                    ));
                    break;
                }
            }
            Ok((_, body)) => {
                report.complete = false;
                report
                    .results
                    .push(import_failure(&name, remote_failure(&body)));
                break;
            }
            Err(_) => {
                report.complete = false;
                report.results.push(import_failure(
                    &name,
                    ProviderProvisionFailureKind::Unverified,
                ));
                break;
            }
        }
    }
    Ok(report)
}

#[must_use]
pub async fn run(config: &Config, op: &ProviderOp) -> ExitCode {
    let store = match ProviderStore::open(&config.data_dir, &config.token_secret) {
        Ok(store) => store,
        Err(e) => {
            eprintln!("error: {e}");
            return ExitCode::from(1);
        }
    };
    run_with(&store, op).await
}

/// The same commands against the *selected* router (issue #294).
///
/// The deployment already exposes full CRUD for providers, admin-gated, so
/// these are honoured rather than refused. `import` is the exception in shape
/// only: it reads a file on *this* machine and then declares each provider
/// remotely, which is what an operator means by importing a local manifest
/// into a deployment.
pub async fn run_remote(
    server: &crate::managed_server::ResolvedServer,
    op: &ProviderOp,
) -> ExitCode {
    warn_zai_policy(op);
    match remote_result(server, op).await {
        Ok(code) => code,
        Err(error) => {
            eprintln!("error: {error}");
            ExitCode::from(1)
        }
    }
}

fn warn_zai_policy(op: &ProviderOp) {
    if let ProviderOp::Add {
        kind,
        enabled,
        acknowledge_intermediary_risk,
        acknowledge_unsupported_client,
        ..
    } = op
        && crate::providers::ProviderKind::from_str_opt(kind)
            == Some(crate::providers::ProviderKind::ZaiCodingPlan)
        && *enabled
    {
        eprintln!(
            "WARNING: z.ai Coding Plan is a personal subscription. Intermediary proxying is not explicitly approved; policy violations may restrict or ban the subscriber account."
        );
        if *acknowledge_intermediary_risk {
            eprintln!("risk accepted: intermediary z.ai Coding Plan proxying");
        }
        for client in acknowledge_unsupported_client {
            eprintln!(
                "WARNING: unsupported z.ai tool risk accepted only for client '{client}'; this may cause account restrictions or a ban"
            );
        }
    }
}

/// The call one provider operation makes against the selected router.
///
/// Separated from sending it so the request can be asserted without a server:
/// a wrong path or a body missing a declared model is the kind of mistake an
/// operator only sees as a provider that never wins a route.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Call {
    /// `GET`, `POST` or `DELETE`, as the endpoint expects.
    pub method: &'static str,
    /// The admin route this operation uses.
    pub path: String,
    /// The JSON body, for a `POST`.
    pub body: Option<serde_json::Value>,
}

/// The call `op` makes, for everything but `import`.
///
/// `import` reads a manifest on this machine and then makes one `add` call per
/// provider it declares, so it has no single call of its own.
///
/// # Errors
///
/// Returns an operator-readable message when the provider cannot be encoded.
pub fn call_for(op: &ProviderOp) -> Result<Option<Call>, String> {
    Ok(match op {
        ProviderOp::List { .. } => Some(Call {
            method: "GET",
            path: crate::route_contract::route_template(crate::route_contract::RouteId::Providers)
                .to_string(),
            body: None,
        }),
        ProviderOp::Show { name, .. } => Some(Call {
            method: "GET",
            path: format!("/api/management/providers/{name}"),
            body: None,
        }),
        ProviderOp::Remove { name, .. } => Some(Call {
            method: "DELETE",
            path: format!("/api/management/providers/{name}"),
            body: None,
        }),
        ProviderOp::Add {
            name,
            kind,
            base_url,
            model,
            models,
            supported_clients,
            api_key,
            api_key_stdin,
            api_key_env,
            subscriber_id,
            acknowledge_intermediary_risk,
            acknowledge_unsupported_client,
            enabled,
            if_absent,
            ..
        } => {
            reject_lefine_argv_key(kind, api_key.as_ref())?;
            Some(Call {
                method: "POST",
                path: crate::route_contract::route_template(
                    crate::route_contract::RouteId::Providers,
                )
                .to_string(),
                body: Some(upsert_body(&ProviderUpsert {
                    name: name.clone(),
                    kind: Some(kind.clone()),
                    base_url: base_url.clone(),
                    default_model: model.clone(),
                    models: Some(models.clone()),
                    supported_clients: Some(supported_clients.clone()),
                    api_key: supplied_api_key(api_key.as_ref(), *api_key_stdin)
                        .map_err(|error| error.to_string())?,
                    api_key_env: api_key_env.clone(),
                    encrypted_api_key: None,
                    enabled: Some(*enabled),
                    subscriber_id: subscriber_id.clone(),
                    acknowledge_intermediary_risk: Some(*acknowledge_intermediary_risk),
                    acknowledge_unsupported_clients: Some(acknowledge_unsupported_client.clone()),
                    if_absent: *if_absent,
                })?),
            })
        }
        ProviderOp::Import { .. } => None,
    })
}

/// The vendor API key this invocation supplies, from argv or standard input.
///
/// `--api-key-stdin` exists because this was the one secret in the tool that
/// could travel only through argv, where shell history and `ps` expose it —
/// while every other secret already had a stdin form (issue #314).
fn supplied_api_key(
    api_key: Option<&String>,
    api_key_stdin: bool,
) -> Result<Option<String>, Box<dyn std::error::Error + Send + Sync>> {
    if api_key_stdin {
        return crate::server_command::read_token().map(Some);
    }
    Ok(api_key.cloned())
}

fn reject_lefine_argv_key(kind: &str, api_key: Option<&String>) -> Result<(), String> {
    if crate::providers::ProviderKind::from_str_opt(kind)
        == Some(crate::providers::ProviderKind::Lefine)
        && api_key.is_some()
    {
        return Err("Lefine API keys must use --api-key-stdin or --api-key-env".into());
    }
    Ok(())
}

/// One provider as the endpoint's own request type encodes it.
///
/// Built from [`ProviderUpsert`] rather than a hand-written JSON object, so the
/// remote and local paths cannot describe a provider differently.
///
/// # Errors
///
/// Returns an operator-readable message when the record cannot be encoded.
pub fn upsert_body(upsert: &ProviderUpsert) -> Result<serde_json::Value, String> {
    serde_json::to_value(upsert).map_err(|error| error.to_string())
}

/// The provider records inside a `/api/management/providers` answer.
#[must_use]
pub fn records_in(answer: &serde_json::Value) -> Vec<serde_json::Value> {
    answer
        .get("data")
        .and_then(serde_json::Value::as_array)
        .cloned()
        .unwrap_or_default()
}

async fn remote_result(
    server: &crate::managed_server::ResolvedServer,
    op: &ProviderOp,
) -> Result<ExitCode, String> {
    if let ProviderOp::Import { path, .. } = op {
        // The manifest is this machine's file; the providers it declares are
        // the deployment's. Reading here and declaring there is what "import
        // into that router" means.
        let text = std::fs::read_to_string(path)
            .map_err(|error| format!("could not read {}: {error}", path.display()))?;
        let imported = crate::providers::parse_provider_import(&text)
            .map_err(|error| format!("could not parse {}: {error}", path.display()))?;
        let report = remote_import_report(server, &imported).await?;
        print_import_report(&report);
        return Ok(if report.complete {
            ExitCode::SUCCESS
        } else {
            ExitCode::from(1)
        });
    }

    let Some(call) = call_for(op)? else {
        return Ok(ExitCode::from(1));
    };
    let answer = match (call.method, call.body) {
        ("POST", Some(body)) => crate::auth_remote::post(server, &call.path, body).await,
        ("DELETE", _) => crate::auth_remote::delete(server, &call.path).await,
        _ => crate::auth_remote::get(server, &call.path).await,
    };

    match op {
        ProviderOp::List { json, .. } => {
            let records = records_in(&answer?);
            if *json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&records).unwrap_or_else(|_| "[]".to_string())
                );
            } else {
                print_remote_table(&records);
            }
            Ok(ExitCode::SUCCESS)
        }
        ProviderOp::Show { name, .. } => match answer {
            Ok(record) => {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&record).unwrap_or_default()
                );
                Ok(ExitCode::SUCCESS)
            }
            // The local path exits 2 for an unknown provider; matching it keeps
            // a script's meaning the same against either target.
            Err(error) if error.contains("404") => {
                eprintln!("not found: {name}");
                Ok(ExitCode::from(2))
            }
            Err(error) => Err(error),
        },
        ProviderOp::Remove { name, .. } => {
            answer?;
            println!("removed {name}");
            Ok(ExitCode::SUCCESS)
        }
        ProviderOp::Add { .. } => {
            let answer = answer?;
            println!(
                "{}",
                serde_json::to_string_pretty(&answer)
                    .map_err(|error| format!("could not encode provider outcome: {error}"))?
            );
            Ok(ExitCode::SUCCESS)
        }
        // Returned above.
        ProviderOp::Import { .. } => Ok(ExitCode::from(1)),
    }
}

/// The provider table, in the one format both paths print.
///
/// Same columns, widths and order as the local table: an operator reading one
/// has no way to tell which machine answered, so a column that differs between
/// them would be worse than no column at all.
///
/// `kind` is taken through [`ProviderKind::as_str`] so table output stays
/// aligned with the accepted CLI spelling.
fn print_remote_table(records: &[serde_json::Value]) {
    println!(
        "{:<20}  {:<18}  {:<32}  {:<10}  default_model",
        "name", "kind", "base_url", "enabled"
    );
    for record in records {
        let text = |key: &str| {
            record
                .get(key)
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
        };
        let kind = crate::providers::ProviderKind::from_str_opt(text("kind"))
            .unwrap_or_default()
            .as_str();
        println!(
            "{:<20}  {:<18}  {:<32}  {:<10}  {}",
            text("name"),
            kind,
            text("base_url"),
            record
                .get("enabled")
                .and_then(serde_json::Value::as_bool)
                .unwrap_or(false),
            text("default_model"),
        );
    }
}

/// The same command against an already-open store.
///
/// Split from [`run`] so the operations can be exercised without constructing
/// a whole configuration around them.
#[must_use]
pub async fn run_with(store: &ProviderStore, op: &ProviderOp) -> ExitCode {
    warn_zai_policy(op);
    let client = match crate::upstream_client::build_upstream_client() {
        Ok(client) => client,
        Err(error) => {
            eprintln!("error: could not build provider validation client: {error}");
            return ExitCode::from(1);
        }
    };
    match op {
        ProviderOp::List { json, .. } => match store.list_redacted() {
            Ok(records) if *json => {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&records).unwrap_or_else(|_| "[]".to_string())
                );
                ExitCode::SUCCESS
            }
            Ok(records) => {
                println!(
                    "{:<20}  {:<18}  {:<32}  {:<10}  default_model",
                    "name", "kind", "base_url", "enabled"
                );
                for record in records {
                    println!(
                        "{:<20}  {:<18}  {:<32}  {:<10}  {}",
                        record.name,
                        record.kind.as_str(),
                        record.base_url,
                        record.enabled,
                        record.default_model.unwrap_or_default()
                    );
                }
                ExitCode::SUCCESS
            }
            Err(e) => {
                eprintln!("error: {e}");
                ExitCode::from(1)
            }
        },
        ProviderOp::Add {
            name,
            kind,
            base_url,
            model,
            models,
            supported_clients,
            api_key,
            api_key_stdin,
            api_key_env,
            subscriber_id,
            acknowledge_intermediary_risk,
            acknowledge_unsupported_client,
            enabled,
            if_absent,
            ..
        } => {
            if let Err(error) = reject_lefine_argv_key(kind, api_key.as_ref()) {
                eprintln!("error: {error}");
                return ExitCode::from(2);
            }
            let api_key = match supplied_api_key(api_key.as_ref(), *api_key_stdin) {
                Ok(api_key) => api_key,
                Err(error) => {
                    eprintln!("error: {error}");
                    return ExitCode::from(2);
                }
            };
            let input = ProviderUpsert {
                name: name.clone(),
                kind: Some(kind.clone()),
                base_url: base_url.clone(),
                default_model: model.clone(),
                models: Some(models.clone()),
                supported_clients: Some(supported_clients.clone()),
                api_key,
                api_key_env: api_key_env.clone(),
                encrypted_api_key: None,
                enabled: Some(*enabled),
                subscriber_id: subscriber_id.clone(),
                acknowledge_intermediary_risk: Some(*acknowledge_intermediary_risk),
                acknowledge_unsupported_clients: Some(acknowledge_unsupported_client.clone()),
                if_absent: *if_absent,
            };
            match crate::provider_acceptance::provision(&client, store, input).await {
                Ok(result) => {
                    println!(
                        "{}",
                        serde_json::to_string_pretty(&result.response()).unwrap_or_default()
                    );
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    eprintln!("error: {e}");
                    ExitCode::from(1)
                }
            }
        }
        ProviderOp::Show { name, .. } => match store.get(name) {
            Ok(Some(record)) => {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&record.redacted()).unwrap_or_default()
                );
                ExitCode::SUCCESS
            }
            Ok(None) => {
                eprintln!("not found: {name}");
                ExitCode::from(2)
            }
            Err(e) => {
                eprintln!("error: {e}");
                ExitCode::from(1)
            }
        },
        ProviderOp::Remove { name, .. } => match store.delete(name) {
            Ok(true) => {
                println!("removed {name}");
                ExitCode::SUCCESS
            }
            Ok(false) => {
                eprintln!("not found: {name}");
                ExitCode::from(2)
            }
            Err(e) => {
                eprintln!("error: {e}");
                ExitCode::from(1)
            }
        },
        ProviderOp::Import { path, .. } => match std::fs::read_to_string(path)
            .map_err(crate::providers::ProviderError::from)
            .and_then(|text| crate::providers::parse_provider_import(&text))
        {
            Ok(inputs) => {
                let report = local_import_report(&client, store, inputs).await;
                print_import_report(&report);
                if report.complete {
                    ExitCode::SUCCESS
                } else {
                    ExitCode::from(1)
                }
            }
            Err(e) => {
                eprintln!("error: {e}");
                ExitCode::from(1)
            }
        },
    }
}

#[cfg(test)]
#[path = "providers_cli_tests.rs"]
mod tests;