返回 CodeWhale
test_cases_02.rs
根目录 / crates / engine / src / client / test_cases_02.rs
1
2 async fn assert_zai_request_truth(streaming: bool) {
3 for base_url in [
4 codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL,
5 "https://api.z.ai/api/paas/v4",
6 ] {
7 let (high_path, high) = capture_zai_chat_request(
8 base_url,
9 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
10 Some("high"),
11 streaming,
12 )
13 .await;
14 let (max_path, max) = capture_zai_chat_request(
15 base_url,
16 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
17 Some("max"),
18 streaming,
19 )
20 .await;
21 assert_eq!(high_path, "/v1/chat/completions");
22 assert_eq!(max_path, "/v1/chat/completions");
23 assert_eq!(high["reasoning_effort"], "high", "{base_url}: {high}");
24 assert_eq!(max["reasoning_effort"], "max", "{base_url}: {max}");
25 for body in [&high, &max] {
26 assert_eq!(
27 body["thinking"],
28 json!({"type": "enabled", "clear_thinking": false}),
29 "{base_url}: {body}"
30 );
31 assert_eq!(
32 body["model"],
33 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL
34 );
35 }
36 let mut high_without_effort = high.clone();
37 let mut max_without_effort = max.clone();
38 high_without_effort
39 .as_object_mut()
40 .expect("object")
41 .remove("reasoning_effort");
42 max_without_effort
43 .as_object_mut()
44 .expect("object")
45 .remove("reasoning_effort");
46 assert_eq!(high_without_effort, max_without_effort);
47
48 for model in [
49 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_1_MODEL,
50 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL,
51 ] {
52 for requested in ["high", "max"] {
53 let (_, toggle_only) =
54 capture_zai_chat_request(base_url, model, Some(requested), streaming).await;
55 assert!(
56 toggle_only.get("reasoning_effort").is_none(),
57 "{model}: {toggle_only}"
58 );
59 assert_eq!(
60 toggle_only["thinking"],
61 json!({"type": "enabled", "clear_thinking": false}),
62 "{model}: {toggle_only}"
63 );
64 }
65 }
66
67 let (_, unknown) =
68 capture_zai_chat_request(base_url, "glm-future-unknown", Some("max"), streaming).await;
69 assert!(unknown.get("reasoning_effort").is_none(), "{unknown}");
70 assert!(unknown.get("thinking").is_none(), "{unknown}");
71 }
72
73 let (_, gateway) = capture_zai_chat_request(
74 "https://gateway.example/v1",
75 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
76 Some("max"),
77 streaming,
78 )
79 .await;
80 assert!(gateway.get("reasoning_effort").is_none(), "{gateway}");
81 assert!(gateway.get("thinking").is_none(), "{gateway}");
82
83 let (_, gateway_turbo) = capture_zai_chat_request(
84 "https://gateway.example/v1",
85 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL,
86 Some("max"),
87 streaming,
88 )
89 .await;
90 assert!(
91 gateway_turbo.get("reasoning_effort").is_none(),
92 "{gateway_turbo}"
93 );
94 assert!(gateway_turbo.get("thinking").is_none(), "{gateway_turbo}");
95 }
96
97 async fn assert_minimax_request_truth(streaming: bool) {
98 for base_url in [
99 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_BASE_URL,
100 "https://api.minimaxi.com/v1",
101 ] {
102 for (effort, expected_thinking) in [
103 ("off", json!({"type": "disabled"})),
104 ("high", json!({"type": "adaptive"})),
105 ("max", json!({"type": "adaptive"})),
106 ] {
107 let (_, body) = capture_minimax_chat_request(
108 base_url,
109 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL,
110 Some(effort),
111 streaming,
112 )
113 .await;
114 assert_eq!(
115 body["max_completion_tokens"], 64,
116 "{base_url} {effort}: {body}"
117 );
118 assert!(
119 body.get("max_tokens").is_none(),
120 "{base_url} {effort}: {body}"
121 );
122 assert_eq!(body["reasoning_split"], true, "{base_url}: {body}");
123 assert_eq!(
124 body["thinking"], expected_thinking,
125 "{base_url} {effort}: {body}"
126 );
127 }
128 }
129
130 for (base_url, model) in [
131 (
132 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_BASE_URL,
133 "MiniMax-M2",
134 ),
135 (
136 "https://gateway.example/v1",
137 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL,
138 ),
139 ] {
140 for effort in ["off", "high", "max"] {
141 let (_, body) =
142 capture_minimax_chat_request(base_url, model, Some(effort), streaming).await;
143 assert_eq!(
144 body["max_tokens"], 64,
145 "{base_url} {model} {effort}: {body}"
146 );
147 assert!(
148 body.get("max_completion_tokens").is_none(),
149 "{base_url} {model} {effort}: {body}"
150 );
151 assert!(
152 body.get("reasoning_split").is_none(),
153 "{base_url} {model} {effort}: {body}"
154 );
155 assert!(
156 body.get("thinking").is_none(),
157 "{base_url} {model} {effort}: {body}"
158 );
159 }
160 }
161 }
162
163 async fn assert_k3_request_json_route_boundaries(streaming: bool) {
164 for (requested, expected) in [("off", "low"), ("high", "high"), ("max", "max")] {
165 let body = capture_moonshot_chat_request(
166 codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL,
167 codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL,
168 Some(requested),
169 streaming,
170 )
171 .await;
172 assert_eq!(body["reasoning_effort"], json!(expected), "{body}");
173 assert!(body.get("thinking").is_none(), "{body}");
174 assert_eq!(body["max_completion_tokens"], json!(64), "{body}");
175 assert!(body.get("max_tokens").is_none(), "{body}");
176 assert!(body.get("temperature").is_none(), "{body}");
177 assert!(body.get("top_p").is_none(), "{body}");
178 assert_eq!(
179 body.get("stream").and_then(Value::as_bool),
180 streaming.then_some(true)
181 );
182 }
183
184 for (requested, expected) in [
185 ("off", Some(json!({"type": "enabled", "effort": "low"}))),
186 ("max", Some(json!({"type": "enabled", "effort": "max"}))),
187 ] {
188 let membership = capture_moonshot_chat_request(
189 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
190 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
191 Some(requested),
192 streaming,
193 )
194 .await;
195 match expected {
196 Some(thinking) => assert_eq!(membership["thinking"], thinking, "{membership}"),
197 None => assert!(membership.get("thinking").is_none(), "{membership}"),
198 }
199 assert!(membership.get("reasoning_effort").is_none(), "{membership}");
200 assert_eq!(membership["max_tokens"], json!(64), "{membership}");
201 assert!(
202 membership.get("max_completion_tokens").is_none(),
203 "{membership}"
204 );
205 // Kimi Code's documented membership models own their sampling
206 // behavior: the exact first-party membership route strips generic
207 // controls (apply_kimi_code_fixed_sampling).
208 assert!(membership.get("temperature").is_none(), "{membership}");
209 assert!(membership.get("top_p").is_none(), "{membership}");
210 }
211
212 let provider_default = capture_moonshot_chat_request(
213 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
214 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
215 None,
216 streaming,
217 )
218 .await;
219 assert!(
220 provider_default.get("thinking").is_none(),
221 "only a genuinely omitted effort leaves the provider default in control: {provider_default}"
222 );
223 assert!(provider_default.get("reasoning_effort").is_none());
224
225 let neighbor = capture_moonshot_chat_request(
226 "https://proxy.example/v1",
227 codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL,
228 Some("max"),
229 streaming,
230 )
231 .await;
232 assert_eq!(
233 neighbor["thinking"],
234 json!({"type": "enabled"}),
235 "{neighbor}"
236 );
237 assert!(neighbor.get("reasoning_effort").is_none(), "{neighbor}");
238 assert!(neighbor.pointer("/thinking/effort").is_none(), "{neighbor}");
239 assert_eq!(neighbor["max_tokens"], json!(64), "{neighbor}");
240 assert!(
241 neighbor.get("max_completion_tokens").is_none(),
242 "{neighbor}"
243 );
244 assert_eq!(neighbor["temperature"], json!(0.25), "{neighbor}");
245 assert_eq!(neighbor["top_p"], json!(0.75), "{neighbor}");
246 }
247
248 async fn assert_kimi_code_raw_off_replays_tool_history(streaming: bool) {
249 let mut request = k3_request_fixture(
250 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
251 Some("off"),
252 streaming,
253 );
254 request.messages = vec![
255 Message {
256 role: Role::Assistant,
257 content: vec![
258 ContentBlock::Thinking {
259 thinking: "Inspect the saved tool state".to_string(),
260 signature: None,
261 state: None,
262 redacted_data: None,
263 },
264 ContentBlock::ToolUse {
265 execution_id: None,
266 id: "call-k3-replay".to_string(),
267 name: "read_file".to_string(),
268 input: json!({"path": "src/lib.rs"}),
269 caller: None,
270 thought_signature: None,
271 },
272 ],
273 },
274 Message {
275 role: Role::User,
276 content: vec![ContentBlock::ToolResult {
277 execution_id: None,
278 tool_use_id: "call-k3-replay".to_string(),
279 content: "file contents".to_string(),
280 is_error: None,
281 content_blocks: None,
282 }],
283 },
284 ];
285
286 let body = capture_moonshot_chat_request_body(
287 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
288 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
289 request,
290 )
291 .await;
292 assert_eq!(
293 body["thinking"],
294 json!({"type": "enabled", "effort": "low"}),
295 "raw Off must still normalize to K3's always-thinking low tier: {body}"
296 );
297 let assistant = body["messages"]
298 .as_array()
299 .and_then(|messages| {
300 messages
301 .iter()
302 .find(|message| message["role"] == "assistant")
303 })
304 .expect("captured assistant tool-call history");
305 assert_eq!(
306 assistant["reasoning_content"],
307 json!("Inspect the saved tool state"),
308 "exact membership K3 must replay reasoning even for a stale raw Off caller: {body}"
309 );
310 assert!(assistant["tool_calls"].is_array(), "{assistant}");
311 }
312
313 async fn assert_kimi_code_apply_patch_schema_is_mfjs_compatible(streaming: bool) {
314 let mut request = k3_request_fixture(
315 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
316 Some("low"),
317 streaming,
318 );
319 request.tools = Some(vec![apply_patch_request_tool()]);
320
321 let body = capture_moonshot_chat_request_body(
322 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
323 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
324 request,
325 )
326 .await;
327 let function = &body["tools"][0]["function"];
328 let parameters = &function["parameters"];
329 assert_eq!(parameters["type"], "object", "{parameters}");
330 assert!(parameters.get("oneOf").is_none(), "{parameters}");
331 assert!(parameters.get("anyOf").is_none(), "{parameters}");
332 assert!(parameters.get("allOf").is_none(), "{parameters}");
333 assert_eq!(parameters["properties"]["patch"]["type"], "string");
334 assert_eq!(parameters["properties"]["replace"]["type"], "array");
335 assert!(parameters["properties"].get("changes").is_none());
336 assert!(
337 function["description"]
338 .as_str()
339 .is_some_and(|description| !description.is_empty()),
340 "tool description must be preserved: {function}"
341 );
342 }
343
344 // Per-tool degradation regression: the old behavior failed the whole
345 // request before transport when any tool's parameters failed MFJS
346 // validation; now only the incompatible tool is dropped from the wire
347 // body and the request still sends, so one bad MCP server cannot sink
348 // every Moonshot-routed turn.
349 async fn assert_kimi_code_invalid_root_ref_drops_only_that_tool(streaming: bool) {
350 let mut request = k3_request_fixture(
351 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
352 Some("low"),
353 streaming,
354 );
355 let mut tool = test_tool("private_schema_tool");
356 tool.input_schema = json!({
357 "$ref": "#/$defs/private-root-name-3158",
358 "$defs": {}
359 });
360 request.tools = Some(vec![tool]);
361 request.tool_choice = Some(json!("auto"));
362
363 let body = capture_moonshot_chat_request_body(
364 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
365 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
366 request,
367 )
368 .await;
369 assert!(
370 body.get("tools").is_none(),
371 "the only tool was dropped, so the wire body must omit tools entirely: {body}"
372 );
373 assert!(
374 body.get("tool_choice").is_none(),
375 "tool_choice must not be sent when every tool was dropped: {body}"
376 );
377 assert!(
378 !body.to_string().contains("private-root-name-3158"),
379 "the wire body must not leak the private $ref value: {body}"
380 );
381 }
382
383 async fn assert_kimi_code_untyped_default_drops_only_that_tool(streaming: bool) {
384 let mut request = k3_request_fixture(
385 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
386 Some("low"),
387 streaming,
388 );
389 let mut tool = test_tool("private_default_tool");
390 tool.input_schema = json!({
391 "type": "object",
392 "properties": {
393 "private-field-4401": {
394 "default": "private-default-value-4402"
395 }
396 }
397 });
398 request.tools = Some(vec![tool]);
399
400 let body = capture_moonshot_chat_request_body(
401 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
402 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
403 request,
404 )
405 .await;
406 assert!(
407 body.get("tools").is_none(),
408 "the only tool was dropped, so the wire body must omit tools entirely: {body}"
409 );
410 assert!(
411 body.get("tool_choice").is_none(),
412 "tool_choice must not be sent when every tool was dropped: {body}"
413 );
414 assert!(!body.to_string().contains("private-field-4401"));
415 assert!(!body.to_string().contains("private-default-value-4402"));
416 }
417
418 async fn assert_kimi_code_streams_mfjs_safe_deferred_dynamic_tool() {
419 let tool = deferred_dynamic_request_tool();
420 assert_eq!(tool.defer_loading, Some(true));
421 assert_eq!(
422 tool.input_schema["properties"]["query"]["nullable"], true,
423 "ToolRegistry must exercise the provider-neutral nullable collapse"
424 );
425 assert!(
426 tool.input_schema["properties"]["query"]
427 .get("anyOf")
428 .is_none()
429 );
430 assert_eq!(tool.input_schema["properties"]["mode"]["const"], "fast");
431
432 let mut request = k3_request_fixture(
433 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
434 Some("low"),
435 true,
436 );
437 request.tools = Some(vec![tool]);
438 let body = capture_moonshot_chat_request_body(
439 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
440 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
441 request,
442 )
443 .await;
444
445 assert_eq!(
446 body["stream"], true,
447 "this must exercise the SSE path: {body}"
448 );
449 let parameters = &captured_function(&body, "deferred_lookup")["parameters"];
450 assert_eq!(parameters["properties"]["mode"]["enum"], json!(["fast"]));
451 assert!(
452 parameters["properties"]["mode"].get("const").is_none(),
453 "{parameters}"
454 );
455 assert_eq!(
456 parameters["properties"]["query"]["anyOf"],
457 json!([{"type": "string"}, {"type": "null"}])
458 );
459 assert!(
460 parameters["properties"]["query"].get("nullable").is_none(),
461 "{parameters}"
462 );
463 codewhale_models::schema_sanitize::validate_mfjs_parameters(parameters).unwrap();
464 }
465
466 async fn assert_kimi_code_captures_exact_general_child_catalog() {
467 let tools = crate::tools::subagent::kimi_general_child_request_tools_fixture();
468 let source_len = tools.len();
469 let source_names = tools
470 .iter()
471 .map(|tool| tool.name.clone())
472 .collect::<std::collections::BTreeSet<_>>();
473 let expected_names = crate::core::engine::default_active_native_tool_names()
474 .iter()
475 .copied()
476 // Children can inspect the shared goal, but only its owning
477 // session can create it or change its completion state.
478 .filter(|name| !matches!(*name, "create_goal" | "update_goal"))
479 .chain([crate::tools::codemode::EXECUTE_TOOLS_TOOL_NAME])
480 .map(str::to_string)
481 .collect();
482 assert_eq!(source_names, expected_names);
483 assert!(!source_names.contains("get_goal"));
484 assert!(!source_names.contains("create_goal"));
485 assert!(!source_names.contains("update_goal"));
486
487 // Name the offending first-party tool in test-only diagnostics while
488 // production errors remain fixed and non-secret.
489 for tool in &tools {
490 let mut parameters = tool.input_schema.clone();
491 codewhale_models::schema_sanitize::sanitize_for_kimi_parameters(&mut parameters)
492 .unwrap_or_else(|error| panic!("General child tool {}: {error}", tool.name));
493 }
494
495 let mut request = k3_request_fixture(
496 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
497 Some("low"),
498 false,
499 );
500 request.tools = Some(tools);
501 let body = capture_moonshot_chat_request_body(
502 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
503 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
504 request,
505 )
506 .await;
507
508 let captured = body["tools"].as_array().expect("captured tool catalog");
509 assert_eq!(captured.len(), source_len);
510 for required in &source_names {
511 assert!(
512 captured_function(&body, required).is_object(),
513 "{required} must reach the Kimi Code wire"
514 );
515 }
516 assert!(
517 captured
518 .iter()
519 .all(|tool| tool["function"]["name"] != "create_goal")
520 );
521 assert!(
522 captured
523 .iter()
524 .all(|tool| tool["function"]["name"] != "update_goal")
525 );
526
527 for tool in captured {
528 let parameters = &tool["function"]["parameters"];
529 for unsupported in ["const", "nullable", "oneOf", "allOf"] {
530 assert!(
531 !value_contains_key(parameters, unsupported),
532 "captured {} still contains {unsupported}: {parameters}",
533 tool["function"]["name"]
534 );
535 }
536 codewhale_models::schema_sanitize::validate_mfjs_parameters(parameters).unwrap();
537 }
538 }
539
540 #[tokio::test]
541 async fn create_message_scenario() {
542 // Scenario consolidation of: create_message_request_json_honors_exact_k3_route_boundaries, create_message_stream_request_json_honors_exact_k3_route_boundaries, create_message_request_json_keeps_zai_effort_route_exact, create_message_stream_request_json_keeps_zai_effort_route_exact, create_message_request_json_keeps_minimax_token_dialect_exact, create_message_stream_request_json_keeps_minimax_token_dialect_exact, create_message_request_json_keeps_modelstudio_enable_thinking_exact, create_message_stream_request_json_keeps_modelstudio_enable_thinking_exact
543 // from create_message_request_json_honors_exact_k3_route_boundaries
544 {
545 assert_k3_request_json_route_boundaries(false).await;
546 }
547 // from create_message_stream_request_json_honors_exact_k3_route_boundaries
548 {
549 assert_k3_request_json_route_boundaries(true).await;
550 }
551 // from create_message_request_json_keeps_zai_effort_route_exact
552 {
553 assert_zai_request_truth(false).await;
554 }
555 // from create_message_stream_request_json_keeps_zai_effort_route_exact
556 {
557 assert_zai_request_truth(true).await;
558 }
559 // from create_message_request_json_keeps_minimax_token_dialect_exact
560 {
561 assert_minimax_request_truth(false).await;
562 }
563 // from create_message_stream_request_json_keeps_minimax_token_dialect_exact
564 {
565 assert_minimax_request_truth(true).await;
566 }
567 // from create_message_request_json_keeps_modelstudio_enable_thinking_exact
568 {
569 assert_modelstudio_request_truth(false).await;
570 }
571 // from create_message_stream_request_json_keeps_modelstudio_enable_thinking_exact
572 {
573 assert_modelstudio_request_truth(true).await;
574 }
575 }
576
577 #[tokio::test]
578 async fn kimi_code_compaction_shape_omits_sampling_parameters_on_wire() {
579 for model in codewhale_runtime::config::KIMI_CODE_MEMBERSHIP_MODELS {
580 let mut request = k3_request_fixture(model, None, /*stream*/ false);
581 request.temperature = Some(0.3);
582 request.top_p = Some(0.8);
583 let body = capture_moonshot_chat_request_body(
584 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
585 model,
586 request,
587 )
588 .await;
589
590 assert_eq!(body["model"], model);
591 assert!(body.get("temperature").is_none(), "{model}: {body}");
592 assert!(body.get("top_p").is_none(), "{model}: {body}");
593 }
594 }
595
596 /// v0.9.1 kimi-k3 dogfood report: the id the user selects has to be the id on the wire. A
597 /// dogfood user selecting `kimi-k3` was served `kimi-k2.7-code`, so this
598 /// asserts the wire `model` field for each K3 product on its own endpoint,
599 /// and that neither one's request carries the other's id.
600 #[tokio::test]
601 async fn selected_moonshot_k3_model_is_the_model_on_the_wire() {
602 let platform = capture_moonshot_chat_request(
603 codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL,
604 codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL,
605 Some("high"),
606 false,
607 )
608 .await;
609 assert_eq!(
610 platform["model"],
611 json!(codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL),
612 "the direct platform route must send the id the user named: {platform}"
613 );
614 assert_ne!(
615 platform["model"],
616 json!(codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_MODEL),
617 "an explicit selection is never replaced by the provider default: {platform}"
618 );
619 assert_ne!(
620 platform["model"],
621 json!(codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL),
622 "the coding-plan id must not leak onto the platform route: {platform}"
623 );
624
625 let membership = capture_moonshot_chat_request(
626 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
627 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
628 Some("high"),
629 false,
630 )
631 .await;
632 assert_eq!(
633 membership["model"],
634 json!(codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL),
635 "the Kimi Code membership route must send bare `k3`: {membership}"
636 );
637 assert_ne!(
638 membership["model"],
639 json!(codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL),
640 "the platform id must not leak onto the coding-plan route: {membership}"
641 );
642 }
643
644 #[tokio::test]
645 async fn create_message_scenario_2() {
646 // Scenario consolidation of: create_message_routes_only_strict_deepseek_tools_to_beta, create_message_stream_routes_only_strict_deepseek_tools_to_beta, create_message_request_replays_kimi_code_history_for_raw_off, create_message_stream_replays_kimi_code_history_for_raw_off, create_message_request_sends_mfjs_compatible_apply_patch_schema, create_message_stream_sends_mfjs_compatible_apply_patch_schema, create_message_request_drops_invalid_kimi_root_ref_tool, create_message_stream_drops_invalid_kimi_root_ref_tool
647 // from create_message_routes_only_strict_deepseek_tools_to_beta
648 {
649 assert_deepseek_strict_request_route_boundary(false).await;
650 }
651 // from create_message_stream_routes_only_strict_deepseek_tools_to_beta
652 {
653 assert_deepseek_strict_request_route_boundary(true).await;
654 }
655 // from create_message_request_replays_kimi_code_history_for_raw_off
656 {
657 assert_kimi_code_raw_off_replays_tool_history(false).await;
658 }
659 // from create_message_stream_replays_kimi_code_history_for_raw_off
660 {
661 assert_kimi_code_raw_off_replays_tool_history(true).await;
662 }
663 // from create_message_request_sends_mfjs_compatible_apply_patch_schema
664 {
665 assert_kimi_code_apply_patch_schema_is_mfjs_compatible(false).await;
666 }
667 // from create_message_stream_sends_mfjs_compatible_apply_patch_schema
668 {
669 assert_kimi_code_apply_patch_schema_is_mfjs_compatible(true).await;
670 }
671 // from create_message_request_drops_invalid_kimi_root_ref_tool
672 {
673 assert_kimi_code_invalid_root_ref_drops_only_that_tool(false).await;
674 }
675 // from create_message_stream_drops_invalid_kimi_root_ref_tool
676 {
677 assert_kimi_code_invalid_root_ref_drops_only_that_tool(true).await;
678 }
679 }
680
681 #[tokio::test]
682 async fn create_message_scenario_3() {
683 // Scenario consolidation of: create_message_request_drops_untyped_kimi_default_tool, create_message_stream_drops_untyped_kimi_default_tool, create_message_stream_sends_mfjs_safe_deferred_dynamic_tool, create_message_captures_exact_mfjs_safe_general_child_catalog
684 // from create_message_request_drops_untyped_kimi_default_tool
685 {
686 assert_kimi_code_untyped_default_drops_only_that_tool(false).await;
687 }
688 // from create_message_stream_drops_untyped_kimi_default_tool
689 {
690 assert_kimi_code_untyped_default_drops_only_that_tool(true).await;
691 }
692 // from create_message_stream_sends_mfjs_safe_deferred_dynamic_tool
693 {
694 assert_kimi_code_streams_mfjs_safe_deferred_dynamic_tool().await;
695 }
696 // from create_message_captures_exact_mfjs_safe_general_child_catalog
697 {
698 assert_kimi_code_captures_exact_general_child_catalog().await;
699 }
700 }
701
702 #[tokio::test]
703 async fn moonshot_drops_only_incompatible_tool() {
704 for streaming in [false, true] {
705 let mut request = k3_request_fixture(
706 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
707 Some("low"),
708 streaming,
709 );
710 let good = test_tool("compatible_lookup");
711 let mut bad = test_tool("mcp_pattern_tool");
712 bad.input_schema = json!({
713 "type": "object",
714 "properties": {
715 "query": {"type": "string", "pattern": "^private-regex-7701$"}
716 }
717 });
718 request.tools = Some(vec![good, bad]);
719 request.tool_choice = Some(json!("auto"));
720
721 let body = capture_moonshot_chat_request_body(
722 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
723 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
724 request,
725 )
726 .await;
727 let tools = body["tools"]
728 .as_array()
729 .expect("compatible tool must stay on the wire");
730 assert_eq!(
731 tools.len(),
732 1,
733 "only the incompatible tool may be dropped (streaming={streaming}): {body}"
734 );
735 assert_eq!(tools[0]["function"]["name"], "compatible_lookup");
736 assert_eq!(
737 body["tool_choice"],
738 json!("auto"),
739 "tool_choice survives while any tool remains: {body}"
740 );
741 assert!(
742 !body.to_string().contains("private-regex-7701"),
743 "the dropped tool's private schema values must not reach the wire: {body}"
744 );
745 }
746 }
747
748 #[tokio::test]
749 async fn moonshot_rejects_named_choice_for_omitted_tool() {
750 for streaming in [false, true] {
751 let server = MockServer::start().await;
752 let client = moonshot_request_boundary_client(
753 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
754 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
755 server.uri(),
756 );
757 let mut request = k3_request_fixture(
758 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
759 Some("low"),
760 streaming,
761 );
762 let good = test_tool("compatible_lookup");
763 let mut bad = test_tool("mcp_pattern_tool");
764 bad.input_schema = json!({
765 "type": "object",
766 "properties": {
767 "query": {"type": "string", "pattern": "^private-regex-8801$"}
768 }
769 });
770 request.tools = Some(vec![good, bad]);
771 request.tool_choice = Some(json!({
772 "type": "tool",
773 "name": "mcp_pattern_tool"
774 }));
775
776 let error = if streaming {
777 match client.create_message_stream(request).await {
778 Ok(_) => {
779 panic!("a named choice for an omitted tool must fail before transport")
780 }
781 Err(error) => error,
782 }
783 } else {
784 match client.create_message(request).await {
785 Ok(_) => {
786 panic!("a named choice for an omitted tool must fail before transport")
787 }
788 Err(error) => error,
789 }
790 };
791 let diagnostic = error.to_string();
792 assert!(
793 diagnostic.contains("cannot force an omitted tool"),
794 "streaming={streaming}: {diagnostic}"
795 );
796 assert!(
797 !diagnostic.contains("private-regex-8801"),
798 "schema values must not leak into the user-visible diagnostic: {diagnostic}"
799 );
800 assert!(
801 server
802 .received_requests()
803 .await
804 .expect("request log")
805 .is_empty(),
806 "dangling named tool_choice must fail locally (streaming={streaming})"
807 );
808 }
809 }
810
811 #[tokio::test]
812 async fn moonshot_emits_matching_blocking_and_stream_projection_warnings() {
813 let server = MockServer::start().await;
814 Mock::given(method("POST"))
815 .and(path("/v1/chat/completions"))
816 .and(wiremock::matchers::body_partial_json(
817 json!({"stream": true}),
818 ))
819 .respond_with(
820 ResponseTemplate::new(200)
821 .insert_header("content-type", "text/event-stream")
822 .set_body_string("data: [DONE]\n\n"),
823 )
824 .expect(1)
825 .mount(&server)
826 .await;
827 Mock::given(method("POST"))
828 .and(path("/v1/chat/completions"))
829 .and(|request: &wiremock::Request| {
830 request.body_json::<Value>().is_ok_and(|body| body["stream"] != true)
831 })
832 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
833 "id": "test", "model": "k3",
834 "choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}]
835 })))
836 .expect(1)
837 .mount(&server)
838 .await;
839 let client = moonshot_request_boundary_client(
840 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
841 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
842 server.uri(),
843 );
844 let mut request = k3_request_fixture(
845 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
846 Some("low"),
847 true,
848 );
849 let good = test_tool("compatible_lookup");
850 let mut bad = test_tool("mcp_pattern_tool");
851 bad.input_schema = json!({
852 "type": "object",
853 "properties": {
854 "query": {"type": "string", "pattern": "^private-regex-9901$"}
855 }
856 });
857 request.tools = Some(vec![good, bad]);
858 request.tool_choice = Some(json!("auto"));
859
860 let blocking = client
861 .create_message(request.clone())
862 .await
863 .expect("blocking response");
864 let warning = blocking
865 .tool_projection_warning
866 .expect("blocking omission warning");
867 let mut stream = client
868 .create_message_stream(request)
869 .await
870 .expect("compatible tools keep the request sendable");
871 let first = stream
872 .next()
873 .await
874 .expect("projection warning precedes provider SSE")
875 .expect("projection warning is not a stream error");
876 let (provider, omitted_tool_names, omitted_tool_count) = match first {
877 codewhale_models::StreamEvent::ToolProjectionWarning {
878 provider,
879 omitted_tool_names,
880 omitted_tool_count,
881 } => (provider, omitted_tool_names, omitted_tool_count),
882 other => panic!("first event must be the projection warning, got {other:?}"),
883 };
884 assert!(provider.contains("Moonshot"), "{provider}");
885 assert_eq!(omitted_tool_names, vec!["mcp_pattern_tool"]);
886 assert_eq!(omitted_tool_count, 1);
887 assert_eq!(warning.provider, provider);
888 assert_eq!(warning.omitted_tool_names, omitted_tool_names);
889 assert_eq!(warning.omitted_tool_count, omitted_tool_count);
890
891 let mut additional_warnings = 0;
892 while let Some(event) = stream.next().await {
893 if matches!(
894 event.expect("captured SSE response remains valid"),
895 codewhale_models::StreamEvent::ToolProjectionWarning { .. }
896 ) {
897 additional_warnings += 1;
898 }
899 }
900 assert_eq!(
901 additional_warnings, 0,
902 "warning must be emitted once per request"
903 );
904
905 let requests = server.received_requests().await.expect("recorded request");
906 assert_eq!(requests.len(), 2);
907 for request in requests {
908 let body: Value = serde_json::from_slice(&request.body).expect("request JSON");
909 assert_eq!(body["tools"].as_array().map(Vec::len), Some(1));
910 assert!(!body.to_string().contains("private-regex-9901"));
911 }
912 }
913
914 /// #6528 — a rejected key names the route, host, key source and the
915 /// command that replaces it; an unknown model names the route and host.
916 #[test]
917 fn auth_and_unknown_model_errors_name_route_host_and_key_source() {
918 let _ = rustls::crypto::ring::default_provider().install_default();
919 let config = {
920 let __cw_config_init_0_0 = Some("openrouter".to_string());
921 let __cw_config_init_0_1 = Some(ProvidersConfig {
922 openrouter: ProviderConfig {
923 api_key: Some("or-rejected-key-1234567890".to_string()),
924 ..ProviderConfig::default()
925 },
926 ..ProvidersConfig::default()
927 });
928 let mut __cw_config_init_0_value: Config = Config::default();
929 __cw_config_init_0_value.provider = __cw_config_init_0_0;
930 __cw_config_init_0_value.providers = __cw_config_init_0_1;
931 __cw_config_init_0_value
932 };
933 let client = CodewhaleClient::new(&config).expect("openrouter client");
934 let auth = client
935 .http_error_with_route_context(401, "Invalid API key", None, None)
936 .to_string();
937 assert!(auth.contains("provider: openrouter"), "{auth}");
938 assert!(auth.contains("openrouter.ai"), "{auth}");
939 assert!(auth.contains("key source: config file"), "{auth}");
940 assert!(
941 auth.contains("fix: codewhale auth set --provider openrouter"),
942 "{auth}"
943 );
944 assert!(!auth.contains("or-rejected-key-1234567890"), "{auth}");
945
946 let model = client
947 .http_error_with_route_context(404, "model not found: nope", None, None)
948 .to_string();
949 assert!(model.contains("provider route: openrouter"), "{model}");
950 assert!(model.contains("host: openrouter.ai"), "{model}");
951 }
952
953 /// A key route gets no subscription guidance; a sign-in route's plan
954 /// limit names the account label and the switch command, never a token.
955 #[test]
956 fn subscription_quota_errors_name_account_and_switch_command() {
957 let _ = rustls::crypto::ring::default_provider().install_default();
958 let config = {
959 let __cw_config_init_1_0 = Some("openrouter".to_string());
960 let __cw_config_init_1_1 = Some(ProvidersConfig {
961 openrouter: ProviderConfig {
962 api_key: Some("or-quota-key-1234567890".to_string()),
963 ..ProviderConfig::default()
964 },
965 ..ProvidersConfig::default()
966 });
967 let mut __cw_config_init_1_value: Config = Config::default();
968 __cw_config_init_1_value.provider = __cw_config_init_1_0;
969 __cw_config_init_1_value.providers = __cw_config_init_1_1;
970 __cw_config_init_1_value
971 };
972 let mut client = CodewhaleClient::new(&config).expect("openrouter client");
973 assert_eq!(client.subscription_limit_guidance, None);
974 let body =
975 r#"{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached"}}"#;
976 let plain = client.http_error_with_route_context(429, body, None, None);
977 assert!(matches!(plain, LlmError::QuotaExhausted(_)), "{plain:?}");
978 assert!(!plain.to_string().contains("codewhale auth"), "{plain}");
979
980 client.subscription_limit_guidance = Some(codewhale_runtime::oauth::usage_limit_guidance(
981 codewhale_runtime::oauth::OAuthProvider::Chatgpt,
982 Some("a@example.com (plus)"),
983 ));
984 let guided = client
985 .http_error_with_route_context(429, body, None, None)
986 .to_string();
987 assert!(
988 guided.contains("The usage limit has been reached"),
989 "{guided}"
990 );
991 assert!(
992 guided.contains("ChatGPT account a@example.com (plus)"),
993 "{guided}"
994 );
995 assert!(
996 guided.contains("`/auth chatgpt` in Codewhale, or `codewhale auth chatgpt` in a shell"),
997 "{guided}"
998 );
999 assert!(!guided.contains("or-quota-key-1234567890"), "{guided}");
1000 // Ordinary rate limits stay retryable and unannotated.
1001 let rate = client.http_error_with_route_context(429, "Too Many Requests", None, None);
1002 assert!(rate.is_retryable());
1003 assert!(!rate.to_string().contains("codewhale auth"), "{rate}");
1004 }
1005
1006 /// `auth_mode = "oauth"` alone does not mean a sign-in made the request:
1007 /// with no usable OAuth credential the resolver falls through to the API
1008 /// key, and a credit error must not blame (or name) a sign-in.
1009 #[test]
1010 fn xai_oauth_mode_that_fell_back_to_an_api_key_gets_no_sign_in_guidance() {
1011 let _ = rustls::crypto::ring::default_provider().install_default();
1012 let _env = crate::test_support::lock_test_env();
1013 let home = tempfile::tempdir().expect("temp home");
1014 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
1015 let _key = crate::test_support::EnvVarGuard::remove("XAI_API_KEY");
1016 let _base = crate::test_support::EnvVarGuard::remove("XAI_BASE_URL");
1017 let config = {
1018 let __cw_config_init_2_0 = Some("xai".to_string());
1019 let __cw_config_init_2_1 = Some(ProvidersConfig {
1020 xai: ProviderConfig {
1021 api_key: Some("xai-fallback-key-1234567890".to_string()),
1022 auth_mode: Some("oauth".to_string()),
1023 ..ProviderConfig::default()
1024 },
1025 ..ProvidersConfig::default()
1026 });
1027 let mut __cw_config_init_2_value: Config = Config::default();
1028 __cw_config_init_2_value.provider = __cw_config_init_2_0;
1029 __cw_config_init_2_value.providers = __cw_config_init_2_1;
1030 __cw_config_init_2_value
1031 };
1032 let client = CodewhaleClient::new(&config).expect("xai client");
1033 assert_ne!(
1034 client.api_key_source,
1035 codewhale_runtime::config::XAI_OAUTH_KEY_SOURCE
1036 );
1037 assert_eq!(client.subscription_limit_guidance, None);
1038 let body =
1039 r#"{"error":{"code":"credit_balance_exhausted","message":"credit balance exhausted"}}"#;
1040 let error = client
1041 .http_error_with_route_context(402, body, None, None)
1042 .to_string();
1043 assert!(!error.contains("codewhale auth"), "{error}");
1044 }
1045
1046 fn test_id_token(email: &str) -> String {
1047 use base64::Engine as _;
1048 format!(
1049 "header.{}.sig",
1050 base64::engine::general_purpose::URL_SAFE_NO_PAD
1051 .encode(json!({ "email": email }).to_string())
1052 )
1053 }
1054
1055 /// The official ChatGPT route names the selected owned grant even when a
1056 /// legacy external login is present and consented for import.
1057 #[test]
1058 fn chatgpt_quota_guidance_names_owned_grant_and_ignores_legacy_import() {
1059 let _ = rustls::crypto::ring::default_provider().install_default();
1060 let _env = crate::test_support::lock_test_env();
1061 let home = tempfile::tempdir().expect("temp home");
1062 let root = home.path().canonicalize().expect("canonical temp root");
1063 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
1064 let _access = crate::test_support::EnvVarGuard::remove("OPENAI_CODEX_ACCESS_TOKEN");
1065 let _legacy_access = crate::test_support::EnvVarGuard::remove("CODEX_ACCESS_TOKEN");
1066 let path = root.join("legacy-auth.json");
1067 std::fs::write(
1068 &path,
1069 serde_json::to_vec(&json!({"tokens": {
1070 "access_token": crate::test_support::future_test_jwt("legacy-import"),
1071 "id_token": test_id_token("legacy@example.com"),
1072 }}))
1073 .unwrap(),
1074 )
1075 .unwrap();
1076 let _auth_path = crate::test_support::EnvVarGuard::set("OPENAI_CODEX_AUTH_FILE", &path);
1077 let mut config = {
1078 let __cw_config_init_3_0 = Some(ProviderKind::OpenaiCodex.as_str().to_string());
1079 let __cw_config_init_3_1 = Some(ProvidersConfig {
1080 openai_codex: ProviderConfig {
1081 external_credentials: Some(
1082 codewhale_config::ExternalCredentialConsentToml::read_only(
1083 codewhale_config::ProviderKind::OpenaiCodex,
1084 codewhale_config::ExternalCredentialSource::CodexCli,
1085 path,
1086 ),
1087 ),
1088 ..ProviderConfig::default()
1089 },
1090 ..ProvidersConfig::default()
1091 });
1092 let mut __cw_config_init_3_value: Config = Config::default();
1093 __cw_config_init_3_value.provider = __cw_config_init_3_0;
1094 __cw_config_init_3_value.providers = __cw_config_init_3_1;
1095 __cw_config_init_3_value
1096 };
1097 assert!(
1098 CodewhaleClient::new(&config).is_err(),
1099 "an import cannot authorize the official route"
1100 );
1101 let config_path = root.join("config.toml");
1102 std::fs::write(&config_path, "").unwrap();
1103 // Stored verified-grant fixture; OAuth signature validation has its
1104 // own signed-token boundary tests.
1105 codewhale_runtime::oauth::activate_login(
1106 codewhale_runtime::oauth::pending_login_with_id_token_for_test(
1107 codewhale_runtime::oauth::OAuthProvider::Chatgpt,
1108 "own-verified-access",
1109 "own-verified-refresh",
1110 Some(&test_id_token("owned@example.com")),
1111 ),
1112 Some(&config_path),
1113 Some(&mut config),
1114 )
1115 .unwrap();
1116 let client = CodewhaleClient::new(&config).expect("official owned ChatGPT client");
1117 assert_eq!(client.api_key, "own-verified-access");
1118 let guidance = client.subscription_limit_guidance.as_deref().unwrap();
1119 assert!(
1120 guidance.contains("ChatGPT account owned@example.com"),
1121 "{guidance}"
1122 );
1123 assert!(!guidance.contains("legacy@example.com"), "{guidance}");
1124 let error = client.http_error_with_route_context(
1125 429,
1126 r#"{"error":{"code":"subscription_sharing_usage_limit_exceeded"}}"#,
1127 None,
1128 None,
1129 );
1130 assert!(matches!(error, LlmError::QuotaExhausted(_)));
1131 assert!(!error.is_retryable());
1132 assert!(error.to_string().contains("owned@example.com"));
1133 assert!(!error.to_string().contains("own-verified-access"));
1134 }
1135
1136 /// An xAI OAuth route names the signed-in account from the credential
1137 /// the client sends; the resolver, the guidance and the picker's
1138 /// credential source share that one read.
1139 #[test]
1140 fn xai_oauth_quota_guidance_names_the_signed_in_account() {
1141 let _ = rustls::crypto::ring::default_provider().install_default();
1142 let _env = crate::test_support::lock_test_env();
1143 let home = tempfile::tempdir().expect("temp home");
1144 let root = home.path().canonicalize().expect("canonical temp root");
1145 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
1146 let _key = crate::test_support::EnvVarGuard::remove("XAI_API_KEY");
1147 let _base = crate::test_support::EnvVarGuard::remove("XAI_BASE_URL");
1148 let config_path = root.join("config.toml");
1149 std::fs::write(&config_path, "").expect("empty config");
1150 let mut config = {
1151 let __cw_config_init_4_0 = Some("xai".to_string());
1152 let mut __cw_config_init_4_value: Config = Config::default();
1153 __cw_config_init_4_value.provider = __cw_config_init_4_0;
1154 __cw_config_init_4_value
1155 };
1156 codewhale_runtime::oauth::activate_login(
1157 codewhale_runtime::oauth::pending_login_with_id_token_for_test(
1158 codewhale_runtime::oauth::OAuthProvider::Xai,
1159 "xai-oauth-access",
1160 "xai-oauth-refresh",
1161 Some(&test_id_token("grok@example.com")),
1162 ),
1163 Some(&config_path),
1164 Some(&mut config),
1165 )
1166 .expect("xAI login");
1167 let client = CodewhaleClient::new(&config).expect("xai client");
1168 assert_eq!(client.api_key, "xai-oauth-access");
1169 assert_eq!(
1170 client.api_key_source,
1171 codewhale_runtime::config::XAI_OAUTH_KEY_SOURCE
1172 );
1173 let guidance = client
1174 .subscription_limit_guidance
1175 .as_deref()
1176 .expect("sign-in guidance");
1177 assert!(
1178 guidance.contains("xAI account grok@example.com"),
1179 "{guidance}"
1180 );
1181 assert!(!guidance.contains("xai-oauth-"), "{guidance}");
1182 assert_eq!(
1183 codewhale_runtime::config::resolve_credential_source(
1184 &config,
1185 &(config).test_identity_for_kind(ProviderKind::Xai)
1186 )
1187 .source,
1188 codewhale_runtime::credentials::CredentialSource::OAuth {
1189 flow: "xAI".to_string(),
1190 account: Some("grok@example.com".to_string()),
1191 }
1192 );
1193 }
1194
1195 /// #6715 review: a consented Grok CLI import is a sign-in the user can
1196 /// switch away from, and its quota error must name the account the Grok
1197 /// file holds (the credential this client sends), not a Codewhale-owned
1198 /// account that sent nothing.
1199 #[test]
1200 fn xai_quota_guidance_names_the_consented_grok_import_that_sent_the_request() {
1201 let _ = rustls::crypto::ring::default_provider().install_default();
1202 let _env = crate::test_support::lock_test_env();
1203 let home = tempfile::tempdir().expect("temp home");
1204 let root = home.path().canonicalize().expect("canonical temp root");
1205 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
1206 let _key = crate::test_support::EnvVarGuard::remove("XAI_API_KEY");
1207 let _base = crate::test_support::EnvVarGuard::remove("XAI_BASE_URL");
1208 let path = root.join("grok-auth.json");
1209 let token = crate::test_support::future_test_jwt("grok-cli");
1210 let scope = format!(
1211 "{}::{}",
1212 codewhale_runtime::oauth::XAI_OIDC_ISSUER,
1213 codewhale_runtime::oauth::GROK_OIDC_CLIENT_ID
1214 );
1215 std::fs::write(
1216 &path,
1217 serde_json::to_vec(&json!({
1218 scope: {
1219 "key": token.clone(),
1220 "expires_at": (chrono::Utc::now() + chrono::Duration::hours(1)).to_rfc3339(),
1221 "id_token": test_id_token("grok-cli@example.com"),
1222 "oidc_issuer": codewhale_runtime::oauth::XAI_OIDC_ISSUER,
1223 "oidc_client_id": codewhale_runtime::oauth::GROK_OIDC_CLIENT_ID,
1224 "auth_mode": "oidc",
1225 }
1226 }))
1227 .expect("serialize fixture"),
1228 )
1229 .expect("write fixture");
1230 let _auth_path = crate::test_support::EnvVarGuard::set("GROK_AUTH_PATH", &path);
1231 let config = {
1232 let __cw_config_init_5_0 = Some(ProviderKind::Xai.as_str().to_string());
1233 let __cw_config_init_5_1 = Some(ProvidersConfig {
1234 xai: ProviderConfig {
1235 auth_mode: Some("oauth".to_string()),
1236 external_credentials: Some(
1237 codewhale_config::ExternalCredentialConsentToml::read_only(
1238 codewhale_config::ProviderKind::Xai,
1239 codewhale_config::ExternalCredentialSource::GrokCli,
1240 path.clone(),
1241 ),
1242 ),
1243 ..ProviderConfig::default()
1244 },
1245 ..ProvidersConfig::default()
1246 });
1247 let mut __cw_config_init_5_value: Config = Config::default();
1248 __cw_config_init_5_value.provider = __cw_config_init_5_0;
1249 __cw_config_init_5_value.providers = __cw_config_init_5_1;
1250 __cw_config_init_5_value
1251 };
1252 let client = CodewhaleClient::new(&config).expect("xai client");
1253 assert_eq!(client.api_key, token);
1254 assert_eq!(
1255 client.api_key_source,
1256 codewhale_runtime::config::XAI_OAUTH_KEY_SOURCE
1257 );
1258 let guidance = client
1259 .subscription_limit_guidance
1260 .as_deref()
1261 .expect("sign-in guidance");
1262 assert!(
1263 guidance.contains("xAI account grok-cli@example.com"),
1264 "{guidance}"
1265 );
1266 assert!(!guidance.contains(&token), "{guidance}");
1267 }
1268
1269 /// Ambient legacy process tokens cannot authorize the official route.
1270 #[test]
1271 fn chatgpt_process_token_cannot_replace_owned_grant_or_account_guidance() {
1272 let _ = rustls::crypto::ring::default_provider().install_default();
1273 let _env = crate::test_support::lock_test_env();
1274 let home = tempfile::tempdir().expect("temp home");
1275 let root = home.path().canonicalize().expect("canonical temp root");
1276 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
1277 let token = crate::test_support::future_test_jwt("process-token");
1278 let _access = crate::test_support::EnvVarGuard::set("OPENAI_CODEX_ACCESS_TOKEN", &token);
1279 let _legacy_access = crate::test_support::EnvVarGuard::remove("CODEX_ACCESS_TOKEN");
1280 let mut config = {
1281 let __cw_config_init_6_0 = Some(ProviderKind::OpenaiCodex.as_str().to_string());
1282 let mut __cw_config_init_6_value: Config = Config::default();
1283 __cw_config_init_6_value.provider = __cw_config_init_6_0;
1284 __cw_config_init_6_value
1285 };
1286 assert!(CodewhaleClient::new(&config).is_err());
1287 let own = codewhale_runtime::oauth::install_test_chatgpt_registration(&mut config).unwrap();
1288 let client = CodewhaleClient::new(&config).expect("official ChatGPT client");
1289 assert_eq!(client.api_key, own);
1290 assert_ne!(client.api_key, token);
1291 assert!(client.subscription_limit_guidance.is_some());
1292 }
1293
1294 fn concentrate_client(server: &MockServer, model: &str) -> CodewhaleClient {
1295 let _ = rustls::crypto::ring::default_provider().install_default();
1296 let config = {
1297 let __cw_config_init_7_0 = Some("concentrate".to_string());
1298 let __cw_config_init_7_1 = Some(ProvidersConfig {
1299 concentrate: ProviderConfig {
1300 api_key: Some("concentrate-test-key".to_string()),
1301 base_url: Some(format!("{}/v1", server.uri())),
1302 model: Some(model.to_string()),
1303 ..ProviderConfig::default()
1304 },
1305 ..ProvidersConfig::default()
1306 });
1307 let mut __cw_config_init_7_value: Config = Config::default();
1308 __cw_config_init_7_value.provider = __cw_config_init_7_0;
1309 __cw_config_init_7_value.providers = __cw_config_init_7_1;
1310 __cw_config_init_7_value
1311 };
1312 CodewhaleClient::new(&config).expect("Concentrate client should resolve its route")
1313 }
1314
1315 /// The documented Concentrate stream: `event:`-typed `response.*` frames
1316 /// with sequence numbers and NO `data: [DONE]` sentinel.
1317 /// https://concentrate.ai/docs/api-reference/endpoint/streaming
1318 fn concentrate_sse_fixture(model: &str) -> String {
1319 let completed = json!({
1320 "id": "resp_1",
1321 "object": "response",
1322 "status": "completed",
1323 "model": model,
1324 "output": [{
1325 "type": "message", "id": "msg_1", "status": "completed", "role": "assistant",
1326 "content": [{"type": "output_text", "text": "ok from stub", "annotations": []}]
1327 }],
1328 "usage": {"input_tokens": 12, "output_tokens": 5, "total_tokens": 17,
1329 "input_tokens_details": {"cached_tokens": 0}}
1330 });
1331 let frame = |event: &str, payload: Value| format!("event: {event}\ndata: {}\n\n", payload);
1332 [
1333 frame("response.created", json!({"type": "response.created", "sequence_number": 0, "response": {"id": "resp_1", "status": "in_progress"}})),
1334 frame("response.output_item.added", json!({"type": "response.output_item.added", "sequence_number": 1, "output_index": 0, "item": {"type": "message", "id": "msg_1", "status": "in_progress", "role": "assistant", "content": []}})),
1335 frame("response.content_part.added", json!({"type": "response.content_part.added", "sequence_number": 2, "item_id": "msg_1", "output_index": 0, "content_index": 0, "part": {"type": "output_text", "text": ""}})),
1336 frame("response.output_text.delta", json!({"type": "response.output_text.delta", "sequence_number": 3, "item_id": "msg_1", "output_index": 0, "content_index": 0, "delta": "ok "})),
1337 frame("response.output_text.delta", json!({"type": "response.output_text.delta", "sequence_number": 4, "item_id": "msg_1", "output_index": 0, "content_index": 0, "delta": "from stub"})),
1338 frame("response.output_text.done", json!({"type": "response.output_text.done", "sequence_number": 5, "item_id": "msg_1", "output_index": 0, "content_index": 0, "text": "ok from stub"})),
1339 frame("response.output_item.done", json!({"type": "response.output_item.done", "sequence_number": 6, "output_index": 0, "item": completed["output"][0].clone()})),
1340 frame("response.completed", json!({"type": "response.completed", "sequence_number": 7, "response": completed})),
1341 ]
1342 .concat()
1343 }
1344
1345 /// Request URL, bearer header, verbatim model, documented-fields body, and
1346 /// the typed SSE stream (no `[DONE]`) — the whole Concentrate contract on
1347 /// a loopback wiremock, never the live gateway.
1348 #[tokio::test]
1349 async fn concentrate_responses_request_matches_the_documented_contract() {
1350 let server = MockServer::start().await;
1351 Mock::given(method("POST"))
1352 .and(path("/v1/responses"))
1353 .and(header("authorization", "Bearer concentrate-test-key"))
1354 .respond_with(
1355 ResponseTemplate::new(200)
1356 .insert_header("Content-Type", "text/event-stream")
1357 .set_body_string(concentrate_sse_fixture("openai/gpt-5.6-sol")),
1358 )
1359 .expect(1)
1360 .mount(&server)
1361 .await;
1362
1363 let client = concentrate_client(&server, "openai/gpt-5.6-sol");
1364 assert_eq!(client.wire_format, WireFormat::Responses);
1365 assert_eq!(client.api_provider, ProviderKind::Concentrate);
1366 assert_eq!(
1367 responses_api_url(
1368 DEFAULT_CONCENTRATE_BASE_URL,
1369 codewhale_config::responses_dialect::ResponsesPathPolicy::VersionedResponses,
1370 ),
1371 "https://api.concentrate.ai/v1/responses",
1372 "the official base URL maps to the documented Responses endpoint"
1373 );
1374
1375 let mut stream = client
1376 .create_message_stream(minimal_zen_request("openai/gpt-5.6-sol"))
1377 .await
1378 .expect("Concentrate Responses request should start");
1379 let mut text = String::new();
1380 let mut usage = None;
1381 let mut stopped = false;
1382 while let Some(event) = stream.next().await {
1383 match event.expect("Concentrate stream event") {
1384 StreamEvent::ContentBlockDelta {
1385 delta: Delta::TextDelta { text: piece },
1386 ..
1387 } => text.push_str(&piece),
1388 StreamEvent::MessageDelta { usage: Some(u), .. } => usage = Some(u),
1389 StreamEvent::MessageStop => stopped = true,
1390 _ => {}
1391 }
1392 }
1393 assert_eq!(text, "ok from stub", "typed deltas assemble the reply");
1394 let usage = usage.expect("response.completed carries usage");
1395 assert_eq!((usage.input_tokens, usage.output_tokens), (12, 5));
1396 assert!(
1397 stopped,
1398 "the stream ends on response.completed without a [DONE] sentinel"
1399 );
1400
1401 let requests = server.received_requests().await.expect("recorded request");
1402 assert_eq!(requests.len(), 1);
1403 let request = &requests[0];
1404 assert_eq!(request.url.path(), "/v1/responses");
1405 for forbidden in [
1406 "openai-beta",
1407 "originator",
1408 "chatgpt-account-id",
1409 "x-api-key",
1410 ] {
1411 assert!(
1412 request.headers.get(forbidden).is_none(),
1413 "Concentrate request must not include {forbidden}"
1414 );
1415 }
1416 let body: Value = serde_json::from_slice(&request.body).expect("Responses JSON body");
1417 assert_eq!(
1418 body["model"], "openai/gpt-5.6-sol",
1419 "model id verbatim: {body}"
1420 );
1421 assert_eq!(body["stream"], true);
1422 assert!(
1423 body.get("messages").is_none(),
1424 "Responses body, not Chat: {body}"
1425 );
1426 for undocumented in [
1427 "store",
1428 "include",
1429 "instructions",
1430 "metadata",
1431 "previous_response_id",
1432 ] {
1433 assert!(
1434 body.get(undocumented).is_none(),
1435 "undocumented field {undocumented} on the wire: {body}"
1436 );
1437 }
1438 assert_eq!(
1439 body["input"][0]["role"], "system",
1440 "system prompt rides as a system input item: {body}"
1441 );
1442 }
1443
1444 /// The documented error body surfaces verbatim and classifies by message:
1445 /// 401 → authentication, 402 → quota (insufficient credits).
1446 /// https://concentrate.ai/docs/api-reference/endpoint/errors
1447 #[tokio::test]
1448 async fn concentrate_error_bodies_surface_verbatim_and_classify() {
1449 for (status, body, expected, needle) in [
1450 (
1451 401,
1452 r#"{"error":"Unauthorized","message":"Invalid API key"}"#,
1453 codewhale_error_taxonomy::ErrorCategory::Authentication,
1454 "Invalid API key",
1455 ),
1456 (
1457 402,
1458 r#"{"error":"Insufficient funds","message":"Your account has insufficient credits. Please add credits to continue."}"#,
1459 codewhale_error_taxonomy::ErrorCategory::RateLimit,
1460 "insufficient credits",
1461 ),
1462 (
1463 400,
1464 r#"{"error":"Bad Request","message":"Invalid model name: 'invalid-model-xyz'"}"#,
1465 codewhale_error_taxonomy::ErrorCategory::InvalidInput,
1466 "Invalid model name",
1467 ),
1468 ] {
1469 let server = MockServer::start().await;
1470 Mock::given(method("POST"))
1471 .and(path("/v1/responses"))
1472 .respond_with(ResponseTemplate::new(status).set_body_string(body))
1473 .mount(&server)
1474 .await;
1475 let client = concentrate_client(&server, "gpt-5.6-sol");
1476 let error = match client
1477 .create_message_stream(minimal_zen_request("gpt-5.6-sol"))
1478 .await
1479 {
1480 Ok(mut stream) => {
1481 let mut failure = None;
1482 while let Some(event) = stream.next().await {
1483 if let Err(err) = event {
1484 failure = Some(err);
1485 break;
1486 }
1487 }
1488 failure.expect("HTTP {status} must fail the stream")
1489 }
1490 Err(err) => err,
1491 };
1492 let message = format!("{error:#}");
1493 assert!(
1494 message.contains(needle),
1495 "HTTP {status}: message must carry the documented text, got: {message}"
1496 );
1497 assert_eq!(
1498 codewhale_error_taxonomy::classify_error_message(&message),
1499 expected,
1500 "HTTP {status}: {message}"
1501 );
1502 }
1503 }
1504
1505 /// Concentrate's `GET /v1/models` is unauthenticated, so a 2xx must not
1506 /// count as key verification. Guided setup treats the probe as unobserved;
1507 /// health_check must not issue the request either.
1508 #[tokio::test]
1509 async fn concentrate_health_check_does_not_treat_unauthenticated_models_as_key_proof() {
1510 let server = MockServer::start().await;
1511 let client = concentrate_client(&server, DEFAULT_CONCENTRATE_MODEL);
1512
1513 assert!(client.health_check().await.expect("health check"));
1514 assert!(!provider_api_key_verification_is_observed(
1515 ProviderKind::Concentrate
1516 ));
1517 let runcrate = codewhale_config::descriptors::provider_descriptor("runcrate").unwrap();
1518 assert!(!provider_api_key_verification_is_observed_for_route(
1519 ProviderKind::Custom,
1520 &runcrate.base_url
1521 ));
1522 assert!(provider_api_key_verification_is_observed_for_route(
1523 ProviderKind::Custom,
1524 &format!("{}/account", runcrate.base_url)
1525 ));
1526 assert!(
1527 verify_provider_api_key(ProviderKind::Custom, "fixture", &runcrate.base_url)
1528 .await
1529 .unwrap()
1530 .is_none()
1531 );
1532 let requests = server.received_requests().await.expect("recorded requests");
1533 assert!(
1534 requests.is_empty(),
1535 "Concentrate must not treat unauthenticated GET /v1/models as key verification"
1536 );
1537 }
1538
1539 /// `GET /v1/models` needs no key and answers the OpenAI list shape; rows
1540 /// are provider-scoped, the default is marked, and unknowns stay unclaimed.
1541 /// https://concentrate.ai/docs/api-reference/endpoint/list-models
1542 #[tokio::test]
1543 async fn concentrate_live_catalog_is_provider_scoped_and_marks_the_default() {
1544 let server = MockServer::start().await;
1545 Mock::given(method("GET"))
1546 .and(path("/v1/models"))
1547 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1548 "object": "list",
1549 "data": [
1550 {"id": "claude-fable-5", "object": "model", "owned_by": "anthropic"},
1551 {"id": DEFAULT_CONCENTRATE_MODEL, "object": "model", "owned_by": "deepseek"},
1552 {"id": "gpt-5.6-sol", "object": "model", "owned_by": "openai"}
1553 ]
1554 })))
1555 .expect(1)
1556 .mount(&server)
1557 .await;
1558
1559 let delta = concentrate_client(&server, DEFAULT_CONCENTRATE_MODEL)
1560 .fetch_catalog_delta()
1561 .await
1562 .expect("Concentrate catalog delta");
1563 assert_eq!(delta.provider, "concentrate");
1564 assert_eq!(delta.offerings.len(), 3);
1565 let default = delta
1566 .offerings
1567 .iter()
1568 .find(|offering| offering.wire_model_id == DEFAULT_CONCENTRATE_MODEL)
1569 .expect("default row");
1570 assert!(default.default_for_provider);
1571 let unknown = delta
1572 .offerings
1573 .iter()
1574 .find(|offering| offering.wire_model_id == "claude-fable-5")
1575 .expect("unclaimed row");
1576 assert!(!unknown.default_for_provider);
1577 assert_eq!(unknown.canonical_model, None);
1578 assert_eq!(
1579 unknown.cost, None,
1580 "no pricing claim from a gateway catalog"
1581 );
1582 assert!(matches!(unknown.source, CatalogSource::Live { .. }));
1583 }
1584
1585 /// A Codewhale-route client pointed at a loopback stub.
1586 ///
1587 /// `base_url` goes through the provider table rather than
1588 /// `CODEWHALE_API_BASE` so the test does not mutate process env, but it
1589 /// exercises the same "declared origin" path: the key must follow the
1590 /// route to whatever origin the operator pointed it at.
1591 fn codewhale_client(server: &MockServer, model: &str) -> CodewhaleClient {
1592 let config = {
1593 let __cw_config_init_8_0 = Some("codewhale".to_string());
1594 let __cw_config_init_8_1 = Some(ProvidersConfig {
1595 codewhale: ProviderConfig {
1596 api_key: Some("cwc_key_test_value".to_string()),
1597 base_url: Some(server.uri()),
1598 model: Some(model.to_string()),
1599 ..ProviderConfig::default()
1600 },
1601 ..ProvidersConfig::default()
1602 });
1603 let mut __cw_config_init_8_value: Config = Config::default();
1604 __cw_config_init_8_value.provider = __cw_config_init_8_0;
1605 __cw_config_init_8_value.providers = __cw_config_init_8_1;
1606 __cw_config_init_8_value
1607 };
1608 CodewhaleClient::new(&config).expect("Codewhale client should resolve its model route")
1609 }
1610
1611 /// The account key must ride as `Authorization: Bearer` and never as
1612 /// `x-api-key`, on both protocols the account API serves.
1613 fn assert_codewhale_bearer(request: &wiremock::Request) {
1614 assert_eq!(
1615 request
1616 .headers
1617 .get(AUTHORIZATION)
1618 .and_then(|value| value.to_str().ok()),
1619 Some("Bearer cwc_key_test_value")
1620 );
1621 assert!(
1622 request.headers.get("x-api-key").is_none(),
1623 "the Codewhale API does not accept x-api-key"
1624 );
1625 }
1626
1627 #[tokio::test]
1628 async fn codewhale_chat_request_carries_the_account_bearer() {
1629 let server = MockServer::start().await;
1630 Mock::given(method("POST"))
1631 .and(path("/v1/chat/completions"))
1632 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1633 "id": "chatcmpl_cw",
1634 "object": "chat.completion",
1635 "model": "deepseek/deepseek-v4-pro",
1636 "choices": [{
1637 "index": 0,
1638 "message": {"role": "assistant", "content": "ok"},
1639 "finish_reason": "stop"
1640 }],
1641 "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
1642 })))
1643 .expect(1)
1644 .mount(&server)
1645 .await;
1646
1647 let client = codewhale_client(&server, "deepseek/deepseek-v4-pro");
1648 assert_eq!(client.wire_format, WireFormat::ChatCompletions);
1649 client
1650 .create_message(minimal_zen_request("deepseek/deepseek-v4-pro"))
1651 .await
1652 .expect("Codewhale chat request should succeed");
1653
1654 let requests = server.received_requests().await.expect("recorded request");
1655 assert_eq!(requests.len(), 1);
1656 assert_codewhale_bearer(&requests[0]);
1657 let body: Value = serde_json::from_slice(&requests[0].body).expect("chat JSON body");
1658 // Model ids reach the account API exactly as its catalog returns them.
1659 assert_eq!(
1660 body.get("model").and_then(Value::as_str),
1661 Some("deepseek/deepseek-v4-pro")
1662 );
1663 }
1664
1665 #[tokio::test]
1666 async fn codewhale_messages_request_carries_the_account_bearer_not_x_api_key() {
1667 let server = MockServer::start().await;
1668 Mock::given(method("POST"))
1669 .and(path("/v1/messages"))
1670 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1671 "id": "msg_cw",
1672 "type": "message",
1673 "role": "assistant",
1674 "content": [{"type": "text", "text": "ok"}],
1675 "model": "anthropic/claude-sonnet-5",
1676 "stop_reason": "end_turn",
1677 "stop_sequence": null,
1678 "usage": {"input_tokens": 1, "output_tokens": 1}
1679 })))
1680 .expect(1)
1681 .mount(&server)
1682 .await;
1683
1684 let client = codewhale_client(&server, "anthropic/claude-sonnet-5");
1685 assert_eq!(client.wire_format, WireFormat::AnthropicMessages);
1686 client
1687 .create_message(minimal_zen_request("anthropic/claude-sonnet-5"))
1688 .await
1689 .expect("Codewhale messages request should succeed");
1690
1691 let requests = server.received_requests().await.expect("recorded request");
1692 assert_eq!(requests.len(), 1);
1693 assert_codewhale_bearer(&requests[0]);
1694 assert_eq!(
1695 requests[0]
1696 .headers
1697 .get("anthropic-version")
1698 .and_then(|value| value.to_str().ok()),
1699 Some("2023-06-01")
1700 );
1701 }
1702
1702 lines RUST