返回 CodeWhale
preview.rs
根目录 / crates / engine / src / core / engine / preview.rs
1 //! Engine-side authority for `/preview-request` (#1004, #3928).
2 //!
3 //! The preview lives here — not in the command layer — because only the
4 //! engine can rebuild the *exact* next-turn state: the tool catalog under the
5 //! live mode, gates, permission posture and connected MCP tools; the system
6 //! prompt for the route the next turn would use; the hypothetical next user
7 //! message in its production form; and the request the turn loop would hand
8 //! to `create_message_stream`.
9 //!
10 //! Four rules this module exists to enforce:
11 //!
12 //! - **Never `session.last_tool_catalog`.** That value is one turn stale and
13 //! stores the pre-activation catalog, so it cannot describe what the *next*
14 //! request would send. The catalog is rebuilt through
15 //! [`Engine::build_turn_tool_registry_and_catalog`], which returns the same
16 //! typed policy a real turn consumes.
17 //! - **Never invent a route.** For fixed routes, the host resolves the next
18 //! turn through the same shared planner production dispatch uses. Auto would
19 //! require a model-classifier call, so the human preview stops before the
20 //! planner and emits a typed unavailable state. No route, endpoint, wire
21 //! model, billing, tool budget, or body hash is recycled from the installed
22 //! route.
23 //! - **Never resolve by side effect.** The catalog build runs with
24 //! [`SubAgentWiring::Inert`] and [`McpAccess::PassiveSnapshot`]: no fork
25 //! snapshot, no spawned drainer, no MCP pool creation, no `connect_all`, no
26 //! status events. When the connected MCP state is not already exactly what
27 //! a turn would use, the tool section is reported unavailable rather than
28 //! made exact by connecting — **and so is the body**, because a body built
29 //! from a tool surface missing its MCP contribution is a body no turn would
30 //! send.
31 //! - **Never install anything, not even briefly.** The planned route is
32 //! projected into a throw-away client; `self.api_provider`,
33 //! `self.session.model`, `self.session.system_prompt`, and the MCP pool are
34 //! all left untouched. Everything a turn would *install before* building its
35 //! request — the command-scoped tool gate, the effective mode and approval
36 //! posture, the policy-narrowing event, the observed working set — is passed
37 //! as a value or snapshotted onto a clone. The git-metadata cache is saved
38 //! and restored around synchronous message construction; no `.await` occurs
39 //! while the hypothetical value is installed.
40 //! - **Never claim exactness the runtime would break.** Mutable
41 //! `message_submit` hooks, background-shell completions, running or
42 //! terminal-undelivered sub-agent completions,
43 //! pending LSP diagnostics, auto-compaction, and context-overflow recovery
44 //! all rewrite the request between submit and the wire. An inspection may
45 //! neither run them nor consume them, so when any of them apply the affected
46 //! sections are typed unavailable instead of published.
47 //!
48 //! Scope: this describes the primary agent turn (`create_message_stream`).
49 //! Auxiliary provider calls are out of scope; see `docs/PREVIEW_REQUEST.md`.
50 //!
51 //! The `dryrun` concept — preview the next request from the real
52 //! request-building seam rather than a hand-rolled summary — is harvested
53 //! from PR #1099 by TaoMu (GTC2080).
54
55 use super::*;
56
57 use crate::client::PreparedOutboundRequest;
58 use crate::compaction::should_compact;
59 use crate::request_manifest::{
60 Availability, BasePromptProvenance, BillingFacts, ManifestDraft, PreparedBodyInputs,
61 PromptProvenance, ReasoningResolution, RequestManifest, RouteFacts, SessionFacts,
62 SystemPromptAssembly, ToolSurfaceFacts, UnavailableReason,
63 };
64 use crate::route_runtime::ResolvedRuntimeRoute;
65 use codewhale_core::request::{PrimaryTurnRequest, prepare_primary_turn_request};
66 use codewhale_runtime::safe_label::SafeLabel;
67
68 /// Everything the host must supply for the engine to describe the next
69 /// request. These are the same posture fields a `SendMessage` would carry, so
70 /// the preview describes the turn the user is actually about to run.
71 #[derive(Debug)]
72 pub struct PreviewRequestInputs {
73 pub mode: AppMode,
74 pub allow_shell: bool,
75 pub trust_mode: bool,
76 pub auto_approve: bool,
77 pub approval_mode: ApprovalMode,
78 pub allowed_tools: Option<Vec<String>>,
79 pub dynamic_tools: Vec<DynamicToolSpec>,
80 pub provenance: UserInputProvenance,
81 /// The model selector the user chose: `auto` when auto model routing is
82 /// on. Never the concrete model an unresolved auto route might pick.
83 pub requested_model: String,
84 /// Reasoning tier the user has selected (`auto`, `high`, `off`, …).
85 pub requested_reasoning: String,
86 pub auto_model: bool,
87 /// Whether the *caller* supplied a hypothetical next prompt.
88 ///
89 /// Deliberately independent of [`Self::next_turn`]: when planning that
90 /// prompt fails, the manifest must still say a prompt was supplied.
91 /// Deriving the flag from `next_turn.is_some()` told the user to "pass
92 /// `--prompt`" when they just had.
93 pub hypothetical_prompt_supplied: bool,
94 /// The exact next turn, resolved by the host's shared route planner.
95 /// `None` means no exact next turn exists to describe.
96 pub next_turn: Option<Box<PreviewNextTurn>>,
97 /// Why `next_turn` is absent. Ignored when `next_turn` is present.
98 pub unresolved: PreviewUnresolved,
99 }
100
101 /// One hypothetical next turn, planned by the production route planner.
102 #[derive(Debug)]
103 pub struct PreviewNextTurn {
104 /// The model-facing text of the hypothetical user message, already
105 /// through the host's file-mention/skill resolution — the same string a
106 /// real `SendMessage` would carry. Never stored in the session and never
107 /// sent to a provider.
108 pub content: String,
109 /// The route the planner resolved for this turn.
110 pub route: Box<ResolvedRuntimeRoute>,
111 /// Immutable prompt facts captured from the same host state as the
112 /// matching production submit.
113 pub prompt_context: NextTurnPromptContext,
114 /// Normalized reasoning-effort api value from the planner, exactly as it
115 /// would be sent.
116 pub reasoning_effort: Option<String>,
117 /// True when the user selected auto reasoning and the planner picked that
118 /// tier.
119 pub reasoning_effort_auto: bool,
120 /// How the auto router chose this route, when auto routing ran.
121 pub auto_route_source: Option<String>,
122 /// Typed selection provenance captured by the shared production planner.
123 pub routing_source: crate::turn_route_plan::TurnRoutingSource,
124 /// The compaction policy the planner resolved for this route. A real turn
125 /// installs it before the turn loop decides whether to auto-compact, so
126 /// the preview evaluates that decision against the same policy.
127 pub compaction: crate::compaction::CompactionConfig,
128 }
129
130 /// Why no exact next turn was planned.
131 #[derive(Debug, Clone)]
132 pub enum PreviewUnresolved {
133 /// Auto model routing is on and no hypothetical prompt was supplied.
134 AutoRouteNeedsPrompt,
135 /// Auto model routing needs a classifier provider call. A preview is
136 /// strictly offline, so it stops before invoking the shared route planner.
137 AutoRouteClassificationNotExecuted,
138 /// No hypothetical prompt was supplied, so there is no next-turn body.
139 NoPrompt,
140 /// The shared planner ran and failed. Carries raw host text; it crosses
141 /// the safe-label boundary before it reaches any surface.
142 PlanFailed(String),
143 /// Mutable `message_submit` hooks are configured. A real submit runs them
144 /// before file mentions, skill wrapping, route planning, and the tool
145 /// policy see the text, and they may replace or block it outright. An
146 /// inspection must not execute a hook, so nothing downstream of the text
147 /// — route, tools, or body — can be claimed exact.
148 MessageSubmitHooksConfigured,
149 /// Resolving the prompt into model-facing content failed exactly as a real
150 /// submit would have failed. Carries raw host text.
151 PromptResolutionFailed(String),
152 }
153
154 impl PreviewUnresolved {
155 fn as_availability<T>(&self) -> Availability<T> {
156 match self {
157 Self::AutoRouteNeedsPrompt => {
158 Availability::unavailable(UnavailableReason::AutoRouteUnresolvedUntilNextPrompt)
159 }
160 Self::AutoRouteClassificationNotExecuted => {
161 Availability::unavailable(UnavailableReason::AutoRouteClassificationNotExecuted)
162 }
163 Self::NoPrompt => {
164 Availability::unavailable(UnavailableReason::NoHypotheticalPromptSupplied)
165 }
166 Self::PlanFailed(error) => {
167 Availability::unavailable_with(UnavailableReason::RoutePlanFailed, error.clone())
168 }
169 Self::MessageSubmitHooksConfigured => {
170 Availability::unavailable(UnavailableReason::MessageSubmitHooksNotExecuted)
171 }
172 Self::PromptResolutionFailed(error) => Availability::unavailable_with(
173 UnavailableReason::PromptResolutionFailed,
174 error.clone(),
175 ),
176 }
177 }
178 }
179
180 impl Engine {
181 /// Describe the request the next turn would send, without sending it.
182 pub(super) async fn build_request_manifest(
183 &mut self,
184 inputs: PreviewRequestInputs,
185 ) -> RequestManifest {
186 let session = self.preview_session_facts(&inputs);
187
188 // Mirror terminal continuation gates before request construction.
189 // Token budgets are telemetry-only unless `[goal]
190 // enforce_token_budget` is set; only then does an exhausted budget
191 // make the next goal request unavailable, as the live gates stop.
192 let goal_budget_exhausted = match self.config.goal_state.lock() {
193 Ok(state) => {
194 let snapshot = state.snapshot();
195 Ok(snapshot.is_active()
196 && codewhale_runtime::goal_loop::token_budget_exhausted(
197 codewhale_runtime::goal_loop::GoalProgress {
198 tokens_used: snapshot.tokens_used,
199 continuations: snapshot.continuation_count,
200 },
201 codewhale_runtime::goal_loop::GoalBudget {
202 token_budget: snapshot.token_budget.map(u64::from),
203 enforce_token_budget: self.config.goal_enforce_token_budget,
204 max_continuations: self.config.goal_max_continuations,
205 },
206 ))
207 }
208 Err(err) => {
209 tracing::warn!("goal state lock poisoned while previewing request: {err}");
210 Err(())
211 }
212 };
213 let unavailable_reason = match goal_budget_exhausted {
214 Ok(true) => Some(UnavailableReason::GoalTokenBudgetExhausted),
215 Ok(false) => None,
216 Err(()) => Some(UnavailableReason::GoalStateNotSnapshottable),
217 };
218 if let Some(reason) = unavailable_reason {
219 return RequestManifest::build(ManifestDraft {
220 session,
221 route: Availability::unavailable(reason),
222 tools: Availability::unavailable(reason),
223 body: Availability::unavailable(reason),
224 });
225 }
226
227 let Some(next_turn) = inputs.next_turn else {
228 let unresolved = inputs.unresolved;
229 return RequestManifest::build(ManifestDraft {
230 session,
231 route: unresolved.as_availability(),
232 tools: unresolved.as_availability(),
233 body: unresolved.as_availability(),
234 });
235 };
236
237 let PreviewNextTurn {
238 content: hypothetical_content,
239 route: planned_route,
240 prompt_context: planned_prompt_context,
241 reasoning_effort,
242 reasoning_effort_auto,
243 auto_route_source,
244 routing_source,
245 compaction: planned_compaction,
246 } = *next_turn;
247
248 // Project the planned route into a throw-away client. `validate`
249 // reuses the host's preflighted client when there is one and never
250 // touches engine state — unlike `install_resolved_runtime_route`,
251 // which is what a real turn calls.
252 let route = match (*planned_route).validate() {
253 Ok(route) => route,
254 Err(error) => {
255 let unavailable = PreviewUnresolved::PlanFailed(error);
256 return RequestManifest::build(ManifestDraft {
257 session,
258 route: unavailable.as_availability(),
259 tools: unavailable.as_availability(),
260 body: unavailable.as_availability(),
261 });
262 }
263 };
264
265 let provider = route.identity.provider;
266 let model = route.model.clone();
267 let limits = crate::route_budget::known_route_limits(route.candidate.limits());
268 let base_url = route.candidate.endpoint().base_url.clone();
269 let route_context = TurnRouteContext {
270 provider,
271 model: model.clone(),
272 capabilities: route.candidate.capabilities(),
273 limits,
274 client: Some(route.client.clone()),
275 api_config: route.config.clone(),
276 locale_tag: self.config.locale_tag.clone(),
277 role_models: self.subagent_role_models(),
278 auto_model: inputs.auto_model,
279 reasoning_effort: reasoning_effort.clone(),
280 reasoning_effort_auto,
281 };
282
283 // Same policy derivation as `handle_send_message`, so the catalog is
284 // filtered under the posture the next turn would actually use.
285 let input_policy = effective_input_policy(
286 inputs.provenance,
287 inputs.mode,
288 &hypothetical_content,
289 inputs.allow_shell,
290 inputs.trust_mode,
291 inputs.auto_approve,
292 inputs.approval_mode,
293 );
294 // The command-scoped allow gate is *passed*, never installed. The
295 // earlier shape wrote `self.config.allowed_tools`, awaited the whole
296 // catalog build, and wrote it back: for the duration of that await the
297 // engine carried a gate belonging to a turn that was never going to
298 // run, and a cancellation or panic in between would have left it
299 // installed for good.
300 let build = self
301 .build_turn_tool_registry_and_catalog(
302 &input_policy,
303 &inputs.dynamic_tools,
304 inputs.allowed_tools.clone(),
305 SubAgentWiring::Inert,
306 McpAccess::PassiveSnapshot,
307 &[],
308 route_context.clone(),
309 "",
310 )
311 .await;
312
313 // The build owns the exact same initial subset dispatch consumes.
314 let surface = &build.surface;
315 let active_tools = surface.active.clone().unwrap_or_default();
316 let active_catalog_sha256 = active_tool_catalog_sha256(&active_tools);
317
318 let tool_choice = surface
319 .active
320 .as_ref()
321 .map(|_| default_tool_choice(surface.strict_tool_mode));
322
323 // The tool surface is only publishable when the MCP contribution is
324 // exactly known. Anything else would be "the tools of some other
325 // turn", which is the failure mode this command exists to avoid.
326 let tools = match build.mcp.server_count() {
327 Some(mcp_server_count) => Availability::Exact(ToolSurfaceFacts {
328 catalog_tool_count: surface.catalog.len(),
329 deferred_tool_count: super::tool_catalog::mode_visible_catalog(
330 &surface.catalog,
331 surface.mode,
332 )
333 .iter()
334 .filter(|tool| tool.defer_loading.unwrap_or(false))
335 .count(),
336 active_tool_count: active_tools.len(),
337 active_tool_catalog_sha256: active_catalog_sha256,
338 tool_surface_budget: format!(
339 "{:?}",
340 route_context.capability_profile().tool_surface_budget
341 ),
342 standard_and_full_surfaces_collapsed: standard_and_full_collapse(
343 &surface.catalog,
344 &self.effective_tools_always_load(),
345 ),
346 mcp_server_count,
347 mcp_tool_count: active_tools
348 .iter()
349 .filter(|tool| build.mcp_tool_names.contains(&tool.name))
350 .count(),
351 }),
352 None => match &build.mcp {
353 McpToolState::Unavailable { reason } => Availability::unavailable_with(
354 UnavailableReason::McpStateNotSnapshottable,
355 reason.label(),
356 ),
357 McpToolState::Disabled | McpToolState::Live { .. } => {
358 Availability::unavailable(UnavailableReason::McpStateNotSnapshottable)
359 }
360 },
361 };
362
363 // The system prompt a turn would send is composed for *its* route, so
364 // an auto-routed preview must not reuse the installed model's prompt.
365 // A session-level override wins here exactly as it does in
366 // `refresh_system_prompt`.
367 // The header is pinned for the session: with unchanged explicit
368 // inputs a real turn reuses the pinned bytes (workspace drift arrives
369 // as a `<context_update>` message instead), so preview mirrors that.
370 let effective_reasoning_effort = super::turn_loop::resolve_auto_effort(
371 reasoning_effort.as_deref(),
372 provider,
373 &base_url,
374 &model,
375 );
376 let planned_output_tokens =
377 crate::route_budget::effective_max_output_tokens_for_turn_with_window(
378 provider,
379 &model,
380 limits,
381 Some(route.context_window.tokens),
382 None,
383 effective_reasoning_effort.as_deref(),
384 );
385 let whale_soul = if inputs.provenance.can_authorize_work() {
386 self.capture_local_whale_voice().await
387 } else {
388 Ok(self
389 .session
390 .pinned_prompt_context
391 .as_ref()
392 .and_then(|current| current.whale_soul.clone()))
393 };
394 let whale_soul = match whale_soul {
395 Ok(voice) => voice,
396 Err(error) => {
397 let detail = format!("{error:#}");
398 let unavailable = Availability::unavailable_with(
399 UnavailableReason::RequestPreparationFailed,
400 detail.clone(),
401 );
402 return RequestManifest::build(ManifestDraft {
403 session,
404 route: unavailable,
405 tools,
406 body: Availability::unavailable_with(
407 UnavailableReason::RequestPreparationFailed,
408 detail,
409 ),
410 });
411 }
412 };
413 let prompt_context = NextTurnPromptContext {
414 whale_soul,
415 mode: input_policy.mode,
416 context_window: Some(route.context_window),
417 planned_output_tokens: Some(planned_output_tokens),
418 ..planned_prompt_context
419 };
420 let (system_prompt, preview_raw, preview_assembly) = if self.session.system_prompt_override
421 || self.session.pinned_prompt_context.as_ref() == Some(&prompt_context)
422 {
423 (
424 self.session.system_prompt.clone(),
425 self.session.project_context.clone(),
426 self.session.instruction_assembly.as_deref().cloned(),
427 )
428 } else {
429 self.compose_preview_prefix(&prompt_context)
430 };
431 let instruction_budgets = crate::project_context::InstructionBudgets::resolve_or_default(
432 &self.instruction_settings.budget,
433 route.context_window.instruction_budget_tokens(),
434 Some(planned_output_tokens as usize),
435 );
436 let pre_guard_system_prompt = system_prompt.clone();
437 let guarded = match self.instruction_budget_error.as_deref() {
438 Some(error) => Err(format!("invalid [instruction_budget]: {error}")),
439 None => crate::prompts::guard_instruction_prefix(
440 system_prompt,
441 preview_raw.as_ref(),
442 preview_assembly,
443 instruction_budgets,
444 &active_tools,
445 )
446 .map_err(|refusal| refusal.render(&self.config.locale_tag)),
447 };
448 let (system_prompt, preview_notice) = match guarded {
449 Ok((system_prompt, guarded_assembly, unowned_notices)) => {
450 let notices = guarded_assembly
451 .as_ref()
452 .map_or(unowned_notices.as_slice(), |assembly| {
453 assembly.notices.as_slice()
454 });
455 let notice =
456 crate::project_context::render_notice_body(notices, &self.config.locale_tag);
457 (system_prompt, notice)
458 }
459 Err(detail) => {
460 return RequestManifest::build(ManifestDraft {
461 session,
462 route: Availability::unavailable_with(
463 UnavailableReason::RequestPreparationFailed,
464 detail.clone(),
465 ),
466 tools,
467 body: Availability::unavailable_with(
468 UnavailableReason::RequestPreparationFailed,
469 detail,
470 ),
471 });
472 }
473 };
474
475 let mut context_update_pending = false;
476 let mut preview_assembly: Option<crate::project_context::InstructionAssembly> = None;
477 if !self.session.system_prompt_override
478 && self.host_owned_system_prompt().is_none()
479 && self.session.pinned_prompt_context.as_ref() == Some(&prompt_context)
480 {
481 let memory = codewhale_runtime::native_memory::native_prompt_block(
482 self.config.memory_enabled,
483 &self.config.memory_path,
484 &self.config.workspace,
485 );
486 match self.observe_context_update(&prompt_context, memory.as_deref()) {
487 Ok(observed) => {
488 preview_assembly = observed.assembly.clone();
489 context_update_pending = observed.message.is_some()
490 || observed
491 .notice
492 .filter(|body| preview_notice.as_ref() != Some(body))
493 .is_some_and(|body| {
494 !self.instruction_notice_in_history(&body, &self.session.messages)
495 });
496 }
497 Err(detail) => {
498 return RequestManifest::build(ManifestDraft {
499 session,
500 route: Availability::unavailable_with(
501 UnavailableReason::RequestPreparationFailed,
502 detail.clone(),
503 ),
504 tools,
505 body: Availability::unavailable_with(
506 UnavailableReason::RequestPreparationFailed,
507 detail,
508 ),
509 });
510 }
511 }
512 }
513
514 let skills_context =
515 if self.should_record_skills_context(route.config.runtime_chat_isolated) {
516 let plugins = self
517 .current_extension_plugin_view()
518 .unwrap_or_else(|| Arc::clone(&self.plugin_registry));
519 Some(
520 self.discover_skills_context(Some(route.context_window.tokens), plugins)
521 .await,
522 )
523 } else {
524 None
525 };
526 let skills_discovery_failed = skills_context.as_ref().is_some_and(Result::is_err);
527
528 // The hypothetical user message goes through the same constructor
529 // production uses — turn metadata, route stamp, and provenance — so
530 // the body being hashed is the body a real turn would build. It is
531 // appended to a *clone* of the history and discarded: the session
532 // never sees it.
533 //
534 // A real submit calls `working_set.observe_user_message` before it
535 // writes `<turn_meta>`, so the block reflects files the new message
536 // mentions. The preview observes the message on a **clone** of the
537 // working set and builds the block from that snapshot: same bytes, no
538 // working-set write.
539 let mut previewed_working_set = self.session.working_set.clone();
540 previewed_working_set.observe_user_message(&hypothetical_content, &self.session.workspace);
541 // #5187: the git-snapshot line is emitted on change only, tracked in a
542 // session cache. Previewing a turn must not advance that cache — the
543 // model never saw the previewed block — so the cache is saved and
544 // restored around the hypothetical build, same as the working set.
545 let previewed_git_snapshot = self
546 .last_turn_meta_git_snapshot
547 .lock()
548 .unwrap_or_else(std::sync::PoisonError::into_inner)
549 .clone();
550 let previewed_turn_git_snapshot = {
551 self.turn_meta_git_snapshot
552 .lock()
553 .unwrap_or_else(std::sync::PoisonError::into_inner)
554 .clone()
555 };
556 let preview_turn_git_snapshot = self.capture_turn_meta_git_snapshot().await;
557 self.install_turn_meta_git_snapshot(preview_turn_git_snapshot);
558 let mut messages = self.messages_with_turn_metadata();
559 let hypothetical_user_message = self.user_text_message_from_snapshot(
560 hypothetical_content.clone(),
561 &model,
562 inputs.auto_model,
563 reasoning_effort.as_deref(),
564 reasoning_effort_auto,
565 inputs.provenance,
566 TurnMetadataSnapshot {
567 planned_compaction: Some(&planned_compaction),
568 prompt_context: &prompt_context,
569 system_prompt: pre_guard_system_prompt.as_ref(),
570 approval_mode: input_policy.approval_mode_for_session(),
571 working_set: &previewed_working_set,
572 policy_narrowing: input_policy.narrowing.as_ref(),
573 messages: &messages,
574 },
575 );
576 messages.push(hypothetical_user_message);
577 if let Some(instructions) = Self::planned_project_instructions_message(
578 preview_assembly
579 .as_ref()
580 .or(self.session.instruction_assembly.as_deref()),
581 &messages,
582 ) {
583 messages.push(instructions);
584 }
585 if let Some(Ok((block, _))) = skills_context {
586 messages.extend(Self::planned_skills_context_message(
587 block.as_deref(),
588 &messages,
589 ));
590 }
591 if let Some(body) =
592 preview_notice.filter(|body| !self.instruction_notice_in_history(body, &messages))
593 {
594 let notice = self.user_text_message_from_snapshot(
595 body,
596 &model,
597 inputs.auto_model,
598 reasoning_effort.as_deref(),
599 reasoning_effort_auto,
600 crate::core::ops::UserInputProvenance::Runtime,
601 TurnMetadataSnapshot {
602 planned_compaction: Some(&planned_compaction),
603 prompt_context: &prompt_context,
604 system_prompt: system_prompt.as_ref(),
605 approval_mode: input_policy.approval_mode_for_session(),
606 working_set: &previewed_working_set,
607 policy_narrowing: input_policy.narrowing.as_ref(),
608 messages: &messages,
609 },
610 );
611 messages.push(notice);
612 }
613 *self
614 .last_turn_meta_git_snapshot
615 .lock()
616 .unwrap_or_else(std::sync::PoisonError::into_inner) = previewed_git_snapshot;
617 *self
618 .turn_meta_git_snapshot
619 .lock()
620 .unwrap_or_else(std::sync::PoisonError::into_inner) = previewed_turn_git_snapshot;
621 // Classification input for the provenance section: the prompt this
622 // request actually carries, not the session's current one.
623 let system_prompt_text =
624 codewhale_core::prefix_cache::system_prompt_text(system_prompt.as_ref());
625
626 // Transforms the turn loop would apply to this conversation between
627 // dispatch and the wire. Detected read-only; nothing pending is
628 // consumed, drained, or flushed by looking.
629 let mut runtime_transforms = self
630 .preview_runtime_transforms(&messages, system_prompt.as_ref(), &planned_compaction)
631 .await;
632 if context_update_pending {
633 runtime_transforms.push("workspace context or instruction notices would be appended");
634 }
635 if skills_discovery_failed {
636 runtime_transforms.push("skills context could not be resolved");
637 }
638
639 // Production sends stored history and nothing else — no synthetic
640 // To-do block, on any step — so the previewed outbound message list is
641 // exactly the message list.
642 let outbound_messages = messages.clone();
643
644 // The production overflow gate estimates the logical messages and
645 // system prompt, not serialized provider-body bytes. Use that same
646 // contract here; the manifest keeps its wire estimate separately as
647 // an observability metric.
648 let production_input_estimate_tokens =
649 crate::compaction::estimate_input_tokens_conservative(
650 &messages,
651 system_prompt.as_ref(),
652 );
653
654 let mut request = prepare_primary_turn_request(PrimaryTurnRequest {
655 model: model.clone(),
656 messages: outbound_messages,
657 max_tokens: planned_output_tokens,
658 system: system_prompt,
659 tools: surface.active.clone(),
660 tool_choice: tool_choice.clone(),
661 reasoning_effort: effective_reasoning_effort,
662 });
663 let (image_input, image_cap) = self.request_image_policy(
664 route.identity.key.as_str(),
665 &model,
666 route_context.capabilities.image_input,
667 );
668 crate::image_attach::strip_images_when_unsupported(
669 &mut request.messages,
670 image_input,
671 &model,
672 );
673 if let Some(cap) = image_cap {
674 codewhale_models::image_window::cap_request_images(&mut request.messages, cap);
675 }
676
677 let prepared = match route.client.prepare_outbound_request(request, true) {
678 Ok(prepared) => {
679 prepared.with_route_id(route.identity.persisted_id().map(str::to_string))
680 }
681 Err(error) => {
682 let detail = super::turn_loop::preview_request_error_user_message(
683 &self.config.locale_tag,
684 &error,
685 );
686 // Route identity is read *off the prepared request*, so a
687 // preparation failure leaves the endpoint, wire model, and
688 // dialect unknown too. The tool surface survives: it was built
689 // before the body and does not depend on it.
690 return RequestManifest::build(ManifestDraft {
691 session,
692 route: Availability::unavailable_with(
693 UnavailableReason::RequestPreparationFailed,
694 detail.clone(),
695 ),
696 tools,
697 body: Availability::unavailable_with(
698 UnavailableReason::RequestPreparationFailed,
699 detail,
700 ),
701 });
702 }
703 };
704
705 // `include` on a Responses body discloses reasoning output; it does not
706 // ask the route to think. Treating any control key as a reasoning
707 // request made every Codex turn read as an explicit user selection.
708 let reasoning_resolution = if !prepared.reasoning.controls_reasoning() {
709 ReasoningResolution::NotApplicable
710 } else if reasoning_effort_auto {
711 ReasoningResolution::ResolvedFromHypotheticalPrompt
712 } else if prepared.reasoning.requested_effort.is_none() {
713 ReasoningResolution::RouteDefault
714 } else {
715 ReasoningResolution::Explicit
716 };
717
718 // Headroom and overflow both follow production's message/system
719 // estimator. When an earlier runtime transform cannot be observed
720 // without mutation, `runtime_transforms` makes this body unavailable
721 // rather than publishing a guess.
722 let input_budget_ceiling_tokens =
723 context_input_budget_for_route(provider, &model, limits, 0);
724 if crate::request_manifest::production_input_budget_exceeded(
725 input_budget_ceiling_tokens,
726 production_input_estimate_tokens,
727 ) {
728 runtime_transforms
729 .push("context-overflow recovery would trim or compact the conversation");
730 }
731
732 let route_facts = RouteFacts {
733 provider_id: SafeLabel::identifier(&prepared.endpoint.provider_id),
734 provider_display: SafeLabel::phrase(&prepared.endpoint.provider_display),
735 route_id: prepared
736 .endpoint
737 .route_id
738 .as_deref()
739 .map(SafeLabel::identifier),
740 dialect: prepared.dialect.as_str().to_string(),
741 responses_profile_id: prepared
742 .responses_profile_id
743 .map(|id| id.as_str().to_string()),
744 route_shape: prepared.endpoint.shape.as_str().to_string(),
745 endpoint_host_class: prepared.safe_endpoint_host_class(),
746 endpoint_fingerprint: prepared.endpoint_fingerprint(),
747 wire_model: SafeLabel::catalog_model(&prepared.wire_model),
748 caller_entrypoint: prepared.entrypoint.as_str().to_string(),
749 body_stream_field: prepared.wire_stream_field(),
750 context_limit_tokens: route.context_window.tokens,
751 context_limit_source: route.context_window.source,
752 route_input_limit_tokens: limits.and_then(|limits| limits.input_tokens),
753 route_output_limit_tokens: limits.and_then(|limits| limits.output_tokens),
754 billing: preview_billing_facts(&route.config, &route.identity, &base_url),
755 routing_source: routing_source.label().to_string(),
756 auto_route_source: auto_route_source.as_deref().map(SafeLabel::phrase),
757 };
758
759 let prompt = self.preview_prompt_provenance(&prepared, system_prompt_text.as_str(), &model);
760
761 // The body is a *dependent* fact. A tool surface whose MCP
762 // contribution is unknown does not yield "the same body with no MCP
763 // tools" — a real turn would connect and may send a different tool
764 // list, a different tool region, and therefore a different body,
765 // local component fingerprint, and hash. Publishing an exact body there was the reviewed
766 // defect: it fabricated an empty MCP contribution and hashed it.
767 // Likewise, a request the turn loop would rewrite before sending is
768 // not the request that would be sent.
769 let body = if let Some(inherited) = tools.propagate() {
770 inherited
771 } else if runtime_transforms.is_empty() {
772 Availability::Exact(PreparedBodyInputs {
773 prepared: &prepared,
774 reasoning_resolution,
775 prompt,
776 input_budget_ceiling_tokens,
777 production_input_estimate_tokens,
778 tool_surface_is_exact: true,
779 })
780 } else {
781 Availability::unavailable_with(
782 UnavailableReason::RuntimeTransformsBeforeSend,
783 runtime_transforms.join("; "),
784 )
785 };
786
787 RequestManifest::build(ManifestDraft {
788 session,
789 route: Availability::Exact(route_facts),
790 tools,
791 body,
792 })
793 }
794
795 /// Transforms the turn loop would apply to this conversation between
796 /// dispatch and the first provider request.
797 ///
798 /// Every check is **read-only**. Nothing here drains the steer channel,
799 /// receives a queued sub-agent completion, flushes an LSP block, or runs
800 /// compaction: an inspection that consumed pending state would change the
801 /// very turn it claims to describe. Where a queue can only be *counted*
802 /// rather than inspected, counting is what happens.
803 ///
804 /// Returned strings are compile-time constants. They are joined into a
805 /// typed unavailable detail, which still crosses the safe-label boundary.
806 async fn preview_runtime_transforms(
807 &self,
808 messages: &[Message],
809 system_prompt: Option<&SystemPrompt>,
810 compaction: &crate::compaction::CompactionConfig,
811 ) -> Vec<&'static str> {
812 let mut reasons = Vec::new();
813 if crate::profile_constitution::account_is_present(
814 self.api_config.account_profile.as_deref(),
815 )
816 .unwrap_or(true)
817 || self
818 .constitution_block
819 .as_deref()
820 .is_some_and(|block| block.starts_with("Account profile constitution,"))
821 {
822 reasons.push("the account constitution is resolved at next-turn admission; preview its guidance in account settings");
823 } else if crate::prompts::load_user_constitution_block() != self.constitution_block {
824 reasons
825 .push("the local constitution changed and will be recorded at next-turn admission");
826 }
827
828 if !self.pending_lsp_blocks.is_empty() {
829 reasons.push("pending LSP diagnostics would be injected as a synthetic message");
830 }
831
832 let shell_completion_may_be_injected = self.shell_manager.lock().map_or(true, |manager| {
833 manager.may_have_undelivered_completion_for_session(&self.session.id)
834 });
835 if shell_completion_may_be_injected {
836 reasons.push("a background shell completion may be injected before the request");
837 }
838
839 let queued_completions = !self.rx_subagent_completion.is_empty() || {
840 let manager = self.subagent_manager.read().await;
841 manager.may_transform_next_parent_request_for_session(
842 &self.session.id,
843 &self.delivered_subagent_completion_ids,
844 )
845 };
846 if queued_completions {
847 reasons.push("a running or undelivered sub-agent completion may be injected");
848 }
849
850 if crate::compaction::compaction_pressure_reached(messages, system_prompt, compaction) {
851 let prepared = self.prepare_compaction_envelope(compaction.clone());
852 if should_compact(messages, system_prompt, &prepared) {
853 reasons.push("making room would summarize the conversation first");
854 }
855 }
856
857 reasons
858 }
859
860 /// Posture that depends on neither the route nor the next message.
861 fn preview_session_facts(&self, inputs: &PreviewRequestInputs) -> SessionFacts {
862 let base = crate::prompts::effective_base_prompt_text();
863 let input_policy = effective_input_policy(
864 inputs.provenance,
865 inputs.mode,
866 "",
867 inputs.allow_shell,
868 inputs.trust_mode,
869 inputs.auto_approve,
870 inputs.approval_mode,
871 );
872 SessionFacts {
873 agent_role: "primary".to_string(),
874 lane_kind: "interactive-primary".to_string(),
875 fleet_assignment: "not-applicable-primary-agent".to_string(),
876 requested_model: SafeLabel::catalog_model(&inputs.requested_model),
877 auto_model_routing: inputs.auto_model,
878 requested_reasoning: SafeLabel::identifier(&inputs.requested_reasoning),
879 // What the caller supplied, not what planning managed to do with
880 // it: a plan failure must not read as "you forgot `--prompt`".
881 hypothetical_prompt_supplied: inputs.hypothetical_prompt_supplied,
882 mode: input_policy.mode.label().to_string(),
883 approval_mode: format!("{:?}", input_policy.approval_mode_for_session()),
884 allowed_tool_gate_count: inputs.allowed_tools.as_ref().map(Vec::len),
885 disallowed_tool_gate_count: self.config.disallowed_tools.as_ref().map(Vec::len),
886 base_prompt: BasePromptProvenance {
887 origin: crate::prompts::base_prompt_origin().label().to_string(),
888 bytes: base.len(),
889 sha256: codewhale_runtime::hashing::sha256_hex(base.as_bytes()),
890 },
891 }
892 }
893
894 /// System-prompt provenance, as labels and hashes only.
895 ///
896 /// `effective` is the prompt of the request being described, so an
897 /// auto-routed preview classifies the prompt it would actually send
898 /// rather than the session's currently installed one.
899 fn preview_prompt_provenance(
900 &self,
901 prepared: &PreparedOutboundRequest,
902 effective: &str,
903 model: &str,
904 ) -> PromptProvenance {
905 let base = crate::prompts::effective_base_prompt_text();
906 let configured = crate::prompts::compose_default_static_layers(model);
907
908 let assembly = if effective.trim().is_empty() {
909 SystemPromptAssembly::None
910 } else if effective.trim() == base.trim() {
911 SystemPromptAssembly::BaseOnly
912 } else if effective.trim() == configured.trim() {
913 SystemPromptAssembly::BaseWithConfiguredLayers
914 } else {
915 SystemPromptAssembly::BaseWithRuntimeAdditions
916 };
917
918 let view = prepared.wire_view();
919 PromptProvenance {
920 assembly,
921 // The hash of the prompt the *prepared request* carries, in its
922 // final wire form — not of an independently recomposed string.
923 effective_system_canonical_json_bytes: view.system_bytes,
924 effective_system_sha256: view.system_sha256.clone(),
925 }
926 }
927 }
928
929 /// Typed billing facts for the planned route, from the same helper the footer
930 /// and sidebar read. Every label is a compile-time constant.
931 fn preview_billing_facts(
932 config: &codewhale_runtime::config::Config,
933 identity: &codewhale_runtime::config::ProviderIdentity,
934 base_url: &str,
935 ) -> BillingFacts {
936 if let Some(surface) =
937 crate::pricing::billing_surface_for_route(identity.provider, Some(base_url))
938 {
939 return BillingFacts::Surface { surface };
940 }
941 match crate::route_billing::for_route(config, identity) {
942 crate::route_billing::BillingPresentation::Metered => BillingFacts::Metered,
943 crate::route_billing::BillingPresentation::Subscription(plan) => {
944 BillingFacts::Subscription { plan }
945 }
946 crate::route_billing::BillingPresentation::Local => BillingFacts::Local,
947 crate::route_billing::BillingPresentation::Unknown => BillingFacts::Unknown,
948 }
949 }
950
951 /// Stable hash over the exact active tool catalog: name, description, and
952 /// schema, in catalog order. Changes when a tool is added, removed,
953 /// reordered, or has its schema transformed.
954 ///
955 /// This is the *single* definition of the active-tool-catalog digest. The
956 /// request manifest fills `ToolSurfaceFacts::active_tool_catalog_sha256` from
957 /// it, and `crate::tool_inspection` reports the same value for the same
958 /// prepared request. Neither surface keeps a digest of its own, so a human
959 /// reading `/tools` and a human reading `/request` are looking at the same
960 /// accounting object rather than two hashes that can silently diverge.
961 pub fn active_tool_catalog_sha256(tools: &[Tool]) -> String {
962 let mut canonical = String::new();
963 for tool in tools {
964 canonical.push_str(&tool.name);
965 canonical.push('\u{1}');
966 canonical.push_str(&tool.description);
967 canonical.push('\u{1}');
968 canonical.push_str(&codewhale_runtime::hashing::canonical_json(
969 &tool.input_schema,
970 ));
971 canonical.push('\n');
972 }
973 codewhale_runtime::hashing::sha256_hex(canonical.as_bytes())
974 }
975
976 /// Whether the Standard and Full tool surfaces currently produce the same
977 /// catalog.
978 ///
979 /// Derived, not asserted: the surface shaper is run over this exact catalog
980 /// under both budgets and the results compared. If Standard and Full ever
981 /// genuinely diverge, this reports `false` without anyone editing copy.
982 fn standard_and_full_collapse(
983 catalog: &[Tool],
984 always_load: &std::collections::HashSet<String>,
985 ) -> bool {
986 super::tool_catalog::surface_budgets_produce_same_catalog(
987 catalog,
988 always_load,
989 crate::model_profile::ToolSurfaceBudget::Standard,
990 crate::model_profile::ToolSurfaceBudget::Full,
991 )
992 }
993
994 #[cfg(test)]
995 #[path = "preview/tests.rs"]
996 mod tests;
997
997 lines RUST