1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
|
/*
* This file is part of agent686
* Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
* SPDX-License-Identifier: GPL-3.0-or-later
* https://git.2137697.xyz/agent686
*/
pub mod fs;
pub mod shell;
use serde_json::{json, Value};
use fs::Change;
/// When a tool needs a human before it runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Approval {
/// Read-only or harmless.
Never,
/// Prompts on first use per session, then remembers.
Once,
/// Prompts on every call, no memory.
EveryCall,
}
pub fn approval(name: &str) -> Approval {
match name {
"write" | "edit" => Approval::Once,
"bash" => Approval::EveryCall,
_ => Approval::Never,
}
}
/// Returns the keys the model actually sent, quoted and bounded.
fn received_keys(args: &Value) -> String {
let Some(object) = args.as_object() else {
return "no arguments".to_string();
};
if object.is_empty() {
return "no arguments".to_string();
}
let mut keys: Vec<String> = object.keys().map(|key| format!("`{key}`")).collect();
keys.sort();
if keys.len() > 6 {
keys.truncate(6);
keys.push("…".to_string());
}
keys.join(", ")
}
/// Rejects a call that cannot run, before a human is asked to approve it.
///
/// The message has to distinguish three different failures: the argument is
/// empty, the argument is missing because the key is wrong, and the call
/// arrived with no arguments at all (usually argument loss in transit). They
/// used to share one message, which pointed callers at the wrong fix.
pub fn validate(name: &str, args: &Value) -> Result<(), String> {
let missing = |key: &str| {
if args.as_object().map(|o| o.is_empty()).unwrap_or(true) {
format!(
"the call arrived with no arguments at all, so `{key}` is missing. \
If you sent one, it was lost in transit — retry the call"
)
} else {
format!(
"missing `{key}`; received {}. The parameter is `{key}`",
received_keys(args)
)
}
};
// Must be present and non-blank.
let required_text = |key: &str| match args.get(key).and_then(|value| value.as_str()) {
Some(value) if !value.trim().is_empty() => Ok(()),
Some(_) => Err(format!("`{key}` is present but empty")),
None => Err(missing(key)),
};
// Must be present, but may be the empty string (an empty file, a deletion).
let required_string = |key: &str| match args.get(key) {
Some(Value::String(_)) => Ok(()),
Some(_) => Err(format!("`{key}` must be a string")),
None => Err(missing(key)),
};
match name {
"bash" => match args.get("cmd").or_else(|| args.get("command")) {
Some(value) if !value.as_str().unwrap_or("").trim().is_empty() => Ok(()),
Some(_) => Err("`cmd` is present but empty".into()),
None => Err(missing("cmd")),
},
"read" => required_text("path"),
"write" => {
required_text("path")?;
required_string("content")
}
"edit" => {
required_text("path")?;
required_text("old")?;
required_string("new")
}
"grep" | "glob" => required_text("pattern"),
"" => Err("the tool call arrived without a tool name; it was probably truncated in transit — retry the call".into()),
_ => Ok(()),
}
}
/// Tools that execute immediately.
pub fn run(name: &str, args: &Value, cancel: &std::sync::atomic::AtomicBool) -> Result<String, String> {
match name {
"read" => fs::read(args),
"grep" => fs::grep(args),
"glob" => fs::glob(args),
"bash" => {
let seconds = args
.get("timeout_seconds")
.and_then(|value| value.as_u64())
.unwrap_or(120)
.clamp(1, 600);
shell::bash(args, std::time::Duration::from_secs(seconds), cancel)
}
other => Err(unknown(other)),
}
}
/// Tools that produce a change needing approval before it is applied.
pub fn plan(name: &str, args: &Value) -> Result<Change, String> {
match name {
"write" => fs::plan_write(args),
"edit" => fs::plan_edit(args),
other => Err(unknown(other)),
}
}
fn unknown(name: &str) -> String {
format!("unknown tool `{name}`; available: read, write, edit, bash, grep, glob")
}
/// Static and in a fixed order, so the serialised prefix never changes.
pub fn schemas() -> Vec<Value> {
vec![
json!({
"type": "function",
"function": {
"name": "read",
"description": "Read a text file. Returns numbered lines. Read before editing.",
"parameters": {
"type": "object",
"properties": {
"path": { "type": "string", "description": "file path" },
"offset": { "type": "integer", "description": "first line, 1-based (default 1)" },
"limit": { "type": "integer", "description": "maximum lines (default and cap 2000)" }
},
"required": ["path"]
}
}
}),
json!({
"type": "function",
"function": {
"name": "write",
"description": "Create or replace a whole file. The parent directory must already exist.",
"parameters": {
"type": "object",
"properties": {
"path": { "type": "string" },
"content": { "type": "string" }
},
"required": ["path", "content"]
}
}
}),
json!({
"type": "function",
"function": {
"name": "edit",
"description": "Replace one exact occurrence of `old` with `new`. Fails if `old` is missing or appears more than once, so include enough context to be unique.",
"parameters": {
"type": "object",
"properties": {
"path": { "type": "string" },
"old": { "type": "string", "description": "exact existing text, including indentation" },
"new": { "type": "string", "description": "replacement text" }
},
"required": ["path", "old", "new"]
}
}
}),
json!({
"type": "function",
"function": {
"name": "bash",
"description": "Run a shell command. The command string is the `cmd` parameter (not `command`). Each call is a fresh shell at the working directory, so `cd` does not persist; pass cwd instead. stdout and stderr are reported in separate labelled sections when both produce output. Times out after timeout_seconds (default 120, maximum 600). Large output is truncated head+tail with an explicit marker; raise max_bytes if the match you need is in the middle.",
"parameters": {
"type": "object",
"properties": {
"cmd": { "type": "string", "description": "the shell command to run" },
"cwd": { "type": "string", "description": "working directory (default: project root)" },
"timeout_seconds": { "type": "integer", "description": "1-600, default 120" },
"max_bytes": { "type": "integer", "description": "per-stream output budget, 1024-16777216, default 81920" }
},
"required": ["cmd"]
}
}
}),
json!({
"type": "function",
"function": {
"name": "grep",
"description": "Search file contents recursively with a regular expression. Skips .git, target, node_modules and similar. Set fixed=true to match literal text instead.",
"parameters": {
"type": "object",
"properties": {
"pattern": { "type": "string", "description": "regular expression, or literal text when fixed=true" },
"path": { "type": "string", "description": "file or directory (default .)" },
"ignore_case": { "type": "boolean" },
"fixed": { "type": "boolean", "description": "treat pattern as literal text" }
},
"required": ["pattern"]
}
}
}),
json!({
"type": "function",
"function": {
"name": "glob",
"description": "List files matching a glob. Supports *, ? and ** across path segments, e.g. **/*.rs.",
"parameters": {
"type": "object",
"properties": {
"pattern": { "type": "string" },
"path": { "type": "string", "description": "directory to search (default .)" }
},
"required": ["pattern"]
}
}
}),
]
}
|