1use std::collections::HashMap;
48
49use serde::{Deserialize, Serialize};
50
51use crate::driver::{ModelRoundTrace, TurnResult, TurnTrace};
52use crate::interaction::TurnInteraction;
53use causa_kernel::{
54 BlockContent, ConversationId, RoundId, StreamDelta, ToolCallPayload, TurnContext, TurnId,
55};
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct ContextEvent {
70 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub conversation_id: Option<ConversationId>,
74 pub turn_id: TurnId,
76 pub kind: ContextEventKind,
78}
79
80#[derive(Debug, Clone, Serialize, Deserialize)]
84#[serde(tag = "type", rename_all = "snake_case")]
85pub enum ContextEventKind {
86 TurnStarted,
88 ToolBatchDispatched {
95 round_id: RoundId,
97 calls: Vec<ToolCallPayload>,
99 },
100 TurnOutcome {
106 result: TurnResult,
108 trace: TurnTrace,
110 },
111 TextDelta {
116 round_id: RoundId,
118 delta: String,
120 },
121 ReasoningDelta {
123 round_id: RoundId,
125 delta: String,
127 },
128 ToolCallDelta {
132 round_id: RoundId,
134 call_index: usize,
136 name_delta: Option<String>,
138 arguments_delta: Option<String>,
140 },
141}
142
143pub fn project_turn(
176 context: &TurnContext,
177 result: &TurnResult,
178 trace: &TurnTrace,
179 conversation_id: Option<ConversationId>,
180) -> Vec<ContextEvent> {
181 let turn_id = context.turn_id();
182 let mut events = Vec::with_capacity(2 + trace.rounds.len());
183 events.push(ContextEvent {
184 conversation_id: conversation_id.clone(),
185 turn_id: turn_id.clone(),
186 kind: ContextEventKind::TurnStarted,
187 });
188 let calls_by_block = call_index(context);
191 for round in &trace.rounds {
192 if round.tool_batch.is_none() {
193 continue;
194 }
195 let calls = committed_calls(&calls_by_block, round);
196 events.push(ContextEvent {
197 conversation_id: conversation_id.clone(),
198 turn_id: turn_id.clone(),
199 kind: ContextEventKind::ToolBatchDispatched {
200 round_id: round.round_id,
201 calls,
202 },
203 });
204 }
205 events.push(ContextEvent {
206 conversation_id,
207 turn_id,
208 kind: ContextEventKind::TurnOutcome {
209 result: result.clone(),
210 trace: trace.clone(),
211 },
212 });
213 events
214}
215
216fn committed_calls(
221 call_index: &HashMap<causa_kernel::BlockId, ToolCallPayload>,
222 round: &ModelRoundTrace,
223) -> Vec<ToolCallPayload> {
224 round
225 .applied_block_ids
226 .iter()
227 .filter_map(|id| call_index.get(id).cloned())
228 .collect()
229}
230
231pub struct StreamEventCollector {
242 turn_id: TurnId,
243 conversation_id: Option<ConversationId>,
244 events: std::sync::Mutex<Vec<ContextEvent>>,
245}
246
247impl StreamEventCollector {
248 pub fn new(turn_id: TurnId, conversation_id: Option<ConversationId>) -> Self {
251 Self {
252 turn_id,
253 conversation_id,
254 events: std::sync::Mutex::new(Vec::new()),
255 }
256 }
257
258 pub fn events(&self) -> Vec<ContextEvent> {
261 self.events.lock().unwrap().clone()
262 }
263
264 pub fn into_events(self) -> Vec<ContextEvent> {
266 self.events.into_inner().unwrap()
267 }
268}
269
270#[async_trait::async_trait]
271impl TurnInteraction for StreamEventCollector {
272 async fn on_delta(&self, round_id: RoundId, delta: &StreamDelta) {
273 let kind = match delta {
274 StreamDelta::TextDelta { delta } => ContextEventKind::TextDelta {
275 round_id,
276 delta: delta.clone(),
277 },
278 StreamDelta::ReasoningDelta { delta } => ContextEventKind::ReasoningDelta {
279 round_id,
280 delta: delta.clone(),
281 },
282 StreamDelta::ToolCallDelta {
283 call_index,
284 name_delta,
285 arguments_delta,
286 ..
287 } => ContextEventKind::ToolCallDelta {
288 round_id,
289 call_index: *call_index,
290 name_delta: name_delta.clone(),
291 arguments_delta: arguments_delta.clone(),
292 },
293 StreamDelta::Usage(_) | StreamDelta::Done { .. } | StreamDelta::Error { .. } => {
295 return;
296 }
297 };
298 self.events.lock().unwrap().push(ContextEvent {
299 conversation_id: self.conversation_id.clone(),
300 turn_id: self.turn_id.clone(),
301 kind,
302 });
303 }
304}
305
306pub fn project_streaming_turn(
330 context: &TurnContext,
331 result: &TurnResult,
332 trace: &TurnTrace,
333 conversation_id: Option<ConversationId>,
334 deltas: Vec<ContextEvent>,
335) -> Vec<ContextEvent> {
336 let turn_id = context.turn_id();
337 let envelope = |kind: ContextEventKind| ContextEvent {
338 conversation_id: conversation_id.clone(),
339 turn_id: turn_id.clone(),
340 kind,
341 };
342 let mut delta_by_round: HashMap<u32, Vec<ContextEvent>> = HashMap::new();
343 for event in deltas {
344 let round = match &event.kind {
345 ContextEventKind::TextDelta { round_id, .. }
346 | ContextEventKind::ReasoningDelta { round_id, .. }
347 | ContextEventKind::ToolCallDelta { round_id, .. } => round_id.0,
348 _ => continue,
349 };
350 delta_by_round.entry(round).or_default().push(event);
351 }
352 let mut rounds: Vec<u32> = trace
353 .rounds
354 .iter()
355 .map(|r| r.round_id.0)
356 .chain(delta_by_round.keys().copied())
357 .collect();
358 rounds.sort_unstable();
359 rounds.dedup();
360
361 let mut events = Vec::with_capacity(2 + rounds.len());
362 events.push(envelope(ContextEventKind::TurnStarted));
363 for round in rounds {
364 if let Some(round_deltas) = delta_by_round.remove(&round) {
365 events.extend(round_deltas);
366 }
367 if let Some(trace_round) = trace
368 .rounds
369 .iter()
370 .find(|r| r.round_id.0 == round)
371 .filter(|r| r.tool_batch.is_some())
372 {
373 let calls = committed_calls(&call_index(context), trace_round);
374 events.push(envelope(ContextEventKind::ToolBatchDispatched {
375 round_id: RoundId(round),
376 calls,
377 }));
378 }
379 }
380 events.push(envelope(ContextEventKind::TurnOutcome {
381 result: result.clone(),
382 trace: trace.clone(),
383 }));
384 events
385}
386
387fn call_index(context: &TurnContext) -> HashMap<causa_kernel::BlockId, ToolCallPayload> {
389 context
390 .blocks()
391 .iter()
392 .filter_map(|b| match &b.content {
393 BlockContent::ToolCall(call) => Some((b.id.clone(), call.clone())),
394 _ => None,
395 })
396 .collect()
397}
398
399#[cfg(test)]
406mod tests {
407 use super::*;
408 use crate::driver::{OutputSummary, ToolBatchTrace, TurnInterruption};
409 use causa_kernel::{
410 BlockId, BlockSequence, ContextVersion, InvocationId, ModelResponse, ModelStopReason,
411 TextPayload, ToolCallId, TurnContext,
412 };
413 use serde_json::json;
414
415 fn turn_id(byte: u8) -> TurnId {
416 TurnId::new(format!("turn-{byte}"))
417 }
418
419 fn empty_trace() -> TurnTrace {
420 TurnTrace {
421 rounds: Vec::new(),
422 tool_calls_total: 0,
423 total_duration_ms: 0,
424 }
425 }
426
427 fn turn_with_tool_call(tool: &str) -> TurnContext {
430 let mut ctx = TurnContext::new(turn_id(1));
431 ctx.append_input(TextPayload::new("hi"), "user")
432 .expect("append_input");
433 let response = ModelResponse {
434 text: TextPayload::new(String::new()),
435 tool_calls: vec![causa_kernel::ToolCallDraft {
436 tool_name: tool.to_string(),
437 arguments: json!({"k": "v"}),
438 provider_call_id: None,
439 }],
440 };
441 ctx.append_model_output(
442 InvocationId {
443 turn_id: turn_id(1),
444 round_id: RoundId(0),
445 },
446 &response,
447 ModelStopReason::ToolUse,
448 )
449 .expect("append_model_output");
450 ctx
451 }
452
453 fn round_with_tool_batch(round_id: RoundId, call_block_seq: u64) -> ModelRoundTrace {
457 ModelRoundTrace {
458 round_id,
459 invocation_id: InvocationId {
460 turn_id: turn_id(1),
461 round_id,
462 },
463 frame_version: ContextVersion(0),
464 attempts: Vec::new(),
465 output_summary: Some(OutputSummary {
466 stop_reason: ModelStopReason::ToolUse,
467 usage: None,
468 tool_call_count: 1,
469 response_text_bytes: 0,
470 }),
471 applied_block_ids: vec![BlockId {
472 turn_id: turn_id(1),
473 sequence: BlockSequence(call_block_seq),
474 }],
475 tool_batch: Some(ToolBatchTrace {
476 calls: vec![],
477 completion_order: Vec::new(),
478 }),
479 }
480 }
481
482 fn round_endturn(round_id: RoundId) -> ModelRoundTrace {
483 ModelRoundTrace {
484 round_id,
485 invocation_id: InvocationId {
486 turn_id: turn_id(2),
487 round_id,
488 },
489 frame_version: ContextVersion(0),
490 attempts: Vec::new(),
491 output_summary: Some(OutputSummary {
492 stop_reason: ModelStopReason::EndTurn,
493 usage: None,
494 tool_call_count: 0,
495 response_text_bytes: 0,
496 }),
497 applied_block_ids: vec![],
498 tool_batch: None,
499 }
500 }
501
502 fn completed() -> TurnResult {
503 TurnResult::Completed {
504 final_output: causa_kernel::ModelOutput {
505 stop_reason: ModelStopReason::EndTurn,
506 usage: None,
507 reasoning: None,
508 response: ModelResponse {
509 text: TextPayload::new(String::new()),
510 tool_calls: Vec::new(),
511 },
512 },
513 }
514 }
515
516 #[test]
517 fn empty_trace_emits_only_started_and_outcome() {
518 let ctx = TurnContext::new(turn_id(1));
519 let events = project_turn(&ctx, &completed(), &empty_trace(), None);
520 assert_eq!(events.len(), 2);
521 assert!(matches!(events[0].kind, ContextEventKind::TurnStarted));
522 assert!(matches!(
523 events[1].kind,
524 ContextEventKind::TurnOutcome { .. }
525 ));
526 }
527
528 #[test]
529 fn dispatched_calls_derive_from_committed_tool_call_blocks() {
530 let ctx = turn_with_tool_call("echo");
531 let mut trace = empty_trace();
532 trace.rounds.push(round_with_tool_batch(RoundId(0), 1));
533
534 let events = project_turn(&ctx, &completed(), &trace, None);
535 assert_eq!(events.len(), 3);
536 match &events[1].kind {
537 ContextEventKind::ToolBatchDispatched { round_id, calls } => {
538 assert_eq!(*round_id, RoundId(0));
539 assert_eq!(calls.len(), 1);
540 assert_eq!(calls[0].tool_name, "echo");
541 assert_eq!(calls[0].arguments, json!({"k": "v"}));
542 }
543 other => panic!("expected ToolBatchDispatched, got {other:?}"),
544 }
545 }
546
547 #[test]
548 fn endturn_round_produces_no_dispatch_event() {
549 let ctx = TurnContext::new(turn_id(1));
550 let mut trace = empty_trace();
551 trace.rounds.push(round_endturn(RoundId(7)));
552
553 let events = project_turn(&ctx, &completed(), &trace, None);
554 assert_eq!(
555 events.len(),
556 2,
557 "EndTurn must not produce ToolBatchDispatched"
558 );
559 assert!(matches!(events[0].kind, ContextEventKind::TurnStarted));
560 assert!(matches!(
561 events[1].kind,
562 ContextEventKind::TurnOutcome { .. }
563 ));
564 }
565
566 #[test]
567 fn multiple_rounds_emit_dispatches_in_round_id_order() {
568 let ctx = turn_with_tool_call("echo");
571 let mut trace = empty_trace();
572 trace.rounds.push(round_with_tool_batch(RoundId(0), 1));
573 trace.rounds.push(round_endturn(RoundId(1)));
574 trace.rounds.push(round_with_tool_batch(RoundId(2), 1));
575
576 let events = project_turn(&ctx, &completed(), &trace, None);
577 assert_eq!(events.len(), 4);
578 let dispatched_round_ids: Vec<RoundId> = events
579 .iter()
580 .filter_map(|e| match e.kind {
581 ContextEventKind::ToolBatchDispatched { round_id, .. } => Some(round_id),
582 _ => None,
583 })
584 .collect();
585 assert_eq!(dispatched_round_ids, vec![RoundId(0), RoundId(2)]);
586 }
587
588 #[test]
589 fn envelope_routes_conversation_and_turn_ids() {
590 let conv = ConversationId("conv-42".to_string());
591 let ctx = turn_with_tool_call("echo");
592 let mut trace = empty_trace();
593 trace.rounds.push(round_with_tool_batch(RoundId(0), 1));
594
595 let events = project_turn(&ctx, &completed(), &trace, Some(conv.clone()));
596 for e in &events {
597 assert_eq!(e.conversation_id, Some(conv.clone()));
598 assert_eq!(e.turn_id, turn_id(1));
599 }
600 let bare = project_turn(&ctx, &completed(), &trace, None);
602 let json = serde_json::to_string(&bare[0]).expect("serialize");
603 assert!(!json.contains("conversation_id"));
604 }
605
606 #[test]
607 fn interrupted_turn_carries_cause_in_outcome() {
608 let ctx = TurnContext::new(turn_id(1));
609 let mut trace = empty_trace();
610 trace.rounds.push(round_endturn(RoundId(0)));
611 let cause = TurnInterruption::MaxModelRounds { limit: 8 };
612 let events = project_turn(
613 &ctx,
614 &TurnResult::Interrupted {
615 cause: cause.clone(),
616 },
617 &trace,
618 None,
619 );
620 assert_eq!(events.len(), 2);
621 match &events[1].kind {
622 ContextEventKind::TurnOutcome { result, .. } => match result {
623 TurnResult::Interrupted { cause: c } => assert_eq!(*c, cause),
624 other => panic!("expected Interrupted, got {other:?}"),
625 },
626 other => panic!("expected TurnOutcome, got {other:?}"),
627 }
628 }
629
630 #[test]
633 fn round_trip_turn_started_no_conversation() {
634 let original = ContextEvent {
635 conversation_id: None,
636 turn_id: turn_id(7),
637 kind: ContextEventKind::TurnStarted,
638 };
639 let json = serde_json::to_string(&original).expect("serialize");
640 assert!(!json.contains("conversation_id"));
643 assert!(json.contains("\"type\":\"turn_started\""));
644 let restored: ContextEvent = serde_json::from_str(&json).expect("deserialize");
645 assert_eq!(restored.turn_id, turn_id(7));
646 assert_eq!(restored.conversation_id, None);
647 }
648
649 #[test]
650 fn round_trip_tool_batch_dispatched() {
651 let original = ContextEvent {
652 conversation_id: Some(ConversationId("conv-batch".into())),
653 turn_id: turn_id(11),
654 kind: ContextEventKind::ToolBatchDispatched {
655 round_id: RoundId(3),
656 calls: vec![ToolCallPayload {
657 call_id: ToolCallId("call-a".into()),
658 tool_name: "echo".into(),
659 arguments: json!({"k": "v"}),
660 }],
661 },
662 };
663 let json = serde_json::to_string(&original).expect("serialize");
664 let restored: ContextEvent = serde_json::from_str(&json).expect("deserialize");
665 match restored.kind {
666 ContextEventKind::ToolBatchDispatched { round_id, calls } => {
667 assert_eq!(round_id, RoundId(3));
668 assert_eq!(calls.len(), 1);
669 assert_eq!(calls[0].call_id.0, "call-a");
670 }
671 other => panic!("expected ToolBatchDispatched, got {other:?}"),
672 }
673 assert_eq!(
674 restored.conversation_id,
675 Some(ConversationId("conv-batch".into()))
676 );
677 assert_eq!(restored.turn_id, turn_id(11));
678 }
679
680 #[test]
681 fn round_trip_turn_outcome_completed_and_interrupted() {
682 let completed_event = ContextEvent {
683 conversation_id: Some(ConversationId("conv-out".into())),
684 turn_id: turn_id(99),
685 kind: ContextEventKind::TurnOutcome {
686 result: completed(),
687 trace: empty_trace(),
688 },
689 };
690 let json = serde_json::to_string(&completed_event).expect("serialize");
691 let restored: ContextEvent = serde_json::from_str(&json).expect("deserialize");
692 assert!(matches!(
693 restored.kind,
694 ContextEventKind::TurnOutcome {
695 result: TurnResult::Completed { .. },
696 ..
697 }
698 ));
699
700 let interrupted_event = ContextEvent {
701 conversation_id: None,
702 turn_id: turn_id(13),
703 kind: ContextEventKind::TurnOutcome {
704 result: TurnResult::Interrupted {
705 cause: TurnInterruption::CompactionFailed {
706 reason: "budget exceeded".into(),
707 },
708 },
709 trace: empty_trace(),
710 },
711 };
712 let json = serde_json::to_string(&interrupted_event).expect("serialize");
713 let restored: ContextEvent = serde_json::from_str(&json).expect("deserialize");
714 match restored.kind {
715 ContextEventKind::TurnOutcome {
716 result: TurnResult::Interrupted { cause },
717 ..
718 } => assert_eq!(
719 cause,
720 TurnInterruption::CompactionFailed {
721 reason: "budget exceeded".into()
722 }
723 ),
724 other => panic!("expected TurnOutcome Interrupted, got {other:?}"),
725 }
726 }
727
728 #[test]
729 fn project_turn_output_survives_serialization_round_trip() {
730 let ctx = turn_with_tool_call("echo");
731 let mut trace = empty_trace();
732 trace.rounds.push(round_with_tool_batch(RoundId(0), 1));
733
734 let events = project_turn(
735 &ctx,
736 &completed(),
737 &trace,
738 Some(ConversationId("conv-e2e".into())),
739 );
740 let json = serde_json::to_string(&events).expect("serialize");
741 let restored: Vec<ContextEvent> = serde_json::from_str(&json).expect("deserialize");
742 assert_eq!(restored.len(), events.len());
743 for e in &restored {
745 assert_eq!(e.conversation_id, Some(ConversationId("conv-e2e".into())));
746 assert_eq!(e.turn_id, turn_id(1));
747 }
748 match &restored[1].kind {
750 ContextEventKind::ToolBatchDispatched { calls, .. } => {
751 assert_eq!(calls.len(), 1);
752 }
753 other => panic!("expected ToolBatchDispatched, got {other:?}"),
754 }
755 }
756
757 #[test]
760 fn round_trip_streaming_delta_variants() {
761 let variants = vec![
762 ContextEvent {
763 conversation_id: Some(ConversationId("conv-s".into())),
764 turn_id: turn_id(21),
765 kind: ContextEventKind::TextDelta {
766 round_id: RoundId(1),
767 delta: "he".into(),
768 },
769 },
770 ContextEvent {
771 conversation_id: None,
772 turn_id: turn_id(22),
773 kind: ContextEventKind::ReasoningDelta {
774 round_id: RoundId(0),
775 delta: "pondering".into(),
776 },
777 },
778 ContextEvent {
779 conversation_id: None,
780 turn_id: turn_id(23),
781 kind: ContextEventKind::ToolCallDelta {
782 round_id: RoundId(2),
783 call_index: 1,
784 name_delta: Some("echo".into()),
785 arguments_delta: Some("{\"a\":1}".into()),
786 },
787 },
788 ];
789 for original in variants {
790 let json = serde_json::to_string(&original).expect("serialize");
791 let restored: ContextEvent = serde_json::from_str(&json).expect("deserialize");
792 assert_eq!(
793 serde_json::to_string(&restored).expect("re-serialize"),
794 json,
795 "round-trip must be stable"
796 );
797 }
798 }
799
800 #[test]
801 fn streaming_delta_wire_discriminators_are_pinned() {
802 let event = ContextEvent {
803 conversation_id: None,
804 turn_id: turn_id(1),
805 kind: ContextEventKind::TextDelta {
806 round_id: RoundId(0),
807 delta: "x".into(),
808 },
809 };
810 let json = serde_json::to_string(&event).expect("serialize");
811 assert!(json.contains("\"type\":\"text_delta\""), "{json}");
812 assert!(json.contains("\"round_id\":0"), "{json}");
813
814 let call = ContextEvent {
815 conversation_id: None,
816 turn_id: turn_id(1),
817 kind: ContextEventKind::ToolCallDelta {
818 round_id: RoundId(0),
819 call_index: 0,
820 name_delta: Some("echo".into()),
821 arguments_delta: None,
822 },
823 };
824 let json = serde_json::to_string(&call).expect("serialize");
825 assert!(json.contains("\"type\":\"tool_call_delta\""), "{json}");
826 let reasoning = ContextEvent {
829 conversation_id: None,
830 turn_id: turn_id(1),
831 kind: ContextEventKind::ReasoningDelta {
832 round_id: RoundId(0),
833 delta: "r".into(),
834 },
835 };
836 let json = serde_json::to_string(&reasoning).expect("serialize");
837 assert!(json.contains("\"type\":\"reasoning_delta\""), "{json}");
838 }
839
840 #[test]
841 fn collector_maps_deltas_and_skips_terminal_ones() {
842 let collector = StreamEventCollector::new(turn_id(9), None);
843 let deltas = vec![
844 StreamDelta::TextDelta { delta: "he".into() },
845 StreamDelta::ReasoningDelta { delta: "th".into() },
846 StreamDelta::ToolCallDelta {
847 call_index: 0,
848 provider_call_id: Some("p1".into()),
849 name_delta: Some("echo".into()),
850 arguments_delta: None,
851 },
852 StreamDelta::Usage(causa_kernel::ModelUsage {
853 input_tokens: 1,
854 output_tokens: 2,
855 cache_read_tokens: None,
856 cache_write_tokens: None,
857 reasoning_tokens: None,
858 }),
859 StreamDelta::Done {
860 stop_reason: ModelStopReason::EndTurn,
861 final_output: causa_kernel::ModelOutput {
862 response: ModelResponse {
863 text: TextPayload::new("he"),
864 tool_calls: vec![],
865 },
866 usage: None,
867 stop_reason: ModelStopReason::EndTurn,
868 reasoning: None,
869 },
870 },
871 StreamDelta::Error {
872 kind: causa_kernel::ModelInvokeErrorKind::Transient,
873 message: "x".into(),
874 },
875 ];
876 let rt = tokio::runtime::Runtime::new().unwrap();
877 for d in &deltas {
878 rt.block_on(collector.on_delta(RoundId(4), d));
879 }
880 let events = collector.into_events();
881 assert_eq!(events.len(), 3);
883 assert!(matches!(
884 events[0].kind,
885 ContextEventKind::TextDelta {
886 round_id: RoundId(4),
887 ..
888 }
889 ));
890 assert!(matches!(
891 events[1].kind,
892 ContextEventKind::ReasoningDelta { .. }
893 ));
894 match &events[2].kind {
895 ContextEventKind::ToolCallDelta {
896 call_index,
897 name_delta,
898 ..
899 } => {
900 assert_eq!(*call_index, 0);
901 assert_eq!(name_delta.as_deref(), Some("echo"));
902 }
903 other => panic!("expected ToolCallDelta, got {other:?}"),
904 }
905 }
906}