1mod agent;
12mod compact;
13
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16
17pub type Id = String;
19
20#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
26#[serde(tag = "role", rename_all = "lowercase")]
27pub enum Message {
28 User {
29 content: String,
30 },
31 Assistant {
32 content: String,
33 #[serde(default, skip_serializing_if = "Vec::is_empty")]
34 tool_calls: Vec<AssistantToolCall>,
35 },
36 Tool {
37 tool_call_id: String,
38 content: String,
39 #[serde(skip)]
46 is_error: bool,
47 },
48}
49
50impl Message {
51 #[must_use]
52 pub fn user(content: impl Into<String>) -> Self {
53 Self::User {
54 content: content.into(),
55 }
56 }
57
58 #[must_use]
59 pub fn assistant(content: impl Into<String>) -> Self {
60 Self::Assistant {
61 content: content.into(),
62 tool_calls: Vec::new(),
63 }
64 }
65
66 #[must_use]
67 pub fn assistant_with_calls(
68 content: impl Into<String>,
69 tool_calls: Vec<AssistantToolCall>,
70 ) -> Self {
71 Self::Assistant {
72 content: content.into(),
73 tool_calls,
74 }
75 }
76
77 #[must_use]
78 pub fn tool(call_id: impl Into<String>, content: impl Into<String>) -> Self {
79 Self::tool_result(call_id, content, false)
80 }
81
82 #[must_use]
83 pub fn tool_result(
84 call_id: impl Into<String>,
85 content: impl Into<String>,
86 is_error: bool,
87 ) -> Self {
88 Self::Tool {
89 tool_call_id: call_id.into(),
90 content: content.into(),
91 is_error,
92 }
93 }
94
95 #[must_use]
97 pub fn text(&self) -> &str {
98 match self {
99 Self::User { content }
100 | Self::Assistant { content, .. }
101 | Self::Tool { content, .. } => content,
102 }
103 }
104
105 #[must_use]
107 pub const fn role(&self) -> Role {
108 match self {
109 Self::User { .. } => Role::User,
110 Self::Assistant { .. } => Role::Assistant,
111 Self::Tool { .. } => Role::Tool,
112 }
113 }
114}
115
116#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
118#[serde(rename_all = "lowercase")]
119pub enum Role {
120 User,
121 Assistant,
122 Tool,
123}
124
125impl Role {
126 #[must_use]
128 pub const fn as_str(self) -> &'static str {
129 match self {
130 Self::User => "user",
131 Self::Assistant => "assistant",
132 Self::Tool => "tool",
133 }
134 }
135}
136
137impl From<&Message> for Role {
138 fn from(message: &Message) -> Self {
139 message.role()
140 }
141}
142
143#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
146pub struct AssistantToolCall {
147 pub id: String,
148 pub name: String,
149 pub arguments: String,
150}
151
152#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
158pub struct ModelConfig {
159 pub model: String,
161 pub base_url: String,
163 pub api_key: String,
170 #[serde(default, skip_serializing_if = "Vec::is_empty")]
177 pub headers: Vec<(String, String)>,
178}
179
180impl ModelConfig {
181 #[must_use]
187 pub fn bearer_token(&self) -> Option<&str> {
188 let token = self.api_key.trim();
189 (!token.is_empty()).then_some(token)
190 }
191
192 #[must_use]
194 pub fn completions_url(&self) -> String {
195 format!("{}/chat/completions", self.base_url.trim_end_matches('/'))
196 }
197
198 #[must_use]
204 pub fn models_url(&self) -> String {
205 format!("{}/models", self.base_url.trim_end_matches('/'))
206 }
207}
208
209#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
215pub struct ToolDef {
216 pub name: String,
217 pub description: String,
218 pub schema: Value,
221}
222
223#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
225pub struct ToolResult {
226 pub call_id: String,
227 pub output: String,
228 pub is_error: bool,
229}
230
231impl ToolResult {
232 #[must_use]
233 pub fn ok(call_id: impl Into<String>, output: impl Into<String>) -> Self {
234 Self {
235 call_id: call_id.into(),
236 output: output.into(),
237 is_error: false,
238 }
239 }
240
241 #[must_use]
242 pub fn err(call_id: impl Into<String>, output: impl Into<String>) -> Self {
243 Self {
244 call_id: call_id.into(),
245 output: output.into(),
246 is_error: true,
247 }
248 }
249
250 #[must_use]
252 pub fn to_message(&self) -> Message {
253 Message::tool_result(self.call_id.clone(), self.output.clone(), self.is_error)
254 }
255}
256
257#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
259pub struct Usage {
260 pub prompt_tokens: u32,
261 pub completion_tokens: u32,
262}
263
264#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
269pub struct Turn {
270 pub text: String,
271 pub tool_calls: Vec<AssistantToolCall>,
272 pub usage: Option<Usage>,
273}
274
275#[derive(Debug, thiserror::Error)]
277pub enum Error {
278 #[error("{0}")]
279 InvalidInput(String),
280 #[error("could not read {path}: {source}")]
281 Read {
282 path: String,
283 #[source]
284 source: std::io::Error,
285 },
286 #[error("could not write {path}: {source}")]
287 Write {
288 path: String,
289 #[source]
290 source: std::io::Error,
291 },
292 #[error("could not drive the terminal: {0}")]
293 Terminal(#[source] std::io::Error),
294 #[error("provider request failed: {0}")]
295 Provider(String),
296 #[error("malformed provider response: {0}")]
297 Malformed(String),
298 #[error("could not read the theme: {0}")]
299 Theme(String),
300 #[error("unknown tool `{name}`")]
301 UnknownTool { name: String },
302 #[error("`{tool}` was given arguments it could not read: {reason}")]
303 BadArgs { tool: String, reason: String },
304 #[error("{tool} failed: {reason}")]
305 Tool { tool: String, reason: String },
306}
307
308pub type Result<T, E = Error> = std::result::Result<T, E>;
309
310pub use agent::{Agent, DiscardSink, ModelCatalog, Provider, SteeringQueue, TextSink, Tool};
311pub use compact::{
312 CompactSettings, CompactionOutcome, estimate_tokens, should_compact, summarize_history,
313 summarize_if_needed, summarize_now, summary_request_messages,
314};
315
316#[cfg(test)]
317mod tests {
321 #![allow(
322 clippy::unwrap_used,
323 clippy::expect_used,
324 clippy::indexing_slicing,
325 clippy::as_conversions,
326 clippy::arithmetic_side_effects
327 )]
328
329 use super::{AssistantToolCall, Error, Message, ModelConfig, Role, ToolDef, ToolResult};
330 use serde_json::json;
331
332 #[test]
333 fn completions_url_joins_without_doubling_slashes() {
334 let config = ModelConfig {
335 model: "m".to_owned(),
336 base_url: "https://openrouter.ai/api/v1/".to_owned(),
337 api_key: "k".to_owned(),
338 headers: Vec::new(),
339 };
340 assert_eq!(
341 config.completions_url(),
342 "https://openrouter.ai/api/v1/chat/completions"
343 );
344 }
345
346 #[test]
347 fn a_blank_key_is_the_absence_of_a_credential_not_an_empty_one() {
348 for blank in ["", " ", "\t\n"] {
351 let config = ModelConfig {
352 model: "m".to_owned(),
353 base_url: "http://localhost:11434/v1".to_owned(),
354 api_key: blank.to_owned(),
355 headers: Vec::new(),
356 };
357 assert_eq!(config.bearer_token(), None, "{blank:?}");
358 }
359
360 let keyed = ModelConfig {
361 model: "m".to_owned(),
362 base_url: "https://openrouter.ai/api/v1".to_owned(),
363 api_key: " sk-key ".to_owned(),
364 headers: Vec::new(),
365 };
366 assert_eq!(keyed.bearer_token(), Some("sk-key"));
367 }
368
369 #[test]
370 fn a_user_message_serialises_to_the_openai_shape() {
371 let json = serde_json::to_string(&Message::user("hi")).expect("serialises");
372 assert_eq!(json, r#"{"role":"user","content":"hi"}"#);
373 assert_eq!(Role::from(&Message::user("hi")), Role::User);
374 }
375
376 #[test]
377 fn an_assistant_message_omits_tool_calls_when_there_are_none() {
378 let json = serde_json::to_string(&Message::assistant("hi")).expect("serialises");
379 assert_eq!(json, r#"{"role":"assistant","content":"hi"}"#);
380 }
381
382 #[test]
383 fn a_tool_result_serialises_with_its_call_id() {
384 let message = ToolResult::ok("call-1", "done").to_message();
385 let json = serde_json::to_string(&message).expect("serialises");
386 assert_eq!(
387 json,
388 r#"{"role":"tool","tool_call_id":"call-1","content":"done"}"#
389 );
390 }
391
392 #[test]
393 fn an_assistant_message_carries_its_calls() {
394 let call = AssistantToolCall {
395 id: "call-1".to_owned(),
396 name: "read".to_owned(),
397 arguments: "{}".to_owned(),
398 };
399 let message = Message::assistant_with_calls("working", vec![call]);
400 let back: Message =
401 serde_json::from_str(&serde_json::to_string(&message).expect("serialises"))
402 .expect("round trips");
403
404 assert_eq!(back, message);
405 }
406
407 #[test]
408 fn a_tool_result_becomes_the_message_the_model_reads() {
409 let result = ToolResult::err("call-1", "no such file");
410
411 assert_eq!(
414 result.to_message(),
415 Message::tool_result("call-1", "no such file", true)
416 );
417 }
418
419 #[test]
420 fn a_tool_def_carries_an_arbitrary_schema() {
421 let def = ToolDef {
422 name: "read".to_owned(),
423 description: "Read a file".to_owned(),
424 schema: json!({"type": "object"}),
425 };
426 assert_eq!(def.schema["type"], "object");
427 }
428
429 #[test]
430 fn errors_name_the_thing_that_went_wrong() {
431 assert!(
432 Error::UnknownTool {
433 name: "nope".to_owned()
434 }
435 .to_string()
436 .contains("nope")
437 );
438 assert!(
439 Error::BadArgs {
440 tool: "read".to_owned(),
441 reason: "missing path".to_owned()
442 }
443 .to_string()
444 .contains("read")
445 );
446 }
447}