1use serde::{Deserialize, Serialize};
2
3#[cfg(feature = "schemars")]
4use schemars::{schema_for, JsonSchema};
5#[cfg(feature = "schemars")]
6use serde_json::Value;
7
8#[cfg(feature = "schemars")]
14pub fn tool_parameters<T: JsonSchema>() -> Value {
15 let mut v = serde_json::to_value(schema_for!(T)).expect("can't parse value from schema");
16
17 if let Some(value) = v.as_object_mut() {
19 value.remove("$schema");
20 value.remove("title");
21 }
22
23 let mut v_str = serde_json::to_string(&v).unwrap();
24 v_str = v_str
25 .replace("/definitions/", "/$defs/")
26 .replace("\"definitions\":", "\"$defs\":");
27
28 v_str = v_str.replace("\"oneOf\":", "\"anyOf\":");
30
31 let mut v: Value = serde_json::from_str(&v_str).expect("can't parse value from updated schema");
32 enforce_openai_strict_schema(&mut v);
33 v
34}
35
36#[cfg(feature = "schemars")]
37fn enforce_openai_strict_schema(v: &mut Value) {
38 match v {
39 Value::Object(map) => {
40 for (_k, child) in map.iter_mut() {
42 enforce_openai_strict_schema(child);
43 }
44
45 let is_object = map
47 .get("type")
48 .and_then(|t| t.as_str())
49 .is_some_and(|t| t == "object");
50 let has_props = map.get("properties").is_some();
51 if is_object || has_props {
52 map.entry("additionalProperties".to_string())
53 .or_insert(Value::Bool(false));
54
55 if let Some(Value::Object(props)) = map.get("properties") {
56 let mut keys: Vec<String> = props.keys().cloned().collect();
57 keys.sort();
58 map.insert(
59 "required".to_string(),
60 Value::Array(keys.into_iter().map(Value::String).collect()),
61 );
62 }
63 }
64 }
65 Value::Array(arr) => {
66 for child in arr.iter_mut() {
67 enforce_openai_strict_schema(child);
68 }
69 }
70 _ => {}
71 }
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
75#[cfg_attr(feature = "schemars", derive(JsonSchema))]
76pub struct ReadFileArgs {
77 pub path: String,
79 pub offset: Option<usize>,
81 pub limit: Option<usize>,
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize)]
86#[cfg_attr(feature = "schemars", derive(JsonSchema))]
87pub struct ListDirArgs {
88 pub path: String,
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
93#[cfg_attr(feature = "schemars", derive(JsonSchema))]
94#[serde(rename_all = "snake_case")]
95pub enum GlobKind {
96 Files,
97 Dirs,
98 All,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
102#[cfg_attr(feature = "schemars", derive(JsonSchema))]
103pub struct GlobArgs {
104 pub pattern: String,
106 pub path: Option<String>,
108 pub limit: Option<usize>,
110 pub kind: Option<GlobKind>,
112 #[serde(default)]
114 pub exclude: Vec<String>,
115}
116
117#[derive(Debug, Clone, Serialize, Deserialize)]
118#[cfg_attr(feature = "schemars", derive(JsonSchema))]
119pub struct GrepArgs {
120 pub pattern: String,
122 pub path: Option<String>,
124 pub glob: Option<String>,
126 pub head_limit: Option<usize>,
128}
129
130#[derive(Debug, Clone, Serialize, Deserialize)]
131#[cfg_attr(feature = "schemars", derive(JsonSchema))]
132pub struct RunShellArgs {
133 pub command: String,
135 pub cwd: Option<String>,
137 pub timeout_seconds: Option<u64>,
142 pub max_output_bytes: Option<u64>,
149 #[serde(default)]
151 pub bg: bool,
152}
153
154#[derive(Debug, Clone, Serialize, Deserialize)]
155#[cfg_attr(feature = "schemars", derive(JsonSchema))]
156pub struct ReadShellOutputArgs {
157 pub shell_id: String,
159 #[serde(default)]
161 pub from_start: bool,
162 pub offset: Option<usize>,
164 pub limit: Option<usize>,
166}
167
168#[derive(Debug, Clone, Serialize, Deserialize)]
169#[cfg_attr(feature = "schemars", derive(JsonSchema))]
170pub struct StopShellArgs {
171 pub shell_id: String,
173}
174
175#[derive(Debug, Clone, Serialize, Deserialize)]
176#[cfg_attr(feature = "schemars", derive(JsonSchema))]
177pub struct SleepArgs {
178 pub seconds: u64,
180 #[serde(default)]
183 pub shell_ids: Vec<String>,
184}
185
186#[derive(Debug, Clone, Serialize, Deserialize)]
187#[cfg_attr(feature = "schemars", derive(JsonSchema))]
188pub struct ApplyDiffArgs {
189 pub diff: String,
193}
194
195#[derive(Debug, Clone, Serialize, Deserialize)]
196#[cfg_attr(feature = "schemars", derive(JsonSchema))]
197pub struct DeleteFilesArgs {
198 pub paths: Vec<String>,
200}
201
202#[cfg(feature = "schemars")]
204pub fn openai_tools() -> Vec<Value> {
205 vec![
206 serde_json::json!({
207 "type": "function",
208 "name": "read_file",
209 "description": "Read a local file (by path), optionally with offset/limit. Returns plain text with a frontmatter block containing `path`, `offset`, `limit`, `total_lines`, `truncated`, and `returned_lines`, followed by the requested file contents.",
210 "strict": true,
211 "parameters": tool_parameters::<ReadFileArgs>(),
212 }),
213 serde_json::json!({
214 "type": "function",
215 "name": "list_dir",
216 "description": "List a local directory (by path). Returns plain text with `Path`, `Entries`, and one entry per line similar to `ls`; directories end with `/`.",
217 "strict": true,
218 "parameters": tool_parameters::<ListDirArgs>(),
219 }),
220 serde_json::json!({
221 "type": "function",
222 "name": "glob",
223 "description": "Find local file or directory paths using a glob pattern under a search root. Use this for path discovery when you need matching paths, not file contents. Returns plain text with Returned, Total, and one relative path per line.",
224 "strict": true,
225 "parameters": tool_parameters::<GlobArgs>(),
226 }),
227 serde_json::json!({
228 "type": "function",
229 "name": "grep",
230 "description": "Search for a regex pattern in files. Returns a JSON string including matches (file, line_number, line). May be truncated to head_limit.",
231 "strict": true,
232 "parameters": tool_parameters::<GrepArgs>(),
233 }),
234 serde_json::json!({
235 "type": "function",
236 "name": "run_shell",
237 "description": "Run a shell command via `bash -lc` (supports pipes/redirection). Requires user confirmation unless the client auto-approves it. Use `max_output_bytes` intentionally for foreground runs: prefer the smallest limit that answers the question, and increase only when needed. Oversize output is cut from the middle, preserving roughly the first 30% and last 70%, so large requests are rarely necessary just to inspect the tail. Set `bg=true` to start a background shell that returns immediately with a shell id. When `bg=true`, omit `timeout_seconds` and omit `max_output_bytes`.",
238 "parameters": tool_parameters::<RunShellArgs>(),
239 }),
240 serde_json::json!({
241 "type": "function",
242 "name": "read_shell_output",
243 "description": "Read captured output from a background shell started with `run_shell(bg=true)`. Output is line-oriented. By default it reads from the end; set `from_start=true` to read from the beginning.",
244 "strict": true,
245 "parameters": tool_parameters::<ReadShellOutputArgs>(),
246 }),
247 serde_json::json!({
248 "type": "function",
249 "name": "stop_shell",
250 "description": "Stop a background shell started with `run_shell(bg=true)` and discard its retained state and logs.",
251 "strict": true,
252 "parameters": tool_parameters::<StopShellArgs>(),
253 }),
254 serde_json::json!({
255 "type": "function",
256 "name": "sleep",
257 "description": "Wait for 15 to 275 seconds. Provide `shell_ids` to return early when any watched background shell exits. Use `shell_ids: []` for a plain timer.",
258 "strict": true,
259 "parameters": tool_parameters::<SleepArgs>(),
260 }),
261 serde_json::json!({
262 "type": "function",
263 "name": "apply_diff",
264 "description": "Apply a patch to the local working tree (create/update files). Use the `*** Begin Patch` / `*** Update File:` format. Returns a JSON string describing what changed or an error.",
265 "strict": true,
266 "parameters": tool_parameters::<ApplyDiffArgs>(),
267 }),
268 serde_json::json!({
269 "type": "function",
270 "name": "delete_files",
271 "description": "Delete one or more files by path (relative to project root). Returns a JSON string listing deleted and missing paths.",
272 "strict": true,
273 "parameters": tool_parameters::<DeleteFilesArgs>(),
274 }),
275 ]
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281 use serde_json::json;
282
283 #[test]
284 fn glob_args_default_exclude_to_empty_list() {
285 let args: GlobArgs = serde_json::from_value(json!({
286 "pattern": "**/*.rs",
287 "path": "src",
288 "limit": 50,
289 "kind": "files",
290 }))
291 .expect("glob args");
292
293 assert_eq!(args.pattern, "**/*.rs");
294 assert_eq!(args.path.as_deref(), Some("src"));
295 assert_eq!(args.limit, Some(50));
296 assert_eq!(args.kind, Some(GlobKind::Files));
297 assert!(args.exclude.is_empty());
298 }
299
300 #[cfg(feature = "schemars")]
301 #[test]
302 fn run_shell_tool_schema_encourages_small_output_limits() {
303 let run_shell = openai_tools()
304 .into_iter()
305 .find(|tool| tool.get("name").and_then(Value::as_str) == Some("run_shell"))
306 .expect("run_shell tool");
307
308 let description = run_shell
309 .get("description")
310 .and_then(Value::as_str)
311 .expect("run_shell description");
312 assert!(description.contains("max_output_bytes"));
313 assert!(description.contains("30%"));
314 assert!(description.contains("70%"));
315 assert!(description.contains("smallest limit"));
316 assert!(description.contains("bg=true"));
317 assert!(description.contains("omit `timeout_seconds`"));
318 assert!(description.contains("omit `max_output_bytes`"));
319
320 let timeout_description = run_shell
321 .get("parameters")
322 .and_then(|value| value.get("properties"))
323 .and_then(|value| value.get("timeout_seconds"))
324 .and_then(|value| value.get("description"))
325 .and_then(Value::as_str)
326 .expect("timeout_seconds description");
327 assert!(timeout_description.contains("30 second timeout"));
328 assert!(timeout_description.contains("model training"));
329 assert!(timeout_description.contains("safe side"));
330 assert!(timeout_description.contains("Must be omitted when `bg=true`"));
331
332 let max_output_description = run_shell
333 .get("parameters")
334 .and_then(|value| value.get("properties"))
335 .and_then(|value| value.get("max_output_bytes"))
336 .and_then(|value| value.get("description"))
337 .and_then(Value::as_str)
338 .expect("max_output_bytes description");
339 assert!(max_output_description.contains("30%"));
340 assert!(max_output_description.contains("70%"));
341 assert!(max_output_description.contains("few KB"));
342 assert!(max_output_description.contains("Must be omitted when `bg=true`"));
343
344 let properties = run_shell
345 .get("parameters")
346 .and_then(|value| value.get("properties"))
347 .and_then(Value::as_object)
348 .expect("run_shell parameters");
349 assert!(properties.contains_key("bg"));
350 }
351
352 #[cfg(feature = "schemars")]
353 #[test]
354 fn openai_tools_include_glob_tool() {
355 let glob_tool = openai_tools()
356 .into_iter()
357 .find(|tool| tool.get("name").and_then(Value::as_str) == Some("glob"))
358 .expect("glob tool");
359
360 let description = glob_tool
361 .get("description")
362 .and_then(Value::as_str)
363 .expect("glob description");
364 assert!(description.contains("path discovery"));
365 assert!(description.contains("Returned"));
366 assert!(description.contains("Total"));
367
368 let properties = glob_tool
369 .get("parameters")
370 .and_then(|value| value.get("properties"))
371 .and_then(Value::as_object)
372 .expect("glob parameters");
373 assert!(properties.contains_key("pattern"));
374 assert!(properties.contains_key("path"));
375 assert!(properties.contains_key("limit"));
376 assert!(properties.contains_key("kind"));
377 assert!(properties.contains_key("exclude"));
378 }
379
380 #[cfg(feature = "schemars")]
381 #[test]
382 fn openai_tools_describe_plaintext_file_and_directory_reads() {
383 let tools = openai_tools();
384
385 let read_file = tools
386 .iter()
387 .find(|tool| tool.get("name").and_then(Value::as_str) == Some("read_file"))
388 .expect("read_file tool");
389 let read_file_description = read_file
390 .get("description")
391 .and_then(Value::as_str)
392 .expect("read_file description");
393 assert!(read_file_description.contains("Returns plain text"));
394 assert!(read_file_description.contains("frontmatter"));
395 assert!(read_file_description.contains("returned_lines"));
396
397 let list_dir = tools
398 .iter()
399 .find(|tool| tool.get("name").and_then(Value::as_str) == Some("list_dir"))
400 .expect("list_dir tool");
401 let list_dir_description = list_dir
402 .get("description")
403 .and_then(Value::as_str)
404 .expect("list_dir description");
405 assert!(list_dir_description.contains("Returns plain text"));
406 assert!(list_dir_description.contains("Path"));
407 assert!(list_dir_description.contains("Entries"));
408 assert!(list_dir_description.contains("similar to `ls`"));
409 assert!(list_dir_description.contains("directories end with `/`"));
410 }
411
412 #[test]
413 fn background_shell_tool_args_default_to_tail_reads() {
414 let read_shell_output: ReadShellOutputArgs = serde_json::from_value(json!({
415 "shell_id": "bg_123"
416 }))
417 .expect("read_shell_output args");
418 assert_eq!(read_shell_output.shell_id, "bg_123");
419 assert!(!read_shell_output.from_start);
420 assert_eq!(read_shell_output.offset, None);
421 assert_eq!(read_shell_output.limit, None);
422
423 let run_shell: RunShellArgs = serde_json::from_value(json!({
424 "command": "echo hi"
425 }))
426 .expect("run_shell args");
427 assert_eq!(run_shell.command, "echo hi");
428 assert!(!run_shell.bg);
429
430 let sleep: SleepArgs = serde_json::from_value(json!({
431 "seconds": 30,
432 "shell_ids": ["bg_123", "bg_456"]
433 }))
434 .expect("sleep args");
435 assert_eq!(sleep.seconds, 30);
436 assert_eq!(sleep.shell_ids, vec!["bg_123", "bg_456"]);
437
438 let timer_only_sleep: SleepArgs = serde_json::from_value(json!({
439 "seconds": 15
440 }))
441 .expect("timer-only sleep args");
442 assert_eq!(timer_only_sleep.seconds, 15);
443 assert!(timer_only_sleep.shell_ids.is_empty());
444 }
445
446 #[cfg(feature = "schemars")]
447 #[test]
448 fn openai_tools_include_background_shell_tools() {
449 let tools = openai_tools();
450 let names = tools
451 .iter()
452 .filter_map(|tool| tool.get("name").and_then(Value::as_str))
453 .collect::<Vec<_>>();
454
455 assert!(names.contains(&"read_shell_output"));
456 assert!(names.contains(&"stop_shell"));
457 assert!(names.contains(&"sleep"));
458 }
459}