Skip to main content

byob_types/
lib.rs

1//! Shared serde types used across every byob layer.
2#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
3
4pub mod channel;
5pub mod chart;
6pub mod config;
7pub mod desktop;
8pub mod layout;
9pub mod process;
10pub mod profile;
11pub mod routine;
12
13use serde::{Deserialize, Serialize};
14
15/// Who authored a chat message.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(rename_all = "lowercase")]
18pub enum Role {
19    System,
20    User,
21    Assistant,
22    Tool,
23}
24
25/// A single chat message as sent to / received from the inference endpoint.
26#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
27pub struct Message {
28    pub role: Role,
29    pub content: String,
30}
31
32/// Which wire protocol an endpoint speaks.
33#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(rename_all = "lowercase")]
35pub enum ApiKind {
36    /// OpenAI chat completions (`POST {base}/chat/completions`): llama-server, vLLM,
37    /// Ollama, LM Studio, OpenAI, OpenRouter, ...
38    #[default]
39    #[serde(rename = "openai")]
40    OpenAi,
41    /// Anthropic's Messages API (`POST {base}/messages`), for Claude.
42    Anthropic,
43    /// A signed-in agent CLI run as a subprocess (`cli://claude`, `cli://codex`): the
44    /// user's own subscription answers, with the CLI's own tools turned off. See
45    /// `byob_llm::agents`.
46    Cli,
47}
48
49/// The URL scheme of an agent CLI endpoint: `cli://<agent>`.
50pub const CLI_SCHEME: &str = "cli://";
51
52/// The agent id of a `cli://<agent>` URL (`"claude"`), or `None` for any other URL.
53pub fn cli_agent(url: &str) -> Option<&str> {
54    let rest = url.trim().get(..CLI_SCHEME.len()).filter(|s| s.eq_ignore_ascii_case(CLI_SCHEME)).and_then(|_| url.trim().get(CLI_SCHEME.len()..))?;
55    let id = rest.trim_end_matches('/');
56    (!id.is_empty() && id.len() <= 32 && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')).then_some(id)
57}
58
59/// An endpoint URL byob can use: `http(s)://…` or `cli://<agent>`.
60pub fn endpoint_url_ok(url: &str) -> bool {
61    url.starts_with("http://") || url.starts_with("https://") || cli_agent(url).is_some()
62}
63
64/// Where and how to reach the model. Replaces hob's local llama.cpp setup.
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66pub struct InferenceConfig {
67    /// Base URL of the API, e.g. `http://127.0.0.1:8080/v1`.
68    pub base_url: String,
69    /// Model name to request; many single-model servers ignore it.
70    pub model: String,
71    /// Optional API key (a bearer token, or Anthropic's `x-api-key`).
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub api_key: Option<String>,
74    /// The API the endpoint speaks; `None` decides from the URL ([`InferenceConfig::api_kind`]).
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub api: Option<ApiKind>,
77    /// Request options of the profile this endpoint came from (temperature, `max_tokens`,
78    /// effort, extra body fields): byob-llm adds them to every chat request made with it
79    /// (see `byob_llm::params`). Never to the probe's own requests.
80    #[serde(default, skip_serializing_if = "profile::Params::is_empty")]
81    pub params: profile::Params,
82    /// Context window to budget against, beating what the probe found (a profile's
83    /// [`profile::Profile::context`]).
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub context: Option<u32>,
86}
87
88impl Default for InferenceConfig {
89    fn default() -> Self {
90        Self {
91            base_url: "http://127.0.0.1:8080/v1".into(),
92            model: "default".into(),
93            api_key: None,
94            api: None,
95            params: profile::Params::default(),
96            context: None,
97        }
98    }
99}
100
101impl InferenceConfig {
102    /// The API to speak: an agent CLI for `cli://` URLs (always), else the configured one,
103    /// else Anthropic for `api.anthropic.com`, else OpenAI.
104    pub fn api_kind(&self) -> ApiKind {
105        if cli_agent(&self.base_url).is_some() {
106            return ApiKind::Cli;
107        }
108        match self.api {
109            Some(ApiKind::Cli) | None => {
110                if url_host(&self.base_url).eq_ignore_ascii_case("api.anthropic.com") {
111                    ApiKind::Anthropic
112                } else {
113                    ApiKind::OpenAi
114                }
115            }
116            Some(kind) => kind,
117        }
118    }
119
120    /// The same endpoint (URL, model, key, API), whatever the request options.
121    pub fn same_endpoint(&self, other: &Self) -> bool {
122        self.base_url == other.base_url && self.model == other.model && self.api_key == other.api_key && self.api == other.api
123    }
124}
125
126/// The host part of `url` (no scheme, user info, port or path); empty if there is none.
127fn url_host(url: &str) -> &str {
128    let rest = url.trim().split_once("://").map_or("", |(_, r)| r);
129    let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
130    let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
131    host.split(':').next().unwrap_or_default().trim_end_matches('.')
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn role_serializes_lowercase() {
140        assert_eq!(serde_json::to_string(&Role::Assistant).unwrap(), "\"assistant\"");
141    }
142
143    #[test]
144    fn api_kind_is_set_or_follows_the_host() {
145        let at = |url: &str| InferenceConfig { base_url: url.into(), ..Default::default() }.api_kind();
146        assert_eq!(at("https://api.anthropic.com/v1"), ApiKind::Anthropic);
147        assert_eq!(at("https://API.Anthropic.com:443/v1/"), ApiKind::Anthropic);
148        assert_eq!(at("http://127.0.0.1:8080/v1"), ApiKind::OpenAi);
149        assert_eq!(at("https://api.anthropic.com.evil.example/v1"), ApiKind::OpenAi);
150        assert_eq!(at("https://proxy.example/?u=api.anthropic.com"), ApiKind::OpenAi);
151        assert_eq!(at("not a url"), ApiKind::OpenAi);
152        let set = InferenceConfig { base_url: "http://proxy:8080/v1".into(), api: Some(ApiKind::Anthropic), ..Default::default() };
153        assert_eq!(set.api_kind(), ApiKind::Anthropic);
154        let forced = InferenceConfig { base_url: "https://api.anthropic.com/v1".into(), api: Some(ApiKind::OpenAi), ..Default::default() };
155        assert_eq!(forced.api_kind(), ApiKind::OpenAi);
156        // Existing configs (no `api`) read and write as before.
157        let old: InferenceConfig = serde_json::from_str(r#"{"base_url":"http://h/v1","model":"m"}"#).unwrap();
158        assert_eq!(old.api, None);
159        assert_eq!(serde_json::to_string(&old).unwrap(), r#"{"base_url":"http://h/v1","model":"m"}"#);
160        assert_eq!(serde_json::to_string(&ApiKind::OpenAi).unwrap(), r#""openai""#);
161        assert_eq!(serde_json::from_str::<ApiKind>(r#""anthropic""#).unwrap(), ApiKind::Anthropic);
162    }
163
164    #[test]
165    fn cli_urls_name_an_agent() {
166        assert_eq!(cli_agent("cli://claude"), Some("claude"));
167        assert_eq!(cli_agent(" CLI://codex/ "), Some("codex"));
168        assert_eq!(cli_agent("cli://"), None);
169        assert_eq!(cli_agent("cli://../etc"), None);
170        assert_eq!(cli_agent("cli://Claude"), None);
171        assert_eq!(cli_agent("http://claude"), None);
172        assert!(endpoint_url_ok("cli://claude") && endpoint_url_ok("http://h/v1") && !endpoint_url_ok("ftp://x"));
173        let at = |url: &str, api| InferenceConfig { base_url: url.into(), api, ..Default::default() }.api_kind();
174        assert_eq!(at("cli://claude", None), ApiKind::Cli);
175        assert_eq!(at("cli://claude", Some(ApiKind::OpenAi)), ApiKind::Cli);
176        // `api: cli` on an http URL can't run anything: it reads as the URL says.
177        assert_eq!(at("http://127.0.0.1:8080/v1", Some(ApiKind::Cli)), ApiKind::OpenAi);
178        assert_eq!(serde_json::to_string(&ApiKind::Cli).unwrap(), r#""cli""#);
179    }
180}