返回 CodeWhale
wire.rs
根目录 / crates / engine / src / client / wire.rs
1 //! Shared token-usage and SSE byte-line decoding extracted from `client.rs`.
2 //!
3 //! Protocol adapters retain event interpretation; this module owns the existing
4 //! accounting and fail-closed UTF-8 line helpers used across those adapters.
5
6 use anyhow::Result;
7 use serde_json::Value;
8
9 use codewhale_config::ProviderKind;
10 use codewhale_models::{ContentBlock, MessageRequest, ServerToolUsage, SystemPrompt, Usage};
11 use std::sync::{Mutex as StdMutex, OnceLock};
12
13 pub fn saturating_u32(value: u64) -> u32 {
14 u32::try_from(value).unwrap_or(u32::MAX)
15 }
16
17 pub fn parse_server_tool_usage(usage: Option<&Value>) -> Option<ServerToolUsage> {
18 usage.and_then(|u| u.get("server_tool_use")).map(|server| {
19 let counter = |key: &str| server.get(key).and_then(Value::as_u64).map(saturating_u32);
20 ServerToolUsage {
21 code_execution_requests: counter("code_execution_requests"),
22 tool_search_requests: counter("tool_search_requests"),
23 web_search_requests: counter("web_search_requests"),
24 web_fetch_requests: counter("web_fetch_requests"),
25 tool_search: counter("tool_search"),
26 tool_fetch: counter("tool_fetch"),
27 tool_image_search: counter("tool_image_search"),
28 }
29 })
30 }
31
32 pub fn parse_safety_tokens(usage: Option<&Value>) -> Option<u32> {
33 usage
34 .and_then(|u| {
35 u.pointer("/output_tokens_details/safety_tokens")
36 .or_else(|| u.pointer("/completion_tokens_details/safety_tokens"))
37 .or_else(|| u.get("safety_tokens"))
38 })
39 .and_then(Value::as_u64)
40 .map(saturating_u32)
41 }
42
43 pub fn parse_usage(usage: Option<&Value>) -> Usage {
44 let input_tokens = usage
45 .and_then(|u| u.get("input_tokens").or_else(|| u.get("prompt_tokens")))
46 .and_then(Value::as_u64)
47 .unwrap_or(0);
48 let mut output_tokens = usage
49 .and_then(|u| {
50 u.get("output_tokens")
51 .or_else(|| u.get("completion_tokens"))
52 })
53 .and_then(Value::as_u64)
54 .unwrap_or(0);
55 let total_tokens = usage
56 .and_then(|u| u.get("total_tokens"))
57 .and_then(Value::as_u64);
58 let reasoning_tokens_raw = usage
59 .and_then(|u| u.get("completion_tokens_details"))
60 .and_then(|details| details.get("reasoning_tokens"))
61 .and_then(Value::as_u64);
62 if output_tokens == 0
63 && let Some(reasoning_tokens) = reasoning_tokens_raw
64 {
65 output_tokens = reasoning_tokens;
66 } else if output_tokens == 0
67 && let Some(total_tokens) = total_tokens
68 {
69 output_tokens = total_tokens.saturating_sub(input_tokens);
70 }
71 let cached_tokens = usage
72 .and_then(|u| u.get("prompt_tokens_details"))
73 .and_then(|details| details.get("cached_tokens"))
74 .and_then(Value::as_u64);
75 let prompt_cache_hit_tokens = usage
76 .and_then(|u| u.get("prompt_cache_hit_tokens"))
77 .and_then(Value::as_u64)
78 .or(cached_tokens)
79 .map(saturating_u32);
80 // Keep reported cache creation separate so pricing can apply its write
81 // rate. Fall back per field: a details object without this field must not
82 // hide the alternate dialect's value.
83 let nested_cache_write_tokens = usage.and_then(|u| {
84 u.pointer("/prompt_tokens_details/cache_write_tokens")
85 .and_then(Value::as_u64)
86 .or_else(|| {
87 u.pointer("/input_tokens_details/cache_write_tokens")
88 .and_then(Value::as_u64)
89 })
90 });
91 let prompt_cache_write_tokens = usage
92 .and_then(|u| u.get("prompt_cache_write_tokens"))
93 .and_then(Value::as_u64)
94 .or(nested_cache_write_tokens)
95 .map(saturating_u32);
96 let prompt_cache_miss_tokens = usage
97 .and_then(|u| u.get("prompt_cache_miss_tokens"))
98 .and_then(Value::as_u64)
99 .or_else(|| {
100 // No cache report means unknown, including when usage is absent.
101 // A reported zero is still a report and permits derivation.
102 (prompt_cache_hit_tokens.is_some() || prompt_cache_write_tokens.is_some()).then(|| {
103 let accounted = u64::from(prompt_cache_hit_tokens.unwrap_or(0))
104 .saturating_add(u64::from(prompt_cache_write_tokens.unwrap_or(0)));
105 input_tokens.saturating_sub(accounted)
106 })
107 })
108 .map(saturating_u32);
109 // Reasoning tokens are a *subset* of the completion count every provider
110 // bills, so they are never added to output. A payload claiming more
111 // reasoning than output contradicts that invariant, which makes the figure
112 // invalid telemetry rather than extra billable output: drop it instead of
113 // letting a bad number reach the cost surfaces (#4318).
114 let reasoning_tokens = reasoning_tokens_raw
115 .filter(|reasoning| *reasoning <= output_tokens)
116 .map(saturating_u32);
117
118 let server_tool_use = parse_server_tool_usage(usage);
119 let safety_tokens = parse_safety_tokens(usage);
120
121 Usage {
122 input_tokens: saturating_u32(input_tokens),
123 output_tokens: saturating_u32(output_tokens),
124 prompt_cache_hit_tokens,
125 prompt_cache_miss_tokens,
126 prompt_cache_write_tokens,
127 reasoning_tokens,
128 reasoning_replay_tokens: None,
129 server_tool_use,
130 safety_tokens,
131
132 input_audio_tokens: usage
133 .and_then(|usage| {
134 usage
135 .pointer("/prompt_tokens_details/audio_tokens")
136 .or_else(|| usage.pointer("/input_tokens_details/audio_tokens"))
137 })
138 .and_then(Value::as_u64)
139 .map(saturating_u32),
140 output_audio_tokens: usage
141 .and_then(|usage| {
142 usage
143 .pointer("/completion_tokens_details/audio_tokens")
144 .or_else(|| usage.pointer("/output_tokens_details/audio_tokens"))
145 })
146 .and_then(Value::as_u64)
147 .map(saturating_u32),
148
149 request_usages: Vec::new(),
150 }
151 }
152
153 pub(super) fn extract_sse_data_value(line: &str) -> Option<&str> {
154 line.strip_prefix("data:")
155 .map(|value| value.strip_prefix(' ').unwrap_or(value))
156 }
157
158 /// Hard ceiling for one pending SSE line, matching the MCP frame limit.
159 /// This does not bound the size of a multi-line event or the whole stream.
160 const MAX_SSE_LINE_BYTES: usize = 8 * 1024 * 1024;
161 /// Hard ceiling for one assembled SSE event (its `data:` fields joined), so a
162 /// peer that never sends the blank line ending an event cannot grow memory
163 /// without bound. Same size as the single-line ceiling.
164 const MAX_SSE_EVENT_BYTES: usize = MAX_SSE_LINE_BYTES;
165
166 /// Invalid or oversized SSE line (or unterminated flush).
167 ///
168 /// HTTP/2 DATA and other transports may split a multi-byte character across
169 /// chunks. That is not this error: callers must buffer raw bytes until a
170 /// complete line (or stream end) before decoding. We never substitute
171 /// U+FFFD — fail closed so garbled CJK cannot enter the transcript.
172 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
173 pub(super) enum SseLineError {
174 InvalidUtf8 { valid_up_to: usize },
175 TooLong,
176 EventTooLong,
177 }
178
179 impl std::fmt::Display for SseLineError {
180 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181 match self {
182 Self::InvalidUtf8 { valid_up_to } => {
183 write!(f, "invalid UTF-8 in SSE stream at byte {valid_up_to}")
184 }
185 Self::TooLong => write!(
186 f,
187 "SSE line exceeded {MAX_SSE_LINE_BYTES} bytes (8 MiB) — aborting stream"
188 ),
189 Self::EventTooLong => write!(
190 f,
191 "SSE event exceeded {MAX_SSE_EVENT_BYTES} bytes (8 MiB) — aborting stream"
192 ),
193 }
194 }
195 }
196
197 impl std::error::Error for SseLineError {}
198
199 /// Decode one assembled SSE line (or stream-end tail) with `str::from_utf8`.
200 /// Does not substitute U+FFFD.
201 fn decode_sse_line_bytes(bytes: &[u8]) -> Result<&str, SseLineError> {
202 std::str::from_utf8(bytes).map_err(|err| SseLineError::InvalidUtf8 {
203 valid_up_to: err.valid_up_to(),
204 })
205 }
206
207 /// Take the next COMPLETE line (up to the first `\n`) off a raw byte buffer,
208 /// draining it, and return it trimmed. Returns `Ok(None)` when no full line is
209 /// buffered yet. Decoding only complete lines (never an arbitrary network-read
210 /// boundary) means a multi-byte UTF-8 char — CJK, emoji, accented letter —
211 /// split across two reads is never corrupted to U+FFFD, since the `\n`
212 /// delimiter is ASCII and can never fall inside a multi-byte sequence.
213 ///
214 /// Genuine invalid bytes fail closed (`Err(SseLineError)`); we do not
215 /// substitute U+FFFD.
216 pub(super) fn take_sse_line(buffer: &mut Vec<u8>) -> Result<Option<String>, SseLineError> {
217 let line_end = buffer.iter().position(|&b| b == b'\n');
218 if line_end.unwrap_or(buffer.len()) > MAX_SSE_LINE_BYTES {
219 buffer.clear();
220 return Err(SseLineError::TooLong);
221 }
222 let Some(line_end) = line_end else {
223 return Ok(None);
224 };
225 // Strip a preceding `\r` so CRLF-delimited SSE frames do not leave CR.
226 let mut end = line_end;
227 if end > 0 && buffer[end - 1] == b'\r' {
228 end -= 1;
229 }
230 let decoded = decode_sse_line_bytes(&buffer[..end]).map(|text| text.trim().to_string());
231 buffer.drain(..=line_end);
232 decoded.map(Some)
233 }
234
235 /// Decode the unterminated tail left in `buffer` at stream end.
236 ///
237 /// Same fail-closed UTF-8 contract as [`take_sse_line`]. Empty / whitespace-only
238 /// tails yield `Ok(None)`.
239 pub(super) fn flush_sse_line(buffer: &mut Vec<u8>) -> Result<Option<String>, SseLineError> {
240 if buffer.len() > MAX_SSE_LINE_BYTES {
241 buffer.clear();
242 return Err(SseLineError::TooLong);
243 }
244 if buffer.is_empty() {
245 return Ok(None);
246 }
247 let mut end = buffer.len();
248 if buffer[end - 1] == b'\r' {
249 end -= 1;
250 }
251 let decoded = decode_sse_line_bytes(&buffer[..end]).map(|text| text.trim().to_string());
252 buffer.clear();
253 decoded.map(|line| (!line.is_empty()).then_some(line))
254 }
255
256 /// Append one `data:` field to the event being assembled. The SSE spec joins
257 /// the `data:` fields of one event with '\n' and dispatches the event at the
258 /// blank line that ends it; a provider may split one JSON payload across
259 /// several fields, so parsing each field alone would drop the event. Fails
260 /// closed (clearing the event) past [`MAX_SSE_EVENT_BYTES`].
261 pub(super) fn push_sse_event_data(event: &mut String, data: &str) -> Result<(), SseLineError> {
262 let needed = event
263 .len()
264 .saturating_add(usize::from(!event.is_empty()))
265 .saturating_add(data.len());
266 if needed > MAX_SSE_EVENT_BYTES {
267 event.clear();
268 return Err(SseLineError::EventTooLong);
269 }
270 if !event.is_empty() {
271 event.push('\n');
272 }
273 event.push_str(data);
274 Ok(())
275 }
276
277 /// Next decoded SSE line. When `at_end` is false, wait for `\n`. When `at_end`
278 /// is true, also flush an unterminated tail (stream closed).
279 pub(super) fn next_sse_line(
280 buffer: &mut Vec<u8>,
281 at_end: bool,
282 ) -> Result<Option<String>, SseLineError> {
283 match take_sse_line(buffer)? {
284 Some(line) => Ok(Some(line)),
285 None if at_end => flush_sse_line(buffer),
286 None => Ok(None),
287 }
288 }
289
290 /// Incremental raw-byte SSE line assembler for tests and the Chat Completions
291 /// decoder. HTTP/2 DATA may split a multi-byte UTF-8 character across chunks;
292 /// we never decode until a complete line or [`SseLineDecoder::finish`].
293 #[cfg(test)]
294 pub(super) struct SseLineDecoder {
295 buffer: Vec<u8>,
296 }
297
298 #[cfg(test)]
299 impl SseLineDecoder {
300 pub(super) fn new() -> Self {
301 Self { buffer: Vec::new() }
302 }
303
304 pub(super) fn push(&mut self, chunk: &[u8]) -> Result<Vec<String>, SseLineError> {
305 self.buffer.extend_from_slice(chunk);
306 let mut lines = Vec::new();
307 while let Some(line) = take_sse_line(&mut self.buffer)? {
308 lines.push(line);
309 }
310 Ok(lines)
311 }
312
313 pub(super) fn finish(mut self) -> Result<Option<String>, SseLineError> {
314 flush_sse_line(&mut self.buffer)
315 }
316 }
317
318 pub fn to_api_tool_name(name: &str) -> String {
319 let mut out = String::new();
320 for ch in name.chars() {
321 if ch.is_ascii_alphanumeric() || ch == '_' {
322 out.push(ch);
323 } else if ch == '-' {
324 out.push_str("--");
325 } else {
326 out.push_str("-x");
327 out.push_str(&format!("{:06X}", ch as u32));
328 out.push('-');
329 }
330 }
331 out
332 }
333
334 fn decode_delimited_tool_name(name: &str) -> String {
335 let mut out = String::new();
336 let mut iter = name.chars().peekable();
337 while let Some(ch) = iter.next() {
338 if ch != '-' {
339 out.push(ch);
340 continue;
341 }
342 if let Some('-') = iter.peek().copied() {
343 iter.next();
344 out.push('-');
345 continue;
346 }
347 if iter.peek().copied() == Some('x') {
348 iter.next();
349 let mut hex = String::new();
350 for _ in 0..6 {
351 if let Some(h) = iter.next() {
352 hex.push(h);
353 } else {
354 break;
355 }
356 }
357 // Only decode if we got exactly 6 hex digits (matching encoder output).
358 // Fewer digits means a truncated/malformed sequence — pass through as-is.
359 if hex.len() == 6
360 && let Ok(code) = u32::from_str_radix(&hex, 16)
361 && let Some(decoded) = std::char::from_u32(code)
362 {
363 if let Some('-') = iter.peek().copied() {
364 iter.next();
365 }
366 out.push(decoded);
367 continue;
368 }
369 out.push('-');
370 out.push('x');
371 out.push_str(&hex);
372 continue;
373 }
374 out.push('-');
375 }
376 out
377 }
378
379 pub fn from_api_tool_name(name: &str) -> String {
380 let exact = decode_delimited_tool_name(name);
381 if to_api_tool_name(&exact) == name {
382 return exact;
383 }
384 decode_bare_hex_escapes(&exact)
385 }
386
387 pub const TOOL_NAME_LIMIT_64: usize = 64;
388 pub const TOOL_NAME_LIMIT_128: usize = 128;
389
390 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
391 pub enum ToolNameWire {
392 AnthropicMessages,
393 OpenAiCompatible,
394 }
395
396 pub fn documented_tool_name_limit(provider: ProviderKind, wire: ToolNameWire) -> Option<usize> {
397 match (provider, wire) {
398 (ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic, _) => Some(TOOL_NAME_LIMIT_128),
399 (ProviderKind::Anthropic, ToolNameWire::AnthropicMessages) => Some(TOOL_NAME_LIMIT_128),
400 (ProviderKind::Openai | ProviderKind::OpenaiCodex, ToolNameWire::OpenAiCompatible) => {
401 Some(TOOL_NAME_LIMIT_64)
402 }
403 _ => None,
404 }
405 }
406
407 pub fn tool_name_limit(provider: ProviderKind, wire: ToolNameWire) -> usize {
408 if let Some(limit) = documented_tool_name_limit(provider, wire) {
409 return limit;
410 }
411 match (provider, wire) {
412 (_, ToolNameWire::AnthropicMessages) => TOOL_NAME_LIMIT_128,
413 (
414 ProviderKind::Ollama
415 | ProviderKind::OllamaCloud
416 | ProviderKind::Vllm
417 | ProviderKind::Sglang
418 | ProviderKind::Custom,
419 _,
420 ) => TOOL_NAME_LIMIT_128,
421 (_, ToolNameWire::OpenAiCompatible) => TOOL_NAME_LIMIT_64,
422 }
423 }
424
425 pub fn check_history_tool_names(request: &MessageRequest, documented: Option<usize>) -> Result<()> {
426 let Some(limit) = documented else {
427 return Ok(());
428 };
429 for message in &request.messages {
430 for block in &message.content {
431 if let ContentBlock::ToolUse { name, .. } = block
432 && tool_name_exceeds_limit(name, limit)
433 {
434 anyhow::bail!(over_limit_history_tool_name_message(name, limit));
435 }
436 }
437 }
438 Ok(())
439 }
440
441 pub fn tool_name_exceeds_limit(name: &str, limit: usize) -> bool {
442 to_api_tool_name(name).len() > limit
443 }
444
445 pub fn over_limit_tool_name_message(name: &str, limit: usize) -> String {
446 format!(
447 "tool name `{name}` encodes to {} characters but this provider accepts at most {limit}; rename the tool (shorter name, fewer dots, hyphens or other special characters) or remove it",
448 to_api_tool_name(name).len()
449 )
450 }
451
452 pub fn over_limit_history_tool_name_message(name: &str, limit: usize) -> String {
453 format!(
454 "tool `{name}` was called earlier in this session and its encoded name is {} characters, but this provider accepts at most {limit}; switch to a route with a larger limit or start a new session",
455 to_api_tool_name(name).len()
456 )
457 }
458
459 pub const SSE_BACKPRESSURE_HIGH_WATERMARK: usize = 1024 * 1024; // 1 MB
460
461 pub const SSE_BACKPRESSURE_SLEEP_MS: u64 = 10;
462
463 pub const SSE_MAX_LINES_PER_CHUNK: usize = 256;
464
465 fn buffer_pool() -> &'static StdMutex<Vec<Vec<u8>>> {
466 static POOL: OnceLock<StdMutex<Vec<Vec<u8>>>> = OnceLock::new();
467 POOL.get_or_init(|| StdMutex::new(Vec::new()))
468 }
469
470 pub fn acquire_stream_buffer() -> Vec<u8> {
471 if let Ok(mut pool) = buffer_pool().lock() {
472 pool.pop().unwrap_or_else(|| Vec::with_capacity(8192))
473 } else {
474 Vec::with_capacity(8192)
475 }
476 }
477
478 pub fn release_stream_buffer(mut buf: Vec<u8>) {
479 buf.clear();
480 if buf.capacity() > 256 * 1024 {
481 buf.shrink_to(256 * 1024);
482 }
483 if let Ok(mut pool) = buffer_pool().lock()
484 && pool.len() < 8
485 {
486 pool.push(buf);
487 }
488 }
489
490 /// Maximum bytes to read from an error response body (64 KB).
491 pub const ERROR_BODY_MAX_BYTES: usize = 64 * 1024;
492
493 /// Read an error response body with a size limit to prevent unbounded allocation.
494 pub async fn bounded_error_text(response: reqwest::Response, max_bytes: usize) -> String {
495 use futures_util::StreamExt;
496 let mut stream = response.bytes_stream();
497 let mut buf = Vec::with_capacity(max_bytes.min(8192));
498 while let Some(chunk) = stream.next().await {
499 let Ok(chunk) = chunk else { break };
500 let remaining = max_bytes.saturating_sub(buf.len());
501 if remaining == 0 {
502 break;
503 }
504 buf.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
505 }
506 String::from_utf8_lossy(&buf).into_owned()
507 }
508
509 pub(super) async fn read_bounded_response_bytes(
510 response: reqwest::Response,
511 max_bytes: usize,
512 ) -> anyhow::Result<Vec<u8>> {
513 use futures_util::StreamExt;
514 if response
515 .content_length()
516 .is_some_and(|len| len > max_bytes as u64)
517 {
518 anyhow::bail!("response body exceeds {max_bytes} byte limit");
519 }
520 let mut stream = response.bytes_stream();
521 let mut buf = Vec::with_capacity(max_bytes.min(8192));
522 while let Some(chunk) = stream.next().await {
523 let chunk = chunk?;
524 if buf.len().saturating_add(chunk.len()) > max_bytes {
525 anyhow::bail!("response body exceeds {max_bytes} byte limit");
526 }
527 buf.extend_from_slice(&chunk);
528 }
529 Ok(buf)
530 }
531
532 pub fn system_to_instructions(system: Option<SystemPrompt>) -> Option<String> {
533 match system {
534 Some(SystemPrompt::Text(text)) => Some(text),
535 Some(SystemPrompt::Blocks(blocks)) => {
536 let joined = blocks
537 .into_iter()
538 .map(|b| b.text)
539 .collect::<Vec<_>>()
540 .join("\n\n---\n\n");
541 if joined.trim().is_empty() {
542 None
543 } else {
544 Some(joined)
545 }
546 }
547 None => None,
548 }
549 }
550
551 /// Decode bare `x[0-9A-Fa-f]{6}` sequences (optionally followed by `-`)
552 /// that survive the standard delimiter-based pass. This handles cases
553 /// where the model strips or replaces the leading `-` of `-x00002E-`.
554 fn decode_bare_hex_escapes(input: &str) -> String {
555 use regex::Regex;
556 use std::sync::OnceLock;
557
558 static RE: OnceLock<Regex> = OnceLock::new();
559 let re = RE.get_or_init(|| Regex::new(r"x([0-9A-Fa-f]{6})-?").unwrap());
560
561 let result = re.replace_all(input, |caps: &regex::Captures| {
562 let hex = &caps[1];
563 if let Ok(code) = u32::from_str_radix(hex, 16)
564 && let Some(decoded) = std::char::from_u32(code)
565 {
566 // Only decode characters that to_api_tool_name would have encoded
567 if !decoded.is_ascii_alphanumeric() && decoded != '_' && decoded != '-' {
568 return decoded.to_string();
569 }
570 }
571 // Not a character we'd encode — leave as-is
572 caps[0].to_string()
573 });
574 result.into_owned()
575 }
576
577 #[cfg(test)]
578 mod tests {
579 use super::*;
580 use serde_json::json;
581
582 #[test]
583 fn tool_name_encoding_is_collision_free_for_hostile_names() {
584 let names = [
585 "web.run",
586 "web-x00002E-run",
587 "web--x00002E--run",
588 "webx00002Erun",
589 "web_x00002Erun",
590 "web_.run",
591 "a-b",
592 "a--b",
593 "a_b",
594 "a.b",
595 "ax00002Eb",
596 "a-x00002E-b",
597 "mcp__srv__tool.name",
598 "mcp__srv__tool-x00002E-name",
599 ];
600 let mut seen = std::collections::HashMap::new();
601 for name in names {
602 let encoded = to_api_tool_name(name);
603 assert!(
604 encoded
605 .chars()
606 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
607 "{encoded}"
608 );
609 if let Some(previous) = seen.insert(encoded.clone(), name) {
610 panic!("{previous} and {name} both encode to {encoded}");
611 }
612 assert_eq!(from_api_tool_name(&encoded), name, "round trip of {name}");
613 }
614 }
615
616 #[test]
617 fn tool_name_limit_follows_the_wire_unless_the_provider_documents_one() {
618 use ToolNameWire::{AnthropicMessages, OpenAiCompatible};
619 assert_eq!(
620 tool_name_limit(ProviderKind::Anthropic, AnthropicMessages),
621 128
622 );
623 assert_eq!(
624 tool_name_limit(ProviderKind::MinimaxAnthropic, AnthropicMessages),
625 128
626 );
627 assert_eq!(
628 tool_name_limit(
629 ProviderKind::ModelstudioTokenPlanAnthropic,
630 AnthropicMessages
631 ),
632 128
633 );
634 assert_eq!(
635 tool_name_limit(ProviderKind::Deepseek, OpenAiCompatible),
636 128
637 );
638 assert_eq!(
639 tool_name_limit(ProviderKind::DeepseekAnthropic, AnthropicMessages),
640 128
641 );
642 assert_eq!(tool_name_limit(ProviderKind::Openai, OpenAiCompatible), 64);
643 assert_eq!(tool_name_limit(ProviderKind::Minimax, OpenAiCompatible), 64);
644 assert_eq!(tool_name_limit(ProviderKind::Ollama, OpenAiCompatible), 128);
645 assert_eq!(
646 documented_tool_name_limit(ProviderKind::Ollama, OpenAiCompatible),
647 None
648 );
649 assert_eq!(
650 documented_tool_name_limit(ProviderKind::Custom, OpenAiCompatible),
651 None
652 );
653 }
654
655 #[test]
656 fn tool_name_limit_counts_the_encoded_form() {
657 let dotted = "mcp__tracker__projects.v2.issues.list-by-assignee";
658 assert!(dotted.len() <= 64);
659 assert!(tool_name_exceeds_limit(dotted, TOOL_NAME_LIMIT_64));
660 assert!(!tool_name_exceeds_limit(dotted, TOOL_NAME_LIMIT_128));
661 let plain = "a".repeat(64);
662 assert!(!tool_name_exceeds_limit(&plain, TOOL_NAME_LIMIT_64));
663 assert!(tool_name_exceeds_limit(
664 &format!("{plain}a"),
665 TOOL_NAME_LIMIT_64
666 ));
667 let message = over_limit_tool_name_message(dotted, TOOL_NAME_LIMIT_64);
668 assert!(
669 message.contains("at most 64") && message.contains(dotted),
670 "{message}"
671 );
672 }
673
674 #[test]
675 fn sse_line_limit_rejects_oversized_pending_complete_and_final_lines() {
676 let mut decoder = SseLineDecoder::new();
677 let at_limit = vec![b'x'; MAX_SSE_LINE_BYTES];
678 assert!(decoder.push(&at_limit).unwrap().is_empty());
679 let error = decoder
680 .push(b"x")
681 .expect_err("pending line exceeds the limit");
682 assert_eq!(error, SseLineError::TooLong);
683 assert!(error.to_string().contains("8 MiB"));
684 assert!(decoder.buffer.is_empty());
685
686 let mut complete = at_limit.clone();
687 complete.push(b'\n');
688 assert_eq!(
689 take_sse_line(&mut complete).unwrap().unwrap().len(),
690 MAX_SSE_LINE_BYTES
691 );
692 assert!(complete.is_empty());
693
694 let mut oversized = vec![b'x'; MAX_SSE_LINE_BYTES + 1];
695 assert_eq!(flush_sse_line(&mut oversized), Err(SseLineError::TooLong));
696 assert!(oversized.is_empty());
697 oversized.resize(MAX_SSE_LINE_BYTES + 1, b'x');
698 oversized.push(b'\n');
699 assert_eq!(
700 next_sse_line(&mut oversized, false),
701 Err(SseLineError::TooLong)
702 );
703 assert!(oversized.is_empty());
704
705 // The cap applies per line, not to a chunk containing several lines.
706 let mut multiple = at_limit;
707 multiple.extend_from_slice(b"\nnext\n");
708 assert!(next_sse_line(&mut multiple, false).unwrap().is_some());
709 assert_eq!(
710 next_sse_line(&mut multiple, false).unwrap().as_deref(),
711 Some("next")
712 );
713 }
714
715 #[test]
716 fn parse_usage_preserves_absent_cache_telemetry_and_explicit_zero() {
717 for payload in [
718 None,
719 Some(json!({})),
720 Some(json!({"prompt_tokens": 100, "completion_tokens": 20})),
721 ] {
722 let usage = parse_usage(payload.as_ref());
723 assert_eq!(usage.prompt_cache_hit_tokens, None);
724 assert_eq!(usage.prompt_cache_miss_tokens, None);
725 assert_eq!(usage.prompt_cache_write_tokens, None);
726 }
727 let zero = parse_usage(Some(&json!({
728 "prompt_tokens": 100,
729 "prompt_cache_hit_tokens": 0,
730 "prompt_cache_write_tokens": 0,
731 "prompt_tokens_details": {"cache_write_tokens": 75}
732 })));
733 assert_eq!(zero.prompt_cache_hit_tokens, Some(0));
734 assert_eq!(zero.prompt_cache_write_tokens, Some(0));
735 assert_eq!(zero.prompt_cache_miss_tokens, Some(100));
736 let explicit_miss = parse_usage(Some(&json!({
737 "prompt_tokens": 100,
738 "prompt_cache_miss_tokens": 0
739 })));
740 assert_eq!(explicit_miss.prompt_cache_miss_tokens, Some(0));
741 }
742
743 #[test]
744 fn parse_usage_cache_write_dialects_partition_the_input_total() {
745 for payload in [
746 json!({
747 "input_tokens": 1000,
748 "prompt_cache_hit_tokens": 600,
749 "prompt_cache_write_tokens": 200
750 }),
751 json!({
752 "prompt_tokens": 1000,
753 "prompt_tokens_details": {"cached_tokens": 600, "cache_write_tokens": 200}
754 }),
755 json!({
756 "input_tokens": 1000,
757 "prompt_cache_hit_tokens": 600,
758 "input_tokens_details": {"cache_write_tokens": 200}
759 }),
760 // Both objects can exist; the first lacks the write field.
761 json!({
762 "prompt_tokens": 1000,
763 "prompt_tokens_details": {"cached_tokens": 600},
764 "input_tokens_details": {"cache_write_tokens": 200}
765 }),
766 ] {
767 let usage = parse_usage(Some(&payload));
768 assert_eq!(usage.input_tokens, 1000);
769 assert_eq!(usage.prompt_cache_hit_tokens, Some(600));
770 assert_eq!(usage.prompt_cache_write_tokens, Some(200));
771 assert_eq!(usage.prompt_cache_miss_tokens, Some(200));
772 let priced = crate::pricing::token_usage_for_pricing(&usage);
773 assert_eq!(priced.cache_read, 600);
774 assert_eq!(priced.cache_write, 200);
775 assert_eq!(priced.input, 200);
776 assert_eq!(priced.input + priced.cache_read + priced.cache_write, 1000);
777 }
778 let write_only = parse_usage(Some(&json!({
779 "prompt_tokens": 1000,
780 "input_tokens_details": {"cache_write_tokens": 200}
781 })));
782 assert_eq!(write_only.prompt_cache_hit_tokens, None);
783 assert_eq!(write_only.prompt_cache_write_tokens, Some(200));
784 assert_eq!(write_only.prompt_cache_miss_tokens, Some(800));
785 }
786
787 #[test]
788 fn parse_usage_cache_write_saturates_and_keeps_explicit_miss() {
789 let excessive = parse_usage(Some(&json!({
790 "prompt_tokens": 100,
791 "prompt_cache_hit_tokens": 60,
792 "prompt_cache_write_tokens": u64::MAX
793 })));
794 assert_eq!(excessive.input_tokens, 100);
795 assert_eq!(excessive.prompt_cache_write_tokens, Some(u32::MAX));
796 assert_eq!(excessive.prompt_cache_miss_tokens, Some(0));
797 let explicit = parse_usage(Some(&json!({
798 "prompt_tokens": 100,
799 "prompt_cache_hit_tokens": 60,
800 "prompt_cache_write_tokens": 20,
801 "prompt_cache_miss_tokens": 10
802 })));
803 assert_eq!(explicit.prompt_cache_write_tokens, Some(20));
804 assert_eq!(explicit.prompt_cache_miss_tokens, Some(10));
805 }
806
807 #[test]
808 fn parse_usage_scenario() {
809 // Scenario consolidation of: parse_usage_reads_deepseek_cache_and_reasoning_tokens, parse_usage_saturates_every_u64_token_field, parse_usage_counts_reasoning_tokens_when_completion_tokens_are_zero, parse_usage_derives_completion_tokens_from_total_tokens_when_needed, parse_usage_reads_v4_prompt_tokens_details_cached_tokens, parse_usage_infers_cache_miss_from_selected_hit_source
810 // from parse_usage_reads_deepseek_cache_and_reasoning_tokens
811 {
812 let usage = parse_usage(Some(&json!({
813 "prompt_tokens": 100,
814 "completion_tokens": 20,
815 "prompt_cache_hit_tokens": 70,
816 "prompt_cache_miss_tokens": 30,
817 "completion_tokens_details": {
818 "reasoning_tokens": 12
819 }
820 })));
821
822 assert_eq!(usage.input_tokens, 100);
823 assert_eq!(usage.output_tokens, 20);
824 assert_eq!(usage.prompt_cache_hit_tokens, Some(70));
825 assert_eq!(usage.prompt_cache_miss_tokens, Some(30));
826 assert_eq!(usage.reasoning_tokens, Some(12));
827 }
828 // from parse_usage_saturates_every_u64_token_field
829 {
830 let usage = parse_usage(Some(&json!({
831 "input_tokens": u64::MAX,
832 "output_tokens": u64::MAX,
833 "prompt_cache_hit_tokens": u64::MAX,
834 "prompt_cache_miss_tokens": u64::MAX,
835 "completion_tokens_details": { "reasoning_tokens": u64::MAX },
836 "server_tool_use": {
837 "code_execution_requests": u64::MAX,
838 "tool_search_requests": u64::MAX
839 }
840 })));
841 assert_eq!(usage.input_tokens, u32::MAX);
842 assert_eq!(usage.output_tokens, u32::MAX);
843 assert_eq!(usage.prompt_cache_hit_tokens, Some(u32::MAX));
844 assert_eq!(usage.prompt_cache_miss_tokens, Some(u32::MAX));
845 assert_eq!(usage.reasoning_tokens, Some(u32::MAX));
846 let server = usage.server_tool_use.expect("server usage");
847 assert_eq!(server.code_execution_requests, Some(u32::MAX));
848 assert_eq!(server.tool_search_requests, Some(u32::MAX));
849 }
850 // from parse_usage_counts_reasoning_tokens_when_completion_tokens_are_zero
851 {
852 let usage = parse_usage(Some(&json!({
853 "prompt_tokens": 100,
854 "completion_tokens": 0,
855 "completion_tokens_details": {
856 "reasoning_tokens": 12
857 }
858 })));
859
860 assert_eq!(usage.input_tokens, 100);
861 assert_eq!(usage.output_tokens, 12);
862 assert_eq!(usage.reasoning_tokens, Some(12));
863 assert!(
864 crate::pricing::calculate_turn_cost_from_usage("deepseek-v4-pro", &usage)
865 .expect("DeepSeek V4 Pro pricing should apply")
866 > 0.0
867 );
868 }
869 // from parse_usage_derives_completion_tokens_from_total_tokens_when_needed
870 {
871 let usage = parse_usage(Some(&json!({
872 "prompt_tokens": 100,
873 "total_tokens": 125,
874 "prompt_cache_hit_tokens": 70,
875 "prompt_cache_miss_tokens": 30
876 })));
877
878 assert_eq!(usage.input_tokens, 100);
879 assert_eq!(usage.output_tokens, 25);
880 assert_eq!(usage.prompt_cache_hit_tokens, Some(70));
881 assert_eq!(usage.prompt_cache_miss_tokens, Some(30));
882 }
883 // from parse_usage_reads_v4_prompt_tokens_details_cached_tokens
884 {
885 let usage = parse_usage(Some(&json!({
886 "prompt_tokens": 4000,
887 "completion_tokens": 20,
888 "prompt_tokens_details": {
889 "cached_tokens": 3000
890 }
891 })));
892
893 assert_eq!(usage.input_tokens, 4000);
894 assert_eq!(usage.output_tokens, 20);
895 assert_eq!(usage.prompt_cache_hit_tokens, Some(3000));
896 assert_eq!(usage.prompt_cache_miss_tokens, Some(1000));
897 }
898 // from parse_usage_infers_cache_miss_from_selected_hit_source
899 {
900 let usage = parse_usage(Some(&json!({
901 "prompt_tokens": 4000,
902 "completion_tokens": 20,
903 "prompt_cache_hit_tokens": 3000,
904 "prompt_tokens_details": {
905 "cached_tokens": 1000
906 }
907 })));
908
909 assert_eq!(usage.input_tokens, 4000);
910 assert_eq!(usage.prompt_cache_hit_tokens, Some(3000));
911 assert_eq!(usage.prompt_cache_miss_tokens, Some(1000));
912 }
913 }
914
915 /// Real-shaped Chat-Completions usage payloads from the three providers most
916 /// likely to report reasoning tokens, carried end-to-end into pricing.
917 ///
918 /// Two invariants hold for every fixture: `reasoning_tokens <= output_tokens`,
919 /// and pricing never adds reasoning on top of output — dropping the reasoning
920 /// field entirely must not change the cost by a single cent.
921 #[test]
922 fn reasoning_parser_fixtures_never_exceed_or_add_to_billable_output() {
923 use crate::pricing::{calculate_turn_cost_estimate_for_provider, token_usage_for_pricing};
924 use codewhale_config::ProviderKind;
925
926 // (label, provider, model, payload)
927 let fixtures: [(&str, ProviderKind, &str, serde_json::Value); 3] = [
928 (
929 "moonshot",
930 ProviderKind::Moonshot,
931 "kimi-k2.7-code",
932 json!({
933 "prompt_tokens": 30_000,
934 "completion_tokens": 2_400,
935 "total_tokens": 32_400,
936 "prompt_tokens_details": { "cached_tokens": 24_000 },
937 "completion_tokens_details": { "reasoning_tokens": 1_900 }
938 }),
939 ),
940 (
941 "minimax",
942 ProviderKind::Minimax,
943 "minimax-m3",
944 json!({
945 "prompt_tokens": 12_000,
946 "completion_tokens": 3_000,
947 "total_tokens": 15_000,
948 "prompt_tokens_details": { "cached_tokens": 4_000 },
949 "completion_tokens_details": { "reasoning_tokens": 2_950 }
950 }),
951 ),
952 (
953 "openrouter",
954 ProviderKind::Openrouter,
955 "qwen/qwen3.7-plus",
956 json!({
957 "prompt_tokens": 8_000,
958 "completion_tokens": 1_500,
959 "total_tokens": 9_500,
960 "prompt_tokens_details": { "cached_tokens": 2_000 },
961 "completion_tokens_details": { "reasoning_tokens": 1_500 }
962 }),
963 ),
964 ];
965
966 for (label, provider, model, payload) in fixtures {
967 let usage = parse_usage(Some(&payload));
968 let reasoning = usage.reasoning_tokens.expect("fixture reports reasoning");
969
970 // Invariant 1: reasoning is a subset of the billed completion count.
971 assert!(
972 reasoning <= usage.output_tokens,
973 "{label}: reasoning {reasoning} exceeds output {}",
974 usage.output_tokens
975 );
976 // Billable output is exactly the reported completion count.
977 let classes = token_usage_for_pricing(&usage);
978 assert_eq!(
979 classes.output,
980 u64::from(usage.output_tokens),
981 "{label}: reasoning leaked into billable output"
982 );
983
984 // Invariant 2: pricing does not add reasoning a second time. The same
985 // usage with the reasoning field removed must cost the same.
986 let without = codewhale_models::Usage {
987 reasoning_tokens: None,
988 ..usage.clone()
989 };
990 assert_eq!(
991 calculate_turn_cost_estimate_for_provider(provider, model, &usage),
992 calculate_turn_cost_estimate_for_provider(provider, model, &without),
993 "{label}: reasoning changed the price"
994 );
995 }
996 }
997
998 /// A payload claiming more reasoning than output contradicts the subset
999 /// invariant. That is broken telemetry, so the field is discarded — and it
1000 /// must never become extra billable output.
1001 #[test]
1002 fn pathological_reasoning_above_output_is_rejected_not_billed() {
1003 let usage = parse_usage(Some(&json!({
1004 "prompt_tokens": 1_000,
1005 "completion_tokens": 100,
1006 "completion_tokens_details": { "reasoning_tokens": 5_000 }
1007 })));
1008
1009 assert_eq!(usage.output_tokens, 100, "output stays as reported");
1010 assert_eq!(
1011 usage.reasoning_tokens, None,
1012 "impossible reasoning telemetry is dropped rather than trusted"
1013 );
1014 let classes = crate::pricing::token_usage_for_pricing(&usage);
1015 assert_eq!(classes.output, 100);
1016
1017 // `completion_tokens: 0` with reasoning present is the *legitimate*
1018 // shape this filter must not break: providers that report only reasoning
1019 // set output from it, keeping reasoning == output.
1020 let zero_output = parse_usage(Some(&json!({
1021 "prompt_tokens": 1_000,
1022 "completion_tokens": 0,
1023 "completion_tokens_details": { "reasoning_tokens": 12 }
1024 })));
1025 assert_eq!(zero_output.output_tokens, 12);
1026 assert_eq!(zero_output.reasoning_tokens, Some(12));
1027 }
1028
1029 fn mid_char_split(text: &str, ch: char) -> usize {
1030 let needle = ch.to_string();
1031 let start = text
1032 .as_bytes()
1033 .windows(needle.len())
1034 .position(|window| window == needle.as_bytes())
1035 .unwrap_or_else(|| panic!("{ch:?} present in {text:?}"));
1036 start + 1
1037 }
1038
1039 #[test]
1040 fn take_sse_scenario() {
1041 // Scenario consolidation of: take_sse_line_preserves_multibyte_split_across_reads, take_sse_line_returns_none_without_newline, take_sse_line_reassembles_cjk_and_rejects_invalid_bytes, take_sse_line_rejects_invalid_bytes_without_replacement
1042 // from take_sse_line_preserves_multibyte_split_across_reads
1043 {
1044 // "你好" streamed so the 3-byte '好' straddles a read boundary.
1045 let full = "data: 你好\n";
1046 let bytes = full.as_bytes();
1047 let split = mid_char_split(full, '好');
1048 let mut buffer: Vec<u8> = Vec::new();
1049 // First read: no complete line yet.
1050 buffer.extend_from_slice(&bytes[..split]);
1051 assert_eq!(take_sse_line(&mut buffer).expect("valid prefix"), None);
1052 // Second read completes the line; '好' must be intact, not U+FFFD.
1053 buffer.extend_from_slice(&bytes[split..]);
1054 let line = take_sse_line(&mut buffer)
1055 .expect("valid utf-8")
1056 .expect("a complete line");
1057 assert_eq!(line, "data: 你好");
1058 assert!(!line.contains('\u{FFFD}'), "multibyte char was corrupted");
1059 assert_eq!(extract_sse_data_value(&line), Some("你好"));
1060 // Buffer fully drained.
1061 assert!(buffer.is_empty());
1062 }
1063 // from take_sse_line_returns_none_without_newline
1064 {
1065 let mut buffer = b"data: partial".to_vec();
1066 assert_eq!(take_sse_line(&mut buffer).expect("valid utf-8"), None);
1067 assert_eq!(buffer, b"data: partial");
1068 }
1069 // from take_sse_line_reassembles_cjk_and_rejects_invalid_bytes
1070 {
1071 let full = "data: 测试中文\n";
1072 let split = mid_char_split(full, '试');
1073 let mut buffer = full.as_bytes()[..split].to_vec();
1074 assert_eq!(take_sse_line(&mut buffer).expect("valid prefix"), None);
1075 buffer.extend_from_slice(&full.as_bytes()[split..]);
1076 let line = take_sse_line(&mut buffer)
1077 .expect("valid utf-8")
1078 .expect("complete line");
1079 assert_eq!(line, "data: 测试中文");
1080 assert!(!line.contains('\u{FFFD}'));
1081
1082 let mut invalid = b"data: ok".to_vec();
1083 invalid.push(0xFF);
1084 invalid.push(b'\n');
1085 let err = take_sse_line(&mut invalid).expect_err("invalid bytes must fail closed");
1086 assert!(!err.to_string().contains('\u{FFFD}'));
1087 assert_eq!(err, SseLineError::InvalidUtf8 { valid_up_to: 8 });
1088 assert!(
1089 invalid.is_empty(),
1090 "invalid line is consumed so retries cannot loop"
1091 );
1092 }
1093 // from take_sse_line_rejects_invalid_bytes_without_replacement
1094 {
1095 let mut buffer = b"data: ok".to_vec();
1096 buffer.push(0xFF);
1097 buffer.extend_from_slice(b"\n");
1098 let err = take_sse_line(&mut buffer).expect_err("0xFF is not UTF-8");
1099 assert_eq!(err, SseLineError::InvalidUtf8 { valid_up_to: 8 });
1100 assert!(!err.to_string().contains('\u{FFFD}'));
1101 assert!(buffer.is_empty(), "invalid line must be drained");
1102 }
1103 }
1104
1105 #[test]
1106 fn flush_sse_scenario() {
1107 // Scenario consolidation of: flush_sse_line_reassembles_cjk_and_rejects_invalid_bytes, flush_sse_line_preserves_unterminated_cjk, flush_sse_line_rejects_truncated_multibyte_sequence
1108 // from flush_sse_line_reassembles_cjk_and_rejects_invalid_bytes
1109 {
1110 let text = "data: 你好世界";
1111 let split = mid_char_split(text, '好');
1112 let mut buffer = text.as_bytes()[..split].to_vec();
1113 assert_eq!(take_sse_line(&mut buffer).expect("no newline yet"), None);
1114 buffer.extend_from_slice(&text.as_bytes()[split..]);
1115 let line = flush_sse_line(&mut buffer)
1116 .expect("valid utf-8")
1117 .expect("unterminated tail");
1118 assert_eq!(line, "data: 你好世界");
1119 assert!(!line.contains('\u{FFFD}'));
1120 assert!(buffer.is_empty());
1121 assert_eq!(flush_sse_line(&mut buffer).expect("empty"), None);
1122
1123 let mut invalid = vec![0x80, 0xBF];
1124 let err = flush_sse_line(&mut invalid).expect_err("invalid flush must fail closed");
1125 assert!(!err.to_string().contains('\u{FFFD}'));
1126 assert_eq!(err, SseLineError::InvalidUtf8 { valid_up_to: 0 });
1127 assert!(invalid.is_empty());
1128 }
1129 // from flush_sse_line_preserves_unterminated_cjk
1130 {
1131 let mut buffer = "data: 你好".as_bytes().to_vec();
1132 let line = flush_sse_line(&mut buffer)
1133 .expect("valid utf-8")
1134 .expect("residual line");
1135 assert_eq!(line, "data: 你好");
1136 assert!(!line.contains('\u{FFFD}'));
1137 assert!(buffer.is_empty());
1138 }
1139 // from flush_sse_line_rejects_truncated_multibyte_sequence
1140 {
1141 let mut buffer = "data: ".as_bytes().to_vec();
1142 buffer.extend_from_slice(&"好".as_bytes()[..2]);
1143 let err = flush_sse_line(&mut buffer).expect_err("truncated UTF-8");
1144 assert_eq!(err, SseLineError::InvalidUtf8 { valid_up_to: 6 });
1145 assert!(!err.to_string().contains('\u{FFFD}'));
1146 assert!(buffer.is_empty());
1147 }
1148 }
1149
1150 #[test]
1151 fn decode_sse_line_bytes_rejects_invalid_without_replacement() {
1152 let ok = decode_sse_line_bytes("data: 你好".as_bytes()).expect("valid");
1153 assert_eq!(ok, "data: 你好");
1154 assert!(!ok.contains('\u{FFFD}'));
1155
1156 let err = decode_sse_line_bytes(&[0xFF]).expect_err("bare 0xFF is invalid");
1157 assert!(!err.to_string().contains('\u{FFFD}'));
1158 assert_eq!(err, SseLineError::InvalidUtf8 { valid_up_to: 0 });
1159 }
1160
1161 #[test]
1162 fn extract_sse_scenario() {
1163 // Scenario consolidation of: extract_sse_data_value_accepts_optional_space, extract_sse_data_value_handles_done_marker, extract_sse_data_value_rejects_non_data_lines
1164 // from extract_sse_data_value_accepts_optional_space
1165 {
1166 assert_eq!(
1167 extract_sse_data_value("data: {\"ok\":true}"),
1168 Some("{\"ok\":true}")
1169 );
1170 assert_eq!(
1171 extract_sse_data_value("data:{\"ok\":true}"),
1172 Some("{\"ok\":true}")
1173 );
1174 }
1175 // from extract_sse_data_value_handles_done_marker
1176 {
1177 assert_eq!(extract_sse_data_value("data: [DONE]"), Some("[DONE]"));
1178 assert_eq!(extract_sse_data_value("data:[DONE]"), Some("[DONE]"));
1179 }
1180 // from extract_sse_data_value_rejects_non_data_lines
1181 {
1182 assert_eq!(extract_sse_data_value("event: message"), None);
1183 assert_eq!(extract_sse_data_value(": heartbeat"), None);
1184 }
1185 }
1186
1187 #[test]
1188 fn parse_usage_extracts_deepseek_server_tool_and_safety_counters() {
1189 let usage = parse_usage(Some(&serde_json::json!({
1190 "prompt_tokens": 120,
1191 "completion_tokens": 40,
1192 "completion_tokens_details": {
1193 "reasoning_tokens": 10,
1194 "safety_tokens": 6
1195 },
1196 "server_tool_use": {
1197 "tool_search": 2,
1198 "tool_fetch": 1,
1199 "tool_image_search": 3,
1200 "web_search_requests": 2,
1201 "web_fetch_requests": 1
1202 }
1203 })));
1204 assert_eq!(usage.input_tokens, 120);
1205 assert_eq!(usage.output_tokens, 40);
1206 assert_eq!(usage.reasoning_tokens, Some(10));
1207 assert_eq!(usage.safety_tokens, Some(6));
1208 let server = usage.server_tool_use.expect("server_tool_use");
1209 assert_eq!(server.tool_search, Some(2));
1210 assert_eq!(server.tool_fetch, Some(1));
1211 assert_eq!(server.tool_image_search, Some(3));
1212 assert_eq!(server.web_search_requests, Some(2));
1213 assert_eq!(server.web_fetch_requests, Some(1));
1214 }
1215 }
1216
1216 lines RUST