Skip to main content

yk_core/
lib.rs

1//! The agent loop, and the vocabulary every other crate in the workspace speaks.
2//!
3//! Nothing here knows about a terminal, an HTTP client, or a file format. If a
4//! change makes this crate aware of any of those, it has leaked.
5//!
6//! The vocabulary is deliberately wider than what the first months need. A tool
7//! call has to survive three round trips: out to the model, back from it, and
8//! out again with the result attached, and a shape that cannot express that
9//! means rewriting the session format later.
10
11mod agent;
12mod compact;
13
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16
17/// Identifier for an entry in a session tree.
18pub type Id = String;
19
20/// One message in the conversation, as it goes to and from the model.
21///
22/// The wire shape is the provider's business, not ours. This is the vocabulary,
23/// and it keeps tool results as a first-class message rather than as text glued
24/// into an assistant turn, because the model has to be able to tell them apart.
25#[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        /// Whether the tool failed.
40        ///
41        /// Not serialised: the provider's tool message has no such field, and
42        /// sending one is at best ignored and at worst rejected. The session file
43        /// records it separately, so resuming a session knows a result was an
44        /// error even though the model was never told in so many words.
45        #[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    /// The prose, with tool results included and tool calls not.
96    #[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    /// Which side of the conversation this message came from.
106    #[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/// Which side of the conversation a message came from.
117#[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    /// The label the provider and the transcript use for this role.
127    #[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/// A tool call as the model emitted it. Argument text arrives as fragments and
144/// is assembled elsewhere; by the time it reaches the loop it is one string.
145#[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/// A model the agent can talk to.
153///
154/// The base URL is configuration rather than a branch, which is why there is no
155/// provider registry anywhere in this workspace. `OpenRouter` serves every vendor
156/// through this one shape, and a local server is a different string.
157#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
158pub struct ModelConfig {
159    /// Identifier as the endpoint names it, such as `anthropic/claude-sonnet-4`.
160    pub model: String,
161    /// Endpoint root, such as `https://openrouter.ai/api/v1`.
162    pub base_url: String,
163    /// Bearer token. Never logged, never written into a session file.
164    ///
165    /// Blank means the endpoint serves without one, which is what a local
166    /// `Ollama` or `vLLM` does. Use [`Self::bearer_token`] rather than reading
167    /// this field: it is the one place that decides whether a blank key is a
168    /// credential or the absence of one.
169    pub api_key: String,
170    /// Headers sent with every request to this endpoint, by name.
171    ///
172    /// Some gateways refuse a request that does not identify the client or the
173    /// conversation it belongs to, and the header they want is not one yk would
174    /// send on its own. Empty for an endpoint that wants nothing beyond the
175    /// credential, which is every endpoint yk points at by default.
176    #[serde(default, skip_serializing_if = "Vec::is_empty")]
177    pub headers: Vec<(String, String)>,
178}
179
180impl ModelConfig {
181    /// The credential to send, or `None` when there is none to send.
182    ///
183    /// Blank and absent are the same state. A keyless endpoint rejects
184    /// `Authorization: Bearer ` outright on some servers, so the header is left
185    /// off entirely rather than sent empty.
186    #[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    /// The URL a chat completion is posted to.
193    #[must_use]
194    pub fn completions_url(&self) -> String {
195        format!("{}/chat/completions", self.base_url.trim_end_matches('/'))
196    }
197
198    /// The URL that lists what the endpoint can serve.
199    ///
200    /// Part of the same `OpenAI` shape, so it is derived rather than configured.
201    /// An endpoint without this route is not an error: the caller falls back to
202    /// the configured model and carries on with no picker.
203    #[must_use]
204    pub fn models_url(&self) -> String {
205        format!("{}/models", self.base_url.trim_end_matches('/'))
206    }
207}
208
209/// One tool as the provider describes it.
210///
211/// Built-in tools and tools registered by a `Lua` extension are both this.
212/// Keeping one type is what makes it cheap: registering a tool is a map insert,
213/// because nothing downstream can tell the difference.
214#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
215pub struct ToolDef {
216    pub name: String,
217    pub description: String,
218    /// JSON Schema for the arguments object, as a `Value` because it came from
219    /// one.
220    pub schema: Value,
221}
222
223/// The outcome of one tool call, as recorded in the session.
224#[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    /// The message to feed back to the model.
251    #[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/// Token accounting, present only when the caller asked for it.
258#[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/// The session's view of a turn, as the provider reports it.
265///
266/// Text and tool calls are separated here rather than kept in one string, so the
267/// loop never has to parse its way back out of prose.
268#[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/// Something that can fail, spelled once so every crate reports it the same way.
276#[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)]
317// Test code is exempt from the panic-shaped lints on purpose: the rules exist so
318// product code has no reachable panic path, and a test that threads Result
319// through every assertion is a worse test. Product code gets none of this.
320mod 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        // A keyless endpoint serves without a credential, and some of them
349        // reject `Authorization: Bearer ` rather than ignoring it.
350        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        // The flag rides along in the message even though the wire shape drops
412        // it, because the session file needs it and the model does not.
413        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}