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
use serde::{Deserialize, Serialize};
// ─── Core identifiers ───────────────────────────────────────────────────────────
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RunId(pub String);
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CheckpointId(pub String);
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AgentId(pub String);
impl RunId {
pub fn new() -> Self {
Self(uuid::Uuid::new_v4().to_string())
}
}
impl CheckpointId {
pub fn new() -> Self {
Self(uuid::Uuid::new_v4().to_string())
}
}
impl AgentId {
pub fn new() -> Self {
Self(uuid::Uuid::new_v4().to_string())
}
}
pub fn friendly_model_switch_reason(reason: &str) -> String {
let lower = reason.to_lowercase();
if lower.contains("ollama api error 404") && lower.contains("model") {
"modèle local indisponible".into()
} else if lower.contains("ollama") {
"provider local indisponible".into()
} else {
reason.to_string()
}
}
pub fn is_local_model_unavailable(reason: &str) -> bool {
matches!(
friendly_model_switch_reason(reason).as_str(),
"modèle local indisponible" | "provider local indisponible"
)
}
/// Streaming filter that strips `<think>…</think>` reasoning blocks emitted by
/// reasoning models (minimax, deepseek-r1, qwq…) so surfaces show the answer,
/// not the chain-of-thought. Handles tags split across streamed deltas.
#[derive(Default)]
pub struct ThinkStripper {
in_think: bool,
pending: String,
/// Content seen inside the current (unclosed) think block, kept so that if
/// the block NEVER closes (model didn't emit </think>) we can recover it on
/// flush rather than silently swallowing the whole answer (fail-open).
think_buf: String,
}
impl ThinkStripper {
pub fn new() -> Self {
Self::default()
}
/// Feed a streamed delta; returns the portion that should be displayed.
pub fn feed(&mut self, delta: &str) -> String {
const OPEN: &str = "<think>";
const CLOSE: &str = "</think>";
self.pending.push_str(delta);
let mut out = String::new();
loop {
if !self.in_think {
if let Some(i) = self.pending.find(OPEN) {
out.push_str(&self.pending[..i]);
self.pending.replace_range(..i + OPEN.len(), "");
self.in_think = true;
self.think_buf.clear();
continue;
}
let keep = dangling_prefix(&self.pending, OPEN);
let emit_to = self.pending.len() - keep;
out.push_str(&self.pending[..emit_to]);
self.pending.replace_range(..emit_to, "");
break;
} else {
if let Some(i) = self.pending.find(CLOSE) {
// Real closed think block → discard its content.
self.pending.replace_range(..i + CLOSE.len(), "");
self.in_think = false;
self.think_buf.clear();
continue;
}
let keep = dangling_prefix(&self.pending, CLOSE);
let drop_to = self.pending.len() - keep;
// Stash dropped think content for fail-open recovery.
self.think_buf.push_str(&self.pending[..drop_to]);
self.pending.replace_range(..drop_to, "");
break;
}
}
out
}
/// Flush remaining buffered text. If a think block was opened but never
/// closed, recover its content (the model likely put the answer there).
pub fn flush(&mut self) -> String {
let mut rest = std::mem::take(&mut self.pending);
if self.in_think {
// Unclosed think → show what we stashed (fail-open).
let recovered = std::mem::take(&mut self.think_buf);
self.in_think = false;
format!("{}{}", recovered, rest)
} else {
self.think_buf.clear();
std::mem::take(&mut rest)
}
}
}
/// Length (bytes) of the trailing portion of `s` that is a prefix of `tag`,
/// so a tag split across deltas isn't emitted prematurely. ASCII tags only.
fn dangling_prefix(s: &str, tag: &str) -> usize {
let max = tag.len().saturating_sub(1).min(s.len());
for n in (1..=max).rev() {
if s.is_char_boundary(s.len() - n) && s[s.len() - n..] == tag[..n] {
return n;
}
}
0
}
// ─── Content blocks ─────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Block {
Text(String),
Json(serde_json::Value),
Image { data: Vec<u8>, mime: String },
Diff { file: String, patch: String },
}
// ─── Tool use types ─────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum RiskLevel {
ReadOnly,
Mutating,
Exec,
Destructive,
Network,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum Decision {
Allow,
AskUser,
Deny,
}
// ─── Agent status ───────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AgentStatus {
Idle,
Thinking,
Working,
WaitingForApproval,
Done,
Error,
}
// ─── Model-related types ────────────────────────────────────────────────────────
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenUsage {
pub input: u64,
pub output: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum StopReason {
EndTurn,
MaxTokens,
StopSequence(String),
ToolUse,
Refusal,
Error,
}
// ─── Autonomy ───────────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AutonomyLevel {
Supervised,
Trusted,
Autonomous,
}
impl AutonomyLevel {
pub fn as_float(&self) -> f64 {
match self {
AutonomyLevel::Supervised => 0.0,
AutonomyLevel::Trusted => 0.5,
AutonomyLevel::Autonomous => 1.0,
}
}
pub fn from_float(f: f64) -> Self {
if f >= 0.75 {
AutonomyLevel::Autonomous
} else if f >= 0.25 {
AutonomyLevel::Trusted
} else {
AutonomyLevel::Supervised
}
}
}
// ─── Outcome ────────────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutcomeSummary {
pub status: String,
pub diffs: Vec<FileDiff>,
pub cost_usd: f64,
pub tokens: TokenUsage,
/// Pre-formatted cost comparison against competitors (empty = no comparison).
/// Populated by the orchestrator at run completion so every surface can display it.
#[serde(default)]
pub cost_comparison: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileDiff {
pub file: String,
pub plus: u32,
pub minus: u32,
}
// ─── THE EVENT MODEL (§3.14) — load-bearing contract ────────────────────────────
/// Every surface renders from this stream; replay records from it.
/// This enum is the contract that connects runtime ↔ surfaces ↔ replay.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Event {
RunStarted {
run: RunId,
task: String,
agent: String,
},
RouteSelected {
run: RunId,
chain: Vec<String>,
context_window: u64,
},
ModelSwitched {
run: RunId,
from: String,
to: String,
reason: String,
},
ThinkingDelta {
run: RunId,
text: String,
},
/// Opaque provider reasoning state. Surfaces should not render this as
/// assistant-visible text, but session persistence must keep it so
/// reasoning-mode providers can receive `reasoning_content` on the next
/// turn when they require it.
ReasoningDelta {
run: RunId,
text: String,
},
Message {
run: RunId,
role: String,
text: String,
},
ToolUseProposed {
run: RunId,
id: String,
name: String,
args: serde_json::Value,
risk: RiskLevel,
},
ApprovalRequested {
run: RunId,
id: String,
summary: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
tool: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
risk: Option<String>,
},
ApprovalResolved {
run: RunId,
id: String,
decision: Decision,
},
ToolUseStarted {
run: RunId,
id: String,
},
ToolOutput {
run: RunId,
id: String,
blocks: Vec<Block>,
},
DiffProposed {
run: RunId,
file: String,
patch: String,
plus: u32,
minus: u32,
},
DiffApplied {
run: RunId,
file: String,
},
TestResult {
run: RunId,
passed: u32,
failed: u32,
detail: String,
},
AgentSpawned {
run: RunId,
role: String,
model: String,
},
AgentStatus {
run: RunId,
role: String,
status: AgentStatus,
note: String,
},
CheckpointCreated {
run: RunId,
id: CheckpointId,
label: String,
},
SkillLearned {
run: RunId,
name: String,
},
CostUpdate {
run: RunId,
usd: f64,
},
TokenUsage {
run: RunId,
input: u64,
output: u64,
},
TokenUsageEstimated {
run: RunId,
input: u64,
output: u64,
reason: String,
},
AutonomyChanged {
run: RunId,
level: AutonomyLevel,
},
RunFinished {
run: RunId,
outcome: OutcomeSummary,
},
Error {
run: RunId,
message: String,
},
/// A compaction pass has just completed. Surfaces the before/after sizes
/// (in chars) and the path of the handoff doc, if any.
Compacted {
run: RunId,
before_chars: usize,
after_chars: usize,
handoff_path: Option<String>,
},
}
impl Event {
/// Returns true for events that may be streamed to user-facing feeds.
///
/// `ReasoningDelta` is provider-internal continuity state: the engine and
/// session stores consume it so reasoning-mode providers can receive the
/// required `reasoning_content` on the next turn, but exposing every delta
/// as NDJSON/WebSocket output floods users with opaque token fragments.
pub fn is_public(&self) -> bool {
!matches!(self, Self::ReasoningDelta { .. })
}
}