mod agent;
mod compact;
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub type Id = String;
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "role", rename_all = "lowercase")]
pub enum Message {
User {
content: String,
},
Assistant {
content: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
tool_calls: Vec<AssistantToolCall>,
},
Tool {
tool_call_id: String,
content: String,
#[serde(skip)]
is_error: bool,
},
}
impl Message {
#[must_use]
pub fn user(content: impl Into<String>) -> Self {
Self::User {
content: content.into(),
}
}
#[must_use]
pub fn assistant(content: impl Into<String>) -> Self {
Self::Assistant {
content: content.into(),
tool_calls: Vec::new(),
}
}
#[must_use]
pub fn assistant_with_calls(
content: impl Into<String>,
tool_calls: Vec<AssistantToolCall>,
) -> Self {
Self::Assistant {
content: content.into(),
tool_calls,
}
}
#[must_use]
pub fn tool(call_id: impl Into<String>, content: impl Into<String>) -> Self {
Self::tool_result(call_id, content, false)
}
#[must_use]
pub fn tool_result(
call_id: impl Into<String>,
content: impl Into<String>,
is_error: bool,
) -> Self {
Self::Tool {
tool_call_id: call_id.into(),
content: content.into(),
is_error,
}
}
#[must_use]
pub fn text(&self) -> &str {
match self {
Self::User { content }
| Self::Assistant { content, .. }
| Self::Tool { content, .. } => content,
}
}
#[must_use]
pub const fn role(&self) -> Role {
match self {
Self::User { .. } => Role::User,
Self::Assistant { .. } => Role::Assistant,
Self::Tool { .. } => Role::Tool,
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
User,
Assistant,
Tool,
}
impl Role {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::User => "user",
Self::Assistant => "assistant",
Self::Tool => "tool",
}
}
}
impl From<&Message> for Role {
fn from(message: &Message) -> Self {
message.role()
}
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct AssistantToolCall {
pub id: String,
pub name: String,
pub arguments: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ModelConfig {
pub model: String,
pub base_url: String,
pub api_key: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub headers: Vec<(String, String)>,
}
impl ModelConfig {
#[must_use]
pub fn bearer_token(&self) -> Option<&str> {
let token = self.api_key.trim();
(!token.is_empty()).then_some(token)
}
#[must_use]
pub fn completions_url(&self) -> String {
format!("{}/chat/completions", self.base_url.trim_end_matches('/'))
}
#[must_use]
pub fn models_url(&self) -> String {
format!("{}/models", self.base_url.trim_end_matches('/'))
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ToolDef {
pub name: String,
pub description: String,
pub schema: Value,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ToolResult {
pub call_id: String,
pub output: String,
pub is_error: bool,
}
impl ToolResult {
#[must_use]
pub fn ok(call_id: impl Into<String>, output: impl Into<String>) -> Self {
Self {
call_id: call_id.into(),
output: output.into(),
is_error: false,
}
}
#[must_use]
pub fn err(call_id: impl Into<String>, output: impl Into<String>) -> Self {
Self {
call_id: call_id.into(),
output: output.into(),
is_error: true,
}
}
#[must_use]
pub fn to_message(&self) -> Message {
Message::tool_result(self.call_id.clone(), self.output.clone(), self.is_error)
}
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct Usage {
pub prompt_tokens: u32,
pub completion_tokens: u32,
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct Turn {
pub text: String,
pub tool_calls: Vec<AssistantToolCall>,
pub usage: Option<Usage>,
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{0}")]
InvalidInput(String),
#[error("could not read {path}: {source}")]
Read {
path: String,
#[source]
source: std::io::Error,
},
#[error("could not write {path}: {source}")]
Write {
path: String,
#[source]
source: std::io::Error,
},
#[error("could not drive the terminal: {0}")]
Terminal(#[source] std::io::Error),
#[error("provider request failed: {0}")]
Provider(String),
#[error("malformed provider response: {0}")]
Malformed(String),
#[error("could not read the theme: {0}")]
Theme(String),
#[error("unknown tool `{name}`")]
UnknownTool { name: String },
#[error("`{tool}` was given arguments it could not read: {reason}")]
BadArgs { tool: String, reason: String },
#[error("{tool} failed: {reason}")]
Tool { tool: String, reason: String },
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub use agent::{Agent, DiscardSink, ModelCatalog, Provider, SteeringQueue, TextSink, Tool};
pub use compact::{
CompactSettings, CompactionOutcome, estimate_tokens, should_compact, summarize_history,
summarize_if_needed, summarize_now, summary_request_messages,
};
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::as_conversions,
clippy::arithmetic_side_effects
)]
use super::{AssistantToolCall, Error, Message, ModelConfig, Role, ToolDef, ToolResult};
use serde_json::json;
#[test]
fn completions_url_joins_without_doubling_slashes() {
let config = ModelConfig {
model: "m".to_owned(),
base_url: "https://openrouter.ai/api/v1/".to_owned(),
api_key: "k".to_owned(),
headers: Vec::new(),
};
assert_eq!(
config.completions_url(),
"https://openrouter.ai/api/v1/chat/completions"
);
}
#[test]
fn a_blank_key_is_the_absence_of_a_credential_not_an_empty_one() {
for blank in ["", " ", "\t\n"] {
let config = ModelConfig {
model: "m".to_owned(),
base_url: "http://localhost:11434/v1".to_owned(),
api_key: blank.to_owned(),
headers: Vec::new(),
};
assert_eq!(config.bearer_token(), None, "{blank:?}");
}
let keyed = ModelConfig {
model: "m".to_owned(),
base_url: "https://openrouter.ai/api/v1".to_owned(),
api_key: " sk-key ".to_owned(),
headers: Vec::new(),
};
assert_eq!(keyed.bearer_token(), Some("sk-key"));
}
#[test]
fn a_user_message_serialises_to_the_openai_shape() {
let json = serde_json::to_string(&Message::user("hi")).expect("serialises");
assert_eq!(json, r#"{"role":"user","content":"hi"}"#);
assert_eq!(Role::from(&Message::user("hi")), Role::User);
}
#[test]
fn an_assistant_message_omits_tool_calls_when_there_are_none() {
let json = serde_json::to_string(&Message::assistant("hi")).expect("serialises");
assert_eq!(json, r#"{"role":"assistant","content":"hi"}"#);
}
#[test]
fn a_tool_result_serialises_with_its_call_id() {
let message = ToolResult::ok("call-1", "done").to_message();
let json = serde_json::to_string(&message).expect("serialises");
assert_eq!(
json,
r#"{"role":"tool","tool_call_id":"call-1","content":"done"}"#
);
}
#[test]
fn an_assistant_message_carries_its_calls() {
let call = AssistantToolCall {
id: "call-1".to_owned(),
name: "read".to_owned(),
arguments: "{}".to_owned(),
};
let message = Message::assistant_with_calls("working", vec![call]);
let back: Message =
serde_json::from_str(&serde_json::to_string(&message).expect("serialises"))
.expect("round trips");
assert_eq!(back, message);
}
#[test]
fn a_tool_result_becomes_the_message_the_model_reads() {
let result = ToolResult::err("call-1", "no such file");
assert_eq!(
result.to_message(),
Message::tool_result("call-1", "no such file", true)
);
}
#[test]
fn a_tool_def_carries_an_arbitrary_schema() {
let def = ToolDef {
name: "read".to_owned(),
description: "Read a file".to_owned(),
schema: json!({"type": "object"}),
};
assert_eq!(def.schema["type"], "object");
}
#[test]
fn errors_name_the_thing_that_went_wrong() {
assert!(
Error::UnknownTool {
name: "nope".to_owned()
}
.to_string()
.contains("nope")
);
assert!(
Error::BadArgs {
tool: "read".to_owned(),
reason: "missing path".to_owned()
}
.to_string()
.contains("read")
);
}
}