bitrouter 1.0.0-alpha.31

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
//! First-run configuration and the default Code ACP entry point.
//!
//! Credentials alone do not complete onboarding: the selected ACP harness and
//! optional model are saved in `chat`, then reused by every bare invocation.

use std::collections::BTreeSet;
use std::io::IsTerminal;
use std::path::PathBuf;
use std::sync::Arc;

use anyhow::{Context, Result};
use bitrouter_providers::hosted::account::credentials::default_credentials_path;
use bitrouter_providers::hosted::account::manager::CredentialManager;
use bitrouter_providers::hosted::applier::PROVIDER_ID;
use bitrouter_providers::oauth::credential_store::CredentialStore;
use bitrouter_sdk::invocation;
use clap::ValueEnum;
use serde::Serialize;

use crate::cloud::auth::{LoginInputs, login as cloud_login};
use crate::commands::{ProviderLoginOptions, login_provider_with_options};
use crate::output::CliReport;
use crate::output::Output;
use crate::output::human::Human;
use crate::spawn::SpawnAgent;

// =====================================================================
// §5 — network-free credential probe
// =====================================================================

/// The BYOK env vars the probe checks, each paired with the provider id it
/// enables. `GEMINI_API_KEY` (Google's own name), **not** `GOOGLE_API_KEY`;
/// `OPENCODE_ZEN_API_KEY` is shared by opencode-zen and opencode-go.
const PROBE_ENV_VARS: &[(&str, &str)] = &[
    ("OPENAI_API_KEY", "openai"),
    ("ANTHROPIC_API_KEY", "anthropic"),
    ("GEMINI_API_KEY", "google"),
    ("OPENROUTER_API_KEY", "openrouter"),
    ("OPENCODE_ZEN_API_KEY", "opencode-zen"),
];

/// Purely-local signals that decide "configured vs not" without any network
/// call, registry load, or `merge_registry_into`. See [`probe`].
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ProbeSignals {
    /// BYOK env var **names** present in the environment (e.g. `OPENAI_API_KEY`).
    pub env_keys: Vec<String>,
    /// Whether the cloud session file (`account-credentials.json`) exists.
    pub cloud_session: bool,
    /// Provider ids with at least one stored credential (subscription session,
    /// pasted key, …) in the local credential store.
    pub subscription_providers: Vec<String>,
}

impl ProbeSignals {
    /// "Configured" = at least one of the three local signals is present.
    pub fn is_configured(&self) -> bool {
        !self.env_keys.is_empty() || self.cloud_session || !self.subscription_providers.is_empty()
    }

    /// The provider ids implied by the detected env keys (e.g. `OPENAI_API_KEY`
    /// → `openai`), used to populate the result envelope.
    fn env_provider_ids(&self) -> Vec<String> {
        self.env_keys
            .iter()
            .filter_map(|var| {
                PROBE_ENV_VARS
                    .iter()
                    .find(|(v, _)| *v == var)
                    .map(|(_, id)| (*id).to_string())
            })
            .collect()
    }

    /// Every provider id onboarding can treat as already-usable: detected env
    /// providers, an active cloud session (`bitrouter`), and store providers.
    fn already_configured(&self) -> BTreeSet<String> {
        let mut set: BTreeSet<String> = self.env_provider_ids().into_iter().collect();
        if self.cloud_session {
            set.insert(PROVIDER_ID.to_string());
        }
        for id in &self.subscription_providers {
            set.insert(id.clone());
        }
        set
    }
}

/// Run the network-free credential probe (§5). Reads, in order: the BYOK env
/// vars, the cloud credentials file's existence, and the local credential
/// store's provider list. Performs **no** network I/O and never loads the
/// registry.
pub fn probe() -> ProbeSignals {
    let env_keys = detected_env_keys(|name| std::env::var(name).ok().filter(|v| !v.is_empty()));
    // File-existence check only — never reads/validates the token, never calls
    // the network.
    let cloud_session = default_credentials_path()
        .map(|p| p.exists())
        .unwrap_or(false);
    // A local marker check: the credential store is a single on-disk JSON file;
    // `providers()` lists ids with a stored credential without any refresh or
    // network call. An unresolved/unreadable store is simply "none".
    let subscription_providers = CredentialStore::default_path()
        .map(|store| store.providers().into_iter().map(String::from).collect())
        .unwrap_or_default();
    ProbeSignals {
        env_keys,
        cloud_session,
        subscription_providers,
    }
}

/// The subset of [`PROBE_ENV_VARS`] whose var is present, per the injected
/// lookup. Factored out so the detection can be unit-tested without touching
/// the process environment.
fn detected_env_keys(lookup: impl Fn(&str) -> Option<String>) -> Vec<String> {
    PROBE_ENV_VARS
        .iter()
        .filter(|(var, _)| lookup(var).is_some())
        .map(|(var, _)| (*var).to_string())
        .collect()
}

// =====================================================================
// Flags (§3.2) — every wizard prompt has a flag equivalent
// =====================================================================

/// The three-way finish exit (§3.2 step 3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum AfterAction {
    /// Open BitRouter's TUI using the selected ACP harness.
    Launch,
    /// Start the daemon and print a paste-in snippet for an existing tool.
    Serve,
    /// Do nothing further.
    Exit,
}

impl AfterAction {
    fn as_str(self) -> &'static str {
        match self {
            AfterAction::Launch => "launch",
            AfterAction::Serve => "serve",
            AfterAction::Exit => "exit",
        }
    }
}

/// Every wizard prompt mapped to a flag — consumed by `--yes` and scriptable
/// directly. Built from `Command::Init` in `main.rs`.
#[derive(Debug, Clone, Default)]
pub struct OnboardingFlags {
    /// Config destination (`-c/--config`, otherwise resolved config or user home).
    pub config: Option<PathBuf>,
    /// Run headlessly, emitting the JSON envelope and never blocking.
    pub yes: bool,
    /// Allow overwriting an existing `bitrouter.yaml` when scaffolding.
    pub force: bool,
    /// Clear stored onboarding credentials before running.
    pub reset: bool,
    /// (Step 1) Sign in to BitRouter Cloud via device-flow OAuth.
    pub cloud_login: bool,
    /// (Step 1) Seed the cloud credential from a `brk_` API key (headless).
    pub api_key: Option<String>,
    /// (Step 1) Log in to these upstream providers by id (repeatable).
    pub providers: Vec<String>,
    /// (Step 1) API keys paired by position with `providers` (repeatable).
    pub provider_api_keys: Vec<String>,
    /// (Step 1) Accept the auto-detected credentials without prompting.
    pub use_detected: bool,
    /// (Step 2) Harnesses to drive: `claude` / `codex` (repeatable).
    pub harnesses: Vec<SpawnAgent>,
    /// (Step 3) What to do at the end.
    pub after: Option<AfterAction>,
    /// (Step 3) Default model saved for future TUI sessions.
    pub model: Option<String>,
}

// =====================================================================
// Result envelope (§3.3) + configured-status view (§13 Q1)
// =====================================================================

/// Paste-in wiring for `after: serve` (§13 Q2 — all three shapes, labeled).
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct Snippet {
    /// The daemon base URL the snippets point at.
    pub base_url: String,
    /// `ANTHROPIC_BASE_URL` + `ANTHROPIC_AUTH_TOKEN` export lines.
    pub anthropic: String,
    /// `OPENAI_BASE_URL` + `OPENAI_API_KEY` export lines.
    pub openai: String,
    /// The Codex command for Code's ACP conversation view.
    pub codex: String,
}

/// The standard onboarding result envelope, emitted on stdout by the wizard and
/// every `--yes` run.
#[derive(Debug, Clone, Serialize)]
pub struct OnboardingReport {
    /// Always `"onboarding"`.
    pub action: &'static str,
    /// Provider ids now usable (detected, pre-existing, or freshly set up).
    pub providers_configured: Vec<String>,
    /// Providers that would need an interactive human (OAuth device/PKCE, a
    /// claude-code session import) and were reported-and-skipped, not attempted.
    pub providers_skipped_interactive: Vec<String>,
    /// Selected built-in ACP ids (legacy field name; no native installation).
    pub harnesses_installed: Vec<String>,
    /// `"launch"` | `"serve"` | `"exit"`.
    pub after: String,
    /// The paste-in snippet for `after: serve`; `null` otherwise.
    pub snippet: Option<Snippet>,
}

impl CliReport for OnboardingReport {
    fn render(&self, h: &mut Human<'_>) -> std::io::Result<()> {
        h.line("onboarding complete")?;
        h.field(
            "providers",
            if self.providers_configured.is_empty() {
                "(none)".to_string()
            } else {
                self.providers_configured.join(", ")
            },
        )?;
        if !self.providers_skipped_interactive.is_empty() {
            h.field("skipped", self.providers_skipped_interactive.join(", "))?;
        }
        h.field(
            "harnesses",
            if self.harnesses_installed.is_empty() {
                "(none)".to_string()
            } else {
                self.harnesses_installed.join(", ")
            },
        )?;
        h.field("after", &self.after)?;
        if let Some(snippet) = &self.snippet {
            h.blank()?;
            h.line(&format!("paste-in wiring ({}):", snippet.base_url))?;
            h.blank()?;
            h.line("  Anthropic / Claude Code:")?;
            for l in snippet.anthropic.lines() {
                h.line(&format!("    {l}"))?;
            }
            h.line("  OpenAI SDK:")?;
            for l in snippet.openai.lines() {
                h.line(&format!("    {l}"))?;
            }
            h.line("  Codex:")?;
            for l in snippet.codex.lines() {
                h.line(&format!("    {l}"))?;
            }
        }
        Ok(())
    }
}

/// Compact credential summary used inside the wizard.
#[derive(Debug, Clone, Serialize)]
pub struct OnboardingStatusReport {
    /// Always `"status"`.
    pub action: &'static str,
    /// Always `true` here — this report is only built for a configured user.
    pub configured: bool,
    /// The local credential signals that made the probe report "configured".
    pub signals: Vec<String>,
    /// The one-line next-step hint.
    pub hint: String,
}

impl OnboardingStatusReport {
    fn from_signals(signals: &ProbeSignals) -> Self {
        let mut parts = Vec::new();
        if signals.cloud_session {
            parts.push("cloud session".to_string());
        }
        if !signals.subscription_providers.is_empty() {
            parts.push(format!(
                "providers: {}",
                signals.subscription_providers.join(", ")
            ));
        }
        if !signals.env_keys.is_empty() {
            parts.push(format!("env: {}", signals.env_keys.join(", ")));
        }
        Self {
            action: "status",
            configured: true,
            signals: parts,
            hint: format!(
                "run `{}` to start an ACP coding session",
                invocation::name()
            ),
        }
    }
}

impl CliReport for OnboardingStatusReport {
    fn render(&self, h: &mut Human<'_>) -> std::io::Result<()> {
        h.line(&format!(
            "BitRouter is configured ({}) — {}",
            if self.signals.is_empty() {
                "credentials present".to_string()
            } else {
                self.signals.join("; ")
            },
            self.hint,
        ))
    }
}

// =====================================================================
// Entry points
// =====================================================================

/// Bare invocation opens the saved default in Code, or the first-run wizard.
pub async fn entry(output: &Output) -> Result<()> {
    let path = config_path(None)?;
    if path.is_file() {
        let source = crate::paths::resolve_config(Some(&path))?;
        let config = crate::paths::load_config(&source).await?;
        if config
            .chat
            .agent
            .as_deref()
            .is_some_and(|id| !id.trim().is_empty())
        {
            return start_default_chat(&source, config).await;
        }
    }
    if std::io::stdin().is_terminal() {
        let manager = crate::cloud::default_manager()?;
        run_interactive(
            OnboardingFlags {
                config: Some(path),
                ..Default::default()
            },
            &probe(),
            output,
            manager,
        )
        .await
    } else {
        print_hint();
        emit(output, &empty_report())
    }
}

/// Find the onboarding destination without requiring a config to exist yet.
fn config_path(explicit: Option<&std::path::Path>) -> Result<PathBuf> {
    if let Some(path) = explicit {
        return Ok(std::path::absolute(path)?);
    }
    let local = std::env::current_dir()?.join("bitrouter.yaml");
    if local.is_file() {
        return Ok(local);
    }
    Ok(std::path::absolute(
        crate::paths::runtime_home()?.join("bitrouter.yaml"),
    )?)
}

async fn start_default_chat(
    source: &crate::paths::ConfigSource,
    config: bitrouter_sdk::config::Config,
) -> Result<()> {
    let agent =
        config.chat.agent.clone().with_context(|| {
            format!("no default ACP harness; run `{} init`", invocation::name())
        })?;
    let routing = crate::acp_cli::RoutingOptions {
        model: config.chat.model.clone(),
        ..Default::default()
    };
    // Preserve the pre-Code plain renderer for scripts and redirected output.
    // Interactive users always enter the one full-screen Code lifecycle UI.
    if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
        return crate::acp_cli::chat(crate::acp_cli::SpawnContext {
            source,
            config,
            agent_id: &agent,
            options: crate::acp_cli::launch_options(None),
            routing,
        })
        .await;
    }
    let config_path = match source {
        crate::paths::ConfigSource::File(path) => Some(path.as_path()),
        crate::paths::ConfigSource::Default { .. } => None,
    };
    crate::dashboard::run(
        None,
        config_path,
        None,
        Some(crate::dashboard::SessionRequest {
            agent,
            selection: crate::acp_cli::SessionSelection::New,
            turn_timeout: None,
            routing,
        }),
    )
    .await
}

/// Persist onboarding atomically; an interrupted wizard never marks itself complete.
fn save_config(
    flags: &OnboardingFlags,
    agent: &str,
    providers: &BTreeSet<String>,
) -> Result<PathBuf> {
    use std::io::Write;
    let path = config_path(flags.config.as_deref())?;
    let existing = path.is_file();
    let text = if existing && !flags.force {
        std::fs::read_to_string(&path)?
    } else {
        crate::commands::STARTER_CONFIG.to_string()
    };
    let mut value: serde_json::Value = serde_saphyr::from_str(&text)?;
    if value.is_null() {
        value = serde_json::json!({});
    }
    let root = value
        .as_object_mut()
        .context("configuration must be a YAML mapping")?;
    let chat = root.entry("chat").or_insert_with(|| serde_json::json!({}));
    let chat = chat
        .as_object_mut()
        .context("chat must be a YAML mapping")?;
    chat.insert("agent".into(), agent.into());
    if let Some(model) = &flags.model {
        chat.insert("model".into(), model.clone().into());
    }
    let entries = root
        .entry("providers")
        .or_insert_with(|| serde_json::json!({}));
    let entries = entries
        .as_object_mut()
        .context("providers must be a YAML mapping")?;
    for provider in providers {
        entries.entry(provider.clone()).or_insert_with(|| {
            if provider == PROVIDER_ID {
                serde_json::json!({"auto_discover": true})
            } else {
                serde_json::json!({})
            }
        });
    }
    let serialized = serde_saphyr::to_string(&value)?;
    // Reject invalid edits before replacing a working configuration.
    let _: bitrouter_sdk::config::Config = serde_saphyr::from_str(&serialized)?;
    let parent = path.parent().context("configuration path has no parent")?;
    if !parent.exists() {
        crate::paths::ensure_home_directory(parent)?;
    }
    let mut temp = tempfile::NamedTempFile::new_in(parent)?;
    temp.write_all(serialized.as_bytes())?;
    temp.as_file().sync_all()?;
    temp.persist(&path)
        .with_context(|| format!("saving {}", path.display()))?;
    note(&format!(
        "saved default ACP harness '{agent}' in {}",
        path.display()
    ));
    Ok(path)
}

fn acp_id(agent: SpawnAgent) -> &'static str {
    match agent {
        SpawnAgent::Claude => "claude-acp",
        SpawnAgent::Codex => "codex-acp",
    }
}

/// `bro init [flags]`. Runs the wizard interactively, or headlessly when
/// `--yes` is set (or no TTY is attached). `--reset` clears credentials first.
pub async fn run(flags: OnboardingFlags, output: &Output) -> Result<()> {
    let manager = crate::cloud::default_manager()?;
    if flags.reset {
        reset_credentials(flags.yes, std::io::stdin().is_terminal()).await?;
    }
    if flags.yes {
        return run_headless(flags, output, manager).await;
    }
    if std::io::stdin().is_terminal() {
        let signals = probe();
        run_interactive(flags, &signals, output, manager).await
    } else {
        run_headless(flags, output, manager).await
    }
}

fn empty_report() -> OnboardingReport {
    OnboardingReport {
        action: "onboarding",
        providers_configured: Vec::new(),
        providers_skipped_interactive: Vec::new(),
        harnesses_installed: Vec::new(),
        after: AfterAction::Exit.as_str().to_string(),
        snippet: None,
    }
}

// =====================================================================
// §4 — headless runner
// =====================================================================

async fn run_headless(
    flags: OnboardingFlags,
    output: &Output,
    manager: Arc<CredentialManager>,
) -> Result<()> {
    let signals = probe();
    // Already-present credentials always count (spec §4: "consume
    // already-present credentials + flag-supplied keys").
    let mut configured = signals.already_configured();
    let mut skipped: Vec<String> = Vec::new();

    // --- Step 1: credentials (flag-driven; interactive OAuth reported-and-skipped) ---
    apply_flag_credentials(&flags, &mut configured, &mut skipped, true, manager).await?;

    // Catalog ACP adapters are built in. No native CLI installation is required.
    let path = config_path(flags.config.as_deref())?;
    let existing_agent = if path.is_file() && !flags.force {
        let config: bitrouter_sdk::config::Config =
            serde_saphyr::from_str(&std::fs::read_to_string(&path)?)?;
        config.chat.agent
    } else {
        None
    };
    let agent = flags
        .harnesses
        .first()
        .copied()
        .map(acp_id)
        .map(String::from)
        .or(existing_agent)
        .unwrap_or_else(|| "codex-acp".into());
    let path = save_config(&flags, &agent, &configured)?;
    let after = flags.after.unwrap_or(AfterAction::Exit);
    let report = OnboardingReport {
        action: "onboarding",
        providers_configured: configured.into_iter().collect(),
        providers_skipped_interactive: skipped,
        harnesses_installed: flags
            .harnesses
            .iter()
            .copied()
            .map(acp_id)
            .map(String::from)
            .chain(flags.harnesses.is_empty().then(|| agent.to_string()))
            .collect(),
        after: after.as_str().to_string(),
        snippet: None,
    };
    match after {
        AfterAction::Launch => finish_launch(&path, report, output).await,
        AfterAction::Serve => finish_serve(&path, report, output).await,
        AfterAction::Exit => emit(output, &report),
    }
}

/// Apply the flag-supplied credentials shared by both the headless runner and
/// the interactive wizard's step-1 pre-pass. `headless` controls the parts a
/// machine can't do: a bare `--cloud-login` (device flow) and a `--provider`
/// with no key are reported-and-skipped headlessly, but drive the real
/// interactive flows when a human is present.
async fn apply_flag_credentials(
    flags: &OnboardingFlags,
    configured: &mut BTreeSet<String>,
    skipped: &mut Vec<String>,
    headless: bool,
    manager: Arc<CredentialManager>,
) -> Result<()> {
    let cloud = PROVIDER_ID;
    // Cloud: a brk_ key is non-interactive; a bare --cloud-login needs the
    // device flow (headless skips, interactive runs it).
    if let Some(key) = flags.api_key.as_deref() {
        seed_cloud_api_key(key, Arc::clone(&manager)).await?;
        configured.insert(cloud.to_string());
    } else if flags.cloud_login {
        if headless {
            skipped.push(cloud.to_string());
        } else {
            match seed_cloud_interactive(Arc::clone(&manager)).await {
                Ok(()) => {
                    configured.insert(cloud.to_string());
                }
                Err(e) => note(&format!("cloud sign-in did not complete: {e:#}")),
            }
        }
    }

    // Per-provider: a paired key seeds it non-interactively; without one it
    // needs an interactive OAuth/PKCE/session flow (headless skips; interactive
    // runs the provider's login menu).
    for (i, provider) in flags.providers.iter().enumerate() {
        match flags.provider_api_keys.get(i) {
            Some(key) => match seed_provider_api_key(provider, key).await {
                Ok(()) => {
                    configured.insert(provider.clone());
                }
                Err(e) => {
                    note(&format!("provider '{provider}' not configured: {e:#}"));
                    skipped.push(provider.clone());
                }
            },
            None if headless => skipped.push(provider.clone()),
            None => match login_provider_with_options(
                provider,
                bitrouter_providers::oauth::credential_store::DEFAULT_LABEL,
                ProviderLoginOptions::default(),
            )
            .await
            {
                Ok(_) => {
                    configured.insert(provider.clone());
                }
                Err(e) => {
                    note(&format!(
                        "provider '{provider}' login did not complete: {e:#}"
                    ));
                    skipped.push(provider.clone());
                }
            },
        }
    }
    Ok(())
}

/// Seed the cloud credential from a `brk_` key. Calls the Cloud login flow
/// directly (not `cloud::cli::run`) so onboarding emits a single result
/// envelope on stdout — `login` writes only progress to stderr and persists
/// the credential to the store.
async fn seed_cloud_api_key(key: &str, manager: Arc<CredentialManager>) -> Result<()> {
    cloud_login(
        manager,
        LoginInputs {
            authorization_server: None,
            client_id: None,
            scope: None,
            api_key: Some(key.to_string()),
        },
    )
    .await
    .map(|_| ())
    .context("seeding the cloud credential from --api-key")
}

/// Seed one upstream provider non-interactively from a pasted key, via the
/// same `providers login --api-key` path.
async fn seed_provider_api_key(provider: &str, key: &str) -> Result<()> {
    login_provider_with_options(
        provider,
        bitrouter_providers::oauth::credential_store::DEFAULT_LABEL,
        ProviderLoginOptions {
            import_existing: false,
            no_browser: true,
            api_key: Some(key.to_string()),
        },
    )
    .await
    .map(|_| ())
}

// =====================================================================
// Interactive wizard
// =====================================================================

async fn run_interactive(
    flags: OnboardingFlags,
    signals: &ProbeSignals,
    output: &Output,
    manager: Arc<CredentialManager>,
) -> Result<()> {
    eprintln!();
    eprintln!("Welcome to BitRouter — let's get you to first value.");
    eprintln!();

    if signals.is_configured() {
        note(&format!(
            "Detected: {}",
            OnboardingStatusReport::from_signals(signals)
                .signals
                .join("; ")
        ));
    }
    // --- Step 1: credentials ---
    let mut configured = signals.already_configured();
    let mut skipped: Vec<String> = Vec::new();
    // Apply any flag-supplied credentials first (so `bro init --api-key …`
    // / `--provider …` seed before we prompt), then either accept the detected
    // set (`--use-detected`) or open the interactive credential menu.
    apply_flag_credentials(
        &flags,
        &mut configured,
        &mut skipped,
        false,
        Arc::clone(&manager),
    )
    .await?;
    let seeded_from_flags =
        flags.api_key.is_some() || flags.cloud_login || !flags.providers.is_empty();
    if flags.use_detected && signals.is_configured() {
        eprintln!("Step 1/3 — Credentials");
        note("using the detected credential(s)");
    } else if !seeded_from_flags {
        interactive_credentials(&flags, &mut configured, &mut skipped, manager).await?;
    }

    // --- Step 2: harness ---
    let installed = interactive_harness(&flags).await?;

    // --- Step 3: finish ---
    let after = interactive_after(&flags, &installed).await?;

    let agent = installed
        .first()
        .context("select an ACP harness to complete onboarding")?;
    let path = save_config(&flags, agent, &configured)?;
    let report = OnboardingReport {
        action: "onboarding",
        providers_configured: configured.into_iter().collect(),
        providers_skipped_interactive: skipped,
        harnesses_installed: installed,
        after: after.as_str().to_string(),
        snippet: None,
    };
    match after {
        AfterAction::Launch => finish_launch(&path, report, output).await,
        AfterAction::Serve => finish_serve(&path, report, output).await,
        AfterAction::Exit => emit(output, &report),
    }
}

/// Providers offered by the OSS registry, with no special placement for Cloud.
fn provider_choices(
    data: &bitrouter_providers::registry::types::RegistryData,
) -> Vec<&bitrouter_providers::registry::types::RegistryProvider> {
    let mut providers: Vec<_> = data
        .providers
        .iter()
        .filter(|provider| provider.is_active() && provider.is_mergeable())
        .collect();
    providers.sort_by_key(|provider| {
        (
            provider
                .display_name
                .as_deref()
                .unwrap_or(&provider.name)
                .to_lowercase(),
            provider.name.clone(),
        )
    });
    providers
}

async fn interactive_credentials(
    flags: &OnboardingFlags,
    configured: &mut BTreeSet<String>,
    skipped: &mut Vec<String>,
    manager: Arc<CredentialManager>,
) -> Result<()> {
    use bitrouter_tui::select::Item;

    let path = config_path(flags.config.as_deref())?;
    let registry = if path.is_file() && !flags.force {
        serde_saphyr::from_str::<bitrouter_sdk::config::Config>(&std::fs::read_to_string(path)?)?
            .registry
    } else {
        bitrouter_sdk::config::RegistryConfig::default()
    };
    note("loading providers from the registry…");
    let data = crate::bundled_registry::load(&registry).await;
    let providers = data.as_ref().map(provider_choices).unwrap_or_default();
    for provider in &providers {
        if provider
            .env_credential_var()
            .is_some_and(|var| crate::spawn::nonempty_env(&var).is_some())
        {
            configured.insert(provider.name.clone());
        }
    }
    let mut help = if providers.is_empty() {
        "Registry unavailable or disabled. Continue to set up an ACP harness.".to_string()
    } else {
        "Choose a provider to sign in. End jumps to Continue.".to_string()
    };
    let mut selected = if configured.is_empty() {
        0
    } else {
        providers.len()
    };
    loop {
        let mut items: Vec<_> = providers
            .iter()
            .map(|provider| {
                let status = if configured.contains(&provider.name) {
                    " · configured"
                } else {
                    ""
                };
                Item::new(
                    provider.display_name.as_deref().unwrap_or(&provider.name),
                    format!("{}{status}", provider.name),
                )
            })
            .collect();
        items.push(Item::new(
            "Continue to harness setup",
            if configured.is_empty() {
                "skip provider login for now".to_string()
            } else {
                format!("use {} configured provider(s)", configured.len())
            },
        ));
        selected = crate::prompt::select("Step 1/3 — Providers", &help, items, selected).await?;
        let Some(provider) = providers.get(selected) else {
            return Ok(());
        };
        let id = &provider.name;
        let result = if id == PROVIDER_ID {
            let method = crate::prompt::select(
                &format!(
                    "Log in to {}",
                    provider.display_name.as_deref().unwrap_or(id)
                ),
                "Choose an authentication method",
                vec![
                    Item::new("Browser sign-in", "device-code OAuth"),
                    Item::new("API key", "paste a static credential"),
                ],
                0,
            )
            .await?;
            if method == 0 {
                seed_cloud_interactive(Arc::clone(&manager)).await
            } else {
                let key = crate::commands::read_api_key(id)?;
                seed_cloud_api_key(&key, Arc::clone(&manager)).await
            }
        } else {
            crate::commands::login_registry_provider(provider)
                .await
                .map(|_| ())
        };
        match result {
            Ok(()) => {
                configured.insert(id.clone());
                skipped.retain(|skipped_id| skipped_id != id);
                help = format!("{id} configured. Add another provider, or Continue.");
                selected = providers.len();
            }
            Err(error) => {
                if error
                    .downcast_ref::<std::io::Error>()
                    .is_some_and(|e| e.kind() == std::io::ErrorKind::Interrupted)
                {
                    return Err(error);
                }
                note(&format!(
                    "provider '{id}' login did not complete: {error:#}"
                ));
                help = format!("{id}: {error}. Select to retry, or choose another provider.");
                if !skipped.contains(id) {
                    skipped.push(id.clone());
                }
            }
        }
    }
}

/// The cloud device-flow sign-in. Calls the Cloud login flow directly (not
/// `cloud::cli::run`) so onboarding emits a single result envelope on stdout;
/// `login` drives the device-flow prompts on stderr and persists the token.
async fn seed_cloud_interactive(manager: Arc<CredentialManager>) -> Result<()> {
    cloud_login(
        manager,
        LoginInputs {
            authorization_server: None,
            client_id: None,
            scope: None,
            api_key: None,
        },
    )
    .await
    .map(|_| ())
    .context("BitRouter Cloud sign-in")
}

async fn interactive_harness(flags: &OnboardingFlags) -> Result<Vec<String>> {
    eprintln!();
    eprintln!("Step 2/3 — Default ACP harness");
    note("BitRouter provides the TUI. ACP adapters use a compatible local CLI when available.");
    if !flags.harnesses.is_empty() {
        return Ok(flags
            .harnesses
            .iter()
            .copied()
            .map(acp_id)
            .map(String::from)
            .collect());
    }
    let harnesses = crate::harness::CATALOG;
    let selected = crate::prompt::select(
        "Step 2/3 — Default ACP harness",
        "BitRouter provides the TUI. Choose the agent it runs.",
        harnesses
            .iter()
            .map(|harness| bitrouter_tui::select::Item::new(harness.id, harness.description))
            .collect(),
        harnesses
            .iter()
            .position(|harness| harness.id == "codex-acp")
            .unwrap_or(0),
    )
    .await?;
    Ok(vec![
        harnesses
            .get(selected)
            .context("no ACP harness selected")?
            .id
            .to_string(),
    ])
}

async fn interactive_after(flags: &OnboardingFlags, installed: &[String]) -> Result<AfterAction> {
    use bitrouter_tui::select::Item;
    if let Some(after) = flags.after {
        return Ok(after);
    }
    let mut actions = Vec::new();
    let mut items = Vec::new();
    if !installed.is_empty() {
        actions.push(AfterAction::Launch);
        items.push(Item::new(
            "Open BitRouter Code now",
            "use the selected default ACP harness",
        ));
    }
    actions.extend([AfterAction::Serve, AfterAction::Exit]);
    items.extend([
        Item::new("Start the daemon", "print connection instructions"),
        Item::new("Save and exit", "run bro whenever you're ready"),
    ]);
    let selected = crate::prompt::select(
        "Step 3/3 — Finish",
        "Save your setup and choose what happens next",
        items,
        0,
    )
    .await?;
    actions
        .get(selected)
        .copied()
        .context("no finish action selected")
}

// =====================================================================
// Finish exits (a) launch / (b) serve+snippet
// =====================================================================

/// Open the same unified Code TUI as every subsequent bare invocation.
async fn finish_launch(
    path: &std::path::Path,
    report: OnboardingReport,
    output: &Output,
) -> Result<()> {
    let source = crate::paths::resolve_config(Some(path))?;
    let config = crate::paths::load_config(&source).await?;
    emit(output, &report)?;
    start_default_chat(&source, config).await
}

/// Exit (b): start the local daemon (best-effort, reusing the launch path's
/// auto-start), build the paste-in snippet, and emit the envelope with it.
async fn finish_serve(
    path: &std::path::Path,
    mut report: OnboardingReport,
    output: &Output,
) -> Result<()> {
    let source = crate::paths::resolve_config(Some(path))?;
    let cfg = crate::paths::load_config(&source).await?;
    crate::spawn::ensure_local_daemon(&source, &cfg, false).await;
    report.snippet = Some(build_snippet(&cfg.server.listen));
    emit(output, &report)
}

/// Build the three labeled paste-in shapes (§13 Q2). Templates the bearer by
/// auth mode: a real exported `BITROUTER_API_KEY` (`brk_`) when present, else
/// the local `skip_auth` placeholder. The Codex example opens Code.
fn build_snippet(listen: &str) -> Snippet {
    let base_url = crate::spawn::derive_base_url(listen);
    let token = crate::spawn::nonempty_env(crate::harness::BITROUTER_API_KEY_ENV)
        .unwrap_or_else(|| crate::harness::PLACEHOLDER_API_KEY.to_string());
    let v1 = {
        let trimmed = base_url.trim_end_matches('/');
        if trimmed.ends_with("/v1") {
            trimmed.to_string()
        } else {
            format!("{trimmed}/v1")
        }
    };
    let anthropic =
        format!("export ANTHROPIC_BASE_URL={base_url}\nexport ANTHROPIC_AUTH_TOKEN={token}");
    let openai = format!("export OPENAI_BASE_URL={v1}\nexport OPENAI_API_KEY={token}");
    let codex = format!("{} code codex --base-url {base_url}", invocation::name());
    Snippet {
        base_url,
        anthropic,
        openai,
        codex,
    }
}

// =====================================================================
// --reset (§13 Q3)
// =====================================================================

/// Clears the cloud session (always) and — after a confirm, unless `--yes` —
/// the stored provider credentials.
async fn reset_credentials(assume_yes: bool, interactive: bool) -> Result<()> {
    let cloud_path = default_credentials_path().ok();
    let mut store = CredentialStore::default_path().ok();

    let provider_ids: Vec<String> = store
        .as_ref()
        .map(|s| s.providers().into_iter().map(String::from).collect())
        .unwrap_or_default();

    // Cloud session is cleared unconditionally; provider credentials only after
    // an explicit confirm (or under --yes).
    let remove_providers = if provider_ids.is_empty() {
        false
    } else if assume_yes {
        true
    } else if interactive {
        prompt_yes_no(
            &format!(
                "  --reset: also remove {} stored provider credential(s) ({})?",
                provider_ids.len(),
                provider_ids.join(", ")
            ),
            false,
        )
        .await?
    } else {
        false
    };

    let outcome = reset_with(cloud_path.as_deref(), store.as_mut(), remove_providers)?;
    if outcome.cloud_cleared {
        note("cleared the cloud session");
    }
    if outcome.providers_removed > 0 {
        note(&format!(
            "removed {} provider credential(s)",
            outcome.providers_removed
        ));
    } else if !provider_ids.is_empty() && !remove_providers {
        note("kept provider credentials");
    }
    Ok(())
}

/// Outcome of [`reset_with`].
#[derive(Debug, Default, PartialEq, Eq)]
struct ResetOutcome {
    cloud_cleared: bool,
    providers_removed: usize,
}

/// The testable core of [`reset_credentials`]: delete the cloud credentials
/// file if present, and (when asked) remove every provider credential from the
/// store. Purely local — no network.
fn reset_with(
    cloud_path: Option<&std::path::Path>,
    store: Option<&mut CredentialStore>,
    remove_providers: bool,
) -> Result<ResetOutcome> {
    let mut outcome = ResetOutcome::default();
    if let Some(path) = cloud_path
        && path.exists()
    {
        std::fs::remove_file(path)
            .with_context(|| format!("removing cloud credentials {}", path.display()))?;
        outcome.cloud_cleared = true;
    }
    if remove_providers && let Some(store) = store {
        let ids: Vec<String> = store.providers().into_iter().map(String::from).collect();
        for id in ids {
            outcome.providers_removed += store
                .remove_all_for(&id)
                .with_context(|| format!("removing credentials for {id}"))?;
        }
    }
    Ok(outcome)
}

// =====================================================================
// Small helpers
// =====================================================================

/// A dim, indented note to stderr (diagnostics never touch stdout).
fn note(msg: &str) {
    let p = crate::style::Palette::for_stderr();
    eprintln!("  {dim}{msg}{reset}", dim = p.dim, reset = p.reset);
}

/// Emit a report to stdout, mapping `Output::emit`'s `io::Result` into the
/// `anyhow::Result` this module threads.
fn emit(output: &Output, report: &dyn CliReport) -> Result<()> {
    Output::emit(output, report).map_err(anyhow::Error::from)
}

/// Confirmation uses the same selector; cancellation propagates before reset.
async fn prompt_yes_no(prompt: &str, default_yes: bool) -> Result<bool> {
    let index = crate::prompt::select(
        prompt,
        "Choose whether to continue",
        vec![
            bitrouter_tui::select::Item::new("Yes", ""),
            bitrouter_tui::select::Item::new("No", ""),
        ],
        usize::from(!default_yes),
    )
    .await?;
    Ok(index == 0)
}

/// The multi-line onboarding hint (unconfigured, non-TTY). Mirrors the recovery
/// chain of the former `print_onboarding_hint`.
fn print_hint() {
    let p = crate::style::Palette::for_stderr();
    eprintln!(
        "{cyan}{bold}info:{reset} setup is not complete. Run `{cli}` in a terminal or `{cli} init --yes`:",
        cyan = p.cyan,
        bold = p.bold,
        reset = p.reset,
        cli = invocation::name(),
    );
    eprintln!();
    eprintln!(
        "  {cli} init                 # guided setup wizard (interactive)",
        cli = invocation::name()
    );
    eprintln!(
        "  {cli} cloud login          # one BitRouter Cloud account, every model",
        cli = invocation::name()
    );
    eprintln!(
        "  {cli} providers login claude-code   # a subscription you already pay for",
        cli = invocation::name()
    );
    eprintln!("  export OPENAI_API_KEY=…        # or any BYOK provider key, then re-run");
    eprintln!();
}

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

    #[test]
    fn provider_menu_contains_every_public_active_entry_in_display_order() -> Result<()> {
        let data: bitrouter_providers::registry::types::RegistryData =
            serde_json::from_value(serde_json::json!({
                "providers": [
                    {"name": "zulu", "display_name": "Zulu", "status": "active"},
                    {"name": "bitrouter", "display_name": "BitRouter Cloud", "status": "active"},
                    {"name": "alpha", "display_name": "Alpha", "status": "active"},
                    {"name": "private", "status": "active", "access": "private"},
                    {"name": "preview", "status": "staging"},
                    {"name": "retired", "status": "withdrawn"}
                ], "canonical": []
            }))?;
        let ids: Vec<_> = provider_choices(&data)
            .iter()
            .map(|provider| provider.name.as_str())
            .collect();
        assert_eq!(ids, ["alpha", "bitrouter", "zulu"]);
        Ok(())
    }

    #[test]
    fn detected_env_keys_reports_present_vars_only() {
        // Only OPENAI + GEMINI "present" in the injected lookup.
        let present = |name: &str| {
            matches!(name, "OPENAI_API_KEY" | "GEMINI_API_KEY").then(|| "x".to_string())
        };
        let keys = detected_env_keys(present);
        assert_eq!(keys, vec!["OPENAI_API_KEY", "GEMINI_API_KEY"]);
    }

    #[test]
    fn detected_env_keys_ignores_empty_values() {
        // The probe's real lookup filters empties; here nothing is present.
        let keys = detected_env_keys(|_| None);
        assert!(keys.is_empty());
    }

    #[test]
    fn probe_uses_gemini_not_google_key() {
        // GOOGLE_API_KEY must NOT be a probe signal (Google's own SDKs use
        // GEMINI_API_KEY); guard against a regression to the wrong var.
        assert!(PROBE_ENV_VARS.iter().any(|(v, _)| *v == "GEMINI_API_KEY"));
        assert!(!PROBE_ENV_VARS.iter().any(|(v, _)| *v == "GOOGLE_API_KEY"));
    }

    #[test]
    fn is_configured_is_false_when_no_signal_present() {
        assert!(!ProbeSignals::default().is_configured());
    }

    #[test]
    fn is_configured_true_for_each_signal_independently() {
        // env key alone
        assert!(
            ProbeSignals {
                env_keys: vec!["OPENAI_API_KEY".to_string()],
                ..Default::default()
            }
            .is_configured()
        );
        // cloud session file alone
        assert!(
            ProbeSignals {
                cloud_session: true,
                ..Default::default()
            }
            .is_configured()
        );
        // a stored subscription/provider credential alone
        assert!(
            ProbeSignals {
                subscription_providers: vec!["claude-code".to_string()],
                ..Default::default()
            }
            .is_configured()
        );
    }

    #[test]
    fn already_configured_maps_env_cloud_and_store() {
        let signals = ProbeSignals {
            env_keys: vec!["OPENAI_API_KEY".to_string(), "GEMINI_API_KEY".to_string()],
            cloud_session: true,
            subscription_providers: vec!["claude-code".to_string()],
        };
        let set = signals.already_configured();
        assert!(set.contains("openai"));
        assert!(set.contains("google")); // GEMINI_API_KEY → google
        assert!(set.contains("bitrouter")); // cloud session
        assert!(set.contains("claude-code"));
    }

    #[test]
    fn envelope_shape_includes_skipped_interactive() {
        let report = OnboardingReport {
            action: "onboarding",
            providers_configured: vec!["bitrouter".to_string(), "openai".to_string()],
            providers_skipped_interactive: vec!["github-copilot".to_string()],
            harnesses_installed: vec!["claude".to_string()],
            after: "launch".to_string(),
            snippet: None,
        };
        let v = serde_json::to_value(&report).unwrap();
        assert_eq!(v["action"], "onboarding");
        assert_eq!(
            v["providers_configured"],
            serde_json::json!(["bitrouter", "openai"])
        );
        assert_eq!(
            v["providers_skipped_interactive"],
            serde_json::json!(["github-copilot"])
        );
        assert_eq!(v["harnesses_installed"], serde_json::json!(["claude"]));
        assert_eq!(v["after"], "launch");
        // `snippet` is present-but-null when there is nothing to paste.
        assert!(v.get("snippet").is_some());
        assert!(v["snippet"].is_null());
        assert!(
            v.get("optimization").is_none(),
            "onboarding must not expose the removed optimization workflow"
        );
    }

    #[tokio::test]
    async fn headless_init_writes_no_removed_optimization_artifacts() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let config = directory.path().join("bitrouter.yaml");
        run_headless(
            OnboardingFlags {
                config: Some(config.clone()),
                yes: true,
                after: Some(AfterAction::Exit),
                ..OnboardingFlags::default()
            },
            &Output::new(crate::output::Format::Json),
            Arc::new(CredentialManager::with_client(
                directory.path().join("account-credentials.json"),
                reqwest::Client::new(),
            )),
        )
        .await?;

        assert!(config.is_file(), "normal starter config was not written");
        for removed in [
            "bitrouter.optimize.yaml",
            "bitrouter.optimize.lock.yaml",
            "bitrouter.eval.md",
        ] {
            assert!(
                !directory.path().join(removed).exists(),
                "removed onboarding artifact {removed} was written"
            );
        }
        Ok(())
    }

    #[test]
    fn snippet_uses_placeholder_when_no_bitrouter_key() {
        // With no BITROUTER_API_KEY exported, the local `skip_auth` placeholder
        // is templated into all three shapes.
        // (This test process does not set BITROUTER_API_KEY.)
        if crate::spawn::nonempty_env(crate::harness::BITROUTER_API_KEY_ENV).is_some() {
            return; // environment is non-hermetic; skip rather than false-fail
        }
        let snippet = build_snippet("127.0.0.1:4356");
        assert_eq!(snippet.base_url, "http://127.0.0.1:4356");
        assert!(
            snippet
                .anthropic
                .contains("ANTHROPIC_BASE_URL=http://127.0.0.1:4356")
        );
        assert!(snippet.anthropic.contains(&format!(
            "ANTHROPIC_AUTH_TOKEN={}",
            crate::harness::PLACEHOLDER_API_KEY
        )));
        // OpenAI shape carries the /v1 suffix.
        assert!(
            snippet
                .openai
                .contains("OPENAI_BASE_URL=http://127.0.0.1:4356/v1")
        );
        assert_eq!(
            snippet.codex,
            "bro code codex --base-url http://127.0.0.1:4356"
        );
    }

    #[test]
    fn reset_clears_cloud_session_and_optionally_providers() -> Result<()> {
        let temp = tempfile::tempdir()?;
        let dir = temp.path();
        let cloud = dir.join("account-credentials.json");
        std::fs::write(&cloud, "{}").unwrap();
        let mut store = CredentialStore::load(dir.join("oauth-tokens.json")).unwrap();
        store
            .set(
                "claude-code",
                "default",
                bitrouter_providers::oauth::credential_store::Credential::ClaudeCodeCli,
            )
            .unwrap();
        store
            .set(
                "openai",
                "default",
                bitrouter_providers::oauth::credential_store::Credential::api_key("sk-x"),
            )
            .unwrap();

        // remove_providers = false: cloud cleared, provider creds kept (Q3).
        let outcome = reset_with(Some(&cloud), Some(&mut store), false).unwrap();
        assert!(outcome.cloud_cleared);
        assert_eq!(outcome.providers_removed, 0);
        assert!(!cloud.exists());
        assert_eq!(store.providers().len(), 2, "provider creds must survive");

        // remove_providers = true: every provider credential is dropped.
        let outcome = reset_with(None, Some(&mut store), true).unwrap();
        assert!(!outcome.cloud_cleared); // no cloud file this call
        assert_eq!(outcome.providers_removed, 2);
        assert!(store.providers().is_empty());
        Ok(())
    }

    #[test]
    fn reset_is_a_noop_when_nothing_stored() -> Result<()> {
        let temp = tempfile::tempdir()?;
        let dir = temp.path();
        let missing_cloud = dir.join("account-credentials.json");
        let mut store = CredentialStore::load(dir.join("oauth-tokens.json")).unwrap();
        let outcome = reset_with(Some(&missing_cloud), Some(&mut store), true).unwrap();
        assert_eq!(outcome, ResetOutcome::default());
        Ok(())
    }

    #[test]
    fn status_report_lists_signals_and_hint() {
        let signals = ProbeSignals {
            env_keys: vec!["OPENAI_API_KEY".to_string()],
            cloud_session: true,
            subscription_providers: vec![],
        };
        let report = OnboardingStatusReport::from_signals(&signals);
        assert!(report.configured);
        assert!(report.hint.contains("ACP"));
        let v = serde_json::to_value(&report).unwrap();
        assert_eq!(v["action"], "status");
        assert_eq!(v["configured"], true);
    }
}