Skip to main content

adk_code/
code_tool.rs

1//! [`CodeTool`] — an [`adk_core::Tool`] implementation that dispatches
2//! to language-specific executors.
3//!
4//! Currently supports Rust via [`RustExecutor`]. Other languages return a
5//! descriptive "not yet supported" message. Errors from the executor are
6//! converted to structured JSON responses (never propagated as `ToolError`),
7//! following the same error-as-information pattern as
8//! [`SandboxTool`](adk_sandbox::SandboxTool).
9
10use std::sync::Arc;
11use std::time::Duration;
12
13use async_trait::async_trait;
14use serde_json::{Value, json};
15use tracing::{debug, instrument};
16
17use adk_core::ToolContext;
18
19use crate::error::CodeError;
20use crate::rust_executor::RustExecutor;
21
22/// Default timeout in seconds when `timeout_secs` is not provided.
23const DEFAULT_TIMEOUT_SECS: u64 = 30;
24
25/// Minimum allowed timeout in seconds.
26const MIN_TIMEOUT_SECS: u64 = 1;
27
28/// Maximum allowed timeout in seconds.
29const MAX_TIMEOUT_SECS: u64 = 300;
30
31/// Scopes required to execute this tool.
32const REQUIRED_SCOPES: &[&str] = &["code:execute", "code:execute:rust"];
33
34/// A tool that executes code through language-specific pipelines.
35///
36/// `CodeTool` wraps a [`RustExecutor`] and implements [`adk_core::Tool`],
37/// making code execution with compiler diagnostics available to LLM agents.
38/// Phase 1 supports Rust only; other languages return a descriptive error.
39///
40/// # Error Handling
41///
42/// Executor errors are **never** propagated as `ToolError`. Instead, they are
43/// converted to structured JSON with a `"status"` field. Compile errors include
44/// a `"diagnostics"` array with structured compiler output.
45///
46/// # Example
47///
48/// ```rust,ignore
49/// use adk_code::{CodeTool, RustExecutor, RustExecutorConfig};
50/// use adk_sandbox::ProcessBackend;
51/// use std::sync::Arc;
52///
53/// let backend = Arc::new(ProcessBackend::default());
54/// let executor = RustExecutor::new(backend, RustExecutorConfig::default());
55/// let tool = CodeTool::new(executor);
56/// assert_eq!(tool.name(), "code_exec");
57/// ```
58pub struct CodeTool {
59    executor: RustExecutor,
60}
61
62impl CodeTool {
63    /// Creates a new `CodeTool` wrapping the given Rust executor.
64    pub fn new(executor: RustExecutor) -> Self {
65        Self { executor }
66    }
67}
68
69/// Converts a [`CodeError`] into a structured JSON value.
70///
71/// The returned JSON always contains a `"status"` field so the agent can
72/// distinguish between different failure modes.
73fn code_error_to_json(err: &CodeError) -> Value {
74    match err {
75        CodeError::CompileError { diagnostics, stderr } => {
76            let diag_json: Vec<Value> = diagnostics
77                .iter()
78                .map(|d| {
79                    json!({
80                        "level": d.level,
81                        "message": d.message,
82                        "spans": d.spans.iter().map(|s| json!({
83                            "file_name": s.file_name,
84                            "line_start": s.line_start,
85                            "line_end": s.line_end,
86                            "column_start": s.column_start,
87                            "column_end": s.column_end,
88                        })).collect::<Vec<_>>(),
89                        "code": d.code,
90                    })
91                })
92                .collect();
93            json!({
94                "status": "compile_error",
95                "diagnostics": diag_json,
96                "stderr": stderr,
97            })
98        }
99        CodeError::DependencyNotFound { name, searched } => json!({
100            "status": "error",
101            "stderr": format!("dependency not found: {name} (searched: {searched:?})"),
102        }),
103        CodeError::Sandbox(sandbox_err) => {
104            use adk_sandbox::SandboxError;
105            match sandbox_err {
106                SandboxError::Timeout { timeout } => json!({
107                    "status": "timeout",
108                    "stderr": format!("execution timed out after {timeout:?}"),
109                    "duration_ms": timeout.as_millis() as u64,
110                }),
111                SandboxError::MemoryExceeded { limit_mb } => json!({
112                    "status": "memory_exceeded",
113                    "stderr": format!("memory limit exceeded: {limit_mb} MB"),
114                }),
115                SandboxError::ExecutionFailed(msg) => json!({
116                    "status": "error",
117                    "stderr": msg,
118                }),
119                SandboxError::InvalidRequest(msg) => json!({
120                    "status": "error",
121                    "stderr": msg,
122                }),
123                SandboxError::BackendUnavailable(msg) => json!({
124                    "status": "error",
125                    "stderr": msg,
126                }),
127                SandboxError::EnforcerFailed { enforcer, message } => json!({
128                    "status": "error",
129                    "stderr": format!("sandbox enforcer '{enforcer}' failed: {message}"),
130                }),
131                SandboxError::EnforcerUnavailable { enforcer, message } => json!({
132                    "status": "error",
133                    "stderr": format!("sandbox enforcer '{enforcer}' unavailable: {message}"),
134                }),
135                SandboxError::PolicyViolation(msg) => json!({
136                    "status": "error",
137                    "stderr": msg,
138                }),
139                other => json!({
140                    "status": "error",
141                    "stderr": other.to_string(),
142                }),
143            }
144        }
145        CodeError::InvalidCode(msg) => json!({
146            "status": "error",
147            "stderr": msg,
148        }),
149    }
150}
151
152#[async_trait]
153impl adk_core::Tool for CodeTool {
154    fn name(&self) -> &str {
155        "code_exec"
156    }
157
158    fn description(&self) -> &str {
159        "Execute Rust code through a check → build → execute pipeline. \
160         The code must provide a `fn run(input: serde_json::Value) -> serde_json::Value` \
161         entry point. Compile errors are returned as structured diagnostics."
162    }
163
164    fn required_scopes(&self) -> &[&str] {
165        REQUIRED_SCOPES
166    }
167
168    fn parameters_schema(&self) -> Option<Value> {
169        Some(json!({
170            "type": "object",
171            "properties": {
172                "language": {
173                    "type": "string",
174                    "enum": ["rust"],
175                    "description": "The programming language. Currently only \"rust\" is supported.",
176                    "default": "rust"
177                },
178                "code": {
179                    "type": "string",
180                    "description": "The Rust source code to execute. Must provide `fn run(input: serde_json::Value) -> serde_json::Value`."
181                },
182                "input": {
183                    "type": "object",
184                    "description": "Optional JSON input passed to the `run()` function via stdin."
185                },
186                "timeout_secs": {
187                    "type": "integer",
188                    "description": "Maximum execution time in seconds.",
189                    "default": DEFAULT_TIMEOUT_SECS,
190                    "minimum": MIN_TIMEOUT_SECS,
191                    "maximum": MAX_TIMEOUT_SECS
192                }
193            },
194            "required": ["code"]
195        }))
196    }
197
198    #[instrument(skip_all, fields(tool = "code_exec"))]
199    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> adk_core::Result<Value> {
200        // Parse language (optional, defaults to "rust").
201        let language = args.get("language").and_then(|v| v.as_str()).unwrap_or("rust");
202
203        if language != "rust" {
204            return Ok(json!({
205                "status": "error",
206                "stderr": format!(
207                    "unsupported language \"{language}\". Only \"rust\" is currently supported."
208                ),
209            }));
210        }
211
212        // Parse code (required).
213        let code = match args.get("code").and_then(|v| v.as_str()) {
214            Some(c) => c,
215            None => {
216                return Ok(json!({
217                    "status": "error",
218                    "stderr": "missing required field \"code\"",
219                }));
220            }
221        };
222
223        // Parse input (optional JSON value).
224        let input = args.get("input").cloned();
225
226        // Parse timeout_secs (optional, default 30).
227        let timeout_secs = args
228            .get("timeout_secs")
229            .and_then(|v| v.as_u64())
230            .unwrap_or(DEFAULT_TIMEOUT_SECS)
231            .clamp(MIN_TIMEOUT_SECS, MAX_TIMEOUT_SECS);
232
233        let timeout = Duration::from_secs(timeout_secs);
234
235        debug!(language, timeout_secs, has_input = input.is_some(), "dispatching to RustExecutor");
236
237        match self.executor.execute(code, input.as_ref(), timeout).await {
238            Ok(result) => Ok(json!({
239                "status": "success",
240                "stdout": result.display_stdout,
241                "stderr": result.exec_result.stderr,
242                "exit_code": result.exec_result.exit_code,
243                "duration_ms": result.exec_result.duration.as_millis() as u64,
244                "output": result.output,
245                "diagnostics": result.diagnostics.iter().map(|d| json!({
246                    "level": d.level,
247                    "message": d.message,
248                    "spans": d.spans.iter().map(|s| json!({
249                        "file_name": s.file_name,
250                        "line_start": s.line_start,
251                        "line_end": s.line_end,
252                        "column_start": s.column_start,
253                        "column_end": s.column_end,
254                    })).collect::<Vec<_>>(),
255                    "code": d.code,
256                })).collect::<Vec<_>>(),
257            })),
258            Err(err) => Ok(code_error_to_json(&err)),
259        }
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use crate::diagnostics::RustDiagnostic;
267    use crate::rust_executor::RustExecutorConfig;
268    use adk_core::{CallbackContext, Content, EventActions, ReadonlyContext, Tool};
269    use adk_sandbox::SandboxBackend;
270    use adk_sandbox::backend::{BackendCapabilities, EnforcedLimits};
271    use adk_sandbox::error::SandboxError;
272    use adk_sandbox::types::{ExecRequest, ExecResult, Language};
273    use std::sync::Mutex;
274    use std::time::Duration;
275
276    // -- Mock backend ----------------------------------------------------------
277
278    struct MockBackend {
279        response: Mutex<Option<Result<ExecResult, SandboxError>>>,
280    }
281
282    impl MockBackend {
283        fn success(stdout: &str) -> Self {
284            Self {
285                response: Mutex::new(Some(Ok(ExecResult {
286                    stdout: stdout.to_string(),
287                    stderr: String::new(),
288                    exit_code: 0,
289                    duration: Duration::from_millis(10),
290                }))),
291            }
292        }
293    }
294
295    #[async_trait]
296    impl SandboxBackend for MockBackend {
297        fn name(&self) -> &str {
298            "mock"
299        }
300
301        fn capabilities(&self) -> BackendCapabilities {
302            BackendCapabilities {
303                supported_languages: vec![Language::Command],
304                isolation_class: "mock".to_string(),
305                enforced_limits: EnforcedLimits {
306                    timeout: true,
307                    memory: false,
308                    network_isolation: false,
309                    filesystem_write_isolation: false,
310                    filesystem_read_isolation: false,
311                    environment_isolation: false,
312                },
313            }
314        }
315
316        async fn execute(&self, _request: ExecRequest) -> Result<ExecResult, SandboxError> {
317            self.response
318                .lock()
319                .unwrap()
320                .take()
321                .unwrap_or(Err(SandboxError::ExecutionFailed("no canned response".to_string())))
322        }
323    }
324
325    // -- Mock ToolContext -------------------------------------------------------
326
327    struct MockToolContext {
328        content: Content,
329        actions: Mutex<EventActions>,
330    }
331
332    impl MockToolContext {
333        fn new() -> Self {
334            Self { content: Content::new("user"), actions: Mutex::new(EventActions::default()) }
335        }
336    }
337
338    #[async_trait]
339    impl ReadonlyContext for MockToolContext {
340        fn invocation_id(&self) -> &str {
341            "inv-1"
342        }
343        fn agent_name(&self) -> &str {
344            "test-agent"
345        }
346        fn user_id(&self) -> &str {
347            "user"
348        }
349        fn app_name(&self) -> &str {
350            "app"
351        }
352        fn session_id(&self) -> &str {
353            "session"
354        }
355        fn branch(&self) -> &str {
356            ""
357        }
358        fn user_content(&self) -> &Content {
359            &self.content
360        }
361    }
362
363    #[async_trait]
364    impl CallbackContext for MockToolContext {
365        fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
366            None
367        }
368    }
369
370    #[async_trait]
371    impl ToolContext for MockToolContext {
372        fn function_call_id(&self) -> &str {
373            "call-1"
374        }
375        fn actions(&self) -> EventActions {
376            self.actions.lock().unwrap().clone()
377        }
378        fn set_actions(&self, actions: EventActions) {
379            *self.actions.lock().unwrap() = actions;
380        }
381        async fn search_memory(
382            &self,
383            _query: &str,
384        ) -> adk_core::Result<Vec<adk_core::MemoryEntry>> {
385            Ok(vec![])
386        }
387    }
388
389    fn ctx() -> Arc<dyn ToolContext> {
390        Arc::new(MockToolContext::new())
391    }
392
393    fn make_tool() -> CodeTool {
394        let backend = Arc::new(MockBackend::success(""));
395        let executor = RustExecutor::new(backend, RustExecutorConfig::default());
396        CodeTool::new(executor)
397    }
398
399    // -- Tests -----------------------------------------------------------------
400
401    #[test]
402    fn test_name() {
403        let tool = make_tool();
404        assert_eq!(tool.name(), "code_exec");
405    }
406
407    #[test]
408    fn test_description_is_nonempty() {
409        let tool = make_tool();
410        assert!(!tool.description().is_empty());
411    }
412
413    #[test]
414    fn test_required_scopes() {
415        let tool = make_tool();
416        assert_eq!(tool.required_scopes(), &["code:execute", "code:execute:rust"]);
417    }
418
419    #[test]
420    fn test_parameters_schema_is_valid() {
421        let tool = make_tool();
422        let schema = tool.parameters_schema().expect("schema should be Some");
423        assert_eq!(schema["type"], "object");
424        assert!(schema["properties"]["language"].is_object());
425        assert!(schema["properties"]["code"].is_object());
426        assert!(schema["properties"]["input"].is_object());
427        assert!(schema["properties"]["timeout_secs"].is_object());
428
429        let required = schema["required"].as_array().unwrap();
430        let required_strs: Vec<&str> = required.iter().map(|v| v.as_str().unwrap()).collect();
431        assert!(required_strs.contains(&"code"));
432        // language is optional (defaults to "rust")
433        assert!(!required_strs.contains(&"language"));
434    }
435
436    #[tokio::test]
437    async fn test_missing_code_field() {
438        let tool = make_tool();
439        let args = json!({ "language": "rust" });
440        let result = tool.execute(ctx(), args).await.unwrap();
441        assert_eq!(result["status"], "error");
442        assert!(result["stderr"].as_str().unwrap().contains("code"));
443    }
444
445    #[tokio::test]
446    async fn test_unsupported_language() {
447        let tool = make_tool();
448        let args = json!({ "language": "python", "code": "print('hi')" });
449        let result = tool.execute(ctx(), args).await.unwrap();
450        assert_eq!(result["status"], "error");
451        assert!(result["stderr"].as_str().unwrap().contains("python"));
452        assert!(result["stderr"].as_str().unwrap().contains("unsupported"));
453    }
454
455    #[tokio::test]
456    async fn test_missing_language_defaults_to_rust() {
457        // Without a language field, it should default to "rust" and attempt
458        // execution. The mock backend won't actually compile, but we verify
459        // it doesn't return an "unsupported language" error.
460        let tool = make_tool();
461        let args =
462            json!({ "code": "fn run(input: serde_json::Value) -> serde_json::Value { input }" });
463        let result = tool.execute(ctx(), args).await.unwrap();
464        // It will either succeed or fail with a compile/dependency error,
465        // but NOT with "unsupported language".
466        let status = result["status"].as_str().unwrap();
467        assert_ne!(status, "error_unsupported_language");
468        // The status should not mention "unsupported"
469        if status == "error" {
470            let stderr = result["stderr"].as_str().unwrap_or("");
471            assert!(!stderr.contains("unsupported language"));
472        }
473    }
474
475    #[test]
476    fn test_code_error_to_json_compile_error() {
477        let err = CodeError::CompileError {
478            diagnostics: vec![RustDiagnostic {
479                level: "error".to_string(),
480                message: "expected `;`".to_string(),
481                spans: vec![],
482                code: Some("E0308".to_string()),
483            }],
484            stderr: "error: expected `;`".to_string(),
485        };
486        let json = code_error_to_json(&err);
487        assert_eq!(json["status"], "compile_error");
488        assert!(json["diagnostics"].is_array());
489        assert_eq!(json["diagnostics"][0]["level"], "error");
490        assert_eq!(json["diagnostics"][0]["message"], "expected `;`");
491        assert_eq!(json["diagnostics"][0]["code"], "E0308");
492        assert_eq!(json["stderr"], "error: expected `;`");
493    }
494
495    #[test]
496    fn test_code_error_to_json_dependency_not_found() {
497        let err = CodeError::DependencyNotFound {
498            name: "serde_json".to_string(),
499            searched: vec!["config: /fake/path".to_string()],
500        };
501        let json = code_error_to_json(&err);
502        assert_eq!(json["status"], "error");
503        assert!(json["stderr"].as_str().unwrap().contains("serde_json"));
504    }
505
506    #[test]
507    fn test_code_error_to_json_sandbox_timeout() {
508        let err = CodeError::Sandbox(SandboxError::Timeout { timeout: Duration::from_secs(5) });
509        let json = code_error_to_json(&err);
510        assert_eq!(json["status"], "timeout");
511        assert!(json["stderr"].as_str().unwrap().contains("timed out"));
512    }
513
514    #[test]
515    fn test_code_error_to_json_invalid_code() {
516        let err = CodeError::InvalidCode("missing `fn run()` entry point".to_string());
517        let json = code_error_to_json(&err);
518        assert_eq!(json["status"], "error");
519        assert!(json["stderr"].as_str().unwrap().contains("fn run()"));
520    }
521
522    #[test]
523    fn test_code_error_to_json_sandbox_memory() {
524        let err = CodeError::Sandbox(SandboxError::MemoryExceeded { limit_mb: 128 });
525        let json = code_error_to_json(&err);
526        assert_eq!(json["status"], "memory_exceeded");
527    }
528
529    #[test]
530    fn test_code_error_to_json_sandbox_execution_failed() {
531        let err = CodeError::Sandbox(SandboxError::ExecutionFailed("boom".into()));
532        let json = code_error_to_json(&err);
533        assert_eq!(json["status"], "error");
534        assert_eq!(json["stderr"], "boom");
535    }
536}