返回 CodeWhale
tool_inspection.rs
根目录 / crates / engine / src / tool_inspection.rs
1 //! Truthful, bounded inspection of a prepared model-client request's tool field.
2 //!
3 //! Capture happens at the request-construction seam and retains only a bounded
4 //! projection. It never claims that the prepared request was delivered.
5 //!
6 //! Two kinds of fact live here, and they are kept apart on purpose:
7 //!
8 //! * **Wire facts** come from the prepared request itself — names, schemas,
9 //! descriptions, per-tool transport flags, byte accounting, and the
10 //! active-tool-catalog digest. The digest is not defined here; it is
11 //! [`crate::core::engine::preview::active_tool_catalog_sha256`], the same
12 //! function the request manifest publishes, so `/tools` and `/request` cannot
13 //! report two different hashes of one catalog.
14 //! * **Surface facts** come from a [`ToolSurfaceContext`] the engine resolves
15 //! once per turn: flattened registry facts, the MCP pool's resolved server
16 //! attributions, the engine-injected catalog names, and the provider receipt
17 //! taken from the *resolved model client*. When that context is present,
18 //! provenance, MCP server identity, capabilities, approval requirement, and
19 //! model visibility become available and true. When it is absent they stay
20 //! explicitly unknown — the context is optional, never faked.
21 //!
22 //! What stays unknowable stays unknown regardless: nothing here observes the
23 //! provider adapter's wire payload, so it is always reported as unavailable.
24
25 mod portable_projection;
26 pub use portable_projection::tool_snapshot as project_snapshot;
27
28 use std::collections::BTreeMap;
29 use std::io::{self, Write};
30
31 use serde::{Deserialize, Serialize};
32 use serde_json::Value;
33
34 use codewhale_models::Tool;
35
36 const MAX_RENDERED_TOOLS: usize = 32;
37 const MAX_NAME_CHARS: usize = 256;
38 const MAX_DESCRIPTION_CHARS: usize = 512;
39 const MAX_SCHEMA_BYTES: usize = 2_048;
40 const MAX_AUXILIARY_CHARS: usize = 512;
41 const MAX_ALLOWED_CALLERS: usize = 16;
42 const MAX_ALLOWED_CALLER_CHARS: usize = 128;
43 const MAX_PAYLOAD_MEASUREMENT_BYTES: usize = 1_048_576;
44
45 #[derive(Debug, Clone, PartialEq, Serialize)]
46 pub struct BoundedString {
47 pub value: String,
48 pub truncated: bool,
49 }
50
51 /// Observed engine exit boundary. This never classifies the assistant's prose.
52 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
53 #[serde(rename_all = "snake_case")]
54 pub enum TurnStopReason {
55 ProviderNoToolCall,
56 ProviderToolCallMissing,
57 StepBudgetExhausted,
58 NoProgress,
59 Interrupted,
60 Failed,
61 }
62
63 /// Terminal facts attached to the existing request inspector, without adding
64 /// conversation input or a notice to an ordinary successful response.
65 #[derive(Debug, Clone, Default, PartialEq, Serialize)]
66 pub struct TurnStopDiagnostics {
67 pub status: Option<crate::core::events::TurnOutcomeStatus>,
68 /// None means the precise runtime exit boundary was not observed.
69 pub reason: Option<TurnStopReason>,
70 /// None means the caller did not install a model-step ceiling.
71 pub effective_max_steps: Option<u32>,
72 pub step_budget_source: &'static str,
73 /// Existing zero-based scheduler step; transport retries do not advance it.
74 pub model_step_index: u32,
75 /// Parent streaming ModelClient calls, including stream retries. Excludes
76 /// HTTP retries inside the client, compaction and child calls; not invoices.
77 pub model_requests_started: u32,
78 /// HTTP retries actually entered inside the captured parent request.
79 /// This is dispatch evidence, not provider usage or a bill.
80 pub transport_retries: u32,
81 pub transparent_stream_retries: u32,
82 pub stream_resumes: u32,
83 pub reasoning_only_reprompts: u32,
84 /// Re-requests after a clean terminal stop that carried no text, no
85 /// reasoning and no tool call (#6310): an exact-prefix retry, then a
86 /// nudged one, before the turn fails visibly.
87 pub empty_stop_retries: u32,
88 pub final_report_requested: bool,
89 pub permission_strategy_switches: u32,
90 /// Denied provider-response batches since the latest useful progress.
91 pub permission_denial_rounds_without_progress: u32,
92 pub last_provider_finish_reason: Option<BoundedString>,
93 /// Structured calls decoded from the stream, before legacy text-call parsing.
94 pub last_response_tool_calls: Option<usize>,
95 /// None means suppression was not counted at this exit boundary.
96 pub last_response_tool_calls_suppressed: Option<usize>,
97 /// Last parent response's reported input tokens, not cumulative billing.
98 pub last_reported_input_tokens: Option<u32>,
99 pub route_context_window_tokens: Option<u64>,
100 /// Engine-prepared output allowance. A transport may omit the field;
101 /// this is budget evidence, not a provider-published capability ceiling.
102 pub last_prepared_output_limit_tokens: Option<u32>,
103 pub automatic_compaction_attempts: u32,
104 pub emergency_compaction_attempts: u32,
105 }
106
107 impl TurnStopDiagnostics {
108 pub fn observe_provider_response(&mut self, finish_reason: Option<&str>, tool_calls: usize) {
109 self.last_provider_finish_reason =
110 finish_reason.map(|reason| bounded_chars(reason, MAX_NAME_CHARS));
111 self.last_response_tool_calls = Some(tool_calls);
112 self.last_response_tool_calls_suppressed = None;
113 }
114 }
115
116 #[derive(Debug, Clone, PartialEq, Serialize)]
117 #[serde(tag = "status", rename_all = "snake_case")]
118 pub enum Evidence<T> {
119 Known { value: T },
120 Unknown { reason: String },
121 }
122
123 #[derive(Debug, Clone, PartialEq, Serialize)]
124 pub struct BoundedList {
125 pub count: usize,
126 pub rendered: Vec<BoundedString>,
127 pub omitted: usize,
128 }
129
130 #[derive(Debug, Clone, PartialEq, Serialize)]
131 pub struct CountOnly {
132 pub count: usize,
133 pub values: &'static str,
134 }
135
136 /// One registry tool flattened to the exact facts this projection may report.
137 ///
138 /// The engine fills this from `ToolSpec`, so this module never holds a tool
139 /// object and therefore cannot execute one.
140 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
141 pub struct RegistryFacts {
142 pub name: String,
143 pub description: String,
144 pub model_visible: bool,
145 pub capabilities: Vec<String>,
146 pub approval: String,
147 /// `true` when the tool came from the plugin surface rather than the
148 /// built-in registry builder.
149 pub plugin: bool,
150 }
151
152 /// Where a tool in the prepared request came from.
153 ///
154 /// `Unknown` is a real answer, not a fallback guess: it means the surface
155 /// context resolved no origin for that name.
156 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
157 #[serde(rename_all = "snake_case")]
158 pub enum ToolProvenance {
159 /// Registered by the built-in registry builder.
160 Builtin,
161 /// Loaded from the plugin/tools surface or `config.toml` overrides.
162 Plugin,
163 /// Contributed by the MCP pool, as attributed by the pool itself.
164 Mcp,
165 /// Injected into the request catalog by the engine rather than registered
166 /// (`tool_search` and its legacy spellings, `code_execution`,
167 /// `execute_tools`).
168 Synthetic,
169 /// Present in the request with no resolved origin.
170 Unknown,
171 }
172
173 /// A tool's state relative to the request that was prepared for this step.
174 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
175 #[serde(rename_all = "snake_case")]
176 pub enum ToolVisibility {
177 /// In this step's request with its schema included.
178 Active,
179 /// In this step's request, marked deferred (schema loads on demand).
180 Deferred,
181 /// In this step's request, with no transport flag to say which.
182 InRequest,
183 }
184
185 impl ToolVisibility {
186 /// Whether this state means the tool's bytes are carried by the prepared
187 /// request. The only honest source of this answer is the request itself.
188 #[must_use]
189 #[cfg(any(test, feature = "test-support"))]
190 pub const fn in_request(self) -> bool {
191 matches!(self, Self::Active | Self::Deferred | Self::InRequest)
192 }
193 }
194
195 /// Provider/route availability, derived from the resolved model client taken at
196 /// the request seam — never from the existence of a tool registry.
197 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
198 #[serde(tag = "status", rename_all = "snake_case")]
199 pub enum ProviderAvailability {
200 /// No client receipt was taken, because no surface context was captured.
201 #[default]
202 Unknown,
203 /// A model client was resolved and this request was built for it.
204 Available { provider: String, model: String },
205 /// The seam was reached with no resolved model client. The reason is a safe
206 /// label, never a URL or credential.
207 Unavailable { reason: String },
208 }
209
210 impl ProviderAvailability {
211 #[must_use]
212 pub const fn is_available(&self) -> bool {
213 matches!(self, Self::Available { .. })
214 }
215
216 #[must_use]
217 #[cfg(any(test, feature = "test-support"))]
218 pub const fn label(&self) -> &'static str {
219 match self {
220 Self::Unknown => "unknown",
221 Self::Available { .. } => "available",
222 Self::Unavailable { .. } => "unavailable",
223 }
224 }
225 }
226
227 /// Everything outside the prepared request that this projection is allowed to
228 /// report, resolved once per turn by the engine.
229 ///
230 /// Plain data only: no registry, no client, no credentials. Resolving it once
231 /// per turn is what keeps the per-step seam from re-locking the MCP pool.
232 #[derive(Debug, Clone, Default)]
233 pub struct ToolSurfaceContext {
234 /// The real registry, flattened. Sorted by name by the producer.
235 pub registry: Vec<RegistryFacts>,
236 /// Model tool name -> MCP server name, only for names the real pool
237 /// resolved. Absent names stay unknown rather than being split apart.
238 pub mcp_servers: BTreeMap<String, String>,
239 /// Request-catalog names the engine injects rather than registering.
240 pub synthetic_names: Vec<String>,
241 /// Receipt from the resolved model client for this turn.
242 pub provider: ProviderAvailability,
243 }
244
245 impl ToolSurfaceContext {
246 fn provenance(&self, name: &str) -> ToolProvenance {
247 if let Some(facts) = self.registry.iter().find(|facts| facts.name == name) {
248 if facts.plugin {
249 return ToolProvenance::Plugin;
250 }
251 if self.mcp_servers.contains_key(name) {
252 return ToolProvenance::Mcp;
253 }
254 return ToolProvenance::Builtin;
255 }
256 if self.mcp_servers.contains_key(name) {
257 return ToolProvenance::Mcp;
258 }
259 if self.synthetic_names.iter().any(|entry| entry == name) {
260 return ToolProvenance::Synthetic;
261 }
262 ToolProvenance::Unknown
263 }
264 }
265
266 #[derive(Debug, Clone, PartialEq, Serialize)]
267 pub struct ToolProjection {
268 pub ordinal: usize,
269 pub name: BoundedString,
270 pub tool_type: Evidence<BoundedString>,
271 pub description: BoundedString,
272 pub input_schema_json: BoundedString,
273 pub allowed_callers: Evidence<BoundedList>,
274 pub defer_loading: Evidence<bool>,
275 pub input_examples: Evidence<CountOnly>,
276 pub strict: Evidence<bool>,
277 pub cache_control_type: Evidence<BoundedString>,
278 /// Where this tool came from. Known only when a surface context was
279 /// captured; `ToolProvenance::Unknown` inside `Known` means the context was
280 /// captured and still resolved no origin.
281 pub provenance: Evidence<ToolProvenance>,
282 /// Owning MCP server, only when the real pool attributed this exact model
283 /// tool name.
284 pub mcp_server: Evidence<BoundedString>,
285 /// Declared capabilities from the registry, sorted. Known-and-empty means
286 /// "declares none"; unknown means "not in the registry".
287 pub capabilities: Evidence<BoundedList>,
288 /// Declared approval requirement from the registry.
289 pub approval: Evidence<BoundedString>,
290 /// Registry model visibility. A tool can be registered but hidden.
291 pub model_visible: Evidence<bool>,
292 /// State relative to this prepared request. Always known: the request is
293 /// the evidence.
294 pub visibility: ToolVisibility,
295 }
296
297 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298 pub struct PreparedMcpToolEstimate {
299 pub step: u32,
300 pub tokens: usize,
301 pub items: Vec<McpServerToolEstimate>,
302 }
303
304 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
305 pub struct McpServerToolEstimate {
306 pub server: String,
307 pub tool_count: usize,
308 pub tokens: usize,
309 }
310
311 fn measure_prepared_mcp_tools(
312 step: u32,
313 tools: &[Tool],
314 surface: &ToolSurfaceContext,
315 ) -> Option<PreparedMcpToolEstimate> {
316 let mut servers = BTreeMap::<&str, McpServerToolEstimate>::new();
317 let mut tokens = 0;
318 for tool in tools {
319 if !tool.name.starts_with("mcp_") {
320 continue;
321 }
322 match surface.provenance(&tool.name) {
323 ToolProvenance::Mcp => {}
324 ToolProvenance::Unknown => return None,
325 _ => continue,
326 }
327 let server = surface.mcp_servers.get(&tool.name)?;
328 if server.is_empty()
329 || server.len() > MAX_NAME_CHARS
330 || server.chars().any(char::is_control)
331 {
332 return None;
333 }
334 let estimated = crate::compaction::estimate_json_tokens(tool)?;
335 let row = servers
336 .entry(server)
337 .or_insert_with(|| McpServerToolEstimate {
338 server: server.clone(),
339 tool_count: 0,
340 tokens: 0,
341 });
342 row.tool_count += 1;
343 row.tokens += estimated;
344 tokens += estimated;
345 if servers.len() > MAX_RENDERED_TOOLS {
346 return None;
347 }
348 }
349 Some(PreparedMcpToolEstimate {
350 step,
351 tokens,
352 items: servers.into_values().collect(),
353 })
354 }
355
356 /// Bounded evidence from a prepared model-client request.
357 #[derive(Debug, Clone, PartialEq, Serialize)]
358 pub struct ToolInspectionSnapshot {
359 pub schema_version: u32,
360 pub capture_source: &'static str,
361 pub delivery_status: &'static str,
362 pub turn_id: BoundedString,
363 pub step: u32,
364 #[serde(skip_serializing_if = "Option::is_none")]
365 pub terminal: Option<TurnStopDiagnostics>,
366 #[serde(skip)]
367 pub(crate) prepared_mcp_tools: Option<PreparedMcpToolEstimate>,
368 pub tools_field_present: bool,
369 pub tool_count: usize,
370 pub rendered_tool_count: usize,
371 pub omitted_tool_count: usize,
372 pub payload_json_bytes: Option<usize>,
373 pub payload_measurement_status: String,
374 /// The active-tool-catalog digest, computed by the *same* function the
375 /// request manifest uses for `active_tool_catalog_sha256`. Absent only when
376 /// the request carried no tools field at all. Covers tool name,
377 /// description, and canonical input schema — not transport-only fields —
378 /// exactly as the manifest does.
379 pub active_tool_catalog_sha256: Option<String>,
380 /// Facts nothing on this path can observe for this request. Shrinks when a
381 /// surface context supplies registry- and client-derived truth; never
382 /// empties, because the provider adapter's wire payload is never visible
383 /// here.
384 pub unavailable_for_this_request: Vec<&'static str>,
385 /// Provider receipt from the resolved model client, or `Unknown` when no
386 /// surface context was captured.
387 pub provider: ProviderAvailability,
388 /// Whether registry-derived facts were captured at all. Absent stays
389 /// distinct from an empty registry.
390 pub registry_facts_present: bool,
391 /// Size of the flattened registry, when it was captured.
392 pub registry_tool_count: Evidence<usize>,
393 /// Registered, model-visible tools this request does *not* carry. Bounded,
394 /// with an explicit omission count.
395 pub registry_only_tools: Evidence<BoundedList>,
396 pub tools: Vec<ToolProjection>,
397 }
398
399 impl ToolInspectionSnapshot {
400 /// Wire facts only. Provenance, attribution, capabilities, approval, and
401 /// provider identity stay explicitly unknown.
402 #[must_use]
403 #[cfg(any(test, feature = "test-support"))]
404 pub fn from_prepared_request(turn_id: &str, step: u32, tools: Option<&[Tool]>) -> Self {
405 Self::from_prepared_request_with_surface(turn_id, step, tools, None)
406 }
407
408 /// Wire facts joined against the turn's resolved surface context.
409 ///
410 /// The context is what turns "unavailable" into truth: it is derived from
411 /// the real registry, the real MCP pool's own attribution, the engine's own
412 /// synthetic-name list, and the resolved model client. Passing `None`
413 /// reproduces the wire-only projection exactly.
414 #[must_use]
415 pub fn from_prepared_request_with_surface(
416 turn_id: &str,
417 step: u32,
418 tools: Option<&[Tool]>,
419 surface: Option<&ToolSurfaceContext>,
420 ) -> Self {
421 let tool_count = tools.map_or(0, <[Tool]>::len);
422 let projected = tools
423 .unwrap_or_default()
424 .iter()
425 .take(MAX_RENDERED_TOOLS)
426 .enumerate()
427 .map(|(index, tool)| project_tool(index, tool, surface))
428 .collect::<Vec<_>>();
429 let (payload_json_bytes, payload_measurement_status) = measure_payload(tools);
430
431 let request_names = tools
432 .unwrap_or_default()
433 .iter()
434 .map(|tool| tool.name.as_str())
435 .collect::<std::collections::BTreeSet<_>>();
436 let registry_only_tools = surface.map_or_else(
437 || unknown("registry facts not captured for this request"),
438 |surface| {
439 let names = surface
440 .registry
441 .iter()
442 .filter(|facts| {
443 facts.model_visible && !request_names.contains(facts.name.as_str())
444 })
445 .map(|facts| facts.name.as_str())
446 .collect::<Vec<_>>();
447 let rendered = names
448 .iter()
449 .take(MAX_RENDERED_TOOLS)
450 .map(|name| bounded_chars(name, MAX_NAME_CHARS))
451 .collect::<Vec<_>>();
452 Evidence::Known {
453 value: BoundedList {
454 count: names.len(),
455 omitted: names.len().saturating_sub(rendered.len()),
456 rendered,
457 },
458 }
459 },
460 );
461
462 let mut unavailable_for_this_request = vec!["provider_wire_payload"];
463 if surface.is_none() {
464 unavailable_for_this_request.extend([
465 "provider",
466 "model",
467 "approval",
468 "provenance",
469 "capabilities",
470 ]);
471 } else if !surface.is_some_and(|surface| surface.provider.is_available()) {
472 unavailable_for_this_request.extend(["provider", "model"]);
473 }
474
475 Self {
476 schema_version: 1,
477 capture_source: "prepared model-client request",
478 delivery_status: "unknown (capture does not prove provider delivery)",
479 turn_id: bounded_chars(turn_id, MAX_AUXILIARY_CHARS),
480 step,
481 terminal: None,
482 prepared_mcp_tools: surface
483 .filter(|_| tools.is_none() || payload_json_bytes.is_some())
484 .and_then(|surface| {
485 measure_prepared_mcp_tools(step, tools.unwrap_or_default(), surface)
486 }),
487 tools_field_present: tools.is_some(),
488 tool_count,
489 rendered_tool_count: projected.len(),
490 omitted_tool_count: tool_count.saturating_sub(projected.len()),
491 payload_json_bytes,
492 payload_measurement_status,
493 active_tool_catalog_sha256: tools
494 .map(crate::core::engine::preview::active_tool_catalog_sha256),
495 unavailable_for_this_request,
496 provider: surface.map_or(ProviderAvailability::Unknown, |surface| {
497 surface.provider.clone()
498 }),
499 registry_facts_present: surface.is_some(),
500 registry_tool_count: surface.map_or_else(
501 || unknown("registry facts not captured for this request"),
502 |surface| Evidence::Known {
503 value: surface.registry.len(),
504 },
505 ),
506 registry_only_tools,
507 tools: projected,
508 }
509 }
510
511 #[must_use]
512 #[cfg(any(test, feature = "test-support"))]
513 pub fn render_text(&self) -> String {
514 codewhale_commands::diagnostics_reports::render_tool_snapshot_text(&project_snapshot(self))
515 }
516
517 #[cfg(any(test, feature = "test-support"))]
518 pub fn render_json(&self) -> Result<String, serde_json::Error> {
519 codewhale_commands::diagnostics_reports::render_tool_snapshot_json(&project_snapshot(self))
520 }
521 }
522
523 fn project_tool(index: usize, tool: &Tool, surface: Option<&ToolSurfaceContext>) -> ToolProjection {
524 let facts = surface.and_then(|surface| {
525 surface
526 .registry
527 .iter()
528 .find(|facts| facts.name == tool.name)
529 });
530 let no_surface = "surface context not captured for this request";
531 let not_registered = "tool is not in the registry";
532 ToolProjection {
533 ordinal: index + 1,
534 name: bounded_chars(&tool.name, MAX_NAME_CHARS),
535 tool_type: optional_bounded(tool.tool_type.as_deref()),
536 description: bounded_chars(&tool.description, MAX_DESCRIPTION_CHARS),
537 input_schema_json: bounded_json(&tool.input_schema, MAX_SCHEMA_BYTES),
538 allowed_callers: tool.allowed_callers.as_ref().map_or_else(
539 || unknown("request field absent"),
540 |values| {
541 let rendered = values
542 .iter()
543 .take(MAX_ALLOWED_CALLERS)
544 .map(|value| bounded_chars(value, MAX_ALLOWED_CALLER_CHARS))
545 .collect::<Vec<_>>();
546 Evidence::Known {
547 value: BoundedList {
548 count: values.len(),
549 omitted: values.len().saturating_sub(rendered.len()),
550 rendered,
551 },
552 }
553 },
554 ),
555 defer_loading: optional_copy(tool.defer_loading.as_ref()),
556 input_examples: tool.input_examples.as_ref().map_or_else(
557 || unknown("request field absent"),
558 |values| Evidence::Known {
559 value: CountOnly {
560 count: values.len(),
561 values: "values omitted from bounded projection",
562 },
563 },
564 ),
565 strict: optional_copy(tool.strict.as_ref()),
566 cache_control_type: optional_bounded(
567 tool.cache_control
568 .as_ref()
569 .map(|value| value.cache_type.as_str()),
570 ),
571 provenance: surface.map_or_else(
572 || unknown(no_surface),
573 |surface| Evidence::Known {
574 value: surface.provenance(&tool.name),
575 },
576 ),
577 mcp_server: surface.map_or_else(
578 || unknown(no_surface),
579 |surface| {
580 surface.mcp_servers.get(&tool.name).map_or_else(
581 || unknown("the MCP pool did not attribute this tool name"),
582 |server| Evidence::Known {
583 value: bounded_chars(server, MAX_AUXILIARY_CHARS),
584 },
585 )
586 },
587 ),
588 capabilities: match (surface, facts) {
589 (None, _) => unknown(no_surface),
590 (Some(_), None) => unknown(not_registered),
591 (Some(_), Some(facts)) => {
592 let rendered = facts
593 .capabilities
594 .iter()
595 .take(MAX_ALLOWED_CALLERS)
596 .map(|value| bounded_chars(value, MAX_ALLOWED_CALLER_CHARS))
597 .collect::<Vec<_>>();
598 Evidence::Known {
599 value: BoundedList {
600 count: facts.capabilities.len(),
601 omitted: facts.capabilities.len().saturating_sub(rendered.len()),
602 rendered,
603 },
604 }
605 }
606 },
607 approval: match (surface, facts) {
608 (None, _) => unknown(no_surface),
609 (Some(_), None) => unknown(not_registered),
610 (Some(_), Some(facts)) => Evidence::Known {
611 value: bounded_chars(&facts.approval, MAX_AUXILIARY_CHARS),
612 },
613 },
614 model_visible: match (surface, facts) {
615 (None, _) => unknown(no_surface),
616 (Some(_), None) => unknown(not_registered),
617 (Some(_), Some(facts)) => Evidence::Known {
618 value: facts.model_visible,
619 },
620 },
621 // Every projected tool is carried by this prepared request; the
622 // transport flag only says whether its schema rides along now.
623 visibility: match tool.defer_loading {
624 Some(true) => ToolVisibility::Deferred,
625 Some(false) => ToolVisibility::Active,
626 None => ToolVisibility::InRequest,
627 },
628 }
629 }
630
631 /// Byte accounting only. The digest is deliberately *not* computed here: it is
632 /// the request path's [`crate::core::engine::preview::active_tool_catalog_sha256`],
633 /// so this projection never defines a second catalog hash.
634 fn measure_payload(tools: Option<&[Tool]>) -> (Option<usize>, String) {
635 let Some(tools) = tools else {
636 return (None, "unavailable (tools field absent)".to_string());
637 };
638 let mut writer = BoundedWriter::new(MAX_PAYLOAD_MEASUREMENT_BYTES);
639 match serde_json::to_writer(&mut writer, tools) {
640 Ok(()) => (
641 Some(writer.bytes.len()),
642 "exact (within 1048576-byte measurement bound)".to_string(),
643 ),
644 Err(_) if writer.exceeded => (
645 None,
646 "unavailable (payload exceeds 1048576-byte measurement bound)".to_string(),
647 ),
648 Err(_) => (None, "unavailable (serialization failed)".to_string()),
649 }
650 }
651
652 fn bounded_json(value: &Value, limit: usize) -> BoundedString {
653 let mut writer = BoundedWriter::new(limit);
654 let result = serde_json::to_writer(&mut writer, value);
655 BoundedString {
656 value: String::from_utf8_lossy(&writer.bytes).into_owned(),
657 truncated: result.is_err() && writer.exceeded,
658 }
659 }
660
661 struct BoundedWriter {
662 bytes: Vec<u8>,
663 limit: usize,
664 exceeded: bool,
665 }
666
667 impl BoundedWriter {
668 fn new(limit: usize) -> Self {
669 Self {
670 bytes: Vec::with_capacity(limit.min(8_192)),
671 limit,
672 exceeded: false,
673 }
674 }
675 }
676
677 impl Write for BoundedWriter {
678 fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
679 let remaining = self.limit.saturating_sub(self.bytes.len());
680 let accepted = buffer.len().min(remaining);
681 self.bytes.extend_from_slice(&buffer[..accepted]);
682 if accepted < buffer.len() {
683 self.exceeded = true;
684 return Err(io::Error::other("inspection bound exceeded"));
685 }
686 Ok(accepted)
687 }
688
689 fn flush(&mut self) -> io::Result<()> {
690 Ok(())
691 }
692 }
693
694 fn bounded_chars(value: &str, limit: usize) -> BoundedString {
695 let mut chars = value.chars();
696 let value = chars.by_ref().take(limit).collect::<String>();
697 BoundedString {
698 value,
699 truncated: chars.next().is_some(),
700 }
701 }
702
703 fn optional_bounded(value: Option<&str>) -> Evidence<BoundedString> {
704 value.map_or_else(
705 || unknown("request field absent"),
706 |value| Evidence::Known {
707 value: bounded_chars(value, MAX_AUXILIARY_CHARS),
708 },
709 )
710 }
711
712 fn optional_copy<T: Copy>(value: Option<&T>) -> Evidence<T> {
713 value.map_or_else(
714 || unknown("request field absent"),
715 |value| Evidence::Known { value: *value },
716 )
717 }
718
719 fn unknown<T>(reason: &str) -> Evidence<T> {
720 Evidence::Unknown {
721 reason: reason.to_string(),
722 }
723 }
724
725 #[cfg(test)]
726 mod tests {
727 use super::*;
728 use serde_json::json;
729
730 fn tool(name: &str) -> Tool {
731 Tool {
732 tool_type: Some("function".to_string()),
733 name: name.to_string(),
734 description: "Read a file".to_string(),
735 input_schema: json!({"type": "object"}),
736 allowed_callers: None,
737 defer_loading: Some(false),
738 input_examples: None,
739 strict: Some(true),
740 cache_control: None,
741 }
742 }
743
744 #[test]
745 fn absent_field_stays_distinct_from_present_empty_array() {
746 let absent = ToolInspectionSnapshot::from_prepared_request("turn", 1, None);
747 let empty = ToolInspectionSnapshot::from_prepared_request("turn", 1, Some(&[]));
748 assert!(!absent.tools_field_present);
749 assert_eq!(absent.payload_json_bytes, None);
750 assert!(absent.active_tool_catalog_sha256.is_none());
751 assert!(empty.tools_field_present);
752 assert_eq!(empty.payload_json_bytes, Some(2));
753 assert!(empty.active_tool_catalog_sha256.is_some());
754 }
755
756 #[test]
757 fn catalog_digest_is_the_request_manifest_digest_not_a_second_definition() {
758 let tools = vec![tool("read_file"), tool("write_file")];
759 let snapshot = ToolInspectionSnapshot::from_prepared_request("turn", 1, Some(&tools));
760
761 // Same prepared request, same accounting object: the value the request
762 // manifest publishes as `active_tool_catalog_sha256`.
763 assert_eq!(
764 snapshot.active_tool_catalog_sha256.as_deref(),
765 Some(crate::core::engine::preview::active_tool_catalog_sha256(&tools).as_str()),
766 );
767
768 // And it is a catalog digest, not an incidental byte hash: reordering
769 // the same tools changes it.
770 let reordered = vec![tools[1].clone(), tools[0].clone()];
771 let reordered = ToolInspectionSnapshot::from_prepared_request("turn", 1, Some(&reordered));
772 assert_ne!(
773 snapshot.active_tool_catalog_sha256,
774 reordered.active_tool_catalog_sha256
775 );
776 }
777
778 #[test]
779 fn projection_preserves_known_false_and_marks_unknown() {
780 let snapshot =
781 ToolInspectionSnapshot::from_prepared_request("turn", 3, Some(&[tool("read_file")]));
782 let text = snapshot.render_text();
783 assert!(text.contains("deferred loading: false"), "{text}");
784 assert!(text.contains("strict: true"), "{text}");
785 assert!(text.contains("allowed callers: unknown (request field absent)"));
786 assert!(text.contains("Delivery: unknown"));
787 assert!(text.contains("Provider-wire tool payload: unavailable"));
788 }
789
790 fn facts(name: &str, plugin: bool, model_visible: bool) -> RegistryFacts {
791 RegistryFacts {
792 name: name.to_string(),
793 description: format!("{name} registry description"),
794 model_visible,
795 capabilities: vec!["ReadOnly".to_string()],
796 approval: "Auto".to_string(),
797 plugin,
798 }
799 }
800
801 fn surface() -> ToolSurfaceContext {
802 ToolSurfaceContext {
803 registry: vec![
804 facts("read_file", false, true),
805 facts("plugin_tool", true, true),
806 facts("hidden_alias", false, false),
807 facts("not_sent", false, true),
808 ],
809 mcp_servers: BTreeMap::from([(
810 "mcp_my_server_read_file".to_string(),
811 "my_server".to_string(),
812 )]),
813 synthetic_names: vec!["tool_search".to_string()],
814 provider: ProviderAvailability::Available {
815 provider: "Deepseek".to_string(),
816 model: "deepseek-chat".to_string(),
817 },
818 }
819 }
820
821 #[test]
822 fn mcp_estimates_use_attributed_prepared_definitions_beyond_rendered_rows() {
823 let surface = surface();
824 let mcp = tool("mcp_my_server_read_file");
825 let expected = crate::compaction::estimate_json_tokens(&mcp).unwrap();
826 let mut tools = vec![tool("read_file"); MAX_RENDERED_TOOLS];
827 tools.push(mcp);
828 let snapshot = ToolInspectionSnapshot::from_prepared_request_with_surface(
829 "turn",
830 2,
831 Some(&tools),
832 Some(&surface),
833 );
834 let estimate = snapshot.prepared_mcp_tools.unwrap();
835 assert_eq!(estimate.step, 2);
836 assert_eq!(estimate.tokens, expected);
837 assert_eq!(
838 estimate.items,
839 [McpServerToolEstimate {
840 server: "my_server".to_string(),
841 tokens: expected,
842 tool_count: 1,
843 }]
844 );
845 assert_eq!(
846 measure_prepared_mcp_tools(0, &tools[..1], &surface)
847 .unwrap()
848 .tokens,
849 0
850 );
851 tools.push(tool("mcp_unknown_owner_tool"));
852 assert!(measure_prepared_mcp_tools(0, &tools, &surface).is_none());
853 }
854
855 #[test]
856 fn surface_context_turns_provenance_and_attribution_into_truth() {
857 let tools = vec![
858 tool("read_file"),
859 tool("plugin_tool"),
860 tool("mcp_my_server_read_file"),
861 tool("tool_search"),
862 tool("stranger"),
863 ];
864 let surface = surface();
865 let snapshot = ToolInspectionSnapshot::from_prepared_request_with_surface(
866 "turn",
867 1,
868 Some(&tools),
869 Some(&surface),
870 );
871
872 let provenance = |name: &str| {
873 snapshot
874 .tools
875 .iter()
876 .find(|entry| entry.name.value == name)
877 .map(|entry| entry.provenance.clone())
878 .expect("projected tool")
879 };
880 for (name, expected) in [
881 ("read_file", ToolProvenance::Builtin),
882 ("plugin_tool", ToolProvenance::Plugin),
883 ("mcp_my_server_read_file", ToolProvenance::Mcp),
884 ("tool_search", ToolProvenance::Synthetic),
885 // Captured context, no resolved origin: unknown is the answer.
886 ("stranger", ToolProvenance::Unknown),
887 ] {
888 assert_eq!(
889 provenance(name),
890 Evidence::Known { value: expected },
891 "provenance for {name}"
892 );
893 }
894
895 let mcp = snapshot
896 .tools
897 .iter()
898 .find(|entry| entry.name.value == "mcp_my_server_read_file")
899 .expect("mcp tool");
900 // Attribution comes from the pool, not from splitting on `_`.
901 assert_eq!(
902 mcp.mcp_server,
903 Evidence::Known {
904 value: BoundedString {
905 value: "my_server".to_string(),
906 truncated: false,
907 }
908 }
909 );
910
911 let read_file = snapshot
912 .tools
913 .iter()
914 .find(|entry| entry.name.value == "read_file")
915 .expect("read_file");
916 assert!(matches!(read_file.capabilities, Evidence::Known { .. }));
917 assert_eq!(
918 read_file.approval,
919 Evidence::Known {
920 value: BoundedString {
921 value: "Auto".to_string(),
922 truncated: false,
923 }
924 }
925 );
926 assert_eq!(read_file.model_visible, Evidence::Known { value: true });
927
928 // Unregistered tools stay unknown rather than being reported as "none".
929 let stranger = snapshot
930 .tools
931 .iter()
932 .find(|entry| entry.name.value == "stranger")
933 .expect("stranger");
934 assert!(matches!(stranger.capabilities, Evidence::Unknown { .. }));
935 assert!(matches!(stranger.approval, Evidence::Unknown { .. }));
936
937 // The unavailable set shrinks to what nothing here can observe.
938 assert_eq!(
939 snapshot.unavailable_for_this_request,
940 vec!["provider_wire_payload"]
941 );
942 assert!(snapshot.provider.is_available());
943 assert!(snapshot.registry_facts_present);
944 assert_eq!(snapshot.registry_tool_count, Evidence::Known { value: 4 });
945
946 let text = snapshot.render_text();
947 assert!(text.contains("provenance: synthetic"), "{text}");
948 assert!(text.contains("MCP server: \"my_server\""), "{text}");
949 assert!(text.contains("Provider: \"Deepseek\""), "{text}");
950 assert!(
951 text.contains("Provider-wire tool payload: unavailable"),
952 "{text}"
953 );
954 }
955
956 #[test]
957 fn registry_only_tools_are_counted_without_expanding_the_projection() {
958 let tools = vec![tool("read_file")];
959 let surface = surface();
960 let snapshot = ToolInspectionSnapshot::from_prepared_request_with_surface(
961 "turn",
962 1,
963 Some(&tools),
964 Some(&surface),
965 );
966
967 // Only the request's tools are projected; the rest are counted.
968 assert_eq!(snapshot.tools.len(), 1);
969 let Evidence::Known { value } = &snapshot.registry_only_tools else {
970 panic!("registry-only tools must be known when facts were captured");
971 };
972 // `hidden_alias` is not model-visible, so it is not a missing tool.
973 assert_eq!(value.count, 2);
974 let rendered = value
975 .rendered
976 .iter()
977 .map(|entry| entry.value.as_str())
978 .collect::<Vec<_>>();
979 // Order follows the registry facts as supplied; the producer sorts.
980 assert_eq!(rendered, vec!["plugin_tool", "not_sent"]);
981
982 // Everything projected is in the request; the request is the evidence.
983 assert!(snapshot.tools.iter().all(|entry| {
984 entry.visibility.in_request() && entry.visibility == ToolVisibility::Active
985 }));
986 }
987
988 #[test]
989 fn absent_surface_keeps_every_registry_derived_field_unknown() {
990 let tools = vec![tool("read_file")];
991 let snapshot = ToolInspectionSnapshot::from_prepared_request("turn", 1, Some(&tools));
992
993 assert_eq!(snapshot.provider, ProviderAvailability::Unknown);
994 assert!(!snapshot.registry_facts_present);
995 assert!(matches!(
996 snapshot.registry_tool_count,
997 Evidence::Unknown { .. }
998 ));
999 assert!(matches!(
1000 snapshot.registry_only_tools,
1001 Evidence::Unknown { .. }
1002 ));
1003 assert_eq!(
1004 snapshot.unavailable_for_this_request,
1005 vec![
1006 "provider_wire_payload",
1007 "provider",
1008 "model",
1009 "approval",
1010 "provenance",
1011 "capabilities",
1012 ]
1013 );
1014 let entry = &snapshot.tools[0];
1015 for evidence in [
1016 matches!(entry.provenance, Evidence::Unknown { .. }),
1017 matches!(entry.mcp_server, Evidence::Unknown { .. }),
1018 matches!(entry.capabilities, Evidence::Unknown { .. }),
1019 matches!(entry.approval, Evidence::Unknown { .. }),
1020 matches!(entry.model_visible, Evidence::Unknown { .. }),
1021 ] {
1022 assert!(evidence);
1023 }
1024 // Wire facts are still exact without a surface context.
1025 assert!(entry.visibility.in_request());
1026 assert!(snapshot.active_tool_catalog_sha256.is_some());
1027 }
1028
1029 #[test]
1030 fn provider_receipt_records_an_unresolved_client_without_borrowing_registry_truth() {
1031 let tools = vec![tool("read_file")];
1032 let surface = ToolSurfaceContext {
1033 registry: vec![facts("read_file", false, true)],
1034 provider: ProviderAvailability::Unavailable {
1035 reason: "no model client resolved for this turn".to_string(),
1036 },
1037 ..ToolSurfaceContext::default()
1038 };
1039 let snapshot = ToolInspectionSnapshot::from_prepared_request_with_surface(
1040 "turn",
1041 1,
1042 Some(&tools),
1043 Some(&surface),
1044 );
1045
1046 // A full registry does not make a provider available.
1047 assert!(!snapshot.provider.is_available());
1048 assert_eq!(snapshot.provider.label(), "unavailable");
1049 assert!(snapshot.unavailable_for_this_request.contains(&"provider"));
1050 // Registry-derived truth is unaffected by the missing client.
1051 assert!(
1052 !snapshot
1053 .unavailable_for_this_request
1054 .contains(&"provenance")
1055 );
1056 assert_eq!(
1057 snapshot.tools[0].provenance,
1058 Evidence::Known {
1059 value: ToolProvenance::Builtin
1060 }
1061 );
1062 }
1063
1064 #[test]
1065 fn capture_and_rendering_are_bounded_with_explicit_receipts() {
1066 let mut tools = (0..40)
1067 .map(|index| {
1068 let mut value = tool(&format!("tool_{index}"));
1069 value.description = "x".repeat(MAX_DESCRIPTION_CHARS + 10);
1070 value.input_schema = json!({"large": "y".repeat(MAX_SCHEMA_BYTES * 600)});
1071 value
1072 })
1073 .collect::<Vec<_>>();
1074 tools[0].allowed_callers = Some(
1075 (0..20)
1076 .map(|caller| format!("caller-{caller}-{}", "z".repeat(200)))
1077 .collect(),
1078 );
1079 let snapshot = ToolInspectionSnapshot::from_prepared_request(
1080 &"t".repeat(MAX_AUXILIARY_CHARS + 1),
1081 1,
1082 Some(&tools),
1083 );
1084 assert_eq!(snapshot.rendered_tool_count, MAX_RENDERED_TOOLS);
1085 assert_eq!(snapshot.omitted_tool_count, 8);
1086 assert!(snapshot.turn_id.truncated);
1087 assert!(snapshot.tools[0].description.truncated);
1088 assert!(snapshot.tools[0].input_schema_json.truncated);
1089 assert_eq!(snapshot.payload_json_bytes, None);
1090 assert!(snapshot.payload_measurement_status.contains("exceeds"));
1091 // The catalog digest is fixed-width, so it survives the byte bound.
1092 assert!(snapshot.active_tool_catalog_sha256.is_some());
1093 let json = snapshot.render_json().expect("bounded JSON");
1094 // 160 KiB: the per-tool evidence fields (provenance, MCP server,
1095 // capabilities, approval, visibility) each carry an explicit reason
1096 // string when unresolved, which is the point — the cap moved, the
1097 // bound did not disappear.
1098 assert!(
1099 json.len() < 163_840,
1100 "projection grew to {} bytes",
1101 json.len()
1102 );
1103 }
1104 }
1105
1105 lines RUST