1use base::interface::model::{Effort, ThinkingMode};
13use base::interface::model::{InputMap, ModelError, ModelErrorKind, ModelEvent, Usage};
14use base::provider::ApiType;
15use serde::{Deserialize, Serialize};
16
17use super::blob::BlobId;
18
19pub const FORMAT_VERSION: u32 = 1;
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
26#[serde(tag = "type", rename_all = "snake_case")]
27pub enum Record {
28 Recording(Header),
29 Call(Box<CallRecord>),
33 Chunk(ChunkRecord),
34 TextChunks(TextRun),
35 ThinkingChunks(TextRun),
36 ToolArgsChunks(ToolArgsRun),
37 End(EndRecord),
38
39 #[serde(other)]
44 Unknown,
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct Header {
49 pub version: u32,
50 pub name: String,
51 pub session_id: String,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub parent: Option<String>,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub agent_type: Option<String>,
60 pub created_at: u64,
61 pub engine_version: String,
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct CallRecord {
66 pub seq: u64,
67 pub ts: u64,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub session_id: Option<String>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub parent_session_id: Option<String>,
80 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub agent_type: Option<String>,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub turn_id: Option<String>,
85 pub turn: u32,
86 pub step: u32,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
93 pub purpose: Option<String>,
94 pub provider: String,
95 pub api_type: ApiType,
96 pub params: RecordedParams,
97 pub system: Vec<BlobId>,
101 pub tools: BlobId,
102 pub messages: Vec<BlobId>,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub input_map: Option<InputMap>,
108}
109
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111pub struct RecordedParams {
112 pub model: String,
113 pub max_tokens: u32,
114 pub thinking_mode: ThinkingMode,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub effort: Option<Effort>,
117 #[serde(default, skip_serializing_if = "Vec::is_empty")]
118 pub cache_edits: Vec<String>,
119 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub search_max_uses: Option<u32>,
123}
124
125#[derive(Debug, Clone, Serialize, Deserialize)]
126pub struct ChunkRecord {
127 pub seq: u64,
128 pub ts: u64,
129 pub call: u64,
130 pub chunk: ModelEvent,
131}
132
133#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct TextRun {
140 pub seq0: u64,
141 pub ts0: u64,
142 pub call: u64,
143 pub texts: Vec<String>,
144 pub dt: Vec<i64>,
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct ToolArgsRun {
151 pub seq0: u64,
152 pub ts0: u64,
153 pub call: u64,
154 pub id: String,
156 pub args: Vec<String>,
157 pub dt: Vec<i64>,
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize)]
161pub struct EndRecord {
162 pub seq: u64,
163 pub ts: u64,
164 pub call: u64,
165 pub outcome: Outcome,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub stop_reason: Option<String>,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
169 pub usage: Option<Usage>,
170 pub duration_ms: u64,
171}
172
173#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
174#[serde(tag = "status", rename_all = "snake_case")]
175pub enum Outcome {
176 Ok,
177 Cancelled,
178 Error {
179 #[serde(flatten)]
180 error: RecordedError,
181 },
182}
183
184#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
193pub struct RecordedError {
194 pub error: ModelErrorKind,
195 #[serde(default, skip_serializing_if = "Option::is_none")]
196 pub http_status: Option<u16>,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub retry_after_ms: Option<u64>,
199 #[serde(default, skip_serializing_if = "String::is_empty")]
200 pub message: String,
201}
202
203impl From<&ModelError> for RecordedError {
204 fn from(e: &ModelError) -> Self {
205 Self {
206 error: e.kind,
207 http_status: e.status,
208 retry_after_ms: e.retry_after.map(|d| d.as_millis() as u64),
209 message: e.message.clone(),
210 }
211 }
212}
213
214impl RecordedError {
215 pub fn into_model_error(self) -> ModelError {
216 let error = ModelError::new(self.error, self.message)
217 .with_retry_after(self.retry_after_ms.map(std::time::Duration::from_millis));
218 match self.http_status {
219 Some(status) => error.with_status(status),
220 None => error,
221 }
222 }
223}
224
225pub fn now_ms() -> u64 {
226 u64::try_from(base::clock::unix_ms()).unwrap_or(0)
227}
228
229#[cfg(test)]
230mod tests {
231 use super::*;
232
233 #[test]
234 fn unknown_record_type_decodes_as_unknown() {
235 let line = r#"{"type":"something_from_the_future","whatever":1}"#;
236 assert!(matches!(
237 serde_json::from_str::<Record>(line).unwrap(),
238 Record::Unknown
239 ));
240 }
241
242 #[test]
243 fn call_record_round_trips() {
244 let record = Record::Call(Box::new(CallRecord {
245 seq: 3,
246 ts: 1_755_500_000_123,
247 session_id: Some("S1".into()),
248 parent_session_id: None,
249 agent_type: None,
250 turn_id: Some("T1".into()),
251 turn: 2,
252 step: 1,
253 purpose: None,
254 provider: "anthropic".into(),
255 api_type: ApiType::Anthropic,
256 params: RecordedParams {
257 search_max_uses: None,
258 model: "claude-opus-5".into(),
259 max_tokens: 8192,
260 thinking_mode: ThinkingMode::Off,
261 effort: None,
262 cache_edits: vec![],
263 },
264 system: vec![BlobId("aaaaaaaaaaaaaaaa".into())],
265 tools: BlobId("bbbbbbbbbbbbbbbb".into()),
266 messages: vec![BlobId("cccccccccccccccc".into())],
267 input_map: None,
268 }));
269 let json = serde_json::to_string(&record).unwrap();
270 assert!(json.contains(r#""type":"call""#));
271 let back: Record = serde_json::from_str(&json).unwrap();
272 let Record::Call(back) = back else {
273 panic!("expected a call record")
274 };
275 assert_eq!(back.seq, 3);
276 assert_eq!(back.turn_id.as_deref(), Some("T1"));
277 assert_eq!(back.system.len(), 1);
278 }
279
280 #[test]
281 fn every_model_error_survives_the_round_trip() {
282 let errors = [
283 ModelError::overloaded()
284 .with_status(529)
285 .with_retry_after(Some(std::time::Duration::from_millis(1500))),
286 ModelError::auth("bad token"),
287 ModelError::rate_limited(),
288 ModelError::timeout("no response headers"),
289 ModelError::cancelled(),
290 ModelError::protocol("boom"),
291 ModelError::not_recorded("no title call"),
292 ];
293 for error in &errors {
294 let recorded = RecordedError::from(error);
295 let json = serde_json::to_string(&recorded).unwrap();
296 let back: RecordedError = serde_json::from_str(&json).unwrap();
297 assert_eq!(recorded, back);
298 assert_eq!(&back.into_model_error(), error);
299 }
300 }
301
302 #[test]
303 fn model_events_round_trip_through_a_chunk_record() {
304 let events = [
305 ModelEvent::TextDelta { text: "hi".into() },
306 ModelEvent::ThinkingDelta { text: "hmm".into() },
307 ModelEvent::ThinkingSignature {
308 signature: "sig".into(),
309 },
310 ModelEvent::RedactedThinking { data: "enc".into() },
311 ModelEvent::ToolUse {
312 id: "t1".into(),
313 name: "Read".into(),
314 input: serde_json::json!({"path": "/tmp/x"}),
315 },
316 ModelEvent::ContentBlockStop { index: 0 },
317 ModelEvent::EndTurn {
318 stop_reason: "end_turn".into(),
319 usage: Usage {
320 input_tokens: 10,
321 output_tokens: 20,
322 ..Default::default()
323 },
324 },
325 ];
326 for event in events {
327 let record = Record::Chunk(ChunkRecord {
328 seq: 0,
329 ts: 1,
330 call: 0,
331 chunk: event.clone(),
332 });
333 let json = serde_json::to_string(&record).unwrap();
334 let back: Record = serde_json::from_str(&json).unwrap();
335 let Record::Chunk(back) = back else {
336 panic!("expected a chunk record")
337 };
338 assert_eq!(format!("{:?}", back.chunk), format!("{event:?}"));
339 }
340 }
341}