1use std::sync::Arc;
2
3use serde_json::Value;
4
5use crate::core::agent::features::FeatureSet;
6use crate::llm::provider::ToolDefinition;
7use crate::tools::tool_intent;
8use crate::tools::validation::commands;
9
10pub fn should_expose_tool_in_mode(
11 tool: &ToolDefinition,
12 planning_active: bool,
13 request_user_input_enabled: bool,
14) -> bool {
15 let Some(name) = tool.function.as_ref().map(|func| func.name.as_str()) else {
16 return true;
17 };
18
19 FeatureSet::tool_enabled_for_mode(name, planning_active, request_user_input_enabled)
20}
21
22pub fn should_expose_tool_in_stable_catalog(tool: &ToolDefinition, request_user_input_enabled: bool) -> bool {
26 should_expose_tool_in_mode(tool, false, request_user_input_enabled)
27 || should_expose_tool_in_mode(tool, true, request_user_input_enabled)
28}
29
30pub fn filter_tool_definitions_for_mode(
31 tools: Option<Arc<Vec<ToolDefinition>>>,
32 planning_active: bool,
33 request_user_input_enabled: bool,
34) -> Option<Arc<Vec<ToolDefinition>>> {
35 filter_tool_definitions_for_mode_with_stability(tools, planning_active, request_user_input_enabled, false)
36}
37
38pub fn filter_tool_definitions_for_mode_with_stability(
39 tools: Option<Arc<Vec<ToolDefinition>>>,
40 planning_active: bool,
41 request_user_input_enabled: bool,
42 stable_catalog: bool,
43) -> Option<Arc<Vec<ToolDefinition>>> {
44 let tools = tools?;
45 if stable_catalog || !planning_active {
48 let expose = |tool: &ToolDefinition| {
49 if stable_catalog {
50 should_expose_tool_in_stable_catalog(tool, request_user_input_enabled)
51 } else {
52 should_expose_tool_in_mode(tool, false, request_user_input_enabled)
53 }
54 };
55 if tools.iter().all(expose) {
60 return Some(tools);
61 }
62 let filtered: Vec<ToolDefinition> = tools.iter().filter(|tool| expose(tool)).cloned().collect();
63 return if filtered.is_empty() {
64 None
65 } else {
66 Some(Arc::new(filtered))
67 };
68 }
69
70 if !tools.is_empty()
72 && tools.iter().all(|tool| {
73 should_expose_tool_in_mode(tool, true, request_user_input_enabled) && planning_action_mask(tool).is_none()
74 })
75 {
76 return Some(tools);
77 }
78
79 let filtered: Vec<ToolDefinition> = tools
80 .iter()
81 .filter(|tool| should_expose_tool_in_mode(tool, true, request_user_input_enabled))
82 .map(|tool| mask_tool_actions_for_mode(tool, true))
83 .collect();
84 if filtered.is_empty() {
85 None
86 } else {
87 Some(Arc::new(filtered))
88 }
89}
90
91fn planning_action_mask(tool: &ToolDefinition) -> Option<&'static [&'static str]> {
96 let function = tool.function.as_ref()?;
97 let allowed = tool_intent::planning_allowed_actions(function.name.as_str())?;
98 let action_enum = function.parameters.get("properties")?.get("action")?.get("enum")?;
99 action_enum.is_array().then_some(allowed)
100}
101
102fn mask_tool_actions_for_mode(tool: &ToolDefinition, planning_active: bool) -> ToolDefinition {
103 if !planning_active {
104 return tool.clone();
105 }
106 let Some(allowed) = planning_action_mask(tool) else {
107 return tool.clone();
108 };
109
110 let mut masked = tool.clone();
111 if let Some(func) = masked.function.as_mut()
112 && let Some(action_prop) = func.parameters.get_mut("properties").and_then(|p| p.get_mut("action"))
113 && let Some(obj) = action_prop.as_object_mut()
114 {
115 obj.insert("enum".to_string(), Value::Array(allowed.iter().map(|a| Value::String((*a).to_string())).collect()));
116 }
117 masked
118}
119
120pub use crate::core::agent::hash_utils::{
121 hash_tool_definitions, hash_value, low_signal_attempt_key, stable_system_prefix_hash,
122};
123pub use crate::core::agent::request_plan::{HarnessRequestPlan, HarnessRequestPlanInput, build_harness_request_plan};
124pub use crate::core::agent::result_reducers::{
125 project_model_tool_result, reduce_tool_result, strip_tui_display_fields,
126};
127pub use crate::core::agent::tool_batching::{
128 FallbackRecommendation, FallbackStep, PreparedToolBatch, PreparedToolBatchKind, PreparedToolCall,
129 is_parallel_safe_tool_batch,
130};
131pub use crate::core::agent::tool_catalog::SessionToolCatalogSnapshot;
132
133pub fn looks_like_grep_style_command(command: &str) -> bool {
134 let lower = command.trim().to_ascii_lowercase();
135 lower.starts_with("grep ") || lower.starts_with("rg ") || lower.contains("/grep ") || lower.contains("/rg ")
136}
137
138pub fn command_is_safe(command: &str) -> bool {
139 commands::validate_command_safety(command).is_ok()
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145 use crate::config::constants::tools;
146 use crate::llm::provider::{Message, ToolChoice};
147
148 fn function_tool(name: &str) -> ToolDefinition {
149 ToolDefinition::function(name.to_string(), name.to_string(), serde_json::json!({}))
150 }
151
152 #[test]
153 fn request_plan_keeps_stable_prefix_hash() {
154 let plan = build_harness_request_plan(HarnessRequestPlanInput {
155 messages: Arc::new(vec![Message::user("hello".to_string())]),
156 system_prompt: Arc::from("base\n[Runtime Context]\n- turns: 1"),
157 tools: Some(Arc::new(vec![function_tool(tools::CODE_SEARCH)])),
158 model: "gpt-5".to_string(),
159 max_tokens: Some(128),
160 temperature: Some(0.7),
161 top_p: None,
162 top_k: None,
163 presence_penalty: None,
164 frequency_penalty: None,
165 stream: true,
166 tool_choice: Some(ToolChoice::auto()),
167 parallel_tool_config: None,
168 reasoning_effort: None,
169 verbosity: None,
170 metadata: None,
171 context_management: None,
172 previous_response_id: None,
173 prompt_cache_key: None,
174 prompt_cache_profile: None,
175 tool_catalog_hash: None,
176 system_prompt_prefix_hash: None,
177 });
178
179 assert!(plan.has_tools);
180 assert!(plan.tool_catalog_hash.is_some());
181 assert_eq!(plan.stable_prefix_hash, stable_system_prefix_hash("base\n[Runtime Context]\n- turns: 1"));
182 }
183
184 #[test]
185 fn request_plan_drops_empty_tool_catalog() {
186 let plan = build_harness_request_plan(HarnessRequestPlanInput {
187 messages: Arc::new(vec![Message::user("hello".to_string())]),
188 system_prompt: Arc::from("base"),
189 tools: Some(Arc::new(Vec::new())),
190 model: "gpt-5".to_string(),
191 max_tokens: Some(128),
192 temperature: Some(0.7),
193 top_p: None,
194 top_k: None,
195 presence_penalty: None,
196 frequency_penalty: None,
197 stream: true,
198 tool_choice: Some(ToolChoice::auto()),
199 parallel_tool_config: None,
200 reasoning_effort: None,
201 verbosity: None,
202 metadata: None,
203 context_management: None,
204 previous_response_id: None,
205 prompt_cache_key: None,
206 prompt_cache_profile: None,
207 tool_catalog_hash: None,
208 system_prompt_prefix_hash: None,
209 });
210
211 assert!(!plan.has_tools);
212 assert!(plan.request.tools.is_none());
213 assert!(plan.tool_catalog_hash.is_none());
214 }
215
216 #[test]
217 fn request_plan_carries_sampling_overrides_into_request() {
218 let plan = build_harness_request_plan(HarnessRequestPlanInput {
219 messages: Arc::new(vec![Message::user("hello".to_string())]),
220 system_prompt: Arc::from("base"),
221 tools: None,
222 model: "gpt-5".to_string(),
223 max_tokens: Some(4_096),
224 temperature: Some(0.2),
225 top_p: Some(0.9),
226 top_k: Some(40),
227 presence_penalty: Some(0.1),
228 frequency_penalty: Some(-0.5),
229 stream: true,
230 tool_choice: None,
231 parallel_tool_config: None,
232 reasoning_effort: None,
233 verbosity: None,
234 metadata: None,
235 context_management: None,
236 previous_response_id: None,
237 prompt_cache_key: None,
238 prompt_cache_profile: None,
239 tool_catalog_hash: None,
240 system_prompt_prefix_hash: None,
241 });
242
243 assert_eq!(plan.request.temperature, Some(0.2));
244 assert_eq!(plan.request.top_p, Some(0.9));
245 assert_eq!(plan.request.top_k, Some(40));
246 assert_eq!(plan.request.presence_penalty, Some(0.1));
247 assert_eq!(plan.request.frequency_penalty, Some(-0.5));
248 assert_eq!(plan.request.max_tokens, Some(4_096));
249 }
250
251 #[test]
252 fn prepared_tool_batches_group_contiguous_parallel_reads() {
253 let batches = PreparedToolBatch::plan(
254 vec![
255 PreparedToolCall::new("read_a".to_string(), true, true, serde_json::json!({})),
256 PreparedToolCall::new("read_b".to_string(), true, true, serde_json::json!({})),
257 PreparedToolCall::new("edit".to_string(), false, false, serde_json::json!({})),
258 ],
259 true,
260 );
261
262 assert_eq!(batches.len(), 2);
263 assert_eq!(batches[0].kind, PreparedToolBatchKind::ParallelReadonly);
264 assert_eq!(batches[0].calls.len(), 2);
265 assert_eq!(batches[1].kind, PreparedToolBatchKind::Sequential);
266 }
267
268 #[test]
269 fn prepared_tool_batches_preserve_order_around_mutating_calls() {
270 let batches = PreparedToolBatch::plan(
271 vec![
272 PreparedToolCall::new("read_a".to_string(), true, true, serde_json::json!({})),
273 PreparedToolCall::new("edit".to_string(), false, false, serde_json::json!({})),
274 PreparedToolCall::new("read_b".to_string(), true, true, serde_json::json!({})),
275 ],
276 true,
277 );
278
279 assert_eq!(batches.len(), 3);
280 assert!(batches.iter().all(|batch| batch.kind == PreparedToolBatchKind::Sequential));
281 assert_eq!(batches[0].calls[0].canonical_name, "read_a");
282 assert_eq!(batches[1].calls[0].canonical_name, "edit");
283 assert_eq!(batches[2].calls[0].canonical_name, "read_b");
284 }
285
286 #[test]
287 fn prepared_tool_batches_group_duplicate_parallel_tool_names() {
288 let batches = PreparedToolBatch::plan(
289 vec![
290 PreparedToolCall::new("read_file".to_string(), true, true, serde_json::json!({})),
291 PreparedToolCall::new("read_file".to_string(), true, true, serde_json::json!({})),
292 ],
293 true,
294 );
295
296 assert_eq!(batches.len(), 1);
297 assert_eq!(batches[0].kind, PreparedToolBatchKind::ParallelReadonly);
298 assert_eq!(batches[0].calls.len(), 2);
299 }
300
301 #[test]
302 fn prepared_tool_batches_keep_duplicate_nonparallel_calls_sequential() {
303 let batches = PreparedToolBatch::plan(
304 vec![
305 PreparedToolCall::new("exec_command".to_string(), false, false, serde_json::json!({})),
306 PreparedToolCall::new("exec_command".to_string(), false, false, serde_json::json!({})),
307 ],
308 true,
309 );
310
311 assert_eq!(batches.len(), 2);
312 assert!(batches.iter().all(|batch| batch.kind == PreparedToolBatchKind::Sequential));
313 assert!(batches.iter().all(|batch| batch.calls.len() == 1));
314 }
315
316 #[test]
317 fn prepared_tool_batches_serializes_all_calls_when_parallel_disabled() {
318 let batches = PreparedToolBatch::plan(
319 vec![
320 PreparedToolCall::new("read_a".to_string(), true, true, serde_json::json!({})),
321 PreparedToolCall::new("read_b".to_string(), true, true, serde_json::json!({})),
322 ],
323 false,
324 );
325
326 assert_eq!(batches.len(), 2);
327 assert!(batches.iter().all(|batch| batch.kind == PreparedToolBatchKind::Sequential));
328 }
329
330 #[test]
331 fn filter_tool_definitions_respects_request_user_input_toggle() {
332 let tools = Arc::new(vec![
333 function_tool(tools::CODE_SEARCH),
334 function_tool(tools::REQUEST_USER_INPUT),
335 ]);
336
337 let filtered = filter_tool_definitions_for_mode(Some(tools), true, false).expect("filtered tools");
338 let names: Vec<&str> = filtered.iter().map(|tool| tool.function_name()).collect();
339
340 assert!(names.contains(&tools::CODE_SEARCH));
341 assert!(!names.contains(&tools::REQUEST_USER_INPUT));
342 }
343
344 #[test]
345 fn filter_tool_definitions_hides_mutating_only_tools_in_planning_workflow() {
346 let tools = Arc::new(vec![
347 function_tool(tools::CODE_SEARCH),
348 function_tool(tools::UNIFIED_FILE),
349 function_tool(tools::APPLY_PATCH),
350 function_tool(tools::WRITE_STDIN),
351 function_tool(tools::WRITE_FILE),
352 ]);
353
354 let filtered = filter_tool_definitions_for_mode(Some(tools), true, false).expect("filtered tools");
355 let names: Vec<&str> = filtered.iter().map(|tool| tool.function_name()).collect();
356
357 assert!(names.contains(&tools::CODE_SEARCH));
358 assert!(names.contains(&tools::UNIFIED_FILE));
359 assert!(!names.contains(&tools::APPLY_PATCH));
360 assert!(!names.contains(&tools::WRITE_STDIN));
361 assert!(!names.contains(&tools::WRITE_FILE));
362 }
363
364 #[test]
365 fn catalog_filters_preserve_exposure_and_actions_for_all_mode_combinations() {
366 let tools = Arc::new(vec![
367 function_tool(tools::CODE_SEARCH),
368 function_tool(tools::REQUEST_USER_INPUT),
369 function_tool(tools::APPLY_PATCH),
370 tool_with_action_enum(tools::UNIFIED_FILE, &["read", "write", "delete"]),
371 ]);
372 for stable in [false, true] {
373 for planning in [false, true] {
374 for input_enabled in [false, true] {
375 let filtered = filter_tool_definitions_for_mode_with_stability(
376 Some(Arc::clone(&tools)),
377 planning,
378 input_enabled,
379 stable,
380 )
381 .expect("search and file tools remain visible");
382 let mut expected_names = vec![tools::CODE_SEARCH];
383 if input_enabled {
384 expected_names.push(tools::REQUEST_USER_INPUT);
385 }
386 if stable || !planning {
387 expected_names.push(tools::APPLY_PATCH);
388 }
389 expected_names.push(tools::UNIFIED_FILE);
390 let names: Vec<_> = filtered.iter().map(ToolDefinition::function_name).collect();
391 assert_eq!(names, expected_names);
392 let parameters = &filtered.last().unwrap().function.as_ref().unwrap().parameters;
393 let expected_actions = if planning && !stable {
394 serde_json::json!(["read"])
395 } else {
396 serde_json::json!(["read", "write", "delete"])
397 };
398 assert_eq!(parameters["properties"]["action"]["enum"], expected_actions);
399 assert_eq!(Arc::ptr_eq(&tools, &filtered), input_enabled && (stable || !planning));
400 }
401 }
402 }
403 }
404
405 #[test]
406 fn catalog_filters_preserve_absent_empty_hidden_and_unchanged_catalogs() {
407 let empty = Arc::new(Vec::new());
408 let hidden = Arc::new(vec![function_tool(tools::REQUEST_USER_INPUT)]);
409 let readonly = Arc::new(vec![function_tool(tools::CODE_SEARCH)]);
410 for stable in [false, true] {
411 for planning in [false, true] {
412 for input_enabled in [false, true] {
413 assert!(
414 filter_tool_definitions_for_mode_with_stability(None, planning, input_enabled, stable)
415 .is_none()
416 );
417 let filtered_empty = filter_tool_definitions_for_mode_with_stability(
418 Some(Arc::clone(&empty)),
419 planning,
420 input_enabled,
421 stable,
422 );
423 if stable || !planning {
424 assert!(Arc::ptr_eq(&empty, &filtered_empty.expect("empty shared catalog")));
425 } else {
426 assert!(filtered_empty.is_none());
427 }
428 let filtered_hidden = filter_tool_definitions_for_mode_with_stability(
429 Some(Arc::clone(&hidden)),
430 planning,
431 input_enabled,
432 stable,
433 );
434 if input_enabled {
435 assert!(Arc::ptr_eq(&hidden, &filtered_hidden.expect("input tool enabled")));
436 } else {
437 assert!(filtered_hidden.is_none());
438 }
439 let filtered_readonly = filter_tool_definitions_for_mode_with_stability(
440 Some(Arc::clone(&readonly)),
441 planning,
442 input_enabled,
443 stable,
444 )
445 .expect("read-only catalog");
446 assert!(Arc::ptr_eq(&readonly, &filtered_readonly));
447 }
448 }
449 }
450 }
451
452 #[test]
453 fn stable_catalog_keeps_mutating_tools_across_planning_toggles() {
454 let tools = Arc::new(vec![
455 function_tool(tools::CODE_SEARCH),
456 function_tool(tools::UNIFIED_FILE),
457 function_tool(tools::APPLY_PATCH),
458 function_tool(tools::WRITE_FILE),
459 ]);
460
461 let planning = filter_tool_definitions_for_mode_with_stability(Some(tools.clone()), true, false, true)
462 .expect("stable planning catalog");
463 let execution = filter_tool_definitions_for_mode_with_stability(Some(tools), false, false, true)
464 .expect("stable execution catalog");
465 let planning_names: Vec<&str> = planning.iter().map(|tool| tool.function_name()).collect();
466 let execution_names: Vec<&str> = execution.iter().map(|tool| tool.function_name()).collect();
467 assert_eq!(planning_names, execution_names, "stable catalog must match across modes");
468 assert!(planning_names.contains(&tools::APPLY_PATCH));
469 assert!(planning_names.contains(&tools::WRITE_FILE));
470 }
471
472 #[test]
473 fn stable_catalog_reuses_arc_when_nothing_is_filtered() {
474 let tools = Arc::new(vec![function_tool(tools::CODE_SEARCH), function_tool(tools::APPLY_PATCH)]);
478
479 let filtered = filter_tool_definitions_for_mode_with_stability(Some(tools.clone()), true, false, true)
480 .expect("stable catalog");
481 assert!(Arc::ptr_eq(&tools, &filtered), "no-op stable filter must reuse the Arc");
482
483 let execution = filter_tool_definitions_for_mode_with_stability(Some(tools.clone()), false, false, true)
484 .expect("stable catalog");
485 assert!(Arc::ptr_eq(&filtered, &execution), "stable catalog must be identical across toggles");
486
487 let mixed = Arc::new(vec![
488 function_tool(tools::CODE_SEARCH),
489 function_tool(tools::REQUEST_USER_INPUT),
490 ]);
491 let pruned = filter_tool_definitions_for_mode_with_stability(Some(mixed.clone()), true, false, true)
492 .expect("stable catalog");
493 assert!(!Arc::ptr_eq(&mixed, &pruned));
494 let names: Vec<&str> = pruned.iter().map(|tool| tool.function_name()).collect();
495 assert!(names.contains(&tools::CODE_SEARCH));
496 assert!(!names.contains(&tools::REQUEST_USER_INPUT));
497
498 let hidden = Arc::new(vec![function_tool(tools::REQUEST_USER_INPUT)]);
499 assert!(
500 filter_tool_definitions_for_mode_with_stability(Some(hidden), false, false, true).is_none(),
501 "fully-hidden stable catalog stays None"
502 );
503 }
504
505 #[test]
506 fn stable_prefix_hash_ignores_runtime_tool_sections() {
507 let base = "Base prompt\n[Harness Limits]\n- max_tool_wall_clock_secs: 60";
508 let with_runtime_sections = format!(
509 "{base}\n\n## Active Tools\n- Capabilities: read-only.\n[Runtime Tool Catalog]\n- version: 1\n- epoch: 2\n- available_tools: 3\n- request_user_input_enabled: false\n\n# PLANNING WORKFLOW (READ-ONLY)\nread-only\n\n# FULL-AUTO: Complete task autonomously until done or blocked.\n- autonomous"
510 );
511
512 assert_eq!(stable_system_prefix_hash(base), stable_system_prefix_hash(&with_runtime_sections));
513 }
514
515 #[test]
516 fn tool_catalog_hash_matches_legacy_json_string_hash() {
517 let tools = vec![
518 function_tool(tools::CODE_SEARCH),
519 ToolDefinition::function(
520 "custom_tool".to_string(),
521 "Custom".to_string(),
522 serde_json::json!({
523 "type": "object",
524 "properties": {
525 "path": { "type": "string" },
526 "line": { "type": "integer" }
527 }
528 }),
529 )
530 .with_strict(true)
531 .with_defer_loading(true),
532 ];
533
534 let expected = serde_json::to_string(&tools).ok().map(|text| hash_value(&text));
535
536 assert_eq!(hash_tool_definitions(Some(&tools)), expected);
537 }
538
539 #[test]
540 fn reduce_command_result_truncates_large_output() {
541 let stdout = (0..2200).map(|_| "a").collect::<Vec<_>>().join("\n");
542 let reduced = reduce_tool_result(
543 tools::UNIFIED_EXEC,
544 serde_json::json!({
545 "stdout": stdout
546 }),
547 );
548
549 assert_eq!(reduced.get("is_truncated"), Some(&Value::Bool(true)));
550 }
551
552 fn tool_with_action_enum(name: &str, actions: &[&str]) -> ToolDefinition {
553 ToolDefinition::function(
554 name.to_string(),
555 name.to_string(),
556 serde_json::json!({
557 "type": "object",
558 "properties": {
559 "action": {
560 "type": "string",
561 "enum": actions
562 }
563 }
564 }),
565 )
566 }
567
568 #[test]
569 fn filter_tool_definitions_masks_unified_file_actions_in_planning() {
570 let tools = Arc::new(vec![tool_with_action_enum(
571 tools::UNIFIED_FILE,
572 &["read", "write", "edit", "patch", "delete", "move", "copy"],
573 )]);
574
575 let filtered = filter_tool_definitions_for_mode(Some(tools), true, false).expect("filtered tools");
576 assert_eq!(filtered.len(), 1);
577
578 let action_enum = filtered[0]
579 .function
580 .as_ref()
581 .unwrap()
582 .parameters
583 .get("properties")
584 .and_then(|p| p.get("action"))
585 .and_then(|a| a.get("enum"))
586 .and_then(|e| e.as_array())
587 .expect("action enum should exist");
588
589 let action_strings: Vec<&str> = action_enum.iter().filter_map(|v| v.as_str()).collect();
590 assert_eq!(action_strings, vec!["read"]);
591 }
592
593 #[test]
594 fn filter_tool_definitions_masks_unified_exec_actions_in_planning() {
595 let tools = Arc::new(vec![tool_with_action_enum(
596 tools::UNIFIED_EXEC,
597 &["run", "write", "poll", "continue", "inspect", "list", "close", "code"],
598 )]);
599
600 let filtered = filter_tool_definitions_for_mode(Some(tools), true, false).expect("filtered tools");
601 assert_eq!(filtered.len(), 1);
602
603 let action_enum = filtered[0]
604 .function
605 .as_ref()
606 .unwrap()
607 .parameters
608 .get("properties")
609 .and_then(|p| p.get("action"))
610 .and_then(|a| a.get("enum"))
611 .and_then(|e| e.as_array())
612 .expect("action enum should exist");
613
614 let action_strings: Vec<&str> = action_enum.iter().filter_map(|v| v.as_str()).collect();
615 assert_eq!(action_strings, vec!["run", "poll", "wait", "list", "inspect", "continue"]);
616 }
617
618 #[test]
619 fn filter_tool_definitions_preserves_actions_when_planning_inactive() {
620 let tools = Arc::new(vec![tool_with_action_enum(
621 tools::UNIFIED_FILE,
622 &["read", "write", "edit", "patch", "delete", "move", "copy"],
623 )]);
624
625 let filtered = filter_tool_definitions_for_mode(Some(tools), false, false).expect("filtered tools");
626 assert_eq!(filtered.len(), 1);
627
628 let action_enum = filtered[0]
629 .function
630 .as_ref()
631 .unwrap()
632 .parameters
633 .get("properties")
634 .and_then(|p| p.get("action"))
635 .and_then(|a| a.get("enum"))
636 .and_then(|e| e.as_array())
637 .expect("action enum should exist");
638
639 let action_strings: Vec<&str> = action_enum.iter().filter_map(|v| v.as_str()).collect();
640 assert_eq!(action_strings, vec!["read", "write", "edit", "patch", "delete", "move", "copy"]);
641 }
642
643 #[test]
644 fn filter_tool_definitions_skips_masking_for_non_multi_action_tools() {
645 let tools = Arc::new(vec![function_tool(tools::CODE_SEARCH)]);
646
647 let filtered = filter_tool_definitions_for_mode(Some(Arc::clone(&tools)), true, false).expect("filtered tools");
648 assert_eq!(filtered.len(), 1);
649 assert_eq!(filtered[0].function_name(), tools::CODE_SEARCH);
651 assert!(Arc::ptr_eq(&tools, &filtered));
652 }
653
654 #[test]
655 fn filter_tool_definitions_preserves_action_schema_without_enum() {
656 let tools = Arc::new(vec![ToolDefinition::function(
657 tools::UNIFIED_FILE.to_string(),
658 "Unified file operation".to_string(),
659 serde_json::json!({
660 "type": "object",
661 "properties": {
662 "action": { "type": "string" }
663 }
664 }),
665 )]);
666
667 let filtered = filter_tool_definitions_for_mode(Some(tools), true, false).expect("filtered tools");
668 let action = filtered[0]
669 .function
670 .as_ref()
671 .and_then(|function| function.parameters.get("properties"))
672 .and_then(|properties| properties.get("action"))
673 .expect("action schema should remain");
674
675 assert_eq!(action.get("type"), Some(&Value::String("string".to_string())));
676 assert!(action.get("enum").is_none());
677 }
678
679 #[test]
680 fn filter_tool_definitions_masks_actions_even_when_no_whole_tool_filter() {
681 let tools = Arc::new(vec![
684 function_tool(tools::CODE_SEARCH),
685 tool_with_action_enum(tools::UNIFIED_FILE, &["read", "write", "edit"]),
686 ]);
687
688 let filtered = filter_tool_definitions_for_mode(Some(tools), true, false).expect("filtered tools");
689 assert_eq!(filtered.len(), 2);
690
691 let unified_file = filtered
692 .iter()
693 .find(|t| t.function_name() == tools::UNIFIED_FILE)
694 .expect("unified_file should be present");
695
696 let action_enum = unified_file
697 .function
698 .as_ref()
699 .unwrap()
700 .parameters
701 .get("properties")
702 .and_then(|p| p.get("action"))
703 .and_then(|a| a.get("enum"))
704 .and_then(|e| e.as_array())
705 .expect("action enum should exist");
706
707 let action_strings: Vec<&str> = action_enum.iter().filter_map(|v| v.as_str()).collect();
708 assert_eq!(action_strings, vec!["read"]);
709 }
710}