claude_code_agent/
replay.rs1use std::path::Path;
13
14use serde_json::{json, Value};
15use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
16
17use crate::protocol::Initialize;
18use crate::session::{Result, Session, SessionError, SessionOptions, Transport};
19
20#[derive(Debug, Clone, PartialEq)]
22pub struct Recording {
23 pub initialize_response: Value,
25 pub turns: Vec<Vec<String>>,
28}
29
30impl Recording {
31 pub fn parse(jsonl: &str) -> Result<Self> {
33 let mut initialize_response = None;
34 let mut turns = vec![];
35 let mut current = vec![];
36 for (n, line) in jsonl.lines().enumerate().filter(|(_, l)| !l.trim().is_empty()) {
37 let frame: Value = serde_json::from_str(line)
38 .map_err(|e| SessionError::InvalidRecording(format!("line {}: {e}", n + 1)))?;
39 match frame.get("type").and_then(Value::as_str) {
40 Some("control_response") => {
41 if initialize_response.is_none() {
42 initialize_response =
43 Some(frame["response"].get("response").cloned().unwrap_or(Value::Null));
44 }
45 }
46 Some("control_request") => {}
47 Some("result") if frame.get("origin").is_none_or(Value::is_null) => {
51 current.push(line.to_string());
52 turns.push(std::mem::take(&mut current));
53 }
54 _ => current.push(line.to_string()),
55 }
56 }
57 if let Some(last) = turns.last_mut() {
60 last.append(&mut current);
61 }
62 let initialize_response = initialize_response
63 .ok_or_else(|| SessionError::InvalidRecording("no initialize response".into()))?;
64 Ok(Self { initialize_response, turns })
65 }
66
67 pub async fn load(path: impl AsRef<Path>) -> Result<Self> {
69 Self::parse(&tokio::fs::read_to_string(path).await?)
70 }
71}
72
73pub async fn replay(path: impl AsRef<Path>, opts: SessionOptions) -> Result<Session> {
76 let recording = Recording::load(path).await?;
77 let record = crate::session::open_record(&opts).await?;
78 let (host, cli) = tokio::io::duplex(1 << 16);
79 let (host_out, host_in) = tokio::io::split(host);
80 let fake = tokio::spawn(fake_cli(cli, recording));
81 let exit = Box::pin(async move { fake.await.ok().map(|()| 0) });
82 let stderr_tail = Box::pin(async { String::new() });
83 let transport =
84 Transport { stdin: Box::new(host_in), stdout: Box::new(host_out), exit, stderr_tail, pgid: None };
85 Session::connect(transport, opts, Initialize::default(), record).await
86}
87
88async fn fake_cli(io: tokio::io::DuplexStream, recording: Recording) {
89 let (read, mut write) = tokio::io::split(io);
90 let mut lines = BufReader::new(read).lines();
91 let mut turns = recording.turns.into_iter();
92 while let Ok(Some(line)) = lines.next_line().await {
93 let Ok(msg) = serde_json::from_str::<Value>(&line) else { continue };
94 let out: Vec<String> = match msg.get("type").and_then(Value::as_str) {
95 Some("control_request") => {
96 let is_init = msg["request"]["subtype"] == "initialize";
97 let payload = if is_init { recording.initialize_response.clone() } else { json!({}) };
98 vec![json!({
99 "type": "control_response",
100 "response": { "subtype": "success", "request_id": msg["request_id"], "response": payload },
101 })
102 .to_string()]
103 }
104 Some("user") => turns.next().map_or_else(|| {
105 vec![
106 json!({ "type": "user", "isReplay": true, "uuid": msg["uuid"], "message": msg["message"] })
107 .to_string(),
108 json!({
109 "type": "result",
110 "subtype": "error_during_execution",
111 "is_error": true,
112 "errors": ["replay exhausted: no recorded turn left"],
113 })
114 .to_string(),
115 ]
116 }, |frames| with_echo_uuid(frames, &msg["uuid"])),
117 _ => vec![],
118 };
119 for frame in out {
120 if write.write_all(frame.as_bytes()).await.is_err() || write.write_all(b"\n").await.is_err() {
121 return;
122 }
123 }
124 }
125}
126
127fn with_echo_uuid(frames: Vec<String>, uuid: &Value) -> Vec<String> {
129 frames
130 .into_iter()
131 .map(|line| match serde_json::from_str::<Value>(&line) {
132 Ok(mut f) if f["type"] == "user" && f["isReplay"] == true => {
133 f["uuid"] = uuid.clone();
134 f.to_string()
135 }
136 _ => line,
137 })
138 .collect()
139}