返回 CodeWhale
prepared.rs
根目录 / crates / engine / src / client / prepared.rs
1 //! The single prepared-outbound-request seam shared by production dispatch
2 //! and `/preview-request` (#1004, #3928).
3 //!
4 //! Every **primary agent turn** — `LlmClient::create_message` and
5 //! `create_message_stream`, in Chat Completions, Anthropic Messages, and
6 //! OpenAI Responses alike — reaches the wire through
7 //! [`crate::client::CodewhaleClient::prepare_outbound_request`], which returns a
8 //! [`PreparedOutboundRequest`]. The transports send it; the preview command
9 //! describes it. Because there is exactly one builder, a preview cannot
10 //! report a request different from the one a turn would send.
11 //!
12 //! Scope, stated plainly: this is *not* every outbound request Codewhale
13 //! makes. Chat-dialect translation builds its own small fixed body, and FIM,
14 //! speech, provider-native search, model listing, and the auto-router
15 //! classifier are separate calls with separate shapes. They are auxiliary and
16 //! are not described by the request manifest. See `docs/PREVIEW_REQUEST.md`.
17 //!
18 //! Nothing in this module performs I/O, mutates client state, or reads the
19 //! filesystem. It is safe to call on any thread at any time.
20 //!
21 //! The seam concept — prepare the exact outbound body once, then let both the
22 //! sender and the inspector consume it — is harvested from PR #1099
23 //! (`build_sanitized_chat_completion_body`) by TaoMu (GTC2080). The
24 //! implementation here is written against the current multi-dialect client.
25
26 use serde::Serialize;
27 use serde_json::Value;
28
29 use codewhale_config::provider::WireFormat;
30 use codewhale_config::responses_dialect::ResponsesProfileId;
31 use codewhale_runtime::hashing::canonical_json;
32
33 use codewhale_config::ProviderKind;
34
35 pub(super) const REQUEST_BODY_BYTE_TRIGGER: usize = 32 * 1024 * 1024;
36 pub(super) const REQUEST_BODY_BYTE_TARGET: usize = 16 * 1024 * 1024;
37 pub(super) const REQUEST_BODY_IMAGE_NOTE: &str = "[Image omitted from this request to fit Codewhale's local request-byte budget. The original remains in the session. Do not guess what it showed. Take a fresh observation if needed; do not repeat an action to recover its image.]";
38 pub(super) const REQUEST_BODY_413_IMAGE_NOTE: &str = "[Image omitted from this retry because the provider rejected the request body as too large (HTTP 413). The original remains in the session. Do not guess what it showed. Take a fresh observation if needed; do not repeat an action to recover its image.]";
39
40 /// The wire protocol a prepared request speaks.
41 ///
42 /// This is the production dialect set. It is deliberately *not* collapsed to
43 /// Chat Completions: projecting an Anthropic Messages or Responses turn
44 /// through the Chat builder would describe a body that is never sent.
45 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
46 #[serde(rename_all = "kebab-case")]
47 pub enum WireDialect {
48 /// OpenAI-style `POST /chat/completions`.
49 ChatCompletions,
50 /// Anthropic-style `POST /v1/messages`.
51 AnthropicMessages,
52 /// OpenAI-style `POST /responses`.
53 OpenAiResponses,
54 GenerateContent,
55 }
56
57 impl WireDialect {
58 pub fn from_wire_format(format: WireFormat) -> Self {
59 match format {
60 WireFormat::ChatCompletions => Self::ChatCompletions,
61 WireFormat::AnthropicMessages => Self::AnthropicMessages,
62 WireFormat::Responses => Self::OpenAiResponses,
63 WireFormat::GenerateContent => Self::GenerateContent,
64 }
65 }
66
67 /// Stable machine label. Used in manifests and tests.
68 pub fn as_str(self) -> &'static str {
69 match self {
70 Self::ChatCompletions => "chat-completions",
71 Self::AnthropicMessages => "anthropic-messages",
72 Self::OpenAiResponses => "openai-responses",
73 Self::GenerateContent => "generate-content",
74 }
75 }
76 }
77
78 /// The provider-specific *shape* selected inside a dialect.
79 ///
80 /// Two routes can share a dialect and still produce structurally different
81 /// bodies and different endpoint paths (DeepSeek's strict-tools `/beta` path,
82 /// Kimi Code's nested `thinking.effort`, the ChatGPT Codex Responses path).
83 /// Naming the shape keeps the manifest honest about which builder branch ran
84 /// without exposing the route URL.
85 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
86 #[serde(rename_all = "kebab-case")]
87 pub enum RouteShape {
88 /// Plain dialect defaults for this provider.
89 Standard,
90 /// DeepSeek's `/beta/chat/completions` strict-tools path.
91 DeepseekBetaStrictTools,
92 /// The exact Kimi Code membership route (nested `thinking.effort`).
93 KimiCodeK3,
94 /// The exact pay-as-you-go Moonshot K3 route (fixed sampling).
95 DirectMoonshotK3,
96 /// The ChatGPT plan Responses path; identifier retained for saved receipts.
97 CodexResponses,
98 /// OpenCode Zen, whose model route re-resolves the wire model per request.
99 OpencodeZen,
100 /// A user-configured custom/compatible endpoint on a standard dialect.
101 CustomCompatible,
102 }
103
104 impl RouteShape {
105 pub fn as_str(self) -> &'static str {
106 match self {
107 Self::Standard => "standard",
108 Self::DeepseekBetaStrictTools => "deepseek-beta-strict-tools",
109 Self::KimiCodeK3 => "kimi-code-k3",
110 Self::DirectMoonshotK3 => "direct-moonshot-k3",
111 Self::CodexResponses => "codex-responses",
112 Self::OpencodeZen => "opencode-zen",
113 Self::CustomCompatible => "custom-compatible",
114 }
115 }
116 }
117
118 /// Which endpoint this request would be POSTed to, as typed facts.
119 ///
120 /// `url` is the real, unredacted target: production needs it to send. Every
121 /// display surface must go through [`codewhale_sanitize::sanitize::redact_url_for_display`] rather
122 /// than printing it, and the manifest only ever publishes the redacted
123 /// scheme/host and a fingerprint — never the path, which can itself carry a
124 /// deployment secret.
125 #[derive(Debug, Clone)]
126 pub struct EndpointIdentity {
127 /// Stable provider id (`ProviderKind::as_str`).
128 pub provider_id: String,
129 /// Human-facing provider name.
130 pub provider_display: String,
131 /// The configured route identity when the user named a custom provider,
132 /// e.g. a `[providers.<name>]` key. `None` for built-ins.
133 pub route_id: Option<String>,
134 /// Full POST target. Never rendered directly.
135 pub url: String,
136 /// Which builder branch produced the body.
137 pub shape: RouteShape,
138 }
139
140 /// What reasoning controls actually landed on the wire, and what was asked
141 /// for.
142 ///
143 /// The receipt is derived from the finished body, not from the intent that
144 /// went in: if a route-specific shaper stripped `reasoning_effort` and wrote
145 /// a nested `thinking.effort` instead, that is what this reports.
146 #[derive(Debug, Clone, PartialEq, Eq)]
147 pub struct ReasoningReceipt {
148 /// The effort string handed to the builder, if any.
149 pub requested_effort: Option<String>,
150 /// Reasoning-shaping fields present on the finished body, in a stable
151 /// order. Keys only come from the dialect allowlist below, so no message
152 /// or prompt content can leak through this field.
153 pub wire_controls: Vec<(String, Value)>,
154 }
155
156 /// A key that only *discloses* reasoning output; it does not ask the route to
157 /// think. Reporting `include` as a reasoning control would make every Responses
158 /// turn look like a deliberate thinking request.
159 const REASONING_DISCLOSURE_ONLY_KEYS: &[&str] = &["include"];
160
161 impl ReasoningReceipt {
162 /// Reasoning-control keys, per dialect. Anything not on this list is not
163 /// a reasoning control and never enters the receipt.
164 fn control_keys(dialect: WireDialect) -> &'static [&'static str] {
165 match dialect {
166 WireDialect::ChatCompletions => &[
167 "reasoning_effort",
168 "thinking",
169 "think",
170 "reasoning",
171 "reasoning_split",
172 "chat_template_kwargs",
173 ],
174 WireDialect::AnthropicMessages => &["thinking", "output_config"],
175 WireDialect::OpenAiResponses => &["reasoning", "include"],
176 WireDialect::GenerateContent => &[],
177 }
178 }
179
180 fn from_body(dialect: WireDialect, body: &Value, requested_effort: Option<String>) -> Self {
181 let mut wire_controls = Vec::new();
182 for key in Self::control_keys(dialect) {
183 if let Some(value) = body.get(*key) {
184 wire_controls.push(((*key).to_string(), value.clone()));
185 }
186 }
187 Self {
188 requested_effort,
189 wire_controls,
190 }
191 }
192
193 /// The plain `reasoning_effort` string when the route uses that dialect.
194 pub fn wire_effort_string(&self) -> Option<&str> {
195 self.wire_controls
196 .iter()
197 .find(|(key, _)| key == "reasoning_effort")
198 .and_then(|(_, value)| value.as_str())
199 }
200
201 /// The effort **actually on the wire**, with the key path it was read from.
202 ///
203 /// Flat `reasoning_effort` is only one of the shapes production emits. The
204 /// Kimi Code route writes `thinking.effort`, the Responses dialect writes
205 /// `reasoning.effort`, and the Anthropic dialect writes
206 /// `output_config.effort`. Reporting only the flat key made every nested
207 /// route read as "no effort sent", which is exactly backwards: those are
208 /// the routes that were asked to think hardest.
209 ///
210 /// The returned key path is a compile-time constant taken from
211 /// [`Self::control_keys`], never a key read out of the body, so no
212 /// provider-shaped field name can reach a manifest surface through it.
213 pub fn wire_effort(&self) -> Option<(&'static str, &str)> {
214 if let Some(effort) = self.wire_effort_string() {
215 return Some(("reasoning_effort", effort));
216 }
217 for (key, value) in &self.wire_controls {
218 let Some(effort) = value.get("effort").and_then(Value::as_str) else {
219 continue;
220 };
221 let path = match key.as_str() {
222 "thinking" => "thinking.effort",
223 "reasoning" => "reasoning.effort",
224 "output_config" => "output_config.effort",
225 "think" => "think.effort",
226 "reasoning_split" => "reasoning_split.effort",
227 "chat_template_kwargs" => "chat_template_kwargs.effort",
228 _ => continue,
229 };
230 return Some((path, effort));
231 }
232 None
233 }
234
235 /// True when the body actually asks the route to think.
236 ///
237 /// Deliberately *not* "the receipt is non-empty": a Responses body that
238 /// carries only `include: ["reasoning.encrypted_content"]` is *disclosing*
239 /// reasoning output, not requesting a tier, and must not be reported as an
240 /// explicit reasoning selection.
241 pub fn controls_reasoning(&self) -> bool {
242 self.wire_controls
243 .iter()
244 .any(|(key, _)| !REASONING_DISCLOSURE_ONLY_KEYS.contains(&key.as_str()))
245 }
246 }
247
248 /// Which transport entry point asked for this request.
249 ///
250 /// This is *caller* intent, not a wire fact. The OpenAI Responses blocking
251 /// entry point deliberately opens an SSE stream and folds it into one
252 /// response, so its body carries `"stream": true` while the caller mode is
253 /// [`Self::Blocking`]. Reporting the two separately is the only way for a
254 /// manifest to describe the body exactly and still say which entry point it
255 /// described. See [`PreparedOutboundRequest::wire_stream_field`].
256 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
257 #[serde(rename_all = "kebab-case")]
258 pub enum CallerStreamMode {
259 /// `create_message_stream` — the caller consumes stream events.
260 Streaming,
261 /// `create_message` — the caller wants one finished response.
262 Blocking,
263 }
264
265 impl CallerStreamMode {
266 pub fn from_stream_flag(stream: bool) -> Self {
267 if stream {
268 Self::Streaming
269 } else {
270 Self::Blocking
271 }
272 }
273
274 pub fn as_str(self) -> &'static str {
275 match self {
276 Self::Streaming => "streaming",
277 Self::Blocking => "blocking",
278 }
279 }
280 }
281
282 /// One fully prepared, not-yet-sent outbound request.
283 ///
284 /// Both `CodewhaleClient::create_message*` and `/preview-request` consume this
285 /// value. Adding a field here is how a new wire fact becomes visible to the
286 /// preview; there is no second builder to keep in sync.
287 #[derive(Debug, Clone)]
288 pub struct PreparedOutboundRequest {
289 pub dialect: WireDialect,
290 pub endpoint: EndpointIdentity,
291 /// The model id literally placed on the wire, after route remapping.
292 pub wire_model: String,
293 /// The final, provider-shaped body. This is the exact JSON that would be
294 /// serialized and POSTed.
295 pub body: Value,
296 pub reasoning: ReasoningReceipt,
297 /// Tokens re-sent because thinking-mode replay substituted
298 /// `reasoning_content` (Chat streaming only).
299 pub replay_input_tokens: Option<u32>,
300 /// Which transport entry point prepared this request. Never a substitute
301 /// for [`Self::wire_stream_field`], which is the wire truth.
302 pub entrypoint: CallerStreamMode,
303 /// Dialect id copied from the client. It is not inserted into `body`, and
304 /// `canonical_body` / `body_sha256` do not cover it.
305 pub responses_profile_id: Option<ResponsesProfileId>,
306 /// Wire-normalized tool names omitted by the route tool projection for
307 /// this request. It only transports a bounded user-visible warning.
308 pub omitted_tool_names: Vec<String>,
309 pub image_omission_notice: Option<String>,
310 pub image_projection: Option<crate::llm_client::ImageProjectionReceipt>,
311 }
312
313 impl PreparedOutboundRequest {
314 pub fn new(
315 dialect: WireDialect,
316 endpoint: EndpointIdentity,
317 wire_model: String,
318 body: Value,
319 requested_effort: Option<String>,
320 replay_input_tokens: Option<u32>,
321 entrypoint: CallerStreamMode,
322 ) -> Self {
323 let reasoning = ReasoningReceipt::from_body(dialect, &body, requested_effort);
324 Self {
325 dialect,
326 endpoint,
327 wire_model,
328 body,
329 reasoning,
330 replay_input_tokens,
331 entrypoint,
332 responses_profile_id: None,
333 omitted_tool_names: Vec::new(),
334 image_omission_notice: None,
335 image_projection: None,
336 }
337 }
338
339 pub fn tool_projection_warning(&self) -> Option<codewhale_models::ToolProjectionWarning> {
340 (!self.omitted_tool_names.is_empty()).then(|| codewhale_models::ToolProjectionWarning {
341 provider: self.endpoint.provider_display.clone(),
342 omitted_tool_names:
343 codewhale_models::tool_projection::bounded_tool_projection_warning_names(
344 &self.omitted_tool_names,
345 ),
346 omitted_tool_count: self.omitted_tool_names.len(),
347 })
348 }
349
350 pub fn serialized_body_bytes(&self) -> anyhow::Result<usize> {
351 let mut writer = codewhale_util::utils::CountingWriter::new();
352 serde_json::to_writer(&mut writer, &self.body)?;
353 Ok(writer.count())
354 }
355
356 #[must_use]
357 pub fn with_omitted_tool_names(mut self, names: Vec<String>) -> Self {
358 self.omitted_tool_names = names;
359 self
360 }
361
362 #[must_use]
363 pub fn with_responses_profile_id(mut self, profile: Option<ResponsesProfileId>) -> Self {
364 self.responses_profile_id = profile;
365 self
366 }
367
368 /// The `stream` field **as it appears on the finished body**, or `None`
369 /// when the body carries no such field at all.
370 ///
371 /// This is the wire truth and the only value a manifest may present as
372 /// "what the request says". It is deliberately not derived from
373 /// [`Self::entrypoint`]: the Responses blocking path sends
374 /// `"stream": true` and the Chat blocking path omits the field entirely,
375 /// so both would be misreported by the caller mode.
376 pub fn wire_stream_field(&self) -> Option<bool> {
377 self.body.get("stream").and_then(Value::as_bool)
378 }
379
380 /// Canonical serialization of the **complete** final body.
381 ///
382 /// `serde_json` is built with `preserve_order` in this crate, so insertion
383 /// order — not key order — drives `to_string`. Canonicalizing here means
384 /// the hash is stable across builder orderings while still changing when
385 /// any value anywhere in the body changes: max-token fields, tool choice,
386 /// nested reasoning controls, transformed tool schemas, attachment parts,
387 /// stream options, and every message.
388 pub fn canonical_body(&self) -> String {
389 canonical_json(&self.body)
390 }
391
392 /// SHA-256 over [`Self::canonical_body`]. Whole-body, not a prefix.
393 pub fn body_sha256(&self) -> String {
394 codewhale_runtime::hashing::sha256_hex(self.canonical_body().as_bytes())
395 }
396
397 /// Dialect-aware view of the finished body, for counting and estimation.
398 pub fn wire_view(&self) -> WireBodyView<'_> {
399 WireBodyView::extract(self.dialect, &self.body)
400 }
401
402 pub fn tool_wire_measurement(&self) -> crate::llm_client::ToolWireMeasurement {
403 let view = self.wire_view();
404 crate::llm_client::ToolWireMeasurement {
405 tool_schema_bytes: view.tool_schema_bytes,
406 tool_schema_sha256: view.tool_schema_sha256,
407 tool_count: view.tool_count,
408 omitted_tool_names: self.omitted_tool_names.clone(),
409 omitted_tool_count: self.omitted_tool_names.len(),
410 }
411 }
412
413 /// Attach the caller's named route identity (a `[providers.<name>]` key,
414 /// or any other route id the resolved turn plan owns).
415 #[must_use]
416 pub fn with_route_id(mut self, route_id: Option<String>) -> Self {
417 self.endpoint.route_id = route_id;
418 self
419 }
420
421 /// SHA-256 of the full endpoint URL. Lets two previews be compared for
422 /// "same endpoint?" without either of them printing the path.
423 pub fn endpoint_fingerprint(&self) -> String {
424 codewhale_runtime::hashing::sha256_hex(self.endpoint.url.as_bytes())
425 }
426
427 /// A bounded endpoint class that never publishes a remote authority.
428 /// Custom-provider tenant subdomains can contain credentials, so every
429 /// non-loopback authority is represented by a short digest.
430 pub fn safe_endpoint_host_class(&self) -> String {
431 let Ok(url) = reqwest::Url::parse(&self.endpoint.url) else {
432 let digest = codewhale_runtime::hashing::sha256_hex(self.endpoint.url.as_bytes());
433 return format!("unparseable sha256:{}", &digest[..12]);
434 };
435 let scheme = match url.scheme() {
436 "http" => "http",
437 "https" => "https",
438 _ => "other",
439 };
440 let host = url.host_str().unwrap_or_default();
441 let loopback = host.eq_ignore_ascii_case("localhost")
442 || host
443 .parse::<std::net::IpAddr>()
444 .is_ok_and(|address| address.is_loopback());
445 if loopback {
446 return format!("{scheme} loopback");
447 }
448 let authority = url.port().map_or_else(
449 || host.to_ascii_lowercase(),
450 |port| format!("{}:{port}", host.to_ascii_lowercase()),
451 );
452 let digest = codewhale_runtime::hashing::sha256_hex(authority.as_bytes());
453 format!("{scheme} remote sha256:{}", &digest[..12])
454 }
455
456 /// Output cap literally serialized into the primary request body.
457 pub fn wire_output_cap_tokens(&self) -> Option<u64> {
458 ["max_tokens", "max_completion_tokens", "max_output_tokens"]
459 .into_iter()
460 .find_map(|key| self.body.get(key).and_then(Value::as_u64))
461 }
462 }
463
464 /// Where a given dialect keeps its system text, turn items, and tool schemas.
465 ///
466 /// Extraction is by shape, never by guessing: a Responses body has
467 /// `instructions`/`input`, an Anthropic body has `system`/`messages`, a Chat
468 /// body carries the system prompt as the first `system`-role message.
469 ///
470 /// # The byte accounting sums exactly
471 ///
472 /// `system_bytes + tool_schema_bytes + item_bytes + framing_bytes ==
473 /// body_bytes`, where `body_bytes` is the length of
474 /// [`PreparedOutboundRequest::canonical_body`] — a stable, key-sorted semantic
475 /// serialization of the body. Production sends the same JSON value, but the
476 /// transport serializer may preserve a different object-key order. These are
477 /// therefore canonical JSON sizes, not literal HTTP payload byte counts. This
478 /// is an accounting decomposition, not a set of four borrowed
479 /// byte ranges in the JSON buffer:
480 ///
481 /// - `system_bytes`, `tool_schema_bytes`, and `item_bytes` are the canonical
482 /// serializations of their *values* (for Chat, `system_bytes` is the
483 /// serialized system-role messages, carved out of the `messages` array);
484 /// - `framing_bytes` is the algebraic remainder after those three canonical
485 /// value-region sizes. It includes every other top-level field and whatever
486 /// JSON structure was not already counted inside a selected array value.
487 ///
488 /// The earlier shape counted selected values and then serialized a *separate*
489 /// object for "framing", which double-omitted key names, brackets, and
490 /// separators and made the parts sum to less than the whole. Framing is now
491 /// defined as the remainder precisely so that cannot happen again;
492 /// [`WireBodyView::partition_is_exact`] asserts only the sum identity; the
493 /// regional names remain attribution estimates over canonical values.
494 ///
495 /// `tool_result_bytes` and `attachment_bytes` are deliberately *not* part of
496 /// the partition: they are subsets of `item_bytes`, reported for attribution.
497 #[derive(Debug, Default)]
498 pub struct WireBodyView<'a> {
499 /// Canonical byte length of the complete wire body.
500 pub body_bytes: usize,
501 /// Serialized bytes of the system/instructions region.
502 pub system_bytes: usize,
503 /// SHA-256 of the canonicalized system/instructions region — the hash of
504 /// the prompt this prepared request would actually send. Empty when the
505 /// request carries no system region.
506 pub system_sha256: String,
507 /// Serialized bytes of the tool-schema region.
508 pub tool_schema_bytes: usize,
509 /// SHA-256 of the canonicalized **wire** tool region: the schemas exactly
510 /// as the provider receives them, after every dialect transform and
511 /// strict-mode sanitizer. Empty when the body carries no `tools` field.
512 pub tool_schema_sha256: String,
513 /// Number of tool schemas on the wire.
514 pub tool_count: usize,
515 /// Turn items (messages / input items), excluding the system region.
516 pub items: Vec<&'a Value>,
517 /// Serialized bytes of the turn-item region, including the array's own
518 /// brackets and separators and excluding any carved-out system messages.
519 pub item_bytes: usize,
520 /// Serialized bytes of tool-result items specifically. Subset of
521 /// [`Self::item_bytes`].
522 pub tool_result_bytes: usize,
523 /// Number of attachment (image) parts referenced anywhere in the items.
524 pub attachment_count: usize,
525 /// Serialized bytes of those attachment parts. Subset of
526 /// [`Self::item_bytes`].
527 pub attachment_bytes: usize,
528 /// Algebraic remainder after the three canonical value-region sizes. This
529 /// includes other top-level fields and JSON structure not already counted
530 /// inside a selected array value.
531 pub framing_bytes: usize,
532 }
533
534 impl<'a> WireBodyView<'a> {
535 fn extract(dialect: WireDialect, body: &'a Value) -> Self {
536 let body_bytes = canonical_json(body).len();
537 let mut view = Self {
538 body_bytes,
539 ..Self::default()
540 };
541 let Some(object) = body.as_object() else {
542 view.framing_bytes = view.body_bytes;
543 return view;
544 };
545
546 let (system_key, items_key) = match dialect {
547 WireDialect::ChatCompletions => (None, "messages"),
548 WireDialect::AnthropicMessages => (Some("system"), "messages"),
549 WireDialect::OpenAiResponses => (Some("instructions"), "input"),
550 WireDialect::GenerateContent => (Some("systemInstruction"), "contents"),
551 };
552
553 // The system region is accumulated as canonical text so it can be
554 // hashed once, then dropped. The text itself never leaves this scope.
555 let mut system_region = String::new();
556 if let Some(key) = system_key
557 && let Some(system) = object.get(key)
558 {
559 system_region.push_str(&canonical_json(system));
560 }
561
562 if let Some(tools) = object.get("tools") {
563 let canonical_tools = canonical_json(tools);
564 view.tool_schema_bytes = canonical_tools.len();
565 view.tool_schema_sha256 =
566 codewhale_runtime::hashing::sha256_hex(canonical_tools.as_bytes());
567 view.tool_count = tools.as_array().map_or(0, |tools| {
568 tools
569 .iter()
570 .map(|tool| {
571 if tool.get("type").and_then(Value::as_str) == Some("namespace") {
572 tool.get("tools")
573 .and_then(Value::as_array)
574 .map_or(0, Vec::len)
575 } else if let Some(declarations) =
576 tool.get("functionDeclarations").and_then(Value::as_array)
577 {
578 declarations.len()
579 } else {
580 1
581 }
582 })
583 .sum()
584 });
585 }
586
587 if let Some(items_value) = object.get(items_key) {
588 // The whole array, brackets and separators included, so the
589 // accounting can include the canonical array value itself.
590 let mut item_region_bytes = canonical_json(items_value).len();
591 if let Some(items) = items_value.as_array() {
592 for item in items {
593 let bytes = canonical_json(item).len();
594 // Chat Completions carries the system prompt inline as the
595 // first system-role message. Account for it as system, not
596 // as conversation, so cross-dialect numbers stay
597 // comparable — and subtract it from the item region so the
598 // two never double-count the same bytes.
599 if dialect == WireDialect::ChatCompletions
600 && item.get("role").and_then(Value::as_str) == Some("system")
601 {
602 system_region.push_str(&canonical_json(item));
603 item_region_bytes = item_region_bytes.saturating_sub(bytes);
604 continue;
605 }
606 if is_tool_result_item(dialect, item) {
607 view.tool_result_bytes = view.tool_result_bytes.saturating_add(bytes);
608 }
609 let (count, attachment_bytes) = count_attachments(dialect, item);
610 view.attachment_count = view.attachment_count.saturating_add(count);
611 view.attachment_bytes = view.attachment_bytes.saturating_add(attachment_bytes);
612 view.items.push(item);
613 }
614 }
615 view.item_bytes = item_region_bytes;
616 }
617
618 view.system_bytes = system_region.len();
619 if !system_region.is_empty() {
620 view.system_sha256 = codewhale_runtime::hashing::sha256_hex(system_region.as_bytes());
621 }
622
623 // Framing is the algebraic remainder, never a separately serialized
624 // object. The sum is exact; these are not four disjoint byte slices.
625 view.framing_bytes = view
626 .body_bytes
627 .saturating_sub(view.system_bytes)
628 .saturating_sub(view.tool_schema_bytes)
629 .saturating_sub(view.item_bytes);
630 view
631 }
632
633 /// Whether the four partition classes sum to the whole wire body.
634 ///
635 /// The manifest publishes these as exact byte facts, so the invariant is
636 /// asserted in tests across every dialect and both entry points rather
637 /// than merely documented.
638 pub fn partition_is_exact(&self) -> bool {
639 self.system_bytes
640 .saturating_add(self.tool_schema_bytes)
641 .saturating_add(self.item_bytes)
642 .saturating_add(self.framing_bytes)
643 == self.body_bytes
644 }
645 }
646
647 fn is_tool_result_item(dialect: WireDialect, item: &Value) -> bool {
648 match dialect {
649 WireDialect::ChatCompletions => item.get("role").and_then(Value::as_str) == Some("tool"),
650 WireDialect::AnthropicMessages => item
651 .get("content")
652 .and_then(Value::as_array)
653 .is_some_and(|blocks| {
654 blocks
655 .iter()
656 .any(|block| block.get("type").and_then(Value::as_str) == Some("tool_result"))
657 }),
658 WireDialect::OpenAiResponses => {
659 item.get("type").and_then(Value::as_str) == Some("function_call_output")
660 }
661 WireDialect::GenerateContent => {
662 item.get("parts")
663 .and_then(Value::as_array)
664 .is_some_and(|parts| {
665 parts
666 .iter()
667 .any(|part| part.get("functionResponse").is_some())
668 })
669 }
670 }
671 }
672
673 /// Count attachment parts and their serialized size. Only sizes leave this
674 /// function — never a URL, path, or payload.
675 fn count_attachments(dialect: WireDialect, item: &Value) -> (usize, usize) {
676 let parts_key = if dialect == WireDialect::GenerateContent {
677 "parts"
678 } else {
679 "content"
680 };
681 let Some(parts) = item.get(parts_key).and_then(Value::as_array) else {
682 return (0, 0);
683 };
684 let mut count = 0usize;
685 let mut bytes = 0usize;
686 for part in parts {
687 let part_type = part.get("type").and_then(Value::as_str);
688 let is_attachment = match dialect {
689 WireDialect::ChatCompletions => {
690 part_type == Some("image_url") || part.get("image_url").is_some()
691 }
692 WireDialect::AnthropicMessages => {
693 matches!(part_type, Some("image" | "document"))
694 }
695 WireDialect::OpenAiResponses => {
696 matches!(part_type, Some("input_image" | "input_file"))
697 }
698 WireDialect::GenerateContent => part.get("inlineData").is_some(),
699 };
700 if !is_attachment {
701 continue;
702 }
703 count += 1;
704 bytes = bytes.saturating_add(canonical_json(part).len());
705 }
706 (count, bytes)
707 }
708
709 /// Classify the provider-specific shape of a prepared Chat Completions body.
710 pub fn chat_route_shape(
711 provider: ProviderKind,
712 base_url: &str,
713 wire_model: &str,
714 url: &str,
715 ) -> RouteShape {
716 if provider == ProviderKind::OpencodeZen {
717 return RouteShape::OpencodeZen;
718 }
719 if url.contains("/beta/chat/completions") {
720 return RouteShape::DeepseekBetaStrictTools;
721 }
722 if codewhale_runtime::config::is_exact_kimi_code_k3_route(provider, base_url, wire_model) {
723 return RouteShape::KimiCodeK3;
724 }
725 if codewhale_runtime::config::is_exact_direct_moonshot_k3_route(provider, base_url, wire_model)
726 {
727 return RouteShape::DirectMoonshotK3;
728 }
729 if provider == ProviderKind::Custom {
730 return RouteShape::CustomCompatible;
731 }
732 RouteShape::Standard
733 }
734
735 #[cfg(test)]
736 mod tests {
737 use super::*;
738 use serde_json::{Map, json};
739
740 fn endpoint() -> EndpointIdentity {
741 EndpointIdentity {
742 provider_id: "deepseek".to_string(),
743 provider_display: "DeepSeek".to_string(),
744 route_id: None,
745 url: "https://api.deepseek.com/chat/completions".to_string(),
746 shape: RouteShape::Standard,
747 }
748 }
749
750 fn prepared(body: Value) -> PreparedOutboundRequest {
751 PreparedOutboundRequest::new(
752 WireDialect::ChatCompletions,
753 endpoint(),
754 "deepseek-chat".to_string(),
755 body,
756 Some("high".to_string()),
757 None,
758 CallerStreamMode::Streaming,
759 )
760 }
761
762 #[test]
763 fn canonical_json_is_key_order_independent() {
764 let a = json!({"b": 1, "a": {"z": 2, "y": [3, {"q": 4, "p": 5}]}});
765 let mut b = Map::new();
766 b.insert("a".to_string(), json!({"y": [3, {"p": 5, "q": 4}], "z": 2}));
767 b.insert("b".to_string(), json!(1));
768 assert_eq!(canonical_json(&a), canonical_json(&Value::Object(b)));
769 assert_eq!(
770 canonical_json(&a),
771 r#"{"a":{"y":[3,{"p":5,"q":4}],"z":2},"b":1}"#
772 );
773 }
774
775 #[test]
776 fn body_hash_covers_every_wire_field() {
777 let base = prepared(json!({
778 "model": "deepseek-chat",
779 "messages": [{"role": "user", "content": "hi"}],
780 "max_tokens": 4096,
781 "tools": [{"type": "function", "function": {"name": "read_file"}}],
782 "tool_choice": {"type": "auto"},
783 "reasoning_effort": "high",
784 "stream": true,
785 }));
786 let baseline = base.body_sha256();
787
788 // Every one of these is a field a preview would have to notice.
789 let mutations: Vec<(&str, Value)> = vec![
790 ("max_tokens", json!(2048)),
791 ("tool_choice", json!("required")),
792 ("reasoning_effort", json!("low")),
793 ("stream", json!(false)),
794 ("temperature", json!(0.2)),
795 ];
796 for (key, value) in mutations {
797 let mut body = base.body.clone();
798 body[key] = value;
799 assert_ne!(
800 baseline,
801 prepared(body).body_sha256(),
802 "mutating `{key}` must change the whole-body hash"
803 );
804 }
805
806 // Nested changes: a transformed tool schema and a nested reasoning
807 // control both have to move the hash.
808 let mut nested = base.body.clone();
809 nested["tools"][0]["function"]["parameters"] = json!({"type": "object"});
810 assert_ne!(baseline, prepared(nested).body_sha256());
811
812 let mut thinking = base.body.clone();
813 thinking["thinking"] = json!({"type": "enabled", "effort": "max"});
814 assert_ne!(baseline, prepared(thinking).body_sha256());
815 }
816
817 #[test]
818 fn endpoint_host_class_never_prints_remote_authority_or_path() {
819 let hostile = |url: &str| {
820 let mut endpoint = endpoint();
821 endpoint.url = url.to_string();
822 PreparedOutboundRequest::new(
823 WireDialect::ChatCompletions,
824 endpoint,
825 "model".to_string(),
826 json!({"model": "model", "messages": []}),
827 None,
828 None,
829 CallerStreamMode::Streaming,
830 )
831 };
832
833 let token_host =
834 hostile("https://sk-live-abcdef0123456789.tenant.example/v1/deployments/secret/chat");
835 let same_host_other_path =
836 hostile("https://sk-live-abcdef0123456789.tenant.example/other/private/path");
837 let idn = hostile("https://秘密.example/private/path?api_key=secret");
838
839 let class = token_host.safe_endpoint_host_class();
840 assert_eq!(class, same_host_other_path.safe_endpoint_host_class());
841 assert_ne!(
842 token_host.endpoint_fingerprint(),
843 same_host_other_path.endpoint_fingerprint(),
844 "the separate full-endpoint fingerprint must still detect path drift"
845 );
846 for forbidden in ["sk-live", "tenant", "example", "deployment", "secret"] {
847 assert!(!class.contains(forbidden), "{forbidden} leaked in {class}");
848 }
849 let idn_class = idn.safe_endpoint_host_class();
850 for forbidden in ["秘密", "xn--", "example", "private", "api_key", "secret"] {
851 assert!(
852 !idn_class.contains(forbidden),
853 "{forbidden} leaked in {idn_class}"
854 );
855 }
856 assert!(class.starts_with("https remote sha256:"), "{class}");
857 assert!(class.len() <= 40, "{class}");
858
859 let loopback = hostile("http://127.0.0.1:8080/private/token-shaped-path");
860 assert_eq!(loopback.safe_endpoint_host_class(), "http loopback");
861 }
862
863 #[test]
864 fn wire_output_cap_is_read_only_from_the_finished_body() {
865 assert_eq!(
866 prepared(json!({"max_tokens": 1024})).wire_output_cap_tokens(),
867 Some(1024)
868 );
869 assert_eq!(
870 prepared(json!({"max_completion_tokens": 2048})).wire_output_cap_tokens(),
871 Some(2048)
872 );
873 assert_eq!(
874 prepared(json!({"model": "m"})).wire_output_cap_tokens(),
875 None
876 );
877 }
878
879 #[test]
880 fn reasoning_receipt_reads_the_finished_body_not_the_intent() {
881 // Kimi Code K3 strips `reasoning_effort` and writes nested thinking.
882 let kimi = prepared(json!({
883 "model": "kimi-k3",
884 "messages": [],
885 "thinking": {"type": "enabled", "effort": "max"},
886 }));
887 assert_eq!(kimi.reasoning.requested_effort.as_deref(), Some("high"));
888 assert_eq!(kimi.reasoning.wire_effort_string(), None);
889 assert_eq!(
890 kimi.reasoning.wire_controls,
891 vec![(
892 "thinking".to_string(),
893 json!({"type": "enabled", "effort": "max"})
894 )]
895 );
896 }
897
898 #[test]
899 fn receipt_never_captures_message_or_prompt_fields() {
900 let leaky = prepared(json!({
901 "model": "m",
902 "messages": [{"role": "user", "content": "SECRET PROMPT"}],
903 "instructions": "SECRET INSTRUCTIONS",
904 "reasoning_effort": "high",
905 }));
906 let rendered = format!("{:?}", leaky.reasoning);
907 assert!(!rendered.contains("SECRET PROMPT"), "{rendered}");
908 assert!(!rendered.contains("SECRET INSTRUCTIONS"), "{rendered}");
909 }
910
911 #[test]
912 fn chat_view_folds_the_system_message_into_the_system_region() {
913 let request = prepared(json!({
914 "model": "m",
915 "messages": [
916 {"role": "system", "content": "SYS"},
917 {"role": "user", "content": "hi"},
918 {"role": "tool", "tool_call_id": "c1", "content": "OUT"},
919 ],
920 "tools": [{"type": "function", "function": {"name": "a"}}],
921 "max_tokens": 100,
922 }));
923 let view = request.wire_view();
924 assert!(view.system_bytes > 0);
925 assert_eq!(view.items.len(), 2, "system message is not a turn item");
926 assert!(view.tool_result_bytes > 0);
927 assert_eq!(view.tool_count, 1);
928 assert!(view.framing_bytes > 0);
929 }
930
931 #[test]
932 fn anthropic_and_responses_views_use_their_own_shapes() {
933 let anthropic_request = PreparedOutboundRequest::new(
934 WireDialect::AnthropicMessages,
935 endpoint(),
936 "claude".to_string(),
937 json!({
938 "model": "claude",
939 "system": "SYS",
940 "messages": [
941 {"role": "user", "content": [{"type": "tool_result", "content": "OUT"}]},
942 {"role": "user", "content": [{"type": "image", "source": {"data": "AAA"}}]},
943 ],
944 "tools": [{"name": "a"}, {"name": "b"}],
945 }),
946 None,
947 None,
948 CallerStreamMode::Streaming,
949 );
950 let anthropic = anthropic_request.wire_view();
951 assert!(anthropic.system_bytes > 0);
952 assert_eq!(anthropic.items.len(), 2);
953 assert!(anthropic.tool_result_bytes > 0);
954 assert_eq!(anthropic.attachment_count, 1);
955 assert_eq!(anthropic.tool_count, 2);
956
957 let responses_request = PreparedOutboundRequest::new(
958 WireDialect::OpenAiResponses,
959 endpoint(),
960 "gpt".to_string(),
961 json!({
962 "model": "gpt",
963 "instructions": "SYS",
964 "input": [
965 {"type": "message", "role": "user", "content": [{"type": "input_text"}]},
966 {"type": "function_call_output", "output": "OUT"},
967 ],
968 "tools": [{"name": "a"}],
969 }),
970 None,
971 None,
972 CallerStreamMode::Streaming,
973 );
974 let responses = responses_request.wire_view();
975 assert!(responses.system_bytes > 0);
976 assert_eq!(responses.items.len(), 2);
977 assert!(responses.tool_result_bytes > 0);
978 assert_eq!(responses.tool_count, 1);
979 }
980
981 /// The reviewed defect: nested reasoning shapes were invisible, so every
982 /// route that actually thinks hardest read as "no effort sent".
983 #[test]
984 fn nested_reasoning_efforts_are_read_from_every_dialect() {
985 let kimi = prepared(json!({
986 "model": "kimi-k3",
987 "messages": [],
988 "thinking": {"type": "enabled", "effort": "max"},
989 }));
990 assert_eq!(
991 kimi.reasoning.wire_effort(),
992 Some(("thinking.effort", "max"))
993 );
994 assert!(kimi.reasoning.controls_reasoning());
995
996 let responses = PreparedOutboundRequest::new(
997 WireDialect::OpenAiResponses,
998 endpoint(),
999 "gpt".to_string(),
1000 json!({
1001 "model": "gpt",
1002 "input": [],
1003 "reasoning": {"effort": "high", "summary": "auto"},
1004 "include": ["reasoning.encrypted_content"],
1005 }),
1006 None,
1007 None,
1008 CallerStreamMode::Streaming,
1009 );
1010 assert_eq!(
1011 responses.reasoning.wire_effort(),
1012 Some(("reasoning.effort", "high"))
1013 );
1014 assert!(responses.reasoning.controls_reasoning());
1015
1016 let anthropic = PreparedOutboundRequest::new(
1017 WireDialect::AnthropicMessages,
1018 endpoint(),
1019 "claude".to_string(),
1020 json!({
1021 "model": "claude",
1022 "messages": [],
1023 "output_config": {"effort": "low"},
1024 }),
1025 None,
1026 None,
1027 CallerStreamMode::Streaming,
1028 );
1029 assert_eq!(
1030 anthropic.reasoning.wire_effort(),
1031 Some(("output_config.effort", "low"))
1032 );
1033
1034 // Flat still wins when the dialect uses it.
1035 let chat = prepared(json!({
1036 "model": "m",
1037 "messages": [],
1038 "reasoning_effort": "medium",
1039 }));
1040 assert_eq!(
1041 chat.reasoning.wire_effort(),
1042 Some(("reasoning_effort", "medium"))
1043 );
1044 }
1045
1046 /// `include` discloses reasoning output; it does not request a tier. A
1047 /// body carrying only `include` must not read as a reasoning control.
1048 #[test]
1049 fn responses_include_alone_is_not_a_reasoning_control() {
1050 let disclosure_only = PreparedOutboundRequest::new(
1051 WireDialect::OpenAiResponses,
1052 endpoint(),
1053 "gpt".to_string(),
1054 json!({
1055 "model": "gpt",
1056 "input": [],
1057 "include": ["reasoning.encrypted_content"],
1058 }),
1059 None,
1060 None,
1061 CallerStreamMode::Streaming,
1062 );
1063 assert!(
1064 !disclosure_only.reasoning.wire_controls.is_empty(),
1065 "`include` is still disclosed on the receipt"
1066 );
1067 assert!(
1068 !disclosure_only.reasoning.controls_reasoning(),
1069 "`include` alone must not read as a reasoning request"
1070 );
1071 assert_eq!(disclosure_only.reasoning.wire_effort(), None);
1072 }
1073
1074 fn assert_partition_exact(request: &PreparedOutboundRequest, what: &str) {
1075 let view = request.wire_view();
1076 assert_eq!(
1077 request.serialized_body_bytes().unwrap(),
1078 serde_json::to_vec(&request.body).unwrap().len()
1079 );
1080 assert_eq!(
1081 view.body_bytes,
1082 request.canonical_body().len(),
1083 "{what}: the view must measure the bytes that would be POSTed"
1084 );
1085 assert!(
1086 view.partition_is_exact(),
1087 "{what}: {} + {} + {} + {} != {}",
1088 view.system_bytes,
1089 view.tool_schema_bytes,
1090 view.item_bytes,
1091 view.framing_bytes,
1092 view.body_bytes
1093 );
1094 assert!(view.tool_result_bytes <= view.item_bytes, "{what}");
1095 assert!(view.attachment_bytes <= view.item_bytes, "{what}");
1096 }
1097
1098 /// The byte classes are published as exact facts, so they must account for
1099 /// every byte of the wire body — key names, brackets, and separators
1100 /// included — in every dialect and on both entry points.
1101 #[test]
1102 fn byte_classes_sum_to_the_whole_wire_body_in_every_dialect() {
1103 assert_partition_exact(
1104 &prepared(json!({
1105 "model": "m",
1106 "messages": [
1107 {"role": "system", "content": "SYS"},
1108 {"role": "user", "content": "hi"},
1109 {"role": "tool", "tool_call_id": "c1", "content": "OUT"},
1110 ],
1111 "tools": [{"type": "function", "function": {"name": "a"}}],
1112 "tool_choice": {"type": "auto"},
1113 "max_tokens": 100,
1114 "stream": true,
1115 })),
1116 "chat streaming",
1117 );
1118 assert_partition_exact(
1119 &prepared(json!({
1120 "model": "m",
1121 "messages": [{"role": "user", "content": "hi"}],
1122 "max_tokens": 100,
1123 })),
1124 "chat blocking (no tools, no system, no stream field)",
1125 );
1126 assert_partition_exact(
1127 &prepared(json!({"model": "m", "messages": []})),
1128 "chat minimal",
1129 );
1130 assert_partition_exact(
1131 &PreparedOutboundRequest::new(
1132 WireDialect::AnthropicMessages,
1133 endpoint(),
1134 "claude".to_string(),
1135 json!({
1136 "model": "claude",
1137 "system": [{"type": "text", "text": "SYS"}],
1138 "messages": [
1139 {"role": "user", "content": [{"type": "tool_result", "content": "OUT"}]},
1140 {"role": "user", "content": [{"type": "image", "source": {"data": "AAA"}}]},
1141 ],
1142 "tools": [{"name": "a"}],
1143 "stream": true,
1144 }),
1145 None,
1146 None,
1147 CallerStreamMode::Streaming,
1148 ),
1149 "anthropic streaming",
1150 );
1151 assert_partition_exact(
1152 &PreparedOutboundRequest::new(
1153 WireDialect::OpenAiResponses,
1154 endpoint(),
1155 "gpt".to_string(),
1156 json!({
1157 "model": "gpt",
1158 "instructions": "SYS",
1159 "input": [
1160 {"type": "message", "role": "user", "content": [{"type": "input_text"}]},
1161 {"type": "function_call_output", "output": "OUT"},
1162 ],
1163 "tools": [{"name": "a"}],
1164 "reasoning": {"effort": "high"},
1165 "stream": true,
1166 }),
1167 None,
1168 None,
1169 CallerStreamMode::Blocking,
1170 ),
1171 "responses blocking entry point (wire still streams)",
1172 );
1173 }
1174
1175 /// Mutating any region must keep the partition exact *and* move the class
1176 /// the mutation belongs to. A partition that stayed exact by dumping the
1177 /// difference into framing would be arithmetically true and useless.
1178 #[test]
1179 fn byte_classes_track_the_region_that_changed() {
1180 let base = json!({
1181 "model": "m",
1182 "messages": [
1183 {"role": "system", "content": "SYS"},
1184 {"role": "user", "content": "hi"},
1185 ],
1186 "tools": [{"type": "function", "function": {"name": "a"}}],
1187 "max_tokens": 100,
1188 });
1189 let baseline = prepared(base.clone());
1190 let baseline_view = baseline.wire_view();
1191
1192 let mut bigger_system = base.clone();
1193 bigger_system["messages"][0]["content"] = json!("SYSTEM PROMPT, MUCH LONGER");
1194 let request = prepared(bigger_system);
1195 let view = request.wire_view();
1196 assert_partition_exact(&request, "grown system");
1197 assert!(view.system_bytes > baseline_view.system_bytes);
1198 assert_eq!(view.item_bytes, baseline_view.item_bytes);
1199
1200 let mut bigger_tools = base.clone();
1201 bigger_tools["tools"][0]["function"]["parameters"] = json!({"type": "object"});
1202 let request = prepared(bigger_tools);
1203 let view = request.wire_view();
1204 assert_partition_exact(&request, "grown tool schema");
1205 assert!(view.tool_schema_bytes > baseline_view.tool_schema_bytes);
1206 assert_ne!(view.tool_schema_sha256, baseline_view.tool_schema_sha256);
1207
1208 let mut extra_message = base.clone();
1209 extra_message["messages"]
1210 .as_array_mut()
1211 .expect("messages array")
1212 .push(json!({"role": "user", "content": "the hypothetical next prompt"}));
1213 let request = prepared(extra_message);
1214 let view = request.wire_view();
1215 assert_partition_exact(&request, "appended message");
1216 assert!(view.item_bytes > baseline_view.item_bytes);
1217 assert_eq!(view.system_bytes, baseline_view.system_bytes);
1218
1219 let mut extra_framing = base;
1220 extra_framing["stream_options"] = json!({"include_usage": true});
1221 let request = prepared(extra_framing);
1222 let view = request.wire_view();
1223 assert_partition_exact(&request, "added framing field");
1224 assert!(view.framing_bytes > baseline_view.framing_bytes);
1225 assert_eq!(view.item_bytes, baseline_view.item_bytes);
1226 }
1227
1228 /// The prefix digest is derived from this hash, so a provider-side schema
1229 /// transform that leaves the logical catalog untouched must still move it.
1230 #[test]
1231 fn wire_tool_hash_tracks_dialect_schema_shaping() {
1232 let logical = prepared(json!({
1233 "model": "m",
1234 "messages": [],
1235 "tools": [{"type": "function", "function": {"name": "a", "parameters": {"type": "object"}}}],
1236 }));
1237 let shaped = prepared(json!({
1238 "model": "m",
1239 "messages": [],
1240 "tools": [{"type": "function", "function": {
1241 "name": "a",
1242 "parameters": {"type": "object", "additionalProperties": false},
1243 "strict": true,
1244 }}],
1245 }));
1246 assert_ne!(
1247 logical.wire_view().tool_schema_sha256,
1248 shaped.wire_view().tool_schema_sha256,
1249 "strict-mode schema sanitizing must move the wire tool hash"
1250 );
1251
1252 let toolless = prepared(json!({"model": "m", "messages": []}));
1253 assert!(toolless.wire_view().tool_schema_sha256.is_empty());
1254 }
1255
1256 #[test]
1257 fn dialect_labels_are_stable() {
1258 assert_eq!(
1259 WireDialect::from_wire_format(WireFormat::ChatCompletions).as_str(),
1260 "chat-completions"
1261 );
1262 assert_eq!(
1263 WireDialect::from_wire_format(WireFormat::AnthropicMessages).as_str(),
1264 "anthropic-messages"
1265 );
1266 assert_eq!(
1267 WireDialect::from_wire_format(WireFormat::Responses).as_str(),
1268 "openai-responses"
1269 );
1270 }
1271 }
1272
1273 /// Per-dialect proof that `/preview-request` and production dispatch consume
1274 /// the same bytes.
1275 ///
1276 /// Each case builds a real client for a production route, prepares a request
1277 /// through [`CodewhaleClient::prepare_outbound_request`] — the value the
1278 /// transports send and the preview describes — and compares its whole-body
1279 /// hash against the dialect's own builder run over the identically
1280 /// pre-processed request. A divergence here means a second body builder has
1281 /// reappeared.
1282 #[cfg(test)]
1283 mod dialect_seam_tests {
1284 use super::*;
1285 use codewhale_models::Role;
1286 use codewhale_models::{ContentBlock, Message, MessageRequest, SystemPrompt, Tool};
1287 use codewhale_runtime::config::{Config, ProviderConfig, ProvidersConfig};
1288 use serde_json::json;
1289
1290 use super::super::CodewhaleClient;
1291
1292 fn tool(name: &str) -> Tool {
1293 Tool {
1294 tool_type: None,
1295 name: name.to_string(),
1296 description: format!("{name} description"),
1297 input_schema: json!({"type": "object", "properties": {}}),
1298 allowed_callers: None,
1299 defer_loading: None,
1300 input_examples: None,
1301 strict: None,
1302 cache_control: None,
1303 }
1304 }
1305
1306 fn request(model: &str) -> MessageRequest {
1307 MessageRequest {
1308 model: model.to_string(),
1309 messages: vec![Message {
1310 role: Role::User,
1311 content: vec![ContentBlock::Text {
1312 text: "hello".to_string(),
1313 cache_control: None,
1314 }],
1315 }],
1316 max_tokens: 4096,
1317 system: Some(SystemPrompt::Text("BASE PROMPT".to_string())),
1318 tools: Some(vec![tool("read_file"), tool("Bash")]),
1319 tool_choice: Some(json!({"type": "auto"})),
1320 metadata: None,
1321 thinking: None,
1322 reasoning_effort: Some("high".to_string()),
1323 stream: Some(true),
1324 temperature: None,
1325 top_p: None,
1326 safety_check: None,
1327 title: None,
1328 }
1329 }
1330
1331 fn client(provider: &str, configure: impl FnOnce(&mut ProvidersConfig)) -> CodewhaleClient {
1332 let mut providers = ProvidersConfig::default();
1333 configure(&mut providers);
1334 CodewhaleClient::new(&{
1335 let __cw_config_init_0_0 = Some(provider.to_string());
1336 let __cw_config_init_0_1 = Some(providers);
1337 let mut __cw_config_init_0_value: Config = Config::default();
1338 __cw_config_init_0_value.provider = __cw_config_init_0_0;
1339 __cw_config_init_0_value.providers = __cw_config_init_0_1;
1340 __cw_config_init_0_value
1341 })
1342 .expect("client resolves for this route")
1343 }
1344
1345 fn configured(api_key: &str, base_url: Option<&str>, model: &str) -> ProviderConfig {
1346 ProviderConfig {
1347 api_key: Some(api_key.to_string()),
1348 base_url: base_url.map(str::to_string),
1349 model: Some(model.to_string()),
1350 ..ProviderConfig::default()
1351 }
1352 }
1353
1354 fn sha256(value: &str) -> String {
1355 codewhale_runtime::hashing::sha256_hex(value.as_bytes())
1356 }
1357
1358 /// The exact pre-processing `prepare_outbound_request` applies before the
1359 /// dialect builder runs. Reproduced here so the reference body is built
1360 /// from the same input, not from a differently-sanitized one.
1361 fn preprocessed(client: &CodewhaleClient, request: MessageRequest) -> MessageRequest {
1362 client
1363 .bind_request_to_protocol(client.prepare_model_bound_request(request))
1364 .expect("protocol binding succeeds")
1365 .0
1366 }
1367
1368 #[test]
1369 fn output_cap_reaches_all_three_wire_dialects_with_reasoning_inside_allowance() {
1370 let _env = crate::test_support::lock_test_env();
1371 for wire in ["chat-completions", "anthropic-messages", "responses"] {
1372 let config = {
1373 let __cw_config_init_1_0 = Some("output-cap-fixture".into());
1374 let __cw_config_init_1_1 = Some(ProvidersConfig {
1375 custom: std::collections::HashMap::from([(
1376 "output-cap-fixture".into(),
1377 ProviderConfig {
1378 kind: Some("openai-compatible".into()),
1379 base_url: Some("http://127.0.0.1:18181/v1".into()),
1380 api_key: Some("fixture-output-cap".into()),
1381 model: Some("fixture-model".into()),
1382 wire: Some(wire.into()),
1383 ..Default::default()
1384 },
1385 )]),
1386 ..Default::default()
1387 });
1388 let mut __cw_config_init_1_value: Config = Config::default();
1389 __cw_config_init_1_value.provider = __cw_config_init_1_0;
1390 __cw_config_init_1_value.providers = __cw_config_init_1_1;
1391 __cw_config_init_1_value
1392 };
1393 let client = CodewhaleClient::new(&config).unwrap();
1394 let mut request = request("fixture-model");
1395 request.max_tokens = 1500;
1396 let prepared = client.prepare_outbound_request(request, true).unwrap();
1397 assert_eq!(prepared.wire_output_cap_tokens(), Some(1500), "{wire}");
1398 if let Some(thinking) = prepared
1399 .body
1400 .pointer("/thinking/budget_tokens")
1401 .and_then(Value::as_u64)
1402 {
1403 assert!(
1404 thinking < 1500,
1405 "reasoning must fit inside the shared allowance"
1406 );
1407 }
1408 }
1409 }
1410
1411 #[test]
1412 fn chat_completions_preview_matches_the_production_chat_builder() {
1413 let client = client("deepseek", |providers| {
1414 providers.deepseek = configured("sk-test-deepseek", None, "deepseek-v4-pro");
1415 });
1416 let prepared = client
1417 .prepare_outbound_request(request("deepseek-v4-pro"), true)
1418 .expect("chat request prepares");
1419 assert_eq!(prepared.dialect, WireDialect::ChatCompletions);
1420
1421 let reference = super::super::chat::build_chat_wire_body(
1422 &preprocessed(&client, request("deepseek-v4-pro")),
1423 client.api_provider(),
1424 client.base_url(),
1425 true,
1426 None,
1427 )
1428 .expect("reference body builds");
1429
1430 assert_eq!(
1431 prepared.body_sha256(),
1432 sha256(&canonical_json(&reference.body))
1433 );
1434 assert_eq!(prepared.wire_model, reference.model);
1435 assert!(
1436 prepared.body.get("tool_choice").is_none(),
1437 "DeepSeek thinking requests omit tool_choice on the final wire body"
1438 );
1439 }
1440
1441 #[test]
1442 fn kimi_code_keeps_its_own_shape_and_is_not_projected_through_plain_chat() {
1443 let client = client("moonshot", |providers| {
1444 providers.moonshot = configured(
1445 "sk-test-kimi",
1446 Some(codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL),
1447 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
1448 );
1449 });
1450 let prepared = client
1451 .prepare_outbound_request(
1452 request(codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL),
1453 true,
1454 )
1455 .expect("kimi code request prepares");
1456
1457 assert_eq!(prepared.dialect, WireDialect::ChatCompletions);
1458 assert_eq!(prepared.endpoint.shape, RouteShape::KimiCodeK3);
1459 // The route-specific shaper replaces flat `reasoning_effort` with the
1460 // nested `thinking.effort` dialect; the receipt must show that.
1461 assert_eq!(prepared.reasoning.wire_effort_string(), None);
1462 assert!(
1463 prepared
1464 .reasoning
1465 .wire_controls
1466 .iter()
1467 .any(|(key, _)| key == "thinking"),
1468 "{:?}",
1469 prepared.reasoning
1470 );
1471
1472 let reference = super::super::chat::build_chat_wire_body(
1473 &preprocessed(
1474 &client,
1475 request(codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL),
1476 ),
1477 client.api_provider(),
1478 client.base_url(),
1479 true,
1480 None,
1481 )
1482 .expect("reference body builds");
1483 assert_eq!(
1484 prepared.body_sha256(),
1485 sha256(&canonical_json(&reference.body))
1486 );
1487 }
1488
1489 /// Every production Anthropic Messages route: native Anthropic, the
1490 /// DeepSeek Messages route, and the MiniMax Messages route. Each shapes
1491 fn message(role: Role, text: &str) -> Message {
1492 Message {
1493 role,
1494 content: vec![ContentBlock::Text {
1495 text: text.to_string(),
1496 cache_control: None,
1497 }],
1498 }
1499 }
1500
1501 /// Anthropic Messages has no in-transcript `system` role, but a compaction
1502 /// summary cannot be dropped or hoisted without changing transcript
1503 /// meaning. The seam keeps it in place and the adapter projects it onto a
1504 /// user message, one of the two roles the wire accepts.
1505 #[test]
1506 fn seam_preserves_an_in_transcript_system_message_on_anthropic() {
1507 let client = client("anthropic", |providers| {
1508 providers.anthropic = configured("sk-ant-test", None, "claude-sonnet-4-5");
1509 });
1510 let mut request = request("claude-sonnet-4-5");
1511 request
1512 .messages
1513 .push(message(Role::System, "compaction summary"));
1514
1515 let prepared = client
1516 .prepare_outbound_request(request, true)
1517 .expect("Anthropic projects positioned system history onto user");
1518 let carried = prepared.body["messages"]
1519 .as_array()
1520 .expect("messages")
1521 .iter()
1522 .find(|message| {
1523 message["content"].as_array().is_some_and(|blocks| {
1524 blocks
1525 .iter()
1526 .any(|block| block["text"] == "compaction summary")
1527 })
1528 })
1529 .expect("compaction summary survives");
1530 assert_eq!(carried["role"], "user");
1531 }
1532
1533 /// The dialects that have always dropped an unrepresentable role keep
1534 /// dropping it. Turning that into a hard failure would break live
1535 /// sessions; the point of the seam is to make the choice explicit, not to
1536 /// make every dialect strict.
1537 #[test]
1538 fn seam_lets_the_openai_shaped_dialects_keep_dropping_unknown_roles() {
1539 let client = client("deepseek", |providers| {
1540 providers.deepseek = configured("sk-test-deepseek", None, "deepseek-v4-pro");
1541 });
1542 let mut request = request("deepseek-v4-pro");
1543 request.messages.push(message(
1544 Role::Unrecognized("future_role".to_string()),
1545 "from a newer build",
1546 ));
1547
1548 let prepared = client
1549 .prepare_outbound_request(request, true)
1550 .expect("an unknown role must not fail a Chat Completions turn");
1551 let body = serde_json::to_string(&prepared.body).expect("serialize body");
1552 assert!(
1553 !body.contains("from a newer build"),
1554 "an unknown role must not reach the wire: {body}"
1555 );
1556 assert!(!body.contains("\"future_role\""), "{body}");
1557 }
1558
1559 /// thinking differently, so each is checked against its own builder run.
1560 #[test]
1561 fn anthropic_messages_preview_matches_the_production_messages_builder() {
1562 type ProviderCase = (
1563 &'static str,
1564 &'static str,
1565 Box<dyn Fn(&mut ProvidersConfig)>,
1566 );
1567
1568 let cases: Vec<ProviderCase> = vec![
1569 (
1570 "anthropic",
1571 "claude-sonnet-4-5",
1572 Box::new(|providers: &mut ProvidersConfig| {
1573 providers.anthropic = configured("sk-ant-test", None, "claude-sonnet-4-5");
1574 }),
1575 ),
1576 (
1577 "deepseek-anthropic",
1578 "deepseek-v4",
1579 Box::new(|providers: &mut ProvidersConfig| {
1580 providers.deepseek_anthropic =
1581 configured("sk-test-deepseek-anthropic", None, "deepseek-v4");
1582 }),
1583 ),
1584 (
1585 "minimax-anthropic",
1586 "MiniMax-M3",
1587 Box::new(|providers: &mut ProvidersConfig| {
1588 providers.minimax_anthropic =
1589 configured("sk-test-minimax-anthropic", None, "MiniMax-M3");
1590 }),
1591 ),
1592 ];
1593
1594 for (provider, model, configure) in cases {
1595 let client = client(provider, |providers| configure(providers));
1596 let prepared = client
1597 .prepare_outbound_request(request(model), true)
1598 .unwrap_or_else(|error| panic!("{provider} request prepares: {error}"));
1599
1600 assert_eq!(
1601 prepared.dialect,
1602 WireDialect::AnthropicMessages,
1603 "{provider} must keep the Messages dialect, not be projected through Chat"
1604 );
1605
1606 let reference =
1607 client.build_anthropic_body(&preprocessed(&client, request(model)), true);
1608 assert_eq!(
1609 prepared.body_sha256(),
1610 sha256(&canonical_json(&reference)),
1611 "{provider} preview body must hash identically to the production builder"
1612 );
1613 assert_eq!(
1614 prepared
1615 .body
1616 .get("tool_choice")
1617 .and_then(|value| value.get("type"))
1618 .and_then(serde_json::Value::as_str),
1619 Some("auto"),
1620 "{provider} tool_choice must come from the final Messages body"
1621 );
1622
1623 // The Messages dialect never carries a flat `reasoning_effort`;
1624 // the receipt must reflect the dialect's own controls.
1625 assert_eq!(prepared.reasoning.wire_effort_string(), None, "{provider}");
1626 assert_eq!(
1627 prepared.reasoning.requested_effort.as_deref(),
1628 Some("high"),
1629 "{provider}"
1630 );
1631 }
1632 }
1633
1634 /// The official plan route requires Codewhale's own protected grant.
1635 fn codex_client() -> CodewhaleClient {
1636 let _env_lock = crate::test_support::lock_test_env();
1637 let home = tempfile::tempdir().expect("isolated ChatGPT credential home");
1638 let root = home
1639 .path()
1640 .canonicalize()
1641 .expect("canonical credential home");
1642 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
1643 let mut config = {
1644 let __cw_config_init_2_0 = Some("openai-codex".to_string());
1645 let mut __cw_config_init_2_value: Config = Config::default();
1646 __cw_config_init_2_value.provider = __cw_config_init_2_0;
1647 __cw_config_init_2_value
1648 };
1649 config
1650 .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::OpenaiCodex))
1651 .unwrap()
1652 .model = Some("gpt-5-codex".into());
1653 codewhale_runtime::oauth::install_test_chatgpt_registration(&mut config)
1654 .expect("official test grant");
1655 CodewhaleClient::new(&config).expect("official ChatGPT client")
1656 }
1657
1658 #[test]
1659 fn responses_preview_matches_the_production_responses_builder() {
1660 let client = codex_client();
1661 let prepared = client
1662 .prepare_outbound_request(request("gpt-5-codex"), true)
1663 .expect("responses request prepares");
1664
1665 assert_eq!(prepared.dialect, WireDialect::OpenAiResponses);
1666 assert_eq!(prepared.endpoint.shape, RouteShape::CodexResponses);
1667 assert_eq!(prepared.endpoint.url, "https://api.openai.com/v1/responses");
1668 assert_eq!(prepared.body["tools"][0]["type"], "namespace");
1669 assert_eq!(prepared.body["tools"][0]["name"], "codewhale");
1670 assert_eq!(
1671 prepared.body["tools"][0]["tools"].as_array().unwrap().len(),
1672 2
1673 );
1674 assert_eq!(
1675 prepared.wire_view().tool_count,
1676 2,
1677 "namespace wrappers are not executable tools"
1678 );
1679
1680 let reference = super::super::responses::build_responses_body_for_provider(
1681 &preprocessed(&client, request("gpt-5-codex")),
1682 ProviderKind::OpenaiCodex,
1683 client.chatgpt_reasoning_api.as_deref(),
1684 );
1685 assert_eq!(prepared.body_sha256(), sha256(&canonical_json(&reference)));
1686 assert_eq!(prepared.body.get("tool_choice"), Some(&json!("auto")));
1687 }
1688
1689 #[test]
1690 fn responses_prepared_request_preserves_full_history_for_its_grant() {
1691 let client = codex_client();
1692 let scope = client.chatgpt_reasoning_api.as_ref().unwrap();
1693 let mut request = request("gpt-5-codex");
1694 for id in ["first", "second"] {
1695 request.messages.push(codewhale_models::Message {
1696 role: codewhale_models::Role::Assistant,
1697 content: vec![codewhale_models::ContentBlock::Thinking {
1698 thinking: "readable-reasoning-must-stay-local".into(),
1699 signature: None,
1700 state: Some(codewhale_models::OpaqueReasoningState {
1701 provider: "openai-codex".into(),
1702 api: scope.clone(),
1703 model: "gpt-5-codex".into(),
1704 id: Some(id.into()),
1705 encrypted_content: format!("opaque-{id}"),
1706 }),
1707 redacted_data: None,
1708 }],
1709 });
1710 }
1711 let prepared = client
1712 .prepare_outbound_request(request.clone(), true)
1713 .unwrap();
1714 let reasoning: Vec<_> = prepared.body["input"]
1715 .as_array()
1716 .unwrap()
1717 .iter()
1718 .filter(|item| item["type"] == "reasoning")
1719 .collect();
1720 assert_eq!(reasoning.len(), 2);
1721 assert_eq!(reasoning[0]["encrypted_content"], "opaque-first");
1722 assert_eq!(reasoning[1]["encrypted_content"], "opaque-second");
1723 assert!(
1724 !prepared
1725 .body
1726 .to_string()
1727 .contains("readable-reasoning-must-stay-local")
1728 );
1729 let mut different_grant = client.clone();
1730 different_grant.chatgpt_reasoning_api = Some("openai-responses-siwc-v1:other".into());
1731 let rejected = different_grant
1732 .prepare_outbound_request(request, true)
1733 .unwrap();
1734 assert!(!rejected.body.to_string().contains("opaque-first"));
1735 assert!(!rejected.body.to_string().contains("opaque-second"));
1736 }
1737
1738 #[test]
1739 fn every_dialect_reports_a_distinct_body_hash_for_the_same_logical_request() {
1740 // Guards against the reviewed failure mode: projecting every route
1741 // through the Chat builder would make these collide.
1742 let chat = client("deepseek", |providers| {
1743 providers.deepseek = configured("sk-test-deepseek", None, "deepseek-v4-pro");
1744 })
1745 .prepare_outbound_request(request("deepseek-v4-pro"), true)
1746 .expect("chat prepares");
1747 let codex = codex_client();
1748 let responses = codex
1749 .prepare_outbound_request(request("gpt-5-codex"), true)
1750 .expect("responses prepares");
1751
1752 assert_ne!(chat.dialect, responses.dialect);
1753 assert_ne!(chat.body_sha256(), responses.body_sha256());
1754 }
1755
1756 #[test]
1757 fn streaming_and_blocking_bodies_are_distinguished_not_conflated() {
1758 let client = client("deepseek", |providers| {
1759 providers.deepseek = configured("sk-test-deepseek", None, "deepseek-v4-pro");
1760 });
1761 let streaming = client
1762 .prepare_outbound_request(request("deepseek-v4-pro"), true)
1763 .expect("streaming prepares");
1764 let blocking = client
1765 .prepare_outbound_request(request("deepseek-v4-pro"), false)
1766 .expect("blocking prepares");
1767
1768 assert_eq!(streaming.entrypoint, CallerStreamMode::Streaming);
1769 assert_eq!(blocking.entrypoint, CallerStreamMode::Blocking);
1770 // Chat is the dialect where caller mode and wire fact agree: the
1771 // streaming body sets `stream: true`, the blocking body omits it.
1772 assert_eq!(streaming.wire_stream_field(), Some(true));
1773 assert_eq!(blocking.wire_stream_field(), None);
1774 assert_ne!(streaming.body_sha256(), blocking.body_sha256());
1775 }
1776
1777 /// #1004 review finding: the Responses blocking entry point opens an SSE
1778 /// stream and folds it into one response, so its body says
1779 /// `"stream": true` while the caller mode is blocking. The manifest must
1780 /// read the body, never the caller mode.
1781 #[test]
1782 fn responses_wire_streaming_is_read_from_the_body_not_the_caller_mode() {
1783 let client = codex_client();
1784 let blocking = client
1785 .prepare_outbound_request(request("gpt-5-codex"), false)
1786 .expect("blocking responses prepares");
1787
1788 assert_eq!(blocking.entrypoint, CallerStreamMode::Blocking);
1789 assert_eq!(
1790 blocking.wire_stream_field(),
1791 Some(true),
1792 "the Responses blocking path genuinely sends an SSE body"
1793 );
1794
1795 let streaming = client
1796 .prepare_outbound_request(request("gpt-5-codex"), true)
1797 .expect("streaming responses prepares");
1798 assert_eq!(streaming.wire_stream_field(), Some(true));
1799 assert_eq!(
1800 streaming.body_sha256(),
1801 blocking.body_sha256(),
1802 "the two Responses entry points send the same bytes; only the \
1803 caller mode differs"
1804 );
1805 }
1806
1807 #[test]
1808 fn preparation_is_deterministic_across_repeated_calls() {
1809 let client = client("deepseek", |providers| {
1810 providers.deepseek = configured("sk-test-deepseek", None, "deepseek-v4-pro");
1811 });
1812 let first = client
1813 .prepare_outbound_request(request("deepseek-v4-pro"), true)
1814 .expect("first prepares");
1815 let second = client
1816 .prepare_outbound_request(request("deepseek-v4-pro"), true)
1817 .expect("second prepares");
1818 assert_eq!(first.body_sha256(), second.body_sha256());
1819 assert_eq!(first.endpoint_fingerprint(), second.endpoint_fingerprint());
1820 }
1821
1822 #[test]
1823 fn legacy_deepseek_chat_alias_resolves_to_flash_responses_route() {
1824 let client = client("deepseek", |providers| {
1825 providers.deepseek = configured("sk-test-deepseek", None, "deepseek-chat");
1826 });
1827 let prepared = client
1828 .prepare_outbound_request(request("deepseek-chat"), true)
1829 .expect("legacy alias prepares");
1830 assert_eq!(prepared.dialect, WireDialect::OpenAiResponses);
1831 assert_eq!(prepared.wire_model, "deepseek-flash");
1832 }
1833 }
1834
1834 lines RUST