Skip to main content

session_activity/
adapters.rs

1use std::collections::HashMap;
2use std::fs;
3use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
4use std::path::{Path, PathBuf};
5
6use anyhow::{Result, ensure};
7use serde_json::Value;
8use time::{OffsetDateTime, format_description::well_known::Rfc3339};
9
10use crate::{Agent, FileEvent, Operation, Outcome, SessionKey, Source, resolve_path};
11
12/// Normalize supported PostToolUse payloads. Other tools (including arbitrary
13/// shell commands) yield no file events. The caller records lifecycle metadata.
14pub fn hook_events(agent: Agent, input: &Value, timestamp: i64) -> Result<Vec<FileEvent>> {
15    let session = SessionKey { agent, session_id: input["session_id"].as_str().unwrap_or_default().into() };
16    session.validate()?;
17    let cwd = Path::new(input["cwd"].as_str().unwrap_or_default());
18    ensure!(cwd.is_absolute(), "hook cwd must be absolute");
19    let failed = agent == Agent::Claude && input["hook_event_name"] == "PostToolUseFailure";
20    if input["hook_event_name"] != "PostToolUse" && !failed {
21        return Ok(Vec::new());
22    }
23    let mut events = tool_events(
24        &session,
25        cwd,
26        input["tool_name"].as_str().unwrap_or_default(),
27        &input["tool_input"],
28        timestamp,
29        Source::Hook,
30    );
31    for event in &mut events {
32        event.tool_call_id = input["tool_use_id"].as_str().map(str::to_owned);
33        event.outcome = if failed { Outcome::Failed } else { outcome(&input["tool_response"]) };
34    }
35    Ok(events)
36}
37
38fn outcome(response: &Value) -> Outcome {
39    let flags = [
40        response["is_error"].as_bool().map(|v| !v),
41        response["isError"].as_bool().map(|v| !v),
42        response["success"].as_bool(),
43    ];
44    if flags.contains(&Some(false)) {
45        return Outcome::Failed;
46    }
47    if flags.contains(&Some(true)) {
48        return Outcome::Succeeded;
49    }
50    // Output formats vary between agent versions; absence of an explicit
51    // success indicator is not proof that an attempted edit succeeded.
52    Outcome::Unknown
53}
54
55fn tool_events(session: &SessionKey, cwd: &Path, tool: &str, input: &Value, at: i64, source: Source) -> Vec<FileEvent> {
56    if session.agent == Agent::Codex && tool == "apply_patch" {
57        return patch_events(session, cwd, input["command"].as_str().unwrap_or_default(), at, source);
58    }
59    if session.agent != Agent::Claude {
60        return Vec::new();
61    }
62    let operation = match tool {
63        "Read" => Operation::Read,
64        "Write" => Operation::Write, // Write can create or replace a file.
65        "Edit" | "MultiEdit" => Operation::Modify,
66        _ => return Vec::new(),
67    };
68    input["file_path"]
69        .as_str()
70        .filter(|p| !p.is_empty())
71        .map(|p| vec![FileEvent::new(session, cwd, Path::new(p), at, operation, source)])
72        .unwrap_or_default()
73}
74
75fn patch_events(session: &SessionKey, cwd: &Path, patch: &str, at: i64, source: Source) -> Vec<FileEvent> {
76    let lines: Vec<_> = patch.trim().lines().collect();
77    if lines.first() != Some(&"*** Begin Patch") || lines.last() != Some(&"*** End Patch") {
78        return Vec::new();
79    }
80    let mut events: Vec<FileEvent> = Vec::new();
81    for line in lines {
82        if let Some(path) = line.strip_prefix("*** Move to: ") {
83            if let Some(previous) = events.last_mut().filter(|e| e.operation == Operation::Modify && !path.is_empty()) {
84                previous.previous_path = Some(previous.path.clone());
85                previous.path = resolve_path(cwd, Path::new(path));
86                previous.operation = Operation::Rename;
87            }
88            continue;
89        }
90        for (prefix, operation) in [
91            ("*** Add File: ", Operation::Create),
92            ("*** Update File: ", Operation::Modify),
93            ("*** Delete File: ", Operation::Delete),
94        ] {
95            if let Some(path) = line.strip_prefix(prefix).filter(|p| !p.is_empty()) {
96                events.push(FileEvent::new(session, cwd, Path::new(path), at, operation, source));
97            }
98        }
99    }
100    events
101}
102
103/// Claude keeps each subagent's transcript next to the main one, in
104/// `<transcript stem>/subagents/`. Sorted for stable results.
105pub fn subagent_transcripts(transcript: &Path) -> Vec<PathBuf> {
106    let Ok(entries) = fs::read_dir(transcript.with_extension("").join("subagents")) else {
107        return Vec::new();
108    };
109    let mut paths: Vec<_> = entries
110        .flatten()
111        .map(|entry| entry.path())
112        .filter(|path| path.extension().is_some_and(|e| e == "jsonl") && path.is_file())
113        .collect();
114    paths.sort();
115    paths
116}
117
118/// Transcript tail read for the last agent activity; enough for many records
119/// while keeping the read cheap on transcripts of any size.
120const ACTIVITY_TAIL_BYTES: u64 = 512 * 1024;
121
122/// When the agent last did something, in Unix seconds: the newest assistant
123/// message or tool result near the end of a Claude transcript. A new prompt is
124/// neither, so this still dates an interrupted turn once the next prompt has
125/// been written. `None` when the tail holds no such record.
126pub fn transcript_last_activity(transcript: &Path) -> Option<i64> {
127    let mut file = fs::File::open(transcript).ok()?;
128    let length = file.metadata().ok()?.len();
129    let start = length.saturating_sub(ACTIVITY_TAIL_BYTES);
130    file.seek(SeekFrom::Start(start)).ok()?;
131    let mut tail = Vec::new();
132    file.read_to_end(&mut tail).ok()?;
133    let text = String::from_utf8_lossy(&tail);
134    // A tail that starts mid-file starts mid-record.
135    let lines = text.lines().skip(usize::from(start > 0));
136    lines
137        .filter(|line| line.contains("\"assistant\"") || line.contains("\"tool_result\""))
138        .filter_map(|line| serde_json::from_str::<Value>(line).ok())
139        .filter(|record| {
140            record["type"] == "assistant"
141                || (record["type"] == "user"
142                    && record["message"]["content"]
143                        .as_array()
144                        .is_some_and(|items| items.iter().any(|item| item["type"] == "tool_result")))
145        })
146        .filter_map(|record| {
147            let at = OffsetDateTime::parse(record["timestamp"].as_str()?, &Rfc3339).ok()?;
148            Some(at.unix_timestamp())
149        })
150        .max()
151}
152
153/// Match Claude tool requests to results by call ID. Requests without results
154/// have unknown outcomes. Codex transcripts remain outside this adapter.
155pub fn transcript_events(session: &SessionKey, cwd: &Path, transcript: &Path) -> Vec<FileEvent> {
156    if session.agent != Agent::Claude {
157        return Vec::new();
158    }
159    let Ok(file) = fs::File::open(transcript) else {
160        return Vec::new();
161    };
162    let mut events = Vec::new();
163    let mut results = HashMap::new();
164    for line in BufReader::new(file).lines().map_while(Result::ok) {
165        if !line.contains("\"tool_use\"") && !line.contains("\"tool_result\"") {
166            continue;
167        }
168        let Ok(record) = serde_json::from_str::<Value>(&line) else {
169            continue;
170        };
171        if record["type"] == "user" {
172            if let Some(content) = record["message"]["content"].as_array() {
173                for item in content.iter().filter(|item| item["type"] == "tool_result") {
174                    if let Some(id) = item["tool_use_id"].as_str() {
175                        let result = match item.get("is_error") {
176                            Some(Value::Bool(true)) => Outcome::Failed,
177                            Some(Value::Bool(false)) | None => Outcome::Succeeded,
178                            _ => Outcome::Unknown,
179                        };
180                        results
181                            .entry(id.to_owned())
182                            .and_modify(|old| {
183                                if *old != result {
184                                    *old = Outcome::Unknown;
185                                }
186                            })
187                            .or_insert(result);
188                    }
189                }
190            }
191            continue;
192        }
193        if record["type"] != "assistant" {
194            continue;
195        }
196        let at = record["timestamp"]
197            .as_str()
198            .and_then(|ts| OffsetDateTime::parse(ts, &Rfc3339).ok())
199            .map(|t| t.unix_timestamp())
200            .unwrap_or(0);
201        let Some(content) = record["message"]["content"].as_array() else {
202            continue;
203        };
204        let cwd = record["cwd"].as_str().map(Path::new).filter(|p| p.is_absolute()).unwrap_or(cwd);
205        for item in content.iter().filter(|item| item["type"] == "tool_use") {
206            let mut found = tool_events(
207                session,
208                cwd,
209                item["name"].as_str().unwrap_or_default(),
210                &item["input"],
211                at,
212                Source::Transcript,
213            );
214            for event in &mut found {
215                event.tool_call_id = item["id"].as_str().map(str::to_owned);
216            }
217            events.extend(found);
218        }
219    }
220    for event in &mut events {
221        if let Some(result) = event.tool_call_id.as_ref().and_then(|id| results.get(id)) {
222            event.outcome = *result;
223        }
224    }
225    events
226}