1use serde_json::{Map, Value, json};
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum Reduction {
13 Rebase,
14}
15
16fn object(fields: &[(&str, Option<&Value>)]) -> Value {
18 let mut map = Map::new();
19 for (key, value) in fields {
20 if let Some(value) = value {
21 map.insert((*key).into(), (*value).clone());
22 }
23 }
24 Value::Object(map)
25}
26
27fn open_operation(kind: &str, event: &Value, from_tip: &Value) -> Value {
28 object(&[
29 ("id", event.get("runId")),
30 ("kind", Some(&kind.into())),
31 ("startedAt", event.get("startedAt")),
32 ("fromTipId", Some(from_tip)),
33 ("status", Some(&"open".into())),
34 ("runningTools", Some(&json!([]))),
35 ])
36}
37
38fn matching<'a>(snapshot: &'a mut Value, id: Option<&Value>) -> Option<&'a mut Map<String, Value>> {
40 let operation = snapshot.get_mut("operation")?.as_object_mut()?;
41 (id.is_some() && operation.get("id") == id).then_some(operation)
42}
43
44fn tools(operation: &mut Map<String, Value>) -> Option<&mut Vec<Value>> {
45 operation.get_mut("runningTools")?.as_array_mut()
46}
47
48fn position(tools: &[Value], call: Option<&Value>) -> Option<usize> {
49 tools.iter().position(|tool| tool.get("toolCallId") == call)
50}
51
52fn failure(event: &Value) -> Option<&Value> {
54 (event.get("status").and_then(Value::as_str) == Some("failed"))
55 .then(|| event.get("error"))
56 .flatten()
57}
58
59fn increment(value: &mut Value) {
60 *value = match (value.as_u64(), value.as_f64()) {
61 (Some(n), _) => json!(n + 1),
62 (None, Some(n)) => json!(n + 1.0),
63 (None, None) => return,
64 };
65}
66
67pub fn reduce_lane_snapshot(snapshot: &mut Value, event: &Value) -> Option<Reduction> {
69 let kind = event.get("type").and_then(Value::as_str).unwrap_or("");
70 if let Some(lane) = event.get("lane")
71 && Some(lane) != snapshot.get("lane")
72 && kind != "usage"
73 {
74 return None;
75 }
76 let run_id = event.get("runId");
77 match kind {
78 "run_start" | "navigation_start" => {
79 let tip = snapshot["tipId"].clone();
80 let kind = if kind == "run_start" { "run" } else { "navigation" };
81 snapshot["operation"] = open_operation(kind, event, &tip);
82 }
83 "compaction_start" => {
84 if snapshot["operation"].is_null() {
85 let tip = snapshot["tipId"].clone();
86 snapshot["operation"] = open_operation("compaction", event, &tip);
87 }
88 }
89 "operation_abort" => {
90 if let Some(operation) = matching(snapshot, event.get("operationId")) {
91 operation.insert("status".into(), "aborting".into());
92 }
93 }
94 "run_resume" => {
95 if let Some(operation) = matching(snapshot, run_id) {
96 operation.shift_remove("deferred");
97 }
98 }
99 "run_suspend" => {
100 if let Some(operation) = matching(snapshot, run_id) {
101 operation.shift_remove("streamingMessage");
102 let deferred = object(&[("handle", event.get("deferred")), ("poll", event.get("poll"))]);
103 operation.insert("deferred".into(), deferred);
104 }
105 }
106 "retry_scheduled" => {
107 if let Some(operation) = matching(snapshot, run_id) {
108 let retry = object(&[
109 ("attempt", event.get("attempt")),
110 ("maxAttempts", event.get("maxAttempts")),
111 ("nextAttemptAt", event.get("notBefore")),
112 ]);
113 operation.insert("retry".into(), retry);
114 }
115 }
116 "retry_start" | "retry_end" => {
117 if let Some(operation) = matching(snapshot, run_id) {
118 operation.shift_remove("retry");
119 }
120 }
121 "message_start" => {
122 let message = &event["message"];
123 if message["role"] != "assistant" || run_id.is_none() || message["stopReason"] != "pending" {
124 return None;
125 }
126 if let Some(operation) = matching(snapshot, run_id) {
127 operation.insert("streamingMessage".into(), message.clone());
128 }
129 }
130 "message_update" => {
133 if let Some(message) = super::stream_fold::message_of(event) {
134 if message["role"] != "assistant" {
135 return None;
136 }
137 if let Some(operation) = matching(snapshot, run_id) {
138 operation.insert("streamingMessage".into(), message.clone());
139 }
140 } else if let Some(streaming) =
141 matching(snapshot, run_id).and_then(|operation| operation.get_mut("streamingMessage"))
142 {
143 super::stream_fold::fold_update(streaming, event);
144 }
145 }
146 "message_end" => {
147 if let Some(operation) = matching(snapshot, run_id) {
148 operation.shift_remove("streamingMessage");
149 }
150 }
151 "tool_start" => {
152 let tools = matching(snapshot, run_id).and_then(tools)?;
153 let tool = object(&[
154 ("status", Some(&"running".into())),
155 ("toolCallId", event.get("toolCallId")),
156 ("toolName", event.get("toolName")),
157 ("args", event.get("args")),
158 ]);
159 match position(tools, event.get("toolCallId")) {
160 Some(index) => tools[index] = tool,
161 None => tools.push(tool),
162 }
163 }
164 "tool_update" => {
165 let tools = matching(snapshot, run_id).and_then(tools)?;
166 if let Some(index) = position(tools, event.get("toolCallId"))
167 && tools[index]["status"] == "running"
168 && let Some(partial) = event.get("partialResult")
169 {
170 tools[index]["result"] = partial.clone();
171 }
172 }
173 "tool_end" => {
174 let tools = matching(snapshot, run_id).and_then(tools)?;
175 let index = position(tools, event.get("toolCallId"))?;
176 let args = tools[index].get("args").cloned();
177 tools[index] = object(&[
178 ("status", Some(&"settled".into())),
179 ("toolCallId", event.get("toolCallId")),
180 ("toolName", event.get("toolName")),
181 ("args", args.as_ref()),
182 ("result", event.get("result")),
183 ("isError", event.get("isError")),
184 ]);
185 }
186 "entry_added" => {
187 let entry = &event["entry"];
188 let is_message = entry["type"] == "message";
189 if is_message
190 && entry["message"]["role"] == "toolResult"
191 && let Some(tools) = snapshot
192 .get_mut("operation")
193 .and_then(Value::as_object_mut)
194 .and_then(tools)
195 && let Some(index) = position(tools, entry["message"].get("toolCallId"))
196 {
197 tools.remove(index);
198 }
199 if let Some(transcript) = snapshot.get_mut("transcript").and_then(Value::as_array_mut) {
200 if entry["type"] == "compaction" {
201 transcript.clear();
202 }
203 transcript.push(entry.clone());
204 }
205 snapshot["tipId"] = entry["id"].clone();
206 if is_message {
207 increment(&mut snapshot["stats"]["messageCount"]);
208 }
209 }
210 "queue_update" => snapshot["queues"] = event["queues"].clone(),
211 "usage" => snapshot["stats"]["usage"] = event["totals"].clone(),
212 "config_update" => {
213 event.get("lane")?;
214 let field = match event["property"].as_str() {
215 Some("model") => "model",
216 Some("thinkingLevel") => "thinkingLevel",
217 Some("activeTools") => "activeToolNames",
218 _ => return None,
219 };
220 snapshot["configuration"][field] = event["value"].clone();
221 }
222 "run_end" => {
223 let tip = event.get("tipId");
224 let operation = matching(snapshot, run_id).filter(|op| op.get("kind") == Some(&"run".into()))?;
225 let record = object(&[
226 ("operationId", run_id),
227 ("kind", Some(&"run".into())),
228 ("status", event.get("status")),
229 ("error", failure(event)),
230 ("fromTipId", event.get("fromTipId")),
231 ("tipId", tip),
232 ("startedAt", operation.get("startedAt")),
233 ("endedAt", event.get("endedAt")),
234 ]);
235 snapshot["lastResult"] = record;
236 snapshot["operation"] = Value::Null;
237 snapshot["tipId"] = tip.cloned().unwrap_or(Value::Null);
238 }
239 "compaction_end" => {
240 let tip = snapshot["tipId"].clone();
241 let operation = matching(snapshot, run_id).filter(|op| op.get("kind") == Some(&"compaction".into()))?;
242 let record = object(&[
243 ("operationId", run_id),
244 ("kind", Some(&"compaction".into())),
245 ("status", event.get("status")),
246 ("error", failure(event)),
247 ("fromTipId", operation.get("fromTipId")),
248 ("tipId", Some(&tip)),
249 ("startedAt", operation.get("startedAt")),
250 ("endedAt", event.get("endedAt")),
251 ]);
252 snapshot["lastResult"] = record;
253 snapshot["operation"] = Value::Null;
254 }
255 "navigation_end" => return Some(Reduction::Rebase),
256 "fault" => snapshot["faulted"] = true.into(),
257 _ => {}
258 }
259 None
260}