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 goal;
15mod json_schema;
16mod matrix;
17#[cfg(feature = "mcp")]
18mod mcp_tool;
19mod responses_api;
20mod tool_kind;
21
22pub use collaboration::{
23 AGENT_DESCRIPTION, ANSWER_SESSION_DESCRIPTION, ASK_SESSION_DESCRIPTION, LIST_SESSIONS_DESCRIPTION,
24 SUBAGENT_REASONING_EFFORT_VALUES, agent_parameters, answer_session_parameters, ask_session_parameters,
25 close_agent_parameters, list_sessions_parameters, request_user_input_description, request_user_input_parameters,
26 resume_agent_parameters, send_input_parameters, spawn_agent_parameters, spawn_background_subprocess_parameters,
27 wait_agent_parameters,
28};
29pub use goal::{get_goal_description, get_goal_parameters, update_goal_description, update_goal_parameters};
30pub use json_schema::{AdditionalProperties, JsonSchema, parse_tool_input_schema};
31pub use matrix::{MATRIX_DESCRIPTION, matrix_parameters};
32#[cfg(feature = "mcp")]
33pub use mcp_tool::{
34 MCP_UI_EXTENSION_ID, MCP_UI_RESOURCE_MIME_TYPE, MCP_UI_RESOURCE_SCHEME, McpToolVisibility, McpUiResourceMeta,
35 McpUiToolMeta, ParsedMcpTool, parse_mcp_tool, parse_ui_resource_meta,
36};
37pub use responses_api::{FreeformTool, FreeformToolFormat, ResponsesApiTool};
38pub(crate) use tool_kind::{CanonicalToolMeta, TokenBucket, ToolKind, ToolNamespace};
39
40pub const SEMANTIC_ANCHOR_GUIDANCE: &str =
41 "Prefer stable semantic @@ anchors such as function, class, method, or impl names.";
42
43pub const APPLY_PATCH_ALIAS_DESCRIPTION: &str = "Alias for 'input': same VT Code patch envelope (*** Begin Patch … *** End Patch); unified diffs (---/+++ format) are rejected.";
51pub 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.";
52pub 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. Inspect relevant hunks and anchors, including docs; edit a bounded region, refresh after mismatch, then verify. Strict inspection requires retained source; warn mode is advisory. *** 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 require 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.";
58
59pub const DEFAULT_MAX_OUTPUT_TOKENS: usize = 10_000;
61
62pub fn record_decision_parameters() -> Value {
64 serde_json::json!({"type":"object","additionalProperties":false,"required":["summary","rationale"],"properties":{
65 "summary":{"type":"string","minLength":1,"maxLength":240},
66 "rationale":{"type":"string","minLength":1,"maxLength":1000},
67 "alternatives":{"type":"array","maxItems":3,"items":{"type":"string","maxLength":1000}},
68 "evidence_ids":{"type":"array","maxItems":8,"items":{"type":"string","minLength":1,"maxLength":240}}
69 }})
70}
71pub const MIN_MAX_OUTPUT_TOKENS: usize = 1;
73pub const MAX_MAX_OUTPUT_TOKENS: usize = 50_000;
75pub const MAX_OUTPUT_TOKENS_FIELD: &str = "max_output_tokens";
80
81#[must_use]
87pub fn with_max_output_tokens_parameter(mut schema: Value) -> Value {
88 let Some(schema_object) = schema.as_object_mut() else {
89 return schema;
90 };
91 let properties = schema_object
92 .entry("properties")
93 .or_insert_with(|| Value::Object(serde_json::Map::new()));
94 let Some(properties_object) = properties.as_object_mut() else {
95 return schema;
96 };
97 {
98 let _entry = properties_object.entry(MAX_OUTPUT_TOKENS_FIELD).or_insert_with(|| {
99 json!({
100 "type": "integer",
101 "minimum": MIN_MAX_OUTPUT_TOKENS,
102 "maximum": MAX_MAX_OUTPUT_TOKENS,
103 "default": DEFAULT_MAX_OUTPUT_TOKENS,
104 "description": "Maximum number of result tokens returned to the model. Full oversized output is spooled when available."
105 })
106 });
107 }
108 schema
109}
110
111#[must_use]
112pub fn with_semantic_anchor_guidance(base: &str) -> String {
113 let trimmed = base.trim_end();
114 if trimmed.contains(SEMANTIC_ANCHOR_GUIDANCE) {
115 trimmed.to_string()
116 } else if trimmed.ends_with('.') {
117 format!("{trimmed} {SEMANTIC_ANCHOR_GUIDANCE}")
118 } else {
119 format!("{trimmed}. {SEMANTIC_ANCHOR_GUIDANCE}")
120 }
121}
122
123#[must_use]
124pub fn apply_patch_parameter_schema(input_description: &str) -> Value {
125 json!({
126 "type": "object",
127 "properties": {
128 "input": {
129 "type": "string",
130 "description": with_semantic_anchor_guidance(input_description)
131 },
132 "patch": {
133 "type": "string",
134 "description": with_semantic_anchor_guidance(APPLY_PATCH_ALIAS_DESCRIPTION)
135 }
136 },
137 "anyOf": [
138 {"required": ["input"]},
139 {"required": ["patch"]}
140 ]
141 })
142}
143
144#[must_use]
145pub fn apply_patch_parameters() -> Value {
146 apply_patch_parameter_schema(DEFAULT_APPLY_PATCH_INPUT_DESCRIPTION)
147}
148
149#[must_use]
150pub fn cron_parameters() -> Value {
151 json!({
152 "type": "object",
153 "required": ["action"],
154 "additionalProperties": false,
155 "properties": {
156 "action": {
157 "type": "string",
158 "enum": ["create", "list", "delete"],
159 "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."
160 },
161 "prompt": {"type": "string", "description": "create: prompt to run when the task fires."},
162 "name": {"type": "string", "description": "create: optional short label for the task."},
163 "cron": {"type": "string", "description": "create: five-field cron expression for recurring tasks."},
164 "delay_minutes": {"type": "integer", "description": "create: fixed recurring interval in minutes."},
165 "run_at": {"type": "string", "description": "create: one-shot fire time in RFC3339 or local datetime form."},
166 "id": {"type": "string", "description": "delete: session scheduled task id to delete."}
167 }
168 })
169}
170
171pub 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.";
175
176#[must_use]
177pub fn mcp_parameters() -> Value {
178 json!({
179 "type": "object",
180 "required": ["action"],
181 "properties": {
182 "action": {
183 "type": "string",
184 "enum": ["search_tools", "get_tool_details", "list_servers", "connect", "disconnect"],
185 "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."
186 },
187 "query": {"type": "string", "description": "search_tools: natural language query describing the MCP capability to find."},
188 "detail_level": {"type": "string", "enum": ["name", "name_description", "full"], "description": "search_tools: response detail level."},
189 "limit": {"type": "integer", "minimum": 1, "maximum": 25, "description": "search_tools: maximum number of results to return."},
190 "name": {"type": "string", "description": "get_tool_details: exact MCP tool name. connect or disconnect: configured MCP server name."}
191 },
192 "additionalProperties": false
193 })
194}
195
196#[must_use]
197pub fn cron_create_parameters() -> Value {
198 json!({
199 "type": "object",
200 "required": ["prompt"],
201 "additionalProperties": false,
202 "properties": {
203 "prompt": {"type": "string", "description": "Prompt to run when the task fires."},
204 "name": {"type": "string", "description": "Optional short label for the task."},
205 "cron": {"type": "string", "description": "Five-field cron expression for recurring tasks."},
206 "delay_minutes": {"type": "integer", "description": "Fixed recurring interval in minutes."},
207 "run_at": {
208 "type": "string",
209 "description": "One-shot fire time in RFC3339 or local datetime form. Use this instead of `cron` or `delay_minutes` for reminders."
210 }
211 }
212 })
213}
214
215#[must_use]
216pub fn cron_list_parameters() -> Value {
217 json!({
218 "type": "object",
219 "properties": {},
220 "additionalProperties": false
221 })
222}
223
224#[must_use]
225pub fn cron_delete_parameters() -> Value {
226 json!({
227 "type": "object",
228 "required": ["id"],
229 "properties": {
230 "id": {"type": "string", "description": "Session scheduled task id to delete."}
231 }
232 })
233}
234
235pub 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. Inspect current target source before edits, then verify the bounded change. 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.";
238
239#[must_use]
240pub fn exec_command_parameters() -> Value {
241 json!({
242 "type": "object",
243 "required": ["cmd"],
244 "properties": {
245 "cmd": {"type": "string", "description": "Shell command to execute, subject to command policy. The tool description lists covered tools."},
246 "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},
247 "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},
248 "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},
249 "monitor_filter": {"type": "string", "description": "Optional case-sensitive substring filter for pipe runs; rejected for tty runs. Matching output lines accumulate into a bounded monitor_digest on run/wait/poll responses so long quiet commands cost no full-output polls. At most 256 characters."},
250 "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."},
251 "workdir": {"type": "string", "description": "Working directory."},
252 "tty": {"type": "boolean", "description": "Run the command in PTY mode for interactive or terminal-sensitive commands.", "default": false},
253 "sandbox_permissions": {
254 "type": "string",
255 "enum": ["use_default", "with_additional_permissions", "require_escalated", "bypass_sandbox"],
256 "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`.",
257 "default": "use_default"
258 },
259 "additional_permissions": {
260 "type": "object",
261 "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.",
262 "properties": {
263 "fs_read": {"type": "array", "items": {"type": "string"}},
264 "fs_write": {"type": "array", "items": {"type": "string"}}
265 },
266 "additionalProperties": false
267 },
268 "justification": {"type": "string", "description": "Short approval question for expanded sandbox scope. Required when sandbox_permissions is `require_escalated` or `bypass_sandbox`."}
269 },
270 "additionalProperties": false
271 })
272}
273
274pub 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.";
276
277#[must_use]
278pub fn write_stdin_parameters() -> Value {
279 json!({
280 "type": "object",
281 "required": ["session_id"],
282 "properties": {
283 "session_id": {"type": "string", "description": "Active execution session id copied verbatim from the run response."},
284 "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."},
285 "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)."},
286 "yield_time_ms": {"type": "integer", "description": "Wait before returning fresh session output (ms).", "default": 1000},
287 "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. Explicit wait time is excluded from the per-turn wall-clock budget."},
288 "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."}
289 },
290 "anyOf": [
291 {"required": ["chars"]},
292 {"required": ["action"], "properties": {"action": {"enum": ["poll", "wait", "inspect", "terminate", "close"]}}}
293 ],
294 "additionalProperties": false
295 })
296}
297
298pub 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.";
300
301#[must_use]
302pub fn search_tools_parameters() -> Value {
303 with_max_output_tokens_parameter(json!({
304 "type": "object",
305 "required": ["query"],
306 "properties": {
307 "query": {
308 "type": "string",
309 "minLength": 1,
310 "description": "Natural-language description of the capability to discover."
311 },
312 "limit": {
313 "type": "integer",
314 "minimum": 1,
315 "maximum": 25,
316 "default": 5,
317 "description": "Maximum number of ranked matches to return (default: 5, max: 25)."
318 },
319 "detail_level": {
320 "type": "string",
321 "enum": ["name", "name_description", "full"],
322 "default": "name_description",
323 "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."
324 }
325 },
326 "additionalProperties": false
327 }))
328}
329
330#[must_use]
331pub fn code_search_parameters() -> Value {
332 json!({
333 "type": "object",
334 "required": ["query"],
335 "additionalProperties": false,
336 "properties": {
337 "query": {
338 "type": "string",
339 "minLength": 1,
340 "pattern": "\\S",
341 "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."
342 },
343 "path": {
344 "type": "string",
345 "minLength": 1,
346 "pattern": "\\S",
347 "description": "Workspace-relative file or directory to search. Omit to search the workspace root."
348 },
349 "file_types": {
350 "type": "array",
351 "minItems": 1,
352 "items": {
353 "type": "string",
354 "minLength": 1,
355 "pattern": "\\S"
356 },
357 "description": "Language names or common file extensions, with or without one leading dot."
358 },
359 "result_types": {
360 "type": "array",
361 "minItems": 1,
362 "items": {
363 "type": "string",
364 "enum": ["definition", "usage", "text", "path"]
365 },
366 "description": "Result categories to include. Omit to include all four categories."
367 },
368 "max_results": {
369 "type": "integer",
370 "minimum": 1,
371 "maximum": 100,
372 "description": "Maximum number of merged results to return. Omit for 20."
373 }
374 }
375 })
376}
377
378#[must_use]
379pub fn list_files_parameters() -> Value {
380 json!({
381 "type": "object",
382 "properties": {
383 "path": {"type": "string", "description": "Directory or file path to inspect.", "default": "."},
384 "mode": {
385 "type": "string",
386 "enum": ["list", "recursive", "tree", "find_name", "find_content", "largest", "file", "files"],
387 "description": "Listing mode. Use page/per_page to continue paginated results.",
388 "default": "list"
389 },
390 "pattern": {"type": "string", "description": "Optional glob-style path filter."},
391 "name_pattern": {"type": "string", "description": "Optional name filter for list/find_name modes."},
392 "content_pattern": {"type": "string", "description": "Content query for find_content mode."},
393 "page": {"type": "integer", "description": "1-indexed results page.", "minimum": 1},
394 "per_page": {"type": "integer", "description": "Items per page.", "minimum": 1},
395 "max_results": {"type": "integer", "description": "Maximum total results to consider before pagination.", "minimum": 1},
396 "include_hidden": {"type": "boolean", "description": "Include dotfiles and hidden entries.", "default": false},
397 "response_format": {"type": "string", "enum": ["concise", "detailed"], "description": "Verbosity of the listing output.", "default": "concise"},
398 "case_sensitive": {"type": "boolean", "description": "Case-sensitive name matching.", "default": false}
399 }
400 })
401}
402
403#[cfg(test)]
404mod tests {
405 use serde_json::json;
406
407 use super::*;
408
409 #[test]
410 fn apply_patch_parameter_schema_keeps_alias_and_guidance_consistent() {
411 let schema = apply_patch_parameter_schema("Patch in VT Code format");
412
413 assert_eq!(
417 schema["properties"]["patch"]["description"],
418 with_semantic_anchor_guidance(APPLY_PATCH_ALIAS_DESCRIPTION)
419 );
420 let patch_description = schema["properties"]["patch"]["description"]
421 .as_str()
422 .expect("patch description");
423 assert!(patch_description.contains("*** Begin Patch"));
424 assert!(patch_description.contains("unified diff"));
425 assert!(patch_description.contains(SEMANTIC_ANCHOR_GUIDANCE));
426
427 let input_description = schema["properties"]["input"]["description"]
428 .as_str()
429 .expect("input description");
430 assert!(input_description.contains(SEMANTIC_ANCHOR_GUIDANCE));
431 }
432
433 #[test]
434 fn search_tools_schema_documents_limit_and_detail_level_defaults() {
435 let schema = search_tools_parameters();
436 let limit = &schema["properties"]["limit"];
437 assert_eq!(limit["default"], json!(5));
438 assert_eq!(limit["maximum"], json!(25));
439 let limit_description = limit["description"].as_str().expect("limit description");
440 assert!(limit_description.contains("default: 5"));
441 assert!(limit_description.contains("max: 25"));
442
443 let detail_level = &schema["properties"]["detail_level"];
444 assert_eq!(detail_level["default"], json!("name_description"));
445 let detail_description = detail_level["description"].as_str().expect("detail_level description");
446 for level in ["name", "name_description", "full"] {
447 assert!(detail_description.contains(level), "{level}");
448 }
449
450 assert!(SEARCH_TOOLS_DESCRIPTION.contains("deferred"));
451 assert!(SEARCH_TOOLS_DESCRIPTION.contains("next request"));
452 assert!(SEARCH_TOOLS_DESCRIPTION.contains("MCP"));
453 assert!(SEARCH_TOOLS_DESCRIPTION.contains("not needed"));
454 }
455
456 #[test]
457 fn apply_patch_tool_description_leads_with_format_and_stays_calm() {
458 assert!(APPLY_PATCH_TOOL_DESCRIPTION.starts_with("Apply a patch in VT Code format (*** Begin Patch"));
459 assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("unified diffs"));
460 assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("workspace-relative"));
461 assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("permission checks"));
462 assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("JSON calls use input (patch is an alias)"));
463 assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("preserving internal whitespace"));
464 assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("one fresh bounded file read range"));
465 for description in [
466 APPLY_PATCH_TOOL_DESCRIPTION,
467 APPLY_PATCH_ALIAS_DESCRIPTION,
468 DEFAULT_APPLY_PATCH_INPUT_DESCRIPTION,
469 ] {
470 assert!(!description.contains("IMPORTANT"), "{description}");
471 assert!(!description.contains("NOT"), "{description}");
472 assert!(!description.contains("never"), "{description}");
473 }
474 }
475
476 #[test]
477 fn common_output_limit_parameter_preserves_strict_schema() {
478 let schema = with_max_output_tokens_parameter(json!({
479 "type": "object",
480 "properties": {"query": {"type": "string"}},
481 "additionalProperties": false
482 }));
483 assert_eq!(schema["additionalProperties"], json!(false));
484 assert_eq!(schema["properties"]["max_output_tokens"]["default"], json!(DEFAULT_MAX_OUTPUT_TOKENS));
485 assert_eq!(schema["properties"]["max_output_tokens"]["minimum"], json!(MIN_MAX_OUTPUT_TOKENS));
486 assert_eq!(schema["properties"]["max_output_tokens"]["maximum"], json!(MAX_MAX_OUTPUT_TOKENS));
487 }
488
489 #[test]
490 fn codex_baseline_exec_schemas_use_public_names_shape() {
491 let exec_params = exec_command_parameters();
492 assert_eq!(exec_params["required"], json!(["cmd"]));
493 assert!(exec_params["properties"]["cmd"].is_object());
494 assert!(exec_params["properties"]["workdir"].is_object());
495 assert!(
496 exec_params["properties"]["yield_time_ms"]["description"]
497 .as_str()
498 .expect("exec yield description")
499 .contains("session_id")
500 );
501 assert!(
502 exec_params["properties"]["yield_time_ms"]["description"]
503 .as_str()
504 .expect("exec yield description")
505 .contains("single-call long run")
506 );
507 assert!(
508 exec_params["properties"]["max_output_tokens"]["description"]
509 .as_str()
510 .expect("exec max output description")
511 .contains("spool_path")
512 );
513 assert_eq!(exec_params["properties"]["tty"]["type"], "boolean");
514 assert_eq!(exec_params["properties"]["tty"]["default"], false);
515 assert_eq!(exec_params["properties"]["background"]["type"], "boolean");
516 assert_eq!(exec_params["properties"]["background"]["default"], false);
517 assert_eq!(exec_params["properties"]["monitor_filter"]["type"], "string");
518 assert!(
519 exec_params["properties"]["monitor_filter"]["description"]
520 .as_str()
521 .expect("monitor_filter description")
522 .contains("monitor_digest")
523 );
524 assert_eq!(exec_params["properties"]["yield_time_ms"]["default"], 10000);
525 assert_eq!(
526 exec_params["properties"]["sandbox_permissions"]["enum"],
527 json!([
528 "use_default",
529 "with_additional_permissions",
530 "require_escalated",
531 "bypass_sandbox"
532 ])
533 );
534 assert_eq!(exec_params["properties"]["sandbox_permissions"]["default"], "use_default");
535 assert_eq!(
536 exec_params["properties"]["additional_permissions"]["properties"]["fs_read"]["items"]["type"],
537 "string"
538 );
539 assert_eq!(
540 exec_params["properties"]["additional_permissions"]["properties"]["fs_write"]["items"]["type"],
541 "string"
542 );
543 assert_eq!(exec_params["properties"]["additional_permissions"]["additionalProperties"], false);
544 assert_eq!(exec_params["properties"]["justification"]["type"], "string");
545 assert!(
546 exec_params["properties"]["sandbox_permissions"]["description"]
547 .as_str()
548 .expect("sandbox_permissions description")
549 .contains("normalized to `with_additional_permissions`")
550 );
551 assert!(
552 exec_params["properties"]["additional_permissions"]["description"]
553 .as_str()
554 .expect("additional_permissions description")
555 .contains("allowed workspace or temp roots")
556 );
557 assert!(
558 exec_params["properties"]["justification"]["description"]
559 .as_str()
560 .expect("justification description")
561 .contains("Required when sandbox_permissions is `require_escalated` or `bypass_sandbox`")
562 );
563 assert_eq!(exec_params["additionalProperties"], false);
564 assert!(
568 exec_params["properties"]["cmd"]["description"]
569 .as_str()
570 .expect("cmd description")
571 .contains("tool description lists covered tools"),
572 "cmd description must defer the example list to the tool description"
573 );
574 for command in ["ls", "rg", "find", "cat", "sed", "awk"] {
575 assert!(
576 EXEC_COMMAND_DESCRIPTION.contains(command),
577 "{command} should be described as an exec_command example"
578 );
579 assert!(
580 exec_params["properties"].get(command).is_none(),
581 "{command} must not be modelled as a separate exec_command field"
582 );
583 }
584
585 let stdin_params = write_stdin_parameters();
586 assert_eq!(stdin_params["required"], json!(["session_id"]));
587 assert!(stdin_params["properties"]["session_id"].is_object());
588 assert_eq!(stdin_params["properties"]["chars"]["type"], "string");
589 assert_eq!(
590 stdin_params["properties"]["action"]["enum"],
591 json!(["write", "poll", "wait", "inspect", "terminate", "close"])
592 );
593 assert_eq!(exec_params["properties"]["stdin"]["default"], false);
594 assert!(stdin_params["properties"]["wait_timeout_seconds"].is_object());
595 assert!(
596 stdin_params["properties"].get("timeout_seconds").is_none(),
597 "write_stdin schema advertises only wait_timeout_seconds"
598 );
599 assert_eq!(stdin_params["anyOf"][1]["required"], json!(["action"]));
600 assert_eq!(
601 stdin_params["anyOf"][1]["properties"]["action"]["enum"],
602 json!(["poll", "wait", "inspect", "terminate", "close"])
603 );
604 assert!(
605 stdin_params["properties"]["chars"]["description"]
606 .as_str()
607 .is_some_and(|description| description.contains("empty string"))
608 );
609 assert!(stdin_params["properties"]["chars"].is_object());
610 assert!(
611 stdin_params["properties"]["yield_time_ms"]["description"]
612 .as_str()
613 .expect("stdin yield description")
614 .contains("fresh session output")
615 );
616 assert!(
617 stdin_params["properties"]["max_output_tokens"]["description"]
618 .as_str()
619 .expect("stdin max output description")
620 .contains("spool_path")
621 );
622 assert_eq!(stdin_params["additionalProperties"], false);
623 }
624
625 #[test]
626 fn mcp_description_distinguishes_server_search_from_catalog_search() {
627 assert!(MCP_DESCRIPTION.starts_with("Discover and manage Model Context Protocol capabilities."));
628 assert!(MCP_DESCRIPTION.contains("action=search_tools searches only tools exposed by configured MCP servers"));
629 assert!(MCP_DESCRIPTION.contains("the separate search_tools tool searches the whole session catalog"));
630 }
631
632 #[test]
633 fn agent_description_routes_shell_processes_to_exec_command() {
634 assert!(AGENT_DESCRIPTION.starts_with("Spawn and steer delegated child agents."));
635 assert!(AGENT_DESCRIPTION.contains("spawn_subprocess runs a subagent defined with background: true"));
636 assert!(AGENT_DESCRIPTION.contains("go through exec_command, with background=true"));
637 let action = agent_parameters()["properties"]["action"]["description"]
638 .as_str()
639 .unwrap_or_default()
640 .to_string();
641 assert!(!action.contains("daemons"), "{action}");
642 }
643
644 #[test]
645 fn exec_command_description_states_edit_routing_and_escalation_rules() {
646 assert!(EXEC_COMMAND_DESCRIPTION.starts_with("Run a shell command through the active sandbox policy"));
647 assert!(EXEC_COMMAND_DESCRIPTION.contains("For file edits, use apply_patch"));
648 assert!(EXEC_COMMAND_DESCRIPTION.contains("approval check"));
649 assert!(
653 !EXEC_COMMAND_DESCRIPTION.contains("non-empty justification"),
654 "justification requirement belongs to the field description"
655 );
656 for mode in ["require_escalated", "bypass_sandbox"] {
657 assert!(
658 exec_command_parameters()["properties"]["sandbox_permissions"]["enum"]
659 .as_array()
660 .expect("sandbox_permissions enum")
661 .iter()
662 .any(|value| value == mode),
663 "{mode} must stay a real sandbox_permissions value"
664 );
665 }
666 }
667
668 #[test]
669 fn code_search_schema_exposes_exact_five_property_contract() {
670 let params = code_search_parameters();
671 let properties = params["properties"].as_object().expect("properties");
672 let mut property_names = properties.keys().map(String::as_str).collect::<Vec<_>>();
673 property_names.sort_unstable();
674
675 assert_eq!(params["required"], json!(["query"]));
676 assert_eq!(property_names, ["file_types", "max_results", "path", "query", "result_types"]);
677 assert_eq!(params["additionalProperties"], false);
678 assert_eq!(params["properties"]["query"]["pattern"], "\\S");
679 assert_eq!(params["properties"]["file_types"]["minItems"], 1);
680 assert_eq!(params["properties"]["result_types"]["minItems"], 1);
681 assert_eq!(
682 params["properties"]["result_types"]["items"]["enum"],
683 json!(["definition", "usage", "text", "path"])
684 );
685 assert_eq!(params["properties"]["max_results"]["minimum"], 1);
686 assert_eq!(params["properties"]["max_results"]["maximum"], 100);
687 assert!(params.get("anyOf").is_none());
688 }
689
690 #[test]
691 fn legacy_list_files_schema_exposes_pagination_fields() {
692 let list_params = list_files_parameters();
693 assert!(list_params["properties"]["page"].is_object());
694 assert!(list_params["properties"]["per_page"].is_object());
695 assert!(
696 list_params["properties"]["mode"]["enum"]
697 .as_array()
698 .expect("mode enum")
699 .iter()
700 .any(|value| value == "recursive")
701 );
702 }
703
704 #[test]
705 fn semantic_anchor_guidance_is_appended_once() {
706 let base = "Patch in VT Code format.";
707 let with_guidance = with_semantic_anchor_guidance(base);
708
709 assert!(with_guidance.contains(SEMANTIC_ANCHOR_GUIDANCE));
710 assert_eq!(with_semantic_anchor_guidance(&with_guidance), with_guidance);
711 }
712
713 #[test]
714 fn default_apply_patch_parameters_keep_expected_alias_shape() {
715 let schema = apply_patch_parameters();
716
717 assert_eq!(
718 schema["anyOf"],
719 json!([
720 {"required": ["input"]},
721 {"required": ["patch"]}
722 ])
723 );
724 }
725}