protocol/watch/
stream_fold.rs1use serde_json::{Map, Value, json};
15
16pub const PARTIAL_JSON: &str = "partialJson";
18
19pub fn fold_update(message: &mut Value, event: &Value) {
21 if let Some(usage) = event.get("usage").filter(|usage| !usage.is_null()) {
22 message["usage"] = usage.clone();
23 }
24 fold_frame(message, &event["frame"]);
25}
26
27pub fn message_of(event: &Value) -> Option<&Value> {
29 event.get("message").filter(|message| message.is_object())
30}
31
32pub fn fold_frame(message: &mut Value, frame: &Value) {
33 let Some(kind) = frame["type"].as_str() else {
34 return;
35 };
36 let Some(index) = frame["contentIndex"].as_u64().map(|index| index as usize) else {
37 return;
38 };
39 if !message["content"].is_array() {
40 message["content"] = json!([]);
41 }
42 let Some(content) = message["content"].as_array_mut() else {
43 return;
44 };
45 let block = match kind {
46 "text_start" => Some(json!({"type": "text", "text": ""})),
47 "thinking_start" => Some(json!({"type": "thinking", "thinking": ""})),
48 "toolcall_start" => Some(json!({
49 "type": "toolCall", "id": frame["id"], "name": frame["toolName"], "arguments": {},
50 })),
51 "toolcall_end" => frame.get("toolCall").filter(|call| call.is_object()).cloned(),
52 _ => None,
53 };
54 if let Some(block) = block {
55 if index < content.len() {
56 content[index] = block;
57 } else {
58 content.resize(index, Value::Null);
60 content.push(block);
61 }
62 return;
63 }
64 let Some(block) = content.get_mut(index).and_then(Value::as_object_mut) else {
65 return;
66 };
67 match kind {
68 "text_delta" | "thinking_delta" => {
69 let key = if kind == "text_delta" { "text" } else { "thinking" };
70 append(block, key, frame["delta"].as_str().unwrap_or_default());
71 }
72 "text_end" | "thinking_end" => {
73 let key = if kind == "text_end" { "text" } else { "thinking" };
74 if let Some(text) = frame["content"].as_str() {
75 block.insert(key.into(), text.into());
76 }
77 }
78 "toolcall_delta" => {
79 append(block, PARTIAL_JSON, frame["delta"].as_str().unwrap_or_default());
80 let arguments = jsrt::json_parse::parse_streaming_json(block[PARTIAL_JSON].as_str().unwrap_or_default());
81 block.insert("arguments".into(), arguments);
82 }
83 _ => {}
84 }
85}
86
87fn append(block: &mut Map<String, Value>, key: &str, delta: &str) {
88 match block.get_mut(key) {
89 Some(Value::String(text)) => text.push_str(delta),
90 _ => {
91 block.insert(key.into(), delta.into());
92 }
93 }
94}