Skip to main content

adk_tool/code_execution/
javascript_code_tool.rs

1//! `JavaScriptCodeTool` — embedded JavaScript execution for lightweight transforms.
2//!
3//! This tool wraps the `adk-code` [`EmbeddedJsExecutor`] backend (via `boa_engine`)
4//! to run JavaScript snippets in-process. It is useful for data transforms, filtering,
5//! and lightweight scripting without requiring Docker.
6//!
7//! When the `embedded-js` feature is not enabled on `adk-code`, the tool returns
8//! a descriptive error explaining how to enable it.
9//!
10//! # Required Scopes
11//!
12//! This tool declares `["code:execute"]` as its required scope. Embedded
13//! JavaScript runs in-process with no network or filesystem access, so no
14//! elevated container or host scopes are needed.
15
16use adk_core::{Result, Tool, ToolContext};
17use async_trait::async_trait;
18use serde_json::{Value, json};
19use std::sync::Arc;
20
21/// Embedded JavaScript code execution tool.
22///
23/// Runs JavaScript snippets in-process via `boa_engine`. The code has access
24/// to an `input` variable containing the JSON input, and should `return` a
25/// value to produce structured output.
26///
27/// Requires the `embedded-js` feature on `adk-code`. Without it, the tool
28/// returns a descriptive error.
29///
30/// # Required Scopes
31///
32/// Returns `["code:execute"]`. No elevated scopes needed.
33///
34/// # Example
35///
36/// ```rust
37/// use adk_tool::{JavaScriptCodeTool, Tool};
38///
39/// let tool = JavaScriptCodeTool::new();
40/// assert_eq!(tool.name(), "javascript_code");
41/// assert_eq!(tool.required_scopes(), &["code:execute"]);
42/// ```
43pub struct JavaScriptCodeTool {
44    _private: (),
45}
46
47impl JavaScriptCodeTool {
48    /// Create a new `JavaScriptCodeTool`.
49    pub fn new() -> Self {
50        Self { _private: () }
51    }
52}
53
54impl Default for JavaScriptCodeTool {
55    fn default() -> Self {
56        Self::new()
57    }
58}
59
60#[async_trait]
61impl Tool for JavaScriptCodeTool {
62    fn name(&self) -> &str {
63        "javascript_code"
64    }
65
66    fn description(&self) -> &str {
67        "Execute JavaScript for lightweight transforms and scripting. \
68         Uses an embedded JS engine with no network or filesystem access. \
69         Access input data via the `input` variable and use `return` to produce output. \
70         Example: return input.items.filter(x => x.price > 10);"
71    }
72
73    fn required_scopes(&self) -> &[&str] {
74        &["code:execute"]
75    }
76
77    fn parameters_schema(&self) -> Option<Value> {
78        Some(json!({
79            "type": "object",
80            "properties": {
81                "code": {
82                    "type": "string",
83                    "description": "JavaScript source code to execute. Use `input` to access JSON input and `return` to produce output."
84                },
85                "input": {
86                    "description": "Optional JSON value passed as the `input` variable."
87                }
88            },
89            "required": ["code"]
90        }))
91    }
92
93    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
94        let code = match args.get("code").and_then(Value::as_str) {
95            Some(c) => c.to_string(),
96            None => {
97                return Ok(json!({
98                    "status": "rejected",
99                    "stdout": "",
100                    "stderr": "missing required field: code",
101                    "output": null,
102                    "exitCode": null,
103                    "durationMs": 0,
104                }));
105            }
106        };
107
108        let input = args.get("input").cloned();
109
110        execute_js(code, input).await
111    }
112}
113
114/// Execute JavaScript using EmbeddedJsExecutor when the feature is available.
115#[cfg(feature = "code-embedded-js")]
116async fn execute_js(code: String, input: Option<Value>) -> Result<Value> {
117    use adk_code::{
118        CodeExecutor, EmbeddedJsExecutor, ExecutionLanguage, ExecutionPayload, ExecutionRequest,
119        SandboxPolicy,
120    };
121
122    let executor = EmbeddedJsExecutor::new();
123    let request = ExecutionRequest {
124        language: ExecutionLanguage::JavaScript,
125        payload: ExecutionPayload::Source { code },
126        argv: vec![],
127        stdin: None,
128        input,
129        sandbox: SandboxPolicy::strict_js(),
130        identity: None,
131    };
132
133    match executor.execute(request).await {
134        Ok(result) => Ok(json!({
135            "status": result.status,
136            "stdout": result.stdout,
137            "stderr": result.stderr,
138            "output": result.output,
139            "exitCode": result.exit_code,
140            "durationMs": result.duration_ms,
141        })),
142        Err(e) => Ok(json!({
143            "status": "failed",
144            "stdout": "",
145            "stderr": e.to_string(),
146            "output": null,
147            "exitCode": null,
148            "durationMs": 0,
149        })),
150    }
151}
152
153/// Fallback when embedded-js feature is not enabled.
154#[cfg(not(feature = "code-embedded-js"))]
155async fn execute_js(_code: String, _input: Option<Value>) -> Result<Value> {
156    Ok(json!({
157        "status": "rejected",
158        "stdout": "",
159        "stderr": "JavaScript execution requires the 'embedded-js' feature. \
160                   Enable it with: adk-code = { features = [\"embedded-js\"] }",
161        "output": null,
162        "exitCode": null,
163        "durationMs": 0,
164    }))
165}