meerkat-client 0.4.0

LLM provider abstraction for Meerkat
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
//! Block assembly for streaming LLM responses.
//!
//! This module provides the `BlockAssembler` for assembling ordered blocks
//! from streaming LLM events. It tracks global arrival order across all block
//! types and handles interleaved reasoning/tool-use blocks correctly.

use indexmap::IndexMap;
use meerkat_core::{AssistantBlock, ProviderMeta};
use serde_json::value::RawValue;

/// Errors that can occur during stream assembly.
/// Returned to caller, who decides whether to skip, count, or abort.
#[derive(Debug, thiserror::Error)]
pub enum StreamAssemblyError {
    #[error("delta for unknown tool call: {0}")]
    OrphanedToolDelta(String),
    #[error("delta for unknown reasoning block")]
    OrphanedReasoningDelta,
    #[error("duplicate tool call start: {0}")]
    DuplicateToolStart(String),
    #[error("complete event for unknown tool: {0}")]
    UnknownToolComplete(String),
    #[error("finalize args for unknown tool: {0}")]
    UnknownToolFinalize(String),
    #[error("invalid args JSON for tool {id}: {reason}")]
    InvalidArgsJson { id: String, reason: String },
}

/// Typed key into the block list - prevents mixing up different indices.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BlockKey(usize);

/// Represents either a finalized block or a placeholder for one still streaming.
enum BlockSlot {
    Finalized(AssistantBlock),
    Pending,
}

/// Buffer for tool call being assembled from streaming deltas.
/// Key (id) is stored in the map, not duplicated here.
struct ToolCallBuffer {
    name: Option<String>,
    args_json: String,
    block_key: BlockKey,
}

/// Buffer for reasoning block being assembled.
struct ReasoningBuffer {
    text: String,
    block_key: BlockKey,
}

/// Assembler for building ordered blocks from streaming events.
///
/// The assembler tracks **global arrival order** across all block types,
/// not just tool calls. Blocks are ordered by when they *started*, not
/// when they completed.
///
/// # Design
///
/// - `Vec<BlockSlot>` provides stable indices because we never remove elements
/// - `BlockKey(usize)` is a newtype - prevents mixing up different indices
/// - Methods return `Result<(), StreamAssemblyError>` for caller-decided policy
/// - `ToolCallBuffer` does NOT store `id` - it's the map key, avoiding duplication
/// - `Box<RawValue>` for args - no parsing in adapter
pub struct BlockAssembler {
    /// Slots are append-only to preserve start-order.
    slots: Vec<BlockSlot>,
    /// Map from tool call ID to buffer. ID is the key, not stored in value.
    tool_buffers: IndexMap<String, ToolCallBuffer>,
    /// Active reasoning block buffer.
    reasoning_buffer: Option<ReasoningBuffer>,
}

impl BlockAssembler {
    /// Create a new empty assembler.
    pub fn new() -> Self {
        Self {
            slots: Vec::new(),
            tool_buffers: IndexMap::new(),
            reasoning_buffer: None,
        }
    }

    /// Handle a text delta event.
    ///
    /// Text deltas can always succeed - no Result needed.
    /// `meta` is used by Gemini for thoughtSignature on text parts.
    pub fn on_text_delta(&mut self, delta: &str, meta: Option<Box<ProviderMeta>>) {
        if meta.is_none()
            && let Some(BlockSlot::Finalized(AssistantBlock::Text { text, meta: None })) =
                self.slots.last_mut()
        {
            text.push_str(delta);
            return;
        }
        // Insert new text block
        self.slots.push(BlockSlot::Finalized(AssistantBlock::Text {
            text: delta.into(),
            meta,
        }));
    }

    /// Start a new reasoning block.
    pub fn on_reasoning_start(&mut self) {
        let key = BlockKey(self.slots.len());
        self.slots.push(BlockSlot::Pending);
        self.reasoning_buffer = Some(ReasoningBuffer {
            text: String::new(),
            block_key: key,
        });
    }

    /// Handle a reasoning delta event.
    ///
    /// # Errors
    /// Returns `OrphanedReasoningDelta` if no reasoning block is currently being assembled.
    pub fn on_reasoning_delta(&mut self, delta: &str) -> Result<(), StreamAssemblyError> {
        let buf = self
            .reasoning_buffer
            .as_mut()
            .ok_or(StreamAssemblyError::OrphanedReasoningDelta)?;
        buf.text.push_str(delta);
        Ok(())
    }

    /// Complete the current reasoning block.
    ///
    /// Provider adapter converts raw JSON to typed `ProviderMeta` before calling.
    pub fn on_reasoning_complete(&mut self, meta: Option<Box<ProviderMeta>>) {
        if let Some(buf) = self.reasoning_buffer.take()
            && let Some(slot) = self.slots.get_mut(buf.block_key.0)
        {
            *slot = BlockSlot::Finalized(AssistantBlock::Reasoning {
                text: buf.text,
                meta,
            });
        }
        // Complete without prior start is silently ignored - provider protocol quirk
    }

    /// Return a snapshot of the current reasoning buffer text.
    /// Returns an empty string if no reasoning block is in progress.
    pub fn current_reasoning_text(&self) -> String {
        self.reasoning_buffer
            .as_ref()
            .map(|buf| buf.text.clone())
            .unwrap_or_default()
    }

    /// Start a new tool call block.
    ///
    /// # Errors
    /// Returns `DuplicateToolStart` if a tool call with the same ID is already being assembled.
    pub fn on_tool_call_start(&mut self, id: String) -> Result<(), StreamAssemblyError> {
        if self.tool_buffers.contains_key(&id) {
            return Err(StreamAssemblyError::DuplicateToolStart(id));
        }
        let key = BlockKey(self.slots.len());
        self.slots.push(BlockSlot::Pending);
        self.tool_buffers.insert(
            id,
            ToolCallBuffer {
                name: None,
                args_json: String::new(),
                block_key: key,
            },
        );
        Ok(())
    }

    /// Handle a tool call delta event.
    ///
    /// # Errors
    /// Returns `OrphanedToolDelta` if no tool call with the given ID is being assembled.
    pub fn on_tool_call_delta(
        &mut self,
        id: &str,
        name: Option<&str>,
        args_delta: &str,
    ) -> Result<(), StreamAssemblyError> {
        let buf = self
            .tool_buffers
            .get_mut(id)
            .ok_or_else(|| StreamAssemblyError::OrphanedToolDelta(id.to_string()))?;
        if let Some(n) = name {
            buf.name = Some(n.into());
        }
        buf.args_json.push_str(args_delta);
        Ok(())
    }

    /// Convert buffered args_json to RawValue. Called before on_tool_call_complete.
    ///
    /// # Errors
    /// - `UnknownToolFinalize` if no buffer exists for this ID (protocol error)
    /// - `InvalidArgsJson` if the buffered JSON is malformed
    pub fn finalize_tool_args(&self, id: &str) -> Result<Box<RawValue>, StreamAssemblyError> {
        let buf = self
            .tool_buffers
            .get(id)
            .ok_or_else(|| StreamAssemblyError::UnknownToolFinalize(id.to_string()))?;

        // Handle empty args (tools with no parameters)
        let args_str = if buf.args_json.is_empty() {
            "{}".to_string()
        } else {
            buf.args_json.clone()
        };

        RawValue::from_string(args_str).map_err(|e| StreamAssemblyError::InvalidArgsJson {
            id: id.to_string(),
            reason: e.to_string(),
        })
    }

    /// Complete a tool call block.
    ///
    /// Provider adapter converts raw JSON to typed `ProviderMeta` before calling.
    ///
    /// # Errors
    /// This method never returns an error. If no prior start exists for the ID,
    /// the tool call is inserted at the end (ordering may be off but we have the data).
    pub fn on_tool_call_complete(
        &mut self,
        id: String,
        name: String,
        args: Box<RawValue>,
        meta: Option<Box<ProviderMeta>>,
    ) -> Result<(), StreamAssemblyError> {
        if let Some((_, _, buf)) = self.tool_buffers.swap_remove_full(&id) {
            if let Some(slot) = self.slots.get_mut(buf.block_key.0) {
                *slot = BlockSlot::Finalized(AssistantBlock::ToolUse {
                    id,
                    name,
                    args,
                    meta,
                });
                return Ok(());
            }
            Ok(())
        } else {
            // No prior start - provider that doesn't emit start events
            // Insert at end; ordering may be off but we have the data
            self.slots
                .push(BlockSlot::Finalized(AssistantBlock::ToolUse {
                    id,
                    name,
                    args,
                    meta,
                }));
            Ok(())
        }
    }

    /// Finalize the assembler and return the ordered blocks.
    ///
    /// Slab iteration is in insertion order, so blocks are returned
    /// in the order they were started.
    pub fn finalize(self) -> Vec<AssistantBlock> {
        self.slots
            .into_iter()
            .filter_map(|slot| match slot {
                BlockSlot::Finalized(block) => Some(block),
                BlockSlot::Pending => None,
            })
            .collect()
    }
}

impl Default for BlockAssembler {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    // =========================================================================
    // Text delta coalescing tests
    // =========================================================================

    #[test]
    fn test_text_deltas_coalesce_into_single_block() {
        let mut assembler = BlockAssembler::new();

        assembler.on_text_delta("Hello", None);
        assembler.on_text_delta(" ", None);
        assembler.on_text_delta("World", None);

        let blocks = assembler.finalize();
        assert_eq!(blocks.len(), 1);

        match &blocks[0] {
            AssistantBlock::Text { text, meta } => {
                assert_eq!(text, "Hello World");
                assert!(meta.is_none());
            }
            _ => panic!("Expected Text block"),
        }
    }

    #[test]
    fn test_text_deltas_with_meta_do_not_coalesce() {
        let mut assembler = BlockAssembler::new();

        assembler.on_text_delta("First", None);
        assembler.on_text_delta(
            "Second",
            Some(Box::new(ProviderMeta::Gemini {
                thought_signature: "sig1".to_string(),
            })),
        );
        assembler.on_text_delta("Third", None);

        let blocks = assembler.finalize();
        assert_eq!(blocks.len(), 3);

        // First and second should not coalesce (second has meta)
        match &blocks[0] {
            AssistantBlock::Text { text, .. } => assert_eq!(text, "First"),
            _ => panic!("Expected Text block"),
        }
        match &blocks[1] {
            AssistantBlock::Text { text, meta } => {
                assert_eq!(text, "Second");
                assert!(meta.is_some());
            }
            _ => panic!("Expected Text block"),
        }
        // Third starts new block because previous has meta
        match &blocks[2] {
            AssistantBlock::Text { text, .. } => assert_eq!(text, "Third"),
            _ => panic!("Expected Text block"),
        }
    }

    // =========================================================================
    // Reasoning block tests
    // =========================================================================

    #[test]
    fn test_reasoning_start_delta_complete() {
        let mut assembler = BlockAssembler::new();

        assembler.on_reasoning_start();
        assembler.on_reasoning_delta("Let me think").unwrap();
        assembler.on_reasoning_delta("...").unwrap();
        assembler.on_reasoning_complete(Some(Box::new(ProviderMeta::Anthropic {
            signature: "sig_abc".to_string(),
        })));

        let blocks = assembler.finalize();
        assert_eq!(blocks.len(), 1);

        match &blocks[0] {
            AssistantBlock::Reasoning { text, meta } => {
                assert_eq!(text, "Let me think...");
                match meta.as_deref() {
                    Some(ProviderMeta::Anthropic { signature }) => {
                        assert_eq!(signature, "sig_abc");
                    }
                    _ => panic!("Expected Anthropic meta"),
                }
            }
            _ => panic!("Expected Reasoning block"),
        }
    }

    #[test]
    fn test_reasoning_complete_without_start_is_ignored() {
        let mut assembler = BlockAssembler::new();

        // Complete without prior start should be silently ignored
        assembler.on_reasoning_complete(None);

        let blocks = assembler.finalize();
        assert!(blocks.is_empty());
    }

    #[test]
    fn test_orphaned_reasoning_delta_returns_error() {
        let mut assembler = BlockAssembler::new();

        // Delta without prior start should error
        let result = assembler.on_reasoning_delta("orphan");
        assert!(matches!(
            result,
            Err(StreamAssemblyError::OrphanedReasoningDelta)
        ));
    }

    // =========================================================================
    // Tool call block tests
    // =========================================================================

    #[test]
    fn test_tool_call_start_delta_complete() {
        let mut assembler = BlockAssembler::new();

        assembler.on_tool_call_start("tc_1".to_string()).unwrap();
        assembler
            .on_tool_call_delta("tc_1", Some("read_file"), r#"{"pa"#)
            .unwrap();
        assembler
            .on_tool_call_delta("tc_1", None, r#"th":"#)
            .unwrap();
        assembler
            .on_tool_call_delta("tc_1", None, r#""/tmp/test"}"#)
            .unwrap();

        let args = assembler.finalize_tool_args("tc_1").unwrap();
        assembler
            .on_tool_call_complete("tc_1".to_string(), "read_file".to_string(), args, None)
            .unwrap();

        let blocks = assembler.finalize();
        assert_eq!(blocks.len(), 1);

        match &blocks[0] {
            AssistantBlock::ToolUse {
                id,
                name,
                args,
                meta,
            } => {
                assert_eq!(id, "tc_1");
                assert_eq!(name, "read_file");
                assert!(meta.is_none());
                // Parse args to verify
                let parsed: serde_json::Value = serde_json::from_str(args.get()).unwrap();
                assert_eq!(parsed["path"], "/tmp/test");
            }
            _ => panic!("Expected ToolUse block"),
        }
    }

    #[test]
    fn test_tool_call_with_gemini_meta() {
        let mut assembler = BlockAssembler::new();

        assembler.on_tool_call_start("tc_2".to_string()).unwrap();
        assembler
            .on_tool_call_delta("tc_2", Some("search"), r#"{"q":"test"}"#)
            .unwrap();

        let args = assembler.finalize_tool_args("tc_2").unwrap();
        assembler
            .on_tool_call_complete(
                "tc_2".to_string(),
                "search".to_string(),
                args,
                Some(Box::new(ProviderMeta::Gemini {
                    thought_signature: "gemini_sig".to_string(),
                })),
            )
            .unwrap();

        let blocks = assembler.finalize();
        match &blocks[0] {
            AssistantBlock::ToolUse { meta, .. } => match meta.as_deref() {
                Some(ProviderMeta::Gemini { thought_signature }) => {
                    assert_eq!(thought_signature, "gemini_sig");
                }
                _ => panic!("Expected Gemini meta"),
            },
            _ => panic!("Expected ToolUse block"),
        }
    }

    #[test]
    fn test_tool_call_complete_without_start_inserts_at_end() {
        let mut assembler = BlockAssembler::new();

        // Add some text first
        assembler.on_text_delta("Hello", None);

        // Complete without prior start - should still work
        let args = RawValue::from_string(r#"{"key":"value"}"#.to_string()).unwrap();
        assembler
            .on_tool_call_complete(
                "tc_orphan".to_string(),
                "orphan_tool".to_string(),
                args,
                None,
            )
            .unwrap();

        let blocks = assembler.finalize();
        assert_eq!(blocks.len(), 2);

        // Tool should be at end
        match &blocks[1] {
            AssistantBlock::ToolUse { id, name, .. } => {
                assert_eq!(id, "tc_orphan");
                assert_eq!(name, "orphan_tool");
            }
            _ => panic!("Expected ToolUse block"),
        }
    }

    #[test]
    fn test_duplicate_tool_start_returns_error() {
        let mut assembler = BlockAssembler::new();

        assembler.on_tool_call_start("tc_dup".to_string()).unwrap();
        let result = assembler.on_tool_call_start("tc_dup".to_string());

        assert!(matches!(
            result,
            Err(StreamAssemblyError::DuplicateToolStart(id)) if id == "tc_dup"
        ));
    }

    #[test]
    fn test_orphaned_tool_delta_returns_error() {
        let mut assembler = BlockAssembler::new();

        let result = assembler.on_tool_call_delta("unknown", Some("tool"), "{}");
        assert!(matches!(
            result,
            Err(StreamAssemblyError::OrphanedToolDelta(id)) if id == "unknown"
        ));
    }

    #[test]
    fn test_finalize_tool_args_unknown_id() {
        let assembler = BlockAssembler::new();

        let result = assembler.finalize_tool_args("unknown");
        assert!(matches!(
            result,
            Err(StreamAssemblyError::UnknownToolFinalize(id)) if id == "unknown"
        ));
    }

    #[test]
    fn test_finalize_tool_args_invalid_json() {
        let mut assembler = BlockAssembler::new();

        assembler.on_tool_call_start("tc_bad".to_string()).unwrap();
        assembler
            .on_tool_call_delta("tc_bad", Some("bad_tool"), r#"{"invalid"#)
            .unwrap();

        let result = assembler.finalize_tool_args("tc_bad");
        assert!(matches!(
            result,
            Err(StreamAssemblyError::InvalidArgsJson { id, .. }) if id == "tc_bad"
        ));
    }

    #[test]
    fn test_finalize_tool_args_empty_args() {
        let mut assembler = BlockAssembler::new();

        assembler
            .on_tool_call_start("tc_empty".to_string())
            .unwrap();
        // No deltas - empty args

        let args = assembler.finalize_tool_args("tc_empty").unwrap();
        let parsed: serde_json::Value = serde_json::from_str(args.get()).unwrap();
        assert_eq!(parsed, serde_json::json!({}));
    }

    // =========================================================================
    // Block ordering tests
    // =========================================================================

    #[test]
    fn test_block_ordering_interleaved_events() {
        let mut assembler = BlockAssembler::new();

        // Simulate interleaved stream:
        // 1. Text "Let me help"
        // 2. Reasoning starts
        // 3. Tool call starts
        // 4. Reasoning delta
        // 5. Tool call delta
        // 6. More text (should NOT coalesce with #1 - reasoning is in between)
        // 7. Reasoning complete
        // 8. Tool complete

        assembler.on_text_delta("Let me help. ", None);

        assembler.on_reasoning_start();

        assembler.on_tool_call_start("tc_1".to_string()).unwrap();

        assembler.on_reasoning_delta("thinking...").unwrap();

        assembler
            .on_tool_call_delta("tc_1", Some("search"), r#"{"q":"x"}"#)
            .unwrap();

        assembler.on_text_delta("Done!", None);

        assembler.on_reasoning_complete(Some(Box::new(ProviderMeta::Anthropic {
            signature: "sig".to_string(),
        })));

        let args = assembler.finalize_tool_args("tc_1").unwrap();
        assembler
            .on_tool_call_complete("tc_1".to_string(), "search".to_string(), args, None)
            .unwrap();

        let blocks = assembler.finalize();

        // Expected order: Text, Reasoning, ToolUse, Text
        assert_eq!(blocks.len(), 4);

        assert!(matches!(&blocks[0], AssistantBlock::Text { text, .. } if text == "Let me help. "));
        assert!(
            matches!(&blocks[1], AssistantBlock::Reasoning { text, .. } if text == "thinking...")
        );
        assert!(matches!(&blocks[2], AssistantBlock::ToolUse { name, .. } if name == "search"));
        assert!(matches!(&blocks[3], AssistantBlock::Text { text, .. } if text == "Done!"));
    }

    #[test]
    fn test_multiple_tool_calls_preserve_start_order() {
        let mut assembler = BlockAssembler::new();

        // Start two tool calls
        assembler
            .on_tool_call_start("tc_first".to_string())
            .unwrap();
        assembler
            .on_tool_call_start("tc_second".to_string())
            .unwrap();

        // Complete in reverse order
        assembler
            .on_tool_call_delta("tc_second", Some("tool_b"), r#"{}"#)
            .unwrap();
        let args2 = assembler.finalize_tool_args("tc_second").unwrap();
        assembler
            .on_tool_call_complete("tc_second".to_string(), "tool_b".to_string(), args2, None)
            .unwrap();

        assembler
            .on_tool_call_delta("tc_first", Some("tool_a"), r#"{}"#)
            .unwrap();
        let args1 = assembler.finalize_tool_args("tc_first").unwrap();
        assembler
            .on_tool_call_complete("tc_first".to_string(), "tool_a".to_string(), args1, None)
            .unwrap();

        let blocks = assembler.finalize();

        // Should be in START order, not completion order
        assert_eq!(blocks.len(), 2);
        assert!(matches!(&blocks[0], AssistantBlock::ToolUse { id, .. } if id == "tc_first"));
        assert!(matches!(&blocks[1], AssistantBlock::ToolUse { id, .. } if id == "tc_second"));
    }

    #[test]
    fn test_pending_blocks_filtered_on_finalize() {
        let mut assembler = BlockAssembler::new();

        assembler.on_text_delta("Complete text", None);
        assembler.on_reasoning_start(); // Started but never completed
        assembler
            .on_tool_call_start("tc_incomplete".to_string())
            .unwrap(); // Started but never completed

        let blocks = assembler.finalize();

        // Only the completed text block should remain
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0], AssistantBlock::Text { .. }));
    }
}