bitrouter 1.0.0-alpha.32

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
//! Typed local-or-remote inspection ports.
//!
//! A remote context names the complete target.  This module resolves that
//! choice before a caller can load a local config, socket, database, or
//! provider environment, then exposes the same read operations to the CLI and
//! operations dashboard.

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

use crate::actions::models::ModelsReport;
use crate::actions::route::{RouteInput, RouteReport};
use crate::actions::status::StatusReport;
use anyhow::Result;

use crate::actions::administration::{
    AgentsReport, ObserveReport, PolicyInput, PolicyReport, PolicyView, ProvidersReport,
};
use crate::actions::models::RoutableModels;
use crate::actions::requests::{RequestFilters, RequestsAction};
use crate::actions::route::RouteAction;
use crate::actions::status::DaemonStatus;
use crate::contexts::RemoteContext;
use crate::daemon::{
    self, DaemonCommand, DaemonInspection, DaemonInspectionReport, DaemonResponse,
};
use crate::output::reports::requests::RequestsReport;
use crate::paths::ConfigSource;
use crate::reload::ReloadState;
use crate::remote_control::operations::{OperationReport, ReloadInput};

/// Result of an explicit reload submitted through a selected target.
///
/// A local control socket completes synchronously and can only return the
/// coordinator's current state. Remote control retains an exact operation
/// receipt by request id, including a still-running operation after bounded
/// client polling.
pub enum ReloadSubmission {
    Local(ReloadState),
    Remote(OperationReport),
}

/// The currently advertised control grants relevant to the dashboard.
///
/// Server-side authorization remains authoritative when an action is sent. The
/// UI uses this snapshot only to avoid presenting a reload trigger to a
/// credential that discovery says cannot submit one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ControlAuthority {
    pub read: bool,
    pub reload: bool,
}

/// One selected target for a passive administration action.
#[derive(Clone)]
pub enum InspectionTarget {
    Local {
        source: ConfigSource,
        socket: PathBuf,
    },
    Remote {
        name: String,
        client: Arc<crate::remote_control::HttpControlClient>,
    },
}

impl InspectionTarget {
    /// Resolve the target once.  A remote context is complete by itself, so
    /// reject local flags before constructing a client or reading any local
    /// configuration.
    pub async fn resolve(
        remote: Option<(String, RemoteContext)>,
        config: Option<&Path>,
        socket: Option<&Path>,
    ) -> Result<Self> {
        match remote {
            Some((name, context)) => {
                reject_remote_local_flags(config, socket)?;
                Ok(Self::Remote {
                    name,
                    client: Arc::new(context.client()?),
                })
            }
            None => {
                let located = if socket.is_none() {
                    crate::daemon_locator::locate(config).await?
                } else {
                    None
                };
                if let Some(located) = located {
                    return Ok(Self::Local {
                        source: located.source().clone(),
                        socket: located.socket().to_path_buf(),
                    });
                }
                let source = crate::daemon_locator::selected_source(config)?;
                let socket = match socket {
                    Some(socket) => socket.to_path_buf(),
                    None => match crate::paths::load_config(&source).await {
                        Ok(config) => daemon::socket_path_for(&source, &config),
                        Err(_) => match &source {
                            ConfigSource::File(path) => {
                                daemon::resolve_socket_path(path, daemon::DEFAULT_CONTROL_SOCKET)
                            }
                            ConfigSource::Default { home } => home.join("bitrouter.sock"),
                        },
                    },
                };
                Ok(Self::Local { source, socket })
            }
        }
    }

    pub fn label(&self) -> String {
        match self {
            Self::Local { .. } => "local".to_string(),
            Self::Remote { name, .. } => format!("remote:{name}"),
        }
    }

    /// Local ACP sessions are deliberately absent from a remote inspection
    /// target.  The catalog itself remains readable through [`Self::agents`].
    pub fn allows_agent_launch(&self) -> bool {
        matches!(self, Self::Local { .. })
    }

    /// The dashboard uses this only to choose the explicitly initiated reload
    /// protocol. It does not widen the local socket protocol.
    pub fn is_remote(&self) -> bool {
        matches!(self, Self::Remote { .. })
    }

    pub fn local_source(&self) -> Option<&ConfigSource> {
        match self {
            Self::Local { source, .. } => Some(source),
            Self::Remote { .. } => None,
        }
    }

    /// The local-only adapter for legacy CLI output may retain the socket in
    /// its established JSON shape. Remote targets never expose a socket.
    pub fn local_socket(&self) -> Option<&Path> {
        match self {
            Self::Local { socket, .. } => Some(socket),
            Self::Remote { .. } => None,
        }
    }

    pub async fn status(&self) -> Result<StatusReport> {
        match self {
            Self::Local { source, socket } => {
                DaemonStatus::new(socket, Some(source.clone()))
                    .report()
                    .await
            }
            Self::Remote { client, .. } => client.status().await,
        }
    }

    pub async fn models(&self, provider: Option<&str>) -> Result<ModelsReport> {
        match self {
            Self::Local { source, socket } => {
                Ok(RoutableModels::new(source.clone(), Some(socket.clone()))
                    .report()
                    .await?
                    .filtered(provider))
            }
            Self::Remote { client, .. } => client.models(provider).await,
        }
    }

    pub async fn requests(&self, filters: RequestFilters) -> Result<RequestsReport> {
        match self {
            Self::Local { source, socket } => {
                RequestsAction::new(source.clone(), socket.clone())
                    .report_filtered(filters)
                    .await
            }
            Self::Remote { client, .. } => client.requests_filtered(&filters).await,
        }
    }

    pub async fn route(&self, input: RouteInput) -> Result<RouteReport> {
        match self {
            Self::Local { source, socket } => {
                RouteAction::new(source.clone(), Some(socket.clone()))
                    .report(input)
                    .await
            }
            Self::Remote { client, .. } => client.route(&input).await,
        }
    }

    pub async fn providers(&self) -> Result<ProvidersReport> {
        match self {
            Self::Local { .. } => match self.inspect(DaemonInspection::Providers).await? {
                DaemonInspectionReport::Providers(report) => Ok(report),
                other => unexpected_inspection("providers", other),
            },
            Self::Remote { client, .. } => client.providers().await,
        }
    }

    pub async fn agents(&self) -> Result<AgentsReport> {
        match self {
            Self::Local { .. } => match self.inspect(DaemonInspection::Agents).await? {
                DaemonInspectionReport::Agents(report) => Ok(report),
                other => unexpected_inspection("agents", other),
            },
            Self::Remote { client, .. } => client.agents().await,
        }
    }

    pub async fn observe(&self) -> Result<ObserveReport> {
        match self {
            Self::Local { .. } => match self.inspect(DaemonInspection::Observe).await {
                Ok(DaemonInspectionReport::Observe(report)) => Ok(report),
                Ok(other) => unexpected_inspection("observe", other),
                Err(error) if daemon::is_not_reachable(&error) => Ok(ObserveReport::from_snapshot(
                    daemon::ObserveStatusPayload::unwired(bitrouter_telemetry::OTEL_ENABLED),
                    false,
                )),
                Err(error) => Err(error),
            },
            Self::Remote { client, .. } => client.observe().await,
        }
    }

    pub async fn policy(&self, input: PolicyInput) -> Result<PolicyReport> {
        input.validate()?;
        match self {
            Self::Local { source, .. } if input.view == PolicyView::Disk => {
                crate::actions::administration::disk_policy(source)
                    .await?
                    .selected(input.name.as_deref())
            }
            Self::Local { .. } => match self.inspect(DaemonInspection::Policy { input }).await? {
                DaemonInspectionReport::Policy(report) => Ok(report),
                other => unexpected_inspection("policy", other),
            },
            Self::Remote { client, .. } => client.policy(&input).await,
        }
    }

    pub async fn checks(&self) -> Result<crate::actions::checks::ChecksReport> {
        match self {
            Self::Local { .. } => match self.inspect(DaemonInspection::Checks).await? {
                DaemonInspectionReport::Checks(report) => Ok(report),
                other => unexpected_inspection("checks", other),
            },
            Self::Remote { client, .. } => client.checks().await,
        }
    }

    pub async fn checks_probe(
        &self,
        checker: &str,
    ) -> Result<crate::actions::checks::CheckerProbeReport> {
        crate::actions::administration::validate_identifier(checker)?;
        match self {
            Self::Local { .. } => match self
                .inspect(DaemonInspection::ChecksProbe {
                    checker: checker.to_string(),
                })
                .await?
            {
                DaemonInspectionReport::ChecksProbe(report) => Ok(report),
                other => unexpected_inspection("checks probe", other),
            },
            Self::Remote { client, .. } => client.checks_probe(checker).await,
        }
    }

    pub async fn check_receipts(
        &self,
        limit: usize,
    ) -> Result<bitrouter_sdk::language_model::receipts::RequestReceiptList> {
        crate::actions::checks::validate_receipt_limit(limit)?;
        match self {
            Self::Local { .. } => match self
                .inspect(DaemonInspection::CheckReceipts { limit })
                .await?
            {
                DaemonInspectionReport::CheckReceipts(report) => Ok(report),
                other => unexpected_inspection("checks receipts", other),
            },
            Self::Remote { client, .. } => client.check_receipts(limit).await,
        }
    }

    pub async fn check_receipt(
        &self,
        request_id: &str,
        incarnation: Option<&str>,
    ) -> Result<bitrouter_sdk::language_model::receipts::RequestReceiptLookup> {
        crate::actions::checks::validate_receipt_lookup(request_id, incarnation)?;
        match self {
            Self::Local { .. } => match self
                .inspect(DaemonInspection::CheckReceipt {
                    request_id: request_id.to_string(),
                    incarnation: incarnation.map(str::to_string),
                })
                .await?
            {
                DaemonInspectionReport::CheckReceipt(report) => Ok(report),
                other => unexpected_inspection("checks receipt", other),
            },
            Self::Remote { client, .. } => client.check_receipt(request_id, incarnation).await,
        }
    }

    pub async fn reload_state(&self) -> Result<ReloadState> {
        match self {
            Self::Local { socket, .. } => {
                match daemon::send_command(socket, &DaemonCommand::ReloadState).await? {
                    DaemonResponse::ReloadState { state } => Ok(state),
                    DaemonResponse::Error { message } => Err(anyhow::anyhow!(message)),
                    other => Err(anyhow::anyhow!(
                        "unexpected daemon reload-state response: {other:?}"
                    )),
                }
            }
            Self::Remote { client, .. } => client.state().await,
        }
    }

    /// Read the control discovery grants cached by the remote client. Local
    /// IPC is operator-local, so it has both capabilities when its daemon
    /// supports the corresponding command.
    pub async fn control_authority(&self) -> Result<ControlAuthority> {
        match self {
            Self::Local { .. } => Ok(ControlAuthority {
                read: true,
                reload: true,
            }),
            Self::Remote { client, .. } => Ok(ControlAuthority {
                read: client.can_action("status").await?,
                reload: client.can_action("reload").await?,
            }),
        }
    }

    pub async fn reload(&self) -> Result<ReloadSubmission> {
        match self {
            Self::Local { socket, .. } => {
                match daemon::send_command(socket, &DaemonCommand::Reload { env: Vec::new() })
                    .await?
                {
                    DaemonResponse::Ok => Ok(ReloadSubmission::Local(self.reload_state().await?)),
                    DaemonResponse::Error { message } => Err(anyhow::anyhow!(message)),
                    other => Err(anyhow::anyhow!(
                        "unexpected daemon reload response: {other:?}"
                    )),
                }
            }
            Self::Remote { client, .. } => Ok(ReloadSubmission::Remote(client.reload().await?)),
        }
    }

    /// Submit an already fenced remote reload request. Keeping this separate
    /// from [`Self::reload`] lets the dashboard retain the generated request
    /// and instance identifiers if the HTTP response is interrupted.
    pub async fn submit_remote_reload(&self, input: &ReloadInput) -> Result<OperationReport> {
        match self {
            Self::Local { .. } => anyhow::bail!(
                "local reloads use the control socket and do not accept remote reload inputs"
            ),
            Self::Remote { client, .. } => client.submit_reload(input).await,
        }
    }

    pub async fn operation(&self, request_id: &str, instance: &str) -> Result<OperationReport> {
        match self {
            Self::Local { .. } => anyhow::bail!(
                "local reloads do not retain operation receipts; inspect the current reload state instead"
            ),
            Self::Remote { client, .. } => client.operation(request_id, instance).await,
        }
    }

    async fn inspect(&self, inspection: DaemonInspection) -> Result<DaemonInspectionReport> {
        let Self::Local { socket, .. } = self else {
            anyhow::bail!("local inspection is unavailable for a remote target");
        };
        match daemon::send_command(socket, &DaemonCommand::Inspect { inspection }).await? {
            DaemonResponse::Inspection { report } => Ok(report),
            DaemonResponse::Error { message } => Err(anyhow::anyhow!(message)),
            other => Err(anyhow::anyhow!(
                "unexpected daemon inspection response: {other:?}"
            )),
        }
    }
}

fn unexpected_inspection<T>(action: &str, report: DaemonInspectionReport) -> Result<T> {
    anyhow::bail!("daemon returned the wrong inspection report for {action}: {report:?}")
}

pub fn reject_remote_local_flags(config: Option<&Path>, socket: Option<&Path>) -> Result<()> {
    if config.is_some() || socket.is_some() {
        return Err(bitrouter_sdk::BitrouterError::bad_request(
            "a remote context does not accept --config or --socket; the named context is the \
             complete target",
        )
        .into());
    }
    Ok(())
}

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

    #[tokio::test]
    async fn remote_local_flags_are_rejected_before_the_token_is_read() -> anyhow::Result<()> {
        let config = tempfile::tempdir()?.path().join("bitrouter.yaml");
        let error = InspectionTarget::resolve(
            Some((
                "workstation".to_string(),
                RemoteContext {
                    endpoint: "https://router.example/control/v1/".to_string(),
                    token_env: "UNSET_TEST_CONTROL_TOKEN".to_string(),
                },
            )),
            Some(&config),
            None,
        )
        .await
        .err()
        .ok_or_else(|| anyhow::anyhow!("remote config flag unexpectedly succeeded"))?;
        assert!(error.to_string().contains("does not accept --config"));
        Ok(())
    }
}