yolop 0.10.0

Yolop — a terminal coding agent built on everruns-runtime
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//! Translation from everruns runtime events into ACP `session/update`s.
//!
//! The runtime emits a rich event stream (reasoning deltas and summaries,
//! message deltas, tool lifecycle, todo writes). ACP wants a narrower
//! vocabulary: assistant message chunks, thought chunks, tool calls,
//! tool-call updates, and plans.
//! [`Translator`] is the pure, per-turn state machine that performs that
//! mapping. Keeping it free of I/O is what makes the wire behaviour fully
//! unit-testable without a live model.

use std::collections::HashSet;

use everruns_core::events::{Event as RuntimeEvent, EventData, ToolCompletedData};
use everruns_core::message::{ContentPart, MessageRole};
use serde_json::Value;

use super::protocol::{
    self, ContentBlock, Plan, PlanEntry, PlanEntryPriority, PlanEntryStatus, SessionUpdate,
    ToolCall, ToolCallContent, ToolCallStatus, ToolCallUpdate, ToolCallUpdateFields, ToolKind,
};

/// The runtime's todo tool. write_todos updates are surfaced as ACP plans
/// rather than opaque tool calls so editors render them in their plan UI.
const WRITE_TODOS: &str = "write_todos";

/// Per-turn translator. Construct one per `session/prompt` so the
/// per-message streaming flag and event-dedup set reset between turns.
#[derive(Default)]
pub struct Translator {
    /// Whether the in-flight assistant message has streamed any delta. When
    /// a provider streams (Anthropic), we forward deltas and suppress the
    /// terminal full-text chunk to avoid duplication. When it does not
    /// (fixed llmsim, some OpenAI paths), we synthesise one chunk from the
    /// completed message instead.
    current_message_streamed: bool,
    /// Event ids already translated. The runtime can redeliver the same
    /// event across the live broadcast and the catch-up drain; dedup keeps
    /// the client from seeing doubles.
    seen: HashSet<String>,
    /// Tool calls already introduced to the client. Persisted history keeps
    /// completed assistant messages and tool completions, but not the
    /// transient `tool.started` events used by the live bridge.
    started_tool_calls: HashSet<String>,
    /// Replay mode is used only for `session/load`, where ACP requires the
    /// agent to stream the historical user turns back to the client. Live
    /// `session/prompt` handling leaves this off because the client already
    /// has the prompt it just sent.
    replay_history: bool,
}

impl Translator {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn for_replay() -> Self {
        Self {
            replay_history: true,
            ..Self::default()
        }
    }

    /// Translate a single runtime event into zero or more ACP updates.
    /// Returns an empty vec for events with no client-visible mapping.
    pub fn on_event(&mut self, event: &RuntimeEvent) -> Vec<SessionUpdate> {
        if !self.seen.insert(event.id.to_string()) {
            return Vec::new();
        }
        match &event.data {
            EventData::InputMessage(data) => {
                if !self.replay_history {
                    return Vec::new();
                }
                if data.message.role != MessageRole::User {
                    return Vec::new();
                }
                match data.message.text().map(str::trim) {
                    Some(text) if !text.is_empty() => {
                        vec![SessionUpdate::UserMessageChunk(protocol::text_chunk(text))]
                    }
                    _ => Vec::new(),
                }
            }
            EventData::OutputMessageStarted(_) => {
                self.current_message_streamed = false;
                Vec::new()
            }
            EventData::OutputMessageDelta(data) => {
                if data.delta.is_empty() {
                    return Vec::new();
                }
                self.current_message_streamed = true;
                vec![SessionUpdate::AgentMessageChunk(protocol::text_chunk(
                    &data.delta,
                ))]
            }
            EventData::OutputMessageCompleted(data) => {
                if self.current_message_streamed {
                    return Vec::new();
                }
                if data.message.role != MessageRole::Agent {
                    return Vec::new();
                }
                let mut updates = data
                    .message
                    .text()
                    .map(str::trim)
                    .filter(|text| !text.is_empty())
                    .map(|text| vec![SessionUpdate::AgentMessageChunk(protocol::text_chunk(text))])
                    .unwrap_or_default();
                if data.message.has_tool_calls() {
                    if !self.replay_history {
                        return updates;
                    }
                    updates.extend(data.message.content.iter().filter_map(|part| {
                        match part {
                            ContentPart::ToolCall(call) if call.name == WRITE_TODOS => {
                                plan_from_value(&call.arguments)
                                    .map(|entries| SessionUpdate::Plan(Plan::new(entries)))
                            }
                            ContentPart::ToolCall(call)
                                if self.started_tool_calls.insert(call.id.clone()) =>
                            {
                                Some(SessionUpdate::ToolCall(
                                    ToolCall::new(call.id.clone(), call.name.clone())
                                        .kind(tool_kind(&call.name))
                                        .status(ToolCallStatus::InProgress)
                                        .raw_input(non_null(call.arguments.clone())),
                                ))
                            }
                            _ => None,
                        }
                    }));
                }
                updates
            }
            EventData::ReasonThinkingDelta(data) => {
                if data.delta.is_empty() {
                    return Vec::new();
                }
                vec![SessionUpdate::AgentThoughtChunk(protocol::text_chunk(
                    &data.delta,
                ))]
            }
            EventData::ReasonItem(data) => {
                // Provider-curated summaries are displayable reasoning, while
                // opaque continuation content remains private.
                let summary = data
                    .summary
                    .iter()
                    .map(|segment| segment.trim())
                    .filter(|segment| !segment.is_empty())
                    .collect::<Vec<_>>()
                    .join("\n\n");
                if summary.is_empty() {
                    Vec::new()
                } else {
                    vec![SessionUpdate::AgentThoughtChunk(protocol::text_chunk(
                        summary,
                    ))]
                }
            }
            EventData::ToolStarted(data) => {
                let name = data.tool_call.name.as_str();
                if name == WRITE_TODOS {
                    return plan_from_value(&data.tool_call.arguments)
                        .map(|entries| vec![SessionUpdate::Plan(Plan::new(entries))])
                        .unwrap_or_default();
                }
                if !self.started_tool_calls.insert(data.tool_call.id.clone()) {
                    return Vec::new();
                }
                let title = data
                    .narration
                    .as_deref()
                    .or(data.display_name.as_deref())
                    .unwrap_or(name)
                    .to_string();
                vec![SessionUpdate::ToolCall(
                    ToolCall::new(data.tool_call.id.clone(), title)
                        .kind(tool_kind(name))
                        .status(ToolCallStatus::InProgress)
                        .raw_input(non_null(data.tool_call.arguments.clone())),
                )]
            }
            EventData::ToolCompleted(data) => {
                if data.tool_name == WRITE_TODOS {
                    // The result echoes the authoritative todo list with
                    // updated statuses; re-emit the plan so the client's view
                    // reflects completion.
                    return result_value(data)
                        .as_ref()
                        .and_then(plan_from_value)
                        .map(|entries| vec![SessionUpdate::Plan(Plan::new(entries))])
                        .unwrap_or_default();
                }
                let status = if data.success {
                    ToolCallStatus::Completed
                } else {
                    ToolCallStatus::Failed
                };
                let content = tool_result_content(data)
                    .map(|block| vec![ToolCallContent::Content(protocol::Content::new(block))])
                    .unwrap_or_default();
                let title = data
                    .narration
                    .as_deref()
                    .or(data.display_name.as_deref())
                    .unwrap_or(&data.tool_name)
                    .to_string();
                let mut updates = Vec::new();
                if self.replay_history && self.started_tool_calls.insert(data.tool_call_id.clone())
                {
                    updates.push(SessionUpdate::ToolCall(
                        ToolCall::new(data.tool_call_id.clone(), title.clone())
                            .kind(tool_kind(&data.tool_name))
                            .status(ToolCallStatus::InProgress),
                    ));
                }
                let mut fields = ToolCallUpdateFields::new().status(status).content(content);
                if self.replay_history {
                    fields = fields.title(title);
                }
                updates.push(SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                    data.tool_call_id.clone(),
                    fields,
                )));
                updates
            }
            _ => Vec::new(),
        }
    }
}

/// Map built-in and dynamically prefixed MCP tool names to ACP's semantic
/// categories. Unknown tools are executable actions, which is more useful to
/// clients than ACP's omitted `other` default.
fn tool_kind(name: &str) -> ToolKind {
    let name = everruns_core::parse_mcp_tool_name(name)
        .map(|(_, tool)| tool)
        .unwrap_or_else(|| name.to_string());
    let normalized = name.to_ascii_lowercase();
    let tokens = normalized
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|token| !token.is_empty())
        .collect::<Vec<_>>();
    let has = |values: &[&str]| tokens.iter().any(|token| values.contains(token));

    if has(&["delete", "remove", "unlink"]) {
        ToolKind::Delete
    } else if has(&["move", "rename"]) {
        ToolKind::Move
    } else if has(&[
        "search", "find", "grep", "query", "lookup", "map", "symbols",
    ]) {
        ToolKind::Search
    } else if has(&["fetch", "browse", "download", "http", "web"]) {
        ToolKind::Fetch
    } else if has(&["read", "list", "stat", "get", "show", "inspect", "view"]) {
        ToolKind::Read
    } else if has(&[
        "edit", "write", "create", "update", "set", "upsert", "patch", "replace", "insert",
        "enable", "disable",
    ]) {
        ToolKind::Edit
    } else if has(&["think", "plan", "todo"]) {
        ToolKind::Think
    } else if has(&["switch"]) {
        ToolKind::SwitchMode
    } else {
        ToolKind::Execute
    }
}

/// One concise text block summarising a finished tool call, or `None` when
/// there is nothing worth surfacing.
fn tool_result_content(data: &ToolCompletedData) -> Option<ContentBlock> {
    let summary = crate::transcript::summarize_tool_result(data);
    let trimmed = summary.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(protocol::text_block(trimmed))
    }
}

/// Parse the runtime's `{ "todos": [...] }` shape (used by both the
/// write_todos arguments and its result) into ACP plan entries.
fn plan_from_value(value: &Value) -> Option<Vec<PlanEntry>> {
    let todos = value.get("todos")?.as_array()?;
    let entries = todos
        .iter()
        .filter_map(|todo| {
            let content = todo.get("content").and_then(Value::as_str)?;
            if content.trim().is_empty() {
                return None;
            }
            let status = match todo.get("status").and_then(Value::as_str) {
                Some("completed") => PlanEntryStatus::Completed,
                Some("in_progress") => PlanEntryStatus::InProgress,
                _ => PlanEntryStatus::Pending,
            };
            Some(PlanEntry::new(content, PlanEntryPriority::Medium, status))
        })
        .collect::<Vec<_>>();
    Some(entries)
}

/// Decode the JSON payload a tool returned, if any. Mirrors the runtime's
/// convention of stashing structured results as JSON text in the first
/// content part.
fn result_value(data: &ToolCompletedData) -> Option<Value> {
    let parts = data.result.as_ref()?;
    for part in parts {
        if let ContentPart::Text(t) = part
            && let Ok(v) = serde_json::from_str::<Value>(&t.text)
        {
            return Some(v);
        }
    }
    None
}

fn non_null(value: Value) -> Option<Value> {
    if value.is_null() { None } else { Some(value) }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;
    use everruns_core::events::{
        Event, EventContext, OutputMessageCompletedData, OutputMessageDeltaData, ReasonItemData,
        ReasonThinkingDeltaData, ToolCompletedData, ToolStartedData,
    };
    use everruns_core::message::{ExecutionPhase, Message};
    use everruns_core::tool_types::ToolCall;
    use everruns_core::typed_id::{EventId, MessageId, SessionId, TurnId};
    use serde_json::json;

    fn event(data: EventData) -> Event {
        Event {
            id: EventId::new(),
            event_type: data.event_type().to_string(),
            ts: Utc::now(),
            session_id: SessionId::new(),
            context: EventContext::empty(),
            data,
            metadata: None,
            tags: None,
            sequence: None,
        }
    }

    #[test]
    fn streaming_deltas_become_message_chunks() {
        let mut t = Translator::new();
        let updates = t.on_event(&event(EventData::OutputMessageDelta(
            OutputMessageDeltaData {
                turn_id: TurnId::new(),
                message_id: MessageId::new(),
                delta: "Hel".into(),
                accumulated: "Hel".into(),
                phase: None,
            },
        )));
        assert_eq!(
            updates,
            vec![SessionUpdate::AgentMessageChunk(protocol::text_chunk(
                "Hel"
            ))]
        );
    }

    #[test]
    fn completed_message_suppressed_after_streaming() {
        let mut t = Translator::new();
        let _ = t.on_event(&event(EventData::OutputMessageDelta(
            OutputMessageDeltaData {
                turn_id: TurnId::new(),
                message_id: MessageId::new(),
                delta: "Hi".into(),
                accumulated: "Hi".into(),
                phase: None,
            },
        )));
        let completed = t.on_event(&event(EventData::OutputMessageCompleted(
            OutputMessageCompletedData {
                message: Message::assistant("Hi"),
                metadata: None,
                usage: None,
                error_code: None,
                error_fields: None,
                error_disclosure: None,
            },
        )));
        assert!(
            completed.is_empty(),
            "streamed text must not be re-sent: {completed:?}"
        );
    }

    #[test]
    fn completed_message_synthesised_when_not_streamed() {
        let mut t = Translator::new();
        let updates = t.on_event(&event(EventData::OutputMessageCompleted(
            OutputMessageCompletedData {
                message: Message::assistant("full answer"),
                metadata: None,
                usage: None,
                error_code: None,
                error_fields: None,
                error_disclosure: None,
            },
        )));
        assert_eq!(
            updates,
            vec![SessionUpdate::AgentMessageChunk(protocol::text_chunk(
                "full answer"
            ))]
        );
    }

    #[test]
    fn completed_tool_call_message_keeps_public_commentary() {
        let mut t = Translator::new();
        let mut message = Message::assistant_with_tools(
            "I’ll inspect the event bridge next.",
            vec![ToolCall {
                id: "call_1".into(),
                name: "read_file".into(),
                arguments: json!({ "path": "src/acp/bridge.rs" }),
            }],
        );
        message.phase = Some(ExecutionPhase::Commentary);
        let updates = t.on_event(&event(EventData::OutputMessageCompleted(
            OutputMessageCompletedData {
                message,
                metadata: None,
                usage: None,
                error_code: None,
                error_fields: None,
                error_disclosure: None,
            },
        )));

        assert_eq!(
            updates,
            vec![SessionUpdate::AgentMessageChunk(protocol::text_chunk(
                "I’ll inspect the event bridge next."
            ))]
        );
    }

    #[test]
    fn reasoning_summaries_render_as_thought_chunks() {
        let mut t = Translator::new();
        let updates = t.on_event(&event(EventData::ReasonItem(ReasonItemData {
            turn_id: TurnId::new(),
            provider: "openai".into(),
            model: Some("gpt-5".into()),
            item_id: "reason_1".into(),
            encrypted_content: Some("opaque".into()),
            summary: vec![
                "**Investigating event semantics**".into(),
                " **Comparing ACP projections** ".into(),
            ],
            token_count: None,
        })));

        assert_eq!(
            updates,
            vec![SessionUpdate::AgentThoughtChunk(protocol::text_chunk(
                "**Investigating event semantics**\n\n**Comparing ACP projections**"
            ))]
        );
    }

    #[test]
    fn thinking_deltas_become_thought_chunks() {
        let mut t = Translator::new();
        let updates = t.on_event(&event(EventData::ReasonThinkingDelta(
            ReasonThinkingDeltaData {
                turn_id: TurnId::new(),
                delta: "pondering".into(),
                accumulated: "pondering".into(),
            },
        )));
        assert_eq!(
            updates,
            vec![SessionUpdate::AgentThoughtChunk(protocol::text_chunk(
                "pondering"
            ))]
        );
    }

    #[test]
    fn tool_started_uses_in_progress_status_with_semantic_kind() {
        let mut t = Translator::new();
        let updates = t.on_event(&event(EventData::ToolStarted(ToolStartedData {
            tool_call: ToolCall {
                id: "call_1".into(),
                name: "bash".into(),
                arguments: json!({ "command": "ls" }),
            },
            tool_call_fingerprint: None,
            display_name: Some("Bash".into()),
            narration: Some("Listing files".into()),
        })));
        assert_eq!(
            updates,
            vec![SessionUpdate::ToolCall(
                protocol::ToolCall::new("call_1", "Listing files")
                    .kind(ToolKind::Execute)
                    .status(ToolCallStatus::InProgress)
                    .raw_input(json!({ "command": "ls" })),
            )]
        );
        let serialized = serde_json::to_value(&updates[0]).unwrap();
        assert_eq!(serialized["status"], "in_progress");
        assert_eq!(
            match &updates[0] {
                SessionUpdate::ToolCall(call) => call.kind,
                other => panic!("expected tool call, got {other:?}"),
            },
            ToolKind::Execute
        );
        assert_eq!(serialized["kind"], "execute");
    }

    #[test]
    fn tool_kind_classifies_builtin_and_mcp_tools() {
        assert_eq!(tool_kind("read_file"), ToolKind::Read);
        assert_eq!(tool_kind("repo_map"), ToolKind::Search);
        assert_eq!(tool_kind("web_fetch"), ToolKind::Fetch);
        assert_eq!(tool_kind("edit_file"), ToolKind::Edit);
        assert_eq!(tool_kind("bash"), ToolKind::Execute);
        assert_eq!(tool_kind("mcp_paseo__list_files"), ToolKind::Read);
        assert_eq!(tool_kind("mcp_paseo__search_files"), ToolKind::Search);
        assert_eq!(tool_kind("mcp_paseo__build_repo_map"), ToolKind::Search);
        assert_eq!(tool_kind("mcp_paseo__custom_action"), ToolKind::Execute);
    }

    #[test]
    fn mcp_tool_started_emits_semantic_kind_on_the_acp_update() {
        let mut translator = Translator::new();
        let updates = translator.on_event(&event(EventData::ToolStarted(ToolStartedData {
            tool_call: ToolCall {
                id: "call_1".into(),
                name: "mcp_paseo__build_repo_map".into(),
                arguments: json!({ "path": "src" }),
            },
            tool_call_fingerprint: None,
            display_name: Some("Build repo map".into()),
            narration: Some("Build repo map: src".into()),
        })));

        let serialized = serde_json::to_value(&updates[0]).unwrap();
        assert_eq!(serialized["title"], "Build repo map: src");
        assert_eq!(serialized["kind"], "search");
    }

    #[test]
    fn tool_completed_failure_maps_to_failed_status() {
        let mut t = Translator::new();
        let updates = t.on_event(&event(EventData::ToolCompleted(ToolCompletedData {
            tool_call_id: "call_1".into(),
            tool_name: "bash".into(),
            tool_call_fingerprint: None,
            tool_result_fingerprint: None,
            display_name: None,
            success: false,
            status: "error".into(),
            result: None,
            error: Some("boom".into()),
            duration_ms: None,
            capability_id: None,
            capability_name: None,
            narration: None,
        })));
        assert_eq!(updates.len(), 1);
        match &updates[0] {
            SessionUpdate::ToolCallUpdate(update) => {
                assert_eq!(update.tool_call_id.to_string(), "call_1");
                assert_eq!(update.fields.status, Some(ToolCallStatus::Failed));
                assert_eq!(
                    update.fields.content,
                    Some(vec![protocol::content("error: boom")])
                );
            }
            other => panic!("expected tool_call_update, got {other:?}"),
        }
    }

    #[test]
    fn tool_completed_failure_with_result_payload_still_includes_error_content() {
        let mut t = Translator::new();
        let updates = t.on_event(&event(EventData::ToolCompleted(ToolCompletedData {
            tool_call_id: "call_1".into(),
            tool_name: "web_fetch".into(),
            tool_call_fingerprint: None,
            tool_result_fingerprint: None,
            display_name: Some("Web Fetch".into()),
            success: false,
            status: "error".into(),
            result: Some(vec![ContentPart::text(json!({ "ok": false }).to_string())]),
            error: Some("Invalid URL: must start with http:// or https://".into()),
            duration_ms: None,
            capability_id: None,
            capability_name: None,
            narration: None,
        })));
        assert_eq!(updates.len(), 1);
        match &updates[0] {
            SessionUpdate::ToolCallUpdate(update) => {
                assert_eq!(update.fields.status, Some(ToolCallStatus::Failed));
                assert_eq!(
                    update.fields.content,
                    Some(vec![protocol::content(
                        "error: Invalid URL: must start with http:// or https://"
                    )])
                );
            }
            other => panic!("expected tool_call_update, got {other:?}"),
        }
    }

    #[test]
    fn write_todos_started_becomes_plan() {
        let mut t = Translator::new();
        let updates = t.on_event(&event(EventData::ToolStarted(ToolStartedData {
            tool_call: ToolCall {
                id: "call_todos".into(),
                name: "write_todos".into(),
                arguments: json!({
                    "todos": [
                        { "content": "first", "status": "completed" },
                        { "content": "second", "status": "in_progress" },
                        { "content": "third", "status": "pending" },
                    ]
                }),
            },
            tool_call_fingerprint: None,
            display_name: None,
            narration: None,
        })));
        assert_eq!(
            updates,
            vec![SessionUpdate::Plan(Plan::new(vec![
                PlanEntry::new(
                    "first",
                    PlanEntryPriority::Medium,
                    PlanEntryStatus::Completed,
                ),
                PlanEntry::new(
                    "second",
                    PlanEntryPriority::Medium,
                    PlanEntryStatus::InProgress,
                ),
                PlanEntry::new("third", PlanEntryPriority::Medium, PlanEntryStatus::Pending,),
            ]))]
        );
    }

    #[test]
    fn duplicate_event_id_is_ignored() {
        let mut t = Translator::new();
        let ev = event(EventData::OutputMessageDelta(OutputMessageDeltaData {
            turn_id: TurnId::new(),
            message_id: MessageId::new(),
            delta: "x".into(),
            accumulated: "x".into(),
            phase: None,
        }));
        assert_eq!(t.on_event(&ev).len(), 1);
        assert_eq!(t.on_event(&ev).len(), 0, "second delivery must be ignored");
    }

    #[test]
    fn replay_mode_emits_user_messages() {
        let mut t = Translator::for_replay();
        let updates = t.on_event(&event(EventData::InputMessage(
            everruns_core::events::InputMessageData::new(Message::user("prior prompt")),
        )));
        assert_eq!(
            updates,
            vec![SessionUpdate::UserMessageChunk(protocol::text_chunk(
                "prior prompt"
            ))]
        );
    }

    #[test]
    fn replay_mode_reconstructs_tool_calls_from_completed_agent_messages() {
        let mut t = Translator::for_replay();
        let message = Message::assistant_with_tools(
            "",
            vec![ToolCall {
                id: "call_1".into(),
                name: "bash".into(),
                arguments: json!({ "command": "ls" }),
            }],
        );

        let updates = t.on_event(&event(EventData::OutputMessageCompleted(
            OutputMessageCompletedData {
                message,
                metadata: None,
                usage: None,
                error_code: None,
                error_fields: None,
                error_disclosure: None,
            },
        )));

        assert_eq!(
            updates,
            vec![SessionUpdate::ToolCall(
                protocol::ToolCall::new("call_1", "bash")
                    .kind(ToolKind::Execute)
                    .status(ToolCallStatus::InProgress)
                    .raw_input(json!({ "command": "ls" })),
            )]
        );
    }

    #[test]
    fn replay_mode_does_not_duplicate_a_reconstructed_tool_start() {
        let mut t = Translator::for_replay();
        let call = ToolCall {
            id: "call_1".into(),
            name: "bash".into(),
            arguments: json!({ "command": "ls" }),
        };
        let completed = event(EventData::OutputMessageCompleted(
            OutputMessageCompletedData {
                message: Message::assistant_with_tools("", vec![call.clone()]),
                metadata: None,
                usage: None,
                error_code: None,
                error_fields: None,
                error_disclosure: None,
            },
        ));
        let started = event(EventData::ToolStarted(ToolStartedData {
            tool_call: call,
            tool_call_fingerprint: None,
            display_name: Some("Bash".into()),
            narration: Some("Listing files".into()),
        }));

        assert_eq!(t.on_event(&completed).len(), 1);
        assert!(t.on_event(&started).is_empty());
    }

    #[test]
    fn replay_mode_never_emits_an_orphaned_tool_completion() {
        let mut t = Translator::for_replay();
        let updates = t.on_event(&event(EventData::ToolCompleted(ToolCompletedData {
            tool_call_id: "call_1".into(),
            tool_name: "bash".into(),
            tool_call_fingerprint: None,
            tool_result_fingerprint: None,
            display_name: Some("Bash".into()),
            success: true,
            status: "success".into(),
            result: None,
            error: None,
            duration_ms: None,
            capability_id: None,
            capability_name: None,
            narration: Some("Listed files".into()),
        })));

        assert_eq!(updates.len(), 2);
        match (&updates[0], &updates[1]) {
            (SessionUpdate::ToolCall(call), SessionUpdate::ToolCallUpdate(update)) => {
                assert_eq!(call.tool_call_id.to_string(), "call_1");
                assert_eq!(call.title, "Listed files");
                assert_eq!(update.tool_call_id.to_string(), "call_1");
                assert_eq!(update.fields.title.as_deref(), Some("Listed files"));
                assert_eq!(update.fields.status, Some(ToolCallStatus::Completed));
            }
            other => panic!("expected tool call followed by completion, got {other:?}"),
        }
    }

    #[test]
    fn live_mode_suppresses_user_messages() {
        let mut t = Translator::new();
        let updates = t.on_event(&event(EventData::InputMessage(
            everruns_core::events::InputMessageData::new(Message::user("current prompt")),
        )));
        assert!(updates.is_empty());
    }
}