bitrouter-providers 0.27.2

BitRouter provider adapters — HTTP client, auth, streaming
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
//! Routing shim installer.
//!
//! Generates a small wrapper script at `<shim_dir>/<agent>` (Unix) or
//! `<shim_dir>/<agent>.cmd` (Windows). The shim probes BitRouter health,
//! sets the agent-specific `*_BASE_URL` if reachable, then `exec`s the
//! real binary. When BitRouter is down, the shim falls through to the
//! real binary unchanged — no broken state.
//!
//! Shims are marked with [`SHIM_MARKER`]; install/uninstall refuse to
//! touch a file at the target path that lacks the marker.

use std::net::SocketAddr;
use std::path::{Path, PathBuf};

/// Marker line embedded in every shim. Used to recognise our own files
/// during refresh and uninstall.
pub const SHIM_MARKER: &str = "# bitrouter-shim:v1";

/// Marker for the Windows `.cmd` flavour. Cmd uses `::` for comments,
/// not `#`, so the marker line is different in form but serves the
/// same role.
pub const SHIM_MARKER_WINDOWS: &str = ":: bitrouter-shim:v1";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Platform {
    Unix,
    Windows,
}

impl Platform {
    pub fn current() -> Self {
        if cfg!(windows) {
            Self::Windows
        } else {
            Self::Unix
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShimAction {
    Created,
    Updated,
    SkippedConflict,
}

#[derive(Debug)]
pub struct ShimEnv {
    pub var: String,
    pub value: String,
}

/// Map an agent id to the `*_BASE_URL` it consumes. Returns `None` for
/// agents we don't have a mapping for — caller should skip rather than
/// guess, since installing a shim that doesn't set anything useful is
/// only blast radius without benefit.
pub fn shim_env_for(agent_id: &str, listen: SocketAddr) -> Option<ShimEnv> {
    let base = format!("http://{listen}");
    let (var, value) = match agent_id {
        "claude" | "claude-acp" | "claude-code-acp" => ("ANTHROPIC_BASE_URL", format!("{base}/v1")),
        "codex" | "codex-acp" => ("OPENAI_BASE_URL", format!("{base}/v1")),
        "gemini" | "gemini-acp" => ("GOOGLE_AI_BASE_URL", format!("{base}/v1beta")),
        _ => return None,
    };
    Some(ShimEnv {
        var: var.to_owned(),
        value,
    })
}

/// Where the shim file lives for a given agent name on the given platform.
pub fn shim_path_for(platform: Platform, shim_dir: &Path, name: &str) -> PathBuf {
    match platform {
        Platform::Unix => shim_dir.join(name),
        Platform::Windows => shim_dir.join(format!("{name}.cmd")),
    }
}

/// Render the shim script body. Pure string; testable on any host.
pub fn render_shim(
    platform: Platform,
    real_binary: &Path,
    listen: SocketAddr,
    env: &ShimEnv,
) -> String {
    match platform {
        Platform::Unix => render_unix_shim(real_binary, listen, env),
        Platform::Windows => render_windows_shim(real_binary, listen, env),
    }
}

fn render_unix_shim(real_binary: &Path, listen: SocketAddr, env: &ShimEnv) -> String {
    let real = shell_single_quote(&real_binary.display().to_string());
    let value = shell_single_quote(&env.value);
    format!(
        "#!/usr/bin/env bash\n\
         {SHIM_MARKER}\n\
         # Auto-generated by `bitrouter init`. Probes BitRouter health and\n\
         # routes through it when reachable; otherwise falls through to the\n\
         # real binary so the command keeps working.\n\
         REAL={real}\n\
         LISTEN={listen}\n\
         if curl -fsS --max-time 1 \"http://${{LISTEN}}/health\" >/dev/null 2>&1; then\n\
         \x20   export {var}={value}\n\
         fi\n\
         exec \"$REAL\" \"$@\"\n",
        var = env.var,
    )
}

fn render_windows_shim(real_binary: &Path, listen: SocketAddr, env: &ShimEnv) -> String {
    format!(
        "@echo off\r\n\
         {SHIM_MARKER_WINDOWS}\r\n\
         :: Auto-generated by `bitrouter init`. Probes BitRouter health and\r\n\
         :: routes through it when reachable; otherwise falls through to the\r\n\
         :: real binary so the command keeps working.\r\n\
         setlocal\r\n\
         set \"REAL={real}\"\r\n\
         set \"LISTEN={listen}\"\r\n\
         curl.exe -fsS --max-time 1 \"http://%LISTEN%/health\" >nul 2>&1\r\n\
         if %ERRORLEVEL% EQU 0 set \"{var}={value}\"\r\n\
         \"%REAL%\" %*\r\n\
         exit /b %ERRORLEVEL%\r\n",
        real = real_binary.display(),
        var = env.var,
        value = env.value,
    )
}

/// Single-quote a string for safe interpolation into a bash script.
fn shell_single_quote(s: &str) -> String {
    let escaped = s.replace('\'', r"'\''");
    format!("'{escaped}'")
}

/// Install (or refresh) a shim. Returns [`ShimAction::SkippedConflict`]
/// if a non-bitrouter file already exists at `shim_path` — the caller
/// can surface this to the user rather than blowing the file away.
pub fn install_shim(
    platform: Platform,
    shim_path: &Path,
    real_binary: &Path,
    listen: SocketAddr,
    env: &ShimEnv,
) -> Result<ShimAction, String> {
    if let Some(parent) = shim_path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?;
    }

    let action = match std::fs::read_to_string(shim_path) {
        Ok(existing) if is_bitrouter_shim(&existing) => ShimAction::Updated,
        Ok(_) => return Ok(ShimAction::SkippedConflict),
        Err(_) => ShimAction::Created,
    };

    let body = render_shim(platform, real_binary, listen, env);
    std::fs::write(shim_path, body).map_err(|e| format!("write {}: {e}", shim_path.display()))?;

    if matches!(platform, Platform::Unix) {
        chmod_executable(shim_path)?;
    }

    Ok(action)
}

#[cfg(unix)]
fn chmod_executable(path: &Path) -> Result<(), String> {
    use std::os::unix::fs::PermissionsExt;
    let mut perms = std::fs::metadata(path)
        .map_err(|e| format!("stat shim: {e}"))?
        .permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(path, perms).map_err(|e| format!("chmod shim: {e}"))?;
    Ok(())
}

#[cfg(not(unix))]
fn chmod_executable(_path: &Path) -> Result<(), String> {
    // .cmd files are executable by extension via PATHEXT — no mode bit
    // to set on Windows.
    Ok(())
}

/// Remove a shim, but only if it carries our marker. Returns true if a
/// bitrouter shim was removed; false if absent or hand-written by the
/// user.
pub fn uninstall_shim(shim_path: &Path) -> Result<bool, String> {
    let Ok(existing) = std::fs::read_to_string(shim_path) else {
        return Ok(false);
    };
    if !is_bitrouter_shim(&existing) {
        return Ok(false);
    }
    std::fs::remove_file(shim_path).map_err(|e| format!("remove shim: {e}"))?;
    Ok(true)
}

/// True if the file at `shim_path` exists and is a bitrouter shim.
pub fn is_installed(shim_path: &Path) -> bool {
    std::fs::read_to_string(shim_path)
        .map(|s| is_bitrouter_shim(&s))
        .unwrap_or(false)
}

fn is_bitrouter_shim(body: &str) -> bool {
    body.contains(SHIM_MARKER) || body.contains(SHIM_MARKER_WINDOWS)
}

/// Resolve the real binary for an agent name on PATH, **excluding**
/// `exclude_dir` (the directory the shim itself lives in). On Windows,
/// also tries each `PATHEXT` suffix so the locator finds `claude.exe`,
/// `claude.cmd`, etc.
pub fn locate_real_binary(name: &str, exclude_dir: &Path) -> Option<PathBuf> {
    let path_var = std::env::var_os("PATH")?;
    let extensions = path_extensions();
    for dir in std::env::split_paths(&path_var) {
        if dir == exclude_dir {
            continue;
        }
        let bare = dir.join(name);
        if bare.is_file() {
            return Some(bare);
        }
        for ext in &extensions {
            let candidate = dir.join(format!("{name}{ext}"));
            if candidate.is_file() {
                return Some(candidate);
            }
        }
    }
    None
}

#[cfg(windows)]
fn path_extensions() -> Vec<String> {
    std::env::var("PATHEXT")
        .unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string())
        .split(';')
        .filter(|s| !s.is_empty())
        .map(|s| s.to_lowercase())
        .collect()
}

#[cfg(not(windows))]
fn path_extensions() -> Vec<String> {
    Vec::new()
}

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

    fn listen() -> SocketAddr {
        "127.0.0.1:8787".parse().expect("static addr parses")
    }

    fn anth_env() -> ShimEnv {
        ShimEnv {
            var: "ANTHROPIC_BASE_URL".to_owned(),
            value: "http://127.0.0.1:8787/v1".to_owned(),
        }
    }

    #[test]
    fn env_mapping_per_agent() {
        let l = listen();
        assert_eq!(
            shim_env_for("claude", l).map(|e| e.var),
            Some("ANTHROPIC_BASE_URL".to_owned())
        );
        assert_eq!(
            shim_env_for("codex", l).map(|e| e.var),
            Some("OPENAI_BASE_URL".to_owned())
        );
        assert_eq!(
            shim_env_for("gemini-acp", l).map(|e| e.var),
            Some("GOOGLE_AI_BASE_URL".to_owned())
        );
        assert!(shim_env_for("unknown-agent", l).is_none());
    }

    #[test]
    fn unix_render_embeds_absolute_real_path_and_marker() {
        let body = render_shim(
            Platform::Unix,
            Path::new("/usr/local/bin/claude"),
            listen(),
            &anth_env(),
        );
        assert!(body.contains(SHIM_MARKER));
        assert!(body.contains("'/usr/local/bin/claude'"));
        assert!(body.contains("export ANTHROPIC_BASE_URL='http://127.0.0.1:8787/v1'"));
        assert!(body.contains("curl -fsS --max-time 1"));
        assert!(body.contains("exec \"$REAL\" \"$@\""));
    }

    #[test]
    fn unix_render_shell_quotes_special_chars() {
        let body = render_shim(
            Platform::Unix,
            Path::new("/path with space/it's/claude"),
            listen(),
            &anth_env(),
        );
        assert!(body.contains(r"'/path with space/it'\''s/claude'"));
    }

    #[test]
    fn windows_render_uses_cmd_idioms() {
        let body = render_shim(
            Platform::Windows,
            Path::new(r"C:\Program Files\Claude\claude.exe"),
            listen(),
            &anth_env(),
        );
        assert!(body.contains("@echo off"));
        assert!(body.contains(SHIM_MARKER_WINDOWS));
        assert!(body.contains("setlocal"));
        assert!(body.contains("curl.exe -fsS --max-time 1"));
        assert!(body.contains(r"C:\Program Files\Claude\claude.exe"));
        assert!(body.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:8787/v1"));
        assert!(body.contains("\r\n"));
        assert!(body.contains("exit /b %ERRORLEVEL%"));
    }

    #[test]
    fn shim_path_extension_matches_platform() {
        let dir = Path::new("/tmp/x");
        assert_eq!(
            shim_path_for(Platform::Unix, dir, "claude"),
            dir.join("claude")
        );
        assert_eq!(
            shim_path_for(Platform::Windows, dir, "claude"),
            dir.join("claude.cmd")
        );
    }

    #[test]
    fn install_creates_executable_shim() -> Result<(), String> {
        let dir = TempDir::new().map_err(|e| e.to_string())?;
        let shim = dir.path().join("claude");
        let action = install_shim(
            Platform::Unix,
            &shim,
            Path::new("/bin/echo"),
            listen(),
            &anth_env(),
        )?;
        assert_eq!(action, ShimAction::Created);
        assert!(shim.exists());
        assert!(is_installed(&shim));

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&shim)
                .map_err(|e| e.to_string())?
                .permissions()
                .mode()
                & 0o777;
            assert_eq!(mode, 0o755);
        }
        Ok(())
    }

    #[test]
    fn install_refreshes_existing_bitrouter_shim() -> Result<(), String> {
        let dir = TempDir::new().map_err(|e| e.to_string())?;
        let shim = dir.path().join("claude");
        install_shim(
            Platform::Unix,
            &shim,
            Path::new("/bin/echo"),
            listen(),
            &anth_env(),
        )?;
        let updated_env = ShimEnv {
            var: "ANTHROPIC_BASE_URL".to_owned(),
            value: "http://127.0.0.1:9999/v1".to_owned(),
        };
        let action = install_shim(
            Platform::Unix,
            &shim,
            Path::new("/bin/echo"),
            listen(),
            &updated_env,
        )?;
        assert_eq!(action, ShimAction::Updated);
        let body = std::fs::read_to_string(&shim).map_err(|e| e.to_string())?;
        assert!(body.contains("http://127.0.0.1:9999/v1"));
        Ok(())
    }

    #[test]
    fn install_refuses_to_clobber_foreign_file() -> Result<(), String> {
        let dir = TempDir::new().map_err(|e| e.to_string())?;
        let shim = dir.path().join("claude");
        std::fs::write(&shim, "#!/bin/sh\necho hand-written\n").map_err(|e| e.to_string())?;
        let action = install_shim(
            Platform::Unix,
            &shim,
            Path::new("/bin/echo"),
            listen(),
            &anth_env(),
        )?;
        assert_eq!(action, ShimAction::SkippedConflict);
        let body = std::fs::read_to_string(&shim).map_err(|e| e.to_string())?;
        assert!(body.contains("hand-written"));
        Ok(())
    }

    #[test]
    fn uninstall_only_removes_marked_shim() -> Result<(), String> {
        let dir = TempDir::new().map_err(|e| e.to_string())?;
        let shim = dir.path().join("claude");

        std::fs::write(&shim, "#!/bin/sh\n").map_err(|e| e.to_string())?;
        assert!(!uninstall_shim(&shim)?);
        assert!(shim.exists());

        // Remove the foreign file so install can write a real shim.
        std::fs::remove_file(&shim).map_err(|e| e.to_string())?;
        install_shim(
            Platform::Unix,
            &shim,
            Path::new("/bin/echo"),
            listen(),
            &anth_env(),
        )?;
        assert!(uninstall_shim(&shim)?);
        assert!(!shim.exists());
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn shim_falls_through_when_bitrouter_unreachable() -> Result<(), String> {
        use std::os::unix::fs::PermissionsExt;
        use std::process::Command;

        let dir = TempDir::new().map_err(|e| e.to_string())?;
        let shim = dir.path().join("claude");

        let real = dir.path().join("real-claude.sh");
        std::fs::write(
            &real,
            "#!/usr/bin/env bash\n\
             if [ -n \"$ANTHROPIC_BASE_URL\" ]; then echo routed; \
             else echo direct; fi\n",
        )
        .map_err(|e| e.to_string())?;
        std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o755))
            .map_err(|e| e.to_string())?;

        // Port 1 — nothing listens here. The shim's curl probe must fail
        // and fall through to the real binary unchanged.
        let dead: SocketAddr = "127.0.0.1:1".parse().expect("static addr parses");
        install_shim(Platform::Unix, &shim, &real, dead, &anth_env())?;

        let out = Command::new(&shim)
            .output()
            .map_err(|e| format!("spawn shim: {e}"))?;
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            stdout.contains("direct"),
            "expected fallback, got: {stdout}"
        );
        Ok(())
    }
}