bitrouter 1.0.0-alpha.32

BitRouter: an LLM API router. CLI + 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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
//! 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::invocation;
use bitrouter_sdk::language_model::routing::ModelInfo;
use bitrouter_sdk::language_model::{RoutingPrefs, RoutingTable};

use crate::actions::skills::SkillsReport;
use crate::auth::{NewApiKey, db as auth_db, generate};
use crate::daemon::RouteHop;
use crate::output::reports::skills::SkillInitReport;

/// The starter `bitrouter.yaml` written by `bro 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 `bro 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
  # `bro 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 `bro key
  # sign` for a multi-tenant deployment.
  skip_auth: true

# Retryable fallback is immediate by default. For providers that can return a
# short overload burst, opt into a bounded delay schedule. Values apply before
# the 2nd, 3rd, ... route candidate; the final value repeats for longer chains.
# upstream:
#   fallback_backoff_ms: [1000, 2000, 4000, 8000, 16000, 30000]

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"

# Routing policies are opt-in and live in a sibling policy-lock.yaml.
# `bro policy init <name> --preset <preset> --strong <model>
# --economy <model>` creates the lock and preset binding. With no binding,
# model routing behaves exactly as it does in zero-config mode.

# 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 `bro providers 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 — `bro tools
# list/status` reads this, and `POST /mcp/<name>` proxies JSON-RPC
# against the entry. Discover servers from the official MCP registry
# with `bro mcp search <query>` and print a paste-ready stub with
# `bro mcp add <name>`. 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 — manage with
# `bro agents list` / `check` / `install`. Spec:
# https://agentclientprotocol.com/protocol/schema
# agents:
#   claude:
#     name: claude
#     transport:
#       type: stdio
#       command: npx
#       args: ["-y", "@agentclientprotocol/claude-agent-acp@0.70.0"]
#   codex:
#     name: codex
#     transport:
#       type: stdio
#       command: npx
#       args: ["-y", "@agentclientprotocol/codex-acp@1.7.0"]

inherit_defaults: true
"#;

/// Outcome of a [`write_starter_config`] scaffold write.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScaffoldOutcome {
    /// The starter `bitrouter.yaml` was written.
    Wrote,
    /// A file already existed and `force` was not set — left untouched.
    Skipped,
}

/// `bro init` — write the starter `bitrouter.yaml` to `path`. Without
/// `force`, an existing file is left untouched (returns
/// [`ScaffoldOutcome::Skipped`]) so the onboarding wizard's `--yes` run never
/// clobbers a config the user already tuned; with `force` it overwrites. This
/// is the single sanctioned `bitrouter.yaml` write — nothing else in the tree
/// serializes a `Config`.
pub async fn write_starter_config(path: &std::path::Path, force: bool) -> Result<ScaffoldOutcome> {
    if !force && tokio::fs::try_exists(path).await.unwrap_or(false) {
        return Ok(ScaffoldOutcome::Skipped);
    }
    tokio::fs::write(path, STARTER_CONFIG)
        .await
        .with_context(|| format!("writing {}", path.display()))?;
    Ok(ScaffoldOutcome::Wrote)
}

/// The outcome of `bro 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,
}

/// `bro 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,
    })
}

/// The routable catalog a config alone can describe — the fallback the
/// `list_models` action uses when no daemon answers.
///
/// Unfiltered by design: `bro models --provider` and the MCP tool's
/// `provider` argument are one filter applied to the shared report
/// (`ModelsReport::filtered`), so neither surface can narrow it its own way.
///
/// **Does network I/O.** `discover_models` probes each `auto_discover: true`
/// provider's `/models` endpoint, which is what turns a zero-config install
/// from "empty" into a useful catalog. Per-request timeouts bound it (2s
/// connect, 5s total) and failures leave the provider with no models rather
/// than bubbling an error, but a caller on a hot path should prefer the
/// daemon: see `crate::actions::models`.
pub async fn list_models(config: &Config) -> Result<Vec<ModelInfo>> {
    let mut resolved = resolve_static(config.clone());
    bitrouter_sdk::config::discover_models(&mut resolved).await;
    Ok(ConfigRoutingTable::from_config(resolved).list_models())
}

/// A config as the daemon sees it at start-up, minus network discovery: the
/// built-in provider defaults applied, then every provider with a credential
/// in the OAuth store re-activated.
///
/// The second step is what a plain `apply_builtin_defaults` pass misses. A
/// subscription / "use your Claude Code session" login stores its credential in
/// the store, not the config, so the defaults pass marks that provider inactive
/// for want of an api key and the routing table drops it — and a standalone
/// answer (`bro models` / `route` with no daemon, `spawn`'s preflight)
/// would then be missing exactly the providers the daemon routes to. Mirrors
/// `assemble.rs`; best-effort, an unreadable store is a no-op.
pub fn resolve_static(mut config: Config) -> Config {
    bitrouter_providers::apply_builtin_defaults(&mut config);
    if let Ok(store) = bitrouter_providers::oauth::credential_store::CredentialStore::default_path()
    {
        bitrouter_providers::activate_stored_credential_providers(&mut config, &store);
    }
    config
}

/// `bro 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 table = ConfigRoutingTable::from_config(resolve_static(config.clone()));
    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 `bro 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,
}

/// `bro 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(())
}

/// `bro 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\
         #   bro 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 {
    /// Use the user's existing Claude Code session: read its OAuth credential
    /// live from `~/.claude` (Keychain / `.credentials.json`), or sign in via
    /// the `claude` CLI when not yet logged in. The preferred path for
    /// `anthropic` — no second token copy, so it can't refresh-rotate Claude
    /// Code out (RFC 6749 §6).
    ClaudeCodeSession,
    /// Browser-based PKCE Authorization Code flow — Anthropic Claude
    /// Pro/Max, OpenAI Codex / ChatGPT.
    PkceSubscription,
    /// Adopt an existing session from the provider's own vendor CLI (Claude
    /// Code, Codex) by reading its on-disk / Keychain OAuth token — no browser.
    ImportFromCli,
    /// 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::ClaudeCodeSession => {
                "Use your Claude Code session (read ~/.claude, or sign in via the claude CLI)"
            }
            AuthMethod::PkceSubscription => "Subscription (browser sign-in)",
            AuthMethod::ImportFromCli => "Import an existing session from the vendor CLI",
            AuthMethod::DeviceCode => "Device-code OAuth (show a code in browser)",
            AuthMethod::ApiKey => "API key (paste a static credential)",
        }
    }
}

/// The vendor CLI bitrouter can adopt an existing OAuth session from, for
/// providers that ship one — `Codex` for `openai-codex`. `None` for every
/// other provider.
///
/// `anthropic` is **not** listed: it is now the platform / pay-as-you-go
/// provider (`x-api-key` only). Adopting a Claude Code session is the
/// `claude-code` subscription provider's job, handled by
/// [`AuthMethod::ClaudeCodeSession`] (a *live* session read, not a one-shot
/// token copy), so there is no vendor-CLI import for `anthropic`.
fn import_cli_for(provider_id: &str) -> Option<&'static str> {
    match provider_id {
        bitrouter_providers::codex::PROVIDER_ID => Some("Codex"),
        bitrouter_providers::supergrok::PROVIDER_ID => Some("Grok"),
        bitrouter_providers::antigravity::PROVIDER_ID => Some("Antigravity (agy)"),
        _ => None,
    }
}

/// 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();
    // The Claude subscription's preferred (and only) path: read the user's live
    // Claude Code session and let the `claude` CLI own login. It belongs to the
    // dedicated `claude-code` subscription provider — `anthropic` is now the
    // platform / pay-as-you-go provider and offers the API-key path only.
    // Listed first so it's the default on <enter> / non-interactive runs.
    let is_claude_code = entry.id == bitrouter_providers::claude_code::PROVIDER_ID;
    if is_claude_code {
        methods.push(AuthMethod::ClaudeCodeSession);
    }
    // Providers with a sibling vendor CLI can adopt its existing session as a
    // one-shot copy — currently only Codex (`openai-codex`). List that before
    // PKCE so the default path reuses an already-authenticated local CLI
    // session when one exists.
    if import_cli_for(&entry.id).is_some() {
        methods.push(AuthMethod::ImportFromCli);
    }
    // `anthropic` is platform / pay-as-you-go: offer the API-key path only. The
    // PKCE registry still carries an `anthropic` entry (the Claude subscription
    // browser flow), but that subscription path now belongs to the dedicated
    // `claude-code` provider, so it must not be offered under `anthropic`.
    let is_anthropic = entry.id == bitrouter_providers::anthropic::PROVIDER_ID;
    let has_pkce = !is_anthropic && 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
}

/// Use the same searchable keyboard selector as onboarding.
async fn prompt_method_choice(provider: &str, options: &[AuthMethod]) -> Result<AuthMethod> {
    let index = crate::prompt::select(
        &format!("Log in to {provider}"),
        "Choose an authentication method",
        options
            .iter()
            .map(|method| bitrouter_tui::select::Item::new(method.label(), ""))
            .collect(),
        0,
    )
    .await?;
    options
        .get(index)
        .copied()
        .context("no authentication method selected")
}

/// `bro providers 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)`.
/// What `login_provider` accomplished — surfaced as the CLI's JSON result while
/// the interactive prompts and confirmation go to stderr.
pub struct LoginOutcome {
    pub provider: String,
    pub label: String,
    pub method: String,
    pub path: String,
}

/// Non-interactive provider-login controls.
#[derive(Debug, Clone, Default)]
pub struct ProviderLoginOptions {
    /// Require importing an already-authenticated vendor CLI session.
    pub import_existing: bool,
    /// Refuse browser-based PKCE flows.
    pub no_browser: bool,
    /// Seed the credential directly from this API key, skipping the interactive
    /// method choice and the stdin paste entirely. Set by `providers login
    /// --api-key` / `--key-stdin` and the onboarding wizard's per-provider
    /// `--provider-api-key`. The provider must offer the API-key method.
    pub api_key: Option<String>,
}

pub async fn login_provider(provider_id: &str, label: &str) -> Result<LoginOutcome> {
    login_provider_with_options(provider_id, label, ProviderLoginOptions::default()).await
}

pub async fn login_provider_with_options(
    provider_id: &str,
    label: &str,
    options: ProviderLoginOptions,
) -> Result<LoginOutcome> {
    use bitrouter_providers::builtin;

    // Cloud and the maintained ACP subscription providers have bundled login
    // defaults. Other providers resolve against the fetched/cached registry.
    let entry: bitrouter_providers::ProviderEntry = match builtin::find(provider_id)
        .cloned()
        .or(crate::bundled_registry::provider(provider_id)?)
    {
        Some(e) => e,
        None => {
            let data =
                crate::bundled_registry::load(&bitrouter_sdk::config::RegistryConfig::default())
                    .await
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "could not load the provider registry (offline, and nothing cached) \
                     to resolve '{provider_id}'"
                        )
                    })?;
            let provider = data
                .providers
                .iter()
                .find(|p| p.name == provider_id)
                .ok_or_else(|| {
                    anyhow::anyhow!(
                        "unknown provider '{provider_id}' — try `{cli} providers list` \
                         for the catalog",
                        cli = invocation::name()
                    )
                })?;
            builtin::entry_from_registry(provider)
                .with_context(|| format!("resolving the auth shape for '{provider_id}'"))?
        }
    };
    login_entry(&entry, label, options).await
}

/// Onboarding uses the exact registry entry shown in its provider list.
pub(crate) async fn login_registry_provider(
    provider: &bitrouter_providers::registry::types::RegistryProvider,
) -> Result<LoginOutcome> {
    let entry = bitrouter_providers::builtin::entry_from_registry(provider)?;
    login_entry(
        &entry,
        bitrouter_providers::oauth::credential_store::DEFAULT_LABEL,
        ProviderLoginOptions::default(),
    )
    .await
}

async fn login_entry(
    entry: &bitrouter_providers::ProviderEntry,
    label: &str,
    options: ProviderLoginOptions,
) -> Result<LoginOutcome> {
    let provider_id = entry.id.as_str();
    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 = choose_auth_method(entry, &methods, &options).await?;
    eprintln!();
    eprintln!(
        "  Logging in to {} via {}",
        entry.display_name,
        chosen.label()
    );

    let credential = match chosen {
        AuthMethod::ClaudeCodeSession => run_claude_code_session().await?,
        AuthMethod::PkceSubscription => run_pkce_subscription(provider_id).await?,
        AuthMethod::ImportFromCli => run_cli_import(provider_id)?,
        AuthMethod::DeviceCode => run_device_code(provider_id, entry).await?,
        // A flag-supplied key (`--api-key` / `--key-stdin` / the wizard) skips
        // the interactive stdin paste; otherwise prompt for it.
        AuthMethod::ApiKey => match options.api_key.as_deref() {
            Some(key) => {
                let key = key.trim();
                if key.is_empty() {
                    anyhow::bail!("the supplied API key is empty — aborting login");
                }
                bitrouter_providers::oauth::credential_store::Credential::api_key(key)
            }
            None => 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(LoginOutcome {
        provider: provider_id.to_string(),
        label: label.to_string(),
        method: kind.to_string(),
        path: store.path().display().to_string(),
    })
}

async fn choose_auth_method(
    entry: &bitrouter_providers::ProviderEntry,
    methods: &[AuthMethod],
    options: &ProviderLoginOptions,
) -> Result<AuthMethod> {
    // A supplied API key is the most explicit signal — take the API-key method
    // directly, or fail clearly if the provider doesn't offer one (OAuth-only
    // backends reject pasted keys).
    if options.api_key.is_some() {
        if methods.contains(&AuthMethod::ApiKey) {
            return Ok(AuthMethod::ApiKey);
        }
        anyhow::bail!(
            "provider '{}' does not accept a pasted API key — it uses an \
             interactive OAuth flow; drop --api-key/--key-stdin",
            entry.id
        );
    }

    if options.import_existing {
        if methods.contains(&AuthMethod::ImportFromCli) {
            return Ok(AuthMethod::ImportFromCli);
        }
        anyhow::bail!(
            "provider '{}' cannot import an existing vendor CLI session",
            entry.id
        );
    }

    let selectable: Vec<AuthMethod> = if options.no_browser {
        methods
            .iter()
            .copied()
            .filter(|m| *m != AuthMethod::PkceSubscription)
            .collect()
    } else {
        methods.to_vec()
    };
    if selectable.is_empty() {
        anyhow::bail!(
            "provider '{}' has no non-browser login path; rerun without --no-browser",
            entry.id
        );
    }
    if selectable.len() == 1 || options.no_browser {
        Ok(selectable[0])
    } else {
        prompt_method_choice(&entry.display_name, &selectable).await
    }
}

/// Adopt the user's existing Claude Code session as the live credential source
/// for the `claude-code` subscription provider.
///
/// Resolution order, mirroring how Claude Code users actually authenticate:
/// 1. If a Claude Code session already exists in `~/.claude` (macOS Keychain /
///    `.credentials.json`), use it as-is — the daemon reads it live and
///    refreshes in place.
/// 2. Otherwise sign the user in with the `claude` CLI itself (`claude auth
///    login --claudeai`), installing it first (the same native installer
///    `bro spawn` uses) when it's missing, then re-read.
///
/// Returns a [`Credential::ClaudeCodeCli`] marker — no token is copied into
/// bitrouter's own store, so bitrouter and Claude Code share one credential and
/// can't refresh-rotate each other out (RFC 6749 §6). `login_provider` stores
/// this marker under the `provider_id` it was invoked with, so
/// `bro providers login claude-code` lands it under `claude-code`.
///
/// # Why this names a login command, when the ACP path may not
///
/// `docs/ACP_AUTH_SPEC.md` §6.1 forbids writing a harness's login command in
/// BitRouter — the harness declares it, or it is not offered. That rule governs
/// the **agent-authentication** axis, and the ACP paths obey it: they read
/// `authMethods` and run what the harness declared.
///
/// This is the other axis. `claude-code` here is a *provider*, and the `claude`
/// CLI is its vendor tool, exactly as the Codex, Grok, and Antigravity CLIs are
/// their providers' (see `import_cli_for`). Routing this through an ACP harness
/// to avoid naming the command would make provider login depend on an ACP
/// adapter being installed — `npx`, a download, a controller — to acquire a
/// credential that has nothing to do with ACP, and would re-conflate the two
/// axes §6.4 exists to keep apart. So the command is named here deliberately.
/// What can be improved is the *seam*, which is what the framing below does.
async fn run_claude_code_session()
-> Result<bitrouter_providers::oauth::credential_store::Credential> {
    use std::io::IsTerminal;

    use bitrouter_providers::import::claude_code::ClaudeCodeStore;
    use bitrouter_providers::oauth::credential_store::Credential;

    // Adopt a legacy #590 marker stored under `anthropic` before checking the
    // live session, so a returning user's existing sign-in is recognised under
    // the new `claude-code` provider.
    crate::claude_code::migrate_legacy_anthropic_marker_default();

    let store = ClaudeCodeStore::system().ok_or_else(|| {
        anyhow::anyhow!(
            "could not resolve your home directory (set HOME) to find the Claude Code session"
        )
    })?;

    // 1. Already signed in to Claude Code?
    if let Some(live) = store
        .read()
        .context("reading your existing Claude Code session")?
    {
        eprintln!(
            "  Found your Claude Code session ({}) — bitrouter will read it live.",
            live.source
        );
        return Ok(Credential::ClaudeCodeCli);
    }

    // 2. Not signed in — drive the `claude` CLI's own login.
    if !std::io::stdin().is_terminal() {
        anyhow::bail!(
            "not signed in to Claude Code. Run `claude auth login` (install the CLI first with \
             `curl -fsSL https://claude.ai/install.sh | bash`), then re-run \
             `bro providers login claude-code`."
        );
    }

    let claude = crate::spawn::ensure_agent_installed(crate::spawn::SpawnAgent::Claude, false)
        .await
        .context("locating the claude CLI to sign you in")?;

    // The handoff is stated before it happens, and marked at both ends.
    //
    // What follows is a *different program's* interactive flow, printing into
    // the same terminal with nothing to distinguish it from bitrouter's own
    // output. Its prompt reads "Paste code here if prompted", which is the
    // `claude` CLI hedging across its flows — in the browser-code flow the
    // paste is required, and a reader who takes "if" at face value closes the
    // window and gets a bare 403. Naming the boundary is what this can fix; the
    // child's own wording is not ours to change.
    eprintln!("  You're not signed in to Claude Code yet.");
    eprintln!("  Handing over to `claude auth login` — it is a separate program.");
    eprintln!("  It opens a browser, and may then ask you to paste a code back here.");
    eprintln!("  Complete both steps; this command resumes when it exits.");
    eprintln!("  ─────────────────────────────────────────────────────────────");
    let status = tokio::process::Command::new(&claude)
        .arg("auth")
        .arg("login")
        .arg("--claudeai")
        .status()
        .await
        .context("running `claude auth login`")?;
    eprintln!("  ─────────────────────────────────────────────────────────────");
    if !status.success() {
        // Which step failed is the child's to know, so this says what is true
        // — it ended without signing in — and names the command that reports
        // the state, rather than guessing at a cause.
        anyhow::bail!(
            "`claude auth login` exited without completing the sign-in ({status}). \
             If a browser opened, the flow may still need the code from it pasted \
             into that prompt. Check with `claude auth status`, then re-run \
             `bro providers login claude-code`."
        );
    }

    match store
        .read()
        .context("re-reading your Claude Code session after sign-in")?
    {
        Some(live) => {
            eprintln!(
                "  Signed in — bitrouter will read your session live from {}.",
                live.source
            );
            Ok(Credential::ClaudeCodeCli)
        }
        None => anyhow::bail!(
            "still no Claude Code session after `claude auth login` — run `claude auth status` \
             to check, then retry."
        ),
    }
}

/// 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))
}

/// Adopt an existing OAuth session from the provider's sibling vendor CLI
/// (Codex for `openai-codex`) by reading its on-disk / Keychain credential.
/// Errors when no such session is found.
///
/// `anthropic` is intentionally absent: it is the platform / pay-as-you-go
/// provider now, and the Claude Code session is adopted *live* by the
/// `claude-code` provider via [`run_claude_code_session`] — not copied in here
/// (the one-shot copy is what risked the RFC 6749 §6 family-revoke).
fn run_cli_import(
    provider_id: &str,
) -> Result<bitrouter_providers::oauth::credential_store::Credential> {
    let imported = match provider_id {
        bitrouter_providers::codex::PROVIDER_ID => bitrouter_providers::import::codex::import(),
        bitrouter_providers::supergrok::PROVIDER_ID => bitrouter_providers::import::grok::import(),
        bitrouter_providers::antigravity::PROVIDER_ID => {
            bitrouter_providers::import::antigravity::import()
        }
        other => anyhow::bail!("no vendor-CLI import is available for provider '{other}'"),
    }
    .with_context(|| format!("importing a CLI credential for {provider_id}"))?;
    let imported = imported.ok_or_else(|| {
        anyhow::anyhow!(
            "no existing CLI session found for {provider_id} — sign in to the \
             vendor CLI first, or choose the browser sign-in instead"
        )
    })?;
    eprintln!("  Imported existing session from {}", imported.source);
    Ok(bitrouter_providers::oauth::credential_store::Credential::from_oauth_token(imported.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> {
    Ok(
        bitrouter_providers::oauth::credential_store::Credential::api_key(read_api_key(
            display_name,
        )?),
    )
}

pub(crate) fn read_api_key(display_name: &str) -> Result<String> {
    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(key.to_string())
}

/// `LoginUx` implementation that drives stderr + stdin. Used by the
/// `bro providers 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)
    }
}

/// `bro providers 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<usize> {
    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(removed)
}

// ===== skills (format + local reads) =====
//
// `add`, `remove`, `find`, and `update` were removed with the skills package
// manager: installing skills is the ecosystem's job (`npx skills add`, the
// Claude Code and Codex plugin marketplaces), not a router's. What remains
// reads the installed-skills directory and scaffolds a `SKILL.md`. See
// `crate::skills` for the reasoning.

/// `bro skills list` — the skills under the chosen root.
///
/// One [action](crate::actions::skills), shared by the CLI report and local
/// session consumers. It gains two things the old single `read_dir` could not
/// do: the `./skills/foo`
/// and root-level layouts, and a `problem` on any skill that cannot actually be
/// loaded.
pub fn skills_list(global: bool) -> Result<SkillsReport> {
    let cwd = std::env::current_dir().context("resolving the current directory")?;
    let roots = crate::skills::root::SkillsRoot::cli_scope(global, cwd)?;
    Ok(crate::actions::skills::InstalledSkills::new(roots).report())
}

/// `bro skills init` — scaffold a SKILL.md.
pub fn skills_init(name: &str, output: &std::path::Path) -> Result<SkillInitReport> {
    crate::skills::validate_skill_name(name)?;
    if output.file_name().and_then(|file| file.to_str()) != Some("SKILL.md") {
        anyhow::bail!("skill output must be named SKILL.md");
    }
    let declared_parent = output
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| std::path::Path::new("."));
    let resolved_parent = if declared_parent == std::path::Path::new(".") {
        std::env::current_dir().context("resolving the current directory")?
    } else {
        declared_parent.to_path_buf()
    };
    if resolved_parent.file_name().and_then(|dir| dir.to_str()) != Some(name) {
        anyhow::bail!("skill parent directory must be named '{name}' to match its frontmatter");
    }
    if output.exists() {
        anyhow::bail!("{} already exists; refusing to overwrite", output.display());
    }
    std::fs::create_dir_all(declared_parent)
        .with_context(|| format!("creating {}", declared_parent.display()))?;
    let body = format!(
        "---\nname: {name}\ndescription: TODO — one line on what this skill does and when to use it.\n---\n\n# {name}\n\nTODO: instructions for the agent.\n\n## When to use\n\n## Steps\n"
    );
    std::fs::write(output, body).with_context(|| format!("writing {}", output.display()))?;
    Ok(SkillInitReport {
        path: output.display().to_string(),
        created: true,
    })
}

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

    #[test]
    fn scaffold_requires_skill_md_under_the_named_directory() {
        let dir = tempfile::tempdir().expect("tempdir");
        let wrong = dir.path().join("other").join("SKILL.md");
        std::fs::create_dir_all(wrong.parent().expect("parent")).expect("mkdir");

        let Err(err) = skills_init("demo", &wrong) else {
            panic!("directory/name mismatch must be invalid");
        };
        assert!(err.to_string().contains("parent directory"), "{err}");
    }

    #[test]
    fn scaffold_creates_a_valid_named_skill_directory() {
        let dir = tempfile::tempdir().expect("tempdir");
        let output = dir.path().join("demo").join("SKILL.md");

        let report = skills_init("demo", &output).expect("scaffold");

        assert!(output.is_file());
        assert_eq!(report.path, output.display().to_string());
        let parsed = crate::skills::format::parse_frontmatter(
            &std::fs::read_to_string(output).expect("read scaffold"),
        )
        .expect("valid frontmatter");
        assert_eq!(parsed.name, "demo");
    }
}

#[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");
        assert_eq!(
            write_starter_config(&path, false).await.unwrap(),
            ScaffoldOutcome::Wrote
        );
        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);
        // Without --force, an existing file is left untouched (Skipped) — the
        // wizard's `--yes` run must never clobber a tuned config.
        tokio::fs::write(&path, "# hand-edited\n").await.unwrap();
        assert_eq!(
            write_starter_config(&path, false).await.unwrap(),
            ScaffoldOutcome::Skipped
        );
        assert_eq!(
            tokio::fs::read_to_string(&path).await.unwrap(),
            "# hand-edited\n"
        );
        // With --force it overwrites.
        assert_eq!(
            write_starter_config(&path, true).await.unwrap(),
            ScaffoldOutcome::Wrote
        );
        assert!(
            tokio::fs::read_to_string(&path)
                .await
                .unwrap()
                .contains("skip_auth: true")
        );
        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 for the out-of-the-box `bro init` → `start` failure:
    /// the starter config ships a *commented* `opencode-go` example that
    /// references `${OPENCODE_GO_KEY_A/B}`. The loader expands `${VAR}` over the
    /// raw text before YAML parsing, so it used to error on those unset vars
    /// even though they live in a comment. With comment-aware substitution the
    /// starter config must load with **no** environment variables set.
    #[test]
    fn starter_config_loads_with_all_env_vars_unset() {
        let cfg = bitrouter_sdk::config::parse_with(STARTER_CONFIG, |_| None)
            .expect("starter config must load with no env vars set");
        assert!(cfg.server.skip_auth);
    }

    /// 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 `bro 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<_>>()
        );
    }

    /// Build a [`ProviderEntry`] from a registry-provider fixture — anthropic
    /// and openai-codex are no longer compiled-in built-ins, so `login` resolves
    /// their auth shape from the fetched registry via `entry_from_registry`.
    fn entry_for(json: serde_json::Value) -> bitrouter_providers::ProviderEntry {
        let p: bitrouter_providers::registry::types::RegistryProvider =
            serde_json::from_value(json).expect("valid registry-provider fixture");
        bitrouter_providers::builtin::entry_from_registry(&p).expect("maps to an entry")
    }

    #[test]
    fn claude_code_prefers_claude_code_session_first() {
        // The `claude-code` subscription provider — the live Claude Code session
        // is its default (and the marker lands under `claude-code`).
        let entry = entry_for(serde_json::json!({
            "name": "claude-code",
            "api_base": "https://api.anthropic.com/v1",
            "status": "active",
            "auth": { "kind": "oauth", "handler": "claude-code" },
            "models": []
        }));
        let methods = available_methods(&entry);
        assert_eq!(
            methods.first(),
            Some(&AuthMethod::ClaudeCodeSession),
            "the live Claude Code session must be the default for claude-code"
        );
        assert!(
            !methods.contains(&AuthMethod::ImportFromCli),
            "claude-code uses the live session, not the one-shot copy that can family-revoke"
        );
    }

    #[test]
    fn anthropic_offers_api_key_only() {
        // `anthropic` is now platform / pay-as-you-go: API-key paste only — no
        // Claude Code session, no subscription PKCE, no vendor-CLI import. The
        // subscription path moved to the `claude-code` provider.
        let entry = entry_for(serde_json::json!({
            "name": "anthropic",
            "api_base": "https://api.anthropic.com/v1",
            "status": "active",
            "auth": { "kind": "header", "header": "x-api-key", "env": "ANTHROPIC_API_KEY" },
            "models": []
        }));
        let methods = available_methods(&entry);
        assert_eq!(
            methods,
            vec![AuthMethod::ApiKey],
            "anthropic must offer the API-key path only"
        );
        assert!(!methods.contains(&AuthMethod::ClaudeCodeSession));
        assert!(!methods.contains(&AuthMethod::PkceSubscription));
        assert!(!methods.contains(&AuthMethod::ImportFromCli));
    }

    #[test]
    fn codex_keeps_oneshot_import_and_offers_no_claude_code_session() {
        let entry = entry_for(serde_json::json!({
            "name": "openai-codex",
            "api_base": "https://chatgpt.com/backend-api/codex",
            "status": "active",
            "auth": { "kind": "oauth", "handler": "openai-codex" },
            "models": []
        }));
        let methods = available_methods(&entry);
        assert_eq!(
            methods.first(),
            Some(&AuthMethod::ImportFromCli),
            "openai-codex onboarding should first reuse an existing Codex CLI session"
        );
        assert!(methods.contains(&AuthMethod::ImportFromCli));
        assert!(methods.contains(&AuthMethod::PkceSubscription));
        assert!(!methods.contains(&AuthMethod::ClaudeCodeSession));
    }

    #[tokio::test]
    async fn import_existing_selects_vendor_cli_import_without_prompting() -> Result<()> {
        let entry = entry_for(serde_json::json!({
            "name": "openai-codex",
            "api_base": "https://chatgpt.com/backend-api/codex",
            "status": "active",
            "auth": { "kind": "oauth", "handler": "openai-codex" },
            "models": []
        }));
        let methods = available_methods(&entry);
        let chosen = choose_auth_method(
            &entry,
            &methods,
            &ProviderLoginOptions {
                import_existing: true,
                no_browser: true,
                api_key: None,
            },
        )
        .await?;
        assert_eq!(chosen, AuthMethod::ImportFromCli);
        Ok(())
    }

    #[tokio::test]
    async fn api_key_option_selects_api_key_method_without_prompting() -> Result<()> {
        // A `--api-key`/`--key-stdin`-supplied key drives the non-interactive
        // BYOK path: `anthropic` offers the API-key method, so it's chosen.
        let entry = entry_for(serde_json::json!({
            "name": "anthropic",
            "api_base": "https://api.anthropic.com/v1",
            "status": "active",
            "auth": { "kind": "header", "header": "x-api-key", "env": "ANTHROPIC_API_KEY" },
            "models": []
        }));
        let methods = available_methods(&entry);
        let chosen = choose_auth_method(
            &entry,
            &methods,
            &ProviderLoginOptions {
                import_existing: false,
                no_browser: false,
                api_key: Some("sk-ant-test".to_string()),
            },
        )
        .await?;
        assert_eq!(chosen, AuthMethod::ApiKey);
        Ok(())
    }

    #[tokio::test]
    async fn api_key_option_rejects_oauth_only_providers() -> Result<()> {
        // `openai-codex` is OAuth-only (no API-key method); a supplied key is a
        // clear error rather than a silently-ignored flag.
        let entry = entry_for(serde_json::json!({
            "name": "openai-codex",
            "api_base": "https://chatgpt.com/backend-api/codex",
            "status": "active",
            "auth": { "kind": "oauth", "handler": "openai-codex" },
            "models": []
        }));
        let methods = available_methods(&entry);
        let err = choose_auth_method(
            &entry,
            &methods,
            &ProviderLoginOptions {
                import_existing: false,
                no_browser: false,
                api_key: Some("sk-whatever".to_string()),
            },
        )
        .await
        .err()
        .context("login flags must be rejected")?;
        assert!(format!("{err:#}").contains("does not accept a pasted API key"));
        Ok(())
    }

    #[tokio::test]
    async fn import_existing_rejects_providers_without_vendor_cli_import() -> Result<()> {
        let entry = entry_for(serde_json::json!({
            "name": "anthropic",
            "api_base": "https://api.anthropic.com/v1",
            "status": "active",
            "auth": { "kind": "header", "header": "x-api-key", "env": "ANTHROPIC_API_KEY" },
            "models": []
        }));
        let methods = available_methods(&entry);
        let err = choose_auth_method(
            &entry,
            &methods,
            &ProviderLoginOptions {
                import_existing: true,
                no_browser: true,
                api_key: None,
            },
        )
        .await
        .err()
        .context("login flags must be rejected")?;
        assert!(format!("{err:#}").contains("cannot import"));
        Ok(())
    }

    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()
    }

    /// The config projection is unfiltered and keeps every provider of every
    /// model — `shared` is declared by both, and both must survive. Filtering
    /// is the shared report's job (`ModelsReport::filtered`), so that one
    /// filter serves `bro models --provider` and the MCP tool alike.
    #[tokio::test]
    async fn list_models_keeps_every_provider_of_a_model() {
        let cfg = sample_config();
        let all = list_models(&cfg).await.unwrap();
        assert_eq!(all.len(), 2); // gpt-5, shared
        let shared = all.iter().find(|m| m.id == "shared").expect("shared");
        assert_eq!(
            shared.providers,
            vec!["anthropic".to_string(), "openai".to_string()]
        );
    }

    #[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;
    }
}