返回 CodeWhale
test_cases_05.rs
根目录 / crates / engine / src / client / test_cases_05.rs
1
2 /// #5055: the Chat and Responses DeepSeek mappings are two spellings of
3 /// one table. If they ever disagree, one of them was edited alone.
4 #[test]
5 fn deepseek_chat_and_responses_wires_agree_with_the_shared_effort_table() {
6 use super::deepseek_effort::{DEEPSEEK_EFFORT_ALIASES, deepseek_effort_tier};
7
8 for &(alias, tier) in DEEPSEEK_EFFORT_ALIASES {
9 for provider in [ProviderKind::Deepseek, ProviderKind::Deepseek] {
10 let mut body = json!({});
11 apply_reasoning_effort(&mut body, Some(alias), provider);
12 assert_eq!(
13 body.get("reasoning_effort").and_then(Value::as_str),
14 tier.chat_reasoning_effort(),
15 "chat wire disagrees with the table for {alias:?} on {provider:?}"
16 );
17 assert_eq!(
18 body.pointer("/thinking/type").and_then(Value::as_str),
19 Some(if tier.chat_thinking_enabled() {
20 "enabled"
21 } else {
22 "disabled"
23 }),
24 "chat thinking toggle disagrees with the table for {alias:?}"
25 );
26 }
27
28 assert_eq!(
29 super::responses::responses_reasoning_effort(alias, true),
30 Some(tier.responses_effort()),
31 "responses wire disagrees with the table for {alias:?}"
32 );
33 }
34
35 // Auto leaves the tier to the provider on both wires.
36 assert_eq!(deepseek_effort_tier("auto"), None);
37 let mut body = json!({});
38 apply_reasoning_effort(&mut body, Some("auto"), ProviderKind::Deepseek);
39 assert_eq!(body, json!({}));
40 assert_eq!(
41 super::responses::responses_reasoning_effort("auto", true),
42 None
43 );
44 }
45
46 async fn capture_deepseek_chat_body_for_effort(
47 effort: Option<&str>,
48 custom: bool,
49 stream: bool,
50 ) -> Value {
51 let server = MockServer::start().await;
52 let model = if custom {
53 "deepseek/deepseek-v4.1-flash"
54 } else {
55 "deepseek-v4-pro"
56 };
57 let response = if stream {
58 ResponseTemplate::new(200)
59 .insert_header("content-type", "text/event-stream")
60 .set_body_string(format!(
61 "data: {}\n\ndata: [DONE]\n\n",
62 json!({
63 "id": "chatcmpl-deepseek-effort-ladder",
64 "object": "chat.completion.chunk",
65 "model": model,
66 "choices": [{
67 "index": 0,
68 "delta": {"content": "ok"},
69 "finish_reason": "stop"
70 }],
71 "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
72 })
73 ))
74 } else {
75 ResponseTemplate::new(200).set_body_json(json!({
76 "id": "chatcmpl-deepseek-effort-ladder",
77 "object": "chat.completion",
78 "model": model,
79 "choices": [{
80 "index": 0,
81 "message": {"role": "assistant", "content": "ok"},
82 "finish_reason": "stop"
83 }],
84 "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
85 }))
86 };
87 Mock::given(method("POST"))
88 .respond_with(response)
89 .expect(1)
90 .mount(&server)
91 .await;
92
93 let request = MessageRequest {
94 model: model.to_string(),
95 messages: vec![Message {
96 role: Role::User,
97 content: vec![ContentBlock::Text {
98 text: "effort ladder capture".to_string(),
99 cache_control: None,
100 }],
101 }],
102 max_tokens: 64,
103 system: None,
104 tools: None,
105 tool_choice: None,
106 metadata: None,
107 thinking: None,
108 reasoning_effort: effort.map(|effort| {
109 crate::reasoning_preference::ReasoningEffort::parse_strict(effort)
110 .expect("valid capture effort")
111 .as_setting_for_route(
112 ProviderKind::Deepseek,
113 &server.uri(),
114 model,
115 )
116 .to_string()
117 }),
118 stream: Some(stream),
119 temperature: None,
120 top_p: None,
121 safety_check: None,
122 title: None,
123 };
124 let client = if custom {
125 custom_mock_client_for_identity(&server, "aicraft")
126 } else {
127 deepseek_request_boundary_client(codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL, server.uri())
128 };
129 if stream {
130 let mut events = client
131 .create_message_stream(request)
132 .await
133 .expect("streaming request succeeds");
134 while let Some(event) = events.next().await {
135 event.expect("streaming event succeeds");
136 }
137 } else {
138 client
139 .create_message(request)
140 .await
141 .unwrap_or_else(|error| panic!("custom={custom} effort={effort:?}: {error}"));
142 }
143
144 let requests = server.received_requests().await.expect("recorded request");
145 assert_eq!(requests.len(), 1);
146 serde_json::from_slice(&requests[0].body).expect("captured request JSON")
147 }
148
149 /// Request-body capture per effort level on direct and custom DeepSeek chat
150 /// route: the wire must carry the documented low/high/max ladder, never an
151 /// invented value (#52). Only the `deepseek`-shaped route carries the
152 /// `thinking` toggle; a gateway borrows the effort spelling and expresses
153 /// `off` as `none`.
154 #[tokio::test]
155 async fn deepseek_chat_wire_body_tracks_the_documented_effort_ladder() {
156 for (effort, expected_effort, expected_thinking, gateway_effort) in [
157 (Some("low"), Some("low"), Some("enabled"), Some("low")),
158 (Some("medium"), Some("high"), Some("enabled"), Some("high")),
159 (Some("high"), Some("high"), Some("enabled"), Some("high")),
160 (Some("max"), Some("max"), Some("enabled"), Some("max")),
161 (Some("off"), None, Some("disabled"), Some("none")),
162 (None, None, None, None),
163 ] {
164 for (custom, stream) in [(false, false), (false, true), (true, false), (true, true)] {
165 let body = capture_deepseek_chat_body_for_effort(effort, custom, stream).await;
166 assert_eq!(body["max_tokens"], 64);
167 assert_eq!(
168 body.get("reasoning_effort").and_then(Value::as_str),
169 if custom { gateway_effort } else { expected_effort },
170 "reasoning_effort on the wire for {effort:?} (custom={custom}): {body}"
171 );
172 let expected_toggle = if custom { None } else { expected_thinking };
173 assert_eq!(
174 body.pointer("/thinking/type").and_then(Value::as_str),
175 expected_toggle,
176 "thinking on the wire for {effort:?} (custom={custom}): {body}"
177 );
178 }
179 }
180 }
181
182 /// TelecomJS TokenHub: the gateway's OpenAI Chat Completions API does NOT
183 /// support `reasoning_effort` or `thinking` fields (#4188 review). Verify
184 /// that no reasoning fields are injected for any effort level, since not
185 /// every gateway model (qwen-max, deepseek-chat, gpt-4o, claude, etc.)
186 /// accepts the same reasoning dialect.
187 #[test]
188 fn reasoning_effort_telecomjs_does_not_inject_reasoning_fields() {
189 for effort in &["off", "low", "medium", "high", "max", "xhigh"] {
190 let mut body = json!({});
191 apply_reasoning_effort(&mut body, Some(effort), ProviderKind::Telecomjs);
192 assert!(
193 body.get("reasoning_effort").is_none(),
194 "TelecomJS must not inject reasoning_effort for effort={effort}: {body}"
195 );
196 assert!(
197 body.get("thinking").is_none(),
198 "TelecomJS must not inject thinking for effort={effort}: {body}"
199 );
200 assert!(
201 body.get("think").is_none(),
202 "TelecomJS must not inject think for effort={effort}: {body}"
203 );
204 }
205 }
206
207 #[test]
208 fn moonshot_uses_codewhale_user_agent_not_kimi_cli_identity() {
209 let user_agent = client_user_agent(ProviderKind::Moonshot);
210
211 assert!(user_agent.contains("codewhale/"));
212 assert!(!user_agent.to_ascii_lowercase().contains("kimi_cli"));
213 assert!(!user_agent.to_ascii_lowercase().contains("kimi-code-cli"));
214 }
215
216 #[test]
217 fn reasoning_effort_scenario_2() {
218 // Scenario consolidation of: reasoning_effort_ollama_cloud_uses_openai_compatible_field, reasoning_effort_uses_nvidia_nim_chat_template_kwargs, reasoning_effort_off_disables_nvidia_nim_thinking, reasoning_effort_uses_openai_compatible_shape_for_fireworks, reasoning_effort_uses_arcee_reasoning_effort_without_thinking_object, reasoning_effort_maps_openrouter_scale_without_deepseek_max_label, reasoning_effort_uses_xiaomi_mimo_thinking_parameter_only, reasoning_effort_zai_uses_documented_thinking_shape
219 // from reasoning_effort_ollama_cloud_uses_openai_compatible_field
220 {
221 for (effort, expected) in [
222 ("off", "none"),
223 ("low", "low"),
224 ("medium", "medium"),
225 ("high", "high"),
226 ("max", "max"),
227 ] {
228 let mut body = json!({});
229 apply_reasoning_effort(&mut body, Some(effort), ProviderKind::OllamaCloud);
230 assert_eq!(body, json!({ "reasoning_effort": expected }));
231 }
232
233 let mut local = json!({});
234 apply_reasoning_effort(&mut local, Some("high"), ProviderKind::Ollama);
235 assert_eq!(local, json!({ "think": true }));
236 }
237 // from reasoning_effort_uses_nvidia_nim_chat_template_kwargs
238 {
239 let mut body = json!({});
240 apply_reasoning_effort(&mut body, Some("max"), ProviderKind::NvidiaNim);
241
242 assert_eq!(
243 body.pointer("/chat_template_kwargs/thinking")
244 .and_then(Value::as_bool),
245 Some(true)
246 );
247 assert_eq!(
248 body.pointer("/chat_template_kwargs/reasoning_effort")
249 .and_then(Value::as_str),
250 Some("max")
251 );
252 assert!(body.get("thinking").is_none());
253 assert!(body.get("reasoning_effort").is_none());
254 }
255 // from reasoning_effort_off_disables_nvidia_nim_thinking
256 {
257 let mut body = json!({});
258 apply_reasoning_effort(&mut body, Some("off"), ProviderKind::NvidiaNim);
259
260 assert_eq!(
261 body.pointer("/chat_template_kwargs/thinking")
262 .and_then(Value::as_bool),
263 Some(false)
264 );
265 assert!(
266 body.pointer("/chat_template_kwargs/reasoning_effort")
267 .is_none()
268 );
269 }
270 // from reasoning_effort_uses_openai_compatible_shape_for_fireworks
271 {
272 let mut body = json!({});
273 apply_reasoning_effort(&mut body, Some("max"), ProviderKind::Fireworks);
274
275 assert_eq!(
276 body.get("reasoning_effort").and_then(Value::as_str),
277 Some("max")
278 );
279 assert!(
280 body.get("thinking").is_none(),
281 "Fireworks strict-validates OpenAI-compatible requests and rejects top-level thinking"
282 );
283 }
284 // from reasoning_effort_uses_arcee_reasoning_effort_without_thinking_object
285 {
286 for (input, expected) in [
287 ("minimal", "minimal"),
288 ("low", "low"),
289 ("mid", "medium"),
290 ("medium", "medium"),
291 ("high", "high"),
292 ("max", "high"),
293 ] {
294 let mut body = json!({});
295 apply_reasoning_effort(&mut body, Some(input), ProviderKind::Arcee);
296
297 assert_eq!(
298 body.get("reasoning_effort").and_then(Value::as_str),
299 Some(expected)
300 );
301 assert!(
302 body.get("thinking").is_none(),
303 "Arcee documents reasoning_effort rather than a DeepSeek thinking object"
304 );
305 }
306 }
307 // from reasoning_effort_maps_openrouter_scale_without_deepseek_max_label
308 {
309 for (input, expected) in [
310 ("low", "low"),
311 ("minimal", "low"),
312 ("medium", "medium"),
313 ("mid", "medium"),
314 ("high", "high"),
315 ("max", "xhigh"),
316 ("xhigh", "xhigh"),
317 ] {
318 let mut body = json!({});
319 apply_reasoning_effort(&mut body, Some(input), ProviderKind::Openrouter);
320
321 assert_eq!(
322 body.get("reasoning_effort").and_then(Value::as_str),
323 Some(expected),
324 "OpenRouter effort mapping for {input}"
325 );
326 assert_eq!(
327 body.pointer("/thinking/type").and_then(Value::as_str),
328 Some("enabled")
329 );
330 }
331 let published_no_xhigh = [json!({"type": "effort", "values": ["low", "medium", "high"]})];
332 let mut clamped = json!({});
333 super::reasoning_effort::apply_reasoning_effort_with_options(
334 &mut clamped,
335 Some("max"),
336 ProviderKind::Openrouter,
337 Some(&published_no_xhigh),
338 );
339 assert_eq!(
340 clamped.get("reasoning_effort").and_then(Value::as_str),
341 Some("high")
342 );
343 }
344 // from reasoning_effort_uses_xiaomi_mimo_thinking_parameter_only
345 {
346 for input in ["low", "medium", "max", "xhigh"] {
347 let mut body = json!({});
348 apply_reasoning_effort(&mut body, Some(input), ProviderKind::XiaomiMimo);
349
350 assert_eq!(
351 body.pointer("/thinking/type").and_then(Value::as_str),
352 Some("enabled"),
353 "MiMo thinking mapping for {input}"
354 );
355 assert!(body.get("reasoning_effort").is_none());
356 }
357
358 let mut body = json!({});
359 apply_reasoning_effort(&mut body, Some("off"), ProviderKind::XiaomiMimo);
360 assert_eq!(
361 body.pointer("/thinking/type").and_then(Value::as_str),
362 Some("disabled")
363 );
364 assert!(body.get("reasoning_effort").is_none());
365 }
366 // from reasoning_effort_zai_uses_documented_thinking_shape
367 {
368 let mut body = json!({});
369 apply_reasoning_effort(&mut body, Some("high"), ProviderKind::Zai);
370 assert_eq!(
371 body,
372 json!({ "thinking": { "type": "enabled", "clear_thinking": false } })
373 );
374
375 let mut body = json!({});
376 apply_reasoning_effort(&mut body, Some("max"), ProviderKind::Zai);
377 assert_eq!(
378 body,
379 json!({ "thinking": { "type": "enabled", "clear_thinking": false } })
380 );
381
382 let mut body = json!({});
383 apply_reasoning_effort(&mut body, Some("ultracode"), ProviderKind::Zai);
384 assert_eq!(
385 body,
386 json!({ "thinking": { "type": "enabled", "clear_thinking": false } })
387 );
388
389 let mut body = json!({});
390 apply_reasoning_effort(&mut body, Some("off"), ProviderKind::Zai);
391 assert_eq!(body, json!({ "thinking": { "type": "disabled" } }));
392 }
393 }
394
395 #[test]
396 fn reasoning_effort_minimax_requires_exact_route_to_split_reasoning() {
397 let mut body = json!({});
398 chat::apply_route_reasoning_controls(
399 &mut body,
400 ProviderKind::Minimax,
401 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_BASE_URL,
402 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL,
403 Some("high"),
404 );
405 assert_eq!(
406 body.get("reasoning_split").and_then(Value::as_bool),
407 Some(true)
408 );
409 assert_eq!(
410 body.pointer("/thinking/type").and_then(Value::as_str),
411 Some("adaptive")
412 );
413 assert!(body.get("reasoning_effort").is_none());
414
415 let mut body = json!({});
416 chat::apply_route_reasoning_controls(
417 &mut body,
418 ProviderKind::Minimax,
419 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_BASE_URL,
420 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL,
421 Some("max"),
422 );
423 assert_eq!(
424 body.pointer("/thinking/type").and_then(Value::as_str),
425 Some("adaptive")
426 );
427 assert!(body.get("reasoning_effort").is_none());
428
429 let mut body = json!({});
430 chat::apply_route_reasoning_controls(
431 &mut body,
432 ProviderKind::Minimax,
433 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_BASE_URL,
434 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL,
435 Some("off"),
436 );
437 assert_eq!(
438 body.get("reasoning_split").and_then(Value::as_bool),
439 Some(true)
440 );
441 assert_eq!(
442 body.pointer("/thinking/type").and_then(Value::as_str),
443 Some("disabled")
444 );
445
446 let mut body = json!({});
447 chat::apply_route_reasoning_controls(
448 &mut body,
449 ProviderKind::Minimax,
450 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_BASE_URL,
451 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL,
452 None,
453 );
454 assert_eq!(body, json!({ "reasoning_split": true }));
455
456 for (base_url, model) in [
457 (
458 "https://gateway.example/v1",
459 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL,
460 ),
461 (codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_BASE_URL, "MiniMax-M2"),
462 ] {
463 for effort in ["off", "high", "max"] {
464 let mut body = json!({});
465 chat::apply_route_reasoning_controls(
466 &mut body,
467 ProviderKind::Minimax,
468 base_url,
469 model,
470 Some(effort),
471 );
472 assert_eq!(body, json!({}), "{base_url} {model} {effort}");
473 }
474 }
475
476 let mut flash_body = json!({});
477 chat::apply_route_reasoning_controls(
478 &mut flash_body,
479 ProviderKind::Minimax,
480 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_BASE_URL,
481 "MiniMax-M3.1-Flash",
482 Some("high"),
483 );
484 assert_eq!(
485 flash_body.get("reasoning_split").and_then(Value::as_bool),
486 Some(true)
487 );
488 assert_eq!(
489 flash_body.pointer("/thinking/type").and_then(Value::as_str),
490 Some("adaptive")
491 );
492 assert_eq!(
493 flash_body.get("reasoning_effort").and_then(Value::as_str),
494 Some("high")
495 );
496 }
497
498 #[test]
499 fn chat_parser_accepts_nvidia_nim_reasoning_field() -> Result<()> {
500 let response = parse_chat_message(&json!({
501 "id": "chatcmpl-test",
502 "model": "deepseek-ai/deepseek-v4-pro",
503 "choices": [{
504 "message": {
505 "role": "assistant",
506 "reasoning": "thinking via NIM",
507 "content": "final answer"
508 },
509 "finish_reason": "stop"
510 }],
511 "usage": {
512 "prompt_tokens": 10,
513 "completion_tokens": 3
514 }
515 }))?;
516
517 assert!(matches!(
518 response.content.first(),
519 Some(ContentBlock::Thinking { thinking, .. }) if thinking == "thinking via NIM"
520 ));
521 assert!(matches!(
522 response.content.get(1),
523 Some(ContentBlock::Text { text, .. }) if text == "final answer"
524 ));
525 Ok(())
526 }
527
528 #[test]
529 fn sse_parser_accepts_nvidia_nim_reasoning_delta() {
530 let mut content_index = 0;
531 let mut text_started = false;
532 let mut thinking_started = false;
533 let mut tool_indices = super::chat::ChatToolStream::default();
534 let mut reasoning_detail_buffers = std::collections::HashMap::new();
535 let events = parse_sse_chunk(
536 &json!({
537 "choices": [{
538 "delta": {
539 "reasoning": "nim thought"
540 }
541 }]
542 }),
543 &mut content_index,
544 &mut text_started,
545 &mut thinking_started,
546 &mut tool_indices,
547 &mut reasoning_detail_buffers,
548 true,
549 );
550
551 assert!(events.iter().any(|event| matches!(
552 event,
553 StreamEvent::ContentBlockDelta {
554 delta: Delta::ThinkingDelta { thinking },
555 ..
556 } if thinking == "nim thought"
557 )));
558 }
559
560 #[test]
561 fn chat_tool_scenario() {
562 // Scenario consolidation of: chat_tool_strict_flag_is_nested_under_function, chat_tool_wire_shape_omits_anthropic_only_metadata
563 // from chat_tool_strict_flag_is_nested_under_function
564 {
565 let tool = Tool {
566 tool_type: Some("function".to_string()),
567 name: "emit_json".to_string(),
568 description: "Emit JSON".to_string(),
569 input_schema: json!({"type": "object", "properties": {}}),
570 allowed_callers: None,
571 defer_loading: None,
572 input_examples: None,
573 strict: Some(true),
574 cache_control: None,
575 };
576 let encoded = super::chat::build_chat_wire_body(
577 &MessageRequest {
578 model: "fixture".to_string(),
579 tools: Some(vec![tool]),
580 messages: vec![], max_tokens: 64, system: None, tool_choice: None,
581 metadata: None, thinking: None, reasoning_effort: None, stream: None,
582 temperature: None, top_p: None,
583 safety_check: None,
584 title: None,
585 },
586 ProviderKind::Openai, "https://api.openai.com/v1", false, None,
587 ).expect("chat projection").body["tools"][0].clone();
588 assert_eq!(
589 encoded
590 .get("function")
591 .and_then(|function| function.get("strict"))
592 .and_then(Value::as_bool),
593 Some(true)
594 );
595 assert!(encoded.get("strict").is_none());
596 }
597 // from chat_tool_wire_shape_omits_anthropic_only_metadata
598 {
599 let tool = Tool {
600 tool_type: Some("function".to_string()),
601 name: "mcp_read_resource".to_string(),
602 description: "Read resource".to_string(),
603 input_schema: json!({"type": "object", "properties": {}}),
604 allowed_callers: Some(vec!["direct".to_string()]),
605 defer_loading: Some(false),
606 input_examples: Some(vec![json!({"uri": "file://example"})]),
607 strict: None,
608 cache_control: None,
609 };
610
611 let encoded = super::chat::build_chat_wire_body(
612 &MessageRequest {
613 model: "fixture".to_string(),
614 tools: Some(vec![tool.clone()]),
615 messages: vec![], max_tokens: 64, system: None, tool_choice: None,
616 metadata: None, thinking: None, reasoning_effort: None, stream: None,
617 temperature: None, top_p: None,
618 safety_check: None,
619 title: None,
620 },
621 ProviderKind::Openai, "https://api.fireworks.ai/inference/v1", false, None,
622 ).expect("chat projection").body["tools"][0].clone();
623
624 assert!(encoded.get("allowed_callers").is_none());
625 assert!(encoded.get("defer_loading").is_none());
626 assert!(encoded.get("input_examples").is_none());
627 }
628 }
629
630 #[test]
631 fn deepseek_non_beta_base_url_strips_strict_tool_flag() {
632 let tool = Tool {
633 tool_type: Some("function".to_string()),
634 name: "emit_json".to_string(),
635 description: "Emit JSON".to_string(),
636 input_schema: json!({"type": "object", "properties": {}}),
637 allowed_callers: None,
638 defer_loading: None,
639 input_examples: None,
640 strict: Some(true),
641 cache_control: None,
642 };
643
644 let encoded = super::chat::build_chat_wire_body(
645 &MessageRequest {
646 model: "fixture".to_string(),
647 tools: Some(vec![tool.clone()]),
648 messages: vec![], max_tokens: 64, system: None, tool_choice: None,
649 metadata: None, thinking: None, reasoning_effort: None, stream: None,
650 temperature: None, top_p: None,
651 safety_check: None,
652 title: None,
653 },
654 ProviderKind::Openai, "https://api.deepseek.com/v1", false, None,
655 ).expect("chat projection").body["tools"][0].clone();
656
657 assert!(
658 encoded
659 .get("function")
660 .and_then(|function| function.get("strict"))
661 .is_none()
662 );
663 }
664
665 #[test]
666 fn deepseek_beta_and_custom_base_urls_keep_strict_tool_flag() {
667 let tool = Tool {
668 tool_type: Some("function".to_string()),
669 name: "emit_json".to_string(),
670 description: "Emit JSON".to_string(),
671 input_schema: json!({"type": "object", "properties": {}}),
672 allowed_callers: None,
673 defer_loading: None,
674 input_examples: None,
675 strict: Some(true),
676 cache_control: None,
677 };
678
679 for base_url in [
680 "https://api.deepseek.com/beta",
681 "https://example.com/openai/v1",
682 ] {
683 let encoded = super::chat::build_chat_wire_body(
684 &MessageRequest {
685 model: "fixture".to_string(),
686 tools: Some(vec![tool.clone()]),
687 messages: vec![], max_tokens: 64, system: None, tool_choice: None,
688 metadata: None, thinking: None, reasoning_effort: None, stream: None,
689 temperature: None, top_p: None,
690 safety_check: None,
691 title: None,
692 },
693 ProviderKind::Openai, base_url, false, None,
694 ).expect("chat projection").body["tools"][0].clone();
695 assert_eq!(
696 encoded
697 .get("function")
698 .and_then(|function| function.get("strict"))
699 .and_then(Value::as_bool),
700 Some(true)
701 );
702 }
703 }
704
705 #[test]
706 fn chat_messages_scenario() {
707 // Scenario consolidation of: chat_messages_drop_thinking_only_assistant_for_non_reasoning_model, chat_messages_drop_orphan_tool_results
708 // from chat_messages_drop_thinking_only_assistant_for_non_reasoning_model
709 {
710 let message = Message {
711 role: Role::Assistant,
712 content: vec![ContentBlock::Thinking {
713 signature: None,
714 state: None,
715 redacted_data: None,
716 thinking: "plan".to_string(),
717 }],
718 };
719 let out = build_chat_messages(None, &[message], "some-non-deepseek-model");
720 assert!(
721 !out.iter()
722 .any(|value| value.get("role").and_then(Value::as_str) == Some("assistant")),
723 "non-reasoning model should drop thinking-only assistant"
724 );
725 }
726 // from chat_messages_drop_orphan_tool_results
727 {
728 let messages = vec![Message {
729 role: Role::User,
730 content: vec![ContentBlock::ToolResult {
731 execution_id: None,
732 tool_use_id: "tool-1".to_string(),
733 content: "ok".to_string(),
734 is_error: None,
735 content_blocks: None,
736 }],
737 }];
738
739 let out = build_chat_messages(None, &messages, "deepseek-v4-flash");
740 assert!(
741 !out.iter()
742 .any(|value| { value.get("role").and_then(Value::as_str) == Some("tool") })
743 );
744 }
745 }
746
747 #[test]
748 fn parse_sse_chunk_closes_each_tool_block_with_matching_index() {
749 let chunk = json!({
750 "choices": [{
751 "delta": {
752 "tool_calls": [
753 {
754 "index": 0,
755 "id": "call_0",
756 "function": {"name": "read_file", "arguments": "{\"path\":\"a\"}"}
757 },
758 {
759 "index": 1,
760 "id": "call_1",
761 "function": {"name": "read_file", "arguments": "{\"path\":\"b\"}"}
762 }
763 ]
764 },
765 "finish_reason": "tool_calls"
766 }]
767 });
768
769 let mut content_index = 0;
770 let mut text_started = false;
771 let mut thinking_started = false;
772 let mut tool_indices = super::chat::ChatToolStream::default();
773 let mut reasoning_detail_buffers = std::collections::HashMap::new();
774 let events = parse_sse_chunk(
775 &chunk,
776 &mut content_index,
777 &mut text_started,
778 &mut thinking_started,
779 &mut tool_indices,
780 &mut reasoning_detail_buffers,
781 false,
782 );
783
784 let starts: Vec<u32> = events
785 .iter()
786 .filter_map(|event| match event {
787 StreamEvent::ContentBlockStart {
788 index,
789 content_block: ContentBlockStart::ToolUse { .. },
790 } => Some(*index),
791 _ => None,
792 })
793 .collect();
794 let stops: Vec<u32> = events
795 .iter()
796 .filter_map(|event| match event {
797 StreamEvent::ContentBlockStop { index } => Some(*index),
798 _ => None,
799 })
800 .collect();
801 let deltas: Vec<u32> = events
802 .iter()
803 .filter_map(|event| match event {
804 StreamEvent::ContentBlockDelta {
805 index,
806 delta: Delta::InputJsonDelta { .. },
807 } => Some(*index),
808 _ => None,
809 })
810 .collect();
811
812 assert_eq!(starts, vec![0, 1]);
813 assert_eq!(stops, vec![0, 1]);
814 assert_eq!(deltas, vec![0, 1]);
815 }
816
817 #[test]
818 fn parse_sse_chunk_handles_empty_choices_usage_chunk() {
819 let chunk = json!({
820 "choices": [],
821 "usage": {
822 "prompt_tokens": 100,
823 "completion_tokens": 20,
824 "prompt_cache_hit_tokens": 70,
825 "prompt_cache_miss_tokens": 30
826 }
827 });
828
829 let mut content_index = 0;
830 let mut text_started = false;
831 let mut thinking_started = false;
832 let mut tool_indices = super::chat::ChatToolStream::default();
833 let mut reasoning_detail_buffers = std::collections::HashMap::new();
834 let events = parse_sse_chunk(
835 &chunk,
836 &mut content_index,
837 &mut text_started,
838 &mut thinking_started,
839 &mut tool_indices,
840 &mut reasoning_detail_buffers,
841 false,
842 );
843
844 let StreamEvent::MessageDelta {
845 usage: Some(usage), ..
846 } = &events[0]
847 else {
848 panic!("expected usage delta");
849 };
850 assert_eq!(usage.input_tokens, 100);
851 assert_eq!(usage.prompt_cache_hit_tokens, Some(70));
852 assert_eq!(usage.prompt_cache_miss_tokens, Some(30));
853 }
854
855 #[test]
856 fn chat_messages_include_tool_results_when_call_present() {
857 let messages = vec![
858 Message {
859 role: Role::Assistant,
860 content: vec![
861 ContentBlock::Thinking {
862 signature: None,
863 state: None,
864 redacted_data: None,
865 thinking: "Need to inspect the directory".to_string(),
866 },
867 ContentBlock::ToolUse {
868 execution_id: None,
869 id: "tool-1".to_string(),
870 name: "list_dir".to_string(),
871 input: json!({}),
872 caller: None,
873 thought_signature: None,
874 },
875 ],
876 },
877 Message {
878 role: Role::User,
879 content: vec![ContentBlock::ToolResult {
880 execution_id: None,
881 tool_use_id: "tool-1".to_string(),
882 content: "ok".to_string(),
883 is_error: None,
884 content_blocks: None,
885 }],
886 },
887 ];
888
889 let out = build_chat_messages(None, &messages, "deepseek-v4-flash");
890 assert!(
891 out.iter()
892 .any(|value| { value.get("role").and_then(Value::as_str) == Some("tool") })
893 );
894 let assistant = out
895 .iter()
896 .find(|value| value.get("role").and_then(Value::as_str) == Some("assistant"))
897 .expect("assistant message");
898 assert!(assistant.get("tool_calls").is_some());
899 }
900
901 #[test]
902 fn chat_messages_encode_tool_call_names() {
903 let messages = vec![
904 Message {
905 role: Role::Assistant,
906 content: vec![
907 ContentBlock::Thinking {
908 signature: None,
909 state: None,
910 redacted_data: None,
911 thinking: "Need to search".to_string(),
912 },
913 ContentBlock::ToolUse {
914 execution_id: None,
915 id: "tool-1".to_string(),
916 name: "web.run".to_string(),
917 input: json!({}),
918 caller: None,
919 thought_signature: None,
920 },
921 ],
922 },
923 Message {
924 role: Role::User,
925 content: vec![ContentBlock::ToolResult {
926 execution_id: None,
927 tool_use_id: "tool-1".to_string(),
928 content: "ok".to_string(),
929 is_error: None,
930 content_blocks: None,
931 }],
932 },
933 ];
934
935 let out = build_chat_messages(None, &messages, "deepseek-v4-flash");
936 let assistant = out
937 .iter()
938 .find(|value| value.get("role").and_then(Value::as_str) == Some("assistant"))
939 .expect("assistant message");
940 let tool_calls = assistant
941 .get("tool_calls")
942 .and_then(Value::as_array)
943 .expect("tool_calls array");
944 let function_name = tool_calls
945 .first()
946 .and_then(|call| call.get("function"))
947 .and_then(|func| func.get("name"))
948 .and_then(Value::as_str)
949 .expect("tool call function name");
950
951 assert_eq!(function_name, to_api_tool_name("web.run"));
952 }
953
954 #[test]
955 fn chat_messages_strips_orphaned_tool_calls_after_compaction() {
956 // Simulates post-compaction state: assistant has tool_calls but the
957 // tool result messages were summarized away.
958 let messages = vec![
959 Message {
960 role: Role::Assistant,
961 content: vec![ContentBlock::ToolUse {
962 execution_id: None,
963 id: "tool-orphan".to_string(),
964 name: "read_file".to_string(),
965 input: json!({"path": "src/main.rs"}),
966 caller: None,
967 thought_signature: None,
968 }],
969 },
970 // No tool result follows — it was removed by compaction.
971 Message {
972 role: Role::User,
973 content: vec![ContentBlock::Text {
974 text: "continue".to_string(),
975 cache_control: None,
976 }],
977 },
978 ];
979
980 let out = build_chat_messages(None, &messages, "deepseek-v4-flash");
981 let assistant = out
982 .iter()
983 .find(|value| value.get("role").and_then(Value::as_str) == Some("assistant"));
984 // The safety net may drop the assistant message entirely if it only
985 // contained orphaned tool_calls and no text content.
986 assert!(
987 assistant.is_none(),
988 "assistant without content/tool_calls should be removed"
989 );
990 assert!(
991 !out.iter()
992 .any(|v| v.get("role").and_then(Value::as_str) == Some("tool")),
993 "orphaned tool results should also be removed"
994 );
995 }
996
997 #[test]
998 fn chat_messages_keeps_valid_tool_calls_intact() {
999 // Complete call+result pair should NOT be stripped.
1000 let messages = vec![
1001 Message {
1002 role: Role::Assistant,
1003 content: vec![
1004 ContentBlock::Thinking {
1005 signature: None,
1006 state: None,
1007 redacted_data: None,
1008 thinking: "Need to list files".to_string(),
1009 },
1010 ContentBlock::ToolUse {
1011 execution_id: None,
1012 id: "tool-ok".to_string(),
1013 name: "list_dir".to_string(),
1014 input: json!({}),
1015 caller: None,
1016 thought_signature: None,
1017 },
1018 ],
1019 },
1020 Message {
1021 role: Role::User,
1022 content: vec![ContentBlock::ToolResult {
1023 execution_id: None,
1024 tool_use_id: "tool-ok".to_string(),
1025 content: "files".to_string(),
1026 is_error: None,
1027 content_blocks: None,
1028 }],
1029 },
1030 ];
1031
1032 let out = build_chat_messages(None, &messages, "deepseek-v4-flash");
1033 let assistant = out
1034 .iter()
1035 .find(|value| value.get("role").and_then(Value::as_str) == Some("assistant"))
1036 .expect("assistant message");
1037 assert!(
1038 assistant.get("tool_calls").is_some(),
1039 "valid tool_calls should remain intact"
1040 );
1041 assert!(
1042 out.iter()
1043 .any(|value| value.get("role").and_then(Value::as_str) == Some("tool")),
1044 "tool result should remain"
1045 );
1046 }
1047
1048 #[test]
1049 fn chat_messages_strips_partial_tool_results() {
1050 let messages = vec![
1051 Message {
1052 role: Role::Assistant,
1053 content: vec![
1054 ContentBlock::ToolUse {
1055 execution_id: None,
1056 id: "t1".to_string(),
1057 name: "read_file".to_string(),
1058 input: json!({"path": "a.rs"}),
1059 caller: None,
1060 thought_signature: None,
1061 },
1062 ContentBlock::ToolUse {
1063 execution_id: None,
1064 id: "t2".to_string(),
1065 name: "read_file".to_string(),
1066 input: json!({"path": "b.rs"}),
1067 caller: None,
1068 thought_signature: None,
1069 },
1070 ContentBlock::ToolUse {
1071 execution_id: None,
1072 id: "t3".to_string(),
1073 name: "shell".to_string(),
1074 input: json!({"cmd": "ls"}),
1075 caller: None,
1076 thought_signature: None,
1077 },
1078 ],
1079 },
1080 Message {
1081 role: Role::User,
1082 content: vec![ContentBlock::ToolResult {
1083 execution_id: None,
1084 tool_use_id: "t1".to_string(),
1085 content: "content a".to_string(),
1086 is_error: None,
1087 content_blocks: None,
1088 }],
1089 },
1090 Message {
1091 role: Role::User,
1092 content: vec![ContentBlock::ToolResult {
1093 execution_id: None,
1094 tool_use_id: "t2".to_string(),
1095 content: "content b".to_string(),
1096 is_error: None,
1097 content_blocks: None,
1098 }],
1099 },
1100 // No result for t3
1101 Message {
1102 role: Role::User,
1103 content: vec![ContentBlock::Text {
1104 text: "continue".to_string(),
1105 cache_control: None,
1106 }],
1107 },
1108 ];
1109
1110 let out = build_chat_messages(None, &messages, "deepseek-v4-flash");
1111 let assistant = out
1112 .iter()
1113 .find(|v| v.get("role").and_then(Value::as_str) == Some("assistant"));
1114 assert!(
1115 assistant.is_none(),
1116 "assistant with only partial tool_calls should be removed"
1117 );
1118 assert!(
1119 !out.iter()
1120 .any(|v| v.get("role").and_then(Value::as_str) == Some("tool")),
1121 "all orphaned tool results should be removed"
1122 );
1123 }
1124
1125 #[test]
1126 fn codewhale_models_listing_carries_the_wire_protocol_per_model() {
1127 let payload = r#"{
1128 "object": "list",
1129 "data": [
1130 {"id": "deepseek/deepseek-v4-pro", "object": "model", "owned_by": "deepseek",
1131 "codewhale": {"provider": "deepseek", "model": "deepseek-v4-pro",
1132 "protocol": "chat-completions",
1133 "endpoint": "/v1/chat/completions",
1134 "default": true, "usable": true}},
1135 {"id": "anthropic/claude-sonnet-5", "object": "model", "owned_by": "anthropic",
1136 "codewhale": {"provider": "anthropic", "model": "claude-sonnet-5",
1137 "protocol": "anthropic-messages",
1138 "endpoint": "/v1/messages", "usable": true}},
1139 {"id": "openai/gpt-5.6", "object": "model", "owned_by": "openai",
1140 "codewhale": {"provider": "openai", "model": "gpt-5.6",
1141 "protocol": "responses",
1142 "endpoint": "/v1/responses", "usable": true}},
1143 {"id": "xai/grok-4.6", "object": "model", "owned_by": "xai",
1144 "codewhale": {"provider": "xai", "model": "grok-4.6",
1145 "protocol": "some-future-wire", "usable": true}},
1146 {"id": "deepseek/deepseek-v4-pro", "object": "model"},
1147 {"id": " ", "object": "model"},
1148 {"id": "anthropic/claude-opus-4-8", "object": "model"},
1149 {"id": "codewhale/Qwen3.8-27B", "object": "model", "owned_by": "codewhale",
1150 "codewhale": {"provider": "codewhale", "model": "Qwen3.8-27B",
1151 "protocol": "chat-completions", "usable": true,
1152 "limits": {"maxInputTokens": 7168, "maxOutputTokens": 1024,
1153 "maxContextTokens": 16384}}}
1154 ]
1155 }"#;
1156
1157 let rows = codewhale_catalog_offerings_from_body(payload, "codewhale", "fp", 7)
1158 .expect("the account listing should parse");
1159 let by_id: std::collections::BTreeMap<&str, &CatalogOffering> = rows
1160 .iter()
1161 .map(|row| (row.wire_model_id.as_str(), row))
1162 .collect();
1163 assert_eq!(rows.len(), 6, "blank and duplicate ids are dropped");
1164 // The protocol comes from the response, not from a compiled roster.
1165 assert_eq!(by_id["deepseek/deepseek-v4-pro"].endpoint_key, "chat");
1166 assert!(by_id["deepseek/deepseek-v4-pro"].default_for_provider);
1167 assert_eq!(by_id["anthropic/claude-sonnet-5"].endpoint_key, "messages");
1168 assert!(!by_id["anthropic/claude-sonnet-5"].default_for_provider);
1169 assert_eq!(by_id["openai/gpt-5.6"].endpoint_key, "responses");
1170 // A protocol label this build predates is not an error: the row falls
1171 // back to the namespace rule so a forward-compatible catalog stays
1172 // reachable.
1173 assert_eq!(by_id["xai/grok-4.6"].endpoint_key, "chat");
1174 // A row with no `codewhale` block still resolves through the namespace
1175 // rule rather than being dropped: the account listed it.
1176 assert_eq!(by_id["anthropic/claude-opus-4-8"].endpoint_key, "messages");
1177 // Nothing is claimed that the account service did not state: only a
1178 // row that advertises `codewhale.limits` carries limits, and they are
1179 // the advertised numbers.
1180 assert!(
1181 rows.iter()
1182 .all(|row| row.canonical_model.is_none() && row.cost.is_none())
1183 );
1184 assert!(
1185 rows.iter()
1186 .filter(|row| row.wire_model_id != "codewhale/Qwen3.8-27B")
1187 .all(|row| row.limit.is_none())
1188 );
1189 let qwen = by_id["codewhale/Qwen3.8-27B"]
1190 .limit
1191 .as_ref()
1192 .expect("advertised limits");
1193 assert_eq!(
1194 (qwen.context, qwen.input, qwen.output),
1195 (Some(16384), Some(7168), Some(1024))
1196 );
1197
1198 assert_eq!(
1199 codewhale_catalog_offerings_from_body(
1200 r#"{"object":"list","data":[]}"#,
1201 "codewhale",
1202 "fp",
1203 7
1204 ),
1205 Ok(Vec::new())
1206 );
1207 for body in [r#"{}"#, r#"{"error":"denied"}"#, r#"{"data":[{}]}"#] {
1208 assert_eq!(codewhale_catalog_offerings_from_body(body, "codewhale", "fp", 7), Err(CatalogRefreshError::InvalidResponse));
1209 }
1210 assert_eq!(
1211 codewhale_catalog_offerings_from_body("not json", "codewhale", "fp", 7),
1212 Err(CatalogRefreshError::InvalidResponse)
1213 );
1214 }
1215
1216 #[test]
1217 fn parse_models_response_parses_and_deduplicates() {
1218 let payload = r#"{
1219 "object": "list",
1220 "data": [
1221 {"id": "deepseek-v4-pro", "object": "model", "owned_by": "deepseek", "created": 1},
1222 {"id": "deepseek-v4-flash", "object": "model"},
1223 {"id": "deepseek-v4-pro", "object": "model", "owned_by": "deepseek", "created": 1}
1224 ]
1225 }"#;
1226
1227 let models = parse_models_response(payload).expect("parse models");
1228 assert_eq!(
1229 models,
1230 vec![
1231 AvailableModel {
1232 id: "deepseek-v4-flash".to_string(),
1233 owned_by: None,
1234 created: None,
1235 display_name: None,
1236 context_window: None,
1237 effective_context_window_percent: None,
1238 reasoning: None,
1239 efforts: Vec::new(),
1240 },
1241 AvailableModel {
1242 id: "deepseek-v4-pro".to_string(),
1243 owned_by: Some("deepseek".to_string()),
1244 created: Some(1),
1245 display_name: None,
1246 context_window: None,
1247 effective_context_window_percent: None,
1248 reasoning: None,
1249 efforts: Vec::new(),
1250 }
1251 ]
1252 );
1253 }
1254
1255 #[test]
1256 fn parse_models_response_accepts_ollama_tag_ids() {
1257 let payload = r#"{
1258 "object": "list",
1259 "data": [
1260 {"id": "qwen2.5-coder:7b", "object": "model", "owned_by": "library"},
1261 {"id": "deepseek-coder-v2:16b", "object": "model"}
1262 ]
1263 }"#;
1264
1265 let models = parse_models_response(payload).expect("parse models");
1266 assert_eq!(
1267 models
1268 .iter()
1269 .map(|model| model.id.as_str())
1270 .collect::<Vec<_>>(),
1271 vec!["deepseek-coder-v2:16b", "qwen2.5-coder:7b"]
1272 );
1273 }
1274
1275 // === #3385: provider live /models fetch + secret-free cache ==============
1276 //
1277 // All model ids below are SYNTHETIC (never real vendor model names), per the
1278 // issue's anti-hardcoding rule.
1279
1280 /// Build a client whose OpenRouter base URL points at a mock server.
1281 pub(super) fn openrouter_client_for(server: &MockServer) -> CodewhaleClient {
1282 let _ = rustls::crypto::ring::default_provider().install_default();
1283 CodewhaleClient::new(&{
1284 let __cw_config_init_0_0 = Some("openrouter".to_string());
1285 let __cw_config_init_0_1 = Some(ProvidersConfig {
1286 openrouter: ProviderConfig {
1287 api_key: Some("test-key".to_string()),
1288 base_url: Some(server.uri()),
1289 ..ProviderConfig::default()
1290 },
1291 ..ProvidersConfig::default()
1292 });
1293 let mut __cw_config_init_0_value: Config = Config::default();
1294 __cw_config_init_0_value.provider = __cw_config_init_0_0;
1295 __cw_config_init_0_value.providers = __cw_config_init_0_1;
1296 __cw_config_init_0_value
1297 })
1298 .expect("openrouter client")
1299 }
1300
1301 pub(super) fn custom_mock_client_for_identity(
1302 server: &MockServer,
1303 identity: &str,
1304 ) -> CodewhaleClient {
1305 let _ = rustls::crypto::ring::default_provider().install_default();
1306 let mut providers = ProvidersConfig::default();
1307 providers.custom.insert(
1308 identity.to_string(),
1309 ProviderConfig {
1310 kind: Some("openai-compatible".to_string()),
1311 api_key: Some("test-custom-key".to_string()),
1312 base_url: Some(format!("{}/v1", server.uri())),
1313 model: Some("synthetic/custom-model".to_string()),
1314 ..ProviderConfig::default()
1315 },
1316 );
1317 CodewhaleClient::new(&{
1318 let __cw_config_init_1_0 = Some(identity.to_string());
1319 let __cw_config_init_1_1 = Some(providers);
1320 let mut __cw_config_init_1_value: Config = Config::default();
1321 __cw_config_init_1_value.provider = __cw_config_init_1_0;
1322 __cw_config_init_1_value.providers = __cw_config_init_1_1;
1323 __cw_config_init_1_value
1324 })
1325 .expect("Baseten client")
1326 }
1327
1328 pub(super) fn opencode_go_client_for(server: &MockServer) -> CodewhaleClient {
1329 let _ = rustls::crypto::ring::default_provider().install_default();
1330 CodewhaleClient::new(&{
1331 let __cw_config_init_2_0 = Some("opencode-go".to_string());
1332 let __cw_config_init_2_1 = Some(ProvidersConfig {
1333 opencode_go: ProviderConfig {
1334 api_key: Some("test-key".to_string()),
1335 base_url: Some(server.uri()),
1336 ..ProviderConfig::default()
1337 },
1338 ..ProvidersConfig::default()
1339 });
1340 let mut __cw_config_init_2_value: Config = Config::default();
1341 __cw_config_init_2_value.provider = __cw_config_init_2_0;
1342 __cw_config_init_2_value.providers = __cw_config_init_2_1;
1343 __cw_config_init_2_value
1344 })
1345 .expect("OpenCode Go client")
1346 }
1347
1348 fn telecomjs_client_for(server: &MockServer) -> CodewhaleClient {
1349 let _ = rustls::crypto::ring::default_provider().install_default();
1350 CodewhaleClient::new(&{
1351 let __cw_config_init_3_0 = Some("telecomjs".to_string());
1352 let __cw_config_init_3_1 = Some(ProvidersConfig {
1353 telecomjs: ProviderConfig {
1354 api_key: Some("test-key".to_string()),
1355 base_url: Some(server.uri()),
1356 ..ProviderConfig::default()
1357 },
1358 ..ProvidersConfig::default()
1359 });
1360 let mut __cw_config_init_3_value: Config = Config::default();
1361 __cw_config_init_3_value.provider = __cw_config_init_3_0;
1362 __cw_config_init_3_value.providers = __cw_config_init_3_1;
1363 __cw_config_init_3_value
1364 })
1365 .expect("TelecomJS client")
1366 }
1367
1368 fn edenai_client_for(server: &MockServer) -> CodewhaleClient {
1369 let _ = rustls::crypto::ring::default_provider().install_default();
1370 CodewhaleClient::new(&{
1371 let __cw_config_init_4_0 = Some("edenai".to_string());
1372 let __cw_config_init_4_1 = Some(ProvidersConfig {
1373 edenai: ProviderConfig {
1374 api_key: Some("test-key".to_string()),
1375 base_url: Some(format!("{}/v3", server.uri())),
1376 ..ProviderConfig::default()
1377 },
1378 ..ProvidersConfig::default()
1379 });
1380 let mut __cw_config_init_4_value: Config = Config::default();
1381 __cw_config_init_4_value.provider = __cw_config_init_4_0;
1382 __cw_config_init_4_value.providers = __cw_config_init_4_1;
1383 __cw_config_init_4_value
1384 })
1385 .expect("Eden AI client")
1386 }
1387
1388 pub(super) async fn mount_models_json(server: &MockServer, status: u16, body: serde_json::Value) {
1389 Mock::given(method("GET"))
1390 .and(path("/v1/models"))
1391 .respond_with(ResponseTemplate::new(status).set_body_json(body))
1392 .mount(server)
1393 .await;
1394 }
1395
1396 #[tokio::test]
1397 async fn verify_provider_scenario() {
1398 // Scenario consolidation of: verify_provider_api_key_accepts_mocked_models_success, verify_provider_api_key_returns_status_and_unicode_body_without_panic
1399 // from verify_provider_api_key_accepts_mocked_models_success
1400 {
1401 let server = MockServer::start().await;
1402 Mock::given(method("GET"))
1403 .and(path("/v1/models"))
1404 .and(header("authorization", "Bearer test-key"))
1405 .respond_with(ResponseTemplate::new(200).set_body_json(json!({"data": []})))
1406 .mount(&server)
1407 .await;
1408
1409 verify_provider_api_key(ProviderKind::Openrouter, "test-key", &server.uri())
1410 .await
1411 .expect("mocked /models success should verify");
1412 }
1413 // from verify_provider_api_key_returns_status_and_unicode_body_without_panic
1414 {
1415 let server = MockServer::start().await;
1416 Mock::given(method("GET"))
1417 .and(path("/v1/models"))
1418 .respond_with(ResponseTemplate::new(401).set_body_string("密钥无效"))
1419 .mount(&server)
1420 .await;
1421
1422 let err = verify_provider_api_key(ProviderKind::Openrouter, "bad-key", &server.uri())
1423 .await
1424 .expect_err("mocked /models failure should be reported");
1425
1426 assert!(err.contains("HTTP 401"), "status is preserved: {err}");
1427 assert!(err.contains("密钥无效"), "unicode body is preserved: {err}");
1428 }
1429 }
1430
1431 #[test]
1432 fn opencode_go_client_rejects_unknown_protocol_models() {
1433 let _ = rustls::crypto::ring::default_provider().install_default();
1434 for model in ["claude-unproven", "gpt-unlisted"] {
1435 let config = {
1436 let __cw_config_init_5_0 = Some("opencode-go".to_string());
1437 let __cw_config_init_5_1 = Some(ProvidersConfig {
1438 opencode_go: ProviderConfig {
1439 api_key: Some("test-key".to_string()),
1440 model: Some(model.to_string()),
1441 ..ProviderConfig::default()
1442 },
1443 ..ProvidersConfig::default()
1444 });
1445 let mut __cw_config_init_5_value: Config = Config::default();
1446 __cw_config_init_5_value.provider = __cw_config_init_5_0;
1447 __cw_config_init_5_value.providers = __cw_config_init_5_1;
1448 __cw_config_init_5_value
1449 };
1450 let err = CodewhaleClient::new(&config)
1451 .err()
1452 .expect("unknown protocol must fail before client construction");
1453 assert!(err.to_string().contains(model), "{err:#}");
1454 }
1455 }
1456
1457 #[tokio::test]
1458 async fn opencode_go_live_model_paths_keep_documented_protocol_rows() {
1459 let server = MockServer::start().await;
1460 let mut rows: Vec<_> = codewhale_config::opencode_go_models()
1461 .iter()
1462 .map(|id| json!({"id": id}))
1463 .collect();
1464 rows.extend([
1465 json!({"id": "minimax-m3"}),
1466 json!({"id": "minimax-m2.7"}),
1467 json!({"id": "minimax-m2.5"}),
1468 json!({"id": "qwen3.7-max"}),
1469 json!({"id": "qwen3.7-plus"}),
1470 json!({"id": "qwen3.6-plus"}),
1471 ]);
1472 mount_models_json(&server, 200, json!({"data": rows})).await;
1473 let client = opencode_go_client_for(&server);
1474
1475 let listed = client.list_models().await.expect("filtered model list");
1476 let listed: std::collections::BTreeSet<_> = listed.into_iter().map(|model| model.id).collect();
1477 let expected: std::collections::BTreeSet<_> = codewhale_config::opencode_go_models()
1478 .iter()
1479 .map(|model| (*model).to_string())
1480 .collect();
1481 assert_eq!(listed, expected);
1482
1483 let delta = client.fetch_catalog_delta().await.expect("filtered delta");
1484 assert_eq!(delta.provider, "opencode-go");
1485 let delta_ids: std::collections::BTreeSet<_> = delta
1486 .offerings
1487 .iter()
1488 .map(|offering| offering.wire_model_id.clone())
1489 .collect();
1490 assert_eq!(delta_ids, expected);
1491 assert!(
1492 delta
1493 .offerings
1494 .iter()
1495 .all(|offering| Some(offering.endpoint_key.as_str())
1496 == codewhale_config::opencode_go_endpoint_key(&offering.wire_model_id))
1497 );
1498 }
1499
1500 #[tokio::test]
1501 async fn telecomjs_live_catalog_keeps_cross_provider_metadata_unknown() {
1502 let server = MockServer::start().await;
1503 let ambiguous_id = codewhale_config::catalog::bundled_catalog_offerings()
1504 .into_iter()
1505 .find(|offering| {
1506 !offering.provider.eq_ignore_ascii_case("telecomjs")
1507 && !offering
1508 .wire_model_id
1509 .eq_ignore_ascii_case(DEFAULT_TELECOMJS_MODEL)
1510 && (offering.canonical_model.is_some()
1511 || offering.family.is_some()
1512 || offering.limit.is_some()
1513 || offering.cost.is_some()
1514 || offering.reasoning.is_some()
1515 || offering.tool_call.is_some())
1516 })
1517 .expect("bundled catalog should contain a metadata-bearing non-TelecomJS row")
1518 .wire_model_id;
1519 Mock::given(method("GET"))
1520 .and(path("/v1/models"))
1521 .and(header("authorization", "Bearer test-key"))
1522 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1523 "data": [
1524 {"id": ambiguous_id.clone()},
1525 {"id": DEFAULT_TELECOMJS_MODEL}
1526 ]
1527 })))
1528 .mount(&server)
1529 .await;
1530
1531 let delta = telecomjs_client_for(&server)
1532 .fetch_catalog_delta()
1533 .await
1534 .expect("TelecomJS catalog delta");
1535 assert_eq!(delta.provider, "telecomjs");
1536 assert_eq!(delta.offerings.len(), 2);
1537
1538 let ambiguous = delta
1539 .offerings
1540 .iter()
1541 .find(|offering| offering.wire_model_id == ambiguous_id)
1542 .expect("ambiguous cross-provider id");
1543 assert!(!ambiguous.default_for_provider);
1544 assert_eq!(ambiguous.endpoint_key, "chat");
1545 assert_eq!(ambiguous.canonical_model, None);
1546 assert_eq!(ambiguous.family, None);
1547 assert_eq!(ambiguous.limit, None);
1548 assert_eq!(ambiguous.cost, None);
1549 assert_eq!(ambiguous.modalities, None);
1550 assert_eq!(ambiguous.attachment, None);
1551 assert_eq!(ambiguous.reasoning, None);
1552 assert_eq!(ambiguous.tool_call, None);
1553 assert_eq!(ambiguous.structured_output, None);
1554 assert!(ambiguous.reasoning_options.is_empty());
1555 assert!(matches!(ambiguous.source, CatalogSource::Live { .. }));
1556
1557 let default = delta
1558 .offerings
1559 .iter()
1560 .find(|offering| offering.wire_model_id == DEFAULT_TELECOMJS_MODEL)
1561 .expect("TelecomJS default row");
1562 assert!(default.default_for_provider);
1563 }
1564
1565 #[tokio::test]
1566 async fn edenai_live_catalog_marks_the_default_and_keeps_unknowns_unclaimed() {
1567 let server = MockServer::start().await;
1568 Mock::given(method("GET"))
1569 .and(path("/v3/models"))
1570 .and(header("authorization", "Bearer test-key"))
1571 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1572 "data": [
1573 {"id": "synthetic/vendor-model"},
1574 {"id": DEFAULT_EDENAI_MODEL}
1575 ]
1576 })))
1577 .mount(&server)
1578 .await;
1579
1580 let delta = edenai_client_for(&server)
1581 .fetch_catalog_delta()
1582 .await
1583 .expect("Eden AI catalog delta");
1584 assert_eq!(delta.provider, "edenai");
1585 assert_eq!(delta.offerings.len(), 2);
1586
1587 let unknown = delta
1588 .offerings
1589 .iter()
1590 .find(|offering| offering.wire_model_id == "synthetic/vendor-model")
1591 .expect("synthetic Eden AI row");
1592 assert_eq!(unknown.canonical_model, None);
1593 assert_eq!(unknown.reasoning, None);
1594 assert_eq!(unknown.tool_call, None);
1595 assert!(!unknown.default_for_provider);
1596
1597 let default = delta
1598 .offerings
1599 .iter()
1600 .find(|offering| offering.wire_model_id == DEFAULT_EDENAI_MODEL)
1601 .expect("Eden AI default row");
1602 assert!(default.default_for_provider);
1603 }
1604
1605 #[tokio::test]
1606 async fn fetch_catalog_delta_success_builds_scoped_secret_free_live_delta() {
1607 let server = MockServer::start().await;
1608 mount_models_json(
1609 &server,
1610 200,
1611 json!({"data": [
1612 {"id": "synthetic-model-alpha", "owned_by": "synthetic-owner"},
1613 {"id": "synthetic-model-beta"}
1614 ]}),
1615 )
1616 .await;
1617 let client = openrouter_client_for(&server);
1618
1619 let delta = client.fetch_catalog_delta().await.expect("delta");
1620 assert_eq!(delta.provider, "openrouter");
1621 assert_eq!(
1622 delta.base_url_fingerprint,
1623 base_url_fingerprint(&server.uri()),
1624 "delta is scoped to the base-URL fingerprint"
1625 );
1626 let ids: Vec<&str> = delta
1627 .offerings
1628 .iter()
1629 .map(|offering| offering.wire_model_id.as_str())
1630 .collect();
1631 assert!(ids.contains(&"synthetic-model-alpha"), "ids: {ids:?}");
1632 assert!(ids.contains(&"synthetic-model-beta"), "ids: {ids:?}");
1633 for offering in &delta.offerings {
1634 // Live rows carry honest provenance and no inferred facts/secrets.
1635 assert!(matches!(offering.source, CatalogSource::Live { .. }));
1636 assert_eq!(offering.canonical_model, None);
1637 assert_eq!(offering.cost, None);
1638 assert!(offering.reasoning.is_none());
1639 }
1640 }
1641
1642 /// #6690: rows shaped like the live OpenRouter roster. A `~` "latest"
1643 /// alias, a router's `"-1"` variable price, an undecodable row and an id
1644 /// the catalog cannot hold each used to fail the whole refresh closed
1645 /// (`invalid_response`), so the lake never went fresh and no OpenRouter
1646 /// turn could be priced. Each now costs only its own row.
1647 #[tokio::test]
1648 async fn fetch_catalog_delta_skips_openrouter_latest_aliases_and_keeps_prices() {
1649 let server = MockServer::start().await;
1650 mount_models_json(
1651 &server,
1652 200,
1653 json!({"data": [
1654 {"id": "~deepseek/deepseek-pro-latest",
1655 "pricing": {"prompt": "0.0000002523", "completion": "0.0000035",
1656 "input_cache_read": "0.0000002518"}},
1657 {"id": "openrouter/auto", "context_length": 2000000,
1658 "pricing": {"prompt": "-1", "completion": "-1"},
1659 "top_provider": {"context_length": null, "max_completion_tokens": null}},
1660 {"id": "synthetic/malformed-row", "context_length": "very long",
1661 "pricing": {"prompt": "0.000001", "completion": "0.000002"}},
1662 {"id": "synthetic/unreadable-price",
1663 "pricing": {"prompt": "not-a-number", "completion": "0.000002"}},
1664 {"id": "synthetic/bad id"},
1665 {"id": "deepseek/deepseek-v4-pro", "context_length": 1048576,
1666 "pricing": {"prompt": "0.00000095526", "completion": "0.00000191052",
1667 "input_cache_read": "0.000000079605"},
1668 "top_provider": {"context_length": 1024000, "max_completion_tokens": 384000}}
1669 ]}),
1670 )
1671 .await;
1672 let client = openrouter_client_for(&server);
1673
1674 let delta = client
1675 .fetch_catalog_delta()
1676 .await
1677 .expect("a bad row must not fail the whole roster");
1678 let ids: Vec<&str> = delta
1679 .offerings
1680 .iter()
1681 .map(|offering| offering.wire_model_id.as_str())
1682 .collect();
1683 assert_eq!(ids, ["openrouter/auto", "deepseek/deepseek-v4-pro"]);
1684 assert_eq!(delta.offerings[0].cost, None, "router price is variable");
1685 let cost = delta.offerings[1].cost.as_ref().expect("served price");
1686 let close = |got: Option<f64>, want: f64| got.is_some_and(|got| (got - want).abs() < 1e-9);
1687 assert!(close(cost.input, 0.95526), "{cost:?}");
1688 assert!(close(cost.output, 1.91052), "{cost:?}");
1689 assert!(close(cost.cache_read, 0.079605), "{cost:?}");
1690 assert_eq!(cost.cache_write, None);
1691
1692 // Only structurally invalid responses still fail the refresh.
1693 for body in [
1694 json!({"data": {"id": "deepseek/deepseek-v4-pro"}}),
1695 json!({"models": []}),
1696 json!({"data": [{"name": "no id"}, {"id": "synthetic/bad id"}]}),
1697 ] {
1698 let server = MockServer::start().await;
1699 mount_models_json(&server, 200, body.clone()).await;
1700 assert_eq!(
1701 openrouter_client_for(&server)
1702 .fetch_catalog_delta()
1703 .await
1704 .expect_err("structurally invalid roster"),
1705 CatalogRefreshError::InvalidResponse,
1706 "{body}"
1707 );
1708 }
1709 }
1710
1711 #[tokio::test]
1712 async fn fetch_catalog_scenario() {
1713 // Scenario consolidation of: fetch_catalog_delta_maps_http_statuses_to_typed_errors, fetch_catalog_delta_maps_invalid_json_and_empty_list
1714 // from fetch_catalog_delta_maps_http_statuses_to_typed_errors
1715 {
1716 for (status, expected) in [
1717 (401u16, CatalogRefreshError::Unauthorized),
1718 (403, CatalogRefreshError::Forbidden),
1719 (404, CatalogRefreshError::NotFound),
1720 (429, CatalogRefreshError::RateLimited),
1721 (500, CatalogRefreshError::Network),
1722 ] {
1723 let server = MockServer::start().await;
1724 mount_models_json(&server, status, json!({"error": "nope"})).await;
1725 let client = openrouter_client_for(&server);
1726 let err = client.fetch_catalog_delta().await.expect_err("should fail");
1727 assert_eq!(err, expected, "status {status} should map to {expected:?}");
1728 }
1729 }
1730 // from fetch_catalog_delta_maps_invalid_json_and_empty_list
1731 {
1732 // Invalid JSON -> InvalidResponse.
1733 let server = MockServer::start().await;
1734 Mock::given(method("GET"))
1735 .and(path("/v1/models"))
1736 .respond_with(ResponseTemplate::new(200).set_body_string("not json"))
1737 .mount(&server)
1738 .await;
1739 let client = openrouter_client_for(&server);
1740 assert_eq!(
1741 client
1742 .fetch_catalog_delta()
1743 .await
1744 .expect_err("invalid json"),
1745 CatalogRefreshError::InvalidResponse
1746 );
1747
1748 let server = MockServer::start().await;
1749 mount_models_json(&server, 200, json!({"data": []})).await;
1750 let client = openrouter_client_for(&server);
1751 assert!(client.fetch_catalog_delta().await.expect("valid empty inventory").offerings.is_empty());
1752 }
1753 }
1754
1755 #[test]
1756 fn anthropic_body_omits_tool_choice_when_every_tool_is_over_the_name_limit() {
1757 let _ = rustls::crypto::ring::default_provider().install_default();
1758 let config = {
1759 let mut config: codewhale_runtime::config::Config = Default::default();
1760 config.provider = Some("anthropic".to_string());
1761 config.providers = Some(codewhale_runtime::config::ProvidersConfig {
1762 anthropic: codewhale_runtime::config::ProviderConfig {
1763 api_key: Some("test-key".to_string()),
1764 ..Default::default()
1765 },
1766 ..Default::default()
1767 });
1768 config
1769 };
1770 let client = CodewhaleClient::new(&config).expect("anthropic client constructs");
1771 let long = format!("mcp__tracker__{}.v2.issues.list", "a".repeat(140));
1772 let request = MessageRequest {
1773 model: "claude-sonnet-4-6".to_string(),
1774 tools: Some(vec![Tool {
1775 tool_type: None,
1776 name: long.clone(),
1777 description: "d".to_string(),
1778 input_schema: json!({"type": "object", "additionalProperties": false}),
1779 allowed_callers: None,
1780 defer_loading: None,
1781 input_examples: None,
1782 strict: None,
1783 cache_control: None,
1784 }]),
1785 messages: vec![],
1786 max_tokens: 64,
1787 system: None,
1788 tool_choice: Some(json!({"type": "auto"})),
1789 metadata: None,
1790 thinking: None,
1791 reasoning_effort: None,
1792 stream: None,
1793 temperature: None,
1794 top_p: None,
1795 safety_check: None,
1796 title: None,
1797 };
1798 let (body, omitted) = client
1799 .build_anthropic_wire_body(&request, true)
1800 .expect("body builds");
1801 assert_eq!(omitted.len(), 1);
1802 assert!(body.get("tools").is_none());
1803 assert!(body.get("tool_choice").is_none());
1804 }
1805
1806 #[test]
1807 fn receipt_tool_measurement_bounds_omitted_names_and_keeps_the_count() {
1808 let names: Vec<String> = (0..20).map(|index| format!("omitted_tool_{index}")).collect();
1809 let measurement = crate::llm_client::ToolWireMeasurement {
1810 tool_schema_bytes: 0,
1811 tool_schema_sha256: String::new(),
1812 tool_count: 0,
1813 omitted_tool_names: names,
1814 omitted_tool_count: 20,
1815 }
1816 .bounded_for_receipt();
1817 let value = serde_json::to_value(&measurement).expect("serializes");
1818 assert!(value["omitted_tool_names"].as_array().expect("names").len() <= 8);
1819 assert_eq!(value["omitted_tool_count"], 20);
1820 }
1821
1822 #[test]
1823 fn openai_compatible_gateway_gets_no_deepseek_thinking_dialect_from_a_model_name() {
1824 for (effort, expected_effort) in [
1825 ("off", Some("none")),
1826 ("low", Some("low")),
1827 ("high", Some("high")),
1828 ("max", Some("max")),
1829 ("auto", None),
1830 ("no-such-tier", None),
1831 ] {
1832 let mut body = json!({});
1833 chat::apply_route_reasoning_controls(
1834 &mut body,
1835 ProviderKind::Custom,
1836 "https://api.freeshare.tech:8443/v1",
1837 "DeepSeek-V4.1-Flash",
1838 Some(effort),
1839 );
1840 assert!(
1841 body.get("thinking").is_none(),
1842 "a gateway rejects DeepSeek's toggle object ({effort}): {body}"
1843 );
1844 assert_eq!(
1845 body.get("reasoning_effort").and_then(Value::as_str),
1846 expected_effort,
1847 "the compatibility wire expresses the tier in its own spelling ({effort}): {body}"
1848 );
1849 }
1850 }
1851
1852 /// A `custom` row pointed at DeepSeek's own host is DeepSeek: it keeps the
1853 /// native toggle, so `off` still disables thinking there rather than
1854 /// degrading to the compatibility spelling. The host decides, so a
1855 /// non-canonical path is still DeepSeek, and a trailing slash, surrounding
1856 /// whitespace, userinfo or an explicit port does not change the answer.
1857 #[test]
1858 fn a_custom_row_on_the_official_deepseek_host_keeps_the_thinking_toggle() {
1859 for base_url in [
1860 "https://api.deepseek.com/v1",
1861 "https://api.deepseek.com",
1862 "https://api.deepseek.com/beta",
1863 "https://api.deepseek.com/v1/",
1864 "https://api.deepseek.com/openai",
1865 " https://API.DeepSeek.com/v1 ",
1866 "https://user:pw@api.deepseek.com/v1",
1867 "https://api.deepseek.com:443/v1",
1868 ] {
1869 for (effort, thinking, wire_effort) in [
1870 ("off", "disabled", None),
1871 ("max", "enabled", Some("max")),
1872 ] {
1873 let mut body = json!({});
1874 chat::apply_route_reasoning_controls(
1875 &mut body,
1876 ProviderKind::Custom,
1877 base_url,
1878 "deepseek-flash",
1879 Some(effort),
1880 );
1881 assert_eq!(
1882 body.pointer("/thinking/type").and_then(Value::as_str),
1883 Some(thinking),
1884 "{base_url} {effort}"
1885 );
1886 assert_eq!(
1887 body.get("reasoning_effort").and_then(Value::as_str),
1888 wire_effort,
1889 "{base_url} {effort}"
1890 );
1891 }
1892 }
1893 }
1894
1895 /// A host that merely resembles DeepSeek's does not inherit the dialect, and
1896 /// neither does an http downgrade or a userinfo trick. The legacy typo host
1897 /// is the one exception: it is in the host set on purpose, for continuity
1898 /// with the strict-tools and Responses lists (see `docs/REBRAND.md`).
1899 #[test]
1900 fn a_lookalike_host_does_not_inherit_the_deepseek_dialect() {
1901 for base_url in [
1902 "https://api.deepseek.com.evil.example/v1",
1903 "https://api.deepseek.com@evil.example/v1",
1904 "https://relay.example?x=@api.deepseek.com/v1",
1905 "https://relay.example#@api.deepseek.com/v1",
1906 "http://api.deepseek.com/v1",
1907 ] {
1908 let mut body = json!({});
1909 chat::apply_route_reasoning_controls(
1910 &mut body,
1911 ProviderKind::Custom,
1912 base_url,
1913 "deepseek-flash",
1914 Some("off"),
1915 );
1916 assert!(
1917 body.get("thinking").is_none(),
1918 "{base_url} must not inherit the native dialect: {body}"
1919 );
1920 assert_eq!(
1921 body.get("reasoning_effort").and_then(Value::as_str),
1922 Some("none"),
1923 "{base_url}"
1924 );
1925 }
1926
1927 let mut body = json!({});
1928 chat::apply_route_reasoning_controls(
1929 &mut body,
1930 ProviderKind::Custom,
1931 "https://api.deepseeki.com/v1",
1932 "deepseek-flash",
1933 Some("off"),
1934 );
1935 assert_eq!(
1936 body.pointer("/thinking/type").and_then(Value::as_str),
1937 Some("disabled"),
1938 "the legacy typo host stays in the set: {body}"
1939 );
1940 }
1941
1942 /// The `deepseek` identity sends its toggle for any host: nothing in the
1943 /// request pipeline checks the host for that label. Both a first-party host
1944 /// and a relay are pinned, so adding endpoint awareness to this identity is
1945 /// a deliberate change rather than a silent one.
1946 #[test]
1947 fn the_deepseek_identity_keeps_its_thinking_toggle() {
1948 for base_url in ["https://api.deepseek.com/beta", "https://relay.example/v1"] {
1949 for (effort, thinking, wire_effort) in [
1950 ("off", "disabled", None),
1951 ("low", "enabled", Some("low")),
1952 ("high", "enabled", Some("high")),
1953 ("max", "enabled", Some("max")),
1954 ] {
1955 let mut body = json!({});
1956 chat::apply_route_reasoning_controls(
1957 &mut body,
1958 ProviderKind::Deepseek,
1959 base_url,
1960 "deepseek-flash",
1961 Some(effort),
1962 );
1963 assert_eq!(
1964 body.pointer("/thinking/type").and_then(Value::as_str),
1965 Some(thinking),
1966 "{base_url} {effort}"
1967 );
1968 assert_eq!(
1969 body.get("reasoning_effort").and_then(Value::as_str),
1970 wire_effort,
1971 "{base_url} {effort}"
1972 );
1973 }
1974 }
1975 }
1976
1976 lines RUST