bitrouter 1.0.0-alpha.29

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
//! The session surface of the shared actions.
//!
//! Lives in `crate::actions`, not `crate::chat`: deciding what a session offers
//! reads the `ACTIONS` table and what the controller advertised, and the chat
//! guard keeps `chat/` from naming anything daemon-wide. The driver is *handed*
//! the finished list and names nothing else — the same move `route_control`
//! already makes.

use std::path::PathBuf;
use std::sync::Arc;

use bitrouter_mcp::actions::models::ModelsQuery;
use bitrouter_mcp::actions::route::{RouteInput, RouteQuery};
use bitrouter_mcp::actions::status::StatusQuery;
use bitrouter_mcp::actions::{ACTIONS, Requires};
use bitrouter_mcp::backend::CallerAuth;
use bitrouter_mcp::error::ToolError;
use bitrouter_sdk::acp::client::{AcpClient, RouteMethod};
use bitrouter_tui::machine::Command;

use crate::output::CliReport;
use crate::paths::ConfigSource;

/// What `/route` says at a session with no route surface to open a picker over.
const NOT_ROUTABLE: &str = "this session cannot be rerouted (the controller advertises no route \
                            control: running direct, or without a trusted local daemon binding)";
/// What `/route reset` says at the same session. Distinct from [`NOT_ROUTABLE`]
/// because a controller may advertise `set` without `reset`, and a reader told
/// "cannot be rerouted" would not know which of the two they had.
const NOT_RESETTABLE: &str = "this session has no route lease to drop (the controller advertises \
                              no route reset)";

/// One line of help per row, for `/commands`.
///
/// App-side rather than on the row because no other surface reads it: the MCP
/// tool has its own description and the CLI leaf has clap's. A guard fails a
/// row that carries a `tui_command` and has no arm here, so this cannot fall
/// behind the table.
pub fn summary_for(action: &str) -> &'static str {
    match action {
        "status" => "whether the daemon is up, and what it has spent",
        "list_models" => "the models this config can route to, optionally by provider",
        "route" => "show where a model would be routed, without sending anything",
        "commands" => "list the commands this session offers",
        "route_set" => "choose the route for the rest of the session",
        "route_reset" => "drop the route lease, so the daemon's default applies",
        _ => "",
    }
}

/// The `ACTIONS` rows that carry a `tui_command`, in table order, with each
/// row's requirement resolved against what this controller advertised.
///
/// Resolved once, at launch, and handed to the reducer as plain data. A row
/// whose requirement is unmet is still returned — with the reason — because a
/// control the session cannot run should say why rather than vanish.
pub fn offered_commands(client: &AcpClient) -> Vec<Command> {
    let capability = client.route_control();
    ACTIONS
        .iter()
        .filter_map(|row| {
            let name = row.tui_command?;
            let unavailable = match (row.requires, row.id) {
                (Requires::Nothing, _) => None,
                // `reset` is advertised separately from `list`/`set`, so it is
                // asked about separately.
                (Requires::Binding, "route_reset") => {
                    (!capability.allows(RouteMethod::Reset)).then_some(NOT_RESETTABLE)
                }
                // The picker lists with one method and sets with another, so
                // both must be there for it to be worth opening.
                (Requires::Binding, _) => (!(capability.allows(RouteMethod::List)
                    && capability.allows(RouteMethod::Set)))
                .then_some(NOT_ROUTABLE),
            };
            Some(Command {
                name,
                action: row.id,
                summary: summary_for(row.id),
                unavailable,
            })
        })
        .collect()
}

/// What a session offers, and what answers it.
///
/// One value rather than three parameters: both chat loops need all three, and
/// threading them separately pushed three signatures past the argument count
/// clippy accepts. Bundling them says the true thing anyway — these are one
/// concept, the session's command surface.
pub struct SessionSurface<'a> {
    /// BitRouter's own commands. Empty until the controller has been asked:
    /// [`offered_commands`] needs a live client, so the piped path fills this
    /// in once its session is open.
    pub commands: Vec<Command>,
    /// The user's prompt-expansion commands, resolved from config at launch.
    pub prompt_commands: Vec<bitrouter_tui::machine::PromptCommand>,
    /// The ports a read command is answered through.
    pub ports: &'a SessionPorts,
}

/// The session's view of the shared actions: the same ports the stdio MCP
/// profile is built from, handed to the chat driver as one value.
///
/// Not a new trait. The four port traits already exist and the MCP profile is
/// already assembled by bundling `Arc<dyn _>` of them; the session is the same
/// bundle with a third consumer. A second implementation of an action would
/// therefore have to be a second `impl StatusQuery`, which is the point — the
/// CLI leaf, the MCP tool and the slash command cannot answer differently
/// because there is only one thing for them to ask.
pub struct SessionPorts {
    status: Arc<dyn StatusQuery>,
    models: Arc<dyn ModelsQuery>,
    route: Arc<dyn RouteQuery>,
}

impl SessionPorts {
    /// The same three constructors `bitrouter status`, `bitrouter models` and
    /// `bitrouter route` call, with the same arguments.
    pub fn open(source: ConfigSource, socket: PathBuf) -> Self {
        Self {
            status: Arc::new(crate::actions::status::DaemonStatus::new(
                socket.clone(),
                Some(source.clone()),
            )),
            models: Arc::new(crate::actions::models::RoutableModels::new(
                source.clone(),
                Some(socket.clone()),
            )),
            route: Arc::new(crate::actions::route::RouteAction::new(
                source,
                Some(socket),
            )),
        }
    }

    /// Resolve one row id and its arguments to a report.
    ///
    /// The only place a slash command becomes a port call. The reducer emits
    /// only ids the app gave it, so an unknown id here is a bug in the list the
    /// app built — reported as an error rather than a panic, because a mistyped
    /// table should not take the session down.
    pub async fn run(
        &self,
        action: &str,
        args: &[String],
    ) -> Result<Box<dyn CliReport>, ToolError> {
        // Local and single-tenant, exactly as the stdio MCP profile: the local
        // implementations document that they ignore the caller.
        let caller = CallerAuth::default();
        match action {
            "status" => {
                // Nothing to take, so what was typed is refused rather than
                // silently dropped.
                if !args.is_empty() {
                    return Err(ToolError::new("usage: /status"));
                }
                Ok(Box::new(self.status.status(&caller).await?))
            }
            // The filter is applied to the report, not asked of the port —
            // the same `filtered` the CLI leaf calls, so both surfaces mean
            // the same thing by "declared by this provider".
            "list_models" => Ok(Box::new(
                self.models
                    .list_models(&caller)
                    .await?
                    .filtered(args.first().map(String::as_str)),
            )),
            "route" => {
                let Some(model) = args.first() else {
                    return Err(ToolError::new("usage: /preview <model>"));
                };
                Ok(Box::new(
                    self.route
                        .route(RouteInput {
                            model: model.clone(),
                            prompt: None,
                        })
                        .await?,
                ))
            }
            other => Err(ToolError::new(format!("no session action `{other}`"))),
        }
    }
}

/// The user's prompt-expansion commands, or an error naming the first one that
/// collides with a command BitRouter answers.
///
/// **This is what lets the guards over `ACTIONS` stay exhaustive.** They are
/// silent about this registry, which is correct only if the two sets cannot
/// overlap — so the overlap is refused here, once, when the config loads,
/// rather than resolved by a precedence rule at every keystroke.
///
/// It cannot live in the SDK: the check needs `ACTIONS`, and `bitrouter-mcp`
/// depends on `bitrouter-sdk`, not the reverse.
pub fn prompt_commands(
    config: &bitrouter_sdk::config::ChatConfig,
) -> anyhow::Result<Vec<bitrouter_tui::machine::PromptCommand>> {
    let mut seen: Vec<&str> = Vec::new();
    let mut commands = Vec::with_capacity(config.commands.len());
    for command in &config.commands {
        let name = command.name.trim();
        anyhow::ensure!(
            !name.is_empty(),
            "a `chat.commands` entry has an empty name"
        );
        anyhow::ensure!(
            !name.contains(char::is_whitespace),
            "`chat.commands` name `{name}` contains whitespace; a command is one word"
        );
        // The resolver strips one slash before matching, so a name stored with
        // its slash could never be reached — it would go to the agent as a
        // prompt and be listed as `//name`. Refused rather than left silent.
        anyhow::ensure!(
            !name.starts_with('/'),
            "`chat.commands` name `{name}` starts with a slash; write it as \
             `{}` — the slash is how it is typed, not part of the name",
            name.trim_start_matches('/')
        );
        if let Some(row) = ACTIONS.iter().find(|row| row.tui_command == Some(name)) {
            anyhow::bail!(
                "`chat.commands` defines `/{name}`, which is BitRouter's own `{}` command. \
                 Rename it: a config command may not shadow one that reaches BitRouter's ports",
                row.id
            );
        }
        if let Some((alias, target)) = bitrouter_tui::machine::ALIASES
            .iter()
            .find(|(alias, _)| *alias == name)
        {
            anyhow::bail!(
                "`chat.commands` defines `/{alias}`, which is BitRouter's alias for \
                 `/{target}`. Rename it"
            );
        }
        anyhow::ensure!(
            !seen.contains(&name),
            "`chat.commands` defines `/{name}` twice"
        );
        seen.push(name);
        commands.push(bitrouter_tui::machine::PromptCommand {
            name: name.to_string(),
            description: command.description.clone(),
            template: command.prompt.clone(),
        });
    }
    Ok(commands)
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::*;
    use crate::actions::status::DaemonStatus;

    /// Write `yaml` as a `bitrouter.yaml` in a fresh temp dir and return the
    /// source pointing at it.
    fn config_source(dir: &Path, yaml: &str) -> ConfigSource {
        let path = dir.join("bitrouter.yaml");
        std::fs::write(&path, yaml).expect("write config");
        ConfigSource::File(path)
    }

    /// One active provider declaring one model.
    const ONE_MODEL: &str = r#"
providers:
  demo:
    api_base: https://api.example.test
    api_key: sk-test
    active: true
    models:
      - id: demo-model
"#;

    /// A config command may not take a name BitRouter answers.
    ///
    /// This is the check that lets the guards over `ACTIONS` stay exhaustive:
    /// they are silent about the open registry, which is only correct because
    /// the two sets cannot overlap.
    #[test]
    fn a_config_command_may_not_shadow_a_bitrouter_one() {
        use bitrouter_sdk::config::{ChatConfig, PromptCommandConfig};

        let entry = |name: &str| PromptCommandConfig {
            name: name.to_string(),
            description: String::new(),
            prompt: "x".to_string(),
        };
        let commands = |names: &[&str]| ChatConfig {
            commands: names.iter().map(|name| entry(name)).collect(),
            ..Default::default()
        };

        let ok = prompt_commands(&commands(&["review", "ship"])).expect("no clash");
        assert_eq!(ok.len(), 2);

        // Every row that carries a `tui_command` is refused by that name.
        for taken in ["status", "models", "preview", "commands", "route"] {
            let error = prompt_commands(&commands(&[taken]))
                .expect_err(&format!("`{taken}` is BitRouter's"));
            assert!(format!("{error}").contains(taken), "{error}");
        }
        // And so is an alias.
        let error = prompt_commands(&commands(&["help"])).expect_err("`help` is an alias");
        assert!(format!("{error}").contains("alias"), "{error}");

        // A duplicate would make one of the two unreachable.
        let error = prompt_commands(&commands(&["dup", "dup"])).expect_err("duplicate");
        assert!(format!("{error}").contains("twice"), "{error}");

        // A name with a space could never be typed as one word.
        let error = prompt_commands(&commands(&["two words"])).expect_err("whitespace");
        assert!(format!("{error}").contains("one word"), "{error}");
    }

    /// The third surface answers with the second's bytes.
    ///
    /// `bitrouter status` constructs `DaemonStatus` and calls `report()`;
    /// `/status` goes through `SessionPorts`. This holds `open` to constructing
    /// the action the leaf constructs, from the same source and the same
    /// socket — a mismatch shows up as a different `socket` in the report.
    ///
    /// What it does not catch is a live-daemon divergence: no daemon runs under
    /// test, which is the same limit `both_surfaces_produce_the_same_report`
    /// has. A shared type stops the shapes diverging, not the contents.
    #[tokio::test]
    async fn the_session_surface_answers_with_the_cli_leafs_bytes() {
        let dir = tempfile::tempdir().expect("tempdir");
        let source = config_source(dir.path(), ONE_MODEL);
        let socket = dir.path().join("bitrouter.sock");

        let leaf = DaemonStatus::new(socket.clone(), Some(source.clone()))
            .report()
            .await
            .expect("cli surface");
        let ports = SessionPorts::open(source, socket);
        let session = ports.run("status", &[]).await.expect("session surface");

        assert_eq!(
            serde_json::to_value(&leaf).expect("leaf json"),
            serde_json::to_value(session.as_ref()).expect("session json"),
            "the session surface must answer with the leaf's bytes"
        );
    }

    /// And it reaches the screen as the CLI's own plain rendering — the same
    /// renderer, with the palette off, so there is one human view of a report
    /// rather than one per surface.
    #[tokio::test]
    async fn the_session_surface_renders_what_the_cli_renders() {
        let dir = tempfile::tempdir().expect("tempdir");
        let source = config_source(dir.path(), ONE_MODEL);
        let socket = dir.path().join("bitrouter.sock");

        let leaf = DaemonStatus::new(socket.clone(), Some(source.clone()))
            .report()
            .await
            .expect("cli surface");
        let ports = SessionPorts::open(source, socket);
        let session = ports.run("status", &[]).await.expect("session surface");

        let human = crate::output::Output::new(crate::output::Format::Human);
        let expected = human.render_to_vec(&leaf);
        assert_eq!(
            human.render_to_vec(session.as_ref()),
            expected,
            "the notice's bytes are the CLI's plain rendering of the same report"
        );
        assert!(
            !expected.is_empty(),
            "a report that renders to nothing would make this test vacuous"
        );
    }

    /// `/models` answers with what `bitrouter models --provider` answers,
    /// filter included — the filter is the report's, so both surfaces read
    /// "declared by this provider" the same way.
    #[tokio::test]
    async fn the_models_surface_answers_with_the_cli_leafs_bytes() {
        let dir = tempfile::tempdir().expect("tempdir");
        let source = config_source(dir.path(), ONE_MODEL);
        let socket = dir.path().join("bitrouter.sock");

        let leaf =
            crate::actions::models::RoutableModels::new(source.clone(), Some(socket.clone()))
                .report()
                .await
                .expect("cli surface")
                .filtered(Some("demo"));
        let ports = SessionPorts::open(source, socket);
        let session = ports
            .run("list_models", &["demo".to_string()])
            .await
            .expect("session surface");

        assert_eq!(
            serde_json::to_value(&leaf).expect("leaf json"),
            serde_json::to_value(session.as_ref()).expect("session json"),
        );
        assert!(!leaf.models.is_empty(), "the fixture declares one model");
    }

    /// `/preview <model>` answers with what `bitrouter route <model>` answers.
    #[tokio::test]
    async fn the_preview_surface_answers_with_the_cli_leafs_bytes() {
        let dir = tempfile::tempdir().expect("tempdir");
        let source = config_source(dir.path(), ONE_MODEL);
        let socket = dir.path().join("bitrouter.sock");

        let leaf = crate::actions::route::RouteAction::new(source.clone(), Some(socket.clone()))
            .report(RouteInput {
                model: "demo-model".to_string(),
                prompt: None,
            })
            .await
            .expect("cli surface");
        let ports = SessionPorts::open(source, socket);
        let session = ports
            .run("route", &["demo-model".to_string()])
            .await
            .expect("session surface");

        assert_eq!(
            serde_json::to_value(&leaf).expect("leaf json"),
            serde_json::to_value(session.as_ref()).expect("session json"),
        );
    }

    /// `/preview` with nothing to preview says how to use it. A missing
    /// argument is a typo, not a crash.
    #[tokio::test]
    async fn preview_without_a_model_answers_with_its_usage() {
        let dir = tempfile::tempdir().expect("tempdir");
        let ports = SessionPorts::open(
            config_source(dir.path(), ONE_MODEL),
            dir.path().join("bitrouter.sock"),
        );
        match ports.run("route", &[]).await {
            Ok(_) => panic!("a model is required"),
            Err(error) => assert!(format!("{error}").contains("usage: /preview"), "{error}"),
        }
    }

    /// An id the table does not carry is an error, not a panic: a mistyped
    /// command list must not take the session down.
    #[tokio::test]
    async fn an_unknown_action_is_reported_rather_than_panicking() {
        let dir = tempfile::tempdir().expect("tempdir");
        let source = config_source(dir.path(), ONE_MODEL);
        let ports = SessionPorts::open(source, dir.path().join("bitrouter.sock"));
        // `Box<dyn CliReport>` is not `Debug`, so this cannot be `expect_err`.
        match ports.run("not_a_row", &[]).await {
            Ok(_) => panic!("an unknown id must not resolve to a report"),
            Err(error) => assert!(format!("{error}").contains("not_a_row"), "{error}"),
        }
    }
}