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
//! Events emitted by the core engine to the UI.
//!
//! These events flow from the engine to the TUI via a channel,
//! enabling non-blocking, real-time updates.
use std::{path::PathBuf, sync::Arc};
use serde_json::Value;
use crate::core::coherence::CoherenceState;
use crate::error_taxonomy::ErrorEnvelope;
use crate::models::{Message, SystemPrompt, Tool, Usage};
use crate::tools::spec::{ToolError, ToolResult};
use crate::tools::subagent::SubAgentResult;
use crate::tools::user_input::UserInputRequest;
/// Final status for a turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TurnOutcomeStatus {
Completed,
Interrupted,
Failed,
}
/// Events emitted by the engine to update the UI.
#[derive(Debug, Clone)]
pub enum Event {
// === Streaming Events ===
/// A new message block has started
MessageStarted {
#[allow(dead_code)]
index: usize,
},
/// Incremental text content delta
MessageDelta {
#[allow(dead_code)]
index: usize,
content: String,
},
/// Message block completed
MessageComplete {
#[allow(dead_code)]
index: usize,
},
/// Thinking block started
ThinkingStarted {
#[allow(dead_code)]
index: usize,
},
/// Incremental thinking content delta
ThinkingDelta {
#[allow(dead_code)]
index: usize,
content: String,
},
/// Thinking block completed
ThinkingComplete {
#[allow(dead_code)]
index: usize,
},
// === Tool Events ===
/// Tool call initiated
ToolCallStarted {
id: String,
name: String,
input: Value,
},
/// Tool execution progress (for long-running tools)
#[allow(dead_code)]
ToolCallProgress { id: String, output: String },
/// Tool call completed
ToolCallComplete {
id: String,
name: String,
result: Result<ToolResult, ToolError>,
},
// === Turn Lifecycle ===
/// A new turn has started (user sent a message)
TurnStarted { turn_id: String },
/// The turn is complete (no more tool calls)
TurnComplete {
usage: Usage,
status: TurnOutcomeStatus,
error: Option<String>,
/// Tool catalog sent with this turn's model request.
tool_catalog: Option<Vec<Tool>>,
/// API base URL used by this turn's client.
base_url: Option<String>,
},
/// Context compaction started.
CompactionStarted {
id: String,
auto: bool,
message: String,
},
/// Context compaction completed.
CompactionCompleted {
id: String,
auto: bool,
message: String,
/// Number of messages before compaction.
#[allow(dead_code)]
messages_before: Option<usize>,
/// Number of messages after compaction.
#[allow(dead_code)]
messages_after: Option<usize>,
},
/// Context purge started.
PurgeStarted {
/// Status message for display.
message: String,
},
/// Context purge completed.
PurgeCompleted {
/// Number of messages before purge.
messages_before: usize,
/// Number of messages after purge.
messages_after: usize,
/// How many messages were removed.
removed_count: usize,
/// How many replace operations were applied.
replaced_count: usize,
/// Summary message for display.
message: String,
},
/// Context purge failed.
PurgeFailed { message: String },
/// Context compaction failed.
CompactionFailed {
id: String,
auto: bool,
message: String,
},
/// Checkpoint-restart cycle boundary advanced (issue #124). The previous
/// cycle has already been archived to disk; the engine has swapped its
/// in-memory message buffer for the seed messages of cycle `to`.
/// Carries the full briefing record so the UI can populate
/// `app.cycle_briefings` for `/cycle <n>`.
CycleAdvanced {
from: u32,
to: u32,
briefing: crate::cycle_manager::CycleBriefing,
},
/// Capacity decision telemetry.
#[allow(dead_code)]
CapacityDecision {
session_id: String,
turn_id: String,
h_hat: f64,
c_hat: f64,
slack: f64,
min_slack: f64,
violation_ratio: f64,
p_fail: f64,
risk_band: String,
action: String,
cooldown_blocked: bool,
reason: String,
},
/// Capacity intervention telemetry.
#[allow(dead_code)]
CapacityIntervention {
session_id: String,
turn_id: String,
action: String,
before_prompt_tokens: usize,
after_prompt_tokens: usize,
compaction_size_reduction: usize,
replay_outcome: Option<String>,
replan_performed: bool,
},
/// Capacity memory persistence failure telemetry.
#[allow(dead_code)]
CapacityMemoryPersistFailed {
session_id: String,
turn_id: String,
action: String,
error: String,
},
/// Plain-language session coherence state.
CoherenceState {
state: CoherenceState,
label: String,
description: String,
reason: String,
},
// === Sub-Agent Events ===
/// A sub-agent has been spawned
AgentSpawned { id: String, prompt: String },
/// Sub-agent progress update
AgentProgress { id: String, status: String },
/// Sub-agent completed
AgentComplete { id: String, result: String },
/// Sub-agent listing
AgentList { agents: Vec<SubAgentResult> },
/// Structured sub-agent mailbox envelope (issue #128). Carries the
/// monotonic seq + the typed `MailboxMessage` so the UI can route each
/// envelope to the correct in-transcript card.
SubAgentMailbox {
seq: u64,
message: crate::tools::subagent::MailboxMessage,
},
// === System Events ===
/// An error occurred
Error {
envelope: ErrorEnvelope,
#[allow(dead_code)]
recoverable: bool,
},
/// Status message for UI display
Status { message: String },
/// Pause terminal input events (for interactive subprocesses).
PauseEvents {
/// Optional one-shot notification fired after the UI has actually
/// released the terminal to the child process.
ack: Option<Arc<tokio::sync::Notify>>,
},
/// Resume terminal input events after subprocess completion
ResumeEvents,
/// Request user approval for a tool call
ApprovalRequired {
id: String,
tool_name: String,
description: String,
/// Tool parameters for approval display. Carried on the event so the
/// TUI does not need to reconstruct them from `pending_tool_uses`.
input: Value,
/// Exact-argument fingerprint, used to scope *denials* (#1617).
approval_key: String,
/// Lossy / arity-aware fingerprint, used to scope *approvals* so an
/// "approve for session" covers later flag variants (v0.8.37).
approval_grouping_key: String,
/// The model's explanation of intent before invoking write tools (#2381).
/// Displayed in the approval view so users understand *why* the change
/// is being made before reviewing *what* will change.
intent_summary: Option<String>,
},
/// Request user input for a tool call
UserInputRequired {
id: String,
request: UserInputRequest,
},
/// Authoritative API conversation state from the engine session.
///
/// The UI receives granular display events, but those are not always a
/// lossless representation of the API transcript. DeepSeek can emit
/// reasoning directly followed by tool calls without a visible assistant
/// text block, and that assistant message still has to be persisted for
/// later `reasoning_content` replay.
SessionUpdated {
session_id: String,
messages: Vec<Message>,
system_prompt: Option<SystemPrompt>,
model: String,
workspace: PathBuf,
},
/// Request user decision after sandbox denial
#[allow(dead_code)]
ElevationRequired {
tool_id: String,
tool_name: String,
command: Option<String>,
denial_reason: String,
blocked_network: bool,
blocked_write: bool,
},
// === Prefix-Cache Stability Events ===
/// The prefix (system prompt + tool specs) changed between turns,
/// which invalidates DeepSeek's KV prefix cache. Carries diagnostics
/// for the TUI to surface.
PrefixCacheChange {
/// Human-readable description of what changed.
description: String,
/// Whether the system prompt component changed.
system_prompt_changed: bool,
/// Whether the tool set component changed.
tools_changed: bool,
/// Overall prefix stability percentage (100 = fully stable).
stability_pct: u32,
/// True when the prefix actually changed (cache invalidated).
/// False for routine stable-check heartbeats.
changed: bool,
/// Current pinned prefix combined hash (SHA-256, 64 hex chars).
/// Carried so `/cache stats` can surface it without reaching
/// into the engine's PrefixStabilityManager.
pinned_combined_hash: String,
},
}
impl Event {
/// Create an error event from a categorized envelope. The envelope's own
/// `recoverable` flag controls whether the UI flips into offline mode.
pub fn error(envelope: ErrorEnvelope) -> Self {
let recoverable = envelope.recoverable;
Event::Error {
envelope,
recoverable,
}
}
/// Create a new status event
pub fn status(message: impl Into<String>) -> Self {
Event::Status {
message: message.into(),
}
}
}