返回 CodeWhale
request_manifest.rs
根目录 / crates / engine / src / request_manifest.rs
1 //! Redacted request manifest for `/preview-request` (#1004, #3928).
2 //!
3 //! A [`RequestManifest`] describes the request the **next primary agent turn**
4 //! would send: dialect, endpoint identity, wire model, reasoning resolution,
5 //! the exact active tool catalog, sizes, conservative offline token estimates,
6 //! and a whole-body hash.
7 //!
8 //! Four properties are load-bearing:
9 //!
10 //! 1. **Single-sourced.** Every wire fact is read off a
11 //! [`PreparedOutboundRequest`] — the same value the transport sends. There
12 //! is no second body builder, no Chat-shaped projection of a non-Chat
13 //! route, and no re-derivation of prompt or tool selection here.
14 //! 2. **Typed, allowlisted disclosure.** The manifest is a fixed set of
15 //! counts, hashes, enums, and short provenance labels, and every free-form
16 //! string crosses [`codewhale_runtime::safe_label`] first. Prompt text, project
17 //! instructions, memory, skill bodies, tool results, message content,
18 //! credentials, URL paths, and absolute workspace paths have no field to
19 //! occupy — and a hostile model or route id gets a fingerprint instead of
20 //! a verbatim copy.
21 //! 3. **Whole-body fidelity.** The body hash covers the complete canonicalized
22 //! wire body, so max-token fields, tool choice, nested reasoning controls,
23 //! transformed tool schemas, attachments, and stream options all move it.
24 //! 4. **Structural honesty.** Facts that are not yet knowable are *absent*,
25 //! not guessed. When auto model routing has not been resolved there is no
26 //! provider, route id, dialect, endpoint, wire model, billing, tool budget,
27 //! or body hash in this structure at all — a typed
28 //! [`Unavailable`] stands in its place on both the human and the JSON
29 //! surface. Recycling the current or previous route would be a lie about
30 //! what the next request will contain.
31 //!
32 //! Scope: this describes the **primary `LlmClient` agent turn** only —
33 //! `create_message` / `create_message_stream`. Auxiliary provider calls (chat
34 //! translation, FIM completion, speech, provider-native search, model
35 //! listing, and the auto-router classifier) are separate requests with their
36 //! own shapes and are deliberately not covered. See `docs/PREVIEW_REQUEST.md`.
37 //!
38 //! Token figures are *offline estimates* (~4 bytes/token plus a conservative
39 //! margin). They are never provider-authoritative token counts.
40 //!
41 //! The `dryrun` concept this serves — inspect the next request from the real
42 //! request-building seam instead of a hand-rolled summary — is harvested from
43 //! PR #1099 by TaoMu (GTC2080).
44
45 use serde::Serialize;
46
47 use crate::client::PreparedOutboundRequest;
48 use codewhale_runtime::safe_label::SafeLabel;
49
50 /// Bytes-per-token divisor for the offline estimator.
51 const BYTES_PER_TOKEN: usize = 4;
52 /// Conservative margin applied to the estimated total (percent).
53 const ESTIMATE_MARGIN_PERCENT: usize = 5;
54 /// Bumped whenever a field is renamed or removed, so scripted consumers can
55 /// detect an incompatible manifest instead of silently reading `null`.
56 ///
57 /// v3 introduced the sectioned `route` / `tools` / `body` availability shape.
58 /// v4 made the byte classes an exact accounting decomposition of the wire
59 /// body, moved the component digest onto the *wire* tool schemas, reported nested reasoning
60 /// efforts with their key path, and re-based headroom on the production input
61 /// budget rather than the raw context window.
62 /// v5 renamed the system/tools digest to state its local component scope and
63 /// removed the unsupported implication that it is a provider cache identity.
64 /// v6 replaced the raw endpoint host with a safe host class/digest and added
65 /// explicit route-limit provenance plus input/output budget facts.
66 /// v7 names canonical JSON sizes truthfully and adds primary-agent identity,
67 /// typed route provenance, and an explicit unavailable provider-usage receipt.
68 /// v8 makes authoritative Work state and the active goal-budget terminal gate
69 /// explicit fail-closed dependencies of an exact body.
70 pub const MANIFEST_SCHEMA_VERSION: u32 = 9;
71
72 /// Exact readable base-prompt-only disclosure for the explicit
73 /// `/preview-request base-prompt` mode. This deliberately returns no runtime
74 /// system layers: project instructions, skills, memory, and message content
75 /// remain represented only by the protected effective-system hash.
76 pub fn exact_base_prompt_only() -> String {
77 crate::prompts::effective_base_prompt_text().to_string()
78 }
79
80 /// A section of the manifest that is either exactly known or typed-absent.
81 ///
82 /// This is the whole point of the structure: there is no "unknown" *value*
83 /// anywhere in a manifest, because an unknown fact has no field.
84 #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
85 #[serde(rename_all = "kebab-case")]
86 pub enum Availability<T> {
87 /// Exactly what the next turn would send.
88 Exact(T),
89 /// Not knowable without doing something a preview must not do.
90 Unavailable(Unavailable),
91 }
92
93 impl<T> Availability<T> {
94 pub fn unavailable(reason: UnavailableReason) -> Self {
95 Self::Unavailable(Unavailable {
96 reason,
97 detail: None,
98 })
99 }
100
101 pub fn unavailable_with(reason: UnavailableReason, detail: String) -> Self {
102 Self::Unavailable(Unavailable {
103 reason,
104 detail: Some(codewhale_runtime::safe_label::safe_error_text(&detail)),
105 })
106 }
107
108 pub fn map<U>(self, transform: impl FnOnce(T) -> U) -> Availability<U> {
109 match self {
110 Self::Exact(value) => Availability::Exact(transform(value)),
111 Self::Unavailable(unavailable) => Availability::Unavailable(unavailable),
112 }
113 }
114
115 #[cfg(any(test, feature = "test-support"))]
116 pub fn exact(&self) -> Option<&T> {
117 match self {
118 Self::Exact(value) => Some(value),
119 Self::Unavailable(_) => None,
120 }
121 }
122
123 /// Carry this section's unavailability onto a section that depends on it.
124 ///
125 /// Returns `None` when this section is exact, so the caller falls through
126 /// to building the dependent section normally. This is what keeps a
127 /// dependency from silently becoming exact: when the MCP contribution to
128 /// the tool surface is unknown, the body built from that surface is a body
129 /// no turn would send, and it must inherit the same typed reason rather
130 /// than publish an exact hash of a fabricated request.
131 pub fn propagate<U>(&self) -> Option<Availability<U>> {
132 match self {
133 Self::Exact(_) => None,
134 Self::Unavailable(unavailable) => Some(Availability::Unavailable(unavailable.clone())),
135 }
136 }
137 }
138
139 /// Why a section could not be described exactly.
140 #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
141 pub struct Unavailable {
142 pub reason: UnavailableReason,
143 /// Bounded, path- and URL-path-safe explanation. Never raw error text.
144 pub detail: Option<String>,
145 }
146
147 #[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
148 #[serde(rename_all = "kebab-case")]
149 pub enum UnavailableReason {
150 /// Auto model routing is on and no hypothetical prompt was supplied, so
151 /// the concrete route is decided by text that does not exist yet.
152 AutoRouteUnresolvedUntilNextPrompt,
153 /// Resolving Auto would make a provider/model classifier call, which an
154 /// offline inspection command must never do.
155 AutoRouteClassificationNotExecuted,
156 /// No `--prompt` was supplied, so there is no exact next-turn body: the
157 /// next user message is part of the request.
158 NoHypotheticalPromptSupplied,
159 /// The host's shared route planner failed for this hypothetical turn.
160 RoutePlanFailed,
161 /// The exact MCP tool state is not knowable without connecting, which an
162 /// inspection must never do. Also carried by the body section: a body
163 /// built from a tool surface that is missing its MCP contribution is not
164 /// the body the next turn would send.
165 McpStateNotSnapshottable,
166 /// The shared prepared-request seam refused to build a body.
167 RequestPreparationFailed,
168 /// Mutable `message_submit` hooks are configured. They may rewrite or
169 /// block the next message before anything downstream sees it, and an
170 /// inspection must not execute them — so the route, tool surface, and body
171 /// they would shape are all unknowable from here.
172 MessageSubmitHooksNotExecuted,
173 /// Resolving the hypothetical prompt into model-facing content failed the
174 /// same way a real submit would have failed (skill authority, file
175 /// mentions).
176 PromptResolutionFailed,
177 /// The turn loop would transform this request between dispatch and the
178 /// wire — auto-compaction, context-overflow recovery, a background-shell
179 /// or queued sub-agent completion, or pending LSP diagnostics — and an
180 /// inspection may neither run nor consume any of them.
181 RuntimeTransformsBeforeSend,
182 /// The active goal has consumed its token budget, so the continuation
183 /// gate stops before creating another provider request.
184 GoalTokenBudgetExhausted,
185 /// The live goal state could not be read without guessing whether its
186 /// terminal budget gate would permit another request.
187 GoalStateNotSnapshottable,
188 /// Preview never sends a provider request, so no provider-counted usage
189 /// receipt exists. This must not be represented by zero token counts.
190 ProviderRequestNotExecuted,
191 }
192
193 impl UnavailableReason {
194 pub fn label(self) -> &'static str {
195 match self {
196 Self::AutoRouteUnresolvedUntilNextPrompt => {
197 "auto model routing is unresolved until the next prompt"
198 }
199 Self::AutoRouteClassificationNotExecuted => {
200 "auto route classification was not executed because preview is offline"
201 }
202 Self::NoHypotheticalPromptSupplied => {
203 "no hypothetical prompt supplied — the next user message is part of the request"
204 }
205 Self::RoutePlanFailed => "the shared route planner could not resolve this turn",
206 Self::McpStateNotSnapshottable => {
207 "MCP tool state cannot be snapshotted without connecting"
208 }
209 Self::RequestPreparationFailed => "request preparation failed",
210 Self::MessageSubmitHooksNotExecuted => {
211 "message-submit hooks are configured and an inspection must not run them"
212 }
213 Self::PromptResolutionFailed => {
214 "the hypothetical prompt could not be resolved into model-facing content"
215 }
216 Self::RuntimeTransformsBeforeSend => {
217 "the turn loop would transform this request before sending it"
218 }
219 Self::GoalTokenBudgetExhausted => {
220 "active goal token budget is exhausted; no outbound request is eligible"
221 }
222 Self::GoalStateNotSnapshottable => "active goal state cannot be snapshotted exactly",
223 Self::ProviderRequestNotExecuted => {
224 "provider request not executed; provider-reported usage is unavailable"
225 }
226 }
227 }
228 }
229
230 /// How the reasoning tier for the next request was determined.
231 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
232 #[serde(rename_all = "kebab-case")]
233 pub enum ReasoningResolution {
234 /// The user pinned a concrete tier; the next request will use it.
235 Explicit,
236 /// Auto routing, resolved against the supplied hypothetical prompt by the
237 /// same planner a real turn runs.
238 ResolvedFromHypotheticalPrompt,
239 /// The body carries a reasoning control the user never asked for: the
240 /// dialect or the route shapes one in by default. Reporting this as
241 /// `Explicit` would credit the user with a selection they did not make.
242 RouteDefault,
243 /// The route asks for no reasoning at all. A Responses body that carries
244 /// only `include` — which *discloses* reasoning output rather than
245 /// requesting a tier — lands here, not on `Explicit`.
246 NotApplicable,
247 }
248
249 impl ReasoningResolution {
250 fn label(self) -> &'static str {
251 match self {
252 Self::Explicit => "explicit user selection",
253 Self::ResolvedFromHypotheticalPrompt => {
254 "auto, resolved against the supplied hypothetical prompt"
255 }
256 Self::RouteDefault => "route default (no user selection)",
257 Self::NotApplicable => "route sends no reasoning control",
258 }
259 }
260 }
261
262 /// How the effective system prompt was assembled, without quoting any of it.
263 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
264 #[serde(rename_all = "kebab-case")]
265 pub enum SystemPromptAssembly {
266 /// The effective system prompt is exactly the base-prompt bytes.
267 BaseOnly,
268 /// Base prompt plus the configured static layers, and nothing else.
269 BaseWithConfiguredLayers,
270 /// Runtime or session layers (environment, project instructions, skills,
271 /// memory, mode) were appended on top.
272 BaseWithRuntimeAdditions,
273 /// No system prompt would be sent.
274 None,
275 }
276
277 impl SystemPromptAssembly {
278 fn label(self) -> &'static str {
279 match self {
280 Self::BaseOnly => "base prompt only",
281 Self::BaseWithConfiguredLayers => "base prompt + configured static layers",
282 Self::BaseWithRuntimeAdditions => {
283 "base prompt + configured layers + runtime/session additions"
284 }
285 Self::None => "no system prompt",
286 }
287 }
288 }
289
290 /// How this route is billed, as typed facts with static labels.
291 #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
292 #[serde(tag = "kind", rename_all = "kebab-case")]
293 pub enum BillingFacts {
294 /// Per-token API usage.
295 Metered,
296 /// Account/subscription quota; per-token dollar estimates are not spend.
297 Subscription { plan: &'static str },
298 /// Local route with no provider bill.
299 Local,
300 /// Billing basis unknown; never invent dollars or a fake zero.
301 Unknown,
302 /// Endpoint-derived pricing surface classification for routes that have
303 /// one (`Stepfun` today). Never a URL.
304 Surface { surface: &'static str },
305 }
306
307 impl BillingFacts {
308 fn label(&self) -> String {
309 match self {
310 Self::Metered => "metered API (per-token)".to_string(),
311 Self::Subscription { plan } => format!("subscription quota ({plan})"),
312 Self::Local => "local route (no provider bill)".to_string(),
313 Self::Unknown => "unknown billing basis".to_string(),
314 Self::Surface { surface } => format!("metered API, pricing surface `{surface}`"),
315 }
316 }
317 }
318
319 /// Base-prompt provenance: labels, byte counts, and hashes only (#3928).
320 #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
321 pub struct BasePromptProvenance {
322 /// Where the base-prompt bytes came from: bundled or configured override.
323 /// A static runtime label, never a source-tree path.
324 pub origin: String,
325 pub bytes: usize,
326 pub sha256: String,
327 }
328
329 /// System-prompt provenance of the *prepared request*.
330 #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
331 pub struct PromptProvenance {
332 /// How the effective prompt was assembled from the base prompt.
333 pub assembly: SystemPromptAssembly,
334 /// Canonical JSON bytes and hash of the system region of the prepared
335 /// request — the same semantic prompt value production sends.
336 pub effective_system_canonical_json_bytes: usize,
337 pub effective_system_sha256: String,
338 }
339
340 /// Session posture that does not depend on the route or the next message.
341 #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
342 pub struct SessionFacts {
343 /// Exact execution identity for this manifest's deliberately narrow scope.
344 pub agent_role: String,
345 pub lane_kind: String,
346 /// Primary interactive turns are not Fleet workers. Say that explicitly
347 /// rather than inventing a Fleet role or leaving an ambiguous null.
348 pub fleet_assignment: String,
349 /// The model the user selected, before route remapping. `auto` when auto
350 /// model routing is on — never a concrete model the user did not pick.
351 pub requested_model: SafeLabel,
352 /// Whether auto model routing is selected.
353 pub auto_model_routing: bool,
354 /// Reasoning tier the user asked for (`auto`, `high`, `off`, …).
355 pub requested_reasoning: SafeLabel,
356 /// Whether the caller supplied a hypothetical next prompt.
357 pub hypothetical_prompt_supplied: bool,
358 /// Operating mode the catalog would be built under.
359 pub mode: String,
360 /// Approval posture the catalog would be filtered under.
361 pub approval_mode: String,
362 /// Number of entries in the allow-list gate, if one is configured.
363 pub allowed_tool_gate_count: Option<usize>,
364 /// Number of entries in the deny-list gate, if one is configured.
365 pub disallowed_tool_gate_count: Option<usize>,
366 pub base_prompt: BasePromptProvenance,
367 }
368
369 /// Exactly which route the next turn would use.
370 #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
371 pub struct RouteFacts {
372 pub provider_id: SafeLabel,
373 pub provider_display: SafeLabel,
374 /// Named custom-provider / route identity from the resolved turn plan.
375 pub route_id: Option<SafeLabel>,
376 pub dialect: String,
377 /// Responses dialect id taken from the prepared request. Empty for every
378 /// other wire. The id is not part of the request body.
379 #[serde(skip_serializing_if = "Option::is_none")]
380 pub responses_profile_id: Option<String>,
381 pub route_shape: String,
382 /// Safe endpoint class. Remote authorities are represented only by a
383 /// bounded digest; even a credential-shaped tenant subdomain is never
384 /// printed. Loopback is reported as a class, never a raw host.
385 pub endpoint_host_class: String,
386 /// SHA-256 of the full endpoint URL, for "same endpoint?" comparisons.
387 pub endpoint_fingerprint: String,
388 /// The model id literally placed on the wire, after route remapping.
389 pub wire_model: SafeLabel,
390 /// Which transport entry point this manifest described.
391 pub caller_entrypoint: String,
392 /// The `stream` field **as it appears on the body**, or `null` when the
393 /// body carries no such field. Derived from the body, never from the
394 /// caller entry point: the Responses blocking path sends `stream: true`.
395 ///
396 /// This lives in the *route* section, and stays exact even when the body
397 /// section does not, because every dialect builder writes it from the
398 /// caller entry point and the provider alone — never from the message list
399 /// or the tool set. It is a property of the route, not of the payload.
400 pub body_stream_field: Option<bool>,
401 /// Active context-window ceiling and the resolver receipt for its source.
402 pub context_limit_tokens: u32,
403 pub context_limit_source: crate::route_runtime::ContextWindowSource,
404 /// Concrete route/offering limits, when advertised. These remain
405 /// separate from the effective wire output cap.
406 pub route_input_limit_tokens: Option<u64>,
407 pub route_output_limit_tokens: Option<u64>,
408 pub billing: BillingFacts,
409 /// Upstream planner receipt for why this concrete route was selected.
410 pub routing_source: String,
411 /// How the auto router chose this route, when auto routing ran.
412 pub auto_route_source: Option<SafeLabel>,
413 }
414
415 /// Everything the manifest reports about the next request's tool surface.
416 #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
417 pub struct ToolSurfaceFacts {
418 /// Tools in the full built catalog, including deferred ones.
419 pub catalog_tool_count: usize,
420 /// Tools deferred (discoverable via tool search, not sent eagerly).
421 pub deferred_tool_count: usize,
422 /// Tools that would actually be serialized into this request.
423 pub active_tool_count: usize,
424 /// Stable hash over the *current active* catalog, before dialect shaping:
425 /// name, description, and canonical logical schema, in catalog order. Not
426 /// the last turn's.
427 ///
428 /// This is a *catalog identity*, not a wire fact. Two routes can agree
429 /// here and still send different bytes, because each dialect transforms
430 /// schemas its own way and strict mode sanitizes them further. The hash
431 /// the provider actually receives is `body.tool_schema_wire_sha256`, and
432 /// that is the one the local system/tools component digest is built from.
433 pub active_tool_catalog_sha256: String,
434 /// The capability profile's surface budget label for this route.
435 pub tool_surface_budget: String,
436 /// Truthful disclosure (#1004): whether Standard and Full currently
437 /// produce the same catalog. Derived by running the surface shaper under
438 /// both budgets over this exact catalog — not asserted.
439 pub standard_and_full_surfaces_collapsed: bool,
440 /// MCP servers connected and contributing tools.
441 pub mcp_server_count: usize,
442 /// Tools in the active catalog that came from MCP.
443 pub mcp_tool_count: usize,
444 }
445
446 /// Per-class conservative offline estimates, derived from the wire body.
447 ///
448 /// `system`, `tool_schemas`, `messages`, and `framing` are estimates over the
449 /// four classes of the exact byte accounting (see [`crate::client::WireBodyView`]),
450 /// so they sum to the whole body rather than a selected part of it.
451 /// `tool_results` and `attachments` are *subsets* of `messages`, reported for
452 /// attribution and never added again.
453 #[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
454 pub struct TokenEstimates {
455 pub system: usize,
456 pub tool_schemas: usize,
457 pub messages: usize,
458 pub tool_results: usize,
459 pub attachments: usize,
460 pub framing: usize,
461 /// Estimate over the **whole** canonical JSON body plus a conservative margin.
462 ///
463 /// Derived from the complete canonical body rather than by summing the
464 /// per-class estimates, so per-class rounding cannot make the total drift
465 /// away from the semantic JSON value production sends.
466 pub total_conservative: usize,
467 }
468
469 /// Facts read off the exact next-turn body.
470 #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
471 pub struct BodyFacts {
472 pub reasoning_resolution: ReasoningResolution,
473 /// Reasoning-control keys present on the wire. Keys only, never values
474 /// that could carry free text.
475 pub reasoning_wire_control_keys: Vec<String>,
476 /// The effort string actually on the wire, whether the dialect writes it
477 /// flat (`reasoning_effort`) or nested (`thinking.effort`,
478 /// `reasoning.effort`, `output_config.effort`).
479 pub reasoning_wire_effort: Option<SafeLabel>,
480 /// Which key path [`Self::reasoning_wire_effort`] was read from. A
481 /// compile-time constant from the dialect allowlist, never a key taken
482 /// out of the body.
483 pub reasoning_wire_effort_source: Option<String>,
484 /// `tool_choice` as it appears on the wire, as a short shape label.
485 pub tool_choice: Option<SafeLabel>,
486 pub omitted_tool_count: usize,
487 pub omitted_tool_names: Vec<String>,
488 pub prompt: PromptProvenance,
489
490 /// Canonical JSON byte length of the complete body. The four accounting
491 /// class counts below sum to this number; they are not HTTP byte ranges.
492 pub body_canonical_json_bytes: usize,
493 pub system_canonical_json_bytes: usize,
494 pub tool_schema_canonical_json_bytes: usize,
495 pub message_count: usize,
496 pub message_canonical_json_bytes: usize,
497 /// Subset of [`Self::message_canonical_json_bytes`].
498 pub tool_result_canonical_json_bytes: usize,
499 pub attachment_count: usize,
500 /// Subset of [`Self::message_canonical_json_bytes`].
501 pub attachment_canonical_json_bytes: usize,
502 /// Algebraic remainder after the selected canonical value-region sizes.
503 pub framing_canonical_json_bytes: usize,
504
505 pub estimates: TokenEstimates,
506 /// Estimated input tokens still available before this route's **input
507 /// budget ceiling** — the production seam
508 /// (`context_input_budget_for_route`) the turn loop itself checks, which
509 /// is the context window minus the output reservation and safety
510 /// headroom. Deliberately *not* the raw context limit: subtracting input
511 /// from a window the route also has to fit its output into reports
512 /// headroom the turn does not have. Negative when the turn would exceed
513 /// the budget; absent when the route publishes no budget.
514 pub estimated_input_headroom_tokens: Option<i64>,
515 /// The exact production input-budget ceiling from which headroom was
516 /// computed, after output reservation and safety headroom.
517 pub input_budget_ceiling_tokens: Option<usize>,
518 /// Output cap literally present on the prepared wire body. Absent means
519 /// this dialect did not publish one; no inferred value is substituted.
520 pub wire_output_cap_tokens: Option<u64>,
521
522 /// SHA-256 over the canonicalized **complete** wire body.
523 pub body_sha256: String,
524 /// SHA-256 over the canonicalized wire `tools` region — the schemas the
525 /// provider receives, after dialect transforms and strict-mode
526 /// sanitizing. Absent when the body carries no tools.
527 pub tool_schema_wire_sha256: Option<String>,
528 /// Local fingerprint over the final wire system-region hash and final wire
529 /// tool-region hash. This is not a provider cache key and makes no claim
530 /// that those regions are adjacent in a provider-specific prefix.
531 pub local_system_tools_component_sha256: Option<String>,
532 /// Provider-authoritative counts are available only after a real response.
533 pub provider_reported_usage: Availability<ProviderReportedUsage>,
534 }
535
536 /// Provider-authoritative usage, populated only from a completed response.
537 #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
538 pub struct ProviderReportedUsage {
539 pub input_tokens: u64,
540 pub output_tokens: u64,
541 }
542
543 /// What the engine hands to [`RequestManifest::build`] for the body section.
544 pub struct PreparedBodyInputs<'a> {
545 pub prepared: &'a PreparedOutboundRequest,
546 pub reasoning_resolution: ReasoningResolution,
547 pub prompt: PromptProvenance,
548 /// This route's production input-budget ceiling in tokens, from
549 /// `context_input_budget_for_route` — the same seam the turn loop checks
550 /// before it sends. `None` when the route publishes no budget.
551 pub input_budget_ceiling_tokens: Option<usize>,
552 /// Input estimate from production's overflow contract,
553 /// the base `estimate_input_tokens_conservative(messages, system)` plus a
554 /// separately framed transient Work-tail estimate, evaluated over the
555 /// exact hypothetical turn. This is intentionally independent of the
556 /// manifest's whole-wire-body estimate.
557 pub production_input_estimate_tokens: usize,
558 /// Whether the tool surface is exactly known. The local component digest
559 /// is published only when it is: a fingerprint computed over a tool region
560 /// missing its MCP contribution would compare equal to nothing real.
561 pub tool_surface_is_exact: bool,
562 }
563
564 /// The complete draft the engine assembles before rendering.
565 pub struct ManifestDraft<'a> {
566 pub session: SessionFacts,
567 pub route: Availability<RouteFacts>,
568 pub tools: Availability<ToolSurfaceFacts>,
569 pub body: Availability<PreparedBodyInputs<'a>>,
570 }
571
572 /// A redacted description of the request that would be sent.
573 #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
574 pub struct RequestManifest {
575 pub schema_version: u32,
576 pub session: SessionFacts,
577 pub route: Availability<RouteFacts>,
578 pub tools: Availability<ToolSurfaceFacts>,
579 pub body: Availability<BodyFacts>,
580 }
581
582 /// Signed production input headroom for one route ceiling and estimate.
583 /// Negative means the turn loop's preflight gate must recover or stop before
584 /// sending. Both the manifest and preview overflow decision use this helper so
585 /// the displayed headroom cannot disagree with request eligibility.
586 pub fn production_input_headroom(
587 ceiling_tokens: Option<usize>,
588 estimate_tokens: usize,
589 ) -> Option<i64> {
590 ceiling_tokens
591 .and_then(|ceiling| {
592 Some((
593 i64::try_from(ceiling).ok()?,
594 i64::try_from(estimate_tokens).ok()?,
595 ))
596 })
597 .map(|(ceiling, estimate)| ceiling - estimate)
598 }
599
600 #[must_use]
601 pub fn production_input_budget_exceeded(
602 ceiling_tokens: Option<usize>,
603 estimate_tokens: usize,
604 ) -> bool {
605 production_input_headroom(ceiling_tokens, estimate_tokens).is_some_and(|headroom| headroom < 0)
606 }
607
608 impl RequestManifest {
609 /// Build a manifest from a draft whose route/tool/body sections have
610 /// already been resolved — or typed as unavailable — by the engine.
611 pub fn build(draft: ManifestDraft<'_>) -> Self {
612 let body = draft.body.map(|inputs| {
613 let view = inputs.prepared.wire_view();
614 // The accounting classes below must sum to the body. They describe
615 // canonical value-region sizes plus a remainder, not disjoint
616 // borrowed ranges in the serialized JSON buffer.
617 debug_assert!(
618 view.partition_is_exact(),
619 "wire byte accounting must sum to the wire body exactly"
620 );
621 let estimates = TokenEstimates::from_view(&view);
622 // Headroom comes from the production input-budget seam, never from
623 // the raw context window: the window has to hold the response too.
624 let estimated_input_headroom_tokens = production_input_headroom(
625 inputs.input_budget_ceiling_tokens,
626 inputs.production_input_estimate_tokens,
627 );
628 let tool_schema_wire_sha256 =
629 (!view.tool_schema_sha256.is_empty()).then(|| view.tool_schema_sha256.clone());
630 // A local identity for the two final wire components. This hashes
631 // their digests rather than claiming they form one contiguous
632 // provider-cache prefix or a route-scoped cache key.
633 let local_system_tools_component_sha256 = inputs.tool_surface_is_exact.then(|| {
634 codewhale_runtime::hashing::sha256_hex(
635 format!(
636 "system={}\ntools={}\n",
637 view.system_sha256, view.tool_schema_sha256
638 )
639 .as_bytes(),
640 )
641 });
642 let wire_effort = inputs.prepared.reasoning.wire_effort();
643
644 BodyFacts {
645 reasoning_resolution: inputs.reasoning_resolution,
646 reasoning_wire_control_keys: inputs
647 .prepared
648 .reasoning
649 .wire_controls
650 .iter()
651 .map(|(key, _)| key.clone())
652 .collect(),
653 reasoning_wire_effort: wire_effort.map(|(_, effort)| SafeLabel::identifier(effort)),
654 reasoning_wire_effort_source: wire_effort.map(|(source, _)| source.to_string()),
655 // Read the final provider-shaped body. The logical request can
656 // be remapped (Anthropic/Responses) or omitted altogether
657 // (DeepSeek thinking), so carrying the pre-transform value
658 // would report a choice the provider never receives.
659 tool_choice: tool_choice_label(inputs.prepared.body.get("tool_choice")),
660 omitted_tool_count: inputs.prepared.omitted_tool_names.len(),
661 omitted_tool_names:
662 codewhale_models::tool_projection::bounded_tool_projection_warning_names(
663 &inputs.prepared.omitted_tool_names,
664 ),
665 prompt: inputs.prompt,
666 body_canonical_json_bytes: view.body_bytes,
667 system_canonical_json_bytes: view.system_bytes,
668 tool_schema_canonical_json_bytes: view.tool_schema_bytes,
669 message_count: view.items.len(),
670 message_canonical_json_bytes: view.item_bytes,
671 tool_result_canonical_json_bytes: view.tool_result_bytes,
672 attachment_count: view.attachment_count,
673 attachment_canonical_json_bytes: view.attachment_bytes,
674 framing_canonical_json_bytes: view.framing_bytes,
675 estimates,
676 estimated_input_headroom_tokens,
677 input_budget_ceiling_tokens: inputs.input_budget_ceiling_tokens,
678 wire_output_cap_tokens: inputs.prepared.wire_output_cap_tokens(),
679 body_sha256: inputs.prepared.body_sha256(),
680 tool_schema_wire_sha256,
681 local_system_tools_component_sha256,
682 provider_reported_usage: Availability::unavailable(
683 UnavailableReason::ProviderRequestNotExecuted,
684 ),
685 }
686 });
687
688 Self {
689 schema_version: MANIFEST_SCHEMA_VERSION,
690 session: draft.session,
691 route: draft.route,
692 tools: draft.tools,
693 body,
694 }
695 }
696
697 /// Pretty JSON rendering. Redacted by construction.
698 pub fn to_json(&self) -> String {
699 serde_json::to_string_pretty(self)
700 .unwrap_or_else(|error| format!("{{\"error\":\"{error}\"}}"))
701 }
702
703 /// Human-readable manifest for the transcript.
704 pub fn render(&self) -> String {
705 let mut out = String::new();
706 out.push_str("Request manifest (preview only — nothing was sent)\n");
707 out.push_str(
708 "Typed counts, hashes, and provenance for the next primary agent turn. \
709 No prompt or message text.\n\n",
710 );
711
712 self.render_session(&mut out);
713 self.render_route(&mut out);
714 self.render_tools(&mut out);
715 self.render_body(&mut out);
716
717 if !self.session.hypothetical_prompt_supplied {
718 if self.session.auto_model_routing {
719 out.push_str(
720 "\nAuto route and body remain unavailable: preview never runs the \
721 provider-backed classifier. Select a fixed route for an exact preview.\n",
722 );
723 } else {
724 out.push_str(
725 "\nPass `--prompt <text>` to resolve the fixed route and describe the exact \
726 next-turn body.\n",
727 );
728 }
729 }
730 out.push_str(
731 "Token figures are offline estimates (~4 bytes/token + 5% margin), \
732 never exact provider tokens.\n",
733 );
734 out.push_str(
735 "Scope: the primary agent turn only. Translation, FIM, speech, \
736 provider-native search, and the auto-router classifier are separate \
737 auxiliary calls; preview never executes them.\n",
738 );
739 out
740 }
741
742 fn render_session(&self, out: &mut String) {
743 out.push_str("Session\n");
744 push_row(out, "agent role", &self.session.agent_role);
745 push_row(out, "lane", &self.session.lane_kind);
746 push_row(out, "Fleet assignment", &self.session.fleet_assignment);
747 push_row(
748 out,
749 "model (requested)",
750 self.session.requested_model.as_str(),
751 );
752 push_row(
753 out,
754 "model routing",
755 if self.session.auto_model_routing {
756 "auto"
757 } else {
758 "fixed"
759 },
760 );
761 push_row(
762 out,
763 "reasoning (requested)",
764 self.session.requested_reasoning.as_str(),
765 );
766 push_row(
767 out,
768 "mode / approval",
769 &format!("{} / {}", self.session.mode, self.session.approval_mode),
770 );
771 push_row(
772 out,
773 "gates (allow / deny)",
774 &format!(
775 "{} / {}",
776 count_label(self.session.allowed_tool_gate_count),
777 count_label(self.session.disallowed_tool_gate_count),
778 ),
779 );
780 push_row(out, "base prompt origin", &self.session.base_prompt.origin);
781 push_row(
782 out,
783 "base prompt",
784 &format!(
785 "{} bytes (sha256 {})",
786 self.session.base_prompt.bytes, self.session.base_prompt.sha256
787 ),
788 );
789 }
790
791 fn render_route(&self, out: &mut String) {
792 out.push_str("\nRoute\n");
793 let route = match &self.route {
794 Availability::Unavailable(unavailable) => {
795 push_unavailable(out, unavailable);
796 return;
797 }
798 Availability::Exact(route) => route,
799 };
800 push_row(
801 out,
802 "provider",
803 &format!("{} ({})", route.provider_display, route.provider_id),
804 );
805 if let Some(route_id) = &route.route_id {
806 push_row(out, "route id", route_id.as_str());
807 }
808 if let Some(source) = &route.auto_route_source {
809 push_row(out, "auto route source", source.as_str());
810 }
811 push_row(out, "routing source", &route.routing_source);
812 push_row(out, "dialect", &route.dialect);
813 push_row(out, "route shape", &route.route_shape);
814 push_row(out, "endpoint host class", &route.endpoint_host_class);
815 push_row(out, "endpoint fingerprint", &route.endpoint_fingerprint);
816 push_row(out, "model (wire)", route.wire_model.as_str());
817 push_row(out, "prepared for", &route.caller_entrypoint);
818 push_row(
819 out,
820 "body `stream` field",
821 match route.body_stream_field {
822 Some(true) => "true",
823 Some(false) => "false",
824 None => "not present on the body",
825 },
826 );
827 push_row(
828 out,
829 "context limit",
830 &format!(
831 "{} ({})",
832 route.context_limit_tokens,
833 route.context_limit_source.label()
834 ),
835 );
836 push_row(
837 out,
838 "route input limit",
839 &route
840 .route_input_limit_tokens
841 .map_or_else(|| "unknown".to_string(), |limit| limit.to_string()),
842 );
843 push_row(
844 out,
845 "route output limit",
846 &route
847 .route_output_limit_tokens
848 .map_or_else(|| "unknown".to_string(), |limit| limit.to_string()),
849 );
850 push_row(out, "billing", &route.billing.label());
851 }
852
853 fn render_tools(&self, out: &mut String) {
854 out.push_str("\nTools (the exact catalog this request would send)\n");
855 let tools = match &self.tools {
856 Availability::Unavailable(unavailable) => {
857 push_unavailable(out, unavailable);
858 return;
859 }
860 Availability::Exact(tools) => tools,
861 };
862 push_row(out, "active", &tools.active_tool_count.to_string());
863 push_row(
864 out,
865 "catalog / deferred",
866 &format!(
867 "{} / {}",
868 tools.catalog_tool_count, tools.deferred_tool_count
869 ),
870 );
871 push_row(
872 out,
873 "active catalog sha256",
874 &tools.active_tool_catalog_sha256,
875 );
876 push_row(out, "surface budget", &tools.tool_surface_budget);
877 push_row(
878 out,
879 "Standard vs Full",
880 if tools.standard_and_full_surfaces_collapsed {
881 "collapsed — both budgets currently produce the same catalog"
882 } else {
883 "distinct — the budgets produce different catalogs"
884 },
885 );
886 push_row(
887 out,
888 "MCP (servers / tools)",
889 &format!("{} / {}", tools.mcp_server_count, tools.mcp_tool_count),
890 );
891 }
892
893 fn render_body(&self, out: &mut String) {
894 out.push_str("\nWire body\n");
895 let body = match &self.body {
896 Availability::Unavailable(unavailable) => {
897 push_unavailable(out, unavailable);
898 return;
899 }
900 Availability::Exact(body) => body,
901 };
902
903 push_row(
904 out,
905 "canonical JSON bytes (total)",
906 &body.body_canonical_json_bytes.to_string(),
907 );
908 push_row(
909 out,
910 "canonical JSON bytes (system)",
911 &body.system_canonical_json_bytes.to_string(),
912 );
913 push_row(
914 out,
915 "canonical JSON bytes (tool schemas)",
916 &body.tool_schema_canonical_json_bytes.to_string(),
917 );
918 push_row(
919 out,
920 "messages / canonical JSON bytes",
921 &format!(
922 "{} / {}",
923 body.message_count, body.message_canonical_json_bytes
924 ),
925 );
926 push_row(
927 out,
928 "tool-result canonical JSON bytes",
929 &body.tool_result_canonical_json_bytes.to_string(),
930 );
931 push_row(
932 out,
933 "attachments / canonical JSON bytes",
934 &format!(
935 "{} / {}",
936 body.attachment_count, body.attachment_canonical_json_bytes
937 ),
938 );
939 push_row(
940 out,
941 "framing canonical JSON bytes",
942 &format!(
943 "{} (key names, punctuation, all other fields)",
944 body.framing_canonical_json_bytes
945 ),
946 );
947 push_row(
948 out,
949 "byte classes",
950 "system + tool schemas + messages + framing = total, exactly",
951 );
952
953 out.push_str("\nReasoning (as prepared)\n");
954 push_row(out, "resolution", body.reasoning_resolution.label());
955 push_row(
956 out,
957 "wire controls",
958 if body.reasoning_wire_control_keys.is_empty() {
959 "none".to_string()
960 } else {
961 body.reasoning_wire_control_keys.join(", ")
962 }
963 .as_str(),
964 );
965 push_row(
966 out,
967 "wire effort",
968 &match (
969 &body.reasoning_wire_effort,
970 &body.reasoning_wire_effort_source,
971 ) {
972 (Some(effort), Some(source)) => format!("{effort} (from `{source}`)"),
973 (Some(effort), None) => effort.as_str().to_string(),
974 _ => "not sent".to_string(),
975 },
976 );
977 push_row(
978 out,
979 "tool_choice",
980 body.tool_choice
981 .as_ref()
982 .map_or("not sent", SafeLabel::as_str),
983 );
984 if body.omitted_tool_count > 0 {
985 push_row(
986 out,
987 "omitted incompatible tools",
988 &format!(
989 "{}: {}",
990 body.omitted_tool_count,
991 crate::core::events::tool_projection_warning_tool_list(
992 &body.omitted_tool_names,
993 body.omitted_tool_count,
994 )
995 ),
996 );
997 }
998
999 out.push_str("\nSystem prompt (as prepared)\n");
1000 push_row(out, "assembly", body.prompt.assembly.label());
1001 push_row(
1002 out,
1003 "effective system",
1004 &format!(
1005 "{} canonical JSON bytes (sha256 {})",
1006 body.prompt.effective_system_canonical_json_bytes,
1007 body.prompt.effective_system_sha256
1008 ),
1009 );
1010
1011 out.push_str("\nEstimated tokens (offline estimate, not provider-counted)\n");
1012 push_row(out, "system", &body.estimates.system.to_string());
1013 push_row(
1014 out,
1015 "tool schemas",
1016 &body.estimates.tool_schemas.to_string(),
1017 );
1018 push_row(out, "messages", &body.estimates.messages.to_string());
1019 push_row(
1020 out,
1021 " of which tool results",
1022 &body.estimates.tool_results.to_string(),
1023 );
1024 push_row(
1025 out,
1026 " of which attachments",
1027 &body.estimates.attachments.to_string(),
1028 );
1029 push_row(out, "framing", &body.estimates.framing.to_string());
1030 push_row(
1031 out,
1032 "total (conservative)",
1033 &format!("~{}", body.estimates.total_conservative),
1034 );
1035 push_row(
1036 out,
1037 "input budget ceiling",
1038 &body
1039 .input_budget_ceiling_tokens
1040 .map_or_else(|| "unknown".to_string(), |ceiling| ceiling.to_string()),
1041 );
1042 push_row(
1043 out,
1044 "headroom (input budget)",
1045 &body.estimated_input_headroom_tokens.map_or_else(
1046 || "unknown".to_string(),
1047 |headroom| {
1048 format!("~{headroom} (production estimate; window minus output reservation)")
1049 },
1050 ),
1051 );
1052 push_row(
1053 out,
1054 "output cap (wire)",
1055 &body
1056 .wire_output_cap_tokens
1057 .map_or_else(|| "unknown".to_string(), |cap| cap.to_string()),
1058 );
1059 push_row(
1060 out,
1061 "provider-reported usage",
1062 UnavailableReason::ProviderRequestNotExecuted.label(),
1063 );
1064
1065 out.push_str("\nHashes\n");
1066 push_row(out, "whole body", &body.body_sha256);
1067 push_row(
1068 out,
1069 "wire tool schemas",
1070 body.tool_schema_wire_sha256
1071 .as_deref()
1072 .unwrap_or("no tools on this request"),
1073 );
1074 push_row(
1075 out,
1076 "local system + tools component",
1077 body.local_system_tools_component_sha256
1078 .as_deref()
1079 .unwrap_or("unavailable — tool surface is not exactly known"),
1080 );
1081 }
1082 }
1083
1084 impl TokenEstimates {
1085 fn from_view(view: &crate::client::WireBodyView<'_>) -> Self {
1086 // The classes partition the body exactly, so the total is taken over
1087 // the body itself rather than summed from four independently rounded
1088 // per-class estimates.
1089 Self {
1090 system: estimate_bytes(view.system_bytes),
1091 tool_schemas: estimate_bytes(view.tool_schema_bytes),
1092 messages: estimate_bytes(view.item_bytes),
1093 // Tool results and attachments are *subsets* of the message bytes,
1094 // reported for attribution and deliberately not added again.
1095 tool_results: estimate_bytes(view.tool_result_bytes),
1096 attachments: estimate_bytes(view.attachment_bytes),
1097 framing: estimate_bytes(view.framing_bytes),
1098 total_conservative: conservative_token_estimate(view.body_bytes),
1099 }
1100 }
1101 }
1102
1103 fn push_row(out: &mut String, label: &str, value: &str) {
1104 out.push_str(&format!(" {label:<30} {value}\n"));
1105 }
1106
1107 fn push_unavailable(out: &mut String, unavailable: &Unavailable) {
1108 push_row(out, "unavailable", unavailable.reason.label());
1109 if let Some(detail) = &unavailable.detail {
1110 push_row(out, " detail", detail);
1111 }
1112 }
1113
1114 fn count_label(count: Option<usize>) -> String {
1115 count.map_or_else(|| "none".to_string(), |count| count.to_string())
1116 }
1117
1118 fn estimate_bytes(bytes: usize) -> usize {
1119 bytes.div_ceil(BYTES_PER_TOKEN)
1120 }
1121
1122 /// The offline input-token estimate this manifest publishes, for `bytes` of
1123 /// wire body.
1124 ///
1125 /// This is an independent provider-body observability estimate. Production's
1126 /// overflow decision and the manifest's headroom deliberately use
1127 /// `compaction::estimate_input_tokens_conservative(messages, system)` instead.
1128 pub fn conservative_token_estimate(bytes: usize) -> usize {
1129 let whole = estimate_bytes(bytes);
1130 whole.saturating_add(whole * ESTIMATE_MARGIN_PERCENT / 100)
1131 }
1132
1133 /// Short shape label for a wire `tool_choice` value.
1134 ///
1135 /// Structural only, and bounded: the forced-function *name* is a tool name,
1136 /// which is safe, but it still crosses the safe-label boundary because a
1137 /// provider-shaped body can carry anything under that key.
1138 pub fn tool_choice_label(value: Option<&serde_json::Value>) -> Option<SafeLabel> {
1139 let value = value?;
1140 if let Some(text) = value.as_str() {
1141 return Some(SafeLabel::identifier(text));
1142 }
1143 let kind = value
1144 .get("type")
1145 .and_then(serde_json::Value::as_str)
1146 .unwrap_or("object");
1147 match value
1148 .pointer("/function/name")
1149 .and_then(serde_json::Value::as_str)
1150 {
1151 Some(name) => Some(SafeLabel::identifier(&format!("{kind}:{name}"))),
1152 None => Some(SafeLabel::identifier(kind)),
1153 }
1154 }
1155
1156 #[cfg(any(test, feature = "test-support"))]
1157 pub mod test_support {
1158 use super::*;
1159
1160 pub fn session() -> SessionFacts {
1161 SessionFacts {
1162 agent_role: "primary".to_string(),
1163 lane_kind: "interactive-primary".to_string(),
1164 fleet_assignment: "not-applicable-primary-agent".to_string(),
1165 requested_model: SafeLabel::identifier("glm-5.2"),
1166 auto_model_routing: false,
1167 requested_reasoning: SafeLabel::identifier("high"),
1168 hypothetical_prompt_supplied: true,
1169 mode: "Agent".to_string(),
1170 approval_mode: "Prompt".to_string(),
1171 allowed_tool_gate_count: None,
1172 disallowed_tool_gate_count: None,
1173 base_prompt: BasePromptProvenance {
1174 origin: crate::prompts::BasePromptOrigin::Bundled
1175 .label()
1176 .to_string(),
1177 bytes: 11,
1178 sha256: codewhale_runtime::hashing::sha256_hex(b"BASE PROMPT"),
1179 },
1180 }
1181 }
1182
1183 pub fn route() -> RouteFacts {
1184 RouteFacts {
1185 provider_id: SafeLabel::identifier("zhipu"),
1186 provider_display: SafeLabel::identifier("Z.ai"),
1187 route_id: Some(SafeLabel::identifier("my-gateway")),
1188 dialect: "chat-completions".to_string(),
1189 responses_profile_id: None,
1190 route_shape: "standard".to_string(),
1191 endpoint_host_class: "https remote sha256:0123456789ab".to_string(),
1192 endpoint_fingerprint: codewhale_runtime::hashing::sha256_hex(b"endpoint"),
1193 wire_model: SafeLabel::identifier("glm-5.2"),
1194 caller_entrypoint: "streaming".to_string(),
1195 body_stream_field: Some(true),
1196 context_limit_tokens: 200_000,
1197 context_limit_source: crate::route_runtime::ContextWindowSource::Catalog,
1198 route_input_limit_tokens: Some(180_000),
1199 route_output_limit_tokens: Some(20_000),
1200 billing: BillingFacts::Metered,
1201 routing_source: "active-fixed-route".to_string(),
1202 auto_route_source: None,
1203 }
1204 }
1205
1206 pub fn tools() -> ToolSurfaceFacts {
1207 ToolSurfaceFacts {
1208 catalog_tool_count: 4,
1209 deferred_tool_count: 2,
1210 active_tool_count: 2,
1211 active_tool_catalog_sha256: codewhale_runtime::hashing::sha256_hex(b"tools"),
1212 tool_surface_budget: "Standard".to_string(),
1213 standard_and_full_surfaces_collapsed: true,
1214 mcp_server_count: 0,
1215 mcp_tool_count: 0,
1216 }
1217 }
1218
1219 pub fn prompt() -> PromptProvenance {
1220 PromptProvenance {
1221 assembly: SystemPromptAssembly::BaseOnly,
1222 effective_system_canonical_json_bytes: 11,
1223 effective_system_sha256: codewhale_runtime::hashing::sha256_hex(b"BASE PROMPT"),
1224 }
1225 }
1226 }
1227
1228 #[cfg(test)]
1229 mod tests {
1230 use super::test_support::{prompt, route, session, tools};
1231 use super::*;
1232 use crate::client::{CallerStreamMode, EndpointIdentity, RouteShape, WireDialect};
1233 use serde_json::json;
1234
1235 fn endpoint(url: &str) -> EndpointIdentity {
1236 EndpointIdentity {
1237 provider_id: "zhipu".to_string(),
1238 provider_display: "Z.ai".to_string(),
1239 route_id: Some("my-gateway".to_string()),
1240 url: url.to_string(),
1241 shape: RouteShape::Standard,
1242 }
1243 }
1244
1245 fn chat_body() -> serde_json::Value {
1246 json!({
1247 "model": "glm-5.2",
1248 "messages": [
1249 {"role": "system", "content": "SECRET SYSTEM PROMPT"},
1250 {"role": "user", "content": "SECRET USER MESSAGE"},
1251 {"role": "tool", "tool_call_id": "c1", "content": "SECRET TOOL OUTPUT"},
1252 ],
1253 "tools": [{"type": "function", "function": {"name": "read_file"}}],
1254 "tool_choice": {"type": "auto"},
1255 "max_tokens": 4096,
1256 "reasoning_effort": "high",
1257 "stream": true,
1258 })
1259 }
1260
1261 fn prepared_chat(body: serde_json::Value) -> PreparedOutboundRequest {
1262 let fixture_url = format!(
1263 "https://user:{}@api.z.ai:8443/api/paas/v4/chat/completions?api_key={}{}",
1264 "hunter2", "sk", "-fixture-not-a-real-key-00000000"
1265 );
1266 PreparedOutboundRequest::new(
1267 WireDialect::ChatCompletions,
1268 endpoint(&fixture_url),
1269 "glm-5.2".to_string(),
1270 body,
1271 Some("high".to_string()),
1272 None,
1273 CallerStreamMode::Streaming,
1274 )
1275 }
1276
1277 /// A stand-in for this route's production input-budget ceiling. Real
1278 /// values come from `context_input_budget_for_route`.
1279 const INPUT_BUDGET_CEILING: usize = 150_000;
1280 const PRODUCTION_INPUT_ESTIMATE: usize = 42_000;
1281
1282 fn manifest_from(prepared: &PreparedOutboundRequest) -> RequestManifest {
1283 RequestManifest::build(ManifestDraft {
1284 session: session(),
1285 route: Availability::Exact(route()),
1286 tools: Availability::Exact(tools()),
1287 body: Availability::Exact(PreparedBodyInputs {
1288 prepared,
1289 reasoning_resolution: ReasoningResolution::Explicit,
1290 prompt: prompt(),
1291 input_budget_ceiling_tokens: Some(INPUT_BUDGET_CEILING),
1292 production_input_estimate_tokens: PRODUCTION_INPUT_ESTIMATE,
1293 tool_surface_is_exact: true,
1294 }),
1295 })
1296 }
1297
1298 fn manifest(body: serde_json::Value) -> RequestManifest {
1299 let prepared = prepared_chat(body);
1300 manifest_from(&prepared)
1301 }
1302
1303 fn body_facts(manifest: &RequestManifest) -> &BodyFacts {
1304 manifest
1305 .body
1306 .exact()
1307 .expect("body is exact in this fixture")
1308 }
1309
1310 #[test]
1311 fn manifest_reports_typed_counts_and_hashes() {
1312 let manifest = manifest(chat_body());
1313 assert_eq!(manifest.schema_version, MANIFEST_SCHEMA_VERSION);
1314 let route = manifest.route.exact().expect("route is exact");
1315 assert_eq!(route.dialect, "chat-completions");
1316 assert_eq!(route.routing_source, "active-fixed-route");
1317 assert_eq!(manifest.session.agent_role, "primary");
1318 assert_eq!(manifest.session.lane_kind, "interactive-primary");
1319 assert_eq!(
1320 manifest.session.fleet_assignment,
1321 "not-applicable-primary-agent"
1322 );
1323 assert_eq!(route.context_limit_tokens, 200_000);
1324 assert_eq!(
1325 route.context_limit_source,
1326 crate::route_runtime::ContextWindowSource::Catalog
1327 );
1328 assert_eq!(
1329 route.route_id.as_ref().map(SafeLabel::as_str),
1330 Some("my-gateway")
1331 );
1332 let body = body_facts(&manifest);
1333 assert_eq!(body.message_count, 2, "system message is not a message");
1334 assert!(body.tool_result_canonical_json_bytes > 0);
1335 assert_eq!(body.body_sha256.len(), 64);
1336 assert_eq!(body.input_budget_ceiling_tokens, Some(INPUT_BUDGET_CEILING));
1337 assert_eq!(body.wire_output_cap_tokens, Some(4_096));
1338 assert!(matches!(
1339 &body.provider_reported_usage,
1340 Availability::Unavailable(Unavailable {
1341 reason: UnavailableReason::ProviderRequestNotExecuted,
1342 ..
1343 })
1344 ));
1345 assert_eq!(
1346 body.local_system_tools_component_sha256
1347 .as_deref()
1348 .map(str::len),
1349 Some(64)
1350 );
1351 }
1352
1353 #[test]
1354 fn explicit_base_prompt_preview_is_exact_and_base_only() {
1355 assert_eq!(
1356 exact_base_prompt_only().as_bytes(),
1357 crate::prompts::effective_base_prompt_text().as_bytes()
1358 );
1359 }
1360
1361 #[test]
1362 fn no_prompt_message_secret_or_path_reaches_any_surface() {
1363 let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string());
1364 let mut body = chat_body();
1365 body["messages"][1]["content"] = json!(format!("look at {home}/.codewhale/config.toml"));
1366 let manifest = manifest(body);
1367
1368 for surface in [
1369 manifest.render(),
1370 manifest.to_json(),
1371 format!("{manifest:?}"),
1372 ] {
1373 for forbidden in [
1374 "SECRET SYSTEM PROMPT",
1375 "SECRET USER MESSAGE",
1376 "SECRET TOOL OUTPUT",
1377 "hunter2",
1378 "sk-abcdef0123456789",
1379 "api_key=",
1380 "/api/paas/v4/chat/completions",
1381 ] {
1382 assert!(
1383 !surface.contains(forbidden),
1384 "`{forbidden}` leaked into a manifest surface:\n{surface}"
1385 );
1386 }
1387 assert!(!surface.contains(&home), "home path leaked:\n{surface}");
1388 }
1389 }
1390
1391 #[test]
1392 fn hostile_route_and_model_identifiers_are_bounded_on_both_surfaces() {
1393 // A custom route id and a wire model are user-authored text: they can
1394 // be absolute paths, URLs, or deployment secrets.
1395 let mut route = route();
1396 route.route_id = Some(SafeLabel::identifier(
1397 "https://internal.example.com/v1/deployments/prod-key-8f2a",
1398 ));
1399 route.provider_id = SafeLabel::identifier("openai/secrets/config");
1400 route.wire_model = SafeLabel::catalog_model("qwen/src/lib.rs");
1401 route.provider_display = SafeLabel::identifier("sk-live-abcdef0123456789abcdef");
1402
1403 let manifest = RequestManifest::build(ManifestDraft {
1404 session: session(),
1405 route: Availability::Exact(route),
1406 tools: Availability::Exact(tools()),
1407 body: Availability::unavailable(UnavailableReason::NoHypotheticalPromptSupplied),
1408 });
1409
1410 for surface in [manifest.render(), manifest.to_json()] {
1411 for forbidden in [
1412 "internal.example.com",
1413 "deployments/prod-key-8f2a",
1414 "openai/secrets/config",
1415 "qwen/src/lib.rs",
1416 "sk-live-",
1417 ] {
1418 assert!(
1419 !surface.contains(forbidden),
1420 "`{forbidden}` leaked into a manifest surface:\n{surface}"
1421 );
1422 }
1423 assert!(surface.contains("sha256:"), "{surface}");
1424 }
1425 }
1426
1427 #[test]
1428 fn unresolved_auto_publishes_no_route_tool_or_body_facts() {
1429 let mut session = session();
1430 session.requested_model = SafeLabel::identifier("auto");
1431 session.auto_model_routing = true;
1432 session.hypothetical_prompt_supplied = false;
1433 session.requested_reasoning = SafeLabel::identifier("auto");
1434
1435 let manifest = RequestManifest::build(ManifestDraft {
1436 session,
1437 route: Availability::unavailable(UnavailableReason::AutoRouteUnresolvedUntilNextPrompt),
1438 tools: Availability::unavailable(UnavailableReason::AutoRouteUnresolvedUntilNextPrompt),
1439 body: Availability::unavailable(UnavailableReason::AutoRouteUnresolvedUntilNextPrompt),
1440 });
1441
1442 let json = manifest.to_json();
1443 for forbidden in [
1444 "provider_id",
1445 "route_id",
1446 "dialect",
1447 "endpoint_host",
1448 "endpoint_fingerprint",
1449 "wire_model",
1450 "billing",
1451 "tool_surface_budget",
1452 "body_sha256",
1453 ] {
1454 assert!(
1455 !json.contains(forbidden),
1456 "`{forbidden}` must not appear when auto routing is unresolved:\n{json}"
1457 );
1458 }
1459 assert!(
1460 json.contains("auto-route-unresolved-until-next-prompt"),
1461 "{json}"
1462 );
1463 assert_eq!(manifest.session.requested_model.as_str(), "auto");
1464
1465 let rendered = manifest.render();
1466 assert!(
1467 rendered.contains("auto model routing is unresolved until the next prompt"),
1468 "{rendered}"
1469 );
1470 assert!(rendered.contains("preview never runs"), "{rendered}");
1471 assert!(rendered.contains("Select a fixed route"), "{rendered}");
1472 }
1473
1474 #[test]
1475 fn prompted_auto_reports_the_offline_classifier_boundary() {
1476 let mut session = session();
1477 session.requested_model = SafeLabel::identifier("auto");
1478 session.auto_model_routing = true;
1479 session.hypothetical_prompt_supplied = true;
1480 let reason = UnavailableReason::AutoRouteClassificationNotExecuted;
1481 let manifest = RequestManifest::build(ManifestDraft {
1482 session,
1483 route: Availability::unavailable(reason),
1484 tools: Availability::unavailable(reason),
1485 body: Availability::unavailable(reason),
1486 });
1487
1488 let json = manifest.to_json();
1489 assert!(
1490 json.contains("auto-route-classification-not-executed"),
1491 "{json}"
1492 );
1493 for forbidden in [
1494 "provider_id",
1495 "endpoint_host_class",
1496 "wire_model",
1497 "body_sha256",
1498 ] {
1499 assert!(!json.contains(forbidden), "{forbidden} leaked:\n{json}");
1500 }
1501 assert!(manifest.render().contains("preview is offline"));
1502 }
1503
1504 #[test]
1505 fn repeated_previews_are_byte_stable() {
1506 let first = manifest(chat_body());
1507 let second = manifest(chat_body());
1508 assert_eq!(first, second);
1509 assert_eq!(first.to_json(), second.to_json());
1510 }
1511
1512 #[test]
1513 fn body_hash_moves_for_every_wire_mutation() {
1514 type BodyMutation = (&'static str, Box<dyn Fn(&mut serde_json::Value)>);
1515
1516 let baseline = body_facts(&manifest(chat_body())).body_sha256.clone();
1517 let mutations: Vec<BodyMutation> = vec![
1518 (
1519 "max_tokens",
1520 Box::new(|b: &mut serde_json::Value| b["max_tokens"] = json!(1024)),
1521 ),
1522 (
1523 "tool_choice",
1524 Box::new(|b: &mut serde_json::Value| b["tool_choice"] = json!("required")),
1525 ),
1526 (
1527 "nested reasoning control",
1528 Box::new(|b: &mut serde_json::Value| {
1529 b["thinking"] = json!({"type": "enabled", "effort": "max"});
1530 }),
1531 ),
1532 (
1533 "transformed tool schema",
1534 Box::new(|b: &mut serde_json::Value| {
1535 b["tools"][0]["function"]["parameters"] = json!({"type": "object"});
1536 }),
1537 ),
1538 (
1539 "attachment",
1540 Box::new(|b: &mut serde_json::Value| {
1541 b["messages"].as_array_mut().unwrap().push(json!({
1542 "role": "user",
1543 "content": [{"type": "image_url", "image_url": {"url": "data:x"}}],
1544 }));
1545 }),
1546 ),
1547 (
1548 "stream options",
1549 Box::new(|b: &mut serde_json::Value| {
1550 b["stream_options"] = json!({"include_usage": true});
1551 }),
1552 ),
1553 (
1554 "appended user message",
1555 Box::new(|b: &mut serde_json::Value| {
1556 b["messages"].as_array_mut().unwrap().push(json!({
1557 "role": "user",
1558 "content": "the hypothetical next prompt",
1559 }));
1560 }),
1561 ),
1562 ];
1563 for (what, mutate) in mutations {
1564 let mut body = chat_body();
1565 mutate(&mut body);
1566 assert_ne!(
1567 baseline,
1568 body_facts(&manifest(body)).body_sha256,
1569 "changing {what} must change the whole-body hash"
1570 );
1571 }
1572 }
1573
1574 #[test]
1575 fn manifest_is_not_a_request_body_export() {
1576 // The inspectability slice must never become a way to dump the wire
1577 // body: no field may reproduce request-body content keys. Human-safe
1578 // explanatory strings may still use words such as `messages`.
1579 fn contains_request_content(value: &serde_json::Value) -> bool {
1580 match value {
1581 serde_json::Value::Object(object) => object.iter().any(|(key, value)| {
1582 (key == "messages" && value.is_array())
1583 || matches!(key.as_str(), "content" | "input_schema")
1584 || contains_request_content(value)
1585 }),
1586 serde_json::Value::Array(values) => values.iter().any(contains_request_content),
1587 _ => false,
1588 }
1589 }
1590
1591 let json = manifest(chat_body()).to_json();
1592 let value: serde_json::Value = serde_json::from_str(&json).expect("valid manifest JSON");
1593 assert!(!contains_request_content(&value), "{json}");
1594 }
1595
1596 #[test]
1597 fn collapsed_tool_surfaces_are_disclosed_not_asserted_away() {
1598 let collapsed = manifest(chat_body());
1599 assert!(
1600 collapsed
1601 .tools
1602 .exact()
1603 .expect("tools exact")
1604 .standard_and_full_surfaces_collapsed
1605 );
1606 assert!(collapsed.render().contains("collapsed — both budgets"));
1607
1608 let mut distinct_tools = tools();
1609 distinct_tools.standard_and_full_surfaces_collapsed = false;
1610 let prepared = prepared_chat(chat_body());
1611 let distinct = RequestManifest::build(ManifestDraft {
1612 session: session(),
1613 route: Availability::Exact(route()),
1614 tools: Availability::Exact(distinct_tools),
1615 body: Availability::Exact(PreparedBodyInputs {
1616 prepared: &prepared,
1617 reasoning_resolution: ReasoningResolution::Explicit,
1618 prompt: prompt(),
1619 input_budget_ceiling_tokens: Some(INPUT_BUDGET_CEILING),
1620 production_input_estimate_tokens: PRODUCTION_INPUT_ESTIMATE,
1621 tool_surface_is_exact: false,
1622 }),
1623 });
1624 assert!(distinct.render().contains("distinct — the budgets"));
1625 assert!(
1626 body_facts(&distinct)
1627 .local_system_tools_component_sha256
1628 .is_none(),
1629 "no local component hash without an exact tool catalog"
1630 );
1631 }
1632
1633 #[test]
1634 fn estimates_do_not_double_count_subsets() {
1635 let manifest = manifest(chat_body());
1636 let body = body_facts(&manifest);
1637 assert!(
1638 body.estimates.tool_results <= body.estimates.messages,
1639 "tool results are a subset of message bytes"
1640 );
1641 assert!(
1642 body.estimates.attachments <= body.estimates.messages,
1643 "attachments are a subset of message bytes"
1644 );
1645 assert!(manifest.render().contains("not provider-counted"));
1646 }
1647
1648 /// The reviewed defect: the published byte classes counted selected values
1649 /// and omitted JSON key names, brackets, and separators, so they summed to
1650 /// less than the request. They are exact facts, so they must partition the
1651 /// body they describe.
1652 #[test]
1653 fn published_byte_classes_partition_the_whole_body() {
1654 for body in [
1655 chat_body(),
1656 json!({"model": "m", "messages": []}),
1657 json!({
1658 "model": "m",
1659 "messages": [{"role": "user", "content": "hi"}],
1660 "max_tokens": 32,
1661 }),
1662 ] {
1663 let manifest = manifest(body);
1664 let facts = body_facts(&manifest);
1665 assert_eq!(
1666 facts.system_canonical_json_bytes
1667 + facts.tool_schema_canonical_json_bytes
1668 + facts.message_canonical_json_bytes
1669 + facts.framing_canonical_json_bytes,
1670 facts.body_canonical_json_bytes,
1671 "classes must sum to the wire body:\n{}",
1672 manifest.render()
1673 );
1674 }
1675 }
1676
1677 /// Headroom is measured against the production input budget, not the raw
1678 /// context window: the window has to hold the response too.
1679 #[test]
1680 fn headroom_comes_from_the_input_budget_not_the_context_window() {
1681 let manifest = manifest(chat_body());
1682 let body = body_facts(&manifest);
1683 assert_eq!(
1684 body.estimated_input_headroom_tokens,
1685 Some(INPUT_BUDGET_CEILING as i64 - PRODUCTION_INPUT_ESTIMATE as i64)
1686 );
1687 assert_ne!(
1688 body.estimated_input_headroom_tokens,
1689 Some(INPUT_BUDGET_CEILING as i64 - body.estimates.total_conservative as i64),
1690 "the independent wire estimate must not drive production headroom"
1691 );
1692 assert_ne!(
1693 body.estimated_input_headroom_tokens,
1694 Some(200_000 - PRODUCTION_INPUT_ESTIMATE as i64),
1695 "the route's context limit is not the input budget"
1696 );
1697 assert!(
1698 manifest
1699 .render()
1700 .contains("window minus output reservation"),
1701 "{}",
1702 manifest.render()
1703 );
1704 }
1705
1706 /// A request over budget reports negative headroom rather than clamping to
1707 /// zero and reading as "it fits".
1708 #[test]
1709 fn headroom_goes_negative_when_the_request_would_not_fit() {
1710 let prepared = prepared_chat(chat_body());
1711 let manifest = RequestManifest::build(ManifestDraft {
1712 session: session(),
1713 route: Availability::Exact(route()),
1714 tools: Availability::Exact(tools()),
1715 body: Availability::Exact(PreparedBodyInputs {
1716 prepared: &prepared,
1717 reasoning_resolution: ReasoningResolution::Explicit,
1718 prompt: prompt(),
1719 input_budget_ceiling_tokens: Some(1),
1720 production_input_estimate_tokens: PRODUCTION_INPUT_ESTIMATE,
1721 tool_surface_is_exact: true,
1722 }),
1723 });
1724 assert!(
1725 body_facts(&manifest)
1726 .estimated_input_headroom_tokens
1727 .is_some_and(|headroom| headroom < 0)
1728 );
1729 }
1730
1731 /// The local component identity follows final wire-shaped schemas even
1732 /// when the logical catalog is untouched.
1733 #[test]
1734 fn local_system_tools_component_follows_wire_regions() {
1735 let baseline = manifest(chat_body());
1736 let baseline_component = body_facts(&baseline)
1737 .local_system_tools_component_sha256
1738 .clone();
1739 let baseline_tools = body_facts(&baseline).tool_schema_wire_sha256.clone();
1740 assert!(baseline_component.is_some());
1741
1742 let mut shaped = chat_body();
1743 shaped["tools"][0]["function"]["parameters"] =
1744 json!({"type": "object", "additionalProperties": false});
1745 shaped["tools"][0]["function"]["strict"] = json!(true);
1746 let shaped = manifest(shaped);
1747 assert_ne!(
1748 baseline_tools,
1749 body_facts(&shaped).tool_schema_wire_sha256,
1750 "a shaped schema must move the wire tool hash"
1751 );
1752 assert_ne!(
1753 baseline_component,
1754 body_facts(&shaped).local_system_tools_component_sha256,
1755 "a shaped schema must move the local system/tools component"
1756 );
1757
1758 // …and the system region moves it too.
1759 let mut other_system = chat_body();
1760 other_system["messages"][0]["content"] = json!("A DIFFERENT SYSTEM PROMPT");
1761 assert_ne!(
1762 baseline_component,
1763 body_facts(&manifest(other_system)).local_system_tools_component_sha256
1764 );
1765 }
1766
1767 #[test]
1768 fn nested_reasoning_effort_is_reported_with_its_key_path() {
1769 let mut body = chat_body();
1770 body.as_object_mut()
1771 .expect("object")
1772 .remove("reasoning_effort");
1773 body["thinking"] = json!({"type": "enabled", "effort": "max"});
1774 let manifest = manifest(body);
1775 let facts = body_facts(&manifest);
1776 assert_eq!(
1777 facts.reasoning_wire_effort.as_ref().map(SafeLabel::as_str),
1778 Some("max")
1779 );
1780 assert_eq!(
1781 facts.reasoning_wire_effort_source.as_deref(),
1782 Some("thinking.effort")
1783 );
1784 assert!(manifest.render().contains("max (from `thinking.effort`)"));
1785 }
1786
1787 /// A body with no reasoning request must not read as an explicit user
1788 /// selection just because the caller happened to pass `Explicit`.
1789 #[test]
1790 fn route_default_and_not_applicable_are_distinguishable_labels() {
1791 assert_eq!(
1792 ReasoningResolution::RouteDefault.label(),
1793 "route default (no user selection)"
1794 );
1795 assert_ne!(
1796 ReasoningResolution::RouteDefault.label(),
1797 ReasoningResolution::Explicit.label()
1798 );
1799 }
1800
1801 /// A section that depends on an unavailable section inherits its typed
1802 /// reason instead of quietly becoming exact.
1803 #[test]
1804 fn unavailability_propagates_to_dependent_sections() {
1805 let unavailable_tools: Availability<ToolSurfaceFacts> =
1806 Availability::unavailable(UnavailableReason::McpStateNotSnapshottable);
1807 let body: Availability<BodyFacts> = unavailable_tools.propagate().expect("propagates");
1808 assert!(body.exact().is_none());
1809 assert!(
1810 Availability::Exact(tools())
1811 .propagate::<BodyFacts>()
1812 .is_none(),
1813 "an exact section propagates nothing"
1814 );
1815 }
1816
1817 #[test]
1818 fn scope_exclusions_are_stated_on_the_human_surface() {
1819 let rendered = manifest(chat_body()).render();
1820 assert!(rendered.contains("primary agent turn"), "{rendered}");
1821 assert!(rendered.contains("auxiliary"), "{rendered}");
1822 }
1823
1824 #[test]
1825 fn tool_choice_labels_are_short_shapes() {
1826 assert_eq!(tool_choice_label(None), None);
1827 assert_eq!(
1828 tool_choice_label(Some(&json!("required")))
1829 .as_ref()
1830 .map(SafeLabel::as_str),
1831 Some("required")
1832 );
1833 assert_eq!(
1834 tool_choice_label(Some(&json!({"type": "auto"})))
1835 .as_ref()
1836 .map(SafeLabel::as_str),
1837 Some("auto")
1838 );
1839 assert_eq!(
1840 tool_choice_label(Some(&json!({
1841 "type": "function",
1842 "function": {"name": "read_file"}
1843 })))
1844 .as_ref()
1845 .map(SafeLabel::as_str),
1846 Some("function:read_file")
1847 );
1848 }
1849
1850 /// The manifest consumes provider wire truth, never the logical
1851 /// `MessageRequest.tool_choice`. These are the three reviewed divergences:
1852 /// Anthropic keeps an object, Responses maps it to a string, and DeepSeek
1853 /// thinking omits the field.
1854 #[test]
1855 fn manifest_tool_choice_is_read_from_the_final_provider_body() {
1856 for (dialect, body, expected) in [
1857 (
1858 WireDialect::AnthropicMessages,
1859 json!({
1860 "model": "claude-sonnet-4-6",
1861 "messages": [],
1862 "tool_choice": {"type": "auto"}
1863 }),
1864 Some("auto"),
1865 ),
1866 (
1867 WireDialect::OpenAiResponses,
1868 json!({
1869 "model": "gpt-5-codex",
1870 "input": [],
1871 "tool_choice": "auto"
1872 }),
1873 Some("auto"),
1874 ),
1875 (
1876 WireDialect::ChatCompletions,
1877 json!({
1878 "model": "deepseek-reasoner",
1879 "messages": [],
1880 "reasoning_effort": "high"
1881 }),
1882 None,
1883 ),
1884 ] {
1885 let prepared = PreparedOutboundRequest::new(
1886 dialect,
1887 endpoint("https://api.example.com/v1/messages"),
1888 "wire-model".to_string(),
1889 body,
1890 Some("high".to_string()),
1891 None,
1892 CallerStreamMode::Streaming,
1893 );
1894 assert_eq!(
1895 body_facts(&manifest_from(&prepared))
1896 .tool_choice
1897 .as_ref()
1898 .map(SafeLabel::as_str),
1899 expected,
1900 "{dialect:?}"
1901 );
1902 }
1903 }
1904 }
1905
1905 lines RUST