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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
pub mod harnesses;
use std::io;
use std::path::{Path, PathBuf};
use std::time::Duration;
use serde_json::{json, Value};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use tokio::task::JoinHandle;
use crate::tools::ToolObserver;
pub use harnesses::claude_code_cli::ClaudeCodeCliHarness;
#[derive(Clone, Debug, PartialEq)]
pub struct MonitorEvent {
pub task_id: String,
pub description: String,
pub event: String,
pub source_uuid: String,
pub delivery_id: String,
pub human_turn: bool,
/// Instruction the model saw with this event; replaces the default
/// PushNotification sentence in Claude transcripts.
pub note: Option<String>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum TranscriptEvent {
User {
text: String,
},
Assistant {
text: String,
},
ToolCall {
id: String,
name: String,
arguments: Value,
},
ToolResult {
id: String,
content: String,
is_error: bool,
/// Harness metadata (code mode nested calls); not model input.
audit: Option<Value>,
},
MonitorEvent(MonitorEvent),
MonitorConsumed {
event: MonitorEvent,
reason: String,
},
}
pub trait SessionHarness: Send {
fn format_name(&self) -> &'static str;
fn session_id(&self) -> &str;
fn session_file(&self) -> &Path;
fn write_event(&mut self, event: &TranscriptEvent) -> io::Result<()>;
fn finish(&mut self) -> io::Result<()> {
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SessionInfo {
pub format: &'static str,
pub session_id: String,
pub session_file: PathBuf,
}
pub struct SessionLogger {
pub sessions: Vec<SessionInfo>,
pub agent_name: String,
tx: UnboundedSender<TranscriptEvent>,
join: JoinHandle<()>,
}
impl SessionLogger {
pub fn start(
harnesses: Vec<Box<dyn SessionHarness>>,
agent_name: impl Into<String>,
) -> io::Result<Self> {
if harnesses.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"at least one session harness is required",
));
}
let sessions = harnesses
.iter()
.map(|harness| SessionInfo {
format: harness.format_name(),
session_id: harness.session_id().to_string(),
session_file: harness.session_file().to_path_buf(),
})
.collect();
let (tx, rx) = mpsc::unbounded_channel();
let join = tokio::spawn(async move { run_harnesses(harnesses, rx).await });
Ok(Self {
sessions,
agent_name: agent_name.into(),
tx,
join,
})
}
/// Convenience accessor for the first configured harness.
pub fn session_id(&self) -> &str {
&self.sessions[0].session_id
}
/// Convenience accessor for the first configured harness.
pub fn session_file(&self) -> &Path {
&self.sessions[0].session_file
}
pub fn first_line(&self) -> io::Result<String> {
let first = self.sessions.first().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "no session harness configured")
})?;
serde_json::to_string(&json!({
"work_name": "session",
"result": {
"session_id": first.session_id,
"session_file": first.session_file.to_string_lossy(),
"harness": first.format,
"agent_name": self.agent_name,
"harnesses": self.sessions.iter().map(|session| json!({
"format": session.format,
"session_id": session.session_id,
"session_file": session.session_file.to_string_lossy(),
})).collect::<Vec<_>>(),
},
}))
.map_err(io::Error::other)
}
pub fn user_message(&self, text: impl Into<String>) {
let _ = self.tx.send(TranscriptEvent::User { text: text.into() });
}
pub fn assistant_message(&self, text: impl Into<String>) {
let _ = self
.tx
.send(TranscriptEvent::Assistant { text: text.into() });
}
pub fn monitor_event(&self, event: MonitorEvent) {
let _ = self.tx.send(TranscriptEvent::MonitorEvent(event));
}
pub fn monitor_consumed(&self, event: MonitorEvent, reason: impl Into<String>) {
let _ = self.tx.send(TranscriptEvent::MonitorConsumed {
event,
reason: reason.into(),
});
}
pub fn transcript_sender(&self) -> UnboundedSender<TranscriptEvent> {
self.tx.clone()
}
pub fn tool_observer(&self) -> std::sync::Arc<dyn ToolObserver> {
std::sync::Arc::new(SessionToolObserver {
tx: self.tx.clone(),
})
}
pub async fn close(self) {
let Self { tx, join, .. } = self;
drop(tx);
match tokio::time::timeout(Duration::from_secs(2), join).await {
Ok(Ok(())) => {}
Ok(Err(error)) => crate::log::emit(
"error",
"session.writer_failed",
serde_json::json!({"error": error.to_string()}),
),
Err(_) => crate::log::emit(
"error",
"session.flush_timeout",
serde_json::json!({"error": "writer did not flush before shutdown"}),
),
}
}
}
async fn run_harnesses(
mut harnesses: Vec<Box<dyn SessionHarness>>,
mut rx: UnboundedReceiver<TranscriptEvent>,
) {
while let Some(event) = rx.recv().await {
for harness in &mut harnesses {
if let Err(error) = harness.write_event(&event) {
crate::log::emit(
"error",
"session.write_failed",
serde_json::json!({"harness": harness.format_name(), "error": error.to_string()}),
);
}
}
}
for harness in &mut harnesses {
if let Err(error) = harness.finish() {
crate::log::emit(
"error",
"session.finish_failed",
serde_json::json!({"harness": harness.format_name(), "error": error.to_string()}),
);
}
}
}
struct SessionToolObserver {
tx: UnboundedSender<TranscriptEvent>,
}
impl ToolObserver for SessionToolObserver {
fn tool_call(&self, id: &str, name: &str, arguments: &Value) {
let _ = self.tx.send(TranscriptEvent::ToolCall {
id: id.to_string(),
name: name.to_string(),
arguments: arguments.clone(),
});
}
fn tool_result(&self, id: &str, content: &str, is_error: bool, audit: Option<&Value>) {
let _ = self.tx.send(TranscriptEvent::ToolResult {
id: id.to_string(),
content: content.to_string(),
is_error,
audit: audit.cloned(),
});
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use super::*;
struct MemoryHarness {
format: &'static str,
session_id: String,
path: PathBuf,
events: Arc<Mutex<Vec<TranscriptEvent>>>,
}
impl SessionHarness for MemoryHarness {
fn format_name(&self) -> &'static str {
self.format
}
fn session_id(&self) -> &str {
&self.session_id
}
fn session_file(&self) -> &Path {
&self.path
}
fn write_event(&mut self, event: &TranscriptEvent) -> io::Result<()> {
self.events.lock().unwrap().push(event.clone());
Ok(())
}
}
fn memory_harness(
format: &'static str,
id: &str,
) -> (Box<dyn SessionHarness>, Arc<Mutex<Vec<TranscriptEvent>>>) {
let events = Arc::new(Mutex::new(Vec::new()));
(
Box::new(MemoryHarness {
format,
session_id: id.to_string(),
path: PathBuf::from(format!("/tmp/{id}.jsonl")),
events: Arc::clone(&events),
}),
events,
)
}
#[tokio::test]
async fn fans_out_events_to_multiple_harnesses() {
let (first, first_events) = memory_harness("first", "session-one");
let (second, second_events) = memory_harness("second", "session-two");
let logger = SessionLogger::start(vec![first, second], "alice").unwrap();
let first_line: Value = serde_json::from_str(&logger.first_line().unwrap()).unwrap();
assert_eq!(first_line["result"]["session_id"], "session-one");
assert_eq!(
first_line["result"]["harnesses"].as_array().unwrap().len(),
2
);
logger.user_message("hello");
logger.assistant_message("hi");
logger.close().await;
let expected = vec![
TranscriptEvent::User {
text: "hello".to_string(),
},
TranscriptEvent::Assistant {
text: "hi".to_string(),
},
];
assert_eq!(*first_events.lock().unwrap(), expected);
assert_eq!(*second_events.lock().unwrap(), expected);
}
}