1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
//! Subscribe command: multiplexed event stream from all active sessions.
//!
//! Watches all active session JSONL files and outputs a single merged
//! event stream. This is the read-side primitive for building real
//! orchestration on top of zag.
use crate::listen;
use anyhow::{Result, bail};
use log::debug;
use std::io::{BufRead, BufReader, Seek, SeekFrom};
use zag_agent::session::SessionStore;
use zag_agent::session_log::AgentLogEvent;
/// Parameters for the subscribe command.
pub struct SubscribeParams {
pub tag: Option<String>,
pub event_type: Option<String>,
pub global: bool,
pub json: bool,
pub root: Option<String>,
}
/// A tracked log file with its current read position.
struct TrackedLog {
#[allow(dead_code)]
session_id: String,
reader: BufReader<std::fs::File>,
}
/// Discover active session log files.
fn discover_sessions(params: &SubscribeParams) -> Result<Vec<(String, std::path::PathBuf)>> {
let store = if params.global {
SessionStore::load_all()?
} else {
SessionStore::load(params.root.as_deref())?
};
let sessions: Vec<_> = if let Some(ref tag) = params.tag {
store.find_by_tag(tag).into_iter().cloned().collect()
} else {
store.sessions.clone()
};
let mut result = Vec::new();
for entry in &sessions {
match listen::resolve_session_log(
Some(&entry.session_id),
false,
false,
params.root.as_deref(),
) {
Ok(path) => {
if path.exists() {
result.push((entry.session_id.clone(), path));
}
}
Err(_) => continue,
}
}
Ok(result)
}
/// Run the subscribe command.
pub fn run_subscribe(params: SubscribeParams) -> Result<()> {
let sessions = discover_sessions(¶ms)?;
if sessions.is_empty() {
bail!("No active sessions found to subscribe to");
}
debug!("Subscribing to {} session(s)", sessions.len());
// Open all log files and seek to end
let mut tracked: Vec<TrackedLog> = Vec::new();
for (session_id, path) in &sessions {
match std::fs::File::open(path) {
Ok(mut file) => {
let _ = file.seek(SeekFrom::End(0));
tracked.push(TrackedLog {
session_id: session_id.clone(),
reader: BufReader::new(file),
});
}
Err(e) => {
debug!("Failed to open log for session {}: {}", session_id, e);
}
}
}
if tracked.is_empty() {
bail!("Could not open any session logs");
}
// Poll loop: read new lines from all tracked logs
loop {
let mut had_data = false;
for log in &mut tracked {
loop {
let mut line = String::new();
match log.reader.read_line(&mut line) {
Ok(0) => break, // No more data in this file
Ok(_) => {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let event: AgentLogEvent = match serde_json::from_str(trimmed) {
Ok(e) => e,
Err(_) => continue,
};
// Filter by event type
if let Some(ref type_filter) = params.event_type {
let event_type = match &event.kind {
zag_agent::session_log::LogEventKind::SessionStarted { .. } => {
"session_started"
}
zag_agent::session_log::LogEventKind::SessionEnded { .. } => {
"session_ended"
}
zag_agent::session_log::LogEventKind::UserMessage { .. } => {
"user_message"
}
zag_agent::session_log::LogEventKind::AssistantMessage {
..
} => "assistant_message",
zag_agent::session_log::LogEventKind::ToolCall { .. } => {
"tool_call"
}
zag_agent::session_log::LogEventKind::ToolResult { .. } => {
"tool_result"
}
_ => "other",
};
if event_type != type_filter.as_str() {
continue;
}
}
had_data = true;
if params.json {
println!("{}", serde_json::to_string(&event).unwrap_or_default());
} else {
let id_short =
&event.wrapper_session_id[..event.wrapper_session_id.len().min(8)];
let type_name = match &event.kind {
zag_agent::session_log::LogEventKind::SessionStarted { .. } => {
"session_started"
}
zag_agent::session_log::LogEventKind::SessionEnded { .. } => {
"session_ended"
}
zag_agent::session_log::LogEventKind::AssistantMessage {
..
} => "assistant_message",
zag_agent::session_log::LogEventKind::ToolCall { .. } => {
"tool_call"
}
_ => "event",
};
println!("[{}] {} {}", id_short, event.ts, type_name);
}
}
Err(_) => break,
}
}
}
if !had_data {
std::thread::sleep(std::time::Duration::from_millis(200));
}
}
}
#[cfg(test)]
#[path = "subscribe_tests.rs"]
mod tests;