1use std::collections::HashMap;
58
59use serde_json::{Map, Value};
60
61use super::super::failure::first_cli_error;
62use super::super::types::{AgentEvent, AgentTurn, CompactionTrigger, TokenCounts};
63use super::Translator;
64
65#[derive(Debug, Default)]
66pub struct ClaudeTranslator {
67 pending_tool: Option<PendingToolUse>,
70 #[allow(dead_code)]
76 tool_names: HashMap<String, String>,
77 accumulated_response: String,
81 transcript: Vec<AgentTurn>,
83}
84
85#[derive(Debug)]
86struct PendingToolUse {
87 id: String,
88 name: String,
89 partial_json: String,
90}
91
92impl ClaudeTranslator {
93 pub fn new() -> Self {
94 Self::default()
95 }
96}
97
98impl Translator for ClaudeTranslator {
99 fn translate(&mut self, frame: Value) -> Vec<AgentEvent> {
100 let mut out = Vec::new();
101 let Some(frame_type) = frame.get("type").and_then(|v| v.as_str()) else {
102 return out;
103 };
104 match frame_type {
105 "stream_event" => handle_stream_event(self, &frame, &mut out),
106 "user" => handle_user_message(self, &frame, &mut out),
107 "assistant" => handle_assistant_message(self, &frame, &mut out),
108 "result" => handle_result(self, &frame, &mut out),
109 "system" => handle_system_message(self, &frame, &mut out),
110 _ => {}
111 }
112 out
113 }
114}
115
116fn handle_stream_event(t: &mut ClaudeTranslator, frame: &Value, out: &mut Vec<AgentEvent>) {
117 let Some(event) = frame.get("event") else {
118 return;
119 };
120 let Some(ev_type) = event.get("type").and_then(|v| v.as_str()) else {
121 return;
122 };
123 match ev_type {
124 "content_block_start" => {
125 let Some(block) = event.get("content_block") else {
126 return;
127 };
128 if block.get("type").and_then(|v| v.as_str()) == Some("tool_use") {
129 let id = block.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();
130 let name = block.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string();
131 t.tool_names.insert(id.clone(), name.clone());
132 t.pending_tool = Some(PendingToolUse {
133 id,
134 name,
135 partial_json: String::new(),
136 });
137 }
138 }
139 "content_block_delta" => {
140 let Some(delta) = event.get("delta") else {
141 return;
142 };
143 match delta.get("type").and_then(|v| v.as_str()) {
144 Some("text_delta") => {
145 if let Some(text) = delta.get("text").and_then(|v| v.as_str()) {
146 t.accumulated_response.push_str(text);
147 out.push(AgentEvent::AssistantText {
148 delta: text.to_string(),
149 });
150 }
151 }
152 Some("input_json_delta") => {
153 if let (Some(pending), Some(partial)) =
154 (&mut t.pending_tool, delta.get("partial_json").and_then(|v| v.as_str()))
155 {
156 pending.partial_json.push_str(partial);
157 }
158 }
159 _ => {} }
161 }
162 "content_block_stop" => {
163 if let Some(pending) = t.pending_tool.take() {
164 let input: Value = if pending.partial_json.is_empty() {
172 Value::Object(Map::new())
173 } else {
174 serde_json::from_str(&pending.partial_json)
178 .unwrap_or(Value::String(pending.partial_json))
179 };
180 out.push(AgentEvent::ToolUse {
181 tool_use_id: pending.id,
182 tool: pending.name,
183 input,
184 });
185 }
186 }
187 "message_start" => {
191 if let Some(content) = event
192 .get("message")
193 .filter(|m| m.get("role").and_then(|v| v.as_str()) == Some("user"))
194 .and_then(|m| m.get("content"))
195 .and_then(|c| c.as_array())
196 {
197 extract_tool_results(t, content, out);
198 }
199 }
200 _ => {} }
202}
203
204fn handle_user_message(t: &mut ClaudeTranslator, frame: &Value, out: &mut Vec<AgentEvent>) {
205 let Some(content) = frame
206 .get("message")
207 .and_then(|m| m.get("content"))
208 .and_then(|c| c.as_array())
209 else {
210 return;
211 };
212 extract_tool_results(t, content, out);
213}
214
215fn extract_tool_results(t: &mut ClaudeTranslator, content: &[Value], out: &mut Vec<AgentEvent>) {
219 for block in content {
220 if block.get("type").and_then(|v| v.as_str()) != Some("tool_result") {
221 continue;
222 }
223 let tool_use_id = block
224 .get("tool_use_id")
225 .and_then(|v| v.as_str())
226 .unwrap_or("")
227 .to_string();
228 let output = block.get("content").cloned().unwrap_or(Value::Null);
231 let is_error = block
232 .get("is_error")
233 .and_then(|v| v.as_bool())
234 .unwrap_or(false);
235 out.push(AgentEvent::ToolResult {
236 tool_use_id: tool_use_id.clone(),
237 output: output.clone(),
238 is_error,
239 });
240 t.transcript.push(AgentTurn {
244 role: "tool_result".to_string(),
245 content: serde_json::json!({
246 "tool_use_id": tool_use_id,
247 "content": output,
248 "is_error": is_error,
249 }),
250 timestamp_ms: now_ms(),
251 });
252 }
253}
254
255fn handle_assistant_message(t: &mut ClaudeTranslator, frame: &Value, _out: &mut Vec<AgentEvent>) {
256 if frame.get("partial").and_then(|v| v.as_bool()) == Some(true) {
265 return;
266 }
267 let Some(message) = frame.get("message") else {
271 return;
272 };
273 let content = message.get("content").cloned().unwrap_or(Value::Null);
274 t.transcript.push(AgentTurn {
275 role: "assistant".to_string(),
276 content,
277 timestamp_ms: now_ms(),
278 });
279}
280
281fn handle_result(t: &mut ClaudeTranslator, frame: &Value, out: &mut Vec<AgentEvent>) {
282 let cost_usd = frame
283 .get("cost_usd")
284 .and_then(|v| v.as_f64())
285 .unwrap_or(0.0);
286 let tokens = parse_usage(frame.get("usage"));
287 out.push(AgentEvent::Cost { cost_usd, tokens });
288
289 if frame.get("is_error").and_then(|v| v.as_bool()) == Some(true) {
295 let api_error_status = frame.get("api_error_status").and_then(|v| v.as_i64());
296 let message = frame
297 .get("result")
298 .and_then(|v| v.as_str())
299 .or_else(|| first_cli_error(frame))
300 .map(|s| s.to_string())
301 .unwrap_or_else(|| match api_error_status {
302 Some(code) if code > 0 => format!("API error {code}"),
303 _ => "Agent encountered an error".to_string(),
304 });
305 t.accumulated_response.clear();
306 t.transcript.clear();
307 out.push(AgentEvent::Error { message });
308 return;
309 }
310
311 let response = frame
312 .get("result")
313 .and_then(|v| v.as_str())
314 .map(|s| s.to_string())
315 .unwrap_or_else(|| std::mem::take(&mut t.accumulated_response));
316 let transcript = std::mem::take(&mut t.transcript);
317 out.push(AgentEvent::Done {
318 response,
319 transcript,
320 });
321}
322
323fn handle_system_message(_t: &mut ClaudeTranslator, frame: &Value, out: &mut Vec<AgentEvent>) {
334 if frame.get("subtype").and_then(|v| v.as_str()) != Some("compact_boundary") {
335 return;
336 }
337 let Some(meta) = field(frame, "compact_metadata", "compactMetadata") else {
338 return;
339 };
340 let Some(trigger) = meta.get("trigger").and_then(|v| v.as_str()).and_then(|s| match s {
341 "auto" => Some(CompactionTrigger::Auto),
342 "manual" => Some(CompactionTrigger::Manual),
343 _ => None, }) else {
345 return;
346 };
347 let count = |snake: &str, camel: &str| field(meta, snake, camel).and_then(|v| v.as_u64());
348 let Some(pre_tokens) = count("pre_tokens", "preTokens") else {
349 return;
350 };
351 let Some(post_tokens) = count("post_tokens", "postTokens") else {
352 return;
353 };
354 let Some(cumulative_dropped_tokens) = count("cumulative_dropped_tokens", "cumulativeDroppedTokens") else {
355 return;
356 };
357 let Some(duration_ms) = count("duration_ms", "durationMs") else {
358 return;
359 };
360 out.push(AgentEvent::CompactionBoundary {
361 trigger,
362 pre_tokens,
363 post_tokens,
364 cumulative_dropped_tokens,
365 duration_ms,
366 });
367}
368
369fn field<'a>(obj: &'a Value, snake: &str, camel: &str) -> Option<&'a Value> {
371 obj.get(snake).or_else(|| obj.get(camel))
372}
373
374pub(crate) fn parse_usage(usage: Option<&Value>) -> TokenCounts {
375 let Some((b, _)) = usage.and_then(crate::backend::usage_of::buckets_of) else {
377 return TokenCounts::default();
378 };
379 TokenCounts { input: b.uncached_input, output: b.output + b.reasoning, cache_creation: b.cache_write(), cache_read: b.cache_read }
380}
381
382use agentmux_common::time::now_ms;
383
384#[cfg(test)]
385mod tests {
386 use super::*;
387 use serde_json::json;
388
389 fn text_delta(text: &str) -> Value {
390 json!({
391 "type": "stream_event",
392 "event": {
393 "type": "content_block_delta",
394 "delta": { "type": "text_delta", "text": text }
395 }
396 })
397 }
398
399 fn tool_use_start(id: &str, name: &str) -> Value {
400 json!({
401 "type": "stream_event",
402 "event": {
403 "type": "content_block_start",
404 "content_block": { "type": "tool_use", "id": id, "name": name }
405 }
406 })
407 }
408
409 fn input_json_delta(partial: &str) -> Value {
410 json!({
411 "type": "stream_event",
412 "event": {
413 "type": "content_block_delta",
414 "delta": { "type": "input_json_delta", "partial_json": partial }
415 }
416 })
417 }
418
419 fn content_block_stop() -> Value {
420 json!({
421 "type": "stream_event",
422 "event": { "type": "content_block_stop" }
423 })
424 }
425
426 #[test]
427 fn text_delta_emits_assistant_text() {
428 let mut t = ClaudeTranslator::new();
429 let events = t.translate(text_delta("hello"));
430 assert_eq!(events.len(), 1);
431 match &events[0] {
432 AgentEvent::AssistantText { delta } => assert_eq!(delta, "hello"),
433 other => panic!("expected AssistantText, got {other:?}"),
434 }
435 }
436
437 #[test]
438 fn streaming_text_accumulates_for_done_response() {
439 let mut t = ClaudeTranslator::new();
442 t.translate(text_delta("Hello "));
443 t.translate(text_delta("world"));
444 let events = t.translate(json!({ "type": "result", "cost_usd": 0.01 }));
445 assert_eq!(events.len(), 2);
447 match &events[1] {
448 AgentEvent::Done { response, .. } => assert_eq!(response, "Hello world"),
449 other => panic!("expected Done with accumulated text, got {other:?}"),
450 }
451 }
452
453 #[test]
454 fn tool_use_emits_only_on_content_block_stop() {
455 let mut t = ClaudeTranslator::new();
456 assert!(t.translate(tool_use_start("t1", "Bash")).is_empty());
458 assert!(t.translate(input_json_delta(r#"{"command":"#)).is_empty());
460 assert!(t.translate(input_json_delta(r#""ls"}"#)).is_empty());
461 let events = t.translate(content_block_stop());
463 assert_eq!(events.len(), 1);
464 match &events[0] {
465 AgentEvent::ToolUse {
466 tool_use_id,
467 tool,
468 input,
469 } => {
470 assert_eq!(tool_use_id, "t1");
471 assert_eq!(tool, "Bash");
472 assert_eq!(input, &json!({ "command": "ls" }));
473 }
474 other => panic!("expected ToolUse, got {other:?}"),
475 }
476 }
477
478 #[test]
479 fn no_arg_tool_emits_empty_object() {
480 let mut t = ClaudeTranslator::new();
484 t.translate(tool_use_start("t1", "Echo"));
485 let events = t.translate(content_block_stop());
486 assert_eq!(events.len(), 1);
487 match &events[0] {
488 AgentEvent::ToolUse { input, .. } => {
489 assert_eq!(input, &json!({}));
490 }
491 other => panic!("expected ToolUse with empty object input, got {other:?}"),
492 }
493 }
494
495 #[test]
496 fn malformed_tool_input_falls_back_to_raw_string() {
497 let mut t = ClaudeTranslator::new();
498 t.translate(tool_use_start("t1", "Edit"));
499 t.translate(input_json_delta(r#"{"this is bad json"#));
500 let events = t.translate(content_block_stop());
501 assert_eq!(events.len(), 1);
502 match &events[0] {
503 AgentEvent::ToolUse { input, .. } => {
504 assert_eq!(input, &json!(r#"{"this is bad json"#));
507 }
508 other => panic!("expected ToolUse fallback, got {other:?}"),
509 }
510 }
511
512 #[test]
513 fn user_tool_result_emits_event() {
514 let mut t = ClaudeTranslator::new();
515 let events = t.translate(json!({
516 "type": "user",
517 "message": {
518 "content": [{
519 "type": "tool_result",
520 "tool_use_id": "t3",
521 "content": "command output here",
522 "is_error": false
523 }]
524 }
525 }));
526 assert_eq!(events.len(), 1);
527 match &events[0] {
528 AgentEvent::ToolResult {
529 tool_use_id,
530 output,
531 is_error,
532 } => {
533 assert_eq!(tool_use_id, "t3");
534 assert_eq!(output, &json!("command output here"));
535 assert!(!is_error);
536 }
537 other => panic!("expected ToolResult, got {other:?}"),
538 }
539 }
540
541 #[test]
542 fn tool_result_is_error_propagates() {
543 let mut t = ClaudeTranslator::new();
544 let events = t.translate(json!({
545 "type": "user",
546 "message": {
547 "content": [{
548 "type": "tool_result",
549 "tool_use_id": "t4",
550 "content": "permission denied",
551 "is_error": true
552 }]
553 }
554 }));
555 match &events[0] {
556 AgentEvent::ToolResult { is_error, .. } => assert!(is_error),
557 other => panic!("expected ToolResult with is_error, got {other:?}"),
558 }
559 }
560
561 #[test]
562 fn result_emits_cost_then_done_with_explicit_response() {
563 let mut t = ClaudeTranslator::new();
564 let events = t.translate(json!({
565 "type": "result",
566 "cost_usd": 0.0123,
567 "usage": {
568 "input_tokens": 100,
569 "output_tokens": 50,
570 "cache_creation_input_tokens": 0,
571 "cache_read_input_tokens": 200
572 },
573 "result": "final answer text"
574 }));
575 assert_eq!(events.len(), 2);
576 match &events[0] {
577 AgentEvent::Cost { cost_usd, tokens } => {
578 assert_eq!(*cost_usd, 0.0123);
579 assert_eq!(tokens.input, 100);
580 assert_eq!(tokens.output, 50);
581 assert_eq!(tokens.cache_creation, 0);
582 assert_eq!(tokens.cache_read, 200);
583 }
584 other => panic!("expected Cost first, got {other:?}"),
585 }
586 match &events[1] {
587 AgentEvent::Done { response, .. } => {
588 assert_eq!(response, "final answer text");
589 }
590 other => panic!("expected Done second, got {other:?}"),
591 }
592 }
593
594 #[test]
595 fn assistant_message_added_to_transcript() {
596 let mut t = ClaudeTranslator::new();
597 let events = t.translate(json!({
601 "type": "assistant",
602 "message": {
603 "content": [{ "type": "text", "text": "hello" }]
604 }
605 }));
606 assert!(events.is_empty());
607 let done = t.translate(json!({ "type": "result", "cost_usd": 0.0 }));
609 match &done[1] {
610 AgentEvent::Done { transcript, .. } => {
611 assert_eq!(transcript.len(), 1);
612 assert_eq!(transcript[0].role, "assistant");
613 }
614 other => panic!("expected Done, got {other:?}"),
615 }
616 }
617
618 #[test]
619 fn unknown_frame_returns_empty() {
620 let mut t = ClaudeTranslator::new();
621 assert!(t.translate(json!({ "type": "system" })).is_empty());
622 assert!(t.translate(json!({ "type": "stream_event", "event": { "type": "message_stop" } })).is_empty());
623 assert!(t.translate(json!({ "type": "stream_event", "event": { "type": "message_delta" } })).is_empty());
624 }
625
626 fn compact_boundary_frame(trigger: &str) -> Value {
629 json!({
633 "type": "system",
634 "subtype": "compact_boundary",
635 "content": "Conversation compacted",
636 "level": "info",
637 "compactMetadata": {
638 "trigger": trigger,
639 "preTokens": 783_887,
640 "postTokens": 11_775,
641 "cumulativeDroppedTokens": 772_112,
642 "durationMs": 231_606,
643 "preCompactDiscoveredTools": ["Bash", "Edit"],
644 "preservedSegment": {
645 "headUuid": "h1",
646 "anchorUuid": "a1",
647 "tailUuid": "t1"
648 }
649 },
650 "timestamp": "2026-07-21T17:55:35.500Z"
651 })
652 }
653
654 #[test]
655 fn compact_boundary_manual_emits_compaction_boundary() {
656 let mut t = ClaudeTranslator::new();
657 let events = t.translate(compact_boundary_frame("manual"));
658 assert_eq!(events.len(), 1);
659 match &events[0] {
660 AgentEvent::CompactionBoundary {
661 trigger,
662 pre_tokens,
663 post_tokens,
664 cumulative_dropped_tokens,
665 duration_ms,
666 } => {
667 assert_eq!(*trigger, CompactionTrigger::Manual);
668 assert_eq!(*pre_tokens, 783_887);
669 assert_eq!(*post_tokens, 11_775);
670 assert_eq!(*cumulative_dropped_tokens, 772_112);
671 assert_eq!(*duration_ms, 231_606);
672 }
673 other => panic!("expected CompactionBoundary, got {other:?}"),
674 }
675 }
676
677 #[test]
678 fn compact_boundary_auto_trigger_maps_correctly() {
679 let mut t = ClaudeTranslator::new();
680 let events = t.translate(compact_boundary_frame("auto"));
681 assert_eq!(events.len(), 1);
682 match &events[0] {
683 AgentEvent::CompactionBoundary { trigger, .. } => {
684 assert_eq!(*trigger, CompactionTrigger::Auto);
685 }
686 other => panic!("expected CompactionBoundary, got {other:?}"),
687 }
688 }
689
690 fn stdout_compact_boundary_frame(trigger: &str) -> Value {
693 json!({
694 "type": "system",
695 "subtype": "compact_boundary",
696 "uuid": "8c1f4e2a-2b7d-4a51-9a0e-6f3c2d1b0a99",
697 "compact_metadata": {
698 "trigger": trigger,
699 "pre_tokens": 25_040,
700 "post_tokens": 733,
701 "cumulative_dropped_tokens": 24_307,
702 "duration_ms": 1_513
703 },
704 "logical_parent_uuid": "3e9b7c10-5d2f-4c8a-b1e4-7a6d5c4b3a21"
705 })
706 }
707
708 #[test]
709 fn stdout_snake_case_compact_boundary_emits_compaction_boundary() {
710 for (wire, expected) in [("manual", CompactionTrigger::Manual), ("auto", CompactionTrigger::Auto)] {
711 let mut t = ClaudeTranslator::new();
712 let events = t.translate(stdout_compact_boundary_frame(wire));
713 assert_eq!(events.len(), 1, "{wire}");
714 match &events[0] {
715 AgentEvent::CompactionBoundary {
716 trigger,
717 pre_tokens,
718 post_tokens,
719 cumulative_dropped_tokens,
720 duration_ms,
721 } => {
722 assert_eq!(*trigger, expected);
723 assert_eq!(*pre_tokens, 25_040);
724 assert_eq!(*post_tokens, 733);
725 assert_eq!(*cumulative_dropped_tokens, 24_307);
726 assert_eq!(*duration_ms, 1_513);
727 }
728 other => panic!("expected CompactionBoundary, got {other:?}"),
729 }
730 }
731 }
732
733 #[test]
734 fn stdout_snake_case_malformed_field_returns_empty() {
735 let mut t = ClaudeTranslator::new();
736 let mut frame = stdout_compact_boundary_frame("manual");
737 frame["compact_metadata"]["pre_tokens"] = json!("not-a-number");
738 assert!(t.translate(frame).is_empty());
739 let mut frame = stdout_compact_boundary_frame("manual");
740 frame["compact_metadata"].as_object_mut().unwrap().remove("duration_ms");
741 assert!(t.translate(frame).is_empty());
742 }
743
744 #[test]
745 fn system_frame_with_unrelated_subtype_returns_empty() {
746 let mut t = ClaudeTranslator::new();
749 assert!(t
750 .translate(json!({ "type": "system", "subtype": "other_thing" }))
751 .is_empty());
752 }
753
754 #[test]
755 fn compact_boundary_missing_metadata_returns_empty() {
756 let mut t = ClaudeTranslator::new();
757 assert!(t
758 .translate(json!({ "type": "system", "subtype": "compact_boundary" }))
759 .is_empty());
760 }
761
762 #[test]
763 fn compact_boundary_malformed_field_returns_empty_not_panic() {
764 let mut t = ClaudeTranslator::new();
765 let events = t.translate(json!({
766 "type": "system",
767 "subtype": "compact_boundary",
768 "compactMetadata": {
769 "trigger": "manual",
770 "preTokens": "not-a-number",
771 "postTokens": 11_775,
772 "cumulativeDroppedTokens": 772_112,
773 "durationMs": 231_606
774 }
775 }));
776 assert!(events.is_empty());
777 }
778
779 #[test]
780 fn compact_boundary_unrecognized_trigger_returns_empty() {
781 let mut t = ClaudeTranslator::new();
782 let events = t.translate(compact_boundary_frame("something_new"));
783 assert!(events.is_empty());
784 }
785
786 #[test]
787 fn malformed_or_missing_type_returns_empty() {
788 let mut t = ClaudeTranslator::new();
789 assert!(t.translate(json!({})).is_empty());
790 assert!(t.translate(json!(null)).is_empty());
791 assert!(t.translate(json!("not an object")).is_empty());
792 assert!(t.translate(json!(42)).is_empty());
793 }
794
795 #[test]
796 fn skips_partial_assistant_snapshots() {
797 let mut t = ClaudeTranslator::new();
802 t.translate(json!({
804 "type": "assistant",
805 "partial": true,
806 "message": { "content": [{ "type": "text", "text": "h" }] }
807 }));
808 t.translate(json!({
809 "type": "assistant",
810 "partial": true,
811 "message": { "content": [{ "type": "text", "text": "he" }] }
812 }));
813 t.translate(json!({
814 "type": "assistant",
815 "partial": true,
816 "message": { "content": [{ "type": "text", "text": "hello" }] }
817 }));
818 t.translate(json!({
820 "type": "assistant",
821 "message": { "content": [{ "type": "text", "text": "hello" }] }
822 }));
823 let done = t.translate(json!({ "type": "result", "cost_usd": 0.0 }));
824 match &done[1] {
825 AgentEvent::Done { transcript, .. } => {
826 assert_eq!(
827 transcript.len(),
828 1,
829 "only the consolidated turn should land; got {transcript:?}"
830 );
831 }
832 other => panic!("expected Done, got {other:?}"),
833 }
834 }
835
836 #[test]
837 fn tool_result_recorded_in_transcript() {
838 let mut t = ClaudeTranslator::new();
842 t.translate(json!({
844 "type": "assistant",
845 "message": {
846 "content": [{
847 "type": "tool_use",
848 "id": "t1",
849 "name": "Bash",
850 "input": { "command": "ls" }
851 }]
852 }
853 }));
854 t.translate(json!({
856 "type": "user",
857 "message": {
858 "content": [{
859 "type": "tool_result",
860 "tool_use_id": "t1",
861 "content": "output",
862 "is_error": false
863 }]
864 }
865 }));
866 t.translate(json!({
868 "type": "assistant",
869 "message": {
870 "content": [{ "type": "text", "text": "done" }]
871 }
872 }));
873 let done = t.translate(json!({ "type": "result", "cost_usd": 0.0 }));
874 match &done[1] {
875 AgentEvent::Done { transcript, .. } => {
876 assert_eq!(transcript.len(), 3, "got {transcript:?}");
877 assert_eq!(transcript[0].role, "assistant");
878 assert_eq!(transcript[1].role, "tool_result");
879 assert_eq!(transcript[2].role, "assistant");
880 let tr = &transcript[1].content;
883 assert_eq!(tr["tool_use_id"], json!("t1"));
884 assert_eq!(tr["content"], json!("output"));
885 assert_eq!(tr["is_error"], json!(false));
886 }
887 other => panic!("expected Done, got {other:?}"),
888 }
889 }
890
891 #[test]
894 fn result_is_error_emits_error_not_done() {
895 let mut t = ClaudeTranslator::new();
896 t.translate(text_delta("partial output before the failure"));
897 let events = t.translate(json!({
898 "type": "result",
899 "cost_usd": 0.002,
900 "is_error": true,
901 "api_error_status": 429,
902 }));
903 assert_eq!(events.len(), 2, "expected Cost + Error, got {events:?}");
904 assert!(matches!(events[0], AgentEvent::Cost { .. }));
905 match &events[1] {
906 AgentEvent::Error { message } => assert_eq!(message, "API error 429"),
907 other => panic!("expected Error, got {other:?}"),
908 }
909 }
910
911 #[test]
912 fn result_is_error_prefers_explicit_result_text_over_status_code() {
913 let mut t = ClaudeTranslator::new();
914 let events = t.translate(json!({
915 "type": "result",
916 "cost_usd": 0.0,
917 "is_error": true,
918 "result": "network error: connection reset",
919 }));
920 match &events[1] {
921 AgentEvent::Error { message } => {
922 assert_eq!(message, "network error: connection reset")
923 }
924 other => panic!("expected Error, got {other:?}"),
925 }
926 }
927
928 #[test]
929 fn result_is_error_with_no_status_or_text_gets_generic_message() {
930 let mut t = ClaudeTranslator::new();
931 let events = t.translate(json!({
932 "type": "result",
933 "cost_usd": 0.0,
934 "is_error": true,
935 }));
936 match &events[1] {
937 AgentEvent::Error { message } => {
938 assert_eq!(message, "Agent encountered an error")
939 }
940 other => panic!("expected Error, got {other:?}"),
941 }
942 }
943
944 #[test]
945 fn result_is_error_with_only_an_errors_list_shows_its_first_entry() {
946 let mut t = ClaudeTranslator::new();
947 let events = t.translate(json!({
948 "type": "result",
949 "is_error": true,
950 "subtype": "error_during_execution",
951 "errors": ["No conversation found with session ID: s1"],
952 }));
953 match &events[1] {
954 AgentEvent::Error { message } => assert_eq!(message, "No conversation found with session ID: s1"),
955 other => panic!("expected Error, got {other:?}"),
956 }
957 }
958
959 #[test]
960 fn result_without_is_error_still_emits_done_as_before() {
961 let mut t = ClaudeTranslator::new();
962 let events = t.translate(json!({ "type": "result", "cost_usd": 0.0, "result": "ok" }));
963 match &events[1] {
964 AgentEvent::Done { response, .. } => assert_eq!(response, "ok"),
965 other => panic!("expected Done, got {other:?}"),
966 }
967 }
968
969 #[test]
970 fn message_start_with_user_role_extracts_tool_result() {
971 let mut t = ClaudeTranslator::new();
972 let events = t.translate(json!({
973 "type": "stream_event",
974 "event": {
975 "type": "message_start",
976 "message": {
977 "role": "user",
978 "content": [{
979 "type": "tool_result",
980 "tool_use_id": "t9",
981 "content": "output",
982 "is_error": false
983 }]
984 }
985 }
986 }));
987 assert_eq!(events.len(), 1);
988 match &events[0] {
989 AgentEvent::ToolResult {
990 tool_use_id,
991 output,
992 is_error,
993 } => {
994 assert_eq!(tool_use_id, "t9");
995 assert_eq!(output, &json!("output"));
996 assert!(!is_error);
997 }
998 other => panic!("expected ToolResult, got {other:?}"),
999 }
1000 let done = t.translate(json!({ "type": "result", "cost_usd": 0.0 }));
1002 match &done[1] {
1003 AgentEvent::Done { transcript, .. } => {
1004 assert_eq!(transcript.len(), 1);
1005 assert_eq!(transcript[0].role, "tool_result");
1006 }
1007 other => panic!("expected Done, got {other:?}"),
1008 }
1009 }
1010
1011 #[test]
1012 fn message_start_with_assistant_role_is_ignored() {
1013 let mut t = ClaudeTranslator::new();
1014 let events = t.translate(json!({
1015 "type": "stream_event",
1016 "event": {
1017 "type": "message_start",
1018 "message": { "role": "assistant", "content": [] }
1019 }
1020 }));
1021 assert!(events.is_empty());
1022 }
1023}