返回 CodeWhale
dispatch.rs
根目录 / crates / engine / src / core / engine / dispatch.rs
1 //! Tool dispatch — plan/execute helpers for the per-turn tool batch.
2 //!
3 //! Extracted from `core/engine.rs` (P1.3). The high-level ordering still
4 //! lives in `Engine::run_turn`; this module owns:
5 //!
6 //! * Streaming-buffer parsing into a finalized `serde_json::Value` tool input
7 //! (`final_tool_input`, `parse_tool_input`, fenced/JSON segment helpers).
8 //! * Policy predicates the turn loop consults — when a batch can run in
9 //! parallel and the small set of read-only MCP tools that are safe to run
10 //! in parallel.
11 //! * The tool execution plan/outcome types the batch driver passes around.
12 //!
13 //! All items are `pub(super)`-only: the public engine surface (Op/Event,
14 //! `EngineHandle`, `spawn_engine`) stays in `core/engine.rs`.
15
16 use serde_json::json;
17
18 use crate::tools::spec::{
19 ResourceClaim, ToolError, ToolExecutionOutcome, ToolResult, ToolResultContentBlock,
20 schedule_non_conflicting,
21 };
22 use codewhale_models::{Tool, ToolCaller};
23
24 use super::ToolUseState;
25
26 const MAX_SCHEMA_CONTAINER_REPAIR_BYTES: usize = 64 * 1024;
27
28 // === Types ============================================================
29
30 pub(super) struct ToolExecOutcome {
31 pub(super) index: usize,
32 pub(super) id: String,
33 pub(super) model_call: Option<crate::core::events::ModelToolCall>,
34 pub(super) name: String,
35 pub(super) input: serde_json::Value,
36 pub(super) started_at: std::time::Instant,
37 pub(super) terminal: ToolExecutionOutcome,
38 pub(super) content_blocks: Vec<ToolResultContentBlock>,
39 /// Read-result bytes before spillover adds call-specific artifact paths.
40 pub(super) original_content_digest: Option<[u8; 32]>,
41 }
42
43 /// Notice appended as a user-role message when the guard first asks the worker
44 /// to change strategy after repeated no-progress denials (#6015).
45 pub const FLEET_STRATEGY_SWITCH_NOTICE: &str = "Fleet strategy switch required: repeated permission denials produced no new evidence. The rejected action is held. Use another permitted tool from the current catalog to make progress, or report completed work and the blocker. Do not work around permissions or request the same approval again.";
46
47 /// Notice appended when denials continue past the strategy switch: the next
48 /// response is report-only and its tool calls are admission-held (#6015).
49 pub const FLEET_FINAL_REPORT_NOTICE: &str = "Fleet no-progress final report: permission denials continued after the strategy switch without new evidence. Your next response is report-only; no tools will execute. Report what you completed, exact evidence, the permission blocker and remaining work. This is the last response unless the user changes direction or authority.";
50
51 /// Terminal reason once the report-only response has been recorded (#6015).
52 pub const FLEET_NO_PROGRESS_STOP: &str = "Fleet worker stopped after repeated permission denials without new evidence. Work and tool results are retained in the transcript; review the blocker before resuming.";
53
54 /// Progress observations for one provider response, independent of tool finish
55 /// order. Only typed permission denials contribute to the retry guard (#6015).
56 #[derive(Default)]
57 pub struct FleetDenialBatch {
58 denied: std::collections::HashSet<String>,
59 made_progress: bool,
60 }
61
62 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
63 pub enum FleetDenialAction {
64 Continue,
65 SwitchStrategy,
66 FinalReport,
67 }
68
69 /// Turn-local guard for an engine with a Fleet authority envelope. This is an
70 /// admission predicate and result accumulator, not another execution loop.
71 /// Three responses give the model two opportunities to use denial feedback;
72 /// after one strategy notice, three more denied responses request a report.
73 /// Fleet sub-agent workers run the same guard in their own loop (#6015).
74 #[derive(Default)]
75 pub struct FleetDenialGuard {
76 denied_rounds: std::collections::HashMap<String, u8>,
77 switch_requested: bool,
78 recovery_denied_rounds: u8,
79 denial_rounds_without_progress: u32,
80 report_only: bool,
81 // Last observed bytes per read request: paths alone cannot distinguish a
82 // changed file, and an unchanged read must not repeatedly reset denials.
83 // Coverage is bounded; an evicted observation is treated conservatively
84 // as new evidence. No raw arguments/bytes are kept.
85 reads: std::collections::VecDeque<([u8; 32], [u8; 32])>,
86 }
87
88 impl FleetDenialGuard {
89 const REPEATED_DENIAL_ROUNDS: u8 = 3;
90 const MAX_OBSERVATIONS: usize = 32;
91
92 pub fn reset(&mut self) {
93 *self = Self::default();
94 }
95
96 pub fn report_only(&self) -> bool {
97 self.report_only
98 }
99
100 pub fn awaiting_strategy_change(&self) -> bool {
101 self.switch_requested
102 }
103
104 pub(super) fn denial_rounds_without_progress(&self) -> u32 {
105 self.denial_rounds_without_progress
106 }
107
108 pub fn original_content_digest(
109 name: &str,
110 input: &serde_json::Value,
111 output: &ToolResult,
112 ) -> Option<[u8; 32]> {
113 use sha2::{Digest, Sha256};
114 let action = codewhale_execpolicy::canonical_action::canonical_action_alias(name, input);
115 (output.success
116 && matches!(
117 action,
118 "read_file" | "list_dir" | "file_search" | "grep_files"
119 ))
120 .then(|| Sha256::digest(output.content.as_bytes()).into())
121 }
122
123 pub fn admission_error(&self, name: &str, input: &serde_json::Value) -> Option<ToolError> {
124 let action = codewhale_execpolicy::canonical_action::canonical_action_alias(name, input);
125 if self.report_only {
126 Some(ToolError::permission_denied(
127 "Fleet no-progress final report: no tools may execute in this response. Report completed work, evidence and the remaining blocker; do not change permission mode or retry tools.",
128 ))
129 } else if self.switch_requested && self.denied_rounds.contains_key(action) {
130 Some(ToolError::permission_denied(
131 "Fleet permission-denial loop: this action is held until useful permitted work or an explicit authority change. Use another permitted tool or report the blocker; do not change permission mode or request permission again.",
132 ))
133 } else {
134 None
135 }
136 }
137
138 pub fn observe(
139 &mut self,
140 batch: &mut FleetDenialBatch,
141 name: &str,
142 input: &serde_json::Value,
143 status: crate::tools::spec::ToolTerminalStatus,
144 result: &Result<ToolResult, ToolError>,
145 original_content_digest: Option<[u8; 32]>,
146 ) {
147 use crate::tools::spec::ToolTerminalStatus;
148
149 let action = codewhale_execpolicy::canonical_action::canonical_action_alias(name, input);
150 if status == ToolTerminalStatus::Denied
151 && matches!(result, Err(ToolError::PermissionDenied { .. }))
152 {
153 batch.denied.insert(action.to_owned());
154 return;
155 }
156 let Ok(output) = result else { return };
157 if status != ToolTerminalStatus::Succeeded
158 || !output.success
159 || output.metadata.as_ref().is_some_and(|metadata| {
160 metadata
161 .get("executed")
162 .and_then(serde_json::Value::as_bool)
163 == Some(false)
164 || metadata
165 .get("cancelled")
166 .and_then(serde_json::Value::as_bool)
167 == Some(true)
168 })
169 {
170 return;
171 }
172 // Waiting is useful coordination, but its repeated success receipt is
173 // neither new evidence nor a failure. Its own timeouts still govern it.
174 if matches!(
175 action,
176 "exec_shell_wait" | "exec_wait" | "terminal_wait" | "wait_for_dev_server" | "sleep"
177 ) || name == "agent"
178 && input
179 .get("action")
180 .and_then(serde_json::Value::as_str)
181 .is_some_and(|action| matches!(action, "wait" | "status" | "list"))
182 {
183 return;
184 }
185 if matches!(
186 action,
187 "read_file" | "list_dir" | "file_search" | "grep_files"
188 ) {
189 use sha2::{Digest, Sha256};
190
191 let mut semantic_input = input.clone();
192 if action != name
193 && let Some(object) = semantic_input.as_object_mut()
194 {
195 object.remove("action");
196 }
197 let mut hasher = Sha256::new();
198 hasher.update(action.as_bytes());
199 hasher.update([0]);
200 // Tool JSON preserves insertion order; reordered equivalent keys
201 // must not manufacture a new read request.
202 hasher.update(codewhale_runtime::hashing::canonical_json(&semantic_input).as_bytes());
203 let key: [u8; 32] = hasher.finalize().into();
204 let contents = original_content_digest
205 .unwrap_or_else(|| Sha256::digest(output.content.as_bytes()).into());
206 let previous = self
207 .reads
208 .iter()
209 .position(|(old_key, _)| *old_key == key)
210 .and_then(|index| self.reads.remove(index));
211 batch.made_progress |=
212 previous.is_none_or(|(_, old_contents)| old_contents != contents);
213 self.reads.push_back((key, contents));
214 if self.reads.len() > Self::MAX_OBSERVATIONS {
215 self.reads.pop_front();
216 }
217 } else {
218 // A successful mutation or unfamiliar tool is useful work. Do not
219 // terminate it based on guesses about its content or side effects.
220 batch.made_progress = true;
221 }
222 }
223
224 pub fn finish_batch(&mut self, batch: FleetDenialBatch) -> FleetDenialAction {
225 if self.report_only {
226 return FleetDenialAction::Continue;
227 }
228 if batch.made_progress {
229 self.denied_rounds.clear();
230 self.switch_requested = false;
231 self.recovery_denied_rounds = 0;
232 self.denial_rounds_without_progress = 0;
233 return FleetDenialAction::Continue;
234 }
235 if batch.denied.is_empty() {
236 return FleetDenialAction::Continue;
237 }
238 self.denial_rounds_without_progress = self.denial_rounds_without_progress.saturating_add(1);
239 if self.switch_requested {
240 self.recovery_denied_rounds = self.recovery_denied_rounds.saturating_add(1);
241 if self.recovery_denied_rounds >= Self::REPEATED_DENIAL_ROUNDS {
242 self.report_only = true;
243 return FleetDenialAction::FinalReport;
244 }
245 return FleetDenialAction::Continue;
246 }
247 for action in batch.denied {
248 // The guard never retains payloads. Unknown families beyond this
249 // bounded window do not evict an already observed denial streak.
250 if self.denied_rounds.contains_key(&action)
251 || self.denied_rounds.len() < Self::MAX_OBSERVATIONS
252 {
253 let count = self.denied_rounds.entry(action).or_default();
254 *count = count.saturating_add(1);
255 }
256 }
257 if self
258 .denied_rounds
259 .values()
260 .any(|count| *count >= Self::REPEATED_DENIAL_ROUNDS)
261 {
262 self.switch_requested = true;
263 FleetDenialAction::SwitchStrategy
264 } else {
265 FleetDenialAction::Continue
266 }
267 }
268 }
269
270 #[derive(Debug, Clone)]
271 pub(super) struct ToolExecutionPlan {
272 pub(super) index: usize,
273 pub(super) id: String,
274 pub(super) model_call: Option<crate::core::events::ModelToolCall>,
275 pub(super) name: String,
276 pub(super) input: serde_json::Value,
277 pub(super) caller: Option<ToolCaller>,
278 pub(super) interactive: bool,
279 pub(super) approval_required: bool,
280 pub(super) approval_description: String,
281 pub(super) mcp_always_binding: Option<u64>,
282 pub(super) approval_force_prompt: bool,
283 pub(super) supports_parallel: bool,
284 pub(super) read_only: bool,
285 pub(super) detached_start: bool,
286 pub(super) resources: Vec<ResourceClaim>,
287 pub(super) blocked_error: Option<ToolError>,
288 pub(super) guard_result: Option<ToolResult>,
289 pub(super) grants_outside_workspace_read: bool,
290 pub(super) creator_gate: Option<crate::extension_host::creator_policy::CreatorGatePlan>,
291 pub(super) search_consent: bool,
292 }
293
294 pub(super) enum ToolExecutionBatch {
295 Parallel(Vec<ToolExecutionPlan>),
296 Serial(Box<ToolExecutionPlan>),
297 }
298
299 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
300 pub(super) enum ToolApprovalStamp {
301 ApprovedByUser,
302 ApprovedWithPolicy,
303 }
304
305 impl ToolApprovalStamp {
306 const ALL: [Self; 2] = [Self::ApprovedByUser, Self::ApprovedWithPolicy];
307
308 fn decision(self) -> &'static str {
309 match self {
310 Self::ApprovedByUser => "approved_by_user",
311 Self::ApprovedWithPolicy => "approved_with_policy",
312 }
313 }
314
315 fn legacy_model_visible_note(self) -> &'static str {
316 match self {
317 Self::ApprovedByUser => {
318 "[approval] This tool call required approval and was approved by the user before execution."
319 }
320 Self::ApprovedWithPolicy => {
321 "[approval] This tool call required approval and was approved by the user with an adjusted execution policy before execution."
322 }
323 }
324 }
325 }
326
327 pub(super) fn stamp_tool_result_approval(result: &mut ToolResult, approval: ToolApprovalStamp) {
328 let approval_metadata = json!({
329 "required": true,
330 "decision": approval.decision(),
331 });
332 let metadata = result.metadata.get_or_insert_with(|| json!({}));
333 if let Some(object) = metadata.as_object_mut() {
334 object.insert("approval".to_string(), approval_metadata);
335 } else {
336 let prior = std::mem::replace(metadata, json!({}));
337 if let Some(object) = metadata.as_object_mut() {
338 object.insert("_prior".to_string(), prior);
339 object.insert("approval".to_string(), approval_metadata);
340 }
341 }
342 }
343
344 /// The tool output a person reads: a result recorded by an earlier Codewhale
345 /// without the approval note those versions put in front of it for the model
346 /// (#6566).
347 ///
348 /// Only a result the engine stamped (`metadata.approval.model_visible`) loses
349 /// a note, and only that decision's exact note text followed by a blank line
350 /// (or nothing). Output that merely begins with "\[approval\] " — from a
351 /// command, a file, or anything else a tool read — is shown whole, so
352 /// injected text cannot hide tool output from the person.
353 pub fn content_without_approval_note(result: &ToolResult) -> &str {
354 let content = result.content.as_str();
355 let approval = result
356 .metadata
357 .as_ref()
358 .and_then(|metadata| metadata.get("approval"));
359 let stamped = approval
360 .and_then(|approval| approval.get("model_visible"))
361 .and_then(serde_json::Value::as_bool)
362 == Some(true);
363 let Some(stamp) = approval
364 .and_then(|approval| approval.get("decision"))
365 .and_then(serde_json::Value::as_str)
366 .and_then(|decision| {
367 ToolApprovalStamp::ALL
368 .into_iter()
369 .find(|stamp| stamp.decision() == decision)
370 })
371 .filter(|_| stamped)
372 else {
373 return content;
374 };
375 match content.strip_prefix(stamp.legacy_model_visible_note()) {
376 Some("") => "",
377 Some(rest) => rest.strip_prefix("\n\n").unwrap_or(content),
378 None => content,
379 }
380 }
381
382 // Hold the lock guard for the duration of a tool execution.
383 // The inner guards are held for RAII purposes (dropped when the guard is dropped).
384 pub(super) enum ToolExecGuard<'a> {
385 Read {
386 _guard: tokio::sync::RwLockReadGuard<'a, ()>,
387 },
388 Write {
389 _guard: tokio::sync::RwLockWriteGuard<'a, ()>,
390 },
391 }
392
393 // === Caller policy and errors ========================================
394
395 pub(super) fn caller_type_for_tool_use(caller: Option<&ToolCaller>) -> &str {
396 caller.map_or("direct", |c| c.caller_type.as_str())
397 }
398
399 pub(super) fn caller_allowed_for_tool(
400 caller: Option<&ToolCaller>,
401 tool_def: Option<&Tool>,
402 ) -> bool {
403 let requested = caller_type_for_tool_use(caller);
404 if let Some(def) = tool_def
405 && let Some(allowed) = &def.allowed_callers
406 {
407 if allowed.is_empty() {
408 return requested == "direct";
409 }
410 return allowed.iter().any(|item| item == requested);
411 }
412 requested == "direct"
413 }
414
415 /// Whole-word check for "mode"/"modes" — a plain `contains("mode")` also
416 /// matched "model", letting provider model errors skip the actionable-hint
417 /// suffix (#3020).
418 fn mentions_mode_word(lower: &str) -> bool {
419 lower
420 .split(|ch: char| !ch.is_ascii_alphanumeric())
421 .any(|word| word == "mode" || word == "modes")
422 }
423
424 #[cfg(test)]
425 pub(super) fn format_tool_error(err: &ToolError, tool_name: &str) -> String {
426 format_tool_error_with_schema(err, tool_name, None)
427 }
428
429 const VALID_SHAPE_MAX_BYTES: usize = 2 * 1024;
430
431 pub(super) fn format_tool_error_with_schema(
432 err: &ToolError,
433 tool_name: &str,
434 input_schema: Option<&serde_json::Value>,
435 ) -> String {
436 let message = match err {
437 ToolError::InvalidInput { message } => {
438 format!("Invalid input for tool '{tool_name}': {message}")
439 }
440 ToolError::MissingField { field } => {
441 format!("Tool '{tool_name}' is missing required field '{field}'")
442 }
443 ToolError::PathEscape { path } => format!(
444 "Path escapes workspace: {}. Use a workspace-relative path or enable trust mode.",
445 path.display()
446 ),
447 ToolError::ExecutionFailed { message, .. } => message.clone(),
448 ToolError::Timeout { seconds } => format!(
449 "Tool '{tool_name}' timed out after {seconds}s. Try a narrower scope or a longer timeout."
450 ),
451 ToolError::Cancelled { message } => message.clone(),
452 ToolError::NotAvailable { message } => {
453 let lower = message.to_ascii_lowercase();
454 // #3020: Pass through self-explanatory messages that already name the
455 // cause (mode switch, allow_shell, feature flag). Avoids appending a
456 // conflicting "Check mode, feature flags" suffix on top of
457 // a message that already names the mode and who can change it.
458 if lower.contains("current tool catalog")
459 || lower.contains("did you mean:")
460 || mentions_mode_word(&lower)
461 || lower.contains("allow_shell")
462 || lower.contains("feature flag")
463 {
464 message.clone()
465 } else {
466 format!(
467 "Tool '{tool_name}' is not available: {message}. Check mode, feature flags, or tool name."
468 )
469 }
470 }
471 ToolError::PermissionDenied { message } => {
472 let lower = message.to_ascii_lowercase();
473 // #3020: messages that already name the denial cause get no
474 // conflicting "Adjust approval mode" suffix. They keep the
475 // `Tool '…' was denied:` lead, which is how a receipt tells a
476 // call Codewhale blocked from one that ran and failed; an
477 // approval denial already starts `Tool '…' denied by user`.
478 if lower.contains("denied by user") {
479 message.clone()
480 } else if mentions_mode_word(&lower) || lower.contains("allow_shell") {
481 format!("Tool '{tool_name}' was denied: {message}")
482 } else {
483 format!(
484 "Tool '{tool_name}' was denied: {message}. Adjust approval mode or request permission."
485 )
486 }
487 }
488 };
489
490 let (category, bad_field) = match err {
491 ToolError::InvalidInput { .. } => ("invalid_input", None),
492 ToolError::MissingField { field } => ("missing_field", Some(field.as_str())),
493 ToolError::PathEscape { .. } => ("path_escape", Some("path")),
494 ToolError::NotAvailable { .. } => ("tool_not_available", Some("tool_name")),
495 _ => return message,
496 };
497 let valid_shape = match input_schema {
498 Some(schema) if schema.to_string().len() <= VALID_SHAPE_MAX_BYTES => schema.clone(),
499 Some(schema) => serde_json::json!({
500 "type": "object",
501 "required": schema.get("required").cloned().unwrap_or_else(|| serde_json::json!([])),
502 "properties": schema
503 .get("properties")
504 .and_then(serde_json::Value::as_object)
505 .map(|properties| properties.keys().cloned().collect::<Vec<_>>())
506 .unwrap_or_default(),
507 "guidance": format!("Full field types are in the advertised input schema for '{tool_name}'")
508 }),
509 None => serde_json::json!({
510 "type": "object",
511 "guidance": format!("Use the advertised input schema for '{tool_name}'")
512 }),
513 };
514 let feedback = serde_json::json!({
515 "category": category,
516 "bad_field": bad_field,
517 "valid_shape": valid_shape,
518 "retryable": true,
519 "side_effect_status": "not_started"
520 });
521 format!("{message}\nTool validation feedback: {feedback}")
522 }
523
524 // === Streaming-buffer parsing =========================================
525
526 /// Promote a streaming `ToolUseState` to a finalized JSON input.
527 ///
528 /// Order of preference:
529 ///
530 /// 1. `input_buffer` (the raw streamed delta concatenation) — parsed as
531 /// JSON. This is the most authoritative because it's what the model
532 /// actually emitted.
533 /// 2. `input` (the per-delta best-effort parse mirror) — used when the
534 /// buffer is empty (pre-streaming tool calls take this path).
535 /// 3. `input_buffer` non-empty but unparseable → fall back to `input`
536 /// (the per-delta parser has already mirrored the most recent valid
537 /// partial parse into `tool_state.input`).
538 pub(super) fn final_tool_input(state: &ToolUseState) -> serde_json::Value {
539 if state.input_parse_error.is_some() {
540 return malformed_tool_arguments_input(&state.input_buffer);
541 }
542 if !state.input_buffer.trim().is_empty()
543 && let Some(parsed) = parse_tool_input(&state.input_buffer)
544 {
545 // Structure was synthesized to make this parse, so the argument text
546 // was cut off. Route it to the same malformed-arguments path as an
547 // outright parse failure rather than dispatching a completed guess.
548 if parsed.structure_synthesized {
549 return malformed_tool_arguments_input(&state.input_buffer);
550 }
551 return parsed.value;
552 }
553 state.input.clone()
554 }
555
556 /// A parsed tool-argument buffer, plus whether the parse only succeeded
557 /// because the repair ladder synthesized structure (see
558 /// `crate::tools::arg_repair`). Mid-stream callers mirroring partial state
559 /// may ignore the flag; the caller making the final dispatch decision must
560 /// not, because synthesized structure means the argument text was cut off.
561 pub(super) struct ParsedToolInput {
562 pub(super) value: serde_json::Value,
563 pub(super) structure_synthesized: bool,
564 }
565
566 pub(super) fn parse_tool_input(buffer: &str) -> Option<ParsedToolInput> {
567 let trimmed = buffer.trim();
568 if trimmed.is_empty() {
569 return None;
570 }
571 // Try the deterministic arg-repair ladder first (handles trailing commas,
572 // unclosed braces, embedded control chars, etc.)
573 if let Ok(repaired) = crate::tools::arg_repair::repair(trimmed) {
574 return Some(ParsedToolInput {
575 value: repaired.value,
576 structure_synthesized: repaired.structure_synthesized,
577 });
578 }
579 // Fall back to existing strategies for code-fenced, double-encoded, and
580 // segment-extraction patterns that the repair ladder doesn't cover.
581 if let Some(stripped) = strip_code_fences(trimmed)
582 && let Ok(value) = serde_json::from_str::<serde_json::Value>(&stripped)
583 {
584 return Some(ParsedToolInput {
585 value,
586 structure_synthesized: false,
587 });
588 }
589 if let Ok(serde_json::Value::String(inner)) = serde_json::from_str::<serde_json::Value>(trimmed)
590 && let Ok(value) = serde_json::from_str::<serde_json::Value>(&inner)
591 {
592 return Some(ParsedToolInput {
593 value,
594 structure_synthesized: false,
595 });
596 }
597 extract_json_segment(trimmed)
598 .and_then(|segment| serde_json::from_str::<serde_json::Value>(&segment).ok())
599 .map(|value| ParsedToolInput {
600 value,
601 structure_synthesized: false,
602 })
603 }
604
605 /// Decode a JSON container that a provider encoded as a string when the tool
606 /// schema explicitly requires an object or array.
607 ///
608 /// This intentionally avoids general argument coercion: the string must be
609 /// bounded, parse as strict JSON, and decode to the declared container type.
610 /// Primitive strings are never coerced.
611 pub(super) fn normalize_schema_json_containers(
612 value: &mut serde_json::Value,
613 schema: &serde_json::Value,
614 ) -> usize {
615 let expected_container = if schema_declares_type(schema, "object") {
616 Some("object")
617 } else if schema_declares_type(schema, "array") {
618 Some("array")
619 } else {
620 None
621 };
622
623 if let (Some(expected), serde_json::Value::String(encoded)) = (expected_container, &*value)
624 && encoded.len() <= MAX_SCHEMA_CONTAINER_REPAIR_BYTES
625 && let Ok(decoded) = serde_json::from_str::<serde_json::Value>(encoded)
626 && ((expected == "object" && decoded.is_object())
627 || (expected == "array" && decoded.is_array()))
628 {
629 *value = decoded;
630 return 1 + normalize_schema_json_containers(value, schema);
631 }
632
633 match value {
634 serde_json::Value::Object(object) => {
635 let properties = schema
636 .get("properties")
637 .and_then(serde_json::Value::as_object);
638 object
639 .iter_mut()
640 .map(|(key, child)| {
641 properties
642 .and_then(|items| items.get(key))
643 .map(|child_schema| normalize_schema_json_containers(child, child_schema))
644 .unwrap_or(0)
645 })
646 .sum()
647 }
648 serde_json::Value::Array(items) => schema
649 .get("items")
650 .map(|item_schema| {
651 items
652 .iter_mut()
653 .map(|item| normalize_schema_json_containers(item, item_schema))
654 .sum()
655 })
656 .unwrap_or(0),
657 _ => 0,
658 }
659 }
660
661 fn schema_declares_type(schema: &serde_json::Value, expected: &str) -> bool {
662 match schema.get("type") {
663 Some(serde_json::Value::String(value)) => value == expected,
664 Some(serde_json::Value::Array(values)) => values.iter().any(|value| value == expected),
665 _ => false,
666 }
667 }
668
669 pub(super) fn malformed_tool_arguments_input(buffer: &str) -> serde_json::Value {
670 json!({ "raw_arguments": buffer })
671 }
672
673 pub(super) fn malformed_tool_arguments_error(buffer: &str) -> String {
674 format!("malformed tool arguments from model: expected valid JSON, got {buffer:?}")
675 }
676
677 pub(super) fn tool_input_log_line(
678 event: &str,
679 name: &str,
680 id: &str,
681 input: &serde_json::Value,
682 ) -> String {
683 let bytes = serde_json::to_vec(input).map_or(0, |encoded| encoded.len());
684 format!("{event} '{name}' (id='{id}'): input {bytes} bytes")
685 }
686
687 fn strip_code_fences(text: &str) -> Option<String> {
688 if !text.contains("```") {
689 return None;
690 }
691 let line_count = text.lines().count();
692 let mut lines = Vec::with_capacity(line_count);
693 for line in text.lines() {
694 if line.trim_start().starts_with("```") {
695 continue;
696 }
697 lines.push(line);
698 }
699 let stripped = lines.join("\n");
700 let stripped = stripped.trim();
701 if stripped.is_empty() {
702 None
703 } else {
704 Some(stripped.to_string())
705 }
706 }
707
708 fn extract_json_segment(text: &str) -> Option<String> {
709 extract_balanced_segment(text, '{', '}').or_else(|| extract_balanced_segment(text, '[', ']'))
710 }
711
712 fn extract_balanced_segment(text: &str, open: char, close: char) -> Option<String> {
713 let start = text.find(open)?;
714 let mut depth = 0i32;
715 let mut end = None;
716 for (offset, ch) in text[start..].char_indices() {
717 if ch == open {
718 depth += 1;
719 } else if ch == close {
720 depth -= 1;
721 if depth == 0 {
722 end = Some(start + offset + ch.len_utf8());
723 break;
724 }
725 }
726 }
727 end.map(|end_idx| text[start..end_idx].to_string())
728 }
729
730 // === Dispatch policy ==================================================
731
732 #[cfg(test)]
733 pub(super) fn should_parallelize_tool_batch(plans: &[ToolExecutionPlan]) -> bool {
734 if plans.is_empty() || !plans.iter().all(tool_plan_can_join_parallel_batch) {
735 return false;
736 }
737 schedule_non_conflicting(
738 plans
739 .iter()
740 .map(|plan| ((), plan.resources.clone()))
741 .collect(),
742 )
743 .len()
744 == 1
745 }
746
747 pub(super) fn tool_plan_is_parallel_safe(plan: &ToolExecutionPlan) -> bool {
748 plan.read_only && plan.supports_parallel && !plan.approval_required && !plan.interactive
749 }
750
751 pub(super) fn tool_plan_can_join_parallel_batch(plan: &ToolExecutionPlan) -> bool {
752 plan.blocked_error.is_none()
753 && !plan.search_consent
754 && (tool_plan_is_parallel_safe(plan)
755 || (plan.detached_start && !plan.approval_required && !plan.interactive))
756 }
757
758 pub(super) fn plan_tool_execution_batches(
759 plans: Vec<ToolExecutionPlan>,
760 ) -> Vec<ToolExecutionBatch> {
761 let mut batches = Vec::new();
762 let mut parallel_candidates = Vec::new();
763
764 let flush_parallel = |parallel_candidates: &mut Vec<_>,
765 batches: &mut Vec<ToolExecutionBatch>| {
766 for chunk in schedule_non_conflicting(std::mem::take(parallel_candidates)) {
767 batches.push(ToolExecutionBatch::Parallel(chunk));
768 }
769 };
770
771 for plan in plans {
772 if tool_plan_can_join_parallel_batch(&plan) {
773 let resources = plan.resources.clone();
774 parallel_candidates.push((plan, resources));
775 continue;
776 }
777
778 flush_parallel(&mut parallel_candidates, &mut batches);
779 batches.push(ToolExecutionBatch::Serial(Box::new(plan)));
780 }
781
782 flush_parallel(&mut parallel_candidates, &mut batches);
783
784 batches
785 }
786
787 pub(super) fn mcp_tool_is_parallel_safe(name: &str) -> bool {
788 matches!(
789 name,
790 "list_mcp_resources"
791 | "list_mcp_resource_templates"
792 | "mcp_read_resource"
793 | "read_mcp_resource"
794 | "mcp_get_prompt"
795 )
796 }
797
798 pub(super) fn mcp_tool_is_read_only(name: &str) -> bool {
799 matches!(
800 name,
801 "list_mcp_resources"
802 | "list_mcp_resource_templates"
803 | "mcp_read_resource"
804 | "read_mcp_resource"
805 | "mcp_get_prompt"
806 )
807 }
808
809 pub(super) fn mcp_tool_approval_description(name: &str, input: &serde_json::Value) -> String {
810 use crate::tools::approval_cache::{ComputerUseUserGate, computer_use_user_gate};
811
812 // K1/K2: a Computer Use consent or script card names exactly what the
813 // person is granting. Generic "may have side effects" text is how a
814 // model-issued consent used to read as routine.
815 match computer_use_user_gate(name, input) {
816 Some(ComputerUseUserGate::Consent {
817 action,
818 app,
819 bundle_id,
820 scope,
821 remember,
822 confirm,
823 }) => {
824 if confirm {
825 // The plugin paused on an action that cannot be taken back
826 // and handed the model a token; approving this card is the
827 // person's confirmation of that one action.
828 return "Computer Use confirmation requested by the model: allow the irreversible action (pay, buy, send, transfer or delete) the plugin just paused on. Approve only if you asked for exactly that action.".to_string();
829 }
830 let target = match scope {
831 "foreground" => {
832 "shared-desktop foreground control (take the pointer and focus)".to_string()
833 }
834 _ => {
835 let app = app.as_deref().unwrap_or("<unnamed app>");
836 match bundle_id.as_deref() {
837 Some(bundle) => format!("app '{app}' (bundle id {bundle})"),
838 None => format!("app '{app}' (bundle id not given)"),
839 }
840 }
841 };
842 let lifetime = if action == "revoke" {
843 "clears session and persisted decisions, including a saved deny"
844 } else if remember {
845 "persisted until revoked"
846 } else {
847 "this session"
848 };
849 let verb = if action == "revoke" {
850 "revoke recorded decisions for"
851 } else {
852 "allow"
853 };
854 return format!(
855 "Computer Use consent requested by the model: {verb} {target}; scope: {scope}; {lifetime}. Approve only if you want this."
856 );
857 }
858 Some(ComputerUseUserGate::AppScript {
859 language,
860 script_sha256,
861 first_line,
862 line_count,
863 }) => {
864 let shown = if line_count > 1 {
865 format!("first of {line_count} lines")
866 } else {
867 "1 line".to_string()
868 };
869 return format!(
870 "Computer Use app_script: run this exact {language} script outside the sandbox (sha256 {}, {shown}): {first_line}",
871 &script_sha256[..16]
872 );
873 }
874 Some(ComputerUseUserGate::Computer {
875 action,
876 transport,
877 destination,
878 }) => {
879 let transport = transport.as_deref().unwrap_or("default");
880 let destination = destination.as_deref().unwrap_or("<not given>");
881 return format!(
882 "Computer Use: {action} a computer the model will then drive (transport {transport}, {destination}). Approve only if you want this machine controlled."
883 );
884 }
885 None => {}
886 }
887 match crate::mcp::mcp_tool_approval_hint(name) {
888 _ if mcp_tool_is_read_only(name) => format!("Read-only MCP tool '{name}'"),
889 Some(crate::mcp::McpToolApprovalHint::TrustedReadOnly) => {
890 format!("Read-only MCP tool '{name}' (declared by a reviewed plugin)")
891 }
892 Some(crate::mcp::McpToolApprovalHint::Destructive) => {
893 format!("MCP tool '{name}' is marked destructive by its server")
894 }
895 None => format!("MCP tool '{name}' may have side effects"),
896 }
897 }
898
899 #[cfg(test)]
900 mod tool_input_log_line_tests {
901 use super::*;
902 use serde_json::json;
903
904 #[test]
905 fn log_line_reports_name_call_id_and_size_but_never_argument_values() {
906 let input = json!({
907 "command": "curl -H 'Authorization: Bearer sentinel-secret-value' https://example.test",
908 "nested": { "token": "sentinel-secret-value", "items": ["sentinel-secret-value"] }
909 });
910 let size = serde_json::to_vec(&input).unwrap().len();
911 let line = tool_input_log_line("Planning tool", "exec_shell", "call_1", &input);
912 assert_eq!(
913 line,
914 format!("Planning tool 'exec_shell' (id='call_1'): input {size} bytes")
915 );
916 assert!(!line.contains("sentinel-secret-value"));
917 assert!(!line.contains("command"));
918 }
919
920 #[test]
921 fn log_line_reports_the_size_of_an_empty_input() {
922 let line = tool_input_log_line("Tool block start", "read_file", "call_2", &json!({}));
923 assert_eq!(
924 line,
925 "Tool block start 'read_file' (id='call_2'): input 2 bytes"
926 );
927 }
928 }
929
930 #[cfg(test)]
931 mod schema_json_container_tests {
932 use super::*;
933 use crate::tools::spec::ToolSpec;
934 use serde_json::json;
935
936 #[test]
937 fn decodes_nested_containers_and_passes_tool_validation() {
938 let schema = crate::tools::user_input::RequestUserInputTool::default().input_schema();
939 let encoded_options = serde_json::to_string(&json!([
940 { "label": "Repository", "description": "Inspect the current repository" },
941 { "label": "Workspace", "description": "Inspect the whole workspace" }
942 ]))
943 .expect("encode options");
944 let encoded_questions = serde_json::to_string(&json!([{
945 "header": "Scope",
946 "id": "scope",
947 "question": "Which scope should be inspected?",
948 "options": encoded_options
949 }]))
950 .expect("encode questions");
951 let mut input = json!({ "questions": encoded_questions });
952
953 assert_eq!(normalize_schema_json_containers(&mut input, &schema), 2);
954 assert!(input["questions"].is_array());
955 assert!(input["questions"][0]["options"].is_array());
956 crate::tools::user_input::UserInputRequest::from_value(&input)
957 .expect("normalized input must still pass tool-specific validation");
958 }
959
960 #[test]
961 fn leaves_primitives_wrong_types_and_unbounded_strings_unchanged() {
962 let schema = json!({
963 "type": "object",
964 "properties": {
965 "text": { "type": "string" },
966 "count": { "type": "integer" },
967 "items": { "type": "array" },
968 "oversized": { "type": "array" }
969 }
970 });
971 let oversized = format!("[\"{}\"]", "x".repeat(MAX_SCHEMA_CONTAINER_REPAIR_BYTES));
972 let mut input = json!({
973 "text": "[\"still text\"]",
974 "count": "10",
975 "items": "{\"wrong\":\"container\"}",
976 "oversized": oversized
977 });
978 let before = input.clone();
979
980 assert_eq!(normalize_schema_json_containers(&mut input, &schema), 0);
981 assert_eq!(input, before);
982 }
983 }
984
984 lines RUST