返回 CodeWhale
run_tool.rs
根目录 / crates / engine / src / tools / run_tool.rs
1 //! Canonical action-based wrapper for run/test/verifier tools.
2 //!
3 //! The model sees one tool: `Run` with an `action` parameter
4 //! (tests | verifiers). The per-action legacy execution aliases were removed
5 //! in v0.9.3.
6
7 use async_trait::async_trait;
8 use serde_json::{Value, json};
9
10 use super::spec::{
11 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
12 };
13 use super::test_runner::RunTestsTool;
14 use super::verifier::RunVerifiersTool;
15 use codewhale_tools::required_action;
16
17 pub struct RunTool {
18 name: &'static str,
19 }
20
21 impl RunTool {
22 pub const fn new(name: &'static str) -> Self {
23 Self { name }
24 }
25
26 const ACTIONS: &'static [&'static str] = &["tests", "verifiers"];
27 const TESTS_ALLOWED_KEYS: &'static [&'static str] =
28 &["args", "all_features", "cwd", "background", "timeout_ms"];
29 const VERIFIERS_ALLOWED_KEYS: &'static [&'static str] = &[
30 "profile",
31 "level",
32 "max_python_files",
33 "background",
34 "cwd",
35 "timeout_ms",
36 ];
37
38 fn validate_action_keys(
39 &self,
40 action: &str,
41 input: &Value,
42 allowed: &[&str],
43 ) -> Result<(), ToolError> {
44 let Some(obj) = input.as_object() else {
45 return Err(ToolError::invalid_input("Run tool input must be an object"));
46 };
47 let mut unexpected: Vec<&str> = obj
48 .keys()
49 .map(String::as_str)
50 .filter(|key| !allowed.contains(key))
51 .collect();
52 if unexpected.is_empty() {
53 return Ok(());
54 }
55 unexpected.sort_unstable();
56 Err(ToolError::invalid_input(format!(
57 "Unexpected parameter(s) for {} action \"{action}\": {}; nothing was run. Allowed keys for action \"{action}\": {}.",
58 self.name,
59 unexpected.join(", "),
60 allowed.join(", ")
61 )))
62 }
63
64 /// Policy-side resolution: approval and parallel-safety predicates cannot
65 /// fail, so a missing action resolves to the most conservative answer.
66 /// Execution does not share this fallback — see `required_action`.
67 fn resolve_action<'a>(&self, input: &'a Value) -> &'a str {
68 input
69 .get("action")
70 .and_then(Value::as_str)
71 .unwrap_or("tests")
72 }
73
74 fn required_action(&self, input: &Value) -> Result<String, ToolError> {
75 required_action(input, self.name, Self::ACTIONS)
76 }
77
78 fn strip_action(&self, input: Value) -> Result<Value, ToolError> {
79 let mut input = input;
80 if let Some(obj) = input.as_object_mut() {
81 obj.remove("action");
82 Ok(input)
83 } else {
84 Err(ToolError::invalid_input("Run tool input must be an object"))
85 }
86 }
87 }
88
89 #[async_trait]
90 impl ToolSpec for RunTool {
91 fn name(&self) -> &'static str {
92 self.name
93 }
94
95 fn model_visible(&self) -> bool {
96 self.name == "Run"
97 }
98
99 fn description(&self) -> &'static str {
100 "Run Cargo tests or repository verifier gates. Use tests for focused Rust test runs and verifiers for cross-language syntax, format, build, test, and lint gates. Tests and verifier gates auto-background after 30s by default unless background=false; verifiers with timeout_ms run in the foreground. Set background=true to detach immediately."
101 }
102
103 fn input_schema(&self) -> Value {
104 json!({
105 "type": "object",
106 "properties": {
107 "action": {
108 "type": "string",
109 "enum": ["tests", "verifiers"],
110 "description": "Action to perform"
111 },
112 "args": {
113 "type": "string",
114 "description": "Extra arguments for cargo test (action=tests)"
115 },
116 "all_features": {
117 "type": "boolean",
118 "description": "Include --all-features for cargo test (action=tests)"
119 },
120 "cwd": {
121 "type": "string",
122 "description": "Optional working directory, relative to the workspace, to run the tests or gates in. Must exist inside the workspace."
123 },
124 "profile": {
125 "type": "string",
126 "enum": ["auto", "rust", "node", "python", "go"],
127 "description": "Verifier profile (action=verifiers)"
128 },
129 "level": {
130 "type": "string",
131 "enum": ["quick", "full"],
132 "description": "Verifier level (action=verifiers)"
133 },
134 "max_python_files": {
135 "type": "integer",
136 "description": "Maximum Python files for the verifier syntax gate (action=verifiers)"
137 },
138 "background": {
139 "type": "boolean",
140 "description": "Start tests or verifier gates immediately as background jobs and return task_id(s). Omitting background waits up to 30000ms (or timeout_ms for action=tests) and auto-backgrounds what is still running, except that action=verifiers with timeout_ms runs in the foreground; set background=false to block until completion."
141 },
142 "timeout_ms": {
143 "type": "integer",
144 "minimum": 1,
145 "maximum": 1800000,
146 "description": "Wall-clock limit in milliseconds. For action=tests, foreground wait before auto-backgrounding (default 30000), or maximum blocking timeout when background=false. For action=verifiers, built-in gate timeout; setting it runs the gates in the foreground (refused when background=true)."
147 }
148 },
149 "required": ["action"]
150 })
151 }
152
153 fn capabilities(&self) -> Vec<ToolCapability> {
154 vec![ToolCapability::ExecutesCode, ToolCapability::Sandboxable]
155 }
156
157 fn approval_requirement_for(&self, _input: &Value) -> ApprovalRequirement {
158 ApprovalRequirement::Required
159 }
160
161 fn is_read_only_for(&self, _input: &Value) -> bool {
162 false
163 }
164
165 fn supports_parallel_for(&self, _input: &Value) -> bool {
166 false
167 }
168
169 fn starts_detached_for(&self, input: &Value) -> bool {
170 matches!(self.resolve_action(input), "tests" | "verifiers")
171 && input.get("background").and_then(Value::as_bool) == Some(true)
172 }
173
174 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
175 crate::tools::execution_envelope::enforce_tool_denial(context, self.name(), &input)?;
176 let action = self.required_action(&input)?;
177 let input = self.strip_action(input)?;
178
179 match action.as_str() {
180 "tests" => {
181 self.validate_action_keys(&action, &input, Self::TESTS_ALLOWED_KEYS)?;
182 RunTestsTool.execute(input, context).await
183 }
184 "verifiers" => {
185 self.validate_action_keys(&action, &input, Self::VERIFIERS_ALLOWED_KEYS)?;
186 RunVerifiersTool.execute(input, context).await
187 }
188 other => Err(ToolError::invalid_input(format!(
189 "Unknown Run action \"{other}\"; nothing was run. Pass one of: {}.",
190 Self::ACTIONS.join(", ")
191 ))),
192 }
193 }
194 }
195
196 #[cfg(test)]
197 mod tests {
198 use super::*;
199 use serde_json::json;
200 use tempfile::tempdir;
201
202 async fn err(input: Value) -> String {
203 let tmp = tempdir().expect("tempdir");
204 let ctx = ToolContext::new(tmp.path().to_path_buf());
205 RunTool::new("Run")
206 .execute(input, &ctx)
207 .await
208 .expect_err("call must be refused")
209 .to_string()
210 }
211
212 /// Defaulting here ran `cargo test` for a model that meant `verifiers`.
213 #[tokio::test]
214 async fn missing_action_does_not_silently_run_tests() {
215 let message = err(json!({"background": true})).await;
216 assert!(message.contains("requires an `action`"), "{message}");
217 assert!(message.contains("nothing was run"), "{message}");
218 assert!(message.contains("tests, verifiers"), "{message}");
219 }
220
221 #[tokio::test]
222 async fn unknown_action_names_the_actions_that_dispatch() {
223 let message = err(json!({"action": "lint"})).await;
224 assert!(message.contains("lint"), "{message}");
225 assert!(message.contains("tests, verifiers"), "{message}");
226 }
227
228 #[test]
229 fn advertised_actions_match_the_actions_that_dispatch() {
230 let schema = RunTool::new("Run").input_schema();
231 let advertised: Vec<&str> = schema["properties"]["action"]["enum"]
232 .as_array()
233 .expect("action enum")
234 .iter()
235 .map(|value| value.as_str().expect("string"))
236 .collect();
237 assert_eq!(advertised, RunTool::ACTIONS);
238 let props = schema["properties"].as_object().expect("properties");
239 for key in props.keys() {
240 if key == "action" {
241 continue;
242 }
243 assert!(
244 RunTool::TESTS_ALLOWED_KEYS.contains(&key.as_str())
245 || RunTool::VERIFIERS_ALLOWED_KEYS.contains(&key.as_str()),
246 "schema key `{key}` missing from per-action allowlists"
247 );
248 }
249 let tool = RunTool::new("Run");
250 assert!(tool.starts_detached_for(&json!({"action": "tests", "background": true})));
251 assert!(tool.starts_detached_for(&json!({"action": "verifiers", "background": true})));
252 assert!(!tool.starts_detached_for(&json!({"action": "tests"})));
253 assert!(!tool.starts_detached_for(&json!({"action": "tests", "background": false})));
254 }
255
256 #[tokio::test]
257 async fn cross_action_and_unknown_parameters_fail_loudly_without_running() {
258 let tests_err = err(json!({
259 "action": "tests",
260 "profile": "rust",
261 "level": "full",
262 "background": true,
263 "timeout_ms": 5000
264 }))
265 .await;
266 assert!(tests_err.contains("Unexpected parameter"), "{tests_err}");
267 assert!(tests_err.contains("level"), "{tests_err}");
268 assert!(tests_err.contains("profile"), "{tests_err}");
269 assert!(tests_err.contains("nothing was run"), "{tests_err}");
270 assert!(tests_err.contains("background"), "{tests_err}");
271 assert!(tests_err.contains("timeout_ms"), "{tests_err}");
272
273 let verifiers_err = err(json!({
274 "action": "verifiers",
275 "args": "--lib foo",
276 "all_features": true
277 }))
278 .await;
279 assert!(
280 verifiers_err.contains("Unexpected parameter"),
281 "{verifiers_err}"
282 );
283 assert!(verifiers_err.contains("all_features"), "{verifiers_err}");
284 assert!(verifiers_err.contains("args"), "{verifiers_err}");
285 assert!(verifiers_err.contains("nothing was run"), "{verifiers_err}");
286 assert!(verifiers_err.contains("profile"), "{verifiers_err}");
287
288 let commands_err = err(json!({
289 "action": "verifiers",
290 "commands": [{"name": "probe", "program": "true"}]
291 }))
292 .await;
293 assert!(
294 commands_err
295 .contains("Unexpected parameter(s) for Run action \"verifiers\": commands;"),
296 "{commands_err}"
297 );
298 assert!(commands_err.contains("nothing was run"), "{commands_err}");
299
300 let tool = RunTool::new("Run");
301 assert!(
302 tool.validate_action_keys(
303 "tests",
304 &json!({"args": "--lib", "background": true, "timeout_ms": 1000, "cwd": "."}),
305 RunTool::TESTS_ALLOWED_KEYS
306 )
307 .is_ok()
308 );
309 }
310 }
311
311 lines RUST