-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessages.rs
More file actions
2620 lines (2440 loc) · 111 KB
/
Copy pathmessages.rs
File metadata and controls
2620 lines (2440 loc) · 111 KB
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
//! SSE parser for the Anthropic `/messages` wire protocol.
//!
//! Maps Anthropic SSE events into [`ResponseEvent`] so the rest of codex-rs
//! is wire-protocol agnostic.
use crate::common::ResponseEvent;
use crate::error::ApiError;
use codex_client::ByteStream;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::models::WebSearchAction;
use crate::sse::usage::RawUsage;
use crate::sse::usage::normalize_token_usage;
use eventsource_stream::Eventsource;
use futures::StreamExt;
use serde::Deserialize;
use std::collections::HashMap;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::time::timeout;
use tracing::debug;
use tracing::trace;
use tracing::warn;
use crate::common::ResponseStream;
use crate::sse::messages_wire_types::AnthropicErrorKind;
use crate::sse::messages_wire_types::ContentBlock;
use crate::sse::messages_wire_types::ContentBlockDelta;
use crate::sse::messages_wire_types::MessageStreamEvent;
/// Parse a flat wire tool name back into a structured
/// `(namespace, bare_name)` pair so the tool-router HashMap lookup
/// (which keys on the structured `ToolName` shape used at
/// registration time) succeeds.
///
/// For inputs that start with `mcp__<server>__<tool>` (the canonical
/// XLI flat wire form for namespaced MCP tools on `/messages`),
/// returns `(Some("mcp__<server>"), "<tool>")`. For built-in tool
/// names and any input without the `mcp__<server>__<tool>` shape,
/// returns `(None, name)` so the call still dispatches as a plain
/// function tool.
///
/// Inlined here (not imported from `codex-mcp`) because
/// `codex-mcp` depends on `codex-api`; the reverse dependency is
/// not available. Keep this in sync with
/// `codex_mcp::parse_flat_mcp_tool_name`.
pub(crate) fn parse_flat_mcp_tool_name_pub(name: &str) -> (Option<String>, String) {
parse_flat_mcp_tool_name(name)
}
fn parse_flat_mcp_tool_name(name: &str) -> (Option<String>, String) {
const MCP_PREFIX: &str = "mcp__";
const DELIM: &str = "__";
let Some(rest) = name.strip_prefix(MCP_PREFIX) else {
return (None, name.to_string());
};
let Some(idx) = rest.find(DELIM) else {
return (None, name.to_string());
};
let (server, after) = rest.split_at(idx);
let tool = &after[DELIM.len()..];
if server.is_empty() || tool.is_empty() {
return (None, name.to_string());
}
(Some(format!("{MCP_PREFIX}{server}")), tool.to_string())
}
/// Curated catalogue of Anthropic `/messages` wire-vocabulary strings
/// XLI knows about. **This is rung-2 of the harness-invariant ladder
/// (see `cli-ops/sortie-board/xli-v3/`)** — a stringly-typed table
/// preserved as documentation alongside the rung-3 typed enums in
/// [`crate::sse::messages_wire_types`].
///
/// Every entry is either:
/// - **handled**: the parser has a dedicated arm for it.
/// - **drop**: explicit silent drop (we know what it is, we don't
/// surface it; document the policy here so it's not invisible).
///
/// With rung-3 typed enums in place, unknown upstream types now route
/// to a typed `Unknown { tag, raw }` variant rather than a silent
/// fall-through, and exhaustive matching on the enum is the compile-time
/// guard that a new variant doesn't get forgotten.
///
/// Source-of-truth for the wire vocabulary:
/// https://docs.anthropic.com/en/api/messages-streaming
pub(crate) mod wire_vocab {
/// Top-level SSE event types we receive on /messages stream.
#[allow(dead_code)] // consumed by wire_vocab_consistent_with_parser regression test
pub(crate) const STREAM_EVENTS: &[(&str, WirePolicy)] = &[
("message_start", WirePolicy::Handled),
("content_block_start", WirePolicy::Handled),
("content_block_delta", WirePolicy::Handled),
("content_block_stop", WirePolicy::Handled),
("message_delta", WirePolicy::Handled),
("message_stop", WirePolicy::Handled),
(
"ping",
WirePolicy::DropExplicit("keepalive; no payload to surface"),
),
("error", WirePolicy::Handled),
];
/// `content_block.type` discriminator. Set by `content_block_start`.
#[allow(dead_code)] // consumed by wire_vocab_consistent_with_parser regression test
pub(crate) const CONTENT_BLOCKS: &[(&str, WirePolicy)] = &[
("text", WirePolicy::Handled),
("tool_use", WirePolicy::Handled),
("thinking", WirePolicy::Handled),
("redacted_thinking", WirePolicy::Handled),
(
"server_tool_use",
WirePolicy::DropExplicit("server-side beta tool; not currently surfaced to XLI"),
),
(
"web_search_tool_result",
WirePolicy::DropExplicit("server-side beta tool; not currently surfaced to XLI"),
),
(
"code_execution_tool_use",
WirePolicy::DropExplicit("server-side beta tool; not currently surfaced to XLI"),
),
];
/// `delta.type` discriminator on `content_block_delta` events.
#[allow(dead_code)] // consumed by wire_vocab_consistent_with_parser regression test
pub(crate) const CONTENT_BLOCK_DELTAS: &[(&str, WirePolicy)] = &[
("text_delta", WirePolicy::Handled),
("input_json_delta", WirePolicy::Handled),
("thinking_delta", WirePolicy::Handled),
("signature_delta", WirePolicy::Handled),
(
"citations_delta",
WirePolicy::DropExplicit("citations not surfaced in XLI yet; tracked separately"),
),
];
#[allow(dead_code)] // consumed by wire_vocab_* regression tests
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WirePolicy {
/// Parser has a dedicated arm; payload is surfaced as a `ResponseEvent`.
Handled,
/// Wire type is recognized but intentionally not surfaced. The
/// `&'static str` is human-readable rationale that shows up in
/// the regression test if anyone tries to remove it.
DropExplicit(&'static str),
}
}
/// Tracks in-flight content blocks by index.
struct BlockTracker {
blocks: HashMap<u64, BlockState>,
}
enum BlockState {
Text {
text: String,
},
Thinking {
thinking: String,
signature: String,
},
ToolUse {
call_id: String,
name: String,
arguments: String,
},
ServerToolUse {
id: String,
name: String,
arguments: String,
},
WebSearchToolResult {
tool_use_id: String,
},
RedactedThinking {
data: String,
},
}
impl BlockTracker {
fn new() -> Self {
Self {
blocks: HashMap::new(),
}
}
}
/// Spawns a task that reads SSE events from a `/messages` byte stream and maps
/// them into `ResponseEvent`s on the returned channel.
pub fn spawn_messages_stream(stream: ByteStream, idle_timeout: Duration) -> ResponseStream {
let (tx_event, rx_event) = mpsc::channel::<Result<ResponseEvent, ApiError>>(1600);
tokio::spawn(process_messages_sse(stream, tx_event, idle_timeout));
ResponseStream {
rx_event,
upstream_request_id: None,
}
}
async fn process_messages_sse(
stream: ByteStream,
tx_event: mpsc::Sender<Result<ResponseEvent, ApiError>>,
idle_timeout: Duration,
) {
let mut sse_stream = stream.eventsource();
let mut tracker = BlockTracker::new();
let mut response_id = String::new();
let mut usage_holder: Option<AnthropicUsage> = None;
let mut stop_reason: Option<String> = None;
let mut tool_use_truncated = false;
loop {
let response = timeout(idle_timeout, sse_stream.next()).await;
let sse = match response {
Ok(Some(Ok(sse))) => sse,
Ok(Some(Err(e))) => {
debug!("Messages SSE error: {e:#}");
let _ = tx_event.send(Err(ApiError::Stream(e.to_string()))).await;
return;
}
Ok(None) => {
let _ = tx_event
.send(Err(ApiError::Stream(
"messages stream closed before message_stop".into(),
)))
.await;
return;
}
Err(_) => {
let _ = tx_event
.send(Err(ApiError::Stream(
"idle timeout waiting for messages SSE".into(),
)))
.await;
return;
}
};
if sse.data.is_empty() {
continue;
}
trace!("Messages SSE event: {}", &sse.data);
let event: MessageStreamEvent = match serde_json::from_str(&sse.data) {
Ok(event) => event,
Err(e) => {
debug!(
"Failed to parse messages SSE event: {e}, data: {}",
&sse.data
);
continue;
}
};
// Rung-3 (S-WIRE-VOCAB-MAX-TEETH): exhaustive match on the typed
// `MessageStreamEvent` enum. The compiler enforces that every variant
// is handled; `MessageStreamEvent::Unknown` is the ONLY tolerant arm
// and it carries the original tag + raw JSON for logging.
match event {
MessageStreamEvent::MessageStart { message } => {
if let Some(id) = message.id.as_deref() {
response_id = id.to_owned();
}
if let Some(u) = message.usage.as_ref()
&& let Ok(u) = serde_json::from_value::<AnthropicUsage>(u.clone())
{
usage_holder = Some(u);
}
if let Some(model) = message.model.as_deref()
&& tx_event
.send(Ok(ResponseEvent::ServerModel(model.to_owned())))
.await
.is_err()
{
return;
}
if tx_event.send(Ok(ResponseEvent::Created)).await.is_err() {
return;
}
}
MessageStreamEvent::ContentBlockStart {
index,
content_block,
} => {
// Exhaustive match on the typed ContentBlock enum.
// Drop arms log via tracing; the Unknown arm captures
// the original tag + raw JSON for visibility.
match content_block {
ContentBlock::Text { .. } => {
tracker.blocks.insert(
index,
BlockState::Text {
text: String::new(),
},
);
let item = ResponseItem::Message {
id: None,
role: "assistant".to_owned(),
content: vec![],
phase: None,
};
if tx_event
.send(Ok(ResponseEvent::OutputItemAdded(item)))
.await
.is_err()
{
return;
}
}
ContentBlock::Thinking { .. } => {
tracker.blocks.insert(
index,
BlockState::Thinking {
thinking: String::new(),
signature: String::new(),
},
);
let item = ResponseItem::Reasoning {
id: None,
summary: Vec::new(),
content: None,
encrypted_content: None,
internal_chat_message_metadata_passthrough: None,
raw_wire_block: None,
};
if tx_event
.send(Ok(ResponseEvent::OutputItemAdded(item)))
.await
.is_err()
{
return;
}
}
ContentBlock::ToolUse { id, name, .. } => {
tracker.blocks.insert(
index,
BlockState::ToolUse {
call_id: id.clone(),
name: name.clone(),
arguments: String::new(),
},
);
let (namespace, bare_name) = parse_flat_mcp_tool_name(&name);
let item = ResponseItem::FunctionCall {
id: None,
name: bare_name,
namespace,
arguments: String::new(),
call_id: id.clone(),
};
if tx_event
.send(Ok(ResponseEvent::OutputItemAdded(item)))
.await
.is_err()
{
return;
}
}
ContentBlock::RedactedThinking { data } => {
tracker
.blocks
.insert(index, BlockState::RedactedThinking { data });
}
ContentBlock::ServerToolUse { id, name, input } => {
if name == "web_search" {
let arguments = if input.is_object() && input.as_object().is_some_and(|o| o.is_empty()) {
String::new()
} else {
serde_json::to_string(&input).unwrap_or_default()
};
tracker.blocks.insert(
index,
BlockState::ServerToolUse {
id: id.clone(),
name: name.clone(),
arguments,
},
);
let item = ResponseItem::WebSearchCall {
id: Some(id.clone()),
status: Some("in_progress".to_string()),
action: None,
};
if tx_event
.send(Ok(ResponseEvent::OutputItemAdded(item)))
.await
.is_err()
{
return;
}
} else {
trace!(
"intentional drop: server_tool_use name={name} (wire_vocab::CONTENT_BLOCKS)"
);
}
}
ContentBlock::WebSearchToolResult { tool_use_id, .. } => {
tracker.blocks.insert(
index,
BlockState::WebSearchToolResult {
tool_use_id: tool_use_id.clone(),
},
);
}
ContentBlock::CodeExecutionToolUse { .. } => {
// Documented intentional drop — policy lives in
// `wire_vocab::CONTENT_BLOCKS` (server-side beta).
trace!(
"intentional drop: code_execution_tool_use (wire_vocab::CONTENT_BLOCKS)"
);
}
ContentBlock::Unknown { tag, raw } => {
warn!(
block_type = %tag,
raw = ?raw,
"Anthropic content_block.type is NOT in known wire vocabulary \
— routed to ContentBlock::Unknown. Add a variant in \
messages_wire_types.rs and a parser arm here, or document a \
drop policy. See cli-ops/sortie-board/xli-v3/.",
);
}
}
}
MessageStreamEvent::ContentBlockDelta { index, delta } => {
// Exhaustive match on the typed ContentBlockDelta enum.
match delta {
ContentBlockDelta::TextDelta { text } => {
if let Some(BlockState::Text { text: acc, .. }) =
tracker.blocks.get_mut(&index)
{
acc.push_str(&text);
if tx_event
.send(Ok(ResponseEvent::OutputTextDelta(text)))
.await
.is_err()
{
return;
}
} else {
trace!("text_delta for untracked block index {index}, ignoring");
}
}
ContentBlockDelta::ThinkingDelta { thinking } => {
if let Some(BlockState::Thinking { thinking: acc, .. }) =
tracker.blocks.get_mut(&index)
{
acc.push_str(&thinking);
if tx_event
.send(Ok(ResponseEvent::ReasoningContentDelta {
delta: thinking,
content_index: index as i64,
}))
.await
.is_err()
{
return;
}
} else {
trace!("thinking_delta for untracked block index {index}, ignoring");
}
}
ContentBlockDelta::SignatureDelta { signature } => {
if let Some(BlockState::Thinking { signature: acc, .. }) =
tracker.blocks.get_mut(&index)
{
acc.push_str(&signature);
}
}
ContentBlockDelta::InputJsonDelta { partial_json } => {
if let Some(BlockState::ToolUse { call_id, arguments: acc, .. }) =
tracker.blocks.get_mut(&index)
{
acc.push_str(&partial_json);
if tx_event
.send(Ok(ResponseEvent::ToolCallInputDelta {
item_id: call_id.clone(),
call_id: Some(call_id.clone()),
delta: partial_json,
}))
.await
.is_err()
{
return;
}
} else if let Some(BlockState::ServerToolUse { arguments: acc, .. }) =
tracker.blocks.get_mut(&index)
{
acc.push_str(&partial_json);
}
}
ContentBlockDelta::CitationsDelta { .. } => {
// Documented intentional drop — policy lives in
// `wire_vocab::CONTENT_BLOCK_DELTAS`.
trace!(
"intentional drop: citations_delta (wire_vocab::CONTENT_BLOCK_DELTAS)"
);
}
ContentBlockDelta::Unknown { tag, raw } => {
warn!(
delta_type = %tag,
raw = ?raw,
"Anthropic delta.type is NOT in known wire vocabulary \
— routed to ContentBlockDelta::Unknown. Add a variant in \
messages_wire_types.rs and a parser arm here, or document a \
drop policy. See cli-ops/sortie-board/xli-v3/.",
);
}
}
}
MessageStreamEvent::ContentBlockStop { index } => {
match tracker.blocks.remove(&index) {
Some(BlockState::ServerToolUse {
id,
name,
arguments,
}) if name == "web_search" => {
let item = ResponseItem::WebSearchCall {
id: Some(id),
status: Some("completed".to_string()),
action: web_search_action_from_arguments(&arguments),
};
if tx_event
.send(Ok(ResponseEvent::OutputItemDone(item)))
.await
.is_err()
{
return;
}
}
Some(BlockState::ServerToolUse { name, .. }) => {
trace!(
"intentional drop on stop: server_tool_use name={name} (wire_vocab::CONTENT_BLOCKS)"
);
}
Some(BlockState::WebSearchToolResult { .. }) => {
// Result block follows server_tool_use; IR emitted on server_tool_use stop.
}
Some(BlockState::ToolUse {
call_id,
name,
arguments,
}) => {
// S-004: Detect truncated tool call arguments.
// If the provider silently truncated output, the JSON
// will be incomplete. Flag it so message_stop can
// override stop_reason to "max_tokens" for retry.
if !arguments.is_empty()
&& serde_json::from_str::<serde_json::Value>(&arguments).is_err()
{
warn!(
call_id = %call_id,
name = %name,
args_len = arguments.len(),
"truncated tool_use arguments detected (invalid JSON)"
);
tool_use_truncated = true;
}
let (namespace, bare_name) = parse_flat_mcp_tool_name(&name);
let item = ResponseItem::FunctionCall {
id: None,
name: bare_name,
namespace,
arguments,
call_id,
};
if tx_event
.send(Ok(ResponseEvent::OutputItemDone(item)))
.await
.is_err()
{
return;
}
}
Some(BlockState::Text { text }) => {
let item = ResponseItem::Message {
id: None,
role: "assistant".to_owned(),
content: vec![ContentItem::OutputText { text }],
phase: None,
};
if tx_event
.send(Ok(ResponseEvent::OutputItemDone(item)))
.await
.is_err()
{
return;
}
}
Some(BlockState::Thinking {
thinking,
signature,
}) => {
// Build the raw wire block for byte-identical replay.
// This is the exact JSON block Anthropic expects when
// the conversation history is sent back.
// S-OPUS47-EMPTY-THINKING: drop signed-but-empty
// thinking blocks. Opus 4.7 adaptive thinking
// (display=summarized/omitted), notably on the
// Vertex route, streams a signature_delta but
// withholds every thinking_delta. Persisting a
// raw_wire_block of shape
// { type: "thinking", thinking: "", signature: <real> }
// and replaying it on the next turn fails Anthropic's
// verifier with `messages.N.content.M: thinking
// blocks in the latest assistant message cannot be
// modified` because the signature was computed over
// content the proxy never returned. Anthropic
// regenerates the thought on the next turn, so
// replay is not required for correctness.
if thinking.is_empty() {
if !signature.is_empty() {
tracing::debug!(
"dropping empty-text signed thinking block (opus-4.7 adaptive/summarized; signature would fail verifier on replay)"
);
}
continue;
}
let raw_block = if signature.is_empty() {
serde_json::json!({
"type": "thinking",
"thinking": &thinking,
})
} else {
serde_json::json!({
"type": "thinking",
"thinking": &thinking,
"signature": &signature,
})
};
let item = ResponseItem::Reasoning {
id: None,
summary: vec![
codex_protocol::models::ReasoningItemReasoningSummary::SummaryText {
text: thinking,
},
],
content: None,
encrypted_content: if signature.is_empty() {
None
} else {
Some(signature)
},
internal_chat_message_metadata_passthrough: None,
raw_wire_block: Some(raw_block),
};
if tx_event
.send(Ok(ResponseEvent::OutputItemDone(item)))
.await
.is_err()
{
return;
}
}
Some(BlockState::RedactedThinking { data }) => {
// Build raw wire block for byte-identical replay.
let raw_block = serde_json::json!({
"type": "redacted_thinking",
"data": &data,
});
// Sentinel prefix "\0REDACTED\0" distinguishes redacted thinking
// from real Anthropic signatures (which are base64 and cannot
// contain null bytes). Consumed by messages_wire.rs translator.
let item = ResponseItem::Reasoning {
id: None,
summary: Vec::new(),
content: None,
encrypted_content: Some(format!("\0REDACTED\0{data}")),
internal_chat_message_metadata_passthrough: None,
raw_wire_block: Some(raw_block),
};
if tx_event
.send(Ok(ResponseEvent::OutputItemDone(item)))
.await
.is_err()
{
return;
}
}
None => {}
}
}
MessageStreamEvent::MessageDelta { delta, usage } => {
if let Some(reason) = delta.stop_reason.as_ref() {
let reason_str = reason.as_wire_str();
trace!("stop_reason: {reason_str}");
stop_reason = Some(reason_str.to_owned());
}
if let Some(usage_val) = usage
&& let Ok(u) = serde_json::from_value::<AnthropicUsage>(usage_val)
{
usage_holder = Some(merge_usage(usage_holder, u));
}
}
MessageStreamEvent::MessageStop => {
// S-004: Check for any tool_use blocks still in the tracker
// (blocks that never received content_block_stop — hard truncation).
for state in tracker.blocks.values() {
if let BlockState::ToolUse {
call_id,
name,
arguments,
} = state
&& !arguments.is_empty()
&& serde_json::from_str::<serde_json::Value>(arguments).is_err()
{
warn!(
call_id = %call_id,
name = %name,
args_len = arguments.len(),
"in-flight tool_use block has truncated arguments at message_stop"
);
tool_use_truncated = true;
}
}
// S-004: If any tool_use block had invalid JSON arguments,
// override stop_reason to "max_tokens" so the harness retries.
if tool_use_truncated {
warn!(
"overriding stop_reason to max_tokens due to truncated tool_use arguments"
);
stop_reason = Some("max_tokens".to_owned());
}
let token_usage = usage_holder.map(|u| normalize_token_usage(u.to_raw_usage()));
let end_turn = if stop_reason.as_deref() == Some("end_turn") {
Some(true)
} else {
None
};
let _ = tx_event
.send(Ok(ResponseEvent::Completed {
end_turn,
stop_reason: stop_reason.take(),
response_id: response_id.clone(),
token_usage,
}))
.await;
return;
}
MessageStreamEvent::Ping => {}
MessageStreamEvent::Error { error } => {
let message = error
.message
.as_deref()
.unwrap_or("unknown anthropic error");
let error_type = error.error_type.as_deref().unwrap_or("");
// S-ERROR-TYPED: classify into a typed kind (rung-3 pattern) so
// the mapping is exhaustive and unknown error types are visible
// (warn!) rather than silently collapsing to a generic error.
let api_error = match AnthropicErrorKind::from_wire(error_type) {
AnthropicErrorKind::Overloaded => ApiError::ServerOverloaded,
AnthropicErrorKind::RateLimit => ApiError::RateLimit(message.to_owned()),
AnthropicErrorKind::Unknown(raw) => {
warn!(
error_type = %raw,
"unmodeled Anthropic error.type; mapping to generic stream error"
);
ApiError::Stream(format!("Anthropic API error: {message}"))
}
};
let _ = tx_event.send(Err(api_error)).await;
return;
}
MessageStreamEvent::Unknown { tag, raw } => {
// The custom Deserialize already logged a warn! with the tag.
// Re-log here with raw payload so the parser-side context shows
// up in a single grep alongside the Deserialize-side warn.
warn!(
wire_type = %tag,
raw = ?raw,
"unhandled Anthropic SSE event in parser; dropping",
);
}
}
}
}
#[derive(Debug, Deserialize, Default, Clone)]
struct AnthropicOutputTokensDetails {
thinking_tokens: Option<i64>,
}
/// TTL-band cache write breakdown (`Usage.cache_creation` on the wire).
#[derive(Debug, Deserialize, Default, Clone)]
struct AnthropicCacheCreation {
ephemeral_5m_input_tokens: Option<i64>,
ephemeral_1h_input_tokens: Option<i64>,
}
/// Server-side tool request counters on the usage object (deserialize-only for
/// now — projection to protocol `TokenUsage` is S-SERVER-TOOL-USAGE).
#[derive(Debug, Deserialize, Default, Clone)]
struct AnthropicServerToolUsage {
web_search_requests: Option<i64>,
web_fetch_requests: Option<i64>,
}
#[derive(Debug, Deserialize, Default, Clone)]
struct AnthropicUsage {
input_tokens: Option<i64>,
output_tokens: Option<i64>,
cache_read_input_tokens: Option<i64>,
cache_creation_input_tokens: Option<i64>,
#[serde(default)]
cache_creation: Option<AnthropicCacheCreation>,
#[serde(default)]
output_tokens_details: Option<AnthropicOutputTokensDetails>,
#[serde(default)]
server_tool_use: Option<AnthropicServerToolUsage>,
}
impl AnthropicUsage {
fn cache_creation_tokens(&self) -> i64 {
if let Some(n) = self.cache_creation_input_tokens {
return n.max(0);
}
self.cache_creation
.as_ref()
.map(|c| {
c.ephemeral_5m_input_tokens.unwrap_or(0).max(0)
+ c.ephemeral_1h_input_tokens.unwrap_or(0).max(0)
})
.unwrap_or(0)
}
fn reasoning_output_tokens(&self) -> i64 {
self.output_tokens_details
.as_ref()
.and_then(|d| d.thinking_tokens)
.unwrap_or(0)
.max(0)
}
fn to_raw_usage(&self) -> RawUsage {
let server = self.server_tool_use.as_ref();
RawUsage {
web_search_requests: server
.and_then(|s| s.web_search_requests)
.unwrap_or(0)
.max(0),
web_fetch_requests: server
.and_then(|s| s.web_fetch_requests)
.unwrap_or(0)
.max(0),
..RawUsage::cache_exclusive_prompt(
self.input_tokens.unwrap_or(0),
self.cache_read_input_tokens.unwrap_or(0),
self.cache_creation_tokens(),
self.output_tokens.unwrap_or(0),
self.reasoning_output_tokens(),
)
}
}
}
fn web_search_action_from_arguments(arguments: &str) -> Option<WebSearchAction> {
let value: serde_json::Value = serde_json::from_str(arguments).ok()?;
let query = value
.get("query")
.and_then(|q| q.as_str())
.map(str::to_owned);
if query.is_none() {
return None;
}
Some(WebSearchAction::Search {
query,
queries: None,
})
}
fn merge_usage(existing: Option<AnthropicUsage>, new: AnthropicUsage) -> AnthropicUsage {
match existing {
None => new,
Some(prev) => AnthropicUsage {
input_tokens: new.input_tokens.or(prev.input_tokens),
output_tokens: new.output_tokens.or(prev.output_tokens),
cache_read_input_tokens: new.cache_read_input_tokens.or(prev.cache_read_input_tokens),
cache_creation_input_tokens: new
.cache_creation_input_tokens
.or(prev.cache_creation_input_tokens),
cache_creation: merge_cache_creation(prev.cache_creation, new.cache_creation),
output_tokens_details: merge_output_tokens_details(
prev.output_tokens_details,
new.output_tokens_details,
),
server_tool_use: merge_server_tool_use(prev.server_tool_use, new.server_tool_use),
},
}
}
fn merge_cache_creation(
prev: Option<AnthropicCacheCreation>,
new: Option<AnthropicCacheCreation>,
) -> Option<AnthropicCacheCreation> {
match (prev, new) {
(None, n) => n,
(Some(p), None) => Some(p),
(Some(p), Some(n)) => Some(AnthropicCacheCreation {
ephemeral_5m_input_tokens: n
.ephemeral_5m_input_tokens
.or(p.ephemeral_5m_input_tokens),
ephemeral_1h_input_tokens: n
.ephemeral_1h_input_tokens
.or(p.ephemeral_1h_input_tokens),
}),
}
}
fn merge_output_tokens_details(
prev: Option<AnthropicOutputTokensDetails>,
new: Option<AnthropicOutputTokensDetails>,
) -> Option<AnthropicOutputTokensDetails> {
match (prev, new) {
(None, n) => n,
(Some(p), None) => Some(p),
(Some(p), Some(n)) => Some(AnthropicOutputTokensDetails {
thinking_tokens: n.thinking_tokens.or(p.thinking_tokens),
}),
}
}
fn merge_server_tool_use(
prev: Option<AnthropicServerToolUsage>,
new: Option<AnthropicServerToolUsage>,
) -> Option<AnthropicServerToolUsage> {
match (prev, new) {
(None, n) => n,
(Some(p), None) => Some(p),
(Some(p), Some(n)) => Some(AnthropicServerToolUsage {
web_search_requests: n.web_search_requests.or(p.web_search_requests),
web_fetch_requests: n.web_fetch_requests.or(p.web_fetch_requests),
}),
}
}
#[cfg(test)]
mod anthropic_usage_wire_tests {
use super::*;
#[test]
fn deserializes_cache_creation_ttl_breakdown() {
let v = serde_json::json!({
"input_tokens": 80,
"output_tokens": 0,
"cache_read_input_tokens": 10,
"cache_creation": {
"ephemeral_5m_input_tokens": 15,
"ephemeral_1h_input_tokens": 5
}
});
let u: AnthropicUsage = serde_json::from_value(v).expect("usage json");
let raw = u.to_raw_usage();
assert_eq!(raw.cache_read, 10);
assert_eq!(raw.cache_creation, 20);
assert_eq!(raw.api_input, 80);
}
#[test]
fn message_start_event_preserves_usage_with_cache_creation_ttl() {
use crate::sse::messages_wire_types::MessageStreamEvent;
let line = serde_json::json!({
"type": "message_start",
"message": {
"id": "msg_ttl",
"type": "message",
"role": "assistant",
"content": [],
"model": "claude-sonnet-4.6",
"usage": {
"input_tokens": 80,
"output_tokens": 0,
"cache_read_input_tokens": 10,
"cache_creation": {
"ephemeral_5m_input_tokens": 15,
"ephemeral_1h_input_tokens": 5
}
}
}
});
let event: MessageStreamEvent =
serde_json::from_value(line).expect("message_start event");
let MessageStreamEvent::MessageStart { message } = event else {
panic!("expected message_start");
};
let usage_val = message.usage.expect("usage value");
let u: AnthropicUsage =
serde_json::from_value(usage_val).expect("anthropic usage");