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
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
//! Mirrors `packages/ai/src/api/anthropic-messages.ts` — the SSE →
//! `AssistantMessageEvent` mapper (`content_block_*` → text/thinking/toolcall
//! start/delta/end, `message_start`/`message_delta` → usage + stop_reason) and
//! `mapStopReason`.
//!
//! The TS `stream` function keeps a single mutable `output: AssistantMessage`
//! plus a `blocks[]` array carrying per-block scratch state (the streaming
//! `partialJson` buffer for tool calls). The Rust port models that as
//! [`MapperState`]: an `AssistantMessage` grown per event, plus a parallel
//! `Vec<BlockScratch>` tracking each content block's Anthropic `index` and, for
//! tool calls, the `partial_json` accumulation.
//!
//! Tool-call arg parsing invariant (plan §5.15): re-parse partial JSON on every
//! `input_json_delta` and do the final authoritative parse on
//! `content_block_stop`. The streaming arm uses [`parse_streaming_json`] so a
//! truncated delta never produces unparseable args — `ToolCallEnd` always
//! carries a real object.
use crate::error::AiError;
use crate::event_stream::AssistantMessageEventStreamProducer;
use crate::providers::anthropic::json_parse::parse_streaming_json;
use crate::providers::anthropic::sse::{AnthropicEvent, SseEventStream};
use crate::types::{
AssistantMessage, AssistantMessageEvent, Content, DoneReason, ErrorReason, StopReason,
TextContent, TextContentType, ThinkingContent, ThinkingContentType, ToolCall, ToolCallType,
Usage, UsageCost,
};
use std::sync::Arc;
/// Per-content-block scratch state, mirroring the TS `Block` shape with its
/// `index` + `partialJson` fields.
#[derive(Debug, Clone)]
struct BlockScratch {
/// The Anthropic `content_block.index` this scratch tracks. The mapper
/// grows `output.content` in arrival order but blocks may arrive with
/// non-sequential indices (e.g. interleaved thinking+text on Opus 4.7); we
/// look up scratch by `index`, not by `content` position.
anthropic_index: i64,
/// The position in `output.content` where this block lives. Set on
/// `content_block_start`, read on every delta/stop.
content_index: usize,
/// The block's kind, so deltas can match without re-inspecting the content.
kind: BlockKind,
/// For tool-call blocks: the running `partial_json` buffer, appended on
/// each `input_json_delta`. Empty for text/thinking.
partial_json: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BlockKind {
Text,
Thinking { redacted: bool },
ToolCall,
}
/// The mutable state the mapper advances per SSE event. Mirrors the TS `output`
/// + `blocks` pair.
pub struct MapperState {
pub output: AssistantMessage,
blocks: Vec<BlockScratch>,
/// Marker that the mapper has emitted `start` for the stream. The TS
/// `stream` pushes `start` right before the event loop; the Rust port
/// defers it to the first event so a pre-stream failure (auth/SSE) doesn't
/// deliver a partial `start` with no terminal event.
started: bool,
/// Whether the protocol's terminal `message_stop` event arrived. Some
/// proxy gateways end the stream at `message_stop` WITHOUT a preceding
/// `message_delta` (which carries `stop_reason`); [`finalize_mapper`] uses
/// this to default a still-`Pending` stop reason to a normal stop instead
/// of erroring (documented divergence — see `finalize_mapper`).
saw_message_end: bool,
}
impl MapperState {
/// Build a fresh state with an empty assistant message ready to grow.
/// `timestamp` is ms-since-epoch; callers pass it from the provider.
pub fn new(
api: crate::types::Api,
provider: impl Into<String>,
model: impl Into<String>,
timestamp: i64,
) -> Self {
Self {
output: AssistantMessage::empty(api, provider, model, timestamp),
blocks: Vec::new(),
started: false,
saw_message_end: false,
}
}
fn ensure_started(&mut self, prod: &mut AssistantMessageEventStreamProducer) {
if !self.started {
self.started = true;
prod.push(AssistantMessageEvent::Start {
partial: Arc::new(self.output.clone()),
});
}
}
fn find_block_by_anthropic_index(&self, anthropic_index: i64) -> Option<usize> {
self.blocks
.iter()
.position(|b| b.anthropic_index == anthropic_index)
}
/// Apply one decoded Anthropic event. Mirrors the per-`event.type` dispatch
/// in the TS `stream` async IIFE. Returns `Err(AiError)` only on
/// unrecoverable mapper state (an unexpected block kind for a delta); SSE
/// parse errors surface earlier, in the decoder. Never panics: a missing
/// block for an index is a no-op (the TS `findIndex` returns -1 and the
/// delta is skipped).
pub fn apply(
&mut self,
event: &AnthropicEvent,
prod: &mut AssistantMessageEventStreamProducer,
) -> Result<(), AiError> {
let AnthropicEvent::Message {
event_type,
payload,
} = event
else {
return Ok(()); // Skipped events are a mapper no-op.
};
// The TS loop only enters the match arms for event names it recognizes;
// `iterate_anthropic_events` already filtered to ANTHROPIC_MESSAGE_EVENTS,
// so we dispatch on the payload `type` (which equals the SSE event name).
match event_type.as_str() {
"message_start" => self.apply_message_start(payload, prod),
"content_block_start" => self.apply_content_block_start(payload, prod),
"content_block_delta" => self.apply_content_block_delta(payload, prod)?,
"content_block_stop" => self.apply_content_block_stop(payload, prod),
"message_delta" => self.apply_message_delta(payload, prod),
"message_stop" => self.saw_message_end = true,
_ => {}
}
Ok(())
}
fn apply_message_start(
&mut self,
payload: &serde_json::Value,
prod: &mut AssistantMessageEventStreamProducer,
) {
self.ensure_started(prod);
// `event.message.id` — response id.
if let Some(id) = payload
.pointer("/message/id")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
{
self.output.response_id = Some(id);
}
// Initial usage (input/cacheRead/cacheWrite; output may be 0 here and
// updated on the final message_delta). Preserves input_tokens from
// message_start when a proxy omits it in message_delta.
if let Some(usage) = payload.pointer("/message/usage") {
let input = usage
.get("input_tokens")
.and_then(|v| v.as_i64())
.unwrap_or(0);
let output = usage
.get("output_tokens")
.and_then(|v| v.as_i64())
.unwrap_or(0);
let cache_read = usage
.get("cache_read_input_tokens")
.and_then(|v| v.as_i64())
.unwrap_or(0);
let cache_write = usage
.get("cache_creation_input_tokens")
.and_then(|v| v.as_i64())
.unwrap_or(0);
// `cache_creation.ephemeral_1h_input_tokens` — the subset of
// cache_creation written with 1h retention (cost calculation
// charges these at 2× input).
let cache_write_1h = usage
.pointer("/cache_creation/ephemeral_1h_input_tokens")
.and_then(|v| v.as_i64())
.unwrap_or(0);
self.output.usage.input = input;
self.output.usage.output = output;
self.output.usage.cache_read = cache_read;
self.output.usage.cache_write = cache_write;
self.output.usage.cache_write_1h = if cache_write_1h > 0 {
Some(cache_write_1h)
} else {
None
};
// Anthropic doesn't report total_tokens; compute from components
// (mirrors the TS `input + output + cacheRead + cacheWrite` line).
self.output.usage.total_tokens = input + output + cache_read + cache_write;
// Cost is recomputed in the provider after the model is known; the
// mapper zeroes cost here so the provider's final pass owns it.
self.output.usage.cost = UsageCost::default();
}
}
fn apply_content_block_start(
&mut self,
payload: &serde_json::Value,
prod: &mut AssistantMessageEventStreamProducer,
) {
self.ensure_started(prod);
let anthropic_index = payload.get("index").and_then(|v| v.as_i64()).unwrap_or(0);
let Some(block) = payload.get("content_block") else {
return;
};
let kind = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
match kind {
"text" => {
let text = block
.get("text")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let content = Content::Text(TextContent {
kind: TextContentType,
text,
text_signature: None,
});
self.output.content.push(content);
let content_index = self.output.content.len() - 1;
self.blocks.push(BlockScratch {
anthropic_index,
content_index,
kind: BlockKind::Text,
partial_json: String::new(),
});
prod.push(AssistantMessageEvent::TextStart {
content_index,
partial: Arc::new(self.output.clone()),
});
}
"thinking" => {
let thinking = block
.get("thinking")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let signature = block
.get("signature")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let content = Content::Thinking(ThinkingContent {
kind: ThinkingContentType,
thinking,
thinking_signature: if signature.is_empty() {
None
} else {
Some(signature)
},
redacted: false,
});
self.output.content.push(content);
let content_index = self.output.content.len() - 1;
self.blocks.push(BlockScratch {
anthropic_index,
content_index,
kind: BlockKind::Thinking { redacted: false },
partial_json: String::new(),
});
prod.push(AssistantMessageEvent::ThinkingStart {
content_index,
partial: Arc::new(self.output.clone()),
});
}
"redacted_thinking" => {
let data = block
.get("data")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let content = Content::Thinking(ThinkingContent {
kind: ThinkingContentType,
// Mirrors the TS: a fixed marker, the opaque payload lives
// in `thinking_signature` so it round-trips back to
// `redacted_thinking` on the next turn.
thinking: "[Reasoning redacted]".to_string(),
thinking_signature: Some(data),
redacted: true,
});
self.output.content.push(content);
let content_index = self.output.content.len() - 1;
self.blocks.push(BlockScratch {
anthropic_index,
content_index,
kind: BlockKind::Thinking { redacted: true },
partial_json: String::new(),
});
prod.push(AssistantMessageEvent::ThinkingStart {
content_index,
partial: Arc::new(self.output.clone()),
});
}
"tool_use" => {
let id = block
.get("id")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let name = block
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
// `input` is usually `{}` on block_start (streaming fills it
// via deltas); keep whatever's present as the initial args.
let args = block
.get("input")
.cloned()
.unwrap_or(serde_json::Value::Object(serde_json::Map::new()));
let content = Content::tool_call(id, name, args);
self.output.content.push(content);
let content_index = self.output.content.len() - 1;
self.blocks.push(BlockScratch {
anthropic_index,
content_index,
kind: BlockKind::ToolCall,
partial_json: String::new(),
});
prod.push(AssistantMessageEvent::ToolCallStart {
content_index,
partial: Arc::new(self.output.clone()),
});
}
// image / unknown content blocks are not emitted by the Anthropic
// Messages streaming API on the assistant side — skip (mirrors TS).
_ => {}
}
}
fn apply_content_block_delta(
&mut self,
payload: &serde_json::Value,
prod: &mut AssistantMessageEventStreamProducer,
) -> Result<(), AiError> {
let anthropic_index = payload.get("index").and_then(|v| v.as_i64()).unwrap_or(0);
let Some(delta) = payload.get("delta") else {
return Ok(());
};
let delta_type = delta.get("type").and_then(|v| v.as_str()).unwrap_or("");
let Some(scratch_index) = self.find_block_by_anthropic_index(anthropic_index) else {
// Delta for an unknown index (block_start missed/truncated) — skip
// rather than panic, matching the TS `if (block && ...)` guards.
return Ok(());
};
let scratch = &mut self.blocks[scratch_index];
let content_index = scratch.content_index;
match (scratch.kind, delta_type) {
(BlockKind::Text, "text_delta") => {
let text = delta
.get("text")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if let Some(Content::Text(slot)) = self.output.content.get_mut(content_index) {
slot.text.push_str(&text);
}
prod.push(AssistantMessageEvent::TextDelta {
content_index,
delta: text,
partial: Arc::new(self.output.clone()),
});
}
(BlockKind::Thinking { redacted: false }, "thinking_delta") => {
let thinking = delta
.get("thinking")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if let Some(Content::Thinking(slot)) = self.output.content.get_mut(content_index) {
slot.thinking.push_str(&thinking);
}
prod.push(AssistantMessageEvent::ThinkingDelta {
content_index,
delta: thinking,
partial: Arc::new(self.output.clone()),
});
}
(BlockKind::Thinking { redacted: false }, "signature_delta") => {
// Append to the existing signature (initializing empty to "").
let sig = delta
.get("signature")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if let Some(Content::Thinking(slot)) = self.output.content.get_mut(content_index) {
let current = slot.thinking_signature.take().unwrap_or_default();
slot.thinking_signature = Some(format!("{current}{sig}"));
}
}
(BlockKind::ToolCall, "input_json_delta") => {
let partial = delta
.get("partial_json")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
scratch.partial_json.push_str(&partial);
// Re-parse the accumulated partial JSON on every delta so the
// partial assistant message renders args live. Mirrors the TS
// `block.arguments = parseStreamingJson(block.partialJson)`.
if let Some(Content::ToolCall(slot)) = self.output.content.get_mut(content_index) {
slot.arguments = parse_streaming_json(Some(&scratch.partial_json));
}
prod.push(AssistantMessageEvent::ToolCallDelta {
content_index,
delta: partial,
partial: Arc::new(self.output.clone()),
});
}
// Redacted-thinking blocks receive no deltas; unknown delta types
// are ignored (forward-compat for future delta variants).
_ => {}
}
Ok(())
}
fn apply_content_block_stop(
&mut self,
payload: &serde_json::Value,
prod: &mut AssistantMessageEventStreamProducer,
) {
let anthropic_index = payload.get("index").and_then(|v| v.as_i64()).unwrap_or(0);
let Some(scratch_index) = self.find_block_by_anthropic_index(anthropic_index) else {
return;
};
let scratch = &mut self.blocks[scratch_index];
let content_index = scratch.content_index;
match scratch.kind {
BlockKind::Text => {
let content = match &self.output.content[content_index] {
Content::Text(t) => t.text.clone(),
_ => String::new(),
};
prod.push(AssistantMessageEvent::TextEnd {
content_index,
content,
partial: Arc::new(self.output.clone()),
});
}
BlockKind::Thinking { redacted } => {
let thinking_text = match &self.output.content[content_index] {
Content::Thinking(t) => t.thinking.clone(),
_ => String::new(),
};
// The final `partialJson` parse was already done on each delta;
// for tool calls the stop event does the authoritative parse.
// For thinking there's no JSON; just emit the accumulated text.
let _ = redacted;
prod.push(AssistantMessageEvent::ThinkingEnd {
content_index,
content: thinking_text,
partial: Arc::new(self.output.clone()),
});
}
BlockKind::ToolCall => {
// Final authoritative parse. Mirrors the TS
// `block.arguments = parseStreamingJson(block.partialJson)`.
let final_args = parse_streaming_json(Some(&scratch.partial_json));
let tool_call = match &self.output.content[content_index] {
Content::ToolCall(tc) => ToolCall {
kind: ToolCallType,
id: tc.id.clone(),
name: tc.name.clone(),
arguments: final_args,
thought_signature: tc.thought_signature.clone(),
namespace: tc.namespace.clone(),
},
_ => return,
};
if let Some(Content::ToolCall(slot)) = self.output.content.get_mut(content_index) {
slot.arguments = tool_call.arguments.clone();
}
prod.push(AssistantMessageEvent::ToolCallEnd {
content_index,
tool_call,
partial: Arc::new(self.output.clone()),
});
}
}
}
fn apply_message_delta(
&mut self,
payload: &serde_json::Value,
prod: &mut AssistantMessageEventStreamProducer,
) {
let _ = prod; // message_delta never pushes events; it mutates output only.
// `delta.stop_reason` → mapStopReason + rawStopReason.
if let Some(stop_reason) = payload
.pointer("/delta/stop_reason")
.and_then(|v| v.as_str())
{
self.output.raw_stop_reason = Some(stop_reason.to_string());
let stop_details = payload.pointer("/delta/stop_details");
match map_stop_reason(stop_reason, stop_details) {
Ok(MappedStop {
stop_reason,
error_message,
}) => {
self.output.stop_reason = stop_reason;
if let Some(msg) = error_message {
self.output.error_message = Some(msg);
}
}
Err(e) => {
// TS throws on unhandled stop reasons; the Rust port records
// it as an error message + Error stop_reason so the stream
// still terminates (the provider loop converts the
// post-stream Error check).
self.output.stop_reason = StopReason::Error;
self.output.error_message = Some(e.to_string());
}
}
}
// Usage update — only fields that are present (not null), mirroring the
// TS field-by-field null checks. Preserves message_start input_tokens
// when the proxy omits them here.
if let Some(usage) = payload.get("usage") {
if let Some(v) = usage.get("input_tokens").and_then(|v| v.as_i64()) {
self.output.usage.input = v;
}
if let Some(v) = usage.get("output_tokens").and_then(|v| v.as_i64()) {
self.output.usage.output = v;
}
if let Some(v) = usage
.get("cache_read_input_tokens")
.and_then(|v| v.as_i64())
{
self.output.usage.cache_read = v;
}
if let Some(v) = usage
.get("cache_creation_input_tokens")
.and_then(|v| v.as_i64())
{
self.output.usage.cache_write = v;
}
// Reasoning tokens — a subset of output_tokens, reported via
// `output_tokens_details.thinking_tokens` (the SDK type omits the
// field; the TS reads it through a narrow cast). Mirrors that.
if let Some(thinking_tokens) = usage
.pointer("/output_tokens_details/thinking_tokens")
.and_then(|v| v.as_i64())
{
self.output.usage.reasoning = Some(thinking_tokens);
}
}
// Anthropic doesn't provide total_tokens; recompute from components
// unconditionally (mirrors TS line 741, OUTSIDE the `if (event.usage)`
// block). When usage is absent the components are unchanged, so this
// is a no-op — but it stays faithful to the source's control flow.
self.output.usage.total_tokens = self.output.usage.input
+ self.output.usage.output
+ self.output.usage.cache_read
+ self.output.usage.cache_write;
}
}
/// The result of mapping an Anthropic stop reason. Mirrors the TS return shape
/// `{ stopReason, errorMessage? }`.
pub struct MappedStop {
pub stop_reason: StopReason,
pub error_message: Option<String>,
}
/// Map an Anthropic `stop_reason` to pi's `StopReason`, optionally carrying an
/// error message (`refusal`/`sensitive`). Mirrors TS `mapStopReason`.
///
/// Returns `Err(AiError::Provider)` for an unhandled stop reason so the caller
/// can surface it; the TS source `throw`s, which the Rust port translates to an
/// `AiError` rather than a panic.
pub fn map_stop_reason(
reason: &str,
stop_details: Option<&serde_json::Value>,
) -> Result<MappedStop, AiError> {
match reason {
"end_turn" => Ok(MappedStop {
stop_reason: StopReason::Stop,
error_message: None,
}),
"max_tokens" => Ok(MappedStop {
stop_reason: StopReason::Length,
error_message: None,
}),
"tool_use" => Ok(MappedStop {
stop_reason: StopReason::ToolUse,
error_message: None,
}),
"refusal" => {
let explanation = stop_details
.and_then(|d| d.get("explanation"))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| "The model refused to complete the request".to_string());
Ok(MappedStop {
stop_reason: StopReason::Error,
error_message: Some(explanation),
})
}
// pause_turn / stop_sequence both collapse to Stop (mirrors TS).
"pause_turn" | "stop_sequence" => Ok(MappedStop {
stop_reason: StopReason::Stop,
error_message: None,
}),
"sensitive" => Ok(MappedStop {
stop_reason: StopReason::Error,
error_message: Some("Provider stopped with: sensitive".to_string()),
}),
other => Err(AiError::Provider {
code: "unhandled_stop_reason".to_string(),
message: format!("Unhandled stop reason: {other}"),
}),
}
}
/// Run the mapper over a live SSE event stream, pushing
/// `AssistantMessageEvent`s to `prod` as each Anthropic event arrives, and
/// emit the terminal `Done`/`Error` event when the stream ends.
///
/// Mirrors the TS `stream` async IIFE's event loop + terminal handling. A
/// missing stop reason (stream ended with `Pending`) is converted to an
/// `Error` event; an aborted signal surfaces as `Error { reason: Aborted }`.
/// `cost_fn` is called on the final `output.usage` before the terminal event
/// so the message carries the model-aware cost (the TS calls `calculateCost`
/// inline; the Rust port defers to the provider, which knows the `Model`).
pub async fn run_mapper<F>(
stream: &mut SseEventStream,
prod: &mut AssistantMessageEventStreamProducer,
state: &mut MapperState,
cost_fn: F,
) where
F: Fn(&Usage) -> UsageCost,
{
loop {
match stream.next_event().await {
Ok(None) => break,
Ok(Some(sse_frame)) => {
let event =
match crate::providers::anthropic::sse::parse_anthropic_event(&sse_frame) {
Ok(e) => e,
Err(err) => {
emit_terminal_error(prod, state, err.to_string(), false);
return;
}
};
if let Err(err) = state.apply(&event, prod) {
emit_terminal_error(prod, state, err.to_string(), false);
return;
}
}
Err(err) => {
let aborted = matches!(err, AiError::Abort { .. });
emit_terminal_error(prod, state, err.to_string(), aborted);
return;
}
}
}
finalize_mapper(prod, state, cost_fn);
}
/// Emit the terminal `Done`/`Error` event for a normally-ended stream. Mirrors
/// the TS post-loop checks (lines 747-759): `pending` stop reason → error;
/// `aborted`/`error` → error with the carried message; otherwise `done` with
/// the model-aware cost applied.
///
/// Extracted from [`run_mapper`] so tests can drive the mapper over a
/// pre-decoded `Vec<AnthropicEvent>` (no `reqwest::Response` needed) and still
/// exercise the terminal logic.
pub fn finalize_mapper<F>(
prod: &mut AssistantMessageEventStreamProducer,
state: &mut MapperState,
cost_fn: F,
) where
F: Fn(&Usage) -> UsageCost,
{
// A stream that reached the protocol's terminal `message_stop` without a
// `message_delta` is a normal stop — some proxy gateways (e.g. the
// anthropic-messages endpoints of DeepSeek/GLM relays) omit `message_delta`
// entirely. The TS check throws "Anthropic stream ended without a stop
// reason" here, which would reject those gateways; v1 defaults the still-
// `Pending` stop reason to a normal `Stop` instead (documented divergence —
// a completed `message_stop` is authoritative, and `message_delta` only
// carries usage + stop_reason). The Pending-error is preserved for streams
// that end WITHOUT `message_stop` (the SSE closed early).
if state.output.stop_reason == StopReason::Pending && state.saw_message_end {
state.output.stop_reason = StopReason::Stop;
}
if state.output.stop_reason == StopReason::Pending {
emit_terminal_error(
prod,
state,
"Anthropic stream ended without a stop reason".to_string(),
false,
);
return;
}
if matches!(
state.output.stop_reason,
StopReason::Aborted | StopReason::Error
) {
let aborted = matches!(state.output.stop_reason, StopReason::Aborted);
let msg = state
.output
.error_message
.clone()
.unwrap_or_else(|| "An unknown error occurred".to_string());
emit_terminal_error(prod, state, msg, aborted);
return;
}
// Success terminal. Apply the model-aware cost last.
state.output.usage.cost = cost_fn(&state.output.usage);
let reason = match state.output.stop_reason {
StopReason::Stop => DoneReason::Stop,
StopReason::Length => DoneReason::Length,
StopReason::ToolUse => DoneReason::ToolUse,
StopReason::Deferred => DoneReason::Deferred,
_ => DoneReason::Stop, // unreachable given the checks above.
};
prod.push(AssistantMessageEvent::Done {
reason,
message: state.output.clone(),
});
}
/// Emit the terminal `Error` event for the stream, stamping `output.stop_reason`
/// + `error_message` and pushing an `AssistantMessageEvent::Error`. Mirrors the
/// TS `catch` block's `output.stopReason = ...; output.errorMessage = ...;
/// stream.push({ type: "error", ... })`.
///
/// Extracted as a `pub` helper so the provider's pre-stream catch (auth
/// failure / HTTP error / abort) reuses the same terminal shape the mapper's
/// in-stream catch uses, keeping the consumer's `result()` contract uniform.
pub fn emit_terminal_error(
prod: &mut AssistantMessageEventStreamProducer,
state: &mut MapperState,
message: String,
aborted: bool,
) {
state.output.stop_reason = if aborted {
StopReason::Aborted
} else {
StopReason::Error
};
state.output.error_message = Some(message);
let reason = if aborted {
ErrorReason::Aborted
} else {
ErrorReason::Error
};
prod.push(AssistantMessageEvent::Error {
reason,
error: state.output.clone(),
});
}
#[cfg(test)]
mod tests {
use super::*;
use crate::event_stream::create_assistant_message_event_stream;
use crate::providers::anthropic::sse::{parse_anthropic_event, ServerSentEvent};
use crate::types::{Api, Content, StopReason};
use serde_json::json;
/// Build a `ServerSentEvent` frame from an event name + raw data string.
fn frame(event: &str, data: &str) -> ServerSentEvent {
ServerSentEvent {
event: Some(event.to_string()),
data: data.to_string(),
raw: vec![format!("event: {event}\ndata: {data}")],
}
}
/// A JSON object literal as a `&str`, for inline event data.
fn j(value: &serde_json::Value) -> String {
serde_json::to_string(value).unwrap()
}
struct Run {
tags: Vec<&'static str>,
result: AssistantMessage,
}
/// Drive a fixture of (event, data) frames through the mapper + finalizer,
/// returning the emitted event tags and the terminal `AssistantMessage`.
async fn run_fixture(frames: Vec<ServerSentEvent>) -> Run {
let (mut prod, stream) = create_assistant_message_event_stream();
let mut state =
MapperState::new(Api::AnthropicMessages, "anthropic", "claude-haiku-4-5", 0);
for f in &frames {
let event = parse_anthropic_event(f).expect("event parses");
state.apply(&event, &mut prod).expect("apply");
}
// finalize_mapper applies the model-aware cost; tests pass a zero cost
// fn since they assert usage fields, not dollar amounts.
finalize_mapper(&mut prod, &mut state, |_| UsageCost::default());
// Hand the producer to a driver task so it can push the buffered events
// while the consumer drains. The producer's push calls happen above
// synchronously; dropping the producer into a task that immediately exits
// lets the consumer observe the terminal event via the result oneshot.
drop(prod);
let mut stream = stream;
let mut tags = Vec::new();
while let Some(ev) = stream.next().await {
tags.push(ev.type_tag());
}
let result = stream.result().await.expect("terminal result");
Run { tags, result }
}
// Mirrors `anthropic-sse-parsing.test.ts::repairs malformed SSE JSON and
// malformed streamed tool JSON`. The partial_json delta carries `\H` (an
// invalid JSON escape) and `\t` (a valid escape). The mapper must repair
// both layers (outer SSE JSON + inner streaming tool JSON) and end with
// `stop_reason: ToolUse` + parseable args.
#[tokio::test]
async fn repairs_malformed_streamed_tool_json() {
// TS `String.raw` keeps the backslashes literal: `\H` and `\t` are
// backslash-H and backslash-t in the raw bytes, NOT an invalid escape
// pre-decode. The Rust raw string r#"..."# reproduces that exactly.
let malformed_delta = r#"{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"path\":\"A\H\",\"text\":\"col1\tcol2\"}"}}"#;
let frames = vec![
frame(
"message_start",
&j(&json!({
"type": "message_start",
"message": {
"id": "msg_test",
"usage": {
"input_tokens": 12,
"output_tokens": 0,
"cache_read_input_tokens": 0,
"cache_creation_input_tokens": 0,
},
},
})),
),
frame(
"content_block_start",
&j(&json!({
"type": "content_block_start",
"index": 0,
"content_block": { "type": "tool_use", "id": "toolu_test", "name": "edit", "input": {} },
})),
),
frame("content_block_delta", malformed_delta),
frame(
"content_block_stop",
&j(&json!({ "type": "content_block_stop", "index": 0 })),
),
frame(
"message_delta",
&j(&json!({
"type": "message_delta",
"delta": { "stop_reason": "tool_use" },
"usage": {
"input_tokens": 12,
"output_tokens": 5,
"cache_read_input_tokens": 0,
"cache_creation_input_tokens": 0,
},
})),
),
frame("message_stop", &j(&json!({ "type": "message_stop" }))),
];
let run = run_fixture(frames).await;
assert_eq!(run.result.stop_reason, StopReason::ToolUse);
assert!(run.result.error_message.is_none());
let toolcall = run
.result
.content
.iter()
.find_map(|c| match c {
Content::ToolCall(tc) => Some(tc),
_ => None,
})
.expect("a tool call block");
assert_eq!(
toolcall.arguments,
json!({ "path": "A\\H", "text": "col1\tcol2" })
);
// Event sequence: start, toolcall_start, toolcall_delta, toolcall_end, done.
assert_eq!(
run.tags,
vec![
"start",
"toolcall_start",
"toolcall_delta",
"toolcall_end",
"done"
]
);
}
// Mirrors `preserves content from content_block_start events` — text +
// thinking blocks retain their initial content and accumulate deltas;
// signature_delta appends to the thinking signature.
#[tokio::test]
async fn preserves_content_from_content_block_start() {
let frames = vec![
frame(
"message_start",
&j(&json!({
"type": "message_start",
"message": {
"id": "msg_initial_content",
"usage": { "input_tokens": 12, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 },
},
})),
),
frame(
"content_block_start",
&j(
&json!({ "type": "content_block_start", "index": 0, "content_block": { "type": "text", "text": "Initial text" } }),
),
),
frame(
"content_block_delta",
&j(
&json!({ "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": " plus delta" } }),
),
),
frame(
"content_block_stop",
&j(&json!({ "type": "content_block_stop", "index": 0 })),
),
frame(
"content_block_start",
&j(
&json!({ "type": "content_block_start", "index": 1, "content_block": { "type": "thinking", "thinking": "Initial thinking", "signature": "initial signature" } }),
),
),
frame(
"content_block_delta",
&j(
&json!({ "type": "content_block_delta", "index": 1, "delta": { "type": "thinking_delta", "thinking": " plus delta" } }),
),
),
frame(
"content_block_delta",
&j(
&json!({ "type": "content_block_delta", "index": 1, "delta": { "type": "signature_delta", "signature": " plus delta" } }),
),
),
frame(
"content_block_stop",
&j(&json!({ "type": "content_block_stop", "index": 1 })),
),
frame(
"message_delta",
&j(&json!({
"type": "message_delta",
"delta": { "stop_reason": "end_turn" },
"usage": { "input_tokens": 12, "output_tokens": 5, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 },
})),
),
frame("message_stop", &j(&json!({ "type": "message_stop" }))),
];
let run = run_fixture(frames).await;
assert_eq!(run.result.stop_reason, StopReason::Stop);
let text = match &run.result.content[0] {
Content::Text(t) => t,
_ => panic!("first block is text"),
};
assert_eq!(text.text, "Initial text plus delta");
let thinking = match &run.result.content[1] {
Content::Thinking(t) => t,
_ => panic!("second block is thinking"),
};
assert_eq!(thinking.thinking, "Initial thinking plus delta");
assert_eq!(
thinking.thinking_signature.as_deref(),
Some("initial signature plus delta")
);
assert!(!thinking.redacted);
}
// Mirrors `preserves refusal stop details from message_delta` — refusal
// stop_reason maps to Error with the explanation.
#[tokio::test]
async fn preserves_refusal_stop_details() {
let explanation = "This request triggered restrictions on violative cyber content and was blocked under Anthropic's Usage Policy.";
let frames = vec![
frame(
"message_start",
&j(&json!({
"type": "message_start",
"message": { "id": "msg_01XFUDYJgAACzvnptvVoYEL", "usage": { "input_tokens": 412, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 } },
})),
),
frame(
"message_delta",
&j(&json!({
"type": "message_delta",
"delta": { "stop_reason": "refusal", "stop_details": { "type": "refusal", "category": "cyber", "explanation": explanation } },
"usage": { "input_tokens": 412, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 },
})),
),
frame("message_stop", &j(&json!({ "type": "message_stop" }))),
];
let run = run_fixture(frames).await;
assert_eq!(run.result.stop_reason, StopReason::Error);
assert_eq!(run.result.raw_stop_reason.as_deref(), Some("refusal"));
assert_eq!(run.result.error_message.as_deref(), Some(explanation));
// Refusal emits an Error terminal, not Done.
assert_eq!(run.tags.last().copied(), Some("error"));
}
// Mirrors `preserves sensitive stop reasons with a descriptive error
// message`.
#[tokio::test]
async fn preserves_sensitive_stop_reasons() {
let frames = vec![
frame(
"message_start",
&j(
&json!({ "type": "message_start", "message": { "id": "msg_sensitive", "usage": { "input_tokens": 12, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 } } }),
),
),
frame(
"message_delta",
&j(
&json!({ "type": "message_delta", "delta": { "stop_reason": "sensitive" }, "usage": { "input_tokens": 12, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 } }),
),
),
frame("message_stop", &j(&json!({ "type": "message_stop" }))),
];
let run = run_fixture(frames).await;
assert_eq!(run.result.stop_reason, StopReason::Error);
assert_eq!(run.result.raw_stop_reason.as_deref(), Some("sensitive"));
assert_eq!(
run.result.error_message.as_deref(),
Some("Provider stopped with: sensitive")
);
}
// Mirrors `treats message_delta without usage as a no-op for usage
// accumulation` — usage retains message_start values; total recomputed
// from components.
#[tokio::test]
async fn message_delta_without_usage_noop() {
let frames = vec![
frame(
"message_start",
&j(
&json!({ "type": "message_start", "message": { "id": "msg_test", "usage": { "input_tokens": 12, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 } } }),
),
),
frame(
"content_block_start",
&j(
&json!({ "type": "content_block_start", "index": 0, "content_block": { "type": "text", "text": "" } }),
),
),
frame(
"content_block_delta",
&j(
&json!({ "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "Hello" } }),
),
),
frame(
"content_block_stop",
&j(&json!({ "type": "content_block_stop", "index": 0 })),
),
// message_delta with stop_reason but NO usage object.
frame(
"message_delta",
&j(&json!({ "type": "message_delta", "delta": { "stop_reason": "end_turn" } })),
),
frame("message_stop", &j(&json!({ "type": "message_stop" }))),
];
let run = run_fixture(frames).await;
assert_eq!(run.result.stop_reason, StopReason::Stop);
assert!(run.result.error_message.is_none());
let text = match &run.result.content[0] {
Content::Text(t) => t,
_ => panic!("text block"),
};
assert_eq!(text.text, "Hello");
assert_eq!(run.result.usage.input, 12);
assert_eq!(run.result.usage.total_tokens, 12);
}
// Mirrors `ignores unknown SSE events after message_stop` — `done` and
// `proxy.stats` frames are skipped (non-ANTHROPIC_MESSAGE_EVENTS), so the
// message still ends cleanly with Stop.
#[tokio::test]
async fn ignores_unknown_events_after_message_stop() {
let mut frames = vec![
frame(
"message_start",
&j(
&json!({ "type": "message_start", "message": { "id": "msg_test", "usage": { "input_tokens": 12, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 } } }),
),
),
frame(
"content_block_start",
&j(
&json!({ "type": "content_block_start", "index": 0, "content_block": { "type": "text", "text": "" } }),
),
),
frame(
"content_block_delta",
&j(
&json!({ "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "Hello" } }),
),
),
frame(
"content_block_stop",
&j(&json!({ "type": "content_block_stop", "index": 0 })),
),
frame(
"message_delta",
&j(
&json!({ "type": "message_delta", "delta": { "stop_reason": "end_turn" }, "usage": { "input_tokens": 12, "output_tokens": 5, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 } }),
),
),
frame("message_stop", &j(&json!({ "type": "message_stop" }))),
];
frames.push(frame("done", "[DONE]"));
frames.push(frame("proxy.stats", "not json"));
let run = run_fixture(frames).await;
assert_eq!(run.result.stop_reason, StopReason::Stop);
assert!(run.result.error_message.is_none());
let text = match &run.result.content[0] {
Content::Text(t) => t,
_ => panic!("text block"),
};
assert_eq!(text.text, "Hello");
}
// ---- map_stop_reason table (anthropic-messages.ts:1326-1352) ----
#[test]
fn map_stop_reason_table() {
let stop = |r: &str| map_stop_reason(r, None).unwrap();
assert_eq!(stop("end_turn").stop_reason, StopReason::Stop);
assert_eq!(stop("max_tokens").stop_reason, StopReason::Length);
assert_eq!(stop("tool_use").stop_reason, StopReason::ToolUse);
assert_eq!(stop("pause_turn").stop_reason, StopReason::Stop);
assert_eq!(stop("stop_sequence").stop_reason, StopReason::Stop);
// refusal with explanation.
let details = json!({ "type": "refusal", "explanation": "blocked" });
let refusal = map_stop_reason("refusal", Some(&details)).unwrap();
assert_eq!(refusal.stop_reason, StopReason::Error);
assert_eq!(refusal.error_message.as_deref(), Some("blocked"));
// refusal without explanation → default message.
let refusal_default = map_stop_reason("refusal", None).unwrap();
assert_eq!(
refusal_default.error_message.as_deref(),
Some("The model refused to complete the request")
);
// sensitive → fixed message.
let sensitive = map_stop_reason("sensitive", None).unwrap();
assert_eq!(sensitive.stop_reason, StopReason::Error);
assert_eq!(
sensitive.error_message.as_deref(),
Some("Provider stopped with: sensitive")
);
// unknown → error (TS throws).
assert!(map_stop_reason("nonsense", None).is_err());
}
// `message_start` records the response id + initial usage (including the
// 1h cache-write subset), mirroring anthropic-messages.ts:574-586.
#[tokio::test]
async fn message_start_records_response_id_and_usage() {
let frames = vec![
frame(
"message_start",
&j(&json!({
"type": "message_start",
"message": {
"id": "msg_abc",
"usage": {
"input_tokens": 10,
"output_tokens": 2,
"cache_read_input_tokens": 3,
"cache_creation_input_tokens": 4,
"cache_creation": { "ephemeral_1h_input_tokens": 1 },
},
},
})),
),
frame(
"message_delta",
&j(&json!({ "type": "message_delta", "delta": { "stop_reason": "end_turn" } })),
),
frame("message_stop", &j(&json!({ "type": "message_stop" }))),
];
let run = run_fixture(frames).await;
assert_eq!(run.result.response_id.as_deref(), Some("msg_abc"));
assert_eq!(run.result.usage.input, 10);
assert_eq!(run.result.usage.output, 2);
assert_eq!(run.result.usage.cache_read, 3);
assert_eq!(run.result.usage.cache_write, 4);
assert_eq!(run.result.usage.cache_write_1h, Some(1));
assert_eq!(run.result.usage.total_tokens, 10 + 2 + 3 + 4);
}
// `message_delta` usage's `output_tokens_details.thinking_tokens` is
// recorded as `usage.reasoning` (a subset of output_tokens).
#[tokio::test]
async fn message_delta_records_reasoning_tokens() {
let frames = vec![
frame(
"message_start",
&j(
&json!({ "type": "message_start", "message": { "id": "m", "usage": { "input_tokens": 1, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 } } }),
),
),
frame(
"message_delta",
&j(&json!({
"type": "message_delta",
"delta": { "stop_reason": "end_turn" },
"usage": {
"input_tokens": 1,
"output_tokens": 50,
"cache_read_input_tokens": 0,
"cache_creation_input_tokens": 0,
"output_tokens_details": { "thinking_tokens": 30 },
},
})),
),
frame("message_stop", &j(&json!({ "type": "message_stop" }))),
];
let run = run_fixture(frames).await;
assert_eq!(run.result.usage.output, 50);
assert_eq!(run.result.usage.reasoning, Some(30));
}
// `redacted_thinking` content_block_start produces a Thinking block with
// the fixed marker text, the opaque payload in `thinking_signature`, and
// `redacted: true`.
#[tokio::test]
async fn redacted_thinking_block() {
let frames = vec![
frame(
"message_start",
&j(
&json!({ "type": "message_start", "message": { "id": "m", "usage": { "input_tokens": 1, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 } } }),
),
),
frame(
"content_block_start",
&j(
&json!({ "type": "content_block_start", "index": 0, "content_block": { "type": "redacted_thinking", "data": "opaque-base64" } }),
),
),
frame(
"content_block_stop",
&j(&json!({ "type": "content_block_stop", "index": 0 })),
),
frame(
"message_delta",
&j(&json!({ "type": "message_delta", "delta": { "stop_reason": "end_turn" } })),
),
frame("message_stop", &j(&json!({ "type": "message_stop" }))),
];
let run = run_fixture(frames).await;
let thinking = match &run.result.content[0] {
Content::Thinking(t) => t,
_ => panic!("thinking block"),
};
assert!(thinking.redacted);
assert_eq!(thinking.thinking, "[Reasoning redacted]");
assert_eq!(
thinking.thinking_signature.as_deref(),
Some("opaque-base64")
);
// Redacted thinking emits a thinking_start/thinking_end pair.
assert!(run.tags.contains(&"thinking_start"));
assert!(run.tags.contains(&"thinking_end"));
}
// A stream that reaches the protocol's terminal `message_stop` without a
// `message_delta` (no stop_reason) finalizes as a NORMAL stop — proxy
// gateways may omit `message_delta` (documented divergence from the TS
// throw; `message_stop` is authoritative). The Pending-error is preserved
// for streams that end WITHOUT `message_stop` (early SSE close).
#[tokio::test]
async fn message_stop_without_stop_reason_is_normal_stop() {
let frames = vec![
frame(
"message_start",
&j(
&json!({ "type": "message_start", "message": { "id": "m", "usage": { "input_tokens": 1, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 } } }),
),
),
frame("message_stop", &j(&json!({ "type": "message_stop" }))),
];
let run = run_fixture(frames).await;
assert_eq!(run.result.stop_reason, StopReason::Stop);
assert_eq!(run.tags.last().copied(), Some("done"));
}
// A stream whose SSE closes BEFORE `message_stop` (no stop_reason, no
// terminal event) still finalizes to an Error terminal — the early-close
// case the Pending check guards.
#[tokio::test]
async fn stream_ending_before_message_stop_is_error() {
let frames = vec![frame(
"message_start",
&j(
&json!({ "type": "message_start", "message": { "id": "m", "usage": { "input_tokens": 1, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 } } }),
),
)];
let run = run_fixture(frames).await;
assert_eq!(run.result.stop_reason, StopReason::Error);
assert_eq!(run.tags.last().copied(), Some("error"));
}
// `input_json_delta` re-parses the partial JSON on every delta so the
// partial assistant message renders args live (invariant §5.15), and the
// final `content_block_stop` does the authoritative parse.
#[tokio::test]
async fn tool_call_partial_json_reparse_each_delta() {
let frames = vec![
frame(
"message_start",
&j(
&json!({ "type": "message_start", "message": { "id": "m", "usage": { "input_tokens": 1, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0 } } }),
),
),
frame(
"content_block_start",
&j(
&json!({ "type": "content_block_start", "index": 0, "content_block": { "type": "tool_use", "id": "t1", "name": "write", "input": {} } }),
),
),
// Two deltas building the args object incrementally.
frame(
"content_block_delta",
&j(
&json!({ "type": "content_block_delta", "index": 0, "delta": { "type": "input_json_delta", "partial_json": "{\"path\":\"a\"," } }),
),
),
frame(
"content_block_delta",
&j(
&json!({ "type": "content_block_delta", "index": 0, "delta": { "type": "input_json_delta", "partial_json": "\"text\":\"b\"}" } }),
),
),
frame(
"content_block_stop",
&j(&json!({ "type": "content_block_stop", "index": 0 })),
),
frame(
"message_delta",
&j(&json!({ "type": "message_delta", "delta": { "stop_reason": "tool_use" } })),
),
frame("message_stop", &j(&json!({ "type": "message_stop" }))),
];
let run = run_fixture(frames).await;
let tc = match &run.result.content[0] {
Content::ToolCall(t) => t,
_ => panic!("toolcall"),
};
assert_eq!(tc.arguments, json!({ "path": "a", "text": "b" }));
// Two input_json_delta frames → two toolcall_delta events + start + end.
let deltas: Vec<&'static str> = run
.tags
.iter()
.filter(|&&t| t == "toolcall_delta")
.copied()
.collect();
assert_eq!(deltas.len(), 2);
}
// A stream that surfaces an `error` SSE event terminates with an Error
// event carrying the SSE data as the message (parse_anthropic_event
// rejects `event: error`).
#[tokio::test]
async fn sse_error_event_surfaces_error() {
let (prod, stream) = create_assistant_message_event_stream();
let mut prod = prod;
let mut state =
MapperState::new(Api::AnthropicMessages, "anthropic", "claude-haiku-4-5", 0);
// An error frame — parse_anthropic_event returns Err.
let err_frame = frame("error", "rate limited");
match parse_anthropic_event(&err_frame) {
Err(e) => emit_terminal_error(&mut prod, &mut state, e.to_string(), false),
Ok(_) => panic!("expected error"),
}
let result = stream.result().await.expect("terminal");
assert_eq!(result.stop_reason, StopReason::Error);
assert!(result
.error_message
.as_deref()
.unwrap()
.contains("rate limited"));
}
}