yk-core 0.1.0

The agent loop and the vocabulary every other crate speaks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! The agent loop, and the vocabulary every other crate in the workspace speaks.
//!
//! Nothing here knows about a terminal, an HTTP client, or a file format. If a
//! change makes this crate aware of any of those, it has leaked.
//!
//! The vocabulary is deliberately wider than what the first months need. A tool
//! call has to survive three round trips: out to the model, back from it, and
//! out again with the result attached, and a shape that cannot express that
//! means rewriting the session format later.

mod agent;
mod compact;

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Identifier for an entry in a session tree.
pub type Id = String;

/// One message in the conversation, as it goes to and from the model.
///
/// The wire shape is the provider's business, not ours. This is the vocabulary,
/// and it keeps tool results as a first-class message rather than as text glued
/// into an assistant turn, because the model has to be able to tell them apart.
#[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,
        /// Whether the tool failed.
        ///
        /// Not serialised: the provider's tool message has no such field, and
        /// sending one is at best ignored and at worst rejected. The session file
        /// records it separately, so resuming a session knows a result was an
        /// error even though the model was never told in so many words.
        #[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,
        }
    }

    /// The prose, with tool results included and tool calls not.
    #[must_use]
    pub fn text(&self) -> &str {
        match self {
            Self::User { content }
            | Self::Assistant { content, .. }
            | Self::Tool { content, .. } => content,
        }
    }

    /// Which side of the conversation this message came from.
    #[must_use]
    pub const fn role(&self) -> Role {
        match self {
            Self::User { .. } => Role::User,
            Self::Assistant { .. } => Role::Assistant,
            Self::Tool { .. } => Role::Tool,
        }
    }
}

/// Which side of the conversation a message came from.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    User,
    Assistant,
    Tool,
}

impl Role {
    /// The label the provider and the transcript use for this 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()
    }
}

/// A tool call as the model emitted it. Argument text arrives as fragments and
/// is assembled elsewhere; by the time it reaches the loop it is one string.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct AssistantToolCall {
    pub id: String,
    pub name: String,
    pub arguments: String,
}

/// A model the agent can talk to.
///
/// The base URL is configuration rather than a branch, which is why there is no
/// provider registry anywhere in this workspace. `OpenRouter` serves every vendor
/// through this one shape, and a local server is a different string.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ModelConfig {
    /// Identifier as the endpoint names it, such as `anthropic/claude-sonnet-4`.
    pub model: String,
    /// Endpoint root, such as `https://openrouter.ai/api/v1`.
    pub base_url: String,
    /// Bearer token. Never logged, never written into a session file.
    ///
    /// Blank means the endpoint serves without one, which is what a local
    /// `Ollama` or `vLLM` does. Use [`Self::bearer_token`] rather than reading
    /// this field: it is the one place that decides whether a blank key is a
    /// credential or the absence of one.
    pub api_key: String,
    /// Headers sent with every request to this endpoint, by name.
    ///
    /// Some gateways refuse a request that does not identify the client or the
    /// conversation it belongs to, and the header they want is not one yk would
    /// send on its own. Empty for an endpoint that wants nothing beyond the
    /// credential, which is every endpoint yk points at by default.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub headers: Vec<(String, String)>,
}

impl ModelConfig {
    /// The credential to send, or `None` when there is none to send.
    ///
    /// Blank and absent are the same state. A keyless endpoint rejects
    /// `Authorization: Bearer ` outright on some servers, so the header is left
    /// off entirely rather than sent empty.
    #[must_use]
    pub fn bearer_token(&self) -> Option<&str> {
        let token = self.api_key.trim();
        (!token.is_empty()).then_some(token)
    }

    /// The URL a chat completion is posted to.
    #[must_use]
    pub fn completions_url(&self) -> String {
        format!("{}/chat/completions", self.base_url.trim_end_matches('/'))
    }

    /// The URL that lists what the endpoint can serve.
    ///
    /// Part of the same `OpenAI` shape, so it is derived rather than configured.
    /// An endpoint without this route is not an error: the caller falls back to
    /// the configured model and carries on with no picker.
    #[must_use]
    pub fn models_url(&self) -> String {
        format!("{}/models", self.base_url.trim_end_matches('/'))
    }
}

/// One tool as the provider describes it.
///
/// Built-in tools and tools registered by a `Lua` extension are both this.
/// Keeping one type is what makes it cheap: registering a tool is a map insert,
/// because nothing downstream can tell the difference.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ToolDef {
    pub name: String,
    pub description: String,
    /// JSON Schema for the arguments object, as a `Value` because it came from
    /// one.
    pub schema: Value,
}

/// The outcome of one tool call, as recorded in the session.
#[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,
        }
    }

    /// The message to feed back to the model.
    #[must_use]
    pub fn to_message(&self) -> Message {
        Message::tool_result(self.call_id.clone(), self.output.clone(), self.is_error)
    }
}

/// Token accounting, present only when the caller asked for it.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct Usage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
}

/// The session's view of a turn, as the provider reports it.
///
/// Text and tool calls are separated here rather than kept in one string, so the
/// loop never has to parse its way back out of prose.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct Turn {
    pub text: String,
    pub tool_calls: Vec<AssistantToolCall>,
    pub usage: Option<Usage>,
}

/// Something that can fail, spelled once so every crate reports it the same way.
#[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)]
// Test code is exempt from the panic-shaped lints on purpose: the rules exist so
// product code has no reachable panic path, and a test that threads Result
// through every assertion is a worse test. Product code gets none of this.
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() {
        // A keyless endpoint serves without a credential, and some of them
        // reject `Authorization: Bearer ` rather than ignoring it.
        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");

        // The flag rides along in the message even though the wire shape drops
        // it, because the session file needs it and the model does not.
        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")
        );
    }
}