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