bitrouter 1.0.0-alpha.26

BitRouter: an LLM API router. CLI + TUI + assembly library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
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
//! `bitrouter launch` — launch a coding-agent harness (Claude Code, Codex, …)
//! as an interactive native-TUI child process with its API base URL pointed at
//! the local BitRouter daemon. This is the *main orchestrator* surface; headless
//! ACP sub-agents are `bitrouter spawn` (see [`crate::acp_cli`]). Both draw
//! their routing knowledge from the shared [`crate::harness`] catalog.
//!
//! The agent's traffic then routes through BitRouter without ever touching the
//! agent's own config files: instead of mutating `~/.claude/config.json` or
//! `~/.codex/config.toml` (the
//! "config takeover" model used by some switcher tools — invasive, needs
//! backup/restore and crash recovery), we set per-process environment variables
//! or one-shot CLI config overrides. Nothing on disk changes, and if BitRouter
//! is down the user simply runs the agent directly.
//!
//! CLI shape follows `cargo run`'s separator convention so there is no
//! ambiguity about which flags belong to which program:
//!
//! ```text
//!   bitrouter launch --agent claude [bitrouter opts] -- <args forwarded to claude>
//! ```
//!
//! Everything after `--` is handed to the agent binary verbatim.
//!
//! ## Claude Code integration
//!
//! - `ANTHROPIC_BASE_URL` redirects the Anthropic SDK Claude Code uses to an
//!   alternate endpoint. See the Claude Code settings reference:
//!   <https://code.claude.com/docs/en/settings#environment-variables>.
//! - Install commands are the official native installers documented in the
//!   Claude Code quickstart: <https://code.claude.com/docs/en/quickstart>.
//!
//! ## Codex integration
//!
//! - Codex custom providers are configured with `model_providers.<id>` and can
//!   be overridden per invocation with repeated `-c key=value` flags.
//! - Current Codex builds route custom providers through the Responses API, so
//!   the BitRouter provider uses `wire_api = "responses"` and a `/v1` base URL.
//!   See <https://developers.openai.com/codex/config-advanced#custom-model-providers>.

use std::ffi::OsString;
use std::io::IsTerminal;
use std::path::PathBuf;
use std::time::Duration;

use anyhow::{Context, Result};
use clap::ValueEnum;
use serde::Serialize;

use crate::output::CliReport;
use crate::output::human::Human;
use crate::style::Palette;

/// The coding-agent harnesses `bitrouter launch` can launch interactively.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum SpawnAgent {
    /// Anthropic's Claude Code CLI (`claude`).
    Claude,
    /// OpenAI's Codex CLI (`codex`).
    Codex,
}

impl SpawnAgent {
    /// Static metadata describing how to find, route, and install this agent.
    pub fn spec(self) -> AgentSpec {
        match self {
            // The gateway env/args this agent needs (ANTHROPIC_BASE_URL /
            // ANTHROPIC_AUTH_TOKEN for Claude, `-c` provider overrides for
            // Codex) live once in the shared `harness` catalog, keyed by the
            // interactive binary — see `run`.
            SpawnAgent::Claude => AgentSpec {
                agent: self,
                // The display id matches the `--agent` value.
                id: "claude",
                // The executable name looked up on `PATH`.
                binary: "claude",
            },
            SpawnAgent::Codex => AgentSpec {
                agent: self,
                id: "codex",
                binary: "codex",
            },
        }
    }
}

/// Resolved, per-agent static facts used by the spawn machinery.
#[derive(Debug, Clone, Copy)]
pub struct AgentSpec {
    /// Which agent this describes.
    pub agent: SpawnAgent,
    /// Catalog id / `--agent` value.
    pub id: &'static str,
    /// Executable name searched for on `PATH`. Also the key into the shared
    /// [`crate::harness`] catalog for this agent's routing knowledge.
    pub binary: &'static str,
}

/// What `bitrouter launch` injects into the child process. The env/args come
/// from the shared [`crate::harness`] catalog's [`RoutingOverlay`], so the
/// interactive and ACP facets of a harness route identically.
#[derive(Debug, Clone, PartialEq, Eq)]
struct ChildLaunch {
    /// Environment overrides for the child process.
    env: Vec<(String, String)>,
    /// Arguments inserted before the user's forwarded args.
    args_prefix: Vec<String>,
}

/// Resolve the gateway bearer credential for a `bitrouter launch` child by
/// precedence: a token the user already exported for the harness →
/// `BITROUTER_API_KEY` → the local placeholder (valid under `skip_auth: true`,
/// the `bitrouter init` default; the harness merely needs *some* credential to
/// start).
fn resolve_launch_token(parent_auth: Option<String>, bitrouter_key: Option<String>) -> String {
    parent_auth
        .or(bitrouter_key)
        .unwrap_or_else(|| crate::harness::PLACEHOLDER_API_KEY.to_string())
}

/// Options gathered from the CLI for one `spawn` invocation.
pub struct SpawnOptions {
    /// Which agent to launch.
    pub agent: SpawnAgent,
    /// Arguments forwarded verbatim to the agent binary (everything the
    /// caller put after `--`).
    pub agent_args: Vec<String>,
    /// Explicit base URL override. When `None` it is derived from the
    /// daemon's `server.listen`.
    pub base_url: Option<String>,
    /// When true, never offer to install a missing agent — error instead.
    /// (Set by `--no-install`, or implied when stdin is not a TTY.)
    pub no_install: bool,
    /// When true, never auto-start a local daemon when none is running — just
    /// warn. (Set by `--no-start`.) Has no effect for a non-local / `--base-url`
    /// target, which is never auto-started regardless.
    pub no_start: bool,
    /// Check the spawn environment and route without launching the agent.
    pub check: bool,
}

/// One preflight check outcome.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SpawnCheckStatus {
    Pass,
    Warn,
    Fail,
}

/// A single preflight row.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SpawnCheckRow {
    pub name: String,
    pub status: SpawnCheckStatus,
    pub message: String,
}

/// Result of `bitrouter spawn --check`.
#[derive(Debug, Clone, Serialize)]
pub struct SpawnCheckReport {
    pub agent: String,
    pub base_url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    pub checks: Vec<SpawnCheckRow>,
}

impl SpawnCheckReport {
    fn has_failures(&self) -> bool {
        self.checks
            .iter()
            .any(|c| matches!(c.status, SpawnCheckStatus::Fail))
    }
}

impl CliReport for SpawnCheckReport {
    fn render(&self, h: &mut Human<'_>) -> std::io::Result<()> {
        h.line(&format!(
            "spawn check for {} via {}",
            self.agent, self.base_url
        ))?;
        if let Some(model) = &self.model {
            h.line(&format!("  model: {model}"))?;
        }
        h.blank()?;
        for check in &self.checks {
            h.line(&format!(
                "  {} {}: {}",
                match check.status {
                    SpawnCheckStatus::Pass => "✓",
                    SpawnCheckStatus::Warn => "!",
                    SpawnCheckStatus::Fail => "✗",
                },
                check.name,
                check.message
            ))?;
        }
        Ok(())
    }

    fn exit_code(&self) -> i32 {
        if self.has_failures() { 1 } else { 0 }
    }
}

/// Run `bitrouter spawn`. Resolves the base URL from `cfg`, locates the agent
/// binary (offering to install it if missing and permitted), ensures the local
/// daemon is up (auto-starting it when down), then execs the agent with the
/// routing environment injected. On success this **does not return** — it exits
/// the process with the agent's exit code, the way a launcher like
/// `git <subcommand>` propagates its child's status.
pub async fn run(
    source: &crate::paths::ConfigSource,
    cfg: &bitrouter_sdk::config::Config,
    opts: SpawnOptions,
) -> Result<()> {
    let spec = opts.agent.spec();

    let base_url = match &opts.base_url {
        Some(explicit) => explicit.clone(),
        None => derive_base_url(&cfg.server.listen),
    };

    if opts.agent == SpawnAgent::Codex {
        let conflicts = codex_forwarded_config_args(&opts.agent_args);
        if !conflicts.is_empty() {
            anyhow::bail!(
                "codex forwarded config flags ({}) can override BitRouter's one-shot provider \
                 injection. Remove those -c/--config flags and run `bitrouter spawn --agent \
                 codex --check` to inspect the route before launching.",
                conflicts.join(", ")
            );
        }
    }

    // Locate the binary; prompt-to-install when it's missing.
    let binary = ensure_agent_installed(opts.agent, opts.no_install).await?;

    // Make sure the daemon the agent will talk to is up. For the local daemon
    // we own (derived base URL + a loopback/wildcard bind), probe its control
    // socket and auto-start it when down; for an explicit `--base-url` or a
    // non-local bind we can only warn — we can't start someone else's daemon.
    if opts.base_url.is_none() && listen_is_local(&cfg.server.listen) {
        ensure_local_daemon(source, cfg, opts.no_start).await;
    } else {
        let target = opts
            .base_url
            .as_deref()
            .and_then(listen_from_base_url)
            .unwrap_or_else(|| cfg.server.listen.clone());
        warn_if_daemon_unreachable(&target);
    }

    // Resolve routing from the shared harness catalog so `launch` and `spawn`
    // inject identical env/args for the same harness (SPAWN_SPEC §4).
    let harness = crate::harness::by_interactive_binary(spec.binary).ok_or_else(|| {
        anyhow::anyhow!(
            "no catalog harness for interactive binary '{}'",
            spec.binary
        )
    })?;
    // Auth precedence (highest first): a bearer token the user already exported
    // for this harness → the BitRouter API key → a local placeholder. Only
    // env-routed harnesses (Claude) have such a var; Codex reads none.
    let parent_auth = match harness.routing {
        crate::harness::Routing::Env { auth_env, .. } => nonempty_env(auth_env),
        _ => None,
    };
    let token = resolve_launch_token(
        parent_auth,
        nonempty_env(crate::harness::BITROUTER_API_KEY_ENV),
    );
    let overlay = harness.routing_overlay(&base_url, &token, None);
    let launch = ChildLaunch {
        env: overlay.env,
        args_prefix: overlay.args,
    };

    let p = Palette::for_stderr();
    eprintln!(
        "{cyan}{bold}spawn:{reset} launching {bold}{}{reset} via BitRouter ({})",
        spec.id,
        base_url,
        cyan = p.cyan,
        bold = p.bold,
        reset = p.reset,
    );

    let mut cmd = tokio::process::Command::new(&binary);
    cmd.args(&launch.args_prefix);
    cmd.args(&opts.agent_args);
    for (k, v) in &launch.env {
        cmd.env(k, v);
    }
    // Inherit the parent's stdio so the agent owns the terminal directly
    // (Claude Code is an interactive TUI). Inheritance is the default for
    // `Command`, but we state it for clarity.
    cmd.stdin(std::process::Stdio::inherit())
        .stdout(std::process::Stdio::inherit())
        .stderr(std::process::Stdio::inherit());

    // Timestamp the wrapped session so the exit summary can attribute
    // spend to exactly this run of the agent.
    let session_start = chrono::Utc::now();

    let status = cmd
        .status()
        .await
        .with_context(|| format!("spawning agent '{}' ({})", spec.id, binary.display()))?;

    print_exit_summary(source, session_start, &p).await;

    // Propagate the agent's exit code. A launcher should be transparent: the
    // shell sees the agent's status, not bitrouter's.
    std::process::exit(status.code().unwrap_or(1));
}

/// The cost-feed exit renderer: after the wrapped agent exits, report
/// what the session spent through the local daemon. Silent when the
/// metering database is absent or recorded nothing in the window (e.g.
/// a `--base-url` pointed at Cloud) — a launcher must never turn a
/// clean exit into noise or an error. Printed to stderr like every
/// other spawn diagnostic; stdout belongs to the child.
async fn print_exit_summary(
    source: &crate::paths::ConfigSource,
    session_start: chrono::DateTime<chrono::Utc>,
    p: &Palette,
) {
    use crate::metering::store::TimeWindow;
    let Some(store) = crate::metering::reader::open_readonly(source).await else {
        return;
    };
    let window = TimeWindow::Custom {
        start: session_start,
        end: chrono::Utc::now(),
    };
    let (Ok(session), Ok(today)) = (
        store.spend_summary(window).await,
        store.spend_summary(TimeWindow::Today).await,
    ) else {
        return;
    };
    if session.requests == 0 {
        return;
    }
    eprintln!(
        "{cyan}{bold}spawn:{reset} session spend {bold}{}{reset} ({} requests) · today {}",
        crate::metering::fmt_usd(session.spend_micro_usd),
        session.requests,
        crate::metering::fmt_usd(today.spend_micro_usd),
        cyan = p.cyan,
        bold = p.bold,
        reset = p.reset,
    );
}

/// Check a spawn invocation without launching the child process.
pub async fn check(
    cfg: &bitrouter_sdk::config::Config,
    opts: &SpawnOptions,
) -> Result<SpawnCheckReport> {
    let spec = opts.agent.spec();
    let base_url = opts
        .base_url
        .clone()
        .unwrap_or_else(|| derive_base_url(&cfg.server.listen));
    let model = (opts.agent == SpawnAgent::Codex)
        .then(|| codex_requested_model(&opts.agent_args))
        .flatten();
    let mut checks = Vec::new();

    checks.push(match resolve_binary(spec.binary) {
        Some(path) => SpawnCheckRow {
            name: "agent binary".to_string(),
            status: SpawnCheckStatus::Pass,
            message: format!("found {}", path.display()),
        },
        None => SpawnCheckRow {
            name: "agent binary".to_string(),
            status: SpawnCheckStatus::Fail,
            message: format!("{} is not on PATH", spec.binary),
        },
    });

    checks.push(check_base_url(&base_url).await);

    if opts.agent == SpawnAgent::Codex {
        let conflicts = codex_forwarded_config_args(&opts.agent_args);
        checks.push(if conflicts.is_empty() {
            SpawnCheckRow {
                name: "codex config overrides".to_string(),
                status: SpawnCheckStatus::Pass,
                message: "no forwarded -c/--config flags detected".to_string(),
            }
        } else {
            SpawnCheckRow {
                name: "codex config overrides".to_string(),
                status: SpawnCheckStatus::Fail,
                message: format!(
                    "forwarded {} can override BitRouter's provider injection",
                    conflicts.join(", ")
                ),
            }
        });

        checks.push(match &model {
            Some(model) => {
                codex_route_check(model, crate::commands::resolve_route(cfg, model).await)
            }
            None => SpawnCheckRow {
                name: "codex model route".to_string(),
                status: SpawnCheckStatus::Warn,
                message: "no --model/-m forwarded; Codex will choose its default model".to_string(),
            },
        });
    }

    Ok(SpawnCheckReport {
        agent: spec.id.to_string(),
        base_url,
        model,
        checks,
    })
}

async fn check_base_url(base_url: &str) -> SpawnCheckRow {
    let health = format!("{}/health", bitrouter_root_url(base_url));
    match base_url_health(base_url).await {
        HealthProbe::Ok(status) => SpawnCheckRow {
            name: "bitrouter base url".to_string(),
            status: SpawnCheckStatus::Pass,
            message: format!("{health} responded {status}"),
        },
        HealthProbe::BadStatus(status) => SpawnCheckRow {
            name: "bitrouter base url".to_string(),
            status: SpawnCheckStatus::Fail,
            message: format!("{health} responded {status}"),
        },
        HealthProbe::Unreachable(e) => SpawnCheckRow {
            name: "bitrouter base url".to_string(),
            status: SpawnCheckStatus::Fail,
            message: format!("could not reach {health}: {e}"),
        },
    }
}

/// Outcome of a `GET {root}/health` probe.
enum HealthProbe {
    /// 2xx — the daemon is up.
    Ok(reqwest::StatusCode),
    /// Reached the daemon but it answered non-2xx.
    BadStatus(reqwest::StatusCode),
    /// Could not reach the endpoint at all.
    Unreachable(String),
}

/// Probe the daemon's `/health` endpoint behind `base_url`. Shared by
/// `spawn --check` and the ACP spawn path's fail-fast liveness gate.
async fn base_url_health(base_url: &str) -> HealthProbe {
    let health = format!("{}/health", bitrouter_root_url(base_url));
    let client = match reqwest::Client::builder()
        .timeout(Duration::from_secs(2))
        .build()
    {
        Ok(client) => client,
        Err(e) => return HealthProbe::Unreachable(format!("could not build HTTP client: {e}")),
    };
    match client.get(&health).send().await {
        Ok(resp) if resp.status().is_success() => HealthProbe::Ok(resp.status()),
        Ok(resp) => HealthProbe::BadStatus(resp.status()),
        Err(e) => HealthProbe::Unreachable(e.to_string()),
    }
}

/// True when the daemon behind `base_url` answers `GET /health` with 2xx.
/// Used by the ACP spawn path to fail fast before any session side effect.
pub(crate) async fn base_url_reachable(base_url: &str) -> bool {
    matches!(base_url_health(base_url).await, HealthProbe::Ok(_))
}

fn bitrouter_root_url(base_url: &str) -> String {
    let trimmed = base_url.trim_end_matches('/');
    trimmed.strip_suffix("/v1").unwrap_or(trimmed).to_string()
}

fn codex_requested_model(args: &[String]) -> Option<String> {
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        if arg == "--model" || arg == "-m" {
            return iter.next().filter(|v| !v.is_empty()).cloned();
        }
        if let Some(value) = arg.strip_prefix("--model=")
            && !value.is_empty()
        {
            return Some(value.to_string());
        }
    }
    None
}

fn codex_forwarded_config_args(args: &[String]) -> Vec<&'static str> {
    args.iter()
        .filter_map(|arg| match arg.as_str() {
            "-c" => Some("-c"),
            "--config" => Some("--config"),
            s if s.starts_with("--config=") => Some("--config"),
            _ => None,
        })
        .collect()
}

fn codex_route_check(model: &str, route: Result<Vec<crate::daemon::RouteHop>>) -> SpawnCheckRow {
    match route {
        Ok(chain) if chain.is_empty() => SpawnCheckRow {
            name: "codex model route".to_string(),
            status: SpawnCheckStatus::Fail,
            message: format!("{model} resolved to an empty route chain"),
        },
        Ok(chain) => {
            let providers = chain
                .iter()
                .map(|hop| format!("{}:{} ({})", hop.provider, hop.service_id, hop.api_protocol))
                .collect::<Vec<_>>()
                .join(" -> ");
            if chain
                .iter()
                .any(|hop| hop.api_protocol.eq_ignore_ascii_case("responses"))
            {
                SpawnCheckRow {
                    name: "codex model route".to_string(),
                    status: SpawnCheckStatus::Pass,
                    message: format!("{model} can route through Responses: {providers}"),
                }
            } else {
                SpawnCheckRow {
                    name: "codex model route".to_string(),
                    status: SpawnCheckStatus::Fail,
                    message: format!(
                        "{model} has no responses-compatible endpoint for Codex: {providers}"
                    ),
                }
            }
        }
        Err(e) => SpawnCheckRow {
            name: "codex model route".to_string(),
            status: SpawnCheckStatus::Fail,
            message: format!("could not resolve {model}: {e:#}"),
        },
    }
}

/// Read an environment variable, treating an unset *or empty* value as absent.
pub(crate) fn nonempty_env(name: &str) -> Option<String> {
    std::env::var(name).ok().filter(|v| !v.is_empty())
}

/// Derive the client-facing base URL from the daemon's `server.listen`
/// (`host:port`). Wildcard bind addresses are rewritten to loopback because a
/// client cannot *connect* to `0.0.0.0` / `::` — those mean "bind every
/// interface", not "reach me here".
pub(crate) fn derive_base_url(listen: &str) -> String {
    let (host, port) = split_listen(listen);
    format!("http://{}:{}", rewrite_host(host), port)
}

/// The default daemon port (mirrors `ServerConfig::default().listen`). Used
/// when `server.listen` carries a bare host with no `:port`.
const DEFAULT_PORT: &str = "4356";

/// Split a `server.listen` value into `(host, port)`, defaulting the port when
/// absent. Handles bracketed IPv6 (`[::1]:4356`, `[::1]`) so the `rsplit_once`
/// does not mistake a colon *inside* the brackets for the port separator.
fn split_listen(listen: &str) -> (&str, &str) {
    // Bracketed IPv6: the port (if any) follows the closing bracket.
    if listen.starts_with('[') {
        return match listen.rsplit_once("]:") {
            Some((host, port)) => (&listen[..host.len() + 1], port),
            // `[::1]` with no port.
            None => (listen, DEFAULT_PORT),
        };
    }
    match listen.rsplit_once(':') {
        Some((host, port)) => (host, port),
        None => (listen, DEFAULT_PORT),
    }
}

/// Rewrite a wildcard bind host to its loopback equivalent for a *client*
/// connection. `0.0.0.0` / empty → `127.0.0.1`; `::` / `[::]` → `[::1]`.
fn rewrite_host(host: &str) -> &str {
    match host {
        "0.0.0.0" | "" => "127.0.0.1",
        "::" | "[::]" => "[::1]",
        other => other,
    }
}

/// True when `listen` binds a loopback / wildcard address — i.e. a daemon on
/// *this* host that `bitrouter spawn` may auto-start. A remote or LAN host is
/// someone else's daemon, which we can only warn about. Exact-match only:
/// `127.0.0.0/8` aliases (e.g. `127.0.0.2`) and IPv4-mapped IPv6 fall through to
/// the warn path — the fail-safe direction (never a wrong auto-start).
pub(crate) fn listen_is_local(listen: &str) -> bool {
    let (host, _port) = split_listen(listen);
    matches!(
        host,
        "127.0.0.1" | "0.0.0.0" | "" | "::1" | "[::1]" | "::" | "[::]" | "localhost"
    )
}

/// Extract the `host[:port]` authority from a base URL for a best-effort
/// reachability note. Returns `None` when there is no authority to probe.
pub(crate) fn listen_from_base_url(url: &str) -> Option<String> {
    let rest = url
        .strip_prefix("http://")
        .or_else(|| url.strip_prefix("https://"))
        .unwrap_or(url);
    let authority = rest.split('/').next().unwrap_or(rest);
    (!authority.is_empty()).then(|| authority.to_string())
}

/// Ensure the local BitRouter daemon is up before launching the agent. Probes
/// the control socket; when nothing is listening (and `--no-start` was not
/// given) it prints a hint and auto-starts a detached `serve`, waiting for
/// readiness. Best-effort throughout: on any failure it warns and returns so
/// the agent still launches (and surfaces its own connection error) — matching
/// spawn's "never block the launch" stance.
pub(crate) async fn ensure_local_daemon(
    source: &crate::paths::ConfigSource,
    cfg: &bitrouter_sdk::config::Config,
    no_start: bool,
) {
    let socket = crate::daemon::socket_path_for(source, cfg);
    match crate::daemon::probe_status(&socket).await {
        // Already running — nothing to do.
        Ok(Some(_)) => {}
        // Definitively not reachable — auto-start unless opted out.
        Ok(None) => {
            let p = Palette::for_stderr();
            if no_start {
                warn_if_daemon_unreachable(&cfg.server.listen);
                return;
            }
            eprintln!(
                "{cyan}note:{reset} no BitRouter daemon is running — starting one…",
                cyan = p.cyan,
                reset = p.reset,
            );
            let log_path = source.home().join("bitrouter.log");
            match crate::daemon::start_and_wait(
                source,
                &log_path,
                Some(&socket),
                crate::daemon::DAEMON_READY_TIMEOUT,
            )
            .await
            {
                Ok(crate::daemon::DaemonStartOutcome::Ready(info)) => {
                    eprintln!(
                        "{cyan}note:{reset} BitRouter daemon ready (pid {})",
                        info.pid,
                        cyan = p.cyan,
                        reset = p.reset,
                    );
                }
                Ok(crate::daemon::DaemonStartOutcome::NotReadyInTime { pid }) => {
                    eprintln!(
                        "{cyan}note:{reset} daemon started (pid {pid}) but is not ready yet — \
                         the agent may need a moment; logs at {}",
                        log_path.display(),
                        cyan = p.cyan,
                        reset = p.reset,
                    );
                }
                Ok(crate::daemon::DaemonStartOutcome::Exited { status, log_tail }) => {
                    eprintln!(
                        "{cyan}note:{reset} daemon exited during startup ({status}) — \
                         launching the agent anyway",
                        cyan = p.cyan,
                        reset = p.reset,
                    );
                    crate::daemon::eprint_failure_log(&log_path, &log_tail);
                }
                Err(e) => {
                    eprintln!(
                        "{cyan}note:{reset} could not start the daemon ({e:#}) — \
                         launching the agent anyway",
                        cyan = p.cyan,
                        reset = p.reset,
                    );
                }
            }
        }
        // Reachable but the exchange errored — assume it's up; don't double-start.
        Err(e) => {
            tracing::debug!(error = %e, "daemon status probe errored; assuming up");
        }
    }
}

/// Locate an executable on `PATH`. Pure-`std` (no `which` crate) so the
/// `#![forbid(unsafe_code)]` lib stays dependency-light: split `$PATH` and
/// probe each entry. Returns the first match.
fn resolve_binary(name: &str) -> Option<PathBuf> {
    find_on_path(name, std::env::var_os("PATH"), &extra_search_dirs())
}

/// Core of [`resolve_binary`], factored out for testing. Searches `path` (an
/// `OsString` of `PATH`-separated dirs) followed by `extra` directories —
/// the latter covers the native installer's target (`~/.local/bin`), which is
/// often not yet on `PATH` in the shell that just ran the install.
fn find_on_path(name: &str, path: Option<OsString>, extra: &[PathBuf]) -> Option<PathBuf> {
    let mut dirs: Vec<PathBuf> = Vec::new();
    if let Some(path) = path {
        dirs.extend(std::env::split_paths(&path));
    }
    dirs.extend(extra.iter().cloned());
    for dir in dirs {
        let candidate = dir.join(name);
        if is_executable_file(&candidate) {
            return Some(candidate);
        }
        // On Windows, executables carry an extension. We probe the common
        // launcher extensions rather than parsing the full `%PATHEXT%` set —
        // agent CLIs ship as `.exe` or an npm `.cmd`/`.bat` shim, which these
        // cover; an exotic `%PATHEXT%` entry (`.com`, `.ps1`) would be missed.
        #[cfg(windows)]
        {
            for ext in ["exe", "cmd", "bat"] {
                let with_ext = dir.join(format!("{name}.{ext}"));
                if is_executable_file(&with_ext) {
                    return Some(with_ext);
                }
            }
        }
    }
    None
}

/// Directories to probe in addition to `PATH`. The Claude Code native
/// installer drops the binary in `~/.local/bin`, which a freshly-installed
/// shell session may not have on `PATH` yet.
fn extra_search_dirs() -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    if let Some(home) = home_dir() {
        dirs.push(home.join(".local").join("bin"));
    }
    dirs
}

/// True when `path` is a regular file we can plausibly execute. On Unix this
/// checks the executable permission bit; on other platforms, file existence.
fn is_executable_file(path: &std::path::Path) -> bool {
    let Ok(meta) = std::fs::metadata(path) else {
        return false;
    };
    if !meta.is_file() {
        return false;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        meta.permissions().mode() & 0o111 != 0
    }
    #[cfg(not(unix))]
    {
        true
    }
}

/// Resolve the user's home directory without pulling in a crate: `$HOME` on
/// Unix, `%USERPROFILE%` on Windows.
fn home_dir() -> Option<PathBuf> {
    #[cfg(windows)]
    {
        std::env::var_os("USERPROFILE").map(PathBuf::from)
    }
    #[cfg(not(windows))]
    {
        std::env::var_os("HOME").map(PathBuf::from)
    }
}

/// Ensure `agent`'s binary is installed — locating it on `PATH` (+
/// `~/.local/bin`) and offering the official native installer when permitted —
/// and return its path. Shared by `bitrouter spawn` and
/// `bitrouter providers login claude-code` (which needs the `claude` CLI to
/// sign the user in) so both go through one detect-and-install path.
pub(crate) async fn ensure_agent_installed(agent: SpawnAgent, no_install: bool) -> Result<PathBuf> {
    let spec = agent.spec();
    match resolve_binary(spec.binary) {
        Some(path) => Ok(path),
        None => ensure_installed(&spec, no_install).await,
    }
}

/// The agent binary is missing. Offer to install it via the official native
/// installer when stdin is interactive and `--no-install` was not set;
/// otherwise return an actionable error listing the install command.
async fn ensure_installed(spec: &AgentSpec, no_install: bool) -> Result<PathBuf> {
    let install = InstallCommand::for_agent(spec.agent);

    let may_prompt = !no_install && std::io::stdin().is_terminal();
    if !may_prompt {
        anyhow::bail!(
            "agent '{}' is not installed (no `{}` on PATH).\n  Install it with:\n    {}",
            spec.id,
            spec.binary,
            install.display(),
        );
    }

    if !confirm_install(spec, &install)? {
        anyhow::bail!("aborted — '{}' was not installed", spec.id);
    }

    install.run().await?;

    // Re-resolve after install. The installer may have landed the binary in
    // `~/.local/bin` (covered by `extra_search_dirs`) even when that dir is
    // not on the current shell's `PATH`.
    resolve_binary(spec.binary).ok_or_else(|| {
        anyhow::anyhow!(
            "installed '{}' but still cannot find `{}` on PATH or in ~/.local/bin — \
             open a new shell (or add the install dir to PATH) and re-run",
            spec.id,
            spec.binary,
        )
    })
}

/// Print the install prompt and read a Y/n answer. Defaults to yes on a bare
/// <enter>. A closed stdin (EOF) is treated as "no" so we never hang.
fn confirm_install(spec: &AgentSpec, install: &InstallCommand) -> Result<bool> {
    use std::io::{BufRead, Write};
    let p = Palette::for_stderr();
    eprintln!(
        "{cyan}{bold}info:{reset} agent `{}` is not installed on this machine.",
        spec.id,
        cyan = p.cyan,
        bold = p.bold,
        reset = p.reset,
    );
    eprintln!("  Installer: {}", install.display());
    eprint!("Proceed to install? [Y/n]: ");
    std::io::stderr().flush().ok();

    let stdin = std::io::stdin();
    let mut line = String::new();
    let n = stdin
        .lock()
        .read_line(&mut line)
        .context("reading install confirmation from stdin")?;
    if n == 0 {
        // EOF — non-interactive; decline rather than block.
        eprintln!();
        return Ok(false);
    }
    let answer = line.trim().to_ascii_lowercase();
    Ok(answer.is_empty() || answer == "y" || answer == "yes")
}

/// Best-effort TCP reachability probe against the daemon's listen address.
/// Prints a one-line warning when nothing is listening; never errors.
fn warn_if_daemon_unreachable(listen: &str) {
    use std::net::{TcpStream, ToSocketAddrs};
    use std::time::Duration;

    // Map the wildcard bind host to loopback for the *connect* attempt, same
    // as the base-URL derivation.
    let (host, port) = split_listen(listen);
    let probe = format!("{}:{}", rewrite_host(host), port);

    let reachable = probe
        .to_socket_addrs()
        .ok()
        .and_then(|mut addrs| addrs.next())
        .map(|addr| TcpStream::connect_timeout(&addr, Duration::from_millis(300)).is_ok())
        .unwrap_or(false);

    if !reachable {
        let p = Palette::for_stderr();
        eprintln!(
            "{cyan}note:{reset} no BitRouter daemon appears to be listening on {probe} — \
             start one with `bitrouter start` (the agent will fail to reach it otherwise).",
            cyan = p.cyan,
            reset = p.reset,
        );
    }
}

/// A platform-specific install command for an agent. Conditional compilation
/// makes exactly one variant visible per platform, so the help text and the
/// executed command never disagree with the host.
#[derive(Debug, Clone)]
pub struct InstallCommand {
    /// Program to run (`bash` / `powershell`).
    program: &'static str,
    /// Arguments to that program.
    args: Vec<String>,
    /// Human-readable one-liner, e.g. `curl -fsSL … | bash`.
    human: String,
}

impl InstallCommand {
    /// The official native installer for `agent` on the *current* platform.
    ///
    /// Sources:
    /// - Claude Code quickstart, "Native Install":
    ///   <https://code.claude.com/docs/en/quickstart>
    /// - macOS / Linux: `curl -fsSL https://claude.ai/install.sh | bash`
    /// - Windows:       `irm https://claude.ai/install.ps1 | iex`
    /// - Codex quickstart:
    ///   <https://developers.openai.com/codex/quickstart>
    /// - macOS / Linux: `curl -fsSL https://chatgpt.com/codex/install.sh | sh`
    /// - Windows:       `irm https://chatgpt.com/codex/install.ps1 | iex`
    pub fn for_agent(agent: SpawnAgent) -> Self {
        match agent {
            SpawnAgent::Claude => Self::claude(),
            SpawnAgent::Codex => Self::codex(),
        }
    }

    #[cfg(not(windows))]
    fn claude() -> Self {
        let human = "curl -fsSL https://claude.ai/install.sh | bash".to_string();
        Self {
            program: "bash",
            args: vec![
                "-c".to_string(),
                "curl -fsSL https://claude.ai/install.sh | bash".to_string(),
            ],
            human,
        }
    }

    #[cfg(windows)]
    fn claude() -> Self {
        let human = "irm https://claude.ai/install.ps1 | iex".to_string();
        Self {
            program: "powershell",
            args: vec![
                "-NoProfile".to_string(),
                "-Command".to_string(),
                "irm https://claude.ai/install.ps1 | iex".to_string(),
            ],
            human,
        }
    }

    #[cfg(not(windows))]
    fn codex() -> Self {
        let human = "curl -fsSL https://chatgpt.com/codex/install.sh | sh".to_string();
        Self {
            program: "sh",
            args: vec![
                "-c".to_string(),
                "curl -fsSL https://chatgpt.com/codex/install.sh | sh".to_string(),
            ],
            human,
        }
    }

    #[cfg(windows)]
    fn codex() -> Self {
        let human =
            r#"powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex""#
                .to_string();
        Self {
            program: "powershell",
            args: vec![
                "-ExecutionPolicy".to_string(),
                "ByPass".to_string(),
                "-c".to_string(),
                "irm https://chatgpt.com/codex/install.ps1 | iex".to_string(),
            ],
            human,
        }
    }

    /// The human-readable one-liner shown in prompts and error messages.
    pub fn display(&self) -> &str {
        &self.human
    }

    /// Execute the installer, inheriting stdio so the user sees its progress.
    /// Errors when the installer exits non-zero.
    async fn run(&self) -> Result<()> {
        let p = Palette::for_stderr();
        eprintln!(
            "{cyan}spawn:{reset} installing — {}",
            self.human,
            cyan = p.cyan,
            reset = p.reset,
        );
        let status = tokio::process::Command::new(self.program)
            .args(&self.args)
            .status()
            .await
            .with_context(|| format!("running installer: {}", self.human))?;
        if !status.success() {
            anyhow::bail!("installer exited with {status}: {}", self.human);
        }
        Ok(())
    }
}

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

    #[test]
    fn listen_is_local_classifies_loopback_and_wildcard() {
        for local in [
            "127.0.0.1:4356",
            "0.0.0.0:4356",
            "[::1]:4356",
            "[::]:4356",
            "localhost:4356",
            "127.0.0.1",
        ] {
            assert!(listen_is_local(local), "{local} should be local");
        }
        for remote in [
            "router.internal:8080",
            "192.168.1.5:4356",
            "10.0.0.3:4356",
            "example.com:443",
        ] {
            assert!(!listen_is_local(remote), "{remote} should be remote");
        }
    }

    #[test]
    fn listen_from_base_url_extracts_authority() {
        assert_eq!(
            listen_from_base_url("http://127.0.0.1:4356").as_deref(),
            Some("127.0.0.1:4356")
        );
        assert_eq!(
            listen_from_base_url("https://router.example.com/v1").as_deref(),
            Some("router.example.com")
        );
        // No scheme → treated as a bare authority.
        assert_eq!(
            listen_from_base_url("127.0.0.1:4356").as_deref(),
            Some("127.0.0.1:4356")
        );
        assert_eq!(listen_from_base_url(""), None);
    }

    #[test]
    fn base_url_rewrites_wildcard_bind_to_loopback() {
        assert_eq!(derive_base_url("0.0.0.0:4356"), "http://127.0.0.1:4356");
        assert_eq!(derive_base_url("[::]:4356"), "http://[::1]:4356");
    }

    #[test]
    fn base_url_preserves_explicit_host() {
        assert_eq!(derive_base_url("127.0.0.1:4356"), "http://127.0.0.1:4356");
        assert_eq!(
            derive_base_url("router.internal:8080"),
            "http://router.internal:8080"
        );
        // A bracketed IPv6 literal keeps its brackets and port.
        assert_eq!(derive_base_url("[::1]:9000"), "http://[::1]:9000");
    }

    #[test]
    fn base_url_defaults_port_when_missing() {
        assert_eq!(derive_base_url("127.0.0.1"), "http://127.0.0.1:4356");
        // Bracketed IPv6 without a port must not split inside the brackets.
        assert_eq!(derive_base_url("[::1]"), "http://[::1]:4356");
    }

    #[test]
    fn launch_token_precedence() {
        // User's exported token wins over everything.
        assert_eq!(
            resolve_launch_token(Some("user-token".into()), Some("brk_key".into())),
            "user-token"
        );
        // No exported token → fall back to the BitRouter API key.
        assert_eq!(
            resolve_launch_token(None, Some("brk_key".into())),
            "brk_key"
        );
        // Neither set → the local placeholder so the harness still starts.
        assert_eq!(
            resolve_launch_token(None, None),
            crate::harness::PLACEHOLDER_API_KEY
        );
    }

    #[test]
    fn launch_agents_map_to_catalog_harnesses() {
        // The interactive binary is the key into the shared routing catalog;
        // the overlay content itself is covered by `harness` tests.
        let claude = crate::harness::by_interactive_binary(SpawnAgent::Claude.spec().binary)
            .expect("claude maps to a catalog harness");
        assert_eq!(claude.id, "claude-acp");
        assert!(matches!(
            claude.routing,
            crate::harness::Routing::Env {
                base_url_env: "ANTHROPIC_BASE_URL",
                auth_env: "ANTHROPIC_AUTH_TOKEN",
                ..
            }
        ));

        let codex = crate::harness::by_interactive_binary(SpawnAgent::Codex.spec().binary)
            .expect("codex maps to a catalog harness");
        assert_eq!(codex.id, "codex-acp");
        assert!(matches!(codex.routing, crate::harness::Routing::CodexArgs));
    }

    #[test]
    fn codex_spec_uses_codex_binary() {
        let spec = SpawnAgent::Codex.spec();
        assert_eq!(spec.binary, "codex");
        assert_eq!(spec.id, "codex");
    }

    #[test]
    fn codex_requested_model_reads_forwarded_model_args() {
        assert_eq!(
            codex_requested_model(&[
                "exec".to_string(),
                "--model".to_string(),
                "gpt-5.5".to_string()
            ])
            .as_deref(),
            Some("gpt-5.5")
        );
        assert_eq!(
            codex_requested_model(&[
                "exec".to_string(),
                "-m".to_string(),
                "local-model".to_string()
            ])
            .as_deref(),
            Some("local-model")
        );
        assert_eq!(codex_requested_model(&["exec".to_string()]), None);
    }

    #[test]
    fn codex_forwarded_config_args_are_flagged_before_launch() {
        let conflicts = codex_forwarded_config_args(&[
            "exec".to_string(),
            "-c".to_string(),
            "foo=1".to_string(),
        ]);
        assert_eq!(conflicts, vec!["-c"]);

        let conflicts = codex_forwarded_config_args(&[
            "exec".to_string(),
            "--config".to_string(),
            "model_provider=\"openai\"".to_string(),
        ]);
        assert_eq!(conflicts, vec!["--config"]);
    }

    #[test]
    fn bitrouter_root_url_strips_v1_for_preflight_health_probe() {
        assert_eq!(
            bitrouter_root_url("http://127.0.0.1:4356/v1"),
            "http://127.0.0.1:4356"
        );
        assert_eq!(
            bitrouter_root_url("http://127.0.0.1:4356"),
            "http://127.0.0.1:4356"
        );
    }

    #[test]
    fn codex_route_check_accepts_any_responses_provider() {
        let route = vec![crate::daemon::RouteHop {
            provider: "openai".to_string(),
            service_id: "gpt-5.5".to_string(),
            api_protocol: "responses".to_string(),
        }];
        let check = codex_route_check("gpt-5.5", Ok(route));
        assert_eq!(check.status, SpawnCheckStatus::Pass);
        assert!(check.message.contains("openai"));
    }

    #[test]
    fn codex_route_check_rejects_non_responses_provider() {
        let route = vec![crate::daemon::RouteHop {
            provider: "anthropic".to_string(),
            service_id: "claude-sonnet".to_string(),
            api_protocol: "messages".to_string(),
        }];
        let check = codex_route_check("claude-sonnet", Ok(route));
        assert_eq!(check.status, SpawnCheckStatus::Fail);
        assert!(check.message.contains("responses"));
    }

    #[test]
    fn install_command_is_the_official_native_installer() {
        let cmd = InstallCommand::for_agent(SpawnAgent::Claude);
        // Same canonical URL on every platform; the transport differs.
        assert!(cmd.display().contains("claude.ai/install"));
        #[cfg(not(windows))]
        {
            assert!(cmd.display().contains("install.sh"));
            assert!(cmd.display().contains("| bash"));
        }
        #[cfg(windows)]
        {
            assert!(cmd.display().contains("install.ps1"));
        }

        let codex = InstallCommand::for_agent(SpawnAgent::Codex);
        assert!(codex.display().contains("chatgpt.com/codex/install"));
        #[cfg(not(windows))]
        {
            assert!(codex.display().contains("install.sh"));
            assert!(codex.display().contains("| sh"));
        }
        #[cfg(windows)]
        {
            assert!(codex.display().contains("install.ps1"));
        }
    }

    #[test]
    fn find_on_path_locates_executable_in_listed_dir() {
        let dir = std::env::temp_dir().join(format!("bitrouter-spawn-path-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let bin = dir.join("fake-agent");
        std::fs::write(&bin, b"#!/bin/sh\n").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        let path = std::env::join_paths([dir.as_os_str()]).unwrap();
        let found = find_on_path("fake-agent", Some(path), &[]);
        assert_eq!(found.as_deref(), Some(bin.as_path()));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn find_on_path_returns_none_when_absent() {
        let path = std::env::join_paths([std::env::temp_dir().as_os_str()]).unwrap();
        assert!(find_on_path("definitely-not-a-real-binary-xyz", Some(path), &[]).is_none());
    }

    #[test]
    fn find_on_path_falls_back_to_extra_dirs() {
        // The post-install re-resolution relies on `extra` (e.g. ~/.local/bin)
        // even when PATH is empty — exercise that path explicitly.
        let dir =
            std::env::temp_dir().join(format!("bitrouter-spawn-extra-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let bin = dir.join("fake-agent");
        std::fs::write(&bin, b"#!/bin/sh\n").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        // PATH is None entirely; the binary is only reachable via `extra`.
        let found = find_on_path("fake-agent", None, std::slice::from_ref(&dir));
        assert_eq!(found.as_deref(), Some(bin.as_path()));
        let _ = std::fs::remove_dir_all(&dir);
    }
}