bitrouter 1.0.0-alpha.30

BitRouter: an LLM API router. CLI + assembly library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Reports for the daemon-lifecycle (`start` / `stop` / `restart` / `reload` /
//! `status`) and `route` commands.

use bitrouter_mcp::actions::route::{ResolvedVia, RouteReport};
use bitrouter_mcp::actions::status::StatusReport;
use serde::Serialize;

use crate::output::CliReport;
use crate::output::human::{Health, Human};

/// Result of a daemon lifecycle action (`start` / `stop` / `restart` /
/// `reload`). `pid`/`listen`/`models`/`log` are present only when the action
/// produced a live daemon (start / restart).
#[derive(Serialize)]
pub struct DaemonActionReport {
    /// The action performed: `start` | `stop` | `restart` | `reload`.
    pub action: &'static str,
    /// The resulting state: `started` | `stopped` | `restarted` | `reloaded` |
    /// `not_ready`.
    pub status: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub listen: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub models: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub log: Option<String>,
}

impl DaemonActionReport {
    /// A daemon came up and answered its control socket.
    pub fn started(
        action: &'static str,
        status: &'static str,
        pid: u32,
        listen: String,
        models: usize,
        log: String,
    ) -> Self {
        Self {
            action,
            status,
            pid: Some(pid),
            listen: Some(listen),
            models: Some(models),
            log: Some(log),
        }
    }

    /// The daemon is alive but slow to answer (still migrating / fetching).
    pub fn not_ready(action: &'static str, pid: u32, log: String) -> Self {
        Self {
            action,
            status: "not_ready",
            pid: Some(pid),
            listen: None,
            models: None,
            log: Some(log),
        }
    }

    /// A payload-less outcome (stop / reload).
    pub fn simple(action: &'static str, status: &'static str) -> Self {
        Self {
            action,
            status,
            pid: None,
            listen: None,
            models: None,
            log: None,
        }
    }
}

impl CliReport for DaemonActionReport {
    fn render(&self, h: &mut Human<'_>) -> std::io::Result<()> {
        match self.pid {
            Some(pid) => {
                let health = if self.status == "not_ready" {
                    Health::Unknown
                } else {
                    Health::Up
                };
                h.status_block(health, &format!("bitrouter daemon {}", self.status))?;
                h.field("pid", pid)?;
                if let Some(listen) = &self.listen {
                    h.field("listen", listen)?;
                }
                if let Some(models) = self.models {
                    h.field("models", format!("{models} routable"))?;
                }
                if let Some(log) = &self.log {
                    h.field("log", log)?;
                }
                Ok(())
            }
            None => h.line(&format!("daemon {}", self.status)),
        }
    }
}

/// The human view of `bitrouter status`. Exit code stays 0 whether running or
/// stopped — "stopped" is an answer, not a failure.
///
/// The report type itself is
/// [`bitrouter_mcp::actions::status::StatusReport`]: the `status`
/// tool returns the same type, so `bitrouter status --json` and the tool's
/// structured content are the same bytes. Rendering stays here — a local trait
/// on a foreign type is legal, and it keeps [`Human`] out of the crate.
impl CliReport for StatusReport {
    fn render(&self, h: &mut Human<'_>) -> std::io::Result<()> {
        if !self.running {
            h.status_block(Health::Down, "bitrouter is stopped")?;
            if let Some(socket) = &self.socket {
                h.field("socket", socket)?;
            }
            // Spend outlives the daemon: what a past daemon spent is on disk
            // and stays true after it exits, so it is shown here too.
            render_spend(self.spend.as_ref(), h)?;
            return h.note("Run `bitrouter start` to launch the daemon.");
        }
        h.status_block(Health::Up, "bitrouter is running")?;
        if let Some(pid) = self.pid {
            h.field("pid", pid)?;
        }
        if let Some(listen) = &self.listen {
            h.field("listen", listen)?;
        }
        if let Some(models) = self.models {
            h.field("models", format!("{models} routable"))?;
        }
        if !self.providers.is_empty() {
            h.field("providers", self.providers.join(", "))?;
        }
        if let Some(socket) = &self.socket {
            h.field("socket", socket)?;
        }
        render_spend(self.spend.as_ref(), h)
    }
}

/// The `spend` block of [`StatusReport`], in the human view.
///
/// Two lines at most, because they are two independent facts: `spend` is money
/// already gone, `credits` is what a capped deployment will still let you
/// spend. A deployment that answers only one prints only one.
///
/// `unpriced` is never rounded away or averaged in. When some requests in the
/// window carried no charge evidence the total is labelled a **floor** and the
/// count is shown, because the one place being wrong about this costs the
/// reader money is exactly here.
fn render_spend(
    spend: Option<&bitrouter_mcp::actions::status::Spend>,
    h: &mut Human<'_>,
) -> std::io::Result<()> {
    let Some(spend) = spend else {
        return Ok(());
    };
    if let Some(spent) = &spend.spent {
        let amount = crate::metering::fmt_usd(spent.estimated_micro_usd);
        let line = match spent.unpriced {
            0 => format!("{amount} {} ({} requests)", spent.window, spent.requests),
            unpriced => format!(
                "{amount}+ {} ({} requests, {unpriced} unpriced — floor, not a total)",
                spent.window, spent.requests
            ),
        };
        h.field("spend", line)?;
    }
    if let Some(limit) = &spend.limit {
        // Not `metering::fmt_usd`: that takes an unsigned amount and hard-
        // codes a `$`, neither of which holds for a signed balance in a
        // currency the account declares.
        h.field(
            "credits",
            format!(
                "{:.2} {} remaining",
                limit.remaining_micro_usd as f64 / 1_000_000.0,
                spend.currency
            ),
        )?;
    }
    Ok(())
}

/// Human rendering for the shared `route` report.
///
/// The type itself lives in `bitrouter-mcp` so the MCP tool can return it;
/// `Human` stays here, app-side, which is what keeps the CLI's presentation
/// vocabulary out of the crate.
impl CliReport for RouteReport {
    fn render(&self, h: &mut Human<'_>) -> std::io::Result<()> {
        // The wire words, so the human view and `--json` name the path the
        // same way.
        let via = match self.resolved_via {
            ResolvedVia::Live => "live",
            ResolvedVia::Config => "config",
            ResolvedVia::ZeroConfig => "zero_config",
        };
        h.line(&format!(
            "model: {}  (resolved via: {via})",
            self.requested_model
        ))?;
        // Only worth a line when the policy table moved the request: an
        // unchanged model with no effort is what the reader already assumed.
        if self.effective_model != self.requested_model || self.effective_effort.is_some() {
            let effort = match self.effective_effort {
                Some(effort) => format!("  (effort: {effort})"),
                None => String::new(),
            };
            h.line(&format!("  policy → {}{effort}", self.effective_model))?;
        }
        if self.provider_chain.is_empty() {
            return h.line("  (empty chain — no provider declares this model)");
        }
        for (i, hop) in self.provider_chain.iter().enumerate() {
            h.line(&format!(
                "  {}. {} → {} ({})",
                i + 1,
                hop.provider,
                hop.service_id,
                hop.api_protocol
            ))?;
        }
        if let Some(cost) = &self.estimated_cost {
            // Rates, not a total: nothing was sent, so there is nothing to
            // multiply by. The bracket count is the honest warning that the
            // base rates are not the whole story for this model.
            h.line(&format!(
                "  rates: in {} / out {} µUSD per token{}",
                rate(cost.input_micro_usd_per_token),
                rate(cost.output_micro_usd_per_token),
                match cost.context_tiers.len() {
                    0 => String::new(),
                    n => format!(" (+{n} long-context bracket(s))"),
                }
            ))?;
        }
        Ok(())
    }
}

/// A per-token rate, or `?` where the registry prices nothing.
fn rate(value: Option<f64>) -> String {
    match value {
        Some(v) => format!("{v}"),
        None => "?".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::output::{Format, Output};

    fn json(r: &dyn CliReport) -> serde_json::Value {
        serde_json::from_slice(&Output::new(Format::Json).render_to_vec(r)).unwrap()
    }

    use bitrouter_mcp::actions::status::{Spend, SpendLimit, Spent};

    /// What the local path builds: the `spent` half only.
    fn local_spend(estimated_micro_usd: u64, requests: u64, unpriced: u64) -> Spend {
        Spend {
            currency: "USD".into(),
            spent: Some(Spent {
                window: "today".into(),
                estimated_micro_usd,
                requests,
                unpriced,
            }),
            limit: None,
        }
    }

    #[test]
    fn status_running_json_and_human() {
        let r = StatusReport::running(
            7,
            "127.0.0.1:4356".into(),
            42,
            vec!["anthropic".into(), "openai".into()],
            "/x.sock".into(),
            Some(local_spend(1_230_000, 9, 0)),
        );
        assert_eq!(
            json(&r),
            serde_json::json!({
                "running": true, "pid": 7, "listen": "127.0.0.1:4356", "models": 42,
                "providers": ["anthropic", "openai"], "socket": "/x.sock",
                "spend": {
                    "currency": "USD",
                    "spent": {
                        "window": "today", "estimated_micro_usd": 1_230_000,
                        "requests": 9, "unpriced": 0
                    }
                }
            })
        );
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert!(h.contains("● bitrouter is running"), "{h:?}");
        assert!(h.contains("  models    42 routable"), "{h:?}");
        assert!(h.contains("anthropic, openai"), "{h:?}");
        assert!(h.contains("$1.23 today (9 requests)"), "{h:?}");
    }

    /// The invariant that costs money to get wrong: a partial figure must
    /// never read like a total. `unpriced` reaches JSON verbatim and the human
    /// view marks the number a floor.
    #[test]
    fn status_spend_never_hides_unpriced_requests() {
        let r = StatusReport::running(
            7,
            "127.0.0.1:4356".into(),
            1,
            vec!["openai".into()],
            "/x.sock".into(),
            Some(local_spend(500_000, 10, 4)),
        );
        assert_eq!(json(&r)["spend"]["spent"]["unpriced"], 4);
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert!(h.contains("4 unpriced"), "{h:?}");
        assert!(h.contains("floor, not a total"), "{h:?}");
    }

    /// Spend is not a liveness fact. The metering database records what a past
    /// daemon spent and reads fine with nothing listening, so a stopped report
    /// still answers "am I OK to spend?".
    #[test]
    fn status_stopped_still_reports_spend() {
        let r = StatusReport::stopped("/x.sock".into(), Some(local_spend(0, 0, 0)));
        assert_eq!(
            json(&r),
            serde_json::json!({
                "running": false, "providers": [], "socket": "/x.sock",
                "spend": {
                    "currency": "USD",
                    "spent": {
                        "window": "today", "estimated_micro_usd": 0,
                        "requests": 0, "unpriced": 0
                    }
                }
            })
        );
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert!(h.contains("○ bitrouter is stopped"), "{h:?}");
        assert!(h.contains("$0.00 today (0 requests)"), "{h:?}");
    }

    #[test]
    fn status_stopped_omits_optional_fields() {
        let r = StatusReport::stopped("/x.sock".into(), None);
        assert_eq!(
            json(&r),
            serde_json::json!({"running": false, "providers": [], "socket": "/x.sock"})
        );
    }

    /// The cloud half: a cap with no spend-to-date. The two halves render
    /// independently, so a report carrying only `limit` prints only `credits`.
    #[test]
    fn status_renders_a_limit_without_a_spent_figure() {
        let r = StatusReport::metered(Spend {
            currency: "USD".into(),
            spent: None,
            limit: Some(SpendLimit {
                balance_micro_usd: 5_000_000,
                pending_micro_usd: 769_000,
                remaining_micro_usd: 4_231_000,
            }),
        });
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert!(h.contains("credits   4.23 USD remaining"), "{h:?}");
        assert!(!h.contains("spend"), "{h:?}");
    }

    /// The whole point of the shared type: what the CLI prints is what the MCP
    /// tool returns, so the tool's structured content deserializes straight
    /// back into the report the CLI emitted.
    #[test]
    fn status_json_round_trips_through_the_shared_type() {
        let r = StatusReport::running(
            7,
            "127.0.0.1:4356".into(),
            42,
            vec!["openai".into()],
            "/x.sock".into(),
            Some(local_spend(42, 1, 1)),
        );
        let back: StatusReport = serde_json::from_value(json(&r)).expect("round trip");
        assert_eq!(serde_json::to_value(&back).unwrap(), json(&r));
    }

    /// An unroutable model is an empty array, not a missing key: a consumer
    /// indexing `provider_chain` must not have to special-case absence.
    #[test]
    fn route_empty_chain_is_empty_array() {
        let r = RouteReport {
            requested_model: "m".into(),
            effective_model: "m".into(),
            effective_effort: None,
            resolved_via: ResolvedVia::Config,
            policy_decision: None,
            provider_chain: vec![],
            estimated_cost: None,
        };
        assert_eq!(json(&r)["provider_chain"], serde_json::json!([]));
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert!(h.contains("no provider declares this model"), "{h}");
    }

    /// The human line has to *say* when the policy table moved the request —
    /// printing only the requested model is how `bitrouter route` used to name
    /// a model the daemon would never pick.
    #[test]
    fn route_human_names_the_effective_model_when_policy_moved_it() {
        use bitrouter_mcp::actions::route::ProviderHop;
        let r = RouteReport {
            requested_model: "small".into(),
            effective_model: "big".into(),
            effective_effort: None,
            resolved_via: ResolvedVia::Config,
            policy_decision: None,
            provider_chain: vec![ProviderHop {
                provider: "demo".into(),
                service_id: "big".into(),
                api_protocol: "openai".into(),
            }],
            estimated_cost: None,
        };
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert!(h.contains("policy → big"), "{h}");
    }

    /// The whole point of the shared type: what `bitrouter route --json` prints
    /// is what the `route_preview` tool returns, so the tool's structured
    /// content deserializes straight back into the report the CLI emitted —
    /// including the enum wire values, which a rename would silently break.
    ///
    /// The wire values are pinned literally too: `resolved_via` is
    /// `live` / `config` / `zero_config`, the same words `bitrouter models`
    /// uses for the same fact, so an agent never sees `live` from one report
    /// and `live daemon` from the other.
    #[test]
    fn route_json_round_trips_through_the_shared_type() {
        use bitrouter_mcp::actions::route::{ContextTierRates, EstimatedCost, ProviderHop};
        use bitrouter_sdk::language_model::types::ReasoningEffort;
        for (via, wire) in [
            (ResolvedVia::Live, "live"),
            (ResolvedVia::Config, "config"),
            (ResolvedVia::ZeroConfig, "zero_config"),
        ] {
            let r = RouteReport {
                requested_model: "small".into(),
                effective_model: "big".into(),
                effective_effort: Some(ReasoningEffort::High),
                resolved_via: via,
                policy_decision: None,
                provider_chain: vec![ProviderHop {
                    provider: "demo".into(),
                    service_id: "big".into(),
                    api_protocol: "openai".into(),
                }],
                estimated_cost: Some(EstimatedCost::new(
                    Some(1.0),
                    Some(2.0),
                    vec![ContextTierRates {
                        above_input_tokens: 200_000,
                        input_micro_usd_per_token: Some(2.0),
                        output_micro_usd_per_token: Some(4.0),
                    }],
                )),
            };
            let emitted = json(&r);
            assert_eq!(emitted["resolved_via"], wire, "{via:?}");
            let back: RouteReport = serde_json::from_value(emitted.clone()).expect("round trip");
            assert_eq!(serde_json::to_value(&back).unwrap(), emitted);
            // The context tiers survive the trip: dropping them would report a
            // long-context model at its cheapest bracket.
            assert_eq!(
                emitted["estimated_cost"]["context_tiers"][0]["above_input_tokens"],
                200_000
            );
        }
    }

    #[test]
    fn daemon_action_simple_one_liner() {
        let r = DaemonActionReport::simple("stop", "stopped");
        assert_eq!(
            json(&r),
            serde_json::json!({"action": "stop", "status": "stopped"})
        );
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert_eq!(h, "daemon stopped\n");
    }
}