agentmux_srv_core/backend/transcript/
provider.rs1use std::collections::HashMap;
21
22use serde_json::{Map, Value};
23use sha2::{Digest, Sha256};
24
25use super::withhold;
26
27#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
29pub struct Item(u128);
30
31fn item(kind: &str, parts: &[&str]) -> Item {
32 let mut h = Sha256::new();
33 h.update((kind.len() as u64).to_le_bytes());
34 h.update(kind.as_bytes());
35 for p in parts {
36 h.update((p.len() as u64).to_le_bytes());
37 h.update(p.as_bytes());
38 }
39 let d = h.finalize();
40 let mut b = [0u8; 16];
41 b.copy_from_slice(&d[..16]);
42 Item(u128::from_le_bytes(b))
43}
44
45fn write_canon(v: &Value, out: &mut String) {
46 match v {
47 Value::Object(m) => {
48 let mut keys: Vec<&String> = m.keys().collect();
49 keys.sort();
50 out.push('{');
51 for (i, k) in keys.into_iter().enumerate() {
52 if i > 0 {
53 out.push(',');
54 }
55 out.push_str(&Value::String(k.clone()).to_string());
56 out.push(':');
57 write_canon(&m[k], out);
58 }
59 out.push('}');
60 }
61 Value::Array(a) => {
62 out.push('[');
63 for (i, e) in a.iter().enumerate() {
64 if i > 0 {
65 out.push(',');
66 }
67 write_canon(e, out);
68 }
69 out.push(']');
70 }
71 other => out.push_str(&other.to_string()),
72 }
73}
74
75fn canon(v: &Value) -> String {
77 let mut s = String::new();
78 write_canon(v, &mut s);
79 s
80}
81
82fn result_text(content: &Value) -> String {
84 match content {
85 Value::String(s) => s.clone(),
86 Value::Array(blocks) if blocks.iter().all(|b| b.get("type").and_then(Value::as_str) == Some("text")) => {
87 blocks.iter().filter_map(|b| b.get("text").and_then(Value::as_str)).collect::<Vec<_>>().join("\n")
88 }
89 other => canon(other),
90 }
91}
92
93fn str_of<'a>(b: &'a Value, key: &str) -> &'a str {
94 b.get(key).and_then(Value::as_str).unwrap_or("")
95}
96
97fn block_item(role: &str, b: &Value) -> Item {
98 match b.get("type").and_then(Value::as_str).unwrap_or("") {
99 "text" => item(&format!("{role}-text"), &[str_of(b, "text")]),
100 "thinking" => item("thinking", &[str_of(b, "thinking"), str_of(b, "signature")]),
101 "tool_use" => item("tool_use", &[str_of(b, "id"), str_of(b, "name"), &canon(b.get("input").unwrap_or(&Value::Null))]),
102 "tool_result" => {
103 let err = if b.get("is_error").and_then(Value::as_bool).unwrap_or(false) { "1" } else { "0" };
104 item("tool_result", &[str_of(b, "tool_use_id"), err, &result_text(b.get("content").unwrap_or(&Value::Null))])
105 }
106 _ => item("block", &[&canon(b)]),
107 }
108}
109
110fn message_items(role: &str, v: &Value) -> Vec<Item> {
111 match v.pointer("/message/content") {
112 Some(Value::String(s)) if !s.is_empty() => vec![item(&format!("{role}-text"), &[s])],
113 Some(Value::Array(blocks)) => blocks.iter().map(|b| block_item(role, b)).collect(),
114 _ => Vec::new(),
115 }
116}
117
118pub fn items_of(v: &Value) -> Vec<Item> {
120 match v.get("type").and_then(Value::as_str).unwrap_or("") {
121 "user" => message_items("user", v),
122 "assistant" => message_items("assistant", v),
123 "summary" => v.get("summary").and_then(Value::as_str).map(|s| vec![item("summary", &[s])]).unwrap_or_default(),
124 "system" => {
125 let meta = v.get("compact_metadata").or_else(|| v.get("compactMetadata")).map(canon).unwrap_or_default();
126 vec![item("system", &[str_of(v, "subtype"), str_of(v, "content"), &meta])]
127 }
128 _ => Vec::new(),
129 }
130}
131
132#[derive(Default)]
134pub struct StoreIndex {
135 at: HashMap<Item, Vec<usize>>,
136 next: usize,
137}
138
139impl StoreIndex {
140 pub fn new() -> Self {
141 Self::default()
142 }
143
144 pub fn add_line(&mut self, sid: &str, line: &str) {
146 let Ok(v) = serde_json::from_str::<Value>(line) else { return };
147 let named = v.get("session_id").or_else(|| v.get("sessionId")).and_then(Value::as_str);
148 if named.is_some_and(|n| n != sid) {
149 return;
150 }
151 for it in items_of(&v) {
152 self.at.entry(it).or_default().push(self.next);
153 self.next += 1;
154 }
155 }
156
157 fn first_from(&self, it: &Item, from: usize) -> Option<usize> {
159 let at = self.at.get(it)?;
160 at.get(at.partition_point(|p| *p < from)).copied()
161 }
162
163 pub fn len(&self) -> usize {
164 self.next
165 }
166}
167
168pub struct Record {
170 pub n: usize,
172 pub line: String,
174 value: Option<Value>,
175 items: Vec<Item>,
176}
177
178pub fn record(n: usize, line: &str) -> Record {
180 let line = withhold::text(line).into_owned();
181 let value = serde_json::from_str::<Value>(&line).ok();
182 let items = value.as_ref().map(items_of).unwrap_or_default();
183 Record { n, line, value, items }
184}
185
186pub struct Matcher<'a> {
188 index: &'a StoreIndex,
189 cursor: usize,
190}
191
192impl<'a> Matcher<'a> {
193 pub fn new(index: &'a StoreIndex) -> Self {
194 Self { index, cursor: 0 }
195 }
196
197 pub fn matches(&mut self, r: &Record) -> bool {
200 if r.items.is_empty() {
201 return false;
202 }
203 let mut at = self.cursor;
204 for it in &r.items {
205 match self.index.first_from(it, at) {
206 Some(p) => at = p + 1,
207 None => return false,
208 }
209 }
210 self.cursor = at;
211 true
212 }
213}
214
215pub fn sidecar_fields(r: &Record) -> Option<Map<String, Value>> {
219 const KEEP: [&str; 17] = [
220 "uuid", "parentUuid", "logicalParentUuid", "isSidechain", "sessionId", "requestId", "version", "slug", "cwd",
221 "gitBranch", "userType", "entrypoint", "timestamp", "isMeta", "isCompactSummary", "agentId", "sourceToolUseID",
222 ];
223 let v = r.value.as_ref()?;
224 let mut out = Map::new();
225 for k in KEEP {
226 if let Some(x) = v.get(k) {
227 out.insert(k.to_string(), x.clone());
228 }
229 }
230 if let Some(m) = v.get("message").and_then(Value::as_object) {
231 let msg: Map<String, Value> =
232 ["id", "model", "usage", "stop_reason", "stop_sequence"].iter().filter_map(|k| m.get(*k).map(|x| (k.to_string(), x.clone()))).collect();
233 if !msg.is_empty() {
234 out.insert("message".to_string(), Value::Object(msg));
235 }
236 }
237 if let Some(extra) = v.get("toolUseResult").filter(|t| !covered_by_results(t, v)) {
238 out.insert("toolUseResult".to_string(), extra.clone());
239 }
240 (!out.is_empty()).then_some(out)
241}
242
243fn leaves<'a>(v: &'a Value, out: &mut Vec<&'a str>) {
244 match v {
245 Value::String(s) => out.push(s),
246 Value::Array(a) => a.iter().for_each(|e| leaves(e, out)),
247 Value::Object(m) => m.values().for_each(|e| leaves(e, out)),
248 _ => {}
249 }
250}
251
252fn covered_by_results(extra: &Value, record: &Value) -> bool {
254 let hay: Vec<String> = match record.pointer("/message/content") {
255 Some(Value::Array(blocks)) => blocks
256 .iter()
257 .filter(|b| b.get("type").and_then(Value::as_str) == Some("tool_result"))
258 .map(|b| result_text(b.get("content").unwrap_or(&Value::Null)))
259 .collect(),
260 _ => Vec::new(),
261 };
262 let mut texts = Vec::new();
263 leaves(extra, &mut texts);
264 texts.iter().all(|t| t.is_empty() || hay.iter().any(|h| h.contains(t)))
265}