bitrouter 1.0.0-alpha.34

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
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
//! Assembly of the Code surface's operational ports and session launcher.
//!
//! The interactive loop receives this boundary; configuration and target
//! selection remain here, outside the conversation's state machine.

use std::path::Path;
use std::sync::{Arc, Mutex};

use crate::actions::route::RouteInput;
use anyhow::{Context, Result, bail, ensure};
use bitrouter_tui::machine::PromptCommand;
use tokio_util::sync::CancellationToken;

use crate::acp_cli::{SessionSelection, SpawnContext, lifecycle_cancelled};
use crate::actions::administration::{PolicyInput, PolicyView};
use crate::actions::supervised::SupervisedHandle;
use crate::administration_target::{InspectionTarget, ReloadSubmission};
use crate::contexts::RemoteContext;
use crate::dashboard::SessionRequest;
use crate::output::{CliReport, Format, Output};

pub(crate) mod evolution;

/// A selectable ACP facet, with its exact configured/catalog identity.
pub(crate) struct AgentChoice {
    pub id: String,
    pub description: String,
}

/// The exact launch inputs a legacy interactive entry already resolved.
///
/// The first Code start consumes these rather than reloading config or
/// rebuilding [`crate::acp_cli::LaunchOptions`]. Code then applies its own
/// terminal-auth capability boundary. Later starts are selected by the user
/// inside Code and follow the usual configuration path.
struct InitialLaunch {
    agent_id: String,
    selection: SessionSelection,
    routing: crate::acp_cli::RoutingOptions,
    config: bitrouter_sdk::config::Config,
    options: crate::acp_cli::LaunchOptions,
}

impl InitialLaunch {
    fn matches(&self, request: &SessionRequest) -> bool {
        self.agent_id == request.agent
            && self.selection == request.selection
            && self.routing == request.routing
    }
}

/// Immutable ports shared by asynchronous interactive effects.
pub(crate) struct CodeServices {
    target: InspectionTarget,
    pub label: String,
    pub operations_only: bool,
    pub can_reload: bool,
    initial_launch: Mutex<Option<InitialLaunch>>,
}

/// Prepared session plus presentation-safe diagnostics and prompt templates.
pub(crate) struct OpenedSession {
    pub handle: SupervisedHandle,
    pub diagnostics: Vec<String>,
    pub prompt_commands: Vec<PromptCommand>,
    pub resumed: bool,
    pub background_choices: bitrouter_tui::agents::NewAgentRunChoices,
}

impl CodeServices {
    /// Observe an already-running local supervisor without starting one for a
    /// remote or report-only Code target.
    pub(crate) async fn background_client(
        &self,
    ) -> Result<Option<crate::agent_sessions::BackgroundClient>> {
        if self.operations_only {
            return Ok(None);
        }
        let Some(source) = self.target.local_source() else {
            return Ok(None);
        };
        if let Some(located) = crate::daemon_locator::locate_source(source).await? {
            return Ok(Some(crate::agent_sessions::BackgroundClient::new(
                located.socket().to_path_buf(),
            )));
        }
        let Some(socket) = self.target.local_socket() else {
            return Ok(None);
        };
        if crate::daemon::probe_status(socket).await?.is_some() {
            return Ok(Some(crate::agent_sessions::BackgroundClient::new(
                socket.to_path_buf(),
            )));
        }
        Ok(None)
    }

    pub fn commands(
        &self,
        capabilities: Option<&crate::acp_cli::CapabilitySnapshot>,
    ) -> Vec<bitrouter_tui::machine::Command> {
        if let Some(capabilities) = capabilities {
            return super::session::offered_route_commands(
                capabilities.route_list,
                capabilities.route_set,
                capabilities.route_reset,
            );
        }
        crate::actions::ACTIONS
            .iter()
            .filter_map(|action| {
                if self.operations_only && !operation_command_supported(action.id) {
                    return None;
                }
                let name = action.tui_command?;
                let unavailable = (!matches!(action.requires, crate::actions::Requires::Nothing))
                    .then_some("Connect a routable ACP session to use this action");
                Some(bitrouter_tui::machine::Command {
                    name,
                    action: action.id,
                    summary: super::session::summary_for(action.id),
                    unavailable,
                })
            })
            .collect()
    }

    pub async fn open(
        remote: Option<(String, RemoteContext)>,
        config: Option<&Path>,
        socket: Option<&Path>,
    ) -> Result<Arc<Self>> {
        let operations_only = remote.is_some() || socket.is_some();
        let target = InspectionTarget::resolve(remote, config, socket).await?;
        let can_reload = target.control_authority().await?.reload;
        let label = if operations_only {
            if target.is_remote() {
                format!(
                    "Remote operations · reports read-only · reload explicit · {}",
                    target.label()
                )
            } else {
                format!(
                    "Local operations · reports read-only · reload explicit · {}",
                    target
                        .local_socket()
                        .context("local operations target has no socket")?
                        .display()
                )
            }
        } else {
            conversation_label(&std::env::current_dir()?)
        };
        Ok(Arc::new(Self {
            target,
            label,
            operations_only,
            can_reload,
            initial_launch: Mutex::new(None),
        }))
    }

    /// Build Code services from an already-resolved legacy interactive launch.
    ///
    /// This preserves its loaded config and launch inputs for the first
    /// session, while Code keeps ownership of its terminal-auth boundary and
    /// asynchronous conversation lifecycle.
    pub(crate) fn from_spawn_context(ctx: SpawnContext<'_>) -> Result<(Arc<Self>, SessionRequest)> {
        let SpawnContext {
            source,
            config,
            agent_id,
            options,
            routing,
        } = ctx;
        let request = SessionRequest {
            agent: agent_id.to_string(),
            selection: SessionSelection::New,
            turn_timeout: options.turn_timeout.map(|timeout| timeout.as_secs()),
            routing: routing.clone(),
        };
        let source = source.clone();
        let socket = crate::daemon::socket_path_for(&source, &config);
        let label = conversation_label(&std::env::current_dir()?);
        let initial_launch = InitialLaunch {
            agent_id: agent_id.to_string(),
            selection: SessionSelection::New,
            routing,
            config,
            options,
        };
        Ok((
            Arc::new(Self {
                target: InspectionTarget::Local { source, socket },
                label,
                operations_only: false,
                can_reload: true,
                initial_launch: Mutex::new(Some(initial_launch)),
            }),
            request,
        ))
    }

    pub async fn agents(&self) -> Result<Vec<AgentChoice>> {
        if self.operations_only {
            return Ok(Vec::new());
        }
        let Some(source) = self.target.local_source() else {
            return Ok(Vec::new());
        };
        let config = crate::paths::load_config(source).await?;
        Ok(crate::agents::list(&config)
            .into_iter()
            .filter_map(|row| {
                agent_is_selectable(&row).then_some(AgentChoice {
                    id: row.id,
                    description: row.description,
                })
            })
            .collect())
    }

    /// Start a local ACP session unless the interactive lifecycle owner has
    /// cancelled it. A cancellation before the session handle is returned
    /// never consumes a controller without reaping it in `SessionHost`.
    pub(crate) async fn start_with_cancel(
        &self,
        request: SessionRequest,
        cancel: &CancellationToken,
    ) -> Result<OpenedSession> {
        if cancel.is_cancelled() {
            return Err(lifecycle_cancelled());
        }
        ensure!(
            !self.operations_only,
            "This target is operations-only; ACP execution is unavailable"
        );
        let Some(source) = self.target.local_source() else {
            bail!("Remote ACP execution is unavailable");
        };
        let initial = self.take_initial_launch(&request)?;
        let (config, agent_id, options, routing) = match initial {
            Some(initial) => (
                initial.config,
                initial.agent_id,
                initial.options,
                initial.routing,
            ),
            None => {
                let config = tokio::select! {
                    biased;
                    _ = cancel.cancelled() => return Err(lifecycle_cancelled()),
                    result = crate::paths::load_config(source) => result?,
                };
                (
                    config,
                    request.agent.clone(),
                    crate::acp_cli::launch_options(request.turn_timeout),
                    request.routing.clone(),
                )
            }
        };
        let prompt_commands = super::session::prompt_commands(&config.chat)?;
        let background_choices = background_choices(&config, Some(&agent_id), true).await?;
        let socket = tokio::select! {
            biased;
            _ = cancel.cancelled() => return Err(lifecycle_cancelled()),
            result = super::supervised::ensure_daemon(source, &config, routing.no_start) => result?,
        };
        let resumed = matches!(
            request.selection,
            crate::acp_cli::SessionSelection::Resume(_)
        );
        if cancel.is_cancelled() {
            return Err(lifecycle_cancelled());
        }
        let (handle, diagnostics) = SupervisedHandle::start(
            socket,
            super::supervised::ForegroundLaunch {
                agent_id,
                cwd: std::env::current_dir().context("resolving current directory")?,
                routing,
                options,
                selection: request.selection,
            },
        )
        .await?;
        Ok(OpenedSession {
            handle,
            diagnostics,
            prompt_commands,
            resumed,
            background_choices,
        })
    }

    fn take_initial_launch(&self, request: &SessionRequest) -> Result<Option<InitialLaunch>> {
        let mut initial = self
            .initial_launch
            .lock()
            .map_err(|_| anyhow::anyhow!("Code initial launch state is unavailable"))?;
        if initial
            .as_ref()
            .is_some_and(|launch| launch.matches(request))
        {
            Ok(initial.take())
        } else {
            Ok(None)
        }
    }

    /// Render the same typed reports as the CLI, only when explicitly requested.
    pub async fn report(&self, action: &str, args: &[String]) -> Result<String> {
        let report: Box<dyn CliReport> = match action {
            "status" => {
                ensure!(args.is_empty(), "usage: /status");
                Box::new(self.target.status().await?)
            }
            "list_models" => Box::new(self.target.models(args.first().map(String::as_str)).await?),
            "requests" => {
                ensure!(args.is_empty(), "Host requests takes no arguments in Code");
                Box::new(
                    self.target
                        .requests(crate::actions::requests::RequestFilters {
                            limit: 100,
                            ..Default::default()
                        })
                        .await?,
                )
            }
            "route" => {
                let model = args.first().context("usage: /preview <model>")?;
                Box::new(
                    self.target
                        .route(RouteInput {
                            model: model.clone(),
                            prompt: None,
                        })
                        .await?,
                )
            }
            "providers_list" => {
                ensure!(args.is_empty(), "usage: /providers list");
                Box::new(self.target.providers().await?)
            }
            "observe_status" => {
                ensure!(args.is_empty(), "usage: /observe status");
                Box::new(self.target.observe().await?)
            }
            "policy_status" => {
                ensure!(args.is_empty(), "usage: /policy status");
                Box::new(self.target.policy(PolicyInput::default()).await?)
            }
            "policy_show" => {
                ensure!(args.len() <= 1, "usage: /policy show [name]");
                Box::new(
                    self.target
                        .policy(PolicyInput {
                            view: PolicyView::Active,
                            name: args.first().cloned(),
                        })
                        .await?,
                )
            }
            "agents_list" => {
                ensure!(args.is_empty(), "usage: /agents list");
                Box::new(self.target.agents().await?)
            }
            "reload_state" => {
                ensure!(args.is_empty(), "usage: /reload state");
                Box::new(self.target.reload_state().await?)
            }
            "reload" => {
                ensure!(args.is_empty(), "usage: /reload");
                match self.target.reload().await? {
                    ReloadSubmission::Local(report) => Box::new(report),
                    ReloadSubmission::Remote(report) => Box::new(report),
                }
            }
            _ => bail!("This target does not offer `{action}`"),
        };
        String::from_utf8(Output::new(Format::Human).render_to_vec(report.as_ref()))
            .context("rendering the requested report")
    }
}

pub(crate) async fn background_choices(
    config: &bitrouter_sdk::config::Config,
    current_agent: Option<&str>,
    foreground_claim: bool,
) -> Result<bitrouter_tui::agents::NewAgentRunChoices> {
    use bitrouter_tui::agents::{NewAgentDirectoryChoice, NewAgentRunChoices};
    let cwd = std::env::current_dir()?;
    let canonical = tokio::fs::canonicalize(&cwd).await?;
    let mut paths = vec![canonical.clone()];
    if let Ok(output) = tokio::process::Command::new("git")
        .arg("-C")
        .arg(&cwd)
        .args(["worktree", "list", "--porcelain", "-z"])
        .output()
        .await
        && output.status.success()
        && let Ok(text) = std::str::from_utf8(&output.stdout)
    {
        for path in text
            .split('\0')
            .filter_map(|field| field.strip_prefix("worktree "))
        {
            if let Ok(path) = tokio::fs::canonicalize(path).await
                && !paths.contains(&path)
            {
                paths.push(path);
            }
        }
    }
    let mut agents = current_agent
        .into_iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>();
    for row in crate::agents::list(config)
        .into_iter()
        .filter(agent_is_selectable)
    {
        if !agents.contains(&row.id) {
            agents.push(row.id);
        }
    }
    Ok(NewAgentRunChoices {
        agents,
        directories: paths
            .into_iter()
            .map(|path| NewAgentDirectoryChoice {
                conflict: (foreground_claim && path == canonical).then(|| {
                    "The foreground run claims this directory; select another directory".into()
                }),
                directory: path.display().to_string(),
            })
            .collect(),
        routes: vec![None],
    })
}

fn conversation_label(workspace: &Path) -> String {
    let short = workspace
        .file_name()
        .unwrap_or(workspace.as_os_str())
        .to_string_lossy();
    format!("{} code · {short}", bitrouter_sdk::invocation::name())
}

/// A socket or named remote target exposes only daemon reports. The typed
/// session controls and route mutations require a local ACP session; route
/// preview remains because it is a read-only report on both operation targets.
fn operation_command_supported(action: &str) -> bool {
    matches!(action, "status" | "list_models" | "route")
}

/// A configured stdio ACP transport is authoritative even when it reuses a
/// catalog id whose bundled harness is interactive-only. Unconfigured catalog
/// entries remain selectable only when the catalog actually supplies ACP.
fn agent_is_selectable(row: &crate::agents::ListRow) -> bool {
    row.configured
        || crate::harness::by_id(&row.id).is_some_and(|harness| harness.acp_command.is_some())
}

#[cfg(test)]
mod tests {
    use super::{
        CodeServices, agent_is_selectable, conversation_label, operation_command_supported,
    };
    use crate::acp_cli::{LaunchOptions, RoutingOptions, SessionSelection, SpawnContext};
    use crate::dashboard::SessionRequest;
    use crate::paths::ConfigSource;

    fn request(agent: &str) -> SessionRequest {
        SessionRequest {
            agent: agent.to_string(),
            selection: SessionSelection::New,
            turn_timeout: None,
            routing: RoutingOptions::default(),
        }
    }

    #[test]
    fn conversation_welcome_uses_only_the_short_workspace_name() {
        assert_eq!(
            conversation_label(std::path::Path::new("/workspaces/bitrouter")),
            "bro code · bitrouter"
        );
    }

    #[test]
    fn initial_launch_waits_for_its_matching_agent_request() -> anyhow::Result<()> {
        let directory = std::env::temp_dir().join("bitrouter-code-test");
        let source = ConfigSource::Default { home: directory };
        let (services, initial_request) = CodeServices::from_spawn_context(SpawnContext {
            source: &source,
            config: bitrouter_sdk::config::Config::default(),
            agent_id: "initial",
            options: LaunchOptions {
                strip_inherited_env: vec!["UNRELATED_AGENT_TOKEN".to_string()],
                turn_timeout: Some(std::time::Duration::from_millis(1_501)),
                terminal_auth: true,
                ..LaunchOptions::default()
            },
            routing: RoutingOptions::default(),
        })?;

        assert_eq!(initial_request.agent, "initial");
        assert!(services.take_initial_launch(&request("other"))?.is_none());
        let initial = services
            .take_initial_launch(&request("initial"))?
            .ok_or_else(|| anyhow::anyhow!("matching initial launch was not retained"))?;
        assert_eq!(
            initial.options.strip_inherited_env,
            vec!["UNRELATED_AGENT_TOKEN".to_string()]
        );
        assert_eq!(
            initial.options.turn_timeout,
            Some(std::time::Duration::from_millis(1_501))
        );
        assert!(initial.options.terminal_auth);
        assert!(services.take_initial_launch(&request("initial"))?.is_none());
        Ok(())
    }

    #[test]
    fn operation_targets_offer_only_their_read_only_reports() {
        for action in ["status", "list_models", "route"] {
            assert!(operation_command_supported(action));
        }
        for action in ["commands", "route_set", "route_reset", "skills_search"] {
            assert!(!operation_command_supported(action));
        }
    }

    #[test]
    fn configured_agent_remains_selectable_without_catalog_acp() {
        let configured = crate::agents::ListRow {
            id: "configured-native-name".to_string(),
            configured: true,
            in_catalog: false,
            description: "configured ACP transport".to_string(),
        };
        let unconfigured = crate::agents::ListRow {
            configured: false,
            ..configured.clone()
        };
        assert!(agent_is_selectable(&configured));
        assert!(!agent_is_selectable(&unconfigured));
    }
}