1#![allow(
2 missing_docs,
3 dead_code,
4 unused_imports,
5 reason = "Intentional compatibility, platform, or test-only suppression."
6)]
7
8#![recursion_limit = "256"]
11use serde_json::{Value, json};
12
13mod collaboration;
14mod json_schema;
15mod matrix;
16#[cfg(feature = "mcp")]
17mod mcp_tool;
18mod responses_api;
19mod tool_kind;
20
21pub use collaboration::{
22 AGENT_DESCRIPTION, SUBAGENT_REASONING_EFFORT_VALUES, agent_parameters, close_agent_parameters,
23 request_user_input_description, request_user_input_parameters, resume_agent_parameters, send_input_parameters,
24 spawn_agent_parameters, spawn_background_subprocess_parameters, wait_agent_parameters,
25};
26pub use json_schema::{AdditionalProperties, JsonSchema, parse_tool_input_schema};
27pub use matrix::{MATRIX_DESCRIPTION, matrix_parameters};
28#[cfg(feature = "mcp")]
29pub use mcp_tool::{ParsedMcpTool, parse_mcp_tool};
30pub use responses_api::{FreeformTool, FreeformToolFormat, ResponsesApiTool};
31pub(crate) use tool_kind::{CanonicalToolMeta, TokenBucket, ToolKind, ToolNamespace};
32
33pub const SEMANTIC_ANCHOR_GUIDANCE: &str =
34 "Prefer stable semantic @@ anchors such as function, class, method, or impl names.";
35
36pub const APPLY_PATCH_ALIAS_DESCRIPTION: &str = "Alias for 'input': same VT Code patch envelope (*** Begin Patch … *** End Patch); unified diffs (---/+++ format) are rejected.";
44pub const DEFAULT_APPLY_PATCH_INPUT_DESCRIPTION: &str = "Patch in VT Code format: *** Begin Patch, *** Update File: path, @@ hunk, -/+ lines, *** End Patch. Every patch path must be workspace-relative; absolute paths, `..`, and traversal-like forms are rejected.";
45pub const APPLY_PATCH_TOOL_DESCRIPTION: &str = "Apply a patch in VT Code format (*** Begin Patch / *** Update File: path / @@ hunks with -/+ lines / *** End Patch); standard unified diffs (---/+++ format) are rejected. *** Add File: path, *** Delete File: path, and *** Move to: path (after *** Update File) are also supported. Every patch path must be workspace-relative; absolute paths, `..`, and traversal-like forms are rejected. Changes are applied after permission checks. Call this tool directly instead of through a shell; JSON calls use input (patch is an alias). Use complete current context/deletion lines, preserving internal whitespace; boundary whitespace and Unicode punctuation normalization are supported, but partial lines are rejected. A typed context mismatch permits one fresh bounded file read range per affected path per turn; other limits remain authoritative.";
51
52pub const DEFAULT_MAX_OUTPUT_TOKENS: usize = 10_000;
54
55pub fn record_decision_parameters() -> Value {
57 serde_json::json!({"type":"object","additionalProperties":false,"required":["summary","rationale"],"properties":{
58 "summary":{"type":"string","minLength":1,"maxLength":240},
59 "rationale":{"type":"string","minLength":1,"maxLength":1000},
60 "alternatives":{"type":"array","maxItems":3,"items":{"type":"string","maxLength":1000}},
61 "evidence_ids":{"type":"array","maxItems":8,"items":{"type":"string","minLength":1,"maxLength":240}}
62 }})
63}
64pub const MIN_MAX_OUTPUT_TOKENS: usize = 1;
66pub const MAX_MAX_OUTPUT_TOKENS: usize = 50_000;
68pub const MAX_OUTPUT_TOKENS_FIELD: &str = "max_output_tokens";
73
74#[must_use]
80pub fn with_max_output_tokens_parameter(mut schema: Value) -> Value {
81 let Some(schema_object) = schema.as_object_mut() else {
82 return schema;
83 };
84 let properties = schema_object
85 .entry("properties")
86 .or_insert_with(|| Value::Object(serde_json::Map::new()));
87 let Some(properties_object) = properties.as_object_mut() else {
88 return schema;
89 };
90 {
91 let _entry = properties_object.entry(MAX_OUTPUT_TOKENS_FIELD).or_insert_with(|| {
92 json!({
93 "type": "integer",
94 "minimum": MIN_MAX_OUTPUT_TOKENS,
95 "maximum": MAX_MAX_OUTPUT_TOKENS,
96 "default": DEFAULT_MAX_OUTPUT_TOKENS,
97 "description": "Maximum number of result tokens returned to the model. Full oversized output is spooled when available."
98 })
99 });
100 }
101 schema
102}
103
104#[must_use]
105pub fn with_semantic_anchor_guidance(base: &str) -> String {
106 let trimmed = base.trim_end();
107 if trimmed.contains(SEMANTIC_ANCHOR_GUIDANCE) {
108 trimmed.to_string()
109 } else if trimmed.ends_with('.') {
110 format!("{trimmed} {SEMANTIC_ANCHOR_GUIDANCE}")
111 } else {
112 format!("{trimmed}. {SEMANTIC_ANCHOR_GUIDANCE}")
113 }
114}
115
116#[must_use]
117pub fn apply_patch_parameter_schema(input_description: &str) -> Value {
118 json!({
119 "type": "object",
120 "properties": {
121 "input": {
122 "type": "string",
123 "description": with_semantic_anchor_guidance(input_description)
124 },
125 "patch": {
126 "type": "string",
127 "description": with_semantic_anchor_guidance(APPLY_PATCH_ALIAS_DESCRIPTION)
128 }
129 },
130 "anyOf": [
131 {"required": ["input"]},
132 {"required": ["patch"]}
133 ]
134 })
135}
136
137#[must_use]
138pub fn apply_patch_parameters() -> Value {
139 apply_patch_parameter_schema(DEFAULT_APPLY_PATCH_INPUT_DESCRIPTION)
140}
141
142#[must_use]
143pub fn cron_parameters() -> Value {
144 json!({
145 "type": "object",
146 "required": ["action"],
147 "additionalProperties": false,
148 "properties": {
149 "action": {
150 "type": "string",
151 "enum": ["create", "list", "delete"],
152 "description": "create: schedule a prompt (requires prompt and exactly one of cron, delay_minutes, or run_at). list: show scheduled prompts. delete: remove one by id."
153 },
154 "prompt": {"type": "string", "description": "create: prompt to run when the task fires."},
155 "name": {"type": "string", "description": "create: optional short label for the task."},
156 "cron": {"type": "string", "description": "create: five-field cron expression for recurring tasks."},
157 "delay_minutes": {"type": "integer", "description": "create: fixed recurring interval in minutes."},
158 "run_at": {"type": "string", "description": "create: one-shot fire time in RFC3339 or local datetime form."},
159 "id": {"type": "string", "description": "delete: session scheduled task id to delete."}
160 }
161 })
162}
163
164pub const MCP_DESCRIPTION: &str = "Discover and manage Model Context Protocol capabilities. Use the `action` field to find tools, fetch one tool schema, list configured servers, and connect or disconnect by name. action=search_tools searches only tools exposed by configured MCP servers; the separate search_tools tool searches the whole session catalog, including deferred built-in tools. Do not disconnect a server while one of its tool calls is active.";
168
169#[must_use]
170pub fn mcp_parameters() -> Value {
171 json!({
172 "type": "object",
173 "required": ["action"],
174 "properties": {
175 "action": {
176 "type": "string",
177 "enum": ["search_tools", "get_tool_details", "list_servers", "connect", "disconnect"],
178 "description": "search_tools: find MCP tools by natural-language query. get_tool_details: fetch the full input schema for one MCP tool name. list_servers: list configured servers and their connection state. connect or disconnect: manage one configured MCP server by name."
179 },
180 "query": {"type": "string", "description": "search_tools: natural language query describing the MCP capability to find."},
181 "detail_level": {"type": "string", "enum": ["name", "name_description", "full"], "description": "search_tools: response detail level."},
182 "limit": {"type": "integer", "minimum": 1, "maximum": 25, "description": "search_tools: maximum number of results to return."},
183 "name": {"type": "string", "description": "get_tool_details: exact MCP tool name. connect or disconnect: configured MCP server name."}
184 },
185 "additionalProperties": false
186 })
187}
188
189#[must_use]
190pub fn cron_create_parameters() -> Value {
191 json!({
192 "type": "object",
193 "required": ["prompt"],
194 "additionalProperties": false,
195 "properties": {
196 "prompt": {"type": "string", "description": "Prompt to run when the task fires."},
197 "name": {"type": "string", "description": "Optional short label for the task."},
198 "cron": {"type": "string", "description": "Five-field cron expression for recurring tasks."},
199 "delay_minutes": {"type": "integer", "description": "Fixed recurring interval in minutes."},
200 "run_at": {
201 "type": "string",
202 "description": "One-shot fire time in RFC3339 or local datetime form. Use this instead of `cron` or `delay_minutes` for reminders."
203 }
204 }
205 })
206}
207
208#[must_use]
209pub fn cron_list_parameters() -> Value {
210 json!({
211 "type": "object",
212 "properties": {},
213 "additionalProperties": false
214 })
215}
216
217#[must_use]
218pub fn cron_delete_parameters() -> Value {
219 json!({
220 "type": "object",
221 "required": ["id"],
222 "properties": {
223 "id": {"type": "string", "description": "Session scheduled task id to delete."}
224 }
225 })
226}
227
228pub const EXEC_COMMAND_DESCRIPTION: &str = "Run a shell command through the active sandbox policy and permission checks. Put normal shell tools such as ls, rg, find, cat, sed, awk, build tools, and test tools in cmd. Returns output, exit status, and a reusable session id when the command is still running. For file edits, use apply_patch instead of shell redirection or in-place editors such as `sed -i`. Expanded sandbox_permissions modes trigger an approval check before the command runs.";
231
232#[must_use]
233pub fn exec_command_parameters() -> Value {
234 json!({
235 "type": "object",
236 "required": ["cmd"],
237 "properties": {
238 "cmd": {"type": "string", "description": "Shell command to execute, subject to command policy. The tool description lists covered tools."},
239 "yield_time_ms": {"type": "integer", "description": "Wait before returning output (ms). If the command is still running, the response includes a session_id for write_stdin. Values above 10000 turn this into a single-call long run: no outer timeout applies and the response returns after the yield window or command exit, whichever is first.", "default": 10000},
240 "background": {"type": "boolean", "description": "Start a retained background process and return after a bounded initial output window. At most three live background processes are allowed per VT Code runtime; use the returned session_id with `write_stdin` for the session lifecycle.", "default": false},
241 "stdin": {"type": "boolean", "description": "Keep pipe stdin open for later write_stdin input. Defaults to false (EOF); enable only for commands that need input. PTY input is always available.", "default": false},
242 "max_output_tokens": {"type": "integer", "minimum": MIN_MAX_OUTPUT_TOKENS, "maximum": MAX_MAX_OUTPUT_TOKENS, "default": DEFAULT_MAX_OUTPUT_TOKENS, "description": "Output token cap. Large or truncated output can return a spool_path; an active session may set spool_complete=false for a readable partial snapshot, while an exited pending spool is withheld until a later wait."},
243 "workdir": {"type": "string", "description": "Working directory."},
244 "tty": {"type": "boolean", "description": "Run the command in PTY mode for interactive or terminal-sensitive commands.", "default": false},
245 "sandbox_permissions": {
246 "type": "string",
247 "enum": ["use_default", "with_additional_permissions", "require_escalated", "bypass_sandbox"],
248 "description": "Sandbox permission mode for this command. Omit it or use `use_default` for the normal sandbox. Non-empty `additional_permissions` is normalized to `with_additional_permissions`. `require_escalated` and `bypass_sandbox` require a non-empty `justification` and cannot be combined with `additional_permissions`.",
249 "default": "use_default"
250 },
251 "additional_permissions": {
252 "type": "object",
253 "description": "Optional extra filesystem roots to grant inside the sandbox. Non-empty `additional_permissions` implicitly requests `with_additional_permissions`; every path is normalized and must stay within allowed workspace or temp roots.",
254 "properties": {
255 "fs_read": {"type": "array", "items": {"type": "string"}},
256 "fs_write": {"type": "array", "items": {"type": "string"}}
257 },
258 "additionalProperties": false
259 },
260 "justification": {"type": "string", "description": "Short approval question for expanded sandbox scope. Required when sandbox_permissions is `require_escalated` or `bypass_sandbox`."}
261 },
262 "additionalProperties": false
263 })
264}
265
266pub const WRITE_STDIN_DESCRIPTION: &str = "Control an owned exec session using its exact session_id (copy verbatim from next_wait_args/next_continue_args; never guess): action=\"write\" sends stdin (pipe runs require stdin:true at launch), action=\"wait\" blocks until exit or wait_timeout_seconds (preferred over polling for long runs; never kills), action=\"poll\" returns the latest output immediately, action=\"inspect\" reads a bounded snapshot, action=\"terminate\" kills the process group, action=\"close\" releases the session.";
268
269#[must_use]
270pub fn write_stdin_parameters() -> Value {
271 json!({
272 "type": "object",
273 "required": ["session_id"],
274 "properties": {
275 "session_id": {"type": "string", "description": "Active execution session id copied verbatim from the run response."},
276 "action": {"type": "string", "enum": ["write", "poll", "wait", "inspect", "terminate", "close"], "description": "write sends chars to stdin; wait blocks until exit or wait_timeout_seconds without killing (preferred for long runs); poll returns latest output immediately and sends no input; inspect reads a bounded snapshot; terminate kills the process group and captures output; close cancels and releases the session."},
277 "chars": {"type": "string", "description": "Bytes to write to stdin; only for action=\"write\". Omit only when action is wait/poll/inspect/terminate/close; an empty string sends no input (polls)."},
278 "yield_time_ms": {"type": "integer", "description": "Wait before returning fresh session output (ms).", "default": 1000},
279 "wait_timeout_seconds": {"type": "integer", "minimum": 1, "description": "Deadline for action=\"wait\" in seconds. A deadline-expired wait returns an in-progress session; call wait again with the same session_id. wait/inspect are exempt from the per-turn tool-call budget."},
280 "max_output_tokens": {"type": "integer", "minimum": MIN_MAX_OUTPUT_TOKENS, "maximum": MAX_MAX_OUTPUT_TOKENS, "default": DEFAULT_MAX_OUTPUT_TOKENS, "description": "Output token cap for the continuation response. Large or truncated output can return a spool_path; the response reports whether an active session has finished writing it."}
281 },
282 "anyOf": [
283 {"required": ["chars"]},
284 {"required": ["action"], "properties": {"action": {"enum": ["poll", "wait", "inspect", "terminate", "close"]}}}
285 ],
286 "additionalProperties": false
287 })
288}
289
290pub const SEARCH_TOOLS_DESCRIPTION: &str = "Search the session tool catalog by capability and return ranked matches. Use it to find tools whose definitions are deferred and not yet sent to you, such as code_search, web_fetch, web_search, cron, and MCP server tools. Deferred matches are listed in `expanded_for_next_segment` and become callable on the next request. It is not needed for tools already defined in the current request; call those directly.";
292
293#[must_use]
294pub fn search_tools_parameters() -> Value {
295 with_max_output_tokens_parameter(json!({
296 "type": "object",
297 "required": ["query"],
298 "properties": {
299 "query": {
300 "type": "string",
301 "minLength": 1,
302 "description": "Natural-language description of the capability to discover."
303 },
304 "limit": {
305 "type": "integer",
306 "minimum": 1,
307 "maximum": 25,
308 "default": 5,
309 "description": "Maximum number of ranked matches to return (default: 5, max: 25)."
310 },
311 "detail_level": {
312 "type": "string",
313 "enum": ["name", "name_description", "full"],
314 "default": "name_description",
315 "description": "Fields returned per match (default: name_description). name returns the tool name and score; name_description adds the description; full also adds the parameter schema."
316 }
317 },
318 "additionalProperties": false
319 }))
320}
321
322#[must_use]
323pub fn code_search_parameters() -> Value {
324 json!({
325 "type": "object",
326 "required": ["query"],
327 "additionalProperties": false,
328 "properties": {
329 "query": {
330 "type": "string",
331 "minLength": 1,
332 "pattern": "\\S",
333 "description": "Literal code or path query. Smart-case applies to content and exact symbol-name matching: a wholly lower-case query matches case-insensitively, while an upper-case character makes matching case-sensitive. Path matching remains fuzzy and case-insensitive."
334 },
335 "path": {
336 "type": "string",
337 "minLength": 1,
338 "pattern": "\\S",
339 "description": "Workspace-relative file or directory to search. Omit to search the workspace root."
340 },
341 "file_types": {
342 "type": "array",
343 "minItems": 1,
344 "items": {
345 "type": "string",
346 "minLength": 1,
347 "pattern": "\\S"
348 },
349 "description": "Language names or common file extensions, with or without one leading dot."
350 },
351 "result_types": {
352 "type": "array",
353 "minItems": 1,
354 "items": {
355 "type": "string",
356 "enum": ["definition", "usage", "text", "path"]
357 },
358 "description": "Result categories to include. Omit to include all four categories."
359 },
360 "max_results": {
361 "type": "integer",
362 "minimum": 1,
363 "maximum": 100,
364 "description": "Maximum number of merged results to return. Omit for 20."
365 }
366 }
367 })
368}
369
370#[must_use]
371pub fn list_files_parameters() -> Value {
372 json!({
373 "type": "object",
374 "properties": {
375 "path": {"type": "string", "description": "Directory or file path to inspect.", "default": "."},
376 "mode": {
377 "type": "string",
378 "enum": ["list", "recursive", "tree", "find_name", "find_content", "largest", "file", "files"],
379 "description": "Listing mode. Use page/per_page to continue paginated results.",
380 "default": "list"
381 },
382 "pattern": {"type": "string", "description": "Optional glob-style path filter."},
383 "name_pattern": {"type": "string", "description": "Optional name filter for list/find_name modes."},
384 "content_pattern": {"type": "string", "description": "Content query for find_content mode."},
385 "page": {"type": "integer", "description": "1-indexed results page.", "minimum": 1},
386 "per_page": {"type": "integer", "description": "Items per page.", "minimum": 1},
387 "max_results": {"type": "integer", "description": "Maximum total results to consider before pagination.", "minimum": 1},
388 "include_hidden": {"type": "boolean", "description": "Include dotfiles and hidden entries.", "default": false},
389 "response_format": {"type": "string", "enum": ["concise", "detailed"], "description": "Verbosity of the listing output.", "default": "concise"},
390 "case_sensitive": {"type": "boolean", "description": "Case-sensitive name matching.", "default": false}
391 }
392 })
393}
394
395#[cfg(test)]
396mod tests {
397 use serde_json::json;
398
399 use super::*;
400
401 #[test]
402 fn apply_patch_parameter_schema_keeps_alias_and_guidance_consistent() {
403 let schema = apply_patch_parameter_schema("Patch in VT Code format");
404
405 assert_eq!(
409 schema["properties"]["patch"]["description"],
410 with_semantic_anchor_guidance(APPLY_PATCH_ALIAS_DESCRIPTION)
411 );
412 let patch_description = schema["properties"]["patch"]["description"]
413 .as_str()
414 .expect("patch description");
415 assert!(patch_description.contains("*** Begin Patch"));
416 assert!(patch_description.contains("unified diff"));
417 assert!(patch_description.contains(SEMANTIC_ANCHOR_GUIDANCE));
418
419 let input_description = schema["properties"]["input"]["description"]
420 .as_str()
421 .expect("input description");
422 assert!(input_description.contains(SEMANTIC_ANCHOR_GUIDANCE));
423 }
424
425 #[test]
426 fn search_tools_schema_documents_limit_and_detail_level_defaults() {
427 let schema = search_tools_parameters();
428 let limit = &schema["properties"]["limit"];
429 assert_eq!(limit["default"], json!(5));
430 assert_eq!(limit["maximum"], json!(25));
431 let limit_description = limit["description"].as_str().expect("limit description");
432 assert!(limit_description.contains("default: 5"));
433 assert!(limit_description.contains("max: 25"));
434
435 let detail_level = &schema["properties"]["detail_level"];
436 assert_eq!(detail_level["default"], json!("name_description"));
437 let detail_description = detail_level["description"].as_str().expect("detail_level description");
438 for level in ["name", "name_description", "full"] {
439 assert!(detail_description.contains(level), "{level}");
440 }
441
442 assert!(SEARCH_TOOLS_DESCRIPTION.contains("deferred"));
443 assert!(SEARCH_TOOLS_DESCRIPTION.contains("next request"));
444 assert!(SEARCH_TOOLS_DESCRIPTION.contains("MCP"));
445 assert!(SEARCH_TOOLS_DESCRIPTION.contains("not needed"));
446 }
447
448 #[test]
449 fn apply_patch_tool_description_leads_with_format_and_stays_calm() {
450 assert!(APPLY_PATCH_TOOL_DESCRIPTION.starts_with("Apply a patch in VT Code format (*** Begin Patch"));
451 assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("unified diffs"));
452 assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("workspace-relative"));
453 assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("permission checks"));
454 assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("JSON calls use input (patch is an alias)"));
455 assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("preserving internal whitespace"));
456 assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("one fresh bounded file read range"));
457 for description in [
458 APPLY_PATCH_TOOL_DESCRIPTION,
459 APPLY_PATCH_ALIAS_DESCRIPTION,
460 DEFAULT_APPLY_PATCH_INPUT_DESCRIPTION,
461 ] {
462 assert!(!description.contains("IMPORTANT"), "{description}");
463 assert!(!description.contains("NOT"), "{description}");
464 assert!(!description.contains("never"), "{description}");
465 }
466 }
467
468 #[test]
469 fn common_output_limit_parameter_preserves_strict_schema() {
470 let schema = with_max_output_tokens_parameter(json!({
471 "type": "object",
472 "properties": {"query": {"type": "string"}},
473 "additionalProperties": false
474 }));
475 assert_eq!(schema["additionalProperties"], json!(false));
476 assert_eq!(schema["properties"]["max_output_tokens"]["default"], json!(DEFAULT_MAX_OUTPUT_TOKENS));
477 assert_eq!(schema["properties"]["max_output_tokens"]["minimum"], json!(MIN_MAX_OUTPUT_TOKENS));
478 assert_eq!(schema["properties"]["max_output_tokens"]["maximum"], json!(MAX_MAX_OUTPUT_TOKENS));
479 }
480
481 #[test]
482 fn codex_baseline_exec_schemas_use_public_names_shape() {
483 let exec_params = exec_command_parameters();
484 assert_eq!(exec_params["required"], json!(["cmd"]));
485 assert!(exec_params["properties"]["cmd"].is_object());
486 assert!(exec_params["properties"]["workdir"].is_object());
487 assert!(
488 exec_params["properties"]["yield_time_ms"]["description"]
489 .as_str()
490 .expect("exec yield description")
491 .contains("session_id")
492 );
493 assert!(
494 exec_params["properties"]["yield_time_ms"]["description"]
495 .as_str()
496 .expect("exec yield description")
497 .contains("single-call long run")
498 );
499 assert!(
500 exec_params["properties"]["max_output_tokens"]["description"]
501 .as_str()
502 .expect("exec max output description")
503 .contains("spool_path")
504 );
505 assert_eq!(exec_params["properties"]["tty"]["type"], "boolean");
506 assert_eq!(exec_params["properties"]["tty"]["default"], false);
507 assert_eq!(exec_params["properties"]["background"]["type"], "boolean");
508 assert_eq!(exec_params["properties"]["background"]["default"], false);
509 assert_eq!(exec_params["properties"]["yield_time_ms"]["default"], 10000);
510 assert_eq!(
511 exec_params["properties"]["sandbox_permissions"]["enum"],
512 json!([
513 "use_default",
514 "with_additional_permissions",
515 "require_escalated",
516 "bypass_sandbox"
517 ])
518 );
519 assert_eq!(exec_params["properties"]["sandbox_permissions"]["default"], "use_default");
520 assert_eq!(
521 exec_params["properties"]["additional_permissions"]["properties"]["fs_read"]["items"]["type"],
522 "string"
523 );
524 assert_eq!(
525 exec_params["properties"]["additional_permissions"]["properties"]["fs_write"]["items"]["type"],
526 "string"
527 );
528 assert_eq!(exec_params["properties"]["additional_permissions"]["additionalProperties"], false);
529 assert_eq!(exec_params["properties"]["justification"]["type"], "string");
530 assert!(
531 exec_params["properties"]["sandbox_permissions"]["description"]
532 .as_str()
533 .expect("sandbox_permissions description")
534 .contains("normalized to `with_additional_permissions`")
535 );
536 assert!(
537 exec_params["properties"]["additional_permissions"]["description"]
538 .as_str()
539 .expect("additional_permissions description")
540 .contains("allowed workspace or temp roots")
541 );
542 assert!(
543 exec_params["properties"]["justification"]["description"]
544 .as_str()
545 .expect("justification description")
546 .contains("Required when sandbox_permissions is `require_escalated` or `bypass_sandbox`")
547 );
548 assert_eq!(exec_params["additionalProperties"], false);
549 assert!(
553 exec_params["properties"]["cmd"]["description"]
554 .as_str()
555 .expect("cmd description")
556 .contains("tool description lists covered tools"),
557 "cmd description must defer the example list to the tool description"
558 );
559 for command in ["ls", "rg", "find", "cat", "sed", "awk"] {
560 assert!(
561 EXEC_COMMAND_DESCRIPTION.contains(command),
562 "{command} should be described as an exec_command example"
563 );
564 assert!(
565 exec_params["properties"].get(command).is_none(),
566 "{command} must not be modelled as a separate exec_command field"
567 );
568 }
569
570 let stdin_params = write_stdin_parameters();
571 assert_eq!(stdin_params["required"], json!(["session_id"]));
572 assert!(stdin_params["properties"]["session_id"].is_object());
573 assert_eq!(stdin_params["properties"]["chars"]["type"], "string");
574 assert_eq!(
575 stdin_params["properties"]["action"]["enum"],
576 json!(["write", "poll", "wait", "inspect", "terminate", "close"])
577 );
578 assert_eq!(exec_params["properties"]["stdin"]["default"], false);
579 assert!(stdin_params["properties"]["wait_timeout_seconds"].is_object());
580 assert!(
581 stdin_params["properties"].get("timeout_seconds").is_none(),
582 "write_stdin schema advertises only wait_timeout_seconds"
583 );
584 assert_eq!(stdin_params["anyOf"][1]["required"], json!(["action"]));
585 assert_eq!(
586 stdin_params["anyOf"][1]["properties"]["action"]["enum"],
587 json!(["poll", "wait", "inspect", "terminate", "close"])
588 );
589 assert!(
590 stdin_params["properties"]["chars"]["description"]
591 .as_str()
592 .is_some_and(|description| description.contains("empty string"))
593 );
594 assert!(stdin_params["properties"]["chars"].is_object());
595 assert!(
596 stdin_params["properties"]["yield_time_ms"]["description"]
597 .as_str()
598 .expect("stdin yield description")
599 .contains("fresh session output")
600 );
601 assert!(
602 stdin_params["properties"]["max_output_tokens"]["description"]
603 .as_str()
604 .expect("stdin max output description")
605 .contains("spool_path")
606 );
607 assert_eq!(stdin_params["additionalProperties"], false);
608 }
609
610 #[test]
611 fn mcp_description_distinguishes_server_search_from_catalog_search() {
612 assert!(MCP_DESCRIPTION.starts_with("Discover and manage Model Context Protocol capabilities."));
613 assert!(MCP_DESCRIPTION.contains("action=search_tools searches only tools exposed by configured MCP servers"));
614 assert!(MCP_DESCRIPTION.contains("the separate search_tools tool searches the whole session catalog"));
615 }
616
617 #[test]
618 fn agent_description_routes_shell_processes_to_exec_command() {
619 assert!(AGENT_DESCRIPTION.starts_with("Spawn and steer delegated child agents."));
620 assert!(AGENT_DESCRIPTION.contains("spawn_subprocess runs a subagent defined with background: true"));
621 assert!(AGENT_DESCRIPTION.contains("go through exec_command, with background=true"));
622 let action = agent_parameters()["properties"]["action"]["description"]
623 .as_str()
624 .unwrap_or_default()
625 .to_string();
626 assert!(!action.contains("daemons"), "{action}");
627 }
628
629 #[test]
630 fn exec_command_description_states_edit_routing_and_escalation_rules() {
631 assert!(EXEC_COMMAND_DESCRIPTION.starts_with("Run a shell command through the active sandbox policy"));
632 assert!(EXEC_COMMAND_DESCRIPTION.contains("For file edits, use apply_patch"));
633 assert!(EXEC_COMMAND_DESCRIPTION.contains("approval check"));
634 assert!(
638 !EXEC_COMMAND_DESCRIPTION.contains("non-empty justification"),
639 "justification requirement belongs to the field description"
640 );
641 for mode in ["require_escalated", "bypass_sandbox"] {
642 assert!(
643 exec_command_parameters()["properties"]["sandbox_permissions"]["enum"]
644 .as_array()
645 .expect("sandbox_permissions enum")
646 .iter()
647 .any(|value| value == mode),
648 "{mode} must stay a real sandbox_permissions value"
649 );
650 }
651 }
652
653 #[test]
654 fn code_search_schema_exposes_exact_five_property_contract() {
655 let params = code_search_parameters();
656 let properties = params["properties"].as_object().expect("properties");
657 let mut property_names = properties.keys().map(String::as_str).collect::<Vec<_>>();
658 property_names.sort_unstable();
659
660 assert_eq!(params["required"], json!(["query"]));
661 assert_eq!(property_names, ["file_types", "max_results", "path", "query", "result_types"]);
662 assert_eq!(params["additionalProperties"], false);
663 assert_eq!(params["properties"]["query"]["pattern"], "\\S");
664 assert_eq!(params["properties"]["file_types"]["minItems"], 1);
665 assert_eq!(params["properties"]["result_types"]["minItems"], 1);
666 assert_eq!(
667 params["properties"]["result_types"]["items"]["enum"],
668 json!(["definition", "usage", "text", "path"])
669 );
670 assert_eq!(params["properties"]["max_results"]["minimum"], 1);
671 assert_eq!(params["properties"]["max_results"]["maximum"], 100);
672 assert!(params.get("anyOf").is_none());
673 }
674
675 #[test]
676 fn legacy_list_files_schema_exposes_pagination_fields() {
677 let list_params = list_files_parameters();
678 assert!(list_params["properties"]["page"].is_object());
679 assert!(list_params["properties"]["per_page"].is_object());
680 assert!(
681 list_params["properties"]["mode"]["enum"]
682 .as_array()
683 .expect("mode enum")
684 .iter()
685 .any(|value| value == "recursive")
686 );
687 }
688
689 #[test]
690 fn semantic_anchor_guidance_is_appended_once() {
691 let base = "Patch in VT Code format.";
692 let with_guidance = with_semantic_anchor_guidance(base);
693
694 assert!(with_guidance.contains(SEMANTIC_ANCHOR_GUIDANCE));
695 assert_eq!(with_semantic_anchor_guidance(&with_guidance), with_guidance);
696 }
697
698 #[test]
699 fn default_apply_patch_parameters_keep_expected_alias_shape() {
700 let schema = apply_patch_parameters();
701
702 assert_eq!(
703 schema["anyOf"],
704 json!([
705 {"required": ["input"]},
706 {"required": ["patch"]}
707 ])
708 );
709 }
710}