tiycore 0.2.7-rc.4

Unified LLM API and stateful Agent runtime in Rust
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
//! Unified message queue for steering and follow-up.
//!
//! Encapsulates local FIFO buffer + optional dynamic supplier into a single
//! consumption path, eliminating the inconsistency between `dequeue_*` (local
//! only) and `poll_*` (local + supplier) methods.

use crate::agent::{AbortSignal, AgentMessage, GetQueuedMessagesFn, QueueKind, QueueMode};
use parking_lot::Mutex;
use std::collections::VecDeque;

// ============================================================================
// DrainStrategy trait
// ============================================================================

/// Defines how messages are selected from the queue buffer on consumption.
///
/// Implementors decide which messages to emit and which to retain.
/// The buffer is passed mutably — the strategy should drain the messages
/// it wants to emit and leave the rest.
pub trait DrainStrategy: Send + Sync {
    /// Select messages to emit from the buffer.
    ///
    /// The implementation should remove selected messages from `buffer`
    /// and return them. Messages left in `buffer` will be available
    /// for future drain calls.
    fn select(&self, buffer: &mut VecDeque<AgentMessage>) -> Vec<AgentMessage>;

    /// Display name for diagnostics.
    fn name(&self) -> &'static str;
}

/// Built-in strategy: emit all queued messages in one batch.
#[allow(dead_code)]
pub struct DrainAll;

impl DrainStrategy for DrainAll {
    fn select(&self, buffer: &mut VecDeque<AgentMessage>) -> Vec<AgentMessage> {
        buffer.drain(..).collect()
    }

    fn name(&self) -> &'static str {
        "all"
    }
}

/// Built-in strategy: emit only the first (oldest) message.
#[allow(dead_code)]
pub struct DrainOne;

impl DrainStrategy for DrainOne {
    fn select(&self, buffer: &mut VecDeque<AgentMessage>) -> Vec<AgentMessage> {
        buffer.pop_front().into_iter().collect()
    }

    fn name(&self) -> &'static str {
        "one_at_a_time"
    }
}

/// Built-in strategy: emit up to N messages per drain.
#[allow(dead_code)]
pub struct DrainBatch {
    /// Maximum messages to emit per drain call.
    pub max: usize,
}

impl DrainStrategy for DrainBatch {
    fn select(&self, buffer: &mut VecDeque<AgentMessage>) -> Vec<AgentMessage> {
        let take = self.max.min(buffer.len());
        buffer.drain(..take).collect()
    }

    fn name(&self) -> &'static str {
        "batch"
    }
}

impl QueueMode {
    /// Convert to the corresponding built-in DrainStrategy.
    #[allow(dead_code)]
    pub(crate) fn to_strategy(self) -> Box<dyn DrainStrategy> {
        match self {
            QueueMode::All => Box::new(DrainAll),
            QueueMode::OneAtATime => Box::new(DrainOne),
        }
    }
}

// ============================================================================
// BackpressureConfig
// ============================================================================

/// Backpressure configuration for message queues.
///
/// Controls behavior when the queue depth exceeds limits.
/// Default is `Unlimited` (no restriction), preserving backward compatibility.
#[derive(Debug, Clone)]
pub struct BackpressureConfig {
    /// Maximum queue depth. 0 = unlimited (default).
    pub max_depth: usize,
    /// What to do when the limit is exceeded.
    pub overflow: OverflowBehavior,
}

impl Default for BackpressureConfig {
    fn default() -> Self {
        Self {
            max_depth: 0,
            overflow: OverflowBehavior::Unlimited,
        }
    }
}

/// Overflow behavior when backpressure limit is reached.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum OverflowBehavior {
    /// No restriction (default, backward-compatible).
    #[default]
    Unlimited,
    /// Drop oldest messages to make room for new ones.
    DropOldest,
    /// Reject new messages (caller receives error).
    Reject,
}

/// Error returned when a message is rejected due to backpressure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QueueFullError {
    /// Current queue depth at the time of rejection.
    pub current_depth: usize,
    /// Configured maximum depth.
    pub max_depth: usize,
}

impl std::fmt::Display for QueueFullError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "queue full: depth {} >= max {}",
            self.current_depth, self.max_depth
        )
    }
}

impl std::error::Error for QueueFullError {}

// ============================================================================
// MessageQueue
// ============================================================================

/// Unified message queue handle.
///
/// Each `MessageQueue` manages a local FIFO buffer. Consumption methods accept
/// an optional dynamic supplier and merge results according to [`QueueMode`].
///
/// Design invariants:
/// - `push()` is synchronous and lock-free beyond the Mutex.
/// - `drain_local()` is synchronous (for hot-path stream loop checks).
/// - `drain()` is async (calls supplier) and should be used at turn boundaries.
/// - The Mutex critical section is nanosecond-scale (VecDeque ops only).
pub(crate) struct MessageQueue {
    buffer: Mutex<VecDeque<AgentMessage>>,
    kind: QueueKind,
    backpressure: Mutex<BackpressureConfig>,
}

impl MessageQueue {
    /// Create a new empty queue.
    pub fn new(kind: QueueKind) -> Self {
        Self {
            buffer: Mutex::new(VecDeque::new()),
            kind,
            backpressure: Mutex::new(BackpressureConfig::default()),
        }
    }

    /// Returns the queue kind (Steering or FollowUp).
    #[allow(dead_code)]
    pub fn kind(&self) -> QueueKind {
        self.kind
    }

    /// Push a single message into the queue.
    pub fn push(&self, message: AgentMessage) {
        self.buffer.lock().push_back(message);
    }

    /// Push multiple messages into the queue.
    ///
    /// This bulk path intentionally bypasses backpressure. It is used to cache
    /// messages that were already produced by dynamic suppliers; callers that
    /// need backpressure enforcement should use [`MessageQueue::try_push`].
    #[allow(dead_code)]
    pub fn push_many(&self, messages: impl IntoIterator<Item = AgentMessage>) {
        let mut buf = self.buffer.lock();
        buf.extend(messages);
    }

    /// Try to push a message, respecting backpressure configuration.
    ///
    /// Returns `Ok(())` if the message was accepted, or `Err(QueueFullError)`
    /// if the queue is full and overflow behavior is `Reject`.
    ///
    /// With `DropOldest`, oldest messages are evicted to make room.
    /// With `Unlimited`, always succeeds (equivalent to `push()`).
    pub fn try_push(&self, message: AgentMessage) -> Result<(), QueueFullError> {
        let bp = self.backpressure.lock().clone();
        if bp.max_depth == 0 || bp.overflow == OverflowBehavior::Unlimited {
            // No limit
            self.buffer.lock().push_back(message);
            return Ok(());
        }

        let mut buf = self.buffer.lock();
        if buf.len() >= bp.max_depth {
            match bp.overflow {
                OverflowBehavior::Reject => {
                    return Err(QueueFullError {
                        current_depth: buf.len(),
                        max_depth: bp.max_depth,
                    });
                }
                OverflowBehavior::DropOldest => {
                    // Evict oldest to make room
                    buf.pop_front();
                }
                OverflowBehavior::Unlimited => unreachable!(),
            }
        }
        buf.push_back(message);
        Ok(())
    }

    /// Set the backpressure configuration.
    pub fn set_backpressure(&self, config: BackpressureConfig) {
        *self.backpressure.lock() = config;
    }

    /// Get the current backpressure configuration.
    #[allow(dead_code)]
    pub fn backpressure(&self) -> BackpressureConfig {
        self.backpressure.lock().clone()
    }

    /// Drain using a custom strategy (instead of QueueMode).
    ///
    /// This allows pluggable consumption logic beyond All/OneAtATime.
    #[allow(dead_code)]
    pub fn drain_with_strategy(&self, strategy: &dyn DrainStrategy) -> Vec<AgentMessage> {
        let mut buf = self.buffer.lock();
        strategy.select(&mut buf)
    }

    /// Synchronous drain from local buffer only (no supplier call).
    ///
    /// This is the fast path used in the stream event loop and sequential
    /// tool execution, where calling an async supplier would block stream
    /// processing.
    pub fn drain_local(&self, mode: QueueMode) -> Vec<AgentMessage> {
        let mut buf = self.buffer.lock();
        match mode {
            QueueMode::All => buf.drain(..).collect(),
            QueueMode::OneAtATime => {
                if let Some(first) = buf.pop_front() {
                    vec![first]
                } else {
                    Vec::new()
                }
            }
        }
    }

    /// Async drain: local buffer + dynamic supplier, merged per mode.
    ///
    /// This is the full consumption path used at turn boundaries, in
    /// `continue_()`, and in deferred steering processing.
    ///
    /// Merge semantics:
    /// - `All`: local messages first, then all supplier messages appended.
    /// - `OneAtATime`: if local has a message, return it (supplier not called).
    ///   If local is empty, call supplier and take at most 1 message.
    pub async fn drain(
        &self,
        mode: QueueMode,
        supplier: &Option<GetQueuedMessagesFn>,
        abort: AbortSignal,
    ) -> Vec<AgentMessage> {
        let local = self.drain_local(mode);

        let dynamic = match supplier {
            Some(s) if mode == QueueMode::All || local.is_empty() => s(abort).await,
            _ => Vec::new(),
        };

        match mode {
            QueueMode::All => {
                let mut merged = local;
                merged.extend(dynamic);
                merged
            }
            QueueMode::OneAtATime => {
                if !local.is_empty() {
                    // Local already yielded one message; supplier wasn't called
                    // (or mode == All which is handled above)
                    local
                } else {
                    // Take at most 1 from supplier
                    dynamic.into_iter().take(1).collect()
                }
            }
        }
    }

    /// Returns true if the local buffer is empty.
    pub fn is_empty(&self) -> bool {
        self.buffer.lock().is_empty()
    }

    /// Returns the number of messages in the local buffer.
    pub fn len(&self) -> usize {
        self.buffer.lock().len()
    }

    /// Clear all messages from the local buffer.
    pub fn clear(&self) {
        self.buffer.lock().clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::AgentMessage;
    use crate::types::UserContent;
    use std::sync::Arc;

    fn make_msg(text: &str) -> AgentMessage {
        AgentMessage::from(text)
    }

    #[test]
    fn test_push_and_drain_all() {
        let q = MessageQueue::new(QueueKind::Steering);
        q.push(make_msg("a"));
        q.push(make_msg("b"));
        q.push(make_msg("c"));

        let drained = q.drain_local(QueueMode::All);
        assert_eq!(drained.len(), 3);
        assert!(q.is_empty());
    }

    #[test]
    fn test_push_and_drain_one_at_a_time() {
        let q = MessageQueue::new(QueueKind::FollowUp);
        q.push(make_msg("a"));
        q.push(make_msg("b"));

        let drained = q.drain_local(QueueMode::OneAtATime);
        assert_eq!(drained.len(), 1);
        assert_eq!(q.len(), 1);

        let drained2 = q.drain_local(QueueMode::OneAtATime);
        assert_eq!(drained2.len(), 1);
        assert!(q.is_empty());
    }

    #[test]
    fn test_drain_local_empty() {
        let q = MessageQueue::new(QueueKind::Steering);
        let drained = q.drain_local(QueueMode::All);
        assert!(drained.is_empty());

        let drained2 = q.drain_local(QueueMode::OneAtATime);
        assert!(drained2.is_empty());
    }

    #[test]
    fn test_clear() {
        let q = MessageQueue::new(QueueKind::Steering);
        q.push(make_msg("a"));
        q.push(make_msg("b"));
        assert_eq!(q.len(), 2);

        q.clear();
        assert!(q.is_empty());
        assert_eq!(q.len(), 0);
    }

    #[test]
    fn test_push_many() {
        let q = MessageQueue::new(QueueKind::FollowUp);
        q.push_many(vec![make_msg("a"), make_msg("b"), make_msg("c")]);
        assert_eq!(q.len(), 3);
    }

    #[test]
    fn test_push_many_bypasses_backpressure() {
        let q = MessageQueue::new(QueueKind::FollowUp);
        q.set_backpressure(BackpressureConfig {
            max_depth: 1,
            overflow: OverflowBehavior::Reject,
        });

        q.push_many(vec![make_msg("a"), make_msg("b"), make_msg("c")]);
        assert_eq!(q.len(), 3);

        let err = q.try_push(make_msg("d")).unwrap_err();
        assert_eq!(err.current_depth, 3);
        assert_eq!(err.max_depth, 1);
    }

    #[tokio::test]
    async fn test_drain_with_supplier_all_mode() {
        let q = MessageQueue::new(QueueKind::Steering);
        q.push(make_msg("local"));

        let supplier: GetQueuedMessagesFn =
            Arc::new(|_signal| Box::pin(async { vec![AgentMessage::from("dynamic")] }));

        let abort = AbortSignal::new();
        let result = q.drain(QueueMode::All, &Some(supplier), abort).await;
        assert_eq!(result.len(), 2); // local + dynamic
    }

    #[tokio::test]
    async fn test_drain_one_at_a_time_local_first() {
        let q = MessageQueue::new(QueueKind::Steering);
        q.push(make_msg("local"));

        let supplier: GetQueuedMessagesFn =
            Arc::new(|_signal| Box::pin(async { vec![AgentMessage::from("dynamic")] }));

        let abort = AbortSignal::new();
        let result = q.drain(QueueMode::OneAtATime, &Some(supplier), abort).await;
        // Local has message, so supplier is NOT called; only 1 local msg returned
        assert_eq!(result.len(), 1);
    }

    #[tokio::test]
    async fn test_drain_one_at_a_time_falls_to_supplier() {
        let q = MessageQueue::new(QueueKind::Steering);
        // Local is empty

        let supplier: GetQueuedMessagesFn = Arc::new(|_signal| {
            Box::pin(async { vec![AgentMessage::from("d1"), AgentMessage::from("d2")] })
        });

        let abort = AbortSignal::new();
        let result = q.drain(QueueMode::OneAtATime, &Some(supplier), abort).await;
        // Supplier returns 2, but OneAtATime takes only 1
        assert_eq!(result.len(), 1);
    }

    #[tokio::test]
    async fn test_drain_all_with_empty_local_uses_supplier_only() {
        let q = MessageQueue::new(QueueKind::Steering);

        let supplier: GetQueuedMessagesFn =
            Arc::new(|_signal| Box::pin(async { vec![AgentMessage::from("dynamic")] }));

        let abort = AbortSignal::new();
        let result = q.drain(QueueMode::All, &Some(supplier), abort).await;
        assert_eq!(result, vec![AgentMessage::from("dynamic")]);
        assert!(q.is_empty());
    }

    #[tokio::test]
    async fn test_drain_one_at_a_time_empty_supplier_returns_empty() {
        let q = MessageQueue::new(QueueKind::Steering);

        let supplier: GetQueuedMessagesFn = Arc::new(|_signal| Box::pin(async { Vec::new() }));

        let abort = AbortSignal::new();
        let result = q.drain(QueueMode::OneAtATime, &Some(supplier), abort).await;
        assert!(result.is_empty());
        assert!(q.is_empty());
    }

    #[tokio::test]
    async fn test_drain_no_supplier() {
        let q = MessageQueue::new(QueueKind::FollowUp);
        q.push(make_msg("a"));

        let abort = AbortSignal::new();
        let result = q.drain(QueueMode::All, &None, abort).await;
        assert_eq!(result.len(), 1);
    }

    // ========== Phase 4 tests ==========

    #[test]
    fn test_drain_strategy_all() {
        let mut buf = VecDeque::from(vec![make_msg("a"), make_msg("b"), make_msg("c")]);
        let strategy = DrainAll;
        let result = strategy.select(&mut buf);
        assert_eq!(result.len(), 3);
        assert!(buf.is_empty());
    }

    #[test]
    fn test_drain_strategy_one() {
        let mut buf = VecDeque::from(vec![make_msg("a"), make_msg("b")]);
        let strategy = DrainOne;
        let result = strategy.select(&mut buf);
        assert_eq!(result.len(), 1);
        assert_eq!(buf.len(), 1);
    }

    #[test]
    fn test_drain_strategy_batch() {
        let mut buf = VecDeque::from(vec![
            make_msg("a"),
            make_msg("b"),
            make_msg("c"),
            make_msg("d"),
        ]);
        let strategy = DrainBatch { max: 2 };
        let result = strategy.select(&mut buf);
        assert_eq!(result.len(), 2);
        assert_eq!(buf.len(), 2);
    }

    #[test]
    fn test_drain_with_strategy() {
        let q = MessageQueue::new(QueueKind::Steering);
        q.push_many(vec![make_msg("a"), make_msg("b"), make_msg("c")]);

        let strategy = DrainBatch { max: 2 };
        let result = q.drain_with_strategy(&strategy);
        assert_eq!(result.len(), 2);
        assert_eq!(q.len(), 1);
    }

    #[test]
    fn test_backpressure_unlimited() {
        let q = MessageQueue::new(QueueKind::Steering);
        // Default is unlimited
        for i in 0..1000 {
            assert!(q.try_push(make_msg(&format!("msg{}", i))).is_ok());
        }
        assert_eq!(q.len(), 1000);
    }

    #[test]
    fn test_backpressure_reject() {
        let q = MessageQueue::new(QueueKind::Steering);
        q.set_backpressure(BackpressureConfig {
            max_depth: 3,
            overflow: OverflowBehavior::Reject,
        });

        assert!(q.try_push(make_msg("a")).is_ok());
        assert!(q.try_push(make_msg("b")).is_ok());
        assert!(q.try_push(make_msg("c")).is_ok());
        // Queue is full
        let err = q.try_push(make_msg("d")).unwrap_err();
        assert_eq!(err.current_depth, 3);
        assert_eq!(err.max_depth, 3);
        assert_eq!(q.len(), 3);
    }

    #[test]
    fn test_backpressure_drop_oldest() {
        let q = MessageQueue::new(QueueKind::Steering);
        q.set_backpressure(BackpressureConfig {
            max_depth: 3,
            overflow: OverflowBehavior::DropOldest,
        });

        assert!(q.try_push(make_msg("a")).is_ok());
        assert!(q.try_push(make_msg("b")).is_ok());
        assert!(q.try_push(make_msg("c")).is_ok());
        // This should succeed, dropping "a"
        assert!(q.try_push(make_msg("d")).is_ok());
        assert_eq!(q.len(), 3);

        // Drain and verify oldest was dropped, remainder order preserved
        let msgs = q.drain_local(QueueMode::All);
        assert_eq!(msgs.len(), 3);
        let texts: Vec<&str> = msgs
            .iter()
            .filter_map(|m| match m {
                AgentMessage::User(u) => match &u.content {
                    UserContent::Text(t) => Some(t.as_str()),
                    _ => None,
                },
                _ => None,
            })
            .collect();
        assert_eq!(texts, vec!["b", "c", "d"]);
    }

    #[test]
    fn test_queue_mode_to_strategy() {
        let mut buf = VecDeque::from(vec![make_msg("a"), make_msg("b")]);
        let strategy = QueueMode::All.to_strategy();
        let result = strategy.select(&mut buf);
        assert_eq!(result.len(), 2);

        let mut buf2 = VecDeque::from(vec![make_msg("x"), make_msg("y")]);
        let strategy2 = QueueMode::OneAtATime.to_strategy();
        let result2 = strategy2.select(&mut buf2);
        assert_eq!(result2.len(), 1);
        assert_eq!(buf2.len(), 1);
    }
}