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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//! The loop, and the two traits it drives.
//!
//! Neither trait knows anything about the world outside the process. A provider
//! takes history and a tool list and produces a turn; a tool takes arguments and
//! produces a string. Everything that touches a socket, a filesystem, or a
//! terminal lives behind them, which is what keeps the loop testable without a
//! network or a mock crate.

use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};

use serde_json::Value;

use crate::{AssistantToolCall, Message, Result, ToolDef, Turn};

/// Somewhere for streamed text to go as it arrives.
///
/// A trait rather than a channel so the loop does not need a runtime, and so a
/// caller that wants nothing can pass a sink that discards.
pub trait TextSink: Send {
    /// Called with each text fragment, in order, as the model produces it.
    fn text(&mut self, delta: &str);
}

/// A sink that throws the text away. Useful for tests and for non-interactive runs.
#[derive(Clone, Copy, Debug, Default)]
pub struct DiscardSink;

impl TextSink for DiscardSink {
    fn text(&mut self, _delta: &str) {}
}

/// Something that can turn a conversation into a turn.
///
/// `tools` is what the model is allowed to ask for on this request, which is how
/// a tool registered mid-session reaches the next turn without the loop knowing
/// anything about registration.
#[async_trait::async_trait]
pub trait Provider: Send + Sync {
    /// `system` is the prompt that precedes the conversation. It is an argument
    /// rather than a message in `history` so it is rebuilt for every request and
    /// never written to the session file.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::Provider`] for transport failures and
    /// [`crate::Error::Malformed`] when the response cannot be read.
    async fn send(
        &self,
        system: &str,
        history: &[Message],
        tools: &[ToolDef],
        sink: &mut (dyn TextSink + Send),
    ) -> Result<Turn>;
}

/// The models one endpoint advertises, and a client for each.
///
/// An interface that can switch models needs both: the picker lists
/// [`ModelCatalog::catalog`], and a switch builds a client through
/// [`ModelCatalog::provider`]. Building a client is above `yk-core` (`OpenAiClient` lives in
/// `yk-provider`), which is why this is a trait rather than a struct.
pub trait ModelCatalog: Send + Sync {
    /// What the endpoint said it can serve.
    ///
    /// Empty is the normal answer for an endpoint with no catalog route and for
    /// one whose key cannot see it. It costs a picker and nothing else.
    fn catalog(&self) -> &[String];

    /// The model the run was configured with.
    ///
    /// The answer for a session that records none, so a new conversation starts
    /// on the configured model rather than on one a previous session switched
    /// to.
    fn default_model(&self) -> &str;

    /// A client for `model`.
    ///
    /// # Errors
    ///
    /// [`crate::Error::Provider`] when the client cannot be built.
    fn provider(&self, model: &str) -> Result<Box<dyn Provider>>;
}

/// A tool the loop can call.
#[async_trait::async_trait]
pub trait Tool: Send + Sync {
    /// The name, description, and argument schema the model sees.
    fn def(&self) -> ToolDef;

    /// # Errors
    ///
    /// Implementations return [`crate::Error::BadArgs`] when the arguments do
    /// not match the schema and [`crate::Error::Tool`] when the work itself
    /// failed. Both are reported back to the model as an ordinary tool result,
    /// because a model can recover from an error but not from a dead process.
    async fn run(&self, args: &Value) -> Result<String>;
}

/// Messages the user submitted while a turn was running.
///
/// The loop drains this before each request, so a message typed during a long
/// answer reaches the model on the next request rather than waiting for the turn
/// to end.
///
/// A lock rather than a channel, because the queue is read and written on one
/// task and a lock is the smallest thing that lets the interface push while the
/// loop drains.
#[derive(Debug, Default)]
pub struct SteeringQueue {
    messages: Mutex<Vec<String>>,
}

impl SteeringQueue {
    /// Queue a message for the next request.
    pub fn push(&self, message: impl Into<String>) {
        self.lock().push(message.into());
    }

    /// Take everything queued so far.
    fn drain(&self) -> Vec<String> {
        std::mem::take(&mut *self.lock())
    }

    /// Whether a message is waiting.
    fn is_pending(&self) -> bool {
        !self.lock().is_empty()
    }

    /// The queue, taking a poisoned lock rather than propagating the panic.
    ///
    /// A poisoned lock means a thread panicked while holding it. The queue is a
    /// convenience, so dropping the message beats propagating the panic.
    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<String>> {
        self.messages
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
}

/// The agent loop.
///
/// It holds no state beyond its collaborators, so one `Agent` can serve many
/// conversations and a conversation can be resumed by rebuilding it from the
/// session file.
pub struct Agent<'a> {
    provider: &'a dyn Provider,
    tools: &'a [&'a dyn Tool],
    system: &'a str,
}

impl<'a> Agent<'a> {
    #[must_use]
    pub const fn new(
        provider: &'a dyn Provider,
        tools: &'a [&'a dyn Tool],
        system: &'a str,
    ) -> Self {
        Self {
            provider,
            tools,
            system,
        }
    }

    /// What the model is told it may call on any request.
    #[must_use]
    pub fn tool_defs(&self) -> Vec<ToolDef> {
        self.tools.iter().map(|tool| tool.def()).collect()
    }

    /// Runs until the model stops asking for tools, or until `stop` is raised.
    ///
    /// `history` is the live conversation and is appended to in place, so a
    /// caller can persist it after every call rather than only at the end.
    ///
    /// `stop` is checked between model requests and between tool calls, which is
    /// where a turn can be interrupted without unwinding through the provider. It
    /// is the difference between a cancel that ends a turn and one that merely
    /// poisons the tools: without it a cancel is fed back to the model as a tool
    /// error and the model tries again, one refusal at a time, for a turn the user
    /// already called off.
    ///
    /// The ceiling: the flag is not consulted mid-stream, so cancelling a long
    /// answer still waits for it to finish. Checking it inside `send` would mean
    /// aborting the provider future, which is a different contract for `Provider`
    /// and buys nothing until a client reports progress finely enough to want it.
    ///
    /// `steering_queue` carries messages submitted while the turn was running. They are
    /// drained before each request, so a message typed during a long answer
    /// reaches the model on the next one.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::Provider`] if the model cannot be reached. A tool
    /// that fails does not end the run; its failure is reported back to the model
    /// as a result, which is the difference between a tool error and an outage.
    pub async fn run(
        &self,
        history: &mut Vec<Message>,
        sink: &mut (dyn TextSink + Send),
        stop: &AtomicBool,
        steering_queue: &SteeringQueue,
    ) -> Result<()> {
        loop {
            if stop.load(Ordering::Relaxed) {
                return Ok(());
            }

            for message in steering_queue.drain() {
                history.push(Message::user(message));
            }

            let defs = self.tool_defs();
            let turn = self
                .provider
                .send(self.system, history, &defs, sink)
                .await?;

            history.push(Message::assistant_with_calls(
                turn.text.clone(),
                turn.tool_calls.clone(),
            ));

            if turn.tool_calls.is_empty() {
                // A message queued while the answer streamed still deserves a
                // reply, so the run continues rather than ending here.
                if !steering_queue.is_pending() {
                    return Ok(());
                }
                continue;
            }

            for call in &turn.tool_calls {
                history.push(self.run_tool_call(call).await.to_message());

                if stop.load(Ordering::Relaxed) {
                    return Ok(());
                }
            }
        }
    }

    /// Runs one call and wraps the outcome, so an error reaches the model as a
    /// result rather than as a failed run.
    async fn run_tool_call(&self, call: &AssistantToolCall) -> crate::ToolResult {
        let Some(tool) = self.tools.iter().find(|t| t.def().name == call.name) else {
            return crate::ToolResult::err(
                &call.id,
                format!("no tool named `{}` is registered", call.name),
            );
        };

        let args = match parse_args(call) {
            Ok(args) => args,
            Err(reason) => {
                return crate::ToolResult::err(
                    &call.id,
                    format!("`{}` arguments were not valid json: {reason}", call.name),
                );
            }
        };

        match tool.run(&args).await {
            Ok(output) => crate::ToolResult::ok(&call.id, output),
            Err(error) => crate::ToolResult::err(&call.id, error.to_string()),
        }
    }
}

/// The model sends arguments as a string, and an empty string means `{}` rather
/// than a parse failure. Models emit both for a no-argument tool.
fn parse_args(call: &AssistantToolCall) -> Result<Value, String> {
    let trimmed = call.arguments.trim();
    if trimmed.is_empty() {
        return Ok(Value::Object(serde_json::Map::new()));
    }
    serde_json::from_str(trimmed).map_err(|error| error.to_string())
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::indexing_slicing,
        clippy::as_conversions,
        clippy::arithmetic_side_effects,
        clippy::too_many_lines
    )]

    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, Mutex};

    use serde_json::{Value, json};

    use super::{Agent, DiscardSink, Provider, SteeringQueue, TextSink, Tool, parse_args};
    use crate::{AssistantToolCall, Error, Message, Result, ToolDef, Turn};

    /// A stop flag nobody raises.
    fn never() -> AtomicBool {
        AtomicBool::new(false)
    }

    /// Answers with scripted turns and records what history it was handed.
    struct Scripted {
        turns: Mutex<Vec<Turn>>,
        seen: Mutex<Vec<Vec<Message>>>,
        seen_tools: Mutex<Vec<String>>,
        seen_system: Mutex<Vec<String>>,
    }

    impl Scripted {
        fn new(turns: Vec<Turn>) -> Self {
            Self {
                turns: Mutex::new(turns),
                seen: Mutex::new(Vec::new()),
                seen_tools: Mutex::new(Vec::new()),
                seen_system: Mutex::new(Vec::new()),
            }
        }
    }

    #[async_trait::async_trait]
    impl Provider for Scripted {
        async fn send(
            &self,
            system: &str,
            history: &[Message],
            tools: &[ToolDef],
            _sink: &mut (dyn TextSink + Send),
        ) -> Result<Turn> {
            self.seen_system
                .lock()
                .expect("lock")
                .push(system.to_owned());
            self.seen.lock().expect("lock").push(history.to_vec());
            self.seen_tools
                .lock()
                .expect("lock")
                .extend(tools.iter().map(|t| t.name.clone()));

            let mut turns = self.turns.lock().expect("lock");
            if turns.is_empty() {
                return Ok(Turn::default());
            }
            Ok(turns.remove(0))
        }
    }

    struct Echo;

    #[async_trait::async_trait]
    impl Tool for Echo {
        fn def(&self) -> ToolDef {
            ToolDef {
                name: "echo".to_owned(),
                description: "Echo the input".to_owned(),
                schema: json!({"type": "object"}),
            }
        }

        async fn run(&self, args: &Value) -> Result<String> {
            args.get("text")
                .map(ToString::to_string)
                .ok_or_else(|| Error::BadArgs {
                    tool: "echo".to_owned(),
                    reason: "missing text".to_owned(),
                })
        }
    }

    struct AlwaysFails;

    #[async_trait::async_trait]
    impl Tool for AlwaysFails {
        fn def(&self) -> ToolDef {
            ToolDef {
                name: "boom".to_owned(),
                description: "Always fails".to_owned(),
                schema: json!({"type": "object"}),
            }
        }

        async fn run(&self, _args: &Value) -> Result<String> {
            Err(Error::Tool {
                tool: "boom".to_owned(),
                reason: "deliberate".to_owned(),
            })
        }
    }

    fn call(id: &str, name: &str, arguments: &str) -> AssistantToolCall {
        AssistantToolCall {
            id: id.to_owned(),
            name: name.to_owned(),
            arguments: arguments.to_owned(),
        }
    }

    #[tokio::test]
    async fn a_turn_with_no_tool_calls_ends_the_run() {
        let provider = Scripted::new(vec![Turn {
            text: "done".to_owned(),
            ..Turn::default()
        }]);
        let agent = Agent::new(&provider, &[], "");
        let mut history = vec![Message::user("hi")];

        agent
            .run(
                &mut history,
                &mut DiscardSink,
                &never(),
                &SteeringQueue::default(),
            )
            .await
            .expect("runs");

        assert_eq!(history.len(), 2);
        assert_eq!(history[1], Message::assistant("done"));
    }

    #[tokio::test]
    async fn the_system_prompt_reaches_the_provider() {
        let provider = Scripted::new(vec![Turn::default()]);
        let agent = Agent::new(&provider, &[], "you are yk");
        let mut history = vec![Message::user("hi")];

        agent
            .run(
                &mut history,
                &mut DiscardSink,
                &never(),
                &SteeringQueue::default(),
            )
            .await
            .expect("runs");

        assert_eq!(
            provider.seen_system.lock().expect("lock").as_slice(),
            ["you are yk"]
        );
    }

    #[tokio::test]
    async fn a_queued_message_reaches_the_next_request() {
        let provider = Scripted::new(vec![Turn::default()]);
        let steering_queue = SteeringQueue::default();
        steering_queue.push("one more thing");
        let agent = Agent::new(&provider, &[], "");
        let mut history = vec![Message::user("first")];

        agent
            .run(&mut history, &mut DiscardSink, &never(), &steering_queue)
            .await
            .expect("runs");

        let reached = provider
            .seen
            .lock()
            .expect("lock")
            .first()
            .is_some_and(|first| {
                first
                    .iter()
                    .any(|message| message.text() == "one more thing")
            });
        assert!(reached, "the queued message did not reach the request");
    }

    #[tokio::test]
    async fn a_tool_result_is_fed_back_and_the_loop_continues() {
        let provider = Scripted::new(vec![
            Turn {
                text: String::new(),
                tool_calls: vec![call("c1", "echo", r#"{"text":"hi"}"#)],
                usage: None,
            },
            Turn {
                text: "all done".to_owned(),
                ..Turn::default()
            },
        ]);
        let echo = Echo;
        let tools: [&dyn Tool; 1] = [&echo];
        let agent = Agent::new(&provider, &tools, "");
        let mut history = vec![Message::user("say hi")];

        agent
            .run(
                &mut history,
                &mut DiscardSink,
                &never(),
                &SteeringQueue::default(),
            )
            .await
            .expect("runs");

        assert_eq!(
            history[2],
            Message::tool("c1", "\"hi\""),
            "the tool output should come back to the model"
        );
        assert_eq!(history[3], Message::assistant("all done"));

        // The second request must have carried the tool result.
        let seen = provider.seen.lock().expect("lock");
        assert_eq!(seen.len(), 2);
        assert_eq!(seen[1].len(), 3);
    }

    #[tokio::test]
    async fn a_failing_tool_reaches_the_model_as_an_error_result() {
        let provider = Scripted::new(vec![
            Turn {
                text: String::new(),
                tool_calls: vec![call("c1", "boom", "{}")],
                usage: None,
            },
            Turn {
                text: "recovered".to_owned(),
                ..Turn::default()
            },
        ]);
        let boom = AlwaysFails;
        let tools: [&dyn Tool; 1] = [&boom];
        let agent = Agent::new(&provider, &tools, "");
        let mut history = vec![Message::user("go")];

        agent
            .run(
                &mut history,
                &mut DiscardSink,
                &never(),
                &SteeringQueue::default(),
            )
            .await
            .expect("a tool failure must not end the run");

        assert!(
            history[2].text().contains("deliberate"),
            "the model should see why: {:?}",
            history[2]
        );
        assert_eq!(history[3], Message::assistant("recovered"));
    }

    #[tokio::test]
    async fn an_unknown_tool_becomes_an_error_result_rather_than_a_panic() {
        let provider = Scripted::new(vec![
            Turn {
                text: String::new(),
                tool_calls: vec![call("c1", "ghost", "{}")],
                usage: None,
            },
            Turn::default(),
        ]);
        let agent = Agent::new(&provider, &[], "");
        let mut history = vec![Message::user("go")];

        agent
            .run(
                &mut history,
                &mut DiscardSink,
                &never(),
                &SteeringQueue::default(),
            )
            .await
            .expect("runs");

        assert!(history[2].text().contains("ghost"));
    }

    #[tokio::test]
    async fn malformed_arguments_become_an_error_result() {
        let provider = Scripted::new(vec![
            Turn {
                text: String::new(),
                tool_calls: vec![call("c1", "echo", "{not json")],
                usage: None,
            },
            Turn::default(),
        ]);
        let echo = Echo;
        let tools: [&dyn Tool; 1] = [&echo];
        let agent = Agent::new(&provider, &tools, "");
        let mut history = vec![Message::user("go")];

        agent
            .run(
                &mut history,
                &mut DiscardSink,
                &never(),
                &SteeringQueue::default(),
            )
            .await
            .expect("runs");

        assert!(history[2].text().contains("not valid json"));
    }

    #[tokio::test]
    async fn every_request_carries_the_registered_tools() {
        let provider = Scripted::new(vec![Turn::default()]);
        let echo = Echo;
        let tools: [&dyn Tool; 1] = [&echo];
        let agent = Agent::new(&provider, &tools, "");
        let mut history = vec![Message::user("hi")];

        agent
            .run(
                &mut history,
                &mut DiscardSink,
                &never(),
                &SteeringQueue::default(),
            )
            .await
            .expect("runs");

        let seen = provider.seen_tools.lock().expect("lock");
        assert_eq!(seen.as_slice(), ["echo"]);
    }

    #[tokio::test]
    async fn a_raised_stop_ends_the_run_before_the_next_request() {
        // The regression this guards. Cancelling without a stop signal feeds the
        // refusal back to the model, and the model asks again, so the turn runs
        // to completion on a user who already called it off.
        let provider = Scripted::new(vec![
            Turn {
                text: String::new(),
                tool_calls: vec![call("c1", "echo", r#"{"text":"hi"}"#)],
                usage: None,
            },
            Turn::default(),
            Turn::default(),
        ]);
        let echo = Echo;
        let tools: [&dyn Tool; 1] = [&echo];
        let agent = Agent::new(&provider, &tools, "");
        let mut history = vec![Message::user("go")];
        let stop = AtomicBool::new(true);

        agent
            .run(
                &mut history,
                &mut DiscardSink,
                &stop,
                &SteeringQueue::default(),
            )
            .await
            .expect("a cancelled turn is not an error");

        assert_eq!(history.len(), 1, "the model was asked anyway: {history:?}");
        assert_eq!(provider.seen.lock().expect("lock").len(), 0);
    }

    #[tokio::test]
    async fn a_stop_raised_mid_turn_stops_before_the_next_tool() {
        // One flag serves both checks: a client that cancels at the permission
        // prompt must not watch the rest of the model's tool calls run anyway.
        struct Raiser(Arc<AtomicBool>);

        #[async_trait::async_trait]
        impl Tool for Raiser {
            fn def(&self) -> ToolDef {
                ToolDef {
                    name: "echo".to_owned(),
                    description: "Raise the stop flag".to_owned(),
                    schema: json!({"type": "object"}),
                }
            }

            async fn run(&self, _args: &Value) -> Result<String> {
                self.0.store(true, Ordering::Relaxed);
                Ok("raised".to_owned())
            }
        }

        let provider = Scripted::new(vec![Turn {
            text: String::new(),
            tool_calls: vec![
                call("c1", "echo", r#"{"text":"a"}"#),
                call("c2", "echo", r#"{"text":"b"}"#),
            ],
            usage: None,
        }]);
        let stop = Arc::new(AtomicBool::new(false));
        let raiser = Raiser(Arc::clone(&stop));
        let tools: [&dyn Tool; 1] = [&raiser];
        let agent = Agent::new(&provider, &tools, "");
        let mut history = vec![Message::user("go")];

        agent
            .run(
                &mut history,
                &mut DiscardSink,
                &stop,
                &SteeringQueue::default(),
            )
            .await
            .expect("runs");

        assert_eq!(
            history.len(),
            3,
            "the second tool call ran after the cancel: {history:?}"
        );
    }

    #[test]
    fn empty_arguments_mean_an_empty_object() {
        let parsed = parse_args(&call("c1", "echo", "   ")).expect("parses");
        assert_eq!(parsed, json!({}));
    }

    #[test]
    fn the_argument_string_is_parsed_as_json() {
        let parsed = parse_args(&call("c1", "echo", r#"{"a":1}"#)).expect("parses");
        assert_eq!(parsed, json!({"a": 1}));
    }
}