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
//! Unified coding-agent **harness catalog** — the single source of truth for
//! how BitRouter finds, launches, and routes each supported harness.
//!
//! A harness is drivable in either of two facets:
//!
//! - **interactive** (`bitrouter launch`) — the harness's own native TUI
//!   (`claude`, `codex`), launched as a child with its LLM traffic env-wrapped
//!   to the daemon; the human drives it directly.
//! - **ACP** (`bitrouter spawn`) — a headless ACP adapter
//!   (`@zed-industries/claude-code-acp`, …) driven as a sub-agent by a program.
//!
//! The crucial fact this module encodes once: **both facets route through the
//! daemon with the same [`Routing`]**, because the interactive binary and the
//! ACP adapter of a given harness share a config/env surface (verified against
//! adapter source — see `SPAWN_SPEC.md` §6). So the routing knowledge that used
//! to live in `spawn::AgentSpec` *and* would have been duplicated onto the ACP
//! side lives here exactly once, and `launch`, `spawn`, and `agents install`
//! all read it.

/// BitRouter's own API-key env var (`brk_…`). When set, it is forwarded to the
/// harness as the gateway bearer credential.
pub const BITROUTER_API_KEY_ENV: &str = "BITROUTER_API_KEY";

/// Placeholder credential injected when no real key is available. Ignored by
/// the daemon under `skip_auth: true` (the `bitrouter init` default); the
/// harness merely needs *some* credential to start.
pub const PLACEHOLDER_API_KEY: &str = "bitrouter-local";

/// One catalog harness. Keyed by [`id`](Self::id), which is the ACP-facet
/// id used under `agents:` in `bitrouter.yaml` and by `bitrouter agents`.
#[derive(Debug, Clone, Copy)]
pub struct Harness {
    /// Catalog / ACP-config id (e.g. `claude-acp`). Also the `agents install`
    /// key.
    pub id: &'static str,
    /// One-line human description (shown in `agents list`).
    pub description: &'static str,
    /// Upstream project URL — the source of the recommended invocation.
    pub project_url: &'static str,
    /// The ACP adapter invocation (`command` + `args`) for `bitrouter spawn`.
    pub acp_command: &'static str,
    /// Args passed to [`acp_command`](Self::acp_command).
    pub acp_args: &'static [&'static str],
    /// A substring that identifies this harness inside a configured agent's
    /// invocation (command or any arg) — used to map a user-renamed
    /// `agents:` entry back to its catalog routing (invocation matching, so
    /// the YAML key carries no semantics). Usually the adapter package name.
    pub package_marker: &'static str,
    /// The interactive native-TUI binary for `bitrouter launch`, when the
    /// harness has one. `None` for adapter-only harnesses (gemini, pi).
    pub interactive_binary: Option<&'static str>,
    /// How this harness's LLM traffic is pointed at the daemon.
    pub routing: Routing,
}

/// How a harness's LLM traffic is redirected to the BitRouter gateway. One
/// value per harness, applied identically to both facets.
#[derive(Debug, Clone, Copy)]
pub enum Routing {
    /// Env-var redirection: set `base_url_env` to the gateway URL and
    /// `auth_env` to the bearer credential (BitRouter's inbound scheme is
    /// `Authorization: Bearer`; never a provider `x-api-key` var). Optional
    /// `model_env` pins the model; `extra` carries fixed vars the redirect
    /// needs. Used by claude-code-acp (and interactive Claude Code) and,
    /// best-effort, gemini-cli.
    Env {
        /// Var the harness reads its gateway base URL from.
        base_url_env: &'static str,
        /// Var the harness turns into the gateway credential.
        auth_env: &'static str,
        /// Whether the harness sends `auth_env` as `Authorization: Bearer`
        /// (BitRouter's inbound scheme). `false` means a provider-native
        /// header the daemon's auth hook rejects under `skip_auth: false`
        /// (e.g. gemini's `x-goog-api-key`) — routing then only works under
        /// `skip_auth: true`, and callers warn when auth is required.
        bearer_auth: bool,
        /// Var that pins the model, when the harness supports one.
        model_env: Option<&'static str>,
        /// Fixed vars required for the redirect to take effect.
        extra: &'static [(&'static str, &'static str)],
    },
    /// Codex `-c` one-shot config overrides (codex-acp forwards argv to codex
    /// core, so the same overrides work for both facets). The gateway must
    /// speak the OpenAI **Responses** API — pinned codex builds dropped
    /// `wire_api = "chat"`.
    CodexArgs,
    /// A known harness with no non-invasive gateway mechanism (verified
    /// absent). Spawned direct with a warning; never silently mis-routed.
    Unroutable {
        /// Why it can't be routed, surfaced to the user.
        reason: &'static str,
    },
}

/// The child-process overrides a [`Routing`] contributes: env vars to set
/// (injection wins over inherited/config env) and args to append to the
/// harness invocation.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RoutingOverlay {
    /// Env vars to set on the child (each overrides any inherited value).
    pub env: Vec<(String, String)>,
    /// Args appended to the harness invocation.
    pub args: Vec<String>,
}

/// The bundled catalog. Limited to publicly-available, actively-maintained
/// harnesses. Extend by PR to bitrouter.
pub const CATALOG: &[Harness] = &[
    Harness {
        id: "claude-acp",
        description: "Anthropic Claude via Zed's `claude-code-acp`",
        project_url: "https://github.com/zed-industries/claude-code-acp",
        acp_command: "npx",
        acp_args: &["-y", "@zed-industries/claude-code-acp@latest"],
        // A substring of both the npm spec (`@zed-industries/claude-code-acp`)
        // and the globally-installed binary name (`claude-code-acp`), so a
        // `command: claude-code-acp` config still catalog-matches.
        package_marker: "claude-code-acp",
        interactive_binary: Some("claude"),
        // claude-code-acp passes process env through to the SDK-spawned CLI,
        // which honors these exactly as interactive Claude Code does.
        // ANTHROPIC_AUTH_TOKEN → `Authorization: Bearer` (also suppresses the
        // login requirement); ANTHROPIC_API_KEY would be `x-api-key`, not
        // BitRouter's inbound scheme, so we never touch it.
        routing: Routing::Env {
            base_url_env: "ANTHROPIC_BASE_URL",
            auth_env: "ANTHROPIC_AUTH_TOKEN",
            bearer_auth: true,
            model_env: Some("ANTHROPIC_MODEL"),
            extra: &[],
        },
    },
    Harness {
        id: "codex-acp",
        description: "OpenAI Codex via Zed's `codex-acp`",
        project_url: "https://github.com/zed-industries/codex-acp",
        acp_command: "npx",
        acp_args: &["-y", "@zed-industries/codex-acp@latest"],
        package_marker: "codex-acp",
        interactive_binary: Some("codex"),
        routing: Routing::CodexArgs,
    },
    Harness {
        id: "gemini-cli",
        description: "Google's Gemini CLI with `--experimental-acp` (best-effort routing)",
        project_url: "https://github.com/google-gemini/gemini-cli",
        acp_command: "npx",
        acp_args: &[
            "-y",
            "--",
            "@google/gemini-cli@latest",
            "--experimental-acp",
        ],
        // Substring of both `@google/gemini-cli` and the `gemini-cli` binary.
        package_marker: "gemini-cli",
        interactive_binary: None,
        // Best-effort: gemini-cli is deprecated upstream (Antigravity). Sends
        // GEMINI_API_KEY as `x-goog-api-key`, which the daemon accepts only
        // under skip_auth; GOOGLE_GEMINI_BASE_URL auto-selects GATEWAY auth.
        routing: Routing::Env {
            base_url_env: "GOOGLE_GEMINI_BASE_URL",
            auth_env: "GEMINI_API_KEY",
            // gemini sends GEMINI_API_KEY as `x-goog-api-key`, not Bearer —
            // the daemon accepts it only under `skip_auth: true`.
            bearer_auth: false,
            model_env: Some("GEMINI_MODEL"),
            extra: &[],
        },
    },
    Harness {
        id: "pi-acp",
        description: "pi coding agent via `pi-acp` (needs `pi` on PATH)",
        project_url: "https://github.com/svkozak/pi-acp",
        acp_command: "npx",
        acp_args: &["-y", "pi-acp@latest"],
        package_marker: "pi-acp",
        interactive_binary: None,
        routing: Routing::Unroutable {
            reason: "pi has no base-URL env var; route by synthesizing a \
                     PI_CODING_AGENT_DIR with a models.json provider \
                     (SPAWN_SPEC §6.4, planned v1.1)",
        },
    },
];

/// Look up a harness by its catalog id.
pub fn by_id(id: &str) -> Option<&'static Harness> {
    CATALOG.iter().find(|h| h.id == id)
}

/// Look up a harness by its interactive binary name (`launch` uses this to
/// share the ACP-side routing knowledge).
pub fn by_interactive_binary(binary: &str) -> Option<&'static Harness> {
    CATALOG
        .iter()
        .find(|h| h.interactive_binary == Some(binary))
}

/// Match a configured agent's invocation back to a catalog harness by its
/// [`package_marker`](Harness::package_marker), so routing follows the
/// *invocation*, not the user-chosen YAML key. Checks the command and every
/// arg for the marker substring.
pub fn match_invocation(command: &str, args: &[String]) -> Option<&'static Harness> {
    CATALOG.iter().find(|h| {
        command.contains(h.package_marker) || args.iter().any(|a| a.contains(h.package_marker))
    })
}

impl Harness {
    /// Compute the child-process overlay that routes this harness's LLM
    /// traffic through `base_url`, authenticating with `auth` (already
    /// resolved by precedence — see [`resolve_gateway_auth`]). `model` pins
    /// the model when the harness supports it. Returns an empty overlay for
    /// an [`Unroutable`](Routing::Unroutable) harness (the caller warns).
    pub fn routing_overlay(
        &self,
        base_url: &str,
        auth: &str,
        model: Option<&str>,
    ) -> RoutingOverlay {
        match &self.routing {
            Routing::Env {
                base_url_env,
                auth_env,
                model_env,
                extra,
                ..
            } => {
                let mut env = vec![
                    ((*base_url_env).to_string(), base_url.to_string()),
                    ((*auth_env).to_string(), auth.to_string()),
                ];
                for (k, v) in *extra {
                    env.push(((*k).to_string(), (*v).to_string()));
                }
                if let (Some(var), Some(m)) = (model_env, model) {
                    env.push(((*var).to_string(), m.to_string()));
                }
                RoutingOverlay {
                    env,
                    args: Vec::new(),
                }
            }
            Routing::CodexArgs => codex_overlay(base_url, auth, model),
            Routing::Unroutable { .. } => RoutingOverlay::default(),
        }
    }

    /// Whether this harness can be routed through the daemon at all.
    pub fn is_routable(&self) -> bool {
        !matches!(self.routing, Routing::Unroutable { .. })
    }

    /// Whether the harness sends its gateway credential as `Authorization:
    /// Bearer` (BitRouter's inbound scheme). `false` means a provider-native
    /// header the daemon rejects under `skip_auth: false` (gemini). Codex's
    /// `env_key` path is Bearer, so non-`Env` routings are bearer-compatible.
    pub fn auth_is_bearer(&self) -> bool {
        match self.routing {
            Routing::Env { bearer_auth, .. } => bearer_auth,
            _ => true,
        }
    }

    /// Whether `--model` can be applied to this harness.
    pub fn supports_model_pin(&self) -> bool {
        match self.routing {
            Routing::Env { model_env, .. } => model_env.is_some(),
            Routing::CodexArgs => true,
            Routing::Unroutable { .. } => false,
        }
    }
}

/// Resolve the gateway credential by precedence: a real `BITROUTER_API_KEY`
/// (`brk_…`) when exported, else the local placeholder. Returns `None` only
/// when `require_key` is set (daemon auth is on) and no real key is present —
/// the caller then fails fast (`SPAWN_SPEC` §5.4).
pub fn resolve_gateway_auth(bitrouter_key: Option<String>, require_key: bool) -> Option<String> {
    match bitrouter_key {
        Some(key) => Some(key),
        None if require_key => None,
        None => Some(PLACEHOLDER_API_KEY.to_string()),
    }
}

/// The Codex `-c` provider-override overlay. Mirrors the interactive
/// `bitrouter launch` codex wiring so both facets route identically.
fn codex_overlay(base_url: &str, auth: &str, model: Option<&str>) -> RoutingOverlay {
    let mut env = Vec::new();
    let mut args = vec![
        "-c".to_string(),
        codex_config_string("model_provider", "bitrouter"),
        "-c".to_string(),
        codex_config_string("model_providers.bitrouter.name", "BitRouter"),
        "-c".to_string(),
        codex_config_string(
            "model_providers.bitrouter.base_url",
            &codex_api_base_url(base_url),
        ),
        "-c".to_string(),
        codex_config_string("model_providers.bitrouter.wire_api", "responses"),
    ];

    // Real key → env_key indirection (keeps the secret out of argv/process
    // listing); placeholder → inline experimental_bearer_token.
    if auth == PLACEHOLDER_API_KEY {
        args.push("-c".to_string());
        args.push(codex_config_string(
            "model_providers.bitrouter.experimental_bearer_token",
            PLACEHOLDER_API_KEY,
        ));
    } else {
        env.push((BITROUTER_API_KEY_ENV.to_string(), auth.to_string()));
        args.push("-c".to_string());
        args.push(codex_config_string(
            "model_providers.bitrouter.env_key",
            BITROUTER_API_KEY_ENV,
        ));
    }

    if let Some(m) = model {
        args.push("-c".to_string());
        args.push(codex_config_string("model", m));
    }

    RoutingOverlay { env, args }
}

/// Codex custom providers use `/v1`-suffixed base URLs (Responses API).
fn codex_api_base_url(base_url: &str) -> String {
    let trimmed = base_url.trim_end_matches('/');
    if trimmed.ends_with("/v1") {
        trimmed.to_string()
    } else {
        format!("{trimmed}/v1")
    }
}

fn codex_config_string(key: &str, value: &str) -> String {
    format!("{key}={}", toml_string(value))
}

/// Quote a value as a TOML basic string for a `-c key=value` override.
fn toml_string(value: &str) -> String {
    let mut out = String::with_capacity(value.len() + 2);
    out.push('"');
    for ch in value.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            other => out.push(other),
        }
    }
    out.push('"');
    out
}

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

    #[test]
    fn catalog_ids_are_unique() {
        let mut ids: Vec<_> = CATALOG.iter().map(|h| h.id).collect();
        ids.sort_unstable();
        let before = ids.len();
        ids.dedup();
        assert_eq!(before, ids.len(), "catalog ids must be unique");
    }

    #[test]
    fn by_interactive_binary_finds_claude_and_codex() {
        assert_eq!(by_interactive_binary("claude").unwrap().id, "claude-acp");
        assert_eq!(by_interactive_binary("codex").unwrap().id, "codex-acp");
        assert!(by_interactive_binary("gemini").is_none());
    }

    #[test]
    fn match_invocation_maps_renamed_key_by_package_marker() {
        // A user-renamed entry ("my-claude") still maps to claude-acp routing.
        let h = match_invocation(
            "npx",
            &[
                "-y".to_string(),
                "@zed-industries/claude-code-acp@latest".to_string(),
            ],
        )
        .expect("matches claude-acp");
        assert_eq!(h.id, "claude-acp");
    }

    #[test]
    fn match_invocation_none_for_unknown_command() {
        assert!(match_invocation("./my-custom-agent", &[]).is_none());
    }

    #[test]
    fn match_invocation_matches_globally_installed_binary_command() {
        // A `command: claude-code-acp` (npm -g binary) must catalog-match the
        // same as the `npx @zed-industries/claude-code-acp` package form.
        assert_eq!(
            match_invocation("claude-code-acp", &[]).unwrap().id,
            "claude-acp"
        );
        assert_eq!(
            match_invocation("gemini-cli", &[]).unwrap().id,
            "gemini-cli"
        );
        assert_eq!(match_invocation("codex-acp", &[]).unwrap().id, "codex-acp");
    }

    #[test]
    fn catalog_markers_are_mutually_non_substrings() {
        // A false-positive would mis-route one harness as another.
        for a in CATALOG {
            for b in CATALOG {
                if a.id != b.id {
                    assert!(
                        !a.package_marker.contains(b.package_marker),
                        "marker '{}' contains '{}'",
                        a.package_marker,
                        b.package_marker
                    );
                }
            }
        }
    }

    #[test]
    fn auth_is_bearer_flags_gemini_as_non_bearer() {
        assert!(by_id("claude-acp").unwrap().auth_is_bearer());
        assert!(by_id("codex-acp").unwrap().auth_is_bearer());
        assert!(!by_id("gemini-cli").unwrap().auth_is_bearer());
    }

    #[test]
    fn supports_model_pin_reflects_catalog() {
        assert!(by_id("claude-acp").unwrap().supports_model_pin());
        assert!(by_id("codex-acp").unwrap().supports_model_pin());
        assert!(by_id("gemini-cli").unwrap().supports_model_pin());
        assert!(!by_id("pi-acp").unwrap().supports_model_pin());
    }

    #[test]
    fn claude_overlay_sets_base_url_and_bearer_token() {
        let h = by_id("claude-acp").unwrap();
        let o = h.routing_overlay("http://127.0.0.1:4356", "brk_real", None);
        assert!(o.env.contains(&(
            "ANTHROPIC_BASE_URL".to_string(),
            "http://127.0.0.1:4356".to_string()
        )));
        assert!(
            o.env
                .contains(&("ANTHROPIC_AUTH_TOKEN".to_string(), "brk_real".to_string()))
        );
        // Never the x-api-key var.
        assert!(o.env.iter().all(|(k, _)| k != "ANTHROPIC_API_KEY"));
        assert!(o.args.is_empty());
    }

    #[test]
    fn claude_overlay_pins_model_when_given() {
        let h = by_id("claude-acp").unwrap();
        let o = h.routing_overlay("http://x:1", "t", Some("claude-sonnet-5"));
        assert!(
            o.env
                .contains(&("ANTHROPIC_MODEL".to_string(), "claude-sonnet-5".to_string()))
        );
        // Absent when no model requested.
        let o2 = h.routing_overlay("http://x:1", "t", None);
        assert!(o2.env.iter().all(|(k, _)| k != "ANTHROPIC_MODEL"));
    }

    #[test]
    fn codex_overlay_routes_responses_to_v1_and_uses_env_key_for_real_key() {
        let h = by_id("codex-acp").unwrap();
        let o = h.routing_overlay("http://127.0.0.1:4356", "brk_real", None);
        assert!(o.args.contains(&"model_provider=\"bitrouter\"".to_string()));
        assert!(o.args.contains(
            &"model_providers.bitrouter.base_url=\"http://127.0.0.1:4356/v1\"".to_string()
        ));
        assert!(
            o.args
                .contains(&"model_providers.bitrouter.wire_api=\"responses\"".to_string())
        );
        assert!(
            o.args
                .contains(&"model_providers.bitrouter.env_key=\"BITROUTER_API_KEY\"".to_string())
        );
        assert!(
            o.env
                .contains(&("BITROUTER_API_KEY".to_string(), "brk_real".to_string()))
        );
        assert!(
            o.args
                .iter()
                .all(|a| !a.contains("experimental_bearer_token"))
        );
    }

    #[test]
    fn codex_overlay_uses_inline_token_for_placeholder() {
        let h = by_id("codex-acp").unwrap();
        let o = h.routing_overlay("http://127.0.0.1:4356", PLACEHOLDER_API_KEY, None);
        assert!(o.args.contains(
            &"model_providers.bitrouter.experimental_bearer_token=\"bitrouter-local\"".to_string()
        ));
        assert!(o.env.iter().all(|(k, _)| k != "BITROUTER_API_KEY"));
    }

    #[test]
    fn codex_overlay_pins_model() {
        let h = by_id("codex-acp").unwrap();
        let o = h.routing_overlay("http://x:1", PLACEHOLDER_API_KEY, Some("gpt-5.2"));
        assert!(o.args.contains(&"model=\"gpt-5.2\"".to_string()));
    }

    #[test]
    fn unroutable_harness_yields_empty_overlay() {
        let h = by_id("pi-acp").unwrap();
        assert!(!h.is_routable());
        assert_eq!(
            h.routing_overlay("http://x:1", "t", None),
            RoutingOverlay::default()
        );
    }

    #[test]
    fn resolve_gateway_auth_precedence() {
        // Real key wins.
        assert_eq!(
            resolve_gateway_auth(Some("brk_x".into()), false).as_deref(),
            Some("brk_x")
        );
        // No key, auth off → placeholder.
        assert_eq!(
            resolve_gateway_auth(None, false).as_deref(),
            Some(PLACEHOLDER_API_KEY)
        );
        // No key, auth required → None (caller fails fast).
        assert_eq!(resolve_gateway_auth(None, true), None);
        // Real key satisfies required auth.
        assert_eq!(
            resolve_gateway_auth(Some("brk_x".into()), true).as_deref(),
            Some("brk_x")
        );
    }
}