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
//! The watcher's record of one turn (X4a): it reads the harness's native
//! output as it relays it, keeps the turn's tool calls in a private spool
//! file and the words its answer is made of, and hands the filing what the
//! child's own hooks would have handed the record verb. The file is
//! removed from the directory as soon as it is made, so it goes with the
//! watcher however the watcher ends, and nothing the child runs can open it.
//! One completed turn gives one record: a repeated completion or a repeated
//! tool call is ignored, and what follows the completion is not this turn.
//! The turn is kept whole within its bound or not at all: a line longer
//! than `LINE_BYTES` or a turn past `TURN_BYTES` marks it over its bound,
//! and the filing then records nothing for it. Everything held is charged
//! to that bound (spooled calls, retained words, tool inputs waiting for
//! their results), and once it is passed the capture lets go of all of it
//! and reads no more, while the watcher still relays the output (X4e P5).
use std::collections::{HashSet, VecDeque};
use std::fs::File;
use std::io::BufWriter;
use serde_json::Value;
use super::adapter::Agent;
use super::native::{self, Said};
mod spool;
use spool::{rewound, size};
/// The longest line of native output the record reads.
pub const LINE_BYTES: usize = 8 << 20;
/// The most one turn's spooled tool calls and answer may hold.
pub const TURN_BYTES: u64 = 64 << 20;
/// Claude Code tool calls whose results have not arrived yet.
const CALLS_KEPT: usize = 256;
/// What the record holds of a turn while it runs.
pub struct Capture {
agent: Agent,
line: Vec<u8>,
line_bytes: usize,
turn_bytes: u64,
session: Option<String>,
calls: VecDeque<(String, String, Value)>,
/// The bytes of the calls in `calls`, ids and names included.
pending: u64,
/// The bytes of the answer held.
answer_bytes: u64,
seen: HashSet<String>,
texts: Vec<String>,
text_bytes: u64,
answer: Option<String>,
completed: bool,
failed: bool,
over: bool,
spool: Option<BufWriter<File>>,
spooled: u64,
error: Option<String>,
/// Pi's and Cursor's streams are read with the turn's state (X5a, X5b).
reader: Option<native::state::Reader>,
}
/// The turn as the filing receives it.
pub struct Captured {
pub session: Option<String>,
/// The provider completed the turn and reported no failure first.
pub completed: bool,
/// The answer the child's Stop hook would have carried.
pub answer: String,
/// A line or the turn passed its bound.
pub over: bool,
/// The spooled PostToolUse payloads, one JSON object per line, read
/// from the start.
pub tools: Option<File>,
/// The spool could not be written.
pub error: Option<String>,
}
impl Capture {
pub fn new(agent: Agent) -> Self {
Self::bounded(agent, LINE_BYTES, TURN_BYTES)
}
/// A capture with the given bounds (the watcher uses `new`).
pub fn bounded(agent: Agent, line_bytes: usize, turn_bytes: u64) -> Self {
Self {
agent,
line: Vec::new(),
line_bytes,
turn_bytes,
session: None,
calls: VecDeque::new(),
pending: 0,
answer_bytes: 0,
seen: HashSet::new(),
texts: Vec::new(),
text_bytes: 0,
answer: None,
completed: false,
failed: false,
over: false,
spool: None,
spooled: 0,
error: None,
reader: native::state::Reader::of(agent),
}
}
/// Bytes of native output as they arrive; none once over the bound.
pub fn push(&mut self, mut bytes: &[u8]) {
while !bytes.is_empty() && !self.over {
let (chunk, newline) = match bytes.iter().position(|b| *b == b'\n') {
Some(at) => (&bytes[..at], Some(at)),
None => (bytes, None),
};
if self.line.len() + chunk.len() > self.line_bytes {
self.release();
return;
}
self.line.extend_from_slice(chunk);
match newline {
Some(at) => {
let line = std::mem::take(&mut self.line);
self.line(&String::from_utf8_lossy(&line));
bytes = &bytes[at + 1..];
}
None => bytes = &[],
}
}
}
fn line(&mut self, line: &str) {
let said = match self.reader.as_mut() {
Some(reader) => match serde_json::from_str(line) {
Ok(Value::Object(event)) => reader.line(&event),
// A line the stream cannot read (X6c U7).
_ if !line.trim().is_empty() => reader.malformed(),
_ => Vec::new(),
},
None => native::read(self.agent, line),
};
for said in said {
self.take(said);
}
// The stateful reader's own state counts toward the bound (X5d).
self.check();
}
fn take(&mut self, said: Said) {
// What follows the completion is not this turn's.
if self.completed || self.over {
return;
}
match said {
Said::Session(session) => {
self.session.get_or_insert(session);
}
Said::Call { id, name, input } => {
// A call that cannot be kept would leave a round out: the
// turn is then not complete, never filed short (X5d).
if self.calls.len() == CALLS_KEPT
&& let Some((id, name, input)) = self.calls.pop_front()
{
self.pending -= size(&id, &name, &input);
self.failed = true;
}
// The whole call is held, its id and name too (X4f Q7).
self.pending += size(&id, &name, &input);
self.calls.push_back((id, name, input));
self.check();
}
Said::Result { id, response, ok } => {
let Some(at) = self.calls.iter().position(|(call, _, _)| *call == id) else {
return;
};
let (id, name, input) = self.calls.remove(at).expect("found");
self.pending -= size(&id, &name, &input);
if ok {
self.tool(Some(id), name, input, response);
}
}
Said::Tool {
id,
name,
input,
response,
} => self.tool(id, name, input, response),
Said::Text(words) => {
if self.agent != Agent::OpenCode {
self.texts.clear();
self.text_bytes = 0;
}
self.text_bytes += words.len() as u64;
self.texts.push(words);
self.check();
}
Said::Step => {
self.texts.clear();
self.text_bytes = 0;
}
Said::Answer(answer) => {
self.answer_bytes = answer.len() as u64;
self.answer = Some(answer);
self.check();
}
Said::Completed => self.completed = !self.failed,
Said::Failed => self.failed = true,
}
}
fn check(&mut self) {
let held = self.reader.as_ref().map_or(0, native::state::Reader::held);
let kept = self.spooled + self.text_bytes + self.pending + self.answer_bytes;
if kept + held > self.turn_bytes {
self.release();
}
}
/// Over the bound: nothing of the turn is kept or read any more.
fn release(&mut self) {
self.over = true;
self.line = Vec::new();
self.calls = VecDeque::new();
self.pending = 0;
self.seen = HashSet::new();
self.texts = Vec::new();
self.text_bytes = 0;
self.answer = None;
self.answer_bytes = 0;
self.spool = None;
self.reader = None;
}
/// The turn as it stands, its spool read from the start; `eof` says
/// the harness's output reached its end (X6c U7).
pub fn finish(mut self, eof: bool) -> Captured {
if !self.over && !self.line.is_empty() {
let line = std::mem::take(&mut self.line);
self.line(&String::from_utf8_lossy(&line));
}
for said in self
.reader
.as_mut()
.map(|r| r.finish(eof))
.unwrap_or_default()
{
self.take(said);
}
let tools = rewound(self.spool.take()).unwrap_or_else(|error| {
self.error = Some(error);
None
});
let answer = match (self.agent, self.answer) {
(_, Some(answer)) if self.reader.is_some() || self.agent == Agent::ClaudeCode => answer,
_ => self.texts.join("\n"),
};
Captured {
session: self.session,
completed: self.completed,
answer,
over: self.over,
tools,
error: self.error,
}
}
}
#[cfg(test)]
mod tests;