eclipse-core 0.13.4

Core library for eclipse: providers, tools, sessions, config, runtime
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
//! Server-sent-events parsing and assembly of streamed chat-completion chunks.
//!
//! Pure and synchronous: bytes go in, events and a final [`Message`] come out, so the
//! parsing is testable without any network.

use crate::error::{Error, ProviderFailure, Result};
use crate::message::{FunctionCall, Message, ToolCall};
use serde_json::Value;
use std::collections::BTreeMap;

/// One piece of a reply as it arrives.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Delta {
    /// Assistant text.
    Text(String),
    /// Reasoning/thinking text emitted by a backend that streams it.
    Reasoning(String),
    /// A fragment of a tool call's JSON arguments, tagged with its call index.
    ToolCallArgs { index: u64, json: String },
}

/// Receives each piece of the reply as it arrives.
pub type DeltaFn<'a> = &'a (dyn Fn(Delta) + Send + Sync);

/// Incremental SSE decoder. Feed it raw bytes in arbitrary chunks (a chunk may end in
/// the middle of a line or of a UTF-8 character); it returns each completed event's
/// `data` payload.
#[derive(Default)]
pub struct SseParser {
    buf: Vec<u8>,
    data: Vec<String>,
}

impl SseParser {
    pub fn push(&mut self, bytes: &[u8]) -> Vec<String> {
        self.buf.extend_from_slice(bytes);
        let mut events = Vec::new();
        while let Some(nl) = self.buf.iter().position(|b| *b == b'\n') {
            let line: Vec<u8> = self.buf.drain(..=nl).collect();
            self.line(&line[..line.len() - 1], &mut events);
        }
        events
    }

    /// Flush at end of stream: a final line or event that lacks its terminating newline
    /// is still delivered (an incomplete JSON payload is rejected later by the caller).
    pub fn finish(&mut self) -> Vec<String> {
        let mut events = Vec::new();
        if !self.buf.is_empty() {
            let rest = std::mem::take(&mut self.buf);
            self.line(&rest, &mut events);
        }
        self.line(b"", &mut events);
        events
    }

    fn line(&mut self, raw: &[u8], events: &mut Vec<String>) {
        let line = raw.strip_suffix(b"\r").unwrap_or(raw);
        if line.is_empty() {
            if !self.data.is_empty() {
                events.push(self.data.join("\n"));
                self.data.clear();
            }
            return;
        }
        if line[0] == b':' {
            return;
        }
        let (field, value) = match line.iter().position(|b| *b == b':') {
            Some(i) => (&line[..i], &line[i + 1..]),
            None => (line, &b""[..]),
        };
        if field == b"data" {
            let value = value.strip_prefix(b" ").unwrap_or(value);
            self.data.push(String::from_utf8_lossy(value).into_owned());
        }
    }
}

#[derive(Default)]
struct PartialCall {
    id: String,
    name: String,
    arguments: String,
}

/// Folds `chat.completion.chunk` payloads into one assistant message.
#[derive(Default)]
pub struct StreamAccumulator {
    content: String,
    reasoning: String,
    finish_reason: Option<String>,
    calls: BTreeMap<u64, PartialCall>,
    finished: bool,
    /// Whatever the stream said about cost: a trailing `usage` chunk (OpenAI) and/or
    /// `timings` (llama.cpp). Kept as a body so [`crate::usage::TurnUsage`] parses it the
    /// same way it parses a non-streaming reply.
    usage: Value,
}

impl StreamAccumulator {
    /// Handle one SSE `data` payload, reporting any text through `on_delta`.
    pub fn push_event(&mut self, data: &str, on_delta: DeltaFn<'_>) -> Result<()> {
        let data = data.trim();
        if data.is_empty() {
            return Ok(());
        }
        if data == "[DONE]" {
            self.finished = true;
            return Ok(());
        }
        let chunk: Value = serde_json::from_str(data).map_err(|e| {
            Error::Provider(ProviderFailure::Response {
                message: format!("malformed stream chunk: {e}"),
                body: Some(data.chars().take(300).collect()),
            })
        })?;
        if let Some(err) = chunk.get("error").filter(|e| !e.is_null()) {
            // A server that reports trouble inside the stream instead of with a status.
            return Err(Error::Provider(ProviderFailure::Response {
                message: format!("the server reported an error mid-stream: {err}"),
                body: Some(data.chars().take(300).collect()),
            }));
        }
        // Cost lands on chunks that carry no text at all — usually the last one.
        for key in ["usage", "timings"] {
            if let Some(v) = chunk.get(key).filter(|v| !v.is_null()) {
                self.usage[key] = v.clone();
            }
        }
        let Some(choice) = chunk.pointer("/choices/0") else {
            return Ok(()); // e.g. a trailing usage-only chunk
        };
        if let Some(text) = choice
            .pointer("/delta/content")
            .and_then(Value::as_str)
            .filter(|t| !t.is_empty())
        {
            self.content.push_str(text);
            on_delta(Delta::Text(text.to_string()));
        }
        if let Some(reasoning) = choice
            .pointer("/delta/reasoning_content")
            .and_then(Value::as_str)
            .filter(|t| !t.is_empty())
        {
            self.reasoning.push_str(reasoning);
            on_delta(Delta::Reasoning(reasoning.to_string()));
        }
        if let Some(calls) = choice
            .pointer("/delta/tool_calls")
            .and_then(Value::as_array)
        {
            for call in calls {
                self.push_tool_call(call, on_delta);
            }
        }
        if let Some(f) = choice
            .get("finish_reason")
            .and_then(Value::as_str)
            .filter(|f| !f.is_empty())
        {
            self.finish_reason = Some(f.to_string());
            self.finished = true;
        }
        Ok(())
    }

    fn push_tool_call(&mut self, call: &Value, on_delta: DeltaFn<'_>) {
        let id = call.get("id").and_then(Value::as_str).unwrap_or("");
        // Some servers omit `index`; a fresh id then starts a new call and anything
        // else continues the latest one.
        let index = match call.get("index").and_then(Value::as_u64) {
            Some(i) => i,
            None => match self.calls.keys().next_back() {
                Some(last) if id.is_empty() => *last,
                Some(last) => last + 1,
                None => 0,
            },
        };
        let entry = self.calls.entry(index).or_default();
        if entry.id.is_empty() {
            entry.id = id.to_string();
        }
        if let Some(name) = call.pointer("/function/name").and_then(Value::as_str) {
            if entry.name.is_empty() {
                entry.name = name.to_string();
            }
        }
        if let Some(args) = call.pointer("/function/arguments").and_then(Value::as_str) {
            if !args.is_empty() {
                on_delta(Delta::ToolCallArgs {
                    index,
                    json: args.to_string(),
                });
            }
            entry.arguments.push_str(args);
        }
    }

    /// The assembled message. Fails if the stream ended before the model signalled
    /// completion, so a cut connection is never mistaken for a finished reply.
    /// What the server said this call cost, in the same shape as a non-streaming reply.
    pub fn usage_body(&self) -> Value {
        self.usage.clone()
    }

    pub fn finish(self) -> Result<Message> {
        if !self.finished {
            return Err(Error::Provider(ProviderFailure::Truncated {
                message: "the stream ended before the model finished its reply".into(),
                streamed_chars: self.content.chars().count(),
            }));
        }
        let content = (!self.content.is_empty()).then_some(self.content);
        let reasoning = (!self.reasoning.is_empty()).then_some(self.reasoning);
        if self.calls.is_empty() {
            let mut m = Message::assistant(content.unwrap_or_default());
            m.reasoning = reasoning;
            m.finish_reason = self.finish_reason.clone();
            return Ok(m);
        }
        let calls = self
            .calls
            .into_values()
            .enumerate()
            .map(|(i, c)| ToolCall {
                id: if c.id.is_empty() {
                    format!("call_{i}")
                } else {
                    c.id
                },
                kind: "function".into(),
                function: FunctionCall {
                    name: c.name,
                    arguments: c.arguments,
                },
            })
            .collect();
        let mut m = Message::assistant_tool_calls(content, calls);
        m.reasoning = reasoning;
        m.finish_reason = self.finish_reason.clone();
        Ok(m)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    #[test]
    fn parser_handles_split_lines_crlf_comments_and_multiline_data() {
        let mut p = SseParser::default();
        assert!(p.push(b": keep-alive\n\ndata: one\n").is_empty());
        assert_eq!(
            p.push(b"\r\ndata:two\r\ndata: three\r\n\r\nda"),
            ["one", "two\nthree"]
        );
        let ev = p.push(b"ta: x\n\n");
        assert_eq!(ev, ["x"]);
        // Event with an `event:` field and no space after the colon.
        assert_eq!(p.push(b"event: ping\ndata:{}\n\n"), ["{}"]);
    }

    #[test]
    fn parser_survives_a_multibyte_char_split_across_chunks() {
        let bytes = "data: héllo\n\n".as_bytes();
        let cut = bytes.iter().position(|b| *b == 0xC3).unwrap() + 1;
        let mut p = SseParser::default();
        assert!(p.push(&bytes[..cut]).is_empty());
        assert_eq!(p.push(&bytes[cut..]), ["héllo"]);
    }

    #[test]
    fn parser_finish_flushes_unterminated_tail() {
        let mut p = SseParser::default();
        assert!(p.push(b"data: [DONE]").is_empty());
        assert_eq!(p.finish(), ["[DONE]"]);
    }

    fn feed(events: &[&str]) -> (Result<Message>, Vec<Delta>) {
        let deltas = Mutex::new(Vec::new());
        let sink = |d: Delta| deltas.lock().unwrap().push(d);
        let mut acc = StreamAccumulator::default();
        for e in events {
            if let Err(e) = acc.push_event(e, &sink) {
                return (Err(e), deltas.into_inner().unwrap());
            }
        }
        (acc.finish(), deltas.into_inner().unwrap())
    }

    fn text_deltas(d: &[Delta]) -> Vec<String> {
        d.iter()
            .filter_map(|x| match x {
                Delta::Text(t) => Some(t.clone()),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn text_deltas_are_forwarded_and_joined() {
        let (msg, deltas) = feed(&[
            r#"{"choices":[{"delta":{"role":"assistant","content":""}}]}"#,
            r#"{"choices":[{"delta":{"content":"Hel"}}]}"#,
            r#"{"choices":[{"delta":{"content":"lo"},"finish_reason":null}]}"#,
            r#"{"choices":[{"delta":{},"finish_reason":"stop"}]}"#,
            r#"{"choices":[],"usage":{"total_tokens":3}}"#,
            "[DONE]",
        ]);
        assert_eq!(text_deltas(&deltas), ["Hel", "lo"]);
        let msg = msg.unwrap();
        assert_eq!(msg.content.as_deref(), Some("Hello"));
        assert_eq!(msg.finish_reason.as_deref(), Some("stop"));
    }

    #[test]
    fn tool_call_fragments_are_assembled_by_index() {
        let (msg, deltas) = feed(&[
            r#"{"choices":[{"delta":{"content":"checking"}}]}"#,
            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","type":"function","function":{"name":"read_file","arguments":""}}]}}]}"#,
            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"path\":"}}]}}]}"#,
            r#"{"choices":[{"delta":{"tool_calls":[{"index":1,"id":"","function":{"name":"shell","arguments":"{}"}}]}}]}"#,
            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"a\"}"}}]}}]}"#,
            r#"{"choices":[{"delta":{},"finish_reason":"tool_calls"}]}"#,
        ]);
        assert_eq!(text_deltas(&deltas), ["checking"]);
        let m = msg.unwrap();
        assert_eq!(m.content.as_deref(), Some("checking"));
        assert_eq!(m.tool_calls.len(), 2);
        assert_eq!(m.tool_calls[0].id, "c1");
        assert_eq!(m.tool_calls[0].function.name, "read_file");
        assert_eq!(m.tool_calls[0].function.arguments, r#"{"path":"a"}"#);
        assert_eq!(m.tool_calls[1].id, "call_1");
        assert_eq!(m.tool_calls[1].function.name, "shell");
    }

    #[test]
    fn tool_calls_without_index_are_still_separated() {
        let (msg, _) = feed(&[
            r#"{"choices":[{"delta":{"tool_calls":[{"id":"a","function":{"name":"x","arguments":"{"}}]}}]}"#,
            r#"{"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"}"}}]}}]}"#,
            r#"{"choices":[{"delta":{"tool_calls":[{"id":"b","function":{"name":"y","arguments":"{}"}}]}}]}"#,
            r#"{"choices":[{"finish_reason":"tool_calls"}]}"#,
        ]);
        let m = msg.unwrap();
        assert_eq!(m.content, None);
        let got: Vec<_> = m
            .tool_calls
            .iter()
            .map(|c| (&*c.id, &*c.function.name, &*c.function.arguments))
            .collect();
        assert_eq!(got, [("a", "x", "{}"), ("b", "y", "{}")]);
    }

    #[test]
    fn stream_without_completion_or_with_error_chunk_fails() {
        let (msg, deltas) = feed(&[r#"{"choices":[{"delta":{"content":"partial"}}]}"#]);
        assert_eq!(text_deltas(&deltas), ["partial"]);
        let err = msg.unwrap_err();
        assert!(err.to_string().contains("before it finished"), "{err}");
        assert_eq!(
            err.provider_failure().map(|f| f.kind()),
            Some(crate::error::ProviderFailureKind::Truncated),
            "a cut stream is classified, not just described"
        );
        let (msg, _) = feed(&[r#"{"error":{"message":"overloaded"}}"#]);
        assert!(msg.unwrap_err().to_string().contains("overloaded"));
        let (msg, _) = feed(&["{not json"]);
        assert!(msg.unwrap_err().to_string().contains("malformed"));
    }
}

#[cfg(test)]
mod reasoning_tests {
    use super::*;
    use std::sync::Mutex;

    #[test]
    fn reasoning_deltas_are_forwarded_and_assembled() {
        let deltas = Mutex::new(Vec::new());
        let sink = |d: Delta| deltas.lock().unwrap().push(d);
        let mut acc = StreamAccumulator::default();
        acc.push_event(
            r#"{"choices":[{"delta":{"reasoning_content":"thinking "}}]}"#,
            &sink,
        )
        .unwrap();
        acc.push_event(
            r#"{"choices":[{"delta":{"reasoning_content":"hard"}}]}"#,
            &sink,
        )
        .unwrap();
        acc.push_event(
            r#"{"choices":[{"delta":{"content":"answer"},"finish_reason":"stop"}]}"#,
            &sink,
        )
        .unwrap();
        let msg = acc.finish().unwrap();
        let got = deltas.into_inner().unwrap();
        assert!(got.contains(&Delta::Reasoning("thinking ".into())));
        assert!(got.contains(&Delta::Reasoning("hard".into())));
        assert_eq!(msg.reasoning.as_deref(), Some("thinking hard"));
        assert_eq!(msg.content.as_deref(), Some("answer"));
    }

    #[test]
    fn tool_call_arg_fragments_are_forwarded_with_their_index() {
        let deltas = Mutex::new(Vec::new());
        let sink = |d: Delta| deltas.lock().unwrap().push(d);
        let mut acc = StreamAccumulator::default();
        acc.push_event(
            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"w","arguments":"{\"a\":"}}]}}]}"#,
            &sink,
        )
        .unwrap();
        acc.push_event(
            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"1}"}}]},"finish_reason":"tool_calls"}]}"#,
            &sink,
        )
        .unwrap();
        let got = deltas.into_inner().unwrap();
        assert_eq!(
            got,
            [
                Delta::ToolCallArgs {
                    index: 0,
                    json: "{\"a\":".into()
                },
                Delta::ToolCallArgs {
                    index: 0,
                    json: "1}".into()
                },
            ]
        );
        let msg = acc.finish().unwrap();
        assert_eq!(msg.tool_calls[0].function.arguments, "{\"a\":1}");
    }
}