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::{ExitInfo, 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() => {
50 current.push(line.to_string());
51 turns.push(std::mem::take(&mut current));
52 }
53 _ => current.push(line.to_string()),
54 }
55 }
56 let initialize_response = initialize_response
57 .ok_or_else(|| SessionError::InvalidRecording("no initialize response".into()))?;
58 Ok(Self { initialize_response, turns })
59 }
60
61 pub async fn load(path: impl AsRef<Path>) -> Result<Self> {
63 Self::parse(&tokio::fs::read_to_string(path).await?)
64 }
65}
66
67pub async fn replay(path: impl AsRef<Path>, opts: SessionOptions) -> Result<Session> {
70 let recording = Recording::load(path).await?;
71 let record = crate::session::open_record(&opts).await?;
72 let (host, cli) = tokio::io::duplex(1 << 16);
73 let (host_out, host_in) = tokio::io::split(host);
74 let fake = tokio::spawn(fake_cli(cli, recording));
75 let exit = Box::pin(async move {
76 let code = fake.await.ok().map(|()| 0);
77 ExitInfo { code, stderr: String::new() }
78 });
79 let transport = Transport { stdin: Box::new(host_in), stdout: Box::new(host_out), exit, pgid: None };
80 Session::connect(transport, opts, Initialize::default(), record).await
81}
82
83async fn fake_cli(io: tokio::io::DuplexStream, recording: Recording) {
84 let (read, mut write) = tokio::io::split(io);
85 let mut lines = BufReader::new(read).lines();
86 let mut turns = recording.turns.into_iter();
87 while let Ok(Some(line)) = lines.next_line().await {
88 let Ok(msg) = serde_json::from_str::<Value>(&line) else { continue };
89 let out: Vec<String> = match msg.get("type").and_then(Value::as_str) {
90 Some("control_request") => {
91 let is_init = msg["request"]["subtype"] == "initialize";
92 let payload = if is_init { recording.initialize_response.clone() } else { json!({}) };
93 vec![json!({
94 "type": "control_response",
95 "response": { "subtype": "success", "request_id": msg["request_id"], "response": payload },
96 })
97 .to_string()]
98 }
99 Some("user") => turns.next().map_or_else(|| {
100 vec![
101 json!({ "type": "user", "isReplay": true, "uuid": msg["uuid"], "message": msg["message"] })
102 .to_string(),
103 json!({
104 "type": "result",
105 "subtype": "error_during_execution",
106 "is_error": true,
107 "errors": ["replay exhausted: no recorded turn left"],
108 })
109 .to_string(),
110 ]
111 }, |frames| with_echo_uuid(frames, &msg["uuid"])),
112 _ => vec![],
113 };
114 for frame in out {
115 if write.write_all(frame.as_bytes()).await.is_err() || write.write_all(b"\n").await.is_err() {
116 return;
117 }
118 }
119 }
120}
121
122fn with_echo_uuid(frames: Vec<String>, uuid: &Value) -> Vec<String> {
124 frames
125 .into_iter()
126 .map(|line| match serde_json::from_str::<Value>(&line) {
127 Ok(mut f) if f["type"] == "user" && f["isReplay"] == true => {
128 f["uuid"] = uuid.clone();
129 f.to_string()
130 }
131 _ => line,
132 })
133 .collect()
134}