bitrouter 1.0.0-alpha.4

BitRouter: an LLM API router. CLI + TUI + assembly library.
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! Management command logic — the implementations behind the CLI subcommands.
//! Kept in the lib so it is testable and so a future desktop front-end can
//! reuse it without dragging in the binary.

use anyhow::{Context, Result};

use bitrouter_sdk::caller::CallerContext;
use bitrouter_sdk::config::{Config, ConfigRoutingTable};
use bitrouter_sdk::language_model::{RoutingPrefs, RoutingTable};

use crate::auth::{NewApiKey, db as auth_db, generate};
use crate::daemon::RouteHop;

/// The starter `bitrouter.yaml` written by `bitrouter init`. Mirrors
/// the zero-config in-memory default so a user who runs `init` and
/// then deletes nothing gets the same behaviour as running bitrouter
/// with no config at all — only the file is here to be edited.
pub const STARTER_CONFIG: &str = r#"# bitrouter.yaml — generated by `bitrouter init`.
#
# This file mirrors the zero-config in-memory default. Delete any
# section you don't want to override, or add custom providers /
# guardrails / policies / MCP servers as needed.

server:
  # Bind localhost only by default — combined with `skip_auth: true`,
  # exposing `0.0.0.0` would let any host on the network use bitrouter
  # without a credential check. Flip to `0.0.0.0:4356` only when you've
  # also set `skip_auth: false` and minted virtual keys with
  # `bitrouter key sign`.
  listen: "127.0.0.1:4356"
  # skip_auth=true admits credential-less local requests (cc-switch /
  # litellm style). Set to false and create keys with `bitrouter key
  # sign` for a multi-tenant deployment.
  skip_auth: true

database:
  # Relative paths are interpreted against the bitrouter home (the
  # directory containing this file) — the daemon chdirs there on
  # startup, so `./bitrouter.db` always lands alongside the config.
  url: "sqlite://./bitrouter.db"

# Built-in providers auto-enable when their env var is set. An entry
# with `inherit_defaults: true` (the workspace default) plus an empty
# body is enough — `api_base`, `api_protocol`, `api_key`, and the
# routable models all flow from the built-in catalog. Comment a line
# out (or set `active: false`) to disable a provider you don't want.
providers:
  openai: {}        # uses OPENAI_API_KEY
  anthropic: {}     # uses ANTHROPIC_API_KEY
  google: {}        # uses GEMINI_API_KEY
  openrouter: {}    # uses OPENROUTER_API_KEY
  # github-copilot needs `bitrouter login github-copilot` first:
  # github-copilot: {}
  # A provider can hold multiple accounts — e.g. two subscriptions to
  # the same upstream. `account_strategy` is `failover` (try the first,
  # drop to the next on a retryable / out-of-credits error — default)
  # or `balance` (spread load evenly across accounts):
  # opencode-go: { account_strategy: failover, accounts: [{ api_key: "${OPENCODE_GO_KEY_A}", label: primary }, { api_key: "${OPENCODE_GO_KEY_B}", label: backup }] }

# Upstream MCP (Model Context Protocol) servers — `bitrouter tools
# list/status` reads this, and `POST /mcp/<name>` proxies JSON-RPC
# against the entry. Spec:
# https://modelcontextprotocol.io/specification/2025-06-18
# mcp_servers:
#   ctx7:
#     name: ctx7
#     transport:
#       type: http
#       url: https://mcp.context7.com/mcp
#       headers:
#         Authorization: "Bearer ${CTX7_TOKEN}"
#   git:
#     name: git
#     transport:
#       type: stdio
#       command: uvx
#       args: ["mcp-server-git"]

# Upstream ACP (Agent Client Protocol) agents — invoked from an editor
# via `bitrouter agent-proxy <id>`. Spec:
# https://agentclientprotocol.com/protocol/schema
# agents:
#   claude:
#     name: claude
#     transport:
#       type: stdio
#       command: npx
#       args: ["-y", "@zed-industries/claude-code-acp@latest"]
#   codex:
#     name: codex
#     transport:
#       type: stdio
#       command: npx
#       args: ["-y", "@zed-industries/codex-acp@latest"]

inherit_defaults: true
"#;

/// `bitrouter init` — write a starter config to `path` (refuses to overwrite).
pub async fn init(path: &std::path::Path) -> Result<()> {
    if tokio::fs::try_exists(path).await.unwrap_or(false) {
        anyhow::bail!("{} already exists — refusing to overwrite", path.display());
    }
    tokio::fs::write(path, STARTER_CONFIG)
        .await
        .with_context(|| format!("writing {}", path.display()))?;
    Ok(())
}

/// The outcome of `bitrouter key generate` — the plaintext secret is shown to
/// the user **once** and never persisted (only its SHA-256 hash is stored).
pub struct GeneratedKey {
    /// The api key id.
    pub id: String,
    /// The plaintext `brvk_…` secret — display once, then discard.
    pub secret: String,
}

/// `bitrouter key sign` — mint a `brvk_` virtual key for `user_id`, persist only
/// its hash, and return the plaintext once. v1 does **not** sign a JWT (004
/// §3.0); the command keeps the `sign` name but creates a DB-backed virtual key.
pub async fn key_sign(
    db_url: &str,
    user_id: &str,
    policy_id: Option<&str>,
) -> Result<GeneratedKey> {
    let db = crate::db::connect(db_url)
        .await
        .with_context(|| format!("connecting to database {db_url}"))?;
    crate::db::run_migrations(&db)
        .await
        .context("running database migrations")?;
    auth_db::upsert_user(&db, user_id)
        .await
        .context("creating user row")?;

    let key = generate();
    let id = format!("brvk_id_{}", &key.hash[..16]);
    auth_db::insert_api_key(
        &db,
        &NewApiKey {
            id: id.clone(),
            key_hash: key.hash.clone(),
            user_id: user_id.to_string(),
            spend_limit_micro_usd: None,
            rpm_limit: None,
            policy_id: policy_id.map(|s| s.to_string()),
        },
    )
    .await
    .context("inserting api key")?;

    Ok(GeneratedKey {
        id,
        secret: key.secret,
    })
}

/// `bitrouter models [--provider <id>]` — list routable models, optionally
/// filtered to those a given provider declares.
pub async fn list_models(
    config: &Config,
    provider_filter: Option<&str>,
) -> Result<Vec<(String, Vec<String>)>> {
    let mut resolved = config.clone();
    bitrouter_providers::apply_builtin_defaults(&mut resolved);
    // Best-effort `/models` discovery for any provider with
    // `auto_discover: true`. Zero-config built-ins set the flag, so
    // this turns `bitrouter models` from "empty" into a useful catalog
    // when the user has the API key set. Failures log and leave the
    // provider with no models — no error bubbles to the user.
    bitrouter_sdk::config::discover_models(&mut resolved).await;
    let table = ConfigRoutingTable::from_config(resolved);
    Ok(table
        .list_models()
        .into_iter()
        .filter(|m| match provider_filter {
            Some(p) => m.providers.iter().any(|x| x == p),
            None => true,
        })
        .map(|m| (m.id, m.providers))
        .collect())
}

/// `bitrouter route <model>` — resolve a model name through the routing table,
/// **standalone** (no running daemon needed). Returns the fallback chain.
pub async fn resolve_route(config: &Config, model: &str) -> Result<Vec<RouteHop>> {
    let mut resolved = config.clone();
    bitrouter_providers::apply_builtin_defaults(&mut resolved);
    let table = ConfigRoutingTable::from_config(resolved);
    let chain = table
        .route_chain(model, &RoutingPrefs::default(), &CallerContext::local())
        .await
        .with_context(|| format!("resolving model '{model}'"))?;
    Ok(chain
        .into_iter()
        .map(|t| RouteHop {
            provider: t.provider_name,
            service_id: t.service_id,
            api_protocol: format!("{:?}", t.api_protocol).to_lowercase(),
        })
        .collect())
}

/// One provider entry for `bitrouter providers list`.
pub struct ProviderListing {
    /// Provider id.
    pub id: String,
    /// Upstream API base.
    pub api_base: String,
    /// Whether the provider is active / routable.
    pub active: bool,
    /// Number of declared models.
    pub model_count: usize,
}

/// `bitrouter providers list` — list every configured provider.
/// Applies built-in catalog defaults first so a zero-config or
/// minimally-declared provider (`openai: {}`) shows its real `api_base`
/// and `active` state instead of empty placeholders.
pub fn list_providers(config: &Config) -> Vec<ProviderListing> {
    let mut resolved = config.clone();
    bitrouter_providers::apply_builtin_defaults(&mut resolved);
    let mut providers: Vec<ProviderListing> = resolved
        .providers
        .iter()
        .map(|(id, p)| ProviderListing {
            id: id.clone(),
            api_base: p.api_base.clone(),
            active: p.active,
            model_count: p.models.len(),
        })
        .collect();
    providers.sort_by(|a, b| a.id.cmp(&b.id));
    providers
}

/// Reject a policy id that would escape its directory or hide as a dotfile.
/// Allowed: ASCII letters / digits / `_` / `-` / `.` (not as the leading char).
fn validate_policy_id(id: &str) -> Result<()> {
    if id.is_empty() {
        anyhow::bail!("policy id must not be empty");
    }
    if id.starts_with('.') {
        anyhow::bail!("policy id must not start with '.' (no dotfiles / `..`)");
    }
    if id.chars().any(|c| {
        c == '/'
            || c == '\\'
            || c == '\0'
            || c.is_whitespace()
            || !(c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
    }) {
        anyhow::bail!(
            "policy id '{id}' contains invalid characters (allowed: letters, digits, `_`, `-`, `.`)"
        );
    }
    Ok(())
}

/// `bitrouter policy create` — write a starter policy file into `policy_dir`.
/// Refuses to overwrite an existing policy of the same id. The `id` must be a
/// plain filename (no path separators, no `..`, no leading dot) so the joined
/// path cannot escape `policy_dir`.
pub async fn create_policy(policy_dir: &std::path::Path, id: &str) -> Result<std::path::PathBuf> {
    validate_policy_id(id)?;
    tokio::fs::create_dir_all(policy_dir)
        .await
        .with_context(|| format!("creating policy dir {}", policy_dir.display()))?;
    let path = policy_dir.join(format!("{id}.yaml"));
    if tokio::fs::try_exists(&path).await.unwrap_or(false) {
        anyhow::bail!("policy '{id}' already exists at {}", path.display());
    }
    let body = format!(
        "# policy '{id}' — edit to taste, then bind it to a key:\n\
         #   bitrouter key sign --user <id> --policy {id}\n\
         id: {id}\n\
         # allowed_models: [gpt-5, claude-sonnet-4-6]\n\
         # denied_models: []\n\
         # max_spend_micro_usd: 1000000\n\
         # max_requests_per_minute: 60\n\
         # allowed_tools: [search]\n"
    );
    tokio::fs::write(&path, body)
        .await
        .with_context(|| format!("writing {}", path.display()))?;
    Ok(path)
}

/// One auth method offered for a provider — derived from the catalog +
/// the PKCE registry. The CLI shows users only the methods the provider
/// actually supports.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AuthMethod {
    /// Browser-based PKCE Authorization Code flow — Anthropic Claude
    /// Pro/Max, OpenAI Codex / ChatGPT.
    PkceSubscription,
    /// RFC 8628 Device Authorization Grant — GitHub Copilot's flow.
    DeviceCode,
    /// User pastes a static API key (sk-…, sk-ant-…).
    ApiKey,
}

impl AuthMethod {
    fn label(self) -> &'static str {
        match self {
            AuthMethod::PkceSubscription => "Subscription (browser sign-in)",
            AuthMethod::DeviceCode => "Device-code OAuth (show a code in browser)",
            AuthMethod::ApiKey => "API key (paste a static credential)",
        }
    }
}

/// Decide which auth methods are wired for `entry`. Order matters — the
/// first entry is what runs when the user hits enter on the prompt.
fn available_methods(entry: &bitrouter_providers::ProviderEntry) -> Vec<AuthMethod> {
    use bitrouter_providers::AuthScheme;
    let mut methods = Vec::new();
    let has_pkce = bitrouter_providers::oauth::registry::has_pkce_flow(&entry.id);
    if has_pkce {
        methods.push(AuthMethod::PkceSubscription);
    }
    match &entry.auth {
        AuthScheme::Bearer { .. } | AuthScheme::Header { .. } => {
            methods.push(AuthMethod::ApiKey);
        }
        AuthScheme::Oauth { params, .. } => {
            // Device-code is only viable when the TOML carries the
            // device authorization endpoint — PKCE-only providers
            // (`openai-codex`) skip this even though their auth scheme
            // is `oauth`.
            let has_device = params
                .get("device_authorization_endpoint")
                .and_then(|v| v.as_str())
                .is_some();
            if has_device {
                methods.push(AuthMethod::DeviceCode);
            }
            // OAuth-only providers don't accept pasted API keys (the
            // Codex backend literally rejects sk-… credentials), so
            // there's no API-key fallback to offer.
        }
        AuthScheme::Native { .. } => {}
    }
    methods
}

/// Prompt for an integer choice between `[1, options.len()]`. Empty
/// input (or just <enter>) picks option 1. Invalid input (non-number,
/// out-of-range) prints a one-line error and re-prompts; a true EOF on
/// stdin (read_line returns 0 bytes) bails so the caller doesn't loop
/// forever in non-interactive contexts.
fn prompt_method_choice(provider: &str, options: &[AuthMethod]) -> Result<AuthMethod> {
    use std::io::BufRead;
    eprintln!();
    eprintln!("How would you like to authenticate to {provider}?");
    for (i, m) in options.iter().enumerate() {
        eprintln!("  {}) {}", i + 1, m.label());
    }
    let stdin = std::io::stdin();
    let mut handle = stdin.lock();
    loop {
        eprint!("Choose [1]: ");
        let mut line = String::new();
        let n_bytes = handle
            .read_line(&mut line)
            .context("reading method choice from stdin")?;
        if n_bytes == 0 {
            anyhow::bail!("stdin closed before a choice was made");
        }
        let trimmed = line.trim();
        if trimmed.is_empty() {
            return Ok(options[0]);
        }
        match trimmed.parse::<usize>() {
            Ok(n) if (1..=options.len()).contains(&n) => return Ok(options[n - 1]),
            Ok(n) => eprintln!("  choice must be between 1 and {}, got {n}", options.len()),
            Err(_) => eprintln!("  '{trimmed}' is not a number"),
        }
    }
}

/// `bitrouter login <provider> [--label <name>]` — interactive credential
/// setup.
///
/// Resolves which auth methods are wired for `provider_id` (subscription
/// PKCE / device-code / API key paste), prompts the user to pick when
/// there's more than one, runs the chosen flow, and persists the
/// resulting [`bitrouter_providers::oauth::credential_store::Credential`]
/// under `(provider_id, label)`.
pub async fn login_provider(provider_id: &str, label: &str) -> Result<()> {
    use bitrouter_providers::builtin;

    let entry = builtin::find(provider_id).ok_or_else(|| {
        anyhow::anyhow!(
            "unknown provider '{provider_id}' — try `bitrouter providers list` for the catalog"
        )
    })?;
    let methods = available_methods(entry);
    if methods.is_empty() {
        anyhow::bail!(
            "provider '{provider_id}' has no interactive login path \
             (auth scheme: {:?})",
            std::mem::discriminant(&entry.auth)
        );
    }
    let chosen = if methods.len() == 1 {
        methods[0]
    } else {
        prompt_method_choice(&entry.display_name, &methods)?
    };
    eprintln!();
    eprintln!(
        "  Logging in to {} via {}",
        entry.display_name,
        chosen.label()
    );

    let credential = match chosen {
        AuthMethod::PkceSubscription => run_pkce_subscription(provider_id).await?,
        AuthMethod::DeviceCode => run_device_code(provider_id, entry).await?,
        AuthMethod::ApiKey => run_api_key_paste(&entry.display_name)?,
    };

    let mut store = bitrouter_providers::oauth::credential_store::CredentialStore::default_path()
        .context("opening credential store")?;
    let kind = credential.kind_label();
    store
        .set(provider_id, label, credential)
        .with_context(|| format!("persisting credential for {provider_id} ({label})"))?;
    eprintln!(
        "  ✓ Saved {kind} credential for {provider_id} (label: {label}) at {}",
        store.path().display()
    );
    eprintln!();
    Ok(())
}

/// Run the browser-based PKCE Authorization Code flow against the
/// PKCE-registered provider. Errors when the provider isn't in
/// `bitrouter_providers::oauth::registry`.
async fn run_pkce_subscription(
    provider_id: &str,
) -> Result<bitrouter_providers::oauth::credential_store::Credential> {
    let registry = bitrouter_providers::oauth::registry::find(provider_id).ok_or_else(|| {
        anyhow::anyhow!(
            "provider '{provider_id}' has no PKCE login registration — \
             this should have been caught by available_methods()"
        )
    })?;
    let client = reqwest::Client::builder()
        .user_agent(concat!("bitrouter/", env!("CARGO_PKG_VERSION")))
        .timeout(std::time::Duration::from_secs(30))
        .build()
        .context("building HTTP client for PKCE login")?;
    let ux = StderrLoginUx;
    let outcome = bitrouter_providers::oauth::login::run_login(
        &client,
        &registry,
        &ux,
        bitrouter_providers::oauth::auth_code::MANUAL_PASTE_TIMEOUT,
    )
    .await
    .with_context(|| format!("PKCE login for {provider_id}"))?;
    if outcome.manual_fallback_used {
        eprintln!("  (used manual paste fallback)");
    }
    Ok(bitrouter_providers::oauth::credential_store::Credential::from_oauth_token(outcome.token))
}

/// Run the RFC 8628 Device Authorization Grant — the existing
/// `github-copilot` flow, lifted out of the old `login_provider`.
async fn run_device_code(
    provider_id: &str,
    entry: &bitrouter_providers::ProviderEntry,
) -> Result<bitrouter_providers::oauth::credential_store::Credential> {
    use bitrouter_providers::AuthScheme;
    let params = match &entry.auth {
        AuthScheme::Oauth { params, .. } => params,
        _ => anyhow::bail!("provider '{provider_id}' is not OAuth — refusing device flow"),
    };
    let client_id = params
        .get("client_id")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("'{provider_id}': auth.params.client_id is missing"))?
        .to_string();
    let scope = params
        .get("scope")
        .and_then(|v| v.as_str())
        .map(str::to_string);
    let device_url = params
        .get("device_authorization_endpoint")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            anyhow::anyhow!("'{provider_id}': auth.params.device_authorization_endpoint is missing")
        })?
        .to_string();
    let token_url = params
        .get("token_endpoint")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("'{provider_id}': auth.params.token_endpoint is missing"))?
        .to_string();

    let flow = bitrouter_providers::oauth::DeviceCodeFlow::new(
        bitrouter_providers::oauth::DeviceCodeParams {
            client_id,
            scope,
            device_authorization_endpoint: device_url,
            token_endpoint: token_url,
        },
    )
    .with_context(|| format!("building OAuth flow for {provider_id}"))?;

    let device_code = flow
        .request_device_code()
        .await
        .with_context(|| format!("requesting OAuth device code for {provider_id}"))?;

    eprintln!();
    eprintln!("  OAuth device authorization for {}", entry.display_name);
    eprintln!("  ──────────────────────────────────────────");
    if let Some(complete) = &device_code.verification_uri_complete {
        eprintln!("  Open:  {complete}");
    } else {
        eprintln!("  Open:  {}", device_code.verification_uri);
    }
    eprintln!("  Code:  {}", device_code.user_code);
    eprintln!();
    eprintln!("  Waiting for authorization…");

    let mut interval = std::time::Duration::from_secs(device_code.interval.max(1));
    let token = loop {
        tokio::time::sleep(interval).await;
        match flow.poll_once(&device_code.device_code).await? {
            bitrouter_providers::oauth::device_code::PollOutcome::Token(t) => break t,
            bitrouter_providers::oauth::device_code::PollOutcome::Pending => continue,
            bitrouter_providers::oauth::device_code::PollOutcome::SlowDown => {
                // RFC 8628 §3.5: server requested back-off — add 5s.
                interval += std::time::Duration::from_secs(5);
            }
        }
    };
    Ok(bitrouter_providers::oauth::credential_store::Credential::from_oauth_token(token))
}

/// Read a static API key from stdin. Input is **not** masked — the user
/// sees what they're pasting, which is the simplest correct UX and
/// matches `gh auth login --with-token`. Future work could wire
/// `rpassword` for a hidden prompt.
fn run_api_key_paste(
    display_name: &str,
) -> Result<bitrouter_providers::oauth::credential_store::Credential> {
    use std::io::BufRead;
    eprintln!();
    eprintln!("  Paste your {display_name} API key, then press enter:");
    eprint!("  > ");
    let stdin = std::io::stdin();
    let mut line = String::new();
    stdin
        .lock()
        .read_line(&mut line)
        .context("reading API key from stdin")?;
    let key = line.trim();
    if key.is_empty() {
        anyhow::bail!("no API key entered — aborting login");
    }
    Ok(bitrouter_providers::oauth::credential_store::Credential::api_key(key))
}

/// `LoginUx` implementation that drives stderr + stdin. Used by the
/// `bitrouter login` CLI; library tests provide their own scripted UX.
struct StderrLoginUx;

#[async_trait::async_trait]
impl bitrouter_providers::oauth::login::LoginUx for StderrLoginUx {
    async fn show_authorize_url(&self, url: &str, hint: &str) {
        eprintln!();
        eprintln!("  Open this URL in your browser to continue:");
        eprintln!();
        eprintln!("    {url}");
        eprintln!();
        eprintln!("  {hint}");
    }

    async fn prompt_pasted_redirect(
        &self,
    ) -> std::result::Result<String, bitrouter_providers::oauth::login::LoginError> {
        // The login flow races this future against the loopback
        // listener. If the listener wins we never read stdin, so a
        // blocking read here would normally pin a thread for the whole
        // OAuth round trip. Run the read on a blocking thread so
        // cancellation (the `tokio::select!` in `run_login` dropping
        // this future when the listener finishes) actually frees it.
        let pasted = tokio::task::spawn_blocking(|| {
            use std::io::BufRead;
            eprint!("  Paste redirect URL (or just the code): ");
            let stdin = std::io::stdin();
            let mut line = String::new();
            stdin.lock().read_line(&mut line).map_err(|e| {
                bitrouter_providers::oauth::login::LoginError::UserIo(format!(
                    "reading pasted redirect: {e}"
                ))
            })?;
            Ok::<_, bitrouter_providers::oauth::login::LoginError>(line)
        })
        .await
        .map_err(|e| {
            bitrouter_providers::oauth::login::LoginError::UserIo(format!(
                "join error reading pasted redirect: {e}"
            ))
        })??;
        Ok(pasted)
    }
}

/// `bitrouter logout <provider>` — drop every stored credential for the
/// provider (subscription OAuth or pasted API key), if any.
pub async fn logout_provider(provider_id: &str) -> Result<()> {
    let mut store = bitrouter_providers::oauth::credential_store::CredentialStore::default_path()
        .context("opening credential store")?;
    let removed = store
        .remove_all_for(provider_id)
        .with_context(|| format!("removing stored credentials for {provider_id}"))?;
    match removed {
        0 => eprintln!("  No stored credentials for {provider_id}; nothing to remove."),
        n => eprintln!("  ✓ Removed {n} stored credential(s) for {provider_id}."),
    }
    Ok(())
}

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

    #[tokio::test]
    async fn init_writes_skip_auth_true_config() {
        let dir = std::env::temp_dir().join(format!(
            "brinit-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        tokio::fs::create_dir_all(&dir).await.unwrap();
        let path = dir.join("bitrouter.yaml");
        init(&path).await.unwrap();
        let written = tokio::fs::read_to_string(&path).await.unwrap();
        assert!(written.contains("skip_auth: true"));
        // and it parses back into a valid Config
        let cfg = bitrouter_sdk::config::parse_with(&written, |_| Some("x".to_string())).unwrap();
        assert!(cfg.server.skip_auth);
        // refuses to overwrite
        assert!(init(&path).await.is_err());
        let _ = tokio::fs::remove_dir_all(&dir).await;
    }

    #[tokio::test]
    async fn key_sign_produces_brvk_secret_and_persists_only_hash() {
        let key = key_sign("sqlite::memory:", "u1", Some("p1")).await.unwrap();
        assert!(key.secret.starts_with("brvk_"));
        assert!(key.id.starts_with("brvk_id_"));
    }

    /// Regression: the `mcp_servers:` and `agents:` blocks in
    /// `STARTER_CONFIG` are commented out by default, but if a user
    /// uncomments them the result must still parse against the current
    /// `Config` schema. This test strips the leading `# ` from those
    /// blocks and reparses; future schema drift fails CI here rather
    /// than fails the next user's `bitrouter init`.
    #[test]
    fn starter_config_parses_with_mcp_and_agents_examples_uncommented() {
        let uncommented: String = STARTER_CONFIG
            .lines()
            .map(|line| {
                // Uncomment any line inside the mcp_servers: / agents:
                // blocks. Those blocks are characterised by lines that
                // start with "# " followed by either the block-header
                // keyword or a key-value pair shaped like YAML.
                let trimmed = line.trim_start();
                if trimmed.starts_with("# mcp_servers:")
                    || trimmed.starts_with("# agents:")
                    || trimmed.starts_with("#   ")
                    || trimmed.starts_with("#     ")
                    || trimmed.starts_with("#       ")
                {
                    let leading_spaces = line.len() - trimmed.len();
                    let stripped = trimmed
                        .strip_prefix("# ")
                        .or_else(|| trimmed.strip_prefix("#"))
                        .unwrap_or(trimmed);
                    format!("{}{}", " ".repeat(leading_spaces), stripped)
                } else {
                    line.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("\n");
        let cfg = bitrouter_sdk::config::parse_with(&uncommented, |_| Some("x".to_string()))
            .expect("uncommented STARTER_CONFIG must parse against current schema");
        assert!(
            !cfg.mcp_servers.is_empty(),
            "mcp_servers block should land as parsed entries; got: {:?}",
            cfg.mcp_servers.keys().collect::<Vec<_>>()
        );
        assert!(
            !cfg.agents.is_empty(),
            "agents block should land as parsed entries; got: {:?}",
            cfg.agents.keys().collect::<Vec<_>>()
        );
    }

    fn sample_config() -> Config {
        let yaml = r#"
providers:
  openai:
    api_base: https://api.openai.com/v1
    api_key: k1
    models: [{ id: gpt-5 }, { id: shared }]
  anthropic:
    api_base: https://api.anthropic.com/v1
    api_key: k2
    models: [{ id: shared }]
"#;
        bitrouter_sdk::config::parse_with(yaml, |_| None).unwrap()
    }

    #[tokio::test]
    async fn list_models_filters_by_provider() {
        let cfg = sample_config();
        let all = list_models(&cfg, None).await.unwrap();
        assert_eq!(all.len(), 2); // gpt-5, shared
        let openai_only = list_models(&cfg, Some("openai")).await.unwrap();
        assert_eq!(openai_only.len(), 2); // gpt-5 + shared (openai declares both)
        let anthropic_only = list_models(&cfg, Some("anthropic")).await.unwrap();
        assert_eq!(anthropic_only.len(), 1); // only `shared`
        assert_eq!(anthropic_only[0].0, "shared");
    }

    #[tokio::test]
    async fn resolve_route_returns_the_cascade_chain() {
        let cfg = sample_config();
        // `shared` is declared by both providers → a 2-hop alphabetical chain
        let chain = resolve_route(&cfg, "shared").await.unwrap();
        assert_eq!(chain.len(), 2);
        assert_eq!(chain[0].provider, "anthropic");
        assert_eq!(chain[1].provider, "openai");
        // an unknown model is a clean error (no DEFAULT_PROVIDER fallback)
        assert!(resolve_route(&cfg, "no-such-model").await.is_err());
    }

    #[test]
    fn list_providers_sorts_and_summarises() {
        let providers = list_providers(&sample_config());
        assert_eq!(providers.len(), 2);
        assert_eq!(providers[0].id, "anthropic");
        assert_eq!(providers[1].id, "openai");
        assert_eq!(providers[1].model_count, 2);
        assert!(providers[1].active);
    }

    #[tokio::test]
    async fn create_policy_rejects_path_traversal_ids() {
        let dir = std::env::temp_dir().join(format!(
            "brpoltrav-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        // Path separators, parent refs, dotfiles, control chars — all rejected
        // before any file is written.
        for bad in [
            "../etc/passwd",
            "foo/bar",
            "..",
            ".hidden",
            "",
            "a b",
            "x\0y",
        ] {
            let err = create_policy(&dir, bad).await.unwrap_err();
            let msg = format!("{err}");
            assert!(
                msg.contains("invalid characters")
                    || msg.contains("must not")
                    || msg.contains("empty"),
                "bad id '{bad}' should have been rejected; got: {msg}"
            );
        }
        // The dir was never created (because every call bailed before touching fs).
        // (We don't assert this strongly — a parallel test could create it — just clean up.)
        let _ = tokio::fs::remove_dir_all(&dir).await;
    }

    #[tokio::test]
    async fn create_policy_writes_a_starter_file() {
        let dir = std::env::temp_dir().join(format!(
            "brpol-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let path = create_policy(&dir, "team-default").await.unwrap();
        let body = tokio::fs::read_to_string(&path).await.unwrap();
        assert!(body.contains("id: team-default"));
        // a re-create refuses to overwrite
        assert!(create_policy(&dir, "team-default").await.is_err());
        let _ = tokio::fs::remove_dir_all(&dir).await;
    }
}