everruns-core 0.42.0

Transport-neutral agent execution contracts for Everruns
Documentation
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
//! Projection of Everruns runtime events onto an AG-UI 1.0 run.
//!
//! A [`Projector`] follows one run: feed it the session's runtime events (in
//! order, already filtered to the run) and drain the AG-UI events it queues.
//! It owns the 1.0 sequencing rules, so callers only decide what to expose
//! through [`ProjectionPolicy`].
//!
//! ```
//! use everruns_core::ag_ui::projection::{ProjectionPolicy, Projector};
//! use everruns_core::ag_ui::Event;
//!
//! let mut projector = Projector::new("thread-1", "run-1", ProjectionPolicy::default());
//! projector.project("turn.cancelled", &serde_json::json!({}));
//! let events: Vec<Event> = projector.drain().collect();
//! assert!(matches!(events.last(), Some(Event::RunFinished(_))));
//! assert!(projector.is_finished());
//! ```

// Message ids are the runtime message's bare UUID, the same id the server's
// `MESSAGES_SNAPSHOT` uses, so a replayed transcript and a live one agree.
//
// Decision: the projector takes `(event_type, data)` as JSON, the canonical
// envelope every Everruns surface already has (the server's durable events,
// the framework's `SessionEvent::canonical_json`), and parses the payloads
// with `everruns-core`'s own data types. One state machine then serves the
// server endpoint, `serve`, and the framework.

use std::collections::{BTreeMap, HashSet, VecDeque};
use std::sync::Arc;

use crate::events::{
    OutputMessageCompletedData, OutputMessageDeltaData, ReasonItemData, SessionTaskEventData,
    TaskMessageEventData, TurnFailedData,
};
use crate::session_task::{
    SessionTask, SessionTaskState, TASK_KIND_SUBAGENT, TaskMessageDirection, TaskMessagePart,
};
use crate::{ContentPart, RuntimeMessage};
use everruns_contracts::execution_phase::ExecutionPhase;
use serde::de::DeserializeOwned;
use serde_json::Value;

use crate::ag_ui::{
    ActivitySnapshotEvent, BaseEvent, Event, Interrupt, Metadata, ReasoningMessageContentEvent,
    ReasoningMessageEndEvent, ReasoningMessageStartEvent, ReasoningSpanEvent, RunErrorEvent,
    RunFinishedEvent, RunFinishedOutcome, StateDeltaEvent, StateSnapshotEvent, SubagentErrorEvent,
    SubagentFinishedEvent, SubagentFinishedOutcome, SubagentStartedEvent, TextMessageContentEvent,
    TextMessageEndEvent, TextMessageStartEvent, TokenUsage, ToolCall, ToolCallArgsEvent,
    ToolCallEndEvent, ToolCallStartEvent, diff,
};

/// The metadata key Everruns-specific run details ride under. `ag-ui` is
/// reserved for the protocol.
pub const METADATA_KEY: &str = "everruns";

/// `activityType` of the activity a subagent reports: structured progress, and
/// the note that it carries on in the background after the run ends.
pub const SUBAGENT_ACTIVITY_TYPE: &str = "everruns.subagent";

/// The tool whose result is the agent's todo list: `write_todos` from the
/// `stateless_todo_list` capability (`crate::builtins`, a feature this module
/// does not depend on). Every call carries the complete list.
pub const TODO_TOOL_NAME: &str = "write_todos";

/// The shared-state key the todo list rides under: the run's state is
/// `{ "todos": [{ "content", "activeForm", "status" }] }`.
pub const TODOS_STATE_KEY: &str = "todos";

/// A failed turn, as handed to [`ProjectionPolicy::error`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TurnFailure {
    /// The runtime's error message. May carry provider detail.
    pub message: String,
    /// The runtime's stable error code, when it has one.
    pub code: Option<String>,
}

/// Builds the `RUN_ERROR` a failure becomes.
pub type ErrorProjection = Arc<dyn Fn(&TurnFailure) -> RunErrorEvent + Send + Sync>;

/// What a projection exposes.
#[derive(Clone)]
pub struct ProjectionPolicy {
    /// Stream model reasoning (`reason.thinking.*`) and provider reasoning
    /// summaries (`reason.item`) on the reasoning channel.
    pub reasoning_visible: bool,
    /// Text shown on the reasoning channel while server-side tools run, or
    /// `None` to show nothing. Never derived from tool names or arguments.
    pub tool_activity_text: Option<String>,
    /// Report the run's token usage on its terminal event, summed per
    /// provider and model from `llm.generation`.
    pub usage_visible: bool,
    /// Project the run's subagent tasks (`task.*` of kind `subagent`) as
    /// `SUBAGENT_*`, with their output attributed by `subagentRunId`.
    pub subagents_visible: bool,
    /// Name the model in the run's `everruns` metadata. It is the model
    /// `usage` would name, so public channels tie it to `usage_visible`.
    pub model_visible: bool,
    /// Stream the agent's todo list as shared state: `STATE_SNAPSHOT` the
    /// first time it is known in a run, `STATE_DELTA` for later changes.
    pub state_visible: bool,
    /// The session id to name in the run's `everruns` metadata, or `None` to
    /// leave it out. Anonymous channels leave it out.
    pub session_id: Option<String>,
    /// Maps a failed turn to its `RUN_ERROR`. Public channels sanitize here.
    pub error: ErrorProjection,
}

impl Default for ProjectionPolicy {
    /// Trusted defaults: reasoning, usage, subagents, the model and state
    /// visible, no tool activity text, no session id, and the runtime's error
    /// message and code passed through.
    fn default() -> Self {
        Self {
            reasoning_visible: true,
            tool_activity_text: None,
            usage_visible: true,
            subagents_visible: true,
            model_visible: true,
            state_visible: true,
            session_id: None,
            error: Arc::new(|failure: &TurnFailure| RunErrorEvent {
                code: failure.code.clone(),
                ..RunErrorEvent::new(failure.message.clone())
            }),
        }
    }
}

impl std::fmt::Debug for ProjectionPolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProjectionPolicy")
            .field("reasoning_visible", &self.reasoning_visible)
            .field("tool_activity_text", &self.tool_activity_text)
            .field("usage_visible", &self.usage_visible)
            .field("subagents_visible", &self.subagents_visible)
            .field("model_visible", &self.model_visible)
            .field("state_visible", &self.state_visible)
            .field("session_id", &self.session_id)
            .finish_non_exhaustive()
    }
}

/// Follows one AG-UI run.
#[derive(Debug)]
pub struct Projector {
    policy: ProjectionPolicy,
    thread_id: String,
    run_id: String,
    queue: VecDeque<Event>,
    /// The open assistant text message, if any.
    assistant_message_id: Option<String>,
    assistant_content_started: bool,
    assistant_emitted_delta: bool,
    /// The last assistant message that carried tool calls rather than an
    /// answer: the parent of any frontend tool call the run stops on.
    tool_call_message_id: Option<String>,
    /// The open reasoning span and reasoning message, if any.
    reasoning_span: Option<String>,
    reasoning_message: Option<String>,
    /// The span was opened by tool activity rather than model reasoning.
    span_opened_by_tools: bool,
    /// Model reasoning (`reason.thinking.*`) is streaming.
    thinking: bool,
    active_tools: usize,
    tool_activity_shown: bool,
    next_reasoning_id: usize,
    /// Usage per (provider, model), ordered by that key so output is stable.
    usage: BTreeMap<(Option<String>, Option<String>), TokenUsage>,
    /// The turn the run follows and the model it last called, for metadata.
    turn_id: Option<String>,
    model: Option<String>,
    /// Subagent invocations started and not yet closed, in start order, with
    /// whether each runs in the background.
    open_subagents: Vec<(String, bool)>,
    /// Every invocation this run announced, so a closed one is never reopened.
    seen_subagents: HashSet<String>,
    /// The shared state this run last sent, `None` until its first
    /// `STATE_SNAPSHOT`; later changes are `STATE_DELTA`s against it.
    state: Option<Value>,
    finished: bool,
}

impl Projector {
    pub fn new(
        thread_id: impl Into<String>,
        run_id: impl Into<String>,
        policy: ProjectionPolicy,
    ) -> Self {
        Self {
            policy,
            thread_id: thread_id.into(),
            run_id: run_id.into(),
            queue: VecDeque::new(),
            assistant_message_id: None,
            assistant_content_started: false,
            assistant_emitted_delta: false,
            tool_call_message_id: None,
            reasoning_span: None,
            reasoning_message: None,
            span_opened_by_tools: false,
            thinking: false,
            active_tools: 0,
            tool_activity_shown: false,
            next_reasoning_id: 0,
            usage: BTreeMap::new(),
            turn_id: None,
            model: None,
            open_subagents: Vec::new(),
            seen_subagents: HashSet::new(),
            state: None,
            finished: false,
        }
    }

    /// Records the turn the run's events belong to, named in the run's
    /// metadata. Callers pass it from the event envelope's context, which the
    /// `(event_type, data)` input does not carry.
    pub fn observe_turn(&mut self, turn_id: impl Into<String>) {
        self.turn_id = Some(turn_id.into());
    }

    /// The run's metadata as known so far: an `everruns` object with
    /// `sessionId` (when the policy names one), `turnId` (once observed) and
    /// `model` (once called, when the policy shows it). `None` when empty.
    /// The terminal event carries it; a caller can put it on `RUN_STARTED`.
    ///
    /// ```
    /// use everruns_core::ag_ui::projection::{ProjectionPolicy, Projector};
    /// use everruns_core::ag_ui::Event;
    ///
    /// let policy = ProjectionPolicy {
    ///     session_id: Some("session-1".into()),
    ///     ..ProjectionPolicy::default()
    /// };
    /// let mut projector = Projector::new("thread", "run", policy);
    /// projector.observe_turn("turn-1");
    /// projector.project("turn.completed", &serde_json::json!({}));
    /// let Some(Event::RunFinished(finished)) = projector.drain().last() else { panic!() };
    /// assert_eq!(
    ///     serde_json::to_value(&finished.base.metadata).unwrap(),
    ///     serde_json::json!({ "everruns": { "sessionId": "session-1", "turnId": "turn-1" } }),
    /// );
    /// ```
    pub fn run_metadata(&self) -> Option<Metadata> {
        let mut everruns = serde_json::Map::new();
        let mut put = |key: &str, value: Option<&String>| {
            if let Some(value) = value {
                everruns.insert(key.to_string(), Value::String(value.clone()));
            }
        };
        put("sessionId", self.policy.session_id.as_ref());
        put("turnId", self.turn_id.as_ref());
        put(
            "model",
            self.model.as_ref().filter(|_| self.policy.model_visible),
        );
        (!everruns.is_empty())
            .then(|| Metadata::from_iter([(METADATA_KEY.to_string(), Value::Object(everruns))]))
    }

    /// Starts the run from the todo list the session already has, as
    /// [`latest_todos`] reads it from history, so a client that reconnects
    /// (or never saw an earlier run) holds the same state as one that
    /// followed along. Queues a `STATE_SNAPSHOT` when the list is non-empty
    /// and the policy shows state; call it before projecting the run's
    /// events. An empty list sends nothing: a fresh client already has none.
    ///
    /// ```
    /// use everruns_core::ag_ui::projection::{ProjectionPolicy, Projector};
    /// use everruns_core::ag_ui::Event;
    ///
    /// let mut projector = Projector::new("thread", "run", ProjectionPolicy::default());
    /// projector.restore_todos(serde_json::json!([
    ///     { "content": "Run tests", "activeForm": "Running tests", "status": "pending" },
    /// ]));
    /// let Some(Event::StateSnapshot(snapshot)) = projector.pop() else { panic!() };
    /// assert_eq!(snapshot.snapshot["todos"][0]["status"], "pending");
    /// ```
    pub fn restore_todos(&mut self, todos: Value) {
        let todos = sanitize_todos(&todos);
        if todos.as_array().is_some_and(|items| !items.is_empty()) {
            self.set_todos(todos);
        }
    }

    /// Whether the run has ended (`RUN_FINISHED` or `RUN_ERROR` queued).
    /// Later input is ignored.
    pub fn is_finished(&self) -> bool {
        self.finished
    }

    /// Takes the queued events.
    pub fn drain(&mut self) -> impl Iterator<Item = Event> + '_ {
        self.queue.drain(..)
    }

    /// Takes the next queued event.
    pub fn pop(&mut self) -> Option<Event> {
        self.queue.pop_front()
    }

    /// Ends the run with an error that did not come from the runtime, such as
    /// the event stream closing early. Open messages are closed first.
    pub fn fail(&mut self, error: RunErrorEvent) {
        if self.finished {
            return;
        }
        self.close_all();
        self.close_subagents();
        let mut error = error;
        if error.usage.is_none() {
            error.usage = self.usage_entries();
        }
        if error.base.metadata.is_none() {
            error.base.metadata = self.run_metadata();
        }
        self.queue.push_back(Event::RunError(error));
        self.finished = true;
    }

    /// Ends the run with the interrupt outcome: it stopped to ask for
    /// something, such as an answer or an approval, and the run that resumes
    /// it carries the answers. An empty list does nothing, because an
    /// interrupt outcome with nothing to answer is invalid.
    pub fn interrupt(&mut self, interrupts: Vec<Interrupt>) {
        self.park(Vec::new(), interrupts);
    }

    /// Ends the run where the turn parked on its consumer.
    ///
    /// Frontend tool calls stream as `TOOL_CALL_START`/`ARGS`/`END` under the
    /// assistant message that made them. With interrupts the run ends with
    /// the interrupt outcome; with only tool calls it is a success naming
    /// them in `pendingToolCallIds`, and the consumer's next run carries
    /// their results as `tool` messages. Both empty does nothing.
    ///
    /// ```
    /// use everruns_core::ag_ui::projection::{ProjectionPolicy, Projector};
    /// use everruns_core::ag_ui::{Event, RunFinishedOutcome, ToolCall};
    ///
    /// let mut projector = Projector::new("thread", "run", ProjectionPolicy::default());
    /// projector.park(vec![ToolCall::function("call-1", "confirm", "{}")], Vec::new());
    /// let events: Vec<Event> = projector.drain().collect();
    /// assert!(matches!(events[0], Event::ToolCallStart(_)));
    /// let Some(Event::RunFinished(finished)) = events.last() else { panic!() };
    /// assert_eq!(
    ///     finished.outcome,
    ///     Some(RunFinishedOutcome::Success {
    ///         pending_tool_call_ids: Some(vec!["call-1".to_string()]),
    ///     })
    /// );
    /// ```
    pub fn park(&mut self, tool_calls: Vec<ToolCall>, interrupts: Vec<Interrupt>) {
        if self.finished || (tool_calls.is_empty() && interrupts.is_empty()) {
            return;
        }
        self.close_all();
        let parent = self.tool_call_message_id.clone();
        let mut pending = Vec::with_capacity(tool_calls.len());
        for call in tool_calls {
            let mut start = ToolCallStartEvent::new(call.id.clone(), call.function.name);
            start.parent_message_id = parent.clone();
            self.queue.push_back(Event::ToolCallStart(start));
            if !call.function.arguments.is_empty() {
                self.queue
                    .push_back(Event::ToolCallArgs(ToolCallArgsEvent::new(
                        call.id.clone(),
                        call.function.arguments,
                    )));
            }
            self.queue
                .push_back(Event::ToolCallEnd(ToolCallEndEvent::new(call.id.clone())));
            pending.push(call.id);
        }
        self.finish(Some(if interrupts.is_empty() {
            RunFinishedOutcome::Success {
                pending_tool_call_ids: Some(pending),
            }
        } else {
            RunFinishedOutcome::Interrupt { interrupts }
        }));
    }

    /// Projects one runtime event, given its dotted type and JSON `data`.
    pub fn project(&mut self, event_type: &str, data: &Value) {
        if self.finished {
            return;
        }
        match event_type {
            "output.message.delta" => {
                if let Some(data) = parse::<OutputMessageDeltaData>(data) {
                    let message_id =
                        self.ensure_assistant_message(data.message_id.uuid().to_string());
                    self.open_assistant_text(&message_id);
                    self.queue
                        .push_back(Event::TextMessageContent(TextMessageContentEvent::new(
                            message_id, data.delta,
                        )));
                    self.assistant_emitted_delta = true;
                }
            }
            "output.message.completed" => {
                if let Some(data) = parse::<OutputMessageCompletedData>(data) {
                    self.output_completed(&data.message);
                }
            }
            "reason.thinking.started" if self.policy.reasoning_visible => {
                if self.reasoning_span.is_none() {
                    self.open_span(false);
                }
                // Model reasoning takes over a span tool activity opened.
                self.span_opened_by_tools = false;
                self.close_reasoning_message();
                self.thinking = true;
            }
            "reason.thinking.delta" if self.policy.reasoning_visible => {
                if !self.thinking {
                    self.project("reason.thinking.started", &Value::Null);
                }
                if let Some(delta) = data.get("delta").and_then(Value::as_str) {
                    let message_id = self.ensure_reasoning_message();
                    self.queue.push_back(Event::ReasoningMessageContent(
                        ReasoningMessageContentEvent::new(message_id, delta),
                    ));
                }
            }
            "reason.thinking.completed" if self.policy.reasoning_visible => {
                self.close_reasoning_message();
                self.close_span();
                self.thinking = false;
                self.span_opened_by_tools = false;
            }
            // A provider `reason.item` summary is a reasoning artifact: it
            // renders on the reasoning channel, never as assistant text, and
            // its opaque encrypted content is never emitted.
            "reason.item" if self.policy.reasoning_visible => {
                if let Some(data) = parse::<ReasonItemData>(data) {
                    self.reasoning_summary(&data.summary);
                }
            }
            "tool.started" => {
                self.active_tools += 1;
                if let Some(text) = self.policy.tool_activity_text.clone() {
                    self.tool_activity(&text);
                }
            }
            "tool.completed" => {
                if data.get("tool_name").and_then(Value::as_str) == Some(TODO_TOOL_NAME)
                    && data.get("success").and_then(Value::as_bool) == Some(true)
                    && let Some(todos) = data.get("result").and_then(todos_from_result)
                {
                    self.set_todos(todos);
                }
                self.active_tools = self.active_tools.saturating_sub(1);
                if self.active_tools == 0 && self.tool_activity_shown {
                    if self.span_opened_by_tools {
                        self.close_reasoning_message();
                        self.close_span();
                    }
                    self.tool_activity_shown = false;
                    self.span_opened_by_tools = false;
                }
            }
            "llm.generation" => self.record_usage(data),
            "task.created" | "task.updated" if self.policy.subagents_visible => {
                if let Some(data) = parse::<SessionTaskEventData>(data) {
                    self.subagent_task(&data.task);
                }
            }
            "task.message.received" if self.policy.subagents_visible => {
                if let Some(data) = parse::<TaskMessageEventData>(data) {
                    self.subagent_message(&data);
                }
            }
            "turn.completed" | "session.idled" => self.finish(None),
            // Cancellation is a deliberate terminal state, typically client
            // initiated, not a fault: 1.0 names it with the cancelled outcome.
            "turn.cancelled" => self.finish(Some(RunFinishedOutcome::Cancelled)),
            "turn.failed" => {
                let failure = parse::<TurnFailedData>(data)
                    .map(|data| TurnFailure {
                        message: data.error,
                        code: data.error_code,
                    })
                    .unwrap_or_default();
                let error = (self.policy.error)(&failure);
                self.fail(error);
            }
            _ => {}
        }
    }

    /// The todo list changed: the run's first state is a snapshot, a later
    /// one the patch from what was last sent, and no change sends nothing.
    /// State is the parent session's: subagent tool calls stay in the child
    /// session (see `subagent_task`), so it is never attributed.
    fn set_todos(&mut self, todos: Value) {
        if !self.policy.state_visible || self.finished {
            return;
        }
        let state = Value::Object(serde_json::Map::from_iter([(
            TODOS_STATE_KEY.to_string(),
            todos,
        )]));
        match &self.state {
            None => self
                .queue
                .push_back(Event::StateSnapshot(StateSnapshotEvent {
                    snapshot: state.clone(),
                    ..StateSnapshotEvent::default()
                })),
            Some(previous) => {
                let delta = diff(previous, &state);
                if delta.is_empty() {
                    return;
                }
                self.queue.push_back(Event::StateDelta(StateDeltaEvent {
                    delta,
                    ..StateDeltaEvent::default()
                }));
            }
        }
        self.state = Some(state);
    }

    fn finish(&mut self, outcome: Option<RunFinishedOutcome>) {
        self.close_all();
        self.close_subagents();
        self.queue.push_back(Event::RunFinished(RunFinishedEvent {
            base: BaseEvent {
                metadata: self.run_metadata(),
                ..BaseEvent::default()
            },
            outcome,
            usage: self.usage_entries(),
            ..RunFinishedEvent::new(self.thread_id.clone(), self.run_id.clone())
        }));
        self.finished = true;
    }

    /// Adds one generation's usage to its provider and model's entry.
    ///
    /// Everruns counts prompt buckets disjointly (non-cached input, cache
    /// reads, cache writes); AG-UI's `inputTokens` is their sum, with the
    /// cache counts as parts of it.
    fn record_usage(&mut self, data: &Value) {
        let metadata = &data["metadata"];
        if let Some(model) = ["response_model", "model"]
            .iter()
            .find_map(|key| metadata.get(*key).and_then(Value::as_str))
        {
            self.model = Some(model.to_string());
        }
        let Some(usage) = metadata.get("usage").filter(|usage| usage.is_object()) else {
            return;
        };
        let count = |key: &str| usage.get(key).and_then(Value::as_u64);
        let text = |key: &str| {
            metadata
                .get(key)
                .and_then(Value::as_str)
                .map(str::to_string)
        };
        let model = text("response_model").or_else(|| text("model"));
        let entry = self
            .usage
            .entry((text("provider"), model.clone()))
            .or_insert_with(|| TokenUsage {
                provider: text("provider"),
                model,
                ..TokenUsage::default()
            });
        let cache_read = count("cache_read_tokens");
        let cache_write = count("cache_creation_tokens");
        let input = count("input_tokens")
            .map(|input| input + cache_read.unwrap_or_default() + cache_write.unwrap_or_default());
        let add = |total: &mut Option<u64>, value: Option<u64>| {
            if let Some(value) = value {
                *total = Some(total.unwrap_or_default().saturating_add(value));
            }
        };
        add(&mut entry.input_tokens, input);
        add(&mut entry.output_tokens, count("output_tokens"));
        add(&mut entry.cached_input_tokens, cache_read);
        add(&mut entry.cache_write_input_tokens, cache_write);
        entry.total_tokens = match (entry.input_tokens, entry.output_tokens) {
            (Some(input), Some(output)) => Some(input.saturating_add(output)),
            _ => None,
        };
    }

    fn usage_entries(&self) -> Option<Vec<TokenUsage>> {
        (self.policy.usage_visible && !self.usage.is_empty())
            .then(|| self.usage.values().cloned().collect())
    }

    fn output_completed(&mut self, message: &RuntimeMessage) {
        if !is_terminal_public_output(message, self.assistant_emitted_delta) {
            // Commentary before tools: close its text message so the final
            // answer can open its own without ending the run early.
            self.close_assistant_text();
            self.tool_call_message_id = Some(message.id.uuid().to_string());
            return;
        }
        let message_id = self.ensure_assistant_message(message.id.uuid().to_string());
        self.open_assistant_text(&message_id);
        let text = public_text(&message.content);
        if !self.assistant_emitted_delta && !text.is_empty() {
            self.queue
                .push_back(Event::TextMessageContent(TextMessageContentEvent::new(
                    message_id.clone(),
                    text,
                )));
        }
        self.close_assistant_text();
        self.finish(None);
    }

    /// Switches to `message_id`, closing a different open assistant message.
    fn ensure_assistant_message(&mut self, message_id: String) -> String {
        if self.assistant_message_id.as_deref() != Some(message_id.as_str()) {
            self.close_assistant_text();
            self.assistant_message_id = Some(message_id.clone());
        }
        message_id
    }

    fn open_assistant_text(&mut self, message_id: &str) {
        if !self.assistant_content_started {
            self.queue
                .push_back(Event::TextMessageStart(TextMessageStartEvent::assistant(
                    message_id,
                )));
            self.assistant_content_started = true;
        }
    }

    fn close_assistant_text(&mut self) {
        if self.assistant_content_started
            && let Some(message_id) = self.assistant_message_id.clone()
        {
            self.queue
                .push_back(Event::TextMessageEnd(TextMessageEndEvent::new(message_id)));
        }
        self.assistant_message_id = None;
        self.assistant_content_started = false;
        self.assistant_emitted_delta = false;
    }

    fn next_id(&mut self, kind: &str) -> String {
        self.next_reasoning_id += 1;
        format!("{}-{kind}-{}", self.run_id, self.next_reasoning_id)
    }

    fn open_span(&mut self, by_tools: bool) {
        let id = self.next_id("reasoning");
        self.queue
            .push_back(Event::ReasoningStart(ReasoningSpanEvent::new(id.clone())));
        self.reasoning_span = Some(id);
        self.span_opened_by_tools = by_tools;
    }

    fn close_span(&mut self) {
        if let Some(id) = self.reasoning_span.take() {
            self.queue
                .push_back(Event::ReasoningEnd(ReasoningSpanEvent::new(id)));
        }
    }

    fn ensure_reasoning_message(&mut self) -> String {
        if let Some(id) = &self.reasoning_message {
            return id.clone();
        }
        let id = self.next_id("reasoning-message");
        self.queue.push_back(Event::ReasoningMessageStart(
            ReasoningMessageStartEvent::new(id.clone()),
        ));
        self.reasoning_message = Some(id.clone());
        id
    }

    fn close_reasoning_message(&mut self) {
        if let Some(id) = self.reasoning_message.take() {
            self.queue
                .push_back(Event::ReasoningMessageEnd(ReasoningMessageEndEvent::new(
                    id,
                )));
        }
    }

    /// Emits a self-contained reasoning message, or appends to the one model
    /// reasoning is streaming.
    fn reasoning_text(&mut self, text: &str) {
        if self.thinking && self.reasoning_message.is_some() {
            let id = self.ensure_reasoning_message();
            self.queue.push_back(Event::ReasoningMessageContent(
                ReasoningMessageContentEvent::new(id, format!("\n{text}")),
            ));
            return;
        }
        let opened_span = self.reasoning_span.is_none();
        if opened_span {
            self.open_span(false);
        }
        self.close_reasoning_message();
        let id = self.ensure_reasoning_message();
        self.queue.push_back(Event::ReasoningMessageContent(
            ReasoningMessageContentEvent::new(id, text),
        ));
        self.close_reasoning_message();
        if opened_span {
            self.close_span();
        }
    }

    fn reasoning_summary(&mut self, summary: &[String]) {
        let text = summary
            .iter()
            .map(|segment| segment.trim())
            .filter(|segment| !segment.is_empty())
            .collect::<Vec<_>>()
            .join("\n");
        if !text.is_empty() {
            self.reasoning_text(&text);
        }
    }

    /// Tool activity shows the policy's fixed text on the reasoning channel.
    /// It opens a span when none is open and keeps it open until the last
    /// running tool completes.
    fn tool_activity(&mut self, text: &str) {
        if !self.tool_activity_shown {
            if self.reasoning_span.is_none() {
                self.open_span(true);
            }
            self.tool_activity_shown = true;
        }
        if self.thinking && self.reasoning_message.is_some() {
            let id = self.ensure_reasoning_message();
            self.queue.push_back(Event::ReasoningMessageContent(
                ReasoningMessageContentEvent::new(id, format!("\n{text}")),
            ));
            return;
        }
        self.close_reasoning_message();
        let id = self.ensure_reasoning_message();
        self.queue.push_back(Event::ReasoningMessageContent(
            ReasoningMessageContentEvent::new(id, text),
        ));
        self.close_reasoning_message();
    }

    /// A subagent task's snapshot: announce a new invocation, close a
    /// terminal one. Other task kinds, and a task first seen already settled
    /// (one an earlier run started), are not this run's subagents.
    fn subagent_task(&mut self, task: &SessionTask) {
        if task.kind != TASK_KIND_SUBAGENT {
            return;
        }
        if !self.seen_subagents.contains(&task.id) {
            if task.state.is_terminal() {
                return;
            }
            self.seen_subagents.insert(task.id.clone());
            let background = task.spec.get("mode").and_then(Value::as_str) == Some("background");
            self.open_subagents.push((task.id.clone(), background));
            self.queue
                .push_back(Event::SubagentStarted(SubagentStartedEvent {
                    subagent_run_id: task.id.clone(),
                    name: task.display_name.clone(),
                    ..SubagentStartedEvent::default()
                }));
        }
        if !task.state.is_terminal() {
            return;
        }
        let Some(position) = self
            .open_subagents
            .iter()
            .position(|(id, _)| *id == task.id)
        else {
            return;
        };
        self.open_subagents.remove(position);
        let id = task.id.clone();
        match task.state {
            SessionTaskState::Succeeded => {
                // The child's final answer: the parent stream sees it as the
                // task's summary, never its transcript.
                if let Some(summary) = task.summary.as_deref().filter(|s| !s.trim().is_empty()) {
                    self.subagent_text(&id, &format!("{id}-summary"), summary);
                }
                self.queue
                    .push_back(Event::SubagentFinished(SubagentFinishedEvent {
                        subagent_run_id: id,
                        ..SubagentFinishedEvent::default()
                    }));
            }
            SessionTaskState::Canceled => {
                self.queue
                    .push_back(Event::SubagentError(SubagentErrorEvent {
                        subagent_run_id: id,
                        message: "Subagent canceled".to_string(),
                        code: Some("cancelled".to_string()),
                        ..SubagentErrorEvent::default()
                    }));
            }
            _ => {
                // Failures go through the policy's error mapping, so a public
                // channel sanitizes a child's error as it does the run's.
                let failure = task
                    .error
                    .as_ref()
                    .map(|error| TurnFailure {
                        message: error.message.clone(),
                        code: Some(error.kind.clone()),
                    })
                    .unwrap_or_default();
                let error = (self.policy.error)(&failure);
                self.queue
                    .push_back(Event::SubagentError(SubagentErrorEvent {
                        subagent_run_id: id,
                        message: error.message,
                        code: error.code,
                        ..SubagentErrorEvent::default()
                    }));
            }
        }
    }

    /// A message a subagent posted to its parent: text becomes an attributed
    /// assistant message, structured data an attributed activity snapshot.
    fn subagent_message(&mut self, data: &TaskMessageEventData) {
        let message = &data.message;
        if message.direction != TaskMessageDirection::Outbound
            || !self
                .open_subagents
                .iter()
                .any(|(id, _)| *id == data.task_id)
        {
            return;
        }
        let text = message
            .content
            .iter()
            .filter_map(|part| match part {
                TaskMessagePart::Text { text } => Some(text.as_str()),
                TaskMessagePart::Data { .. } => None,
            })
            .filter(|text| !text.is_empty())
            .collect::<Vec<_>>()
            .join("\n");
        if !text.is_empty() {
            self.subagent_text(&data.task_id, &message.id, &text);
        }
        for (index, part) in message.content.iter().enumerate() {
            if let TaskMessagePart::Data { data: value } = part {
                let content = serde_json::Map::from_iter([("data".to_string(), value.clone())]);
                self.queue
                    .push_back(Event::ActivitySnapshot(ActivitySnapshotEvent {
                        message_id: format!("{}-{index}", message.id),
                        activity_type: SUBAGENT_ACTIVITY_TYPE.to_string(),
                        content,
                        subagent_run_id: Some(data.task_id.clone()),
                        ..ActivitySnapshotEvent::default()
                    }));
            }
        }
    }

    /// A complete assistant text message attributed to a subagent.
    fn subagent_text(&mut self, subagent_run_id: &str, message_id: &str, text: &str) {
        let attributed = Some(subagent_run_id.to_string());
        self.queue
            .push_back(Event::TextMessageStart(TextMessageStartEvent {
                subagent_run_id: attributed.clone(),
                ..TextMessageStartEvent::assistant(message_id)
            }));
        self.queue
            .push_back(Event::TextMessageContent(TextMessageContentEvent {
                subagent_run_id: attributed.clone(),
                ..TextMessageContentEvent::new(message_id, text)
            }));
        self.queue
            .push_back(Event::TextMessageEnd(TextMessageEndEvent {
                subagent_run_id: attributed,
                ..TextMessageEndEvent::new(message_id)
            }));
    }

    /// A run may not end while a subagent invocation is open. A foreground
    /// child ends inside its parent's turn, so one open here outlived a
    /// cancelled or failed turn, or waits beside an interrupt. A background
    /// child carries on after the run: an activity says so first. Either way
    /// the segment ends `suspended`, which 1.0 defines as terminal for this
    /// stream and not for the subagent; success or error would claim an
    /// outcome nobody has seen yet.
    fn close_subagents(&mut self) {
        for (id, background) in std::mem::take(&mut self.open_subagents) {
            if background {
                let content = serde_json::Map::from_iter([(
                    "state".to_string(),
                    Value::String("running".to_string()),
                )]);
                self.queue
                    .push_back(Event::ActivitySnapshot(ActivitySnapshotEvent {
                        message_id: format!("{id}-background"),
                        activity_type: SUBAGENT_ACTIVITY_TYPE.to_string(),
                        content,
                        subagent_run_id: Some(id.clone()),
                        ..ActivitySnapshotEvent::default()
                    }));
            }
            self.queue
                .push_back(Event::SubagentFinished(SubagentFinishedEvent {
                    subagent_run_id: id,
                    outcome: Some(SubagentFinishedOutcome::Suspended {
                        interrupt_ids: None,
                    }),
                    ..SubagentFinishedEvent::default()
                }));
        }
    }

    /// 1.0 fails a run that finishes with a message or span still open.
    fn close_all(&mut self) {
        self.close_assistant_text();
        self.close_reasoning_message();
        self.close_span();
        self.thinking = false;
        self.tool_activity_shown = false;
        self.span_opened_by_tools = false;
    }
}

/// The session's current todo list as its history shows it: the result of
/// the last successful `write_todos` call, or `None` when the agent never
/// wrote one. Pass the messages' content oldest first, as history stores it.
/// [`TodoHistory`] reads the same thing a page at a time.
pub fn latest_todos<'a>(messages: impl IntoIterator<Item = &'a [ContentPart]>) -> Option<Value> {
    let mut history = TodoHistory::default();
    for parts in messages {
        history.observe(parts);
    }
    history.into_todos()
}

/// [`latest_todos`] fed incrementally, for history read in pages: a call and
/// its result can land on different pages.
#[derive(Clone, Debug, Default)]
pub struct TodoHistory {
    /// `write_todos` calls whose result has not been seen yet.
    calls: HashSet<String>,
    latest: Option<Value>,
}

impl TodoHistory {
    /// Reads one message's content, the next oldest first.
    pub fn observe(&mut self, parts: &[ContentPart]) {
        for part in parts {
            match part {
                ContentPart::ToolCall(call) if call.name == TODO_TOOL_NAME => {
                    self.calls.insert(call.id.clone());
                }
                ContentPart::ToolResult(result) if self.calls.remove(&result.tool_call_id) => {
                    if result.error.is_none()
                        && let Some(todos) = result.result.as_ref().and_then(todos_from_result)
                    {
                        self.latest = Some(todos);
                    }
                }
                _ => {}
            }
        }
    }

    /// The latest list seen, if any.
    pub fn into_todos(self) -> Option<Value> {
        self.latest
    }
}

/// The todo list in a `write_todos` result, in any of the shapes the runtime
/// stores one: the tool's JSON object, that object as a JSON string, or
/// content parts whose text is that string (`tool.completed`).
fn todos_from_result(result: &Value) -> Option<Value> {
    match result {
        Value::Object(object) => object
            .get(TODOS_STATE_KEY)
            .filter(|todos| todos.is_array())
            .map(sanitize_todos),
        Value::String(text) => serde_json::from_str::<Value>(text)
            .ok()
            .filter(Value::is_object)
            .and_then(|value| todos_from_result(&value)),
        Value::Array(parts) => parts.iter().rev().find_map(|part| {
            (part.get("type").and_then(Value::as_str) == Some("text"))
                .then(|| part.get("text"))
                .flatten()
                .and_then(todos_from_result)
        }),
        _ => None,
    }
}

/// Keeps only the todo fields the tool defines, as strings, so whatever
/// else a result carries never reaches the client's state.
fn sanitize_todos(todos: &Value) -> Value {
    let items = todos
        .as_array()
        .map(|items| {
            items
                .iter()
                .filter_map(Value::as_object)
                .map(|item| {
                    let fields =
                        ["content", "activeForm", "status"]
                            .into_iter()
                            .filter_map(|key| {
                                item.get(key)
                                    .filter(|value| value.is_string())
                                    .map(|value| (key.to_string(), value.clone()))
                            });
                    Value::Object(serde_json::Map::from_iter(fields))
                })
                .collect()
        })
        .unwrap_or_default();
    Value::Array(items)
}

fn parse<T: DeserializeOwned>(data: &Value) -> Option<T> {
    serde_json::from_value(data.clone()).ok()
}

/// Whether a completed output message is the run's public answer: not
/// commentary, not a tool-call carrier, and with something to show.
pub fn is_terminal_public_output(message: &RuntimeMessage, emitted_delta: bool) -> bool {
    if matches!(message.phase, Some(ExecutionPhase::Commentary)) {
        return false;
    }
    if message
        .content
        .iter()
        .any(|part| matches!(part, ContentPart::ToolCall(_) | ContentPart::ToolResult(_)))
    {
        return false;
    }
    emitted_delta || !public_text(&message.content).is_empty()
}

/// The text of content parts as an AG-UI string. Tool calls, tool results
/// and reasoning are other channels' content and are left out; media becomes
/// a short placeholder.
pub fn public_text(parts: &[ContentPart]) -> String {
    parts
        .iter()
        .filter_map(public_part_text)
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>()
        .join("\n")
}

fn public_part_text(part: &ContentPart) -> Option<String> {
    match part {
        ContentPart::Text(text) => Some(text.text.clone()),
        ContentPart::Image(image) => {
            Some(image.url.clone().unwrap_or_else(|| "[Image]".to_string()))
        }
        ContentPart::ImageFile(image) => Some(format!(
            "[Image file: {}]",
            image.filename.as_deref().unwrap_or("unnamed")
        )),
        ContentPart::File(file) => Some(format!(
            "[File: {}]",
            file.filename.as_deref().unwrap_or("unnamed")
        )),
        // Tool calls, tool results and reasoning belong to other channels;
        // `ContentPart` is non-exhaustive, and a part this build cannot
        // project is omitted rather than rendered as an unknown marker.
        _ => None,
    }
}