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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use crate::message::{AgentMessage, StopReason, Usage};
use serde::{Deserialize, Serialize};
/// Internal seam between LLM adapter and agent loop. Not serialized.
#[derive(Clone, Debug, PartialEq)]
pub enum LlmStreamEvent {
TextDelta(String),
ThinkingDelta(String),
/// A complete thinking block (provider restates the whole reasoning after
/// streaming deltas). Replacement semantics: supersedes *all* thinking
/// accumulated so far in this message — the kernel drops prior thinking
/// blocks instead of appending, so the context never doubles up.
ThinkingReplace(String),
ToolCall {
id: String,
name: String,
arguments: serde_json::Value,
},
Done {
stop_reason: StopReason,
usage: Option<Usage>,
},
/// The adapter is about to retry a failed connect after a transient error.
/// `attempt` is 1-based; advisory — the loop only surfaces it.
Retrying {
attempt: u32,
max: u32,
reason: String,
},
Error {
message: String,
/// True when the failure is of a hard-fatal class (bad request, auth,
/// schema, build/parse) that retrying or re-feeding cannot fix. The
/// loop ends the run on a fatal error; a transient-class error that
/// exhausted its retries (or landed mid-stream after content) is fed
/// back to the model for a corrective turn instead.
fatal: bool,
},
}
/// The status of a [`TodoItem`]. `Cancelled` is deliberately absent in v1: the
/// model drops an item by rewriting the whole list.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TodoStatus {
Pending,
InProgress,
Completed,
}
/// One entry in the `todo` tool's session-local checklist. Lives in the harness
/// because it rides the serialized [`AgentEvent`] (the CLI tool reuses it).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct TodoItem {
/// What the item is about (non-empty after trim; the tool validates).
pub content: String,
pub status: TodoStatus,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AgentEvent {
AgentStart,
TurnStart,
MessageStart {
message: AgentMessage,
},
MessageUpdate {
message: AgentMessage,
},
MessageEnd {
message: AgentMessage,
},
ToolExecutionStart {
call_id: String,
name: String,
},
ToolExecutionUpdate {
call_id: String,
name: String,
partial: String,
},
ToolExecutionEnd {
call_id: String,
name: String,
output: String,
is_error: bool,
/// UI-only unified diff (see `ToolOutput::diff`); absent when there is
/// nothing to show, or on an older peer that predates the field.
#[serde(default, skip_serializing_if = "Option::is_none")]
diff: Option<String>,
/// UI-only path of the changed file (see `ToolOutput::path`); absent
/// when the tool touched no file, or on an older peer.
#[serde(default, skip_serializing_if = "Option::is_none")]
path: Option<String>,
/// Wall-clock duration of the tool call in milliseconds — `execute` plus
/// its `after_tool_call` hook. UI-only, like `diff`/`path`: it rides this
/// event but never enters `ToolOutput`/the model's context. `None` on an
/// older peer, or a call that never ran (blocked by a hook, or a dead
/// sink).
#[serde(default, skip_serializing_if = "Option::is_none")]
duration_ms: Option<u64>,
},
TurnEnd {
message: AgentMessage,
},
/// Auto-compaction summarized `summarized` older messages, keeping `kept`.
Compaction {
summarized: usize,
kept: usize,
},
/// Best-effort auto-compaction was attempted (the context was near the
/// ceiling) but did NOT complete — a summarizer/stream failure. The run
/// continues. Deliberately NOT [`AgentEvent::Error`], whose contract is a
/// *stream-level* failure: a TUI renders `Error` as a failed run, so routing
/// a best-effort compaction miss through it would falsely mark the run
/// failed. `reason` is the summarizer's error text, for display only — never
/// fed back to the model and never fatal. Purely additive on the wire
/// (`{"type":"compaction_skipped","reason":…}`), so
/// [`crate::protocol::PROTOCOL_VERSION`] need not bump.
CompactionSkipped {
reason: String,
},
/// The adapter retried a failed connect after a transient error.
Retrying {
attempt: u32,
max: u32,
reason: String,
},
/// A peer delivered a message to this session (`Request::Notify`/
/// `Interrupt`/`Wake`). `from` is the sender's address (§5.2 — the human is
/// [`crate::protocol::USER`]); streamed, so a UI can surface an inbound
/// message. Not a reply.
MessageReceived {
from: crate::protocol::SessionId,
content: String,
},
/// Stream-level failure. A fatal-class failure (bad request, auth, schema)
/// ends the run with `StopReason::Error`; a transient-class failure that
/// exhausted its retries (or landed mid-stream) is fed back to the model
/// and the loop continues, still bounded by a consecutive-error cap.
Error {
message: String,
},
/// Reply: a request with no richer answer succeeded (e.g. `SetModel`).
/// Never *streamed* — it answers one request, correlated by the transport
/// (an in-process reply channel today, the envelope's `reply_to` on the
/// wire).
Ack,
/// Reply: the run finished, with why it stopped. Answers a `Submit`. Never
/// streamed (see [`AgentEvent::Ack`]).
Stopped {
stop_reason: StopReason,
},
/// Reply: a tool-free side answer to a `Request::SideAsk` (`/btw`). Never
/// streamed (see [`AgentEvent::Ack`]). Carries the answer text and the
/// turn's usage (for a `/usage`-style readout); styling is the front-end's.
SideAnswer {
text: String,
usage: Option<Usage>,
},
/// Reply: the conversation so far, answering a `Request::GetHistory`. Never
/// streamed (see [`AgentEvent::Ack`]).
History {
messages: Vec<AgentMessage>,
},
/// Reply: a compact status — the text of the session's most recent assistant
/// message — answering a [`crate::protocol::Request::Status`]. Never streamed
/// (see [`AgentEvent::Ack`]); one small string, not the transcript.
Status {
last_assistant_text: Option<String>,
},
/// Reply: the agent's own settings, answering a
/// [`crate::protocol::Request::Settings`]. Never streamed (see
/// [`AgentEvent::Ack`]) — one reply, correlated by the transport, exactly
/// like [`AgentEvent::Status`]; what ships is four scalars, not the
/// transcript, so a mid-session read needs no baseline and compaction
/// cannot invalidate it.
///
/// `context_limit: None` means the window is UNKNOWN — never `0`, and
/// never a guess. Today `limits::model_limit` recognises one endpoint
/// family (`limits.rs:63`), so `None` is the common case and the panel
/// renders the honest absence (`docs/work/W032-tui-settings.md` §11.8).
///
/// Purely additive on the wire (`{"type":"settings","model":…}`) — an
/// older peer drops the frame — so `PROTOCOL_VERSION` stays 1, the same
/// argument `Usage` records above.
Settings {
model: String,
effort: Option<String>,
plan: bool,
context_limit: Option<u64>,
},
/// Reply: this session's usage report — turns, summed input/output/cache
/// tokens, the cache hit rate, per-tool `calls`/`errors`/`result_bytes`, and
/// a `$` cost when the model is priced (all inside [`crate::stats::SessionStats`]).
/// Answers a [`crate::protocol::Request::Usage`]. Never streamed (see
/// [`AgentEvent::Ack`]) — the [`AgentEvent::Status`] rationale: a FOLDED
/// summary ships, not the transcript, so a mid-session `Usage` needs no
/// baseline and cannot be invalidated by compaction. Purely additive on the
/// wire (`{"type":"usage","stats":{…}}`), exactly like `CompactionSkipped`
/// (`event.rs:117-119`) — an older peer drops the frame — so
/// `crate::protocol::PROTOCOL_VERSION` stays 1.
///
/// `stats.cost` is `None` when nothing could be priced (an unknown model, or
/// a session that reported no usage) — absence, never `$0`.
Usage {
stats: crate::stats::SessionStats,
},
/// Reply: the model catalog the provider advertises, answering a
/// [`crate::protocol::Request::ListModels`]. Never streamed (see
/// [`AgentEvent::Ack`]) — one reply, correlated by the transport, exactly
/// like [`AgentEvent::Sessions`]. Each entry is a bare model id; ordering
/// is the provider's (`streamfn::list_models`).
Models {
models: Vec<String>,
},
/// Reply: the sessions a server serves, in order (root first), each
/// with the model the server knows for it ([`crate::protocol::SessionInfo`]).
/// Answers a [`crate::protocol::Request::ListSessions`]. Never streamed (see
/// [`AgentEvent::Ack`]).
Sessions {
sessions: Vec<crate::protocol::SessionInfo>,
},
/// Reply: a peer defined a worker and returns its address, answering a
/// [`crate::protocol::Request::Define`]. Never streamed (see
/// [`AgentEvent::Ack`]).
///
/// The field is `worker`, not `id`: the envelope already carries a top-level
/// `id` (the request it replies to), and a flattened duplicate key would not
/// deserialize.
Spawned {
worker: crate::protocol::SessionId,
},
/// The `todo` checklist, streamed on every write (mirror `Compaction` /
/// `Retrying`: a plain state payload the UI reduces). The field is `todos`,
/// not `id`: the envelope already carries a top-level `id` and a flattened
/// duplicate key would not deserialize.
Todo {
todos: Vec<TodoItem>,
},
/// The session's title is now `title` (W031) — STREAMED, like `Todo` /
/// `Compaction` (a plain state payload the UI reduces), and also the reply
/// to a [`crate::protocol::Request::SetTitle`]. Emitted by the loop's
/// auto-titler at a turn boundary and by the actor's `SetTitle` arm.
///
/// The field is `title`, not `id`: the envelope already carries a top-level
/// `id` and a flattened duplicate key would not deserialize — the same
/// constraint `Todo`/`Spawned` document.
///
/// Wire note: unlike `Request`, this enum has **no** `#[serde(other)]`
/// catch-all (it is exhaustive by design). A peer that cannot deserialize a
/// new variant does not skip it — `read_frame` returns `Err` and the socket
/// client breaks its read loop and RECONNECTS. So an old client talking to a
/// new auto-titling server drops the connection once per titled session.
/// That is pre-existing forward-compat behaviour and deliberately NOT
/// "fixed" by adding an `Unknown` arm here (which would make every
/// consumer's match silently permissive instead of exhaustive).
SessionTitle {
title: String,
},
AgentEnd,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::message::ContentBlock;
use serde_json::json;
fn roundtrip(e: AgentEvent, expected_tag: &str) {
let v = serde_json::to_value(&e).unwrap();
assert_eq!(v["type"], expected_tag);
let back: AgentEvent = serde_json::from_value(v.clone()).unwrap();
let v2 = serde_json::to_value(&back).unwrap();
assert_eq!(v, v2);
}
fn assistant() -> AgentMessage {
AgentMessage::Assistant {
content: vec![ContentBlock::Text { text: "a".into() }],
stop_reason: StopReason::Stop,
usage: Some(Usage::default()),
model: None,
}
}
#[test]
fn agent_event_roundtrip_all_variants() {
roundtrip(AgentEvent::AgentStart, "agent_start");
roundtrip(AgentEvent::TurnStart, "turn_start");
roundtrip(
AgentEvent::MessageStart {
message: assistant(),
},
"message_start",
);
roundtrip(
AgentEvent::MessageUpdate {
message: assistant(),
},
"message_update",
);
roundtrip(
AgentEvent::MessageEnd {
message: assistant(),
},
"message_end",
);
roundtrip(
AgentEvent::ToolExecutionStart {
call_id: "t1".into(),
name: "run".into(),
},
"tool_execution_start",
);
roundtrip(
AgentEvent::ToolExecutionUpdate {
call_id: "t1".into(),
name: "run".into(),
partial: "out".into(),
},
"tool_execution_update",
);
roundtrip(
AgentEvent::ToolExecutionEnd {
call_id: "t1".into(),
name: "run".into(),
output: "out".into(),
is_error: false,
diff: Some("@@ -1 +1 @@".into()),
path: Some("src/f.rs".into()),
duration_ms: Some(12),
},
"tool_execution_end",
);
roundtrip(
AgentEvent::TurnEnd {
message: assistant(),
},
"turn_end",
);
roundtrip(
AgentEvent::Error {
message: "boom".into(),
},
"error",
);
roundtrip(
AgentEvent::Compaction {
summarized: 3,
kept: 2,
},
"compaction",
);
roundtrip(
AgentEvent::CompactionSkipped {
reason: "summarizer 500".into(),
},
"compaction_skipped",
);
roundtrip(
AgentEvent::Retrying {
attempt: 2,
max: 3,
reason: "503".into(),
},
"retrying",
);
roundtrip(AgentEvent::Ack, "ack");
roundtrip(
AgentEvent::Stopped {
stop_reason: StopReason::Aborted,
},
"stopped",
);
roundtrip(
AgentEvent::SideAnswer {
text: "hi".into(),
usage: None,
},
"side_answer",
);
roundtrip(
AgentEvent::History {
messages: vec![AgentMessage::user_text("hi")],
},
"history",
);
roundtrip(
AgentEvent::Status {
last_assistant_text: Some("last said".into()),
},
"status",
);
roundtrip(
AgentEvent::Settings {
model: "m1".into(),
effort: Some("high".into()),
plan: true,
context_limit: Some(200_000),
},
"settings",
);
// The unknown-window spelling survives the wire as `null`, not `0`.
roundtrip(
AgentEvent::Settings {
model: "m1".into(),
effort: None,
plan: false,
context_limit: None,
},
"settings",
);
roundtrip(
AgentEvent::Usage {
stats: crate::stats::SessionStats {
turns: 1,
input_tokens: 1_000,
output_tokens: 500,
cache_read_tokens: 400,
cache_write_tokens: 5,
cache_turns: 1,
tools: vec![crate::stats::ToolStat {
name: "read".into(),
calls: 2,
errors: 1,
result_bytes: 42,
}],
tool_errors: 1,
last_input_tokens: Some(1_000),
cost: Some(crate::stats::Cost {
micro_usd: 391,
unpriced_turns: 0,
}),
},
},
"usage",
);
roundtrip(
AgentEvent::Models { models: vec!["m1".into(), "m2".into()] },
"models",
);
roundtrip(
AgentEvent::MessageReceived {
from: crate::protocol::SessionId::new("user"),
content: "ping".into(),
},
"message_received",
);
roundtrip(AgentEvent::AgentEnd, "agent_end");
roundtrip(
AgentEvent::Sessions {
sessions: vec![
crate::protocol::SessionInfo {
id: crate::protocol::SessionId::new("root"),
model: Some("m1".into()),
effort: Some("high".into()),
context_window: Some(200_000),
state: crate::protocol::MemberState::Idle,
},
crate::protocol::SessionInfo {
id: crate::protocol::SessionId::agent("w1"),
model: None,
effort: None,
context_window: None,
state: crate::protocol::MemberState::Idle,
},
],
},
"sessions",
);
roundtrip(
AgentEvent::Spawned {
worker: crate::protocol::SessionId::agent("w1"),
},
"spawned",
);
roundtrip(
AgentEvent::Todo {
todos: vec![
TodoItem {
content: "write tests".into(),
status: TodoStatus::Pending,
},
TodoItem {
content: "ship it".into(),
status: TodoStatus::Completed,
},
],
},
"todo",
);
roundtrip(
AgentEvent::SessionTitle {
title: "retry backoff fix".into(),
},
"session_title",
);
}
#[test]
fn agent_event_shape_matches_tagged_payload() {
let v = serde_json::to_value(&AgentEvent::ToolExecutionStart {
call_id: "t1".into(),
name: "run".into(),
})
.unwrap();
assert_eq!(
v,
json!({"type": "tool_execution_start", "call_id": "t1", "name": "run"})
);
let m = AgentMessage::user_text("hi");
let v2 = serde_json::to_value(&AgentEvent::TurnEnd { message: m }).unwrap();
assert_eq!(v2["type"], "turn_end");
assert_eq!(v2["message"]["role"], "user");
// Pin the flat `usage` shape once so a field rename cannot slip past.
let v3 = serde_json::to_value(&AgentEvent::Usage {
stats: crate::stats::SessionStats {
turns: 1,
..Default::default()
},
})
.unwrap();
assert_eq!(v3["type"], "usage");
assert_eq!(v3["stats"]["turns"], 1);
}
}