Skip to main content

tracevault_cli/commands/
stream.rs

1use std::fs::{self, OpenOptions};
2use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
3use std::path::Path;
4
5use tracevault_core::hooks::{parse_hook_event, HookResponse};
6use tracevault_core::streaming::{
7    extract_is_error_from_transcript, StreamEventRequest, StreamEventType,
8};
9
10pub fn read_new_transcript_lines(
11    transcript_path: &Path,
12    offset_path: &Path,
13) -> Result<(Vec<serde_json::Value>, i64), io::Error> {
14    if !transcript_path.exists() {
15        return Ok((vec![], 0));
16    }
17
18    let offset: i64 = if offset_path.exists() {
19        let content = fs::read_to_string(offset_path)?;
20        content
21            .trim()
22            .parse::<i64>()
23            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
24    } else {
25        0
26    };
27
28    let mut file = fs::File::open(transcript_path)?;
29    file.seek(SeekFrom::Start(offset as u64))?;
30
31    let reader = io::BufReader::new(file);
32    let mut lines = Vec::new();
33    let mut bytes_read = offset;
34
35    for line_result in reader.lines() {
36        let line = line_result?;
37        // +1 for the newline character
38        bytes_read += line.len() as i64 + 1;
39        if line.trim().is_empty() {
40            continue;
41        }
42        if let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) {
43            lines.push(value);
44        }
45    }
46
47    Ok((lines, bytes_read))
48}
49
50pub fn append_pending(pending_path: &Path, json: &str) -> Result<(), io::Error> {
51    let mut file = OpenOptions::new()
52        .create(true)
53        .append(true)
54        .open(pending_path)?;
55    writeln!(file, "{json}")?;
56    Ok(())
57}
58
59pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
60    if !pending_path.exists() {
61        return Ok(vec![]);
62    }
63    let content = fs::read_to_string(pending_path)?;
64    let lines: Vec<String> = content
65        .lines()
66        .filter(|l| !l.trim().is_empty())
67        .map(String::from)
68        .collect();
69    fs::remove_file(pending_path)?;
70    Ok(lines)
71}
72
73pub async fn run_stream(event_type: &str) -> Result<(), Box<dyn std::error::Error>> {
74    // 1. Read HookEvent from stdin
75    let mut input = String::new();
76    io::stdin().read_to_string(&mut input)?;
77    let hook_event = parse_hook_event(&input)?;
78
79    // Resolve project_root from hook_event.cwd (the repo directory Claude Code reports),
80    // walking up to find the nearest .tracevault/ directory. Falls back to cwd if not found.
81    let hook_cwd = Path::new(&hook_event.cwd);
82    let project_root = hook_cwd
83        .ancestors()
84        .find(|p| p.join(".tracevault").exists())
85        .unwrap_or(hook_cwd);
86
87    // 2. Create session dir
88    let session_dir = project_root
89        .join(".tracevault")
90        .join("sessions")
91        .join(&hook_event.session_id);
92    fs::create_dir_all(&session_dir)?;
93
94    // 3. Mint a time-ordered event id. UUIDv7 is stamped at hook-fire time, so
95    //    it both orders events and is a stable idempotency key — no shared
96    //    `.event_counter` file (which raced between concurrent parallel-tool
97    //    hooks and could collide/drop events).
98    let event_uuid = uuid::Uuid::now_v7();
99
100    // 4. Read new transcript lines
101    let transcript_path = Path::new(&hook_event.transcript_path);
102    let offset_path = session_dir.join(".stream_offset");
103    let (transcript_lines, new_offset) = read_new_transcript_lines(transcript_path, &offset_path)?;
104
105    // 5. Build StreamEventRequest
106    let stream_event_type = match event_type {
107        "notification" => StreamEventType::SessionStart,
108        "stop" => StreamEventType::SessionEnd,
109        _ => StreamEventType::ToolUse,
110    };
111
112    // Extract is_error from transcript for this tool_use_id
113    let tool_is_error = hook_event
114        .tool_use_id
115        .as_deref()
116        .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines));
117
118    let mut req = StreamEventRequest {
119        protocol_version: 1,
120        tool: Some("claude-code".to_string()),
121        event_type: stream_event_type,
122        session_id: hook_event.session_id.clone(),
123        timestamp: chrono::Utc::now(),
124        hook_event_name: Some(hook_event.hook_event_name.clone()),
125        tool_name: hook_event.tool_name.clone(),
126        tool_use_id: hook_event.tool_use_id.clone(),
127        tool_input: hook_event.tool_input.clone(),
128        tool_response: hook_event.tool_response.clone(),
129        tool_is_error,
130        event_index: None,
131        event_uuid: Some(event_uuid),
132        transcript_lines: if transcript_lines.is_empty() {
133            None
134        } else {
135            Some(transcript_lines)
136        },
137        transcript_offset: Some(new_offset),
138        model: None,
139        cwd: Some(hook_event.cwd.clone()),
140        final_stats: None,
141        flow_id: None,
142        labels: None,
143        params: None,
144    };
145
146    req.truncate_large_fields();
147
148    // 6. Resolve credentials
149    let (server_url, token) = crate::api_client::resolve_credentials(project_root);
150
151    // 7. Load config for org_slug and repo_id
152    let config =
153        crate::config::TracevaultConfig::load(project_root).ok_or("TracevaultConfig not found")?;
154    let org_slug = config
155        .org_slug
156        .as_deref()
157        .ok_or("org_slug not configured")?;
158    let repo_id = config.repo_id.as_deref().ok_or("repo_id not configured")?;
159
160    // 8. Create ApiClient
161    let server_url = server_url.ok_or("server_url not configured")?;
162    let client = crate::api_client::ApiClient::new(&server_url, token.as_deref());
163
164    // 9. Try drain pending queue and send
165    let pending_path = session_dir.join("pending.jsonl");
166    let pending_events = drain_pending(&pending_path)?;
167
168    let mut send_failed = false;
169
170    // Send pending events first
171    for pending_json in &pending_events {
172        if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
173            if client
174                .stream_event(org_slug, repo_id, &pending_req)
175                .await
176                .is_err()
177            {
178                // Re-queue all remaining pending events
179                for evt in &pending_events {
180                    append_pending(&pending_path, evt)?;
181                }
182                send_failed = true;
183                break;
184            }
185        }
186    }
187
188    // Send current event
189    let req_json = serde_json::to_string(&req)?;
190    if send_failed {
191        append_pending(&pending_path, &req_json)?;
192    } else {
193        match client.stream_event(org_slug, repo_id, &req).await {
194            Ok(_) => {
195                // 10. On success update .stream_offset
196                fs::write(&offset_path, new_offset.to_string())?;
197            }
198            Err(_) => {
199                // 11. On failure append to pending.jsonl
200                append_pending(&pending_path, &req_json)?;
201            }
202        }
203    }
204
205    // 12. Always print HookResponse::allow() to stdout
206    let response = HookResponse::allow();
207    println!("{}", serde_json::to_string(&response)?);
208
209    Ok(())
210}