Skip to main content

adk_tool/code_execution/
frontend_code_tool.rs

1//! `FrontendCodeTool` — container-backed frontend code execution preset.
2//!
3//! This tool provides named presets (e.g., [`FrontendCodeTool::react`]) for
4//! frontend code execution in isolated containers.
5//!
6//! # Required Scopes
7//!
8//! This tool declares `["code:execute", "code:execute:container"]` as
9//! required scopes.
10
11use adk_code::{
12    CodeExecutor, ContainerCommandExecutor, ContainerConfig, ExecutionLanguage, ExecutionPayload,
13    ExecutionRequest, SandboxPolicy,
14};
15use adk_core::{Result, Tool, ToolContext};
16use async_trait::async_trait;
17use serde_json::{Value, json};
18use std::sync::Arc;
19
20/// Container-backed frontend code execution tool.
21///
22/// # Required Scopes
23///
24/// Returns `["code:execute", "code:execute:container"]`.
25///
26/// # Example
27///
28/// ```rust
29/// use adk_tool::{FrontendCodeTool, Tool};
30/// use std::sync::Arc;
31///
32/// let tool = Arc::new(FrontendCodeTool::react());
33/// assert_eq!(tool.name(), "frontend_code");
34/// assert_eq!(tool.required_scopes(), &["code:execute", "code:execute:container"]);
35/// ```
36pub struct FrontendCodeTool {
37    framework: String,
38    executor: Arc<dyn CodeExecutor>,
39}
40
41impl FrontendCodeTool {
42    /// React/TypeScript frontend preset using a Node.js container.
43    pub fn react() -> Self {
44        Self {
45            framework: "react".to_string(),
46            executor: Arc::new(ContainerCommandExecutor::new(ContainerConfig {
47                default_image: "node:20-slim".to_string(),
48                ..ContainerConfig::default()
49            })),
50        }
51    }
52
53    /// Generic frontend preset with a custom framework label.
54    pub fn new(framework: impl Into<String>) -> Self {
55        Self {
56            framework: framework.into(),
57            executor: Arc::new(ContainerCommandExecutor::new(ContainerConfig {
58                default_image: "node:20-slim".to_string(),
59                ..ContainerConfig::default()
60            })),
61        }
62    }
63
64    /// Create with a custom executor (e.g., `DockerExecutor` for persistent containers).
65    pub fn with_executor(framework: impl Into<String>, executor: Arc<dyn CodeExecutor>) -> Self {
66        Self { framework: framework.into(), executor }
67    }
68
69    /// Create with a custom CLI container configuration.
70    pub fn with_config(framework: impl Into<String>, config: ContainerConfig) -> Self {
71        Self {
72            framework: framework.into(),
73            executor: Arc::new(ContainerCommandExecutor::new(config)),
74        }
75    }
76
77    /// The framework label for this preset.
78    pub fn framework(&self) -> &str {
79        &self.framework
80    }
81}
82
83#[async_trait]
84impl Tool for FrontendCodeTool {
85    fn name(&self) -> &str {
86        "frontend_code"
87    }
88
89    fn description(&self) -> &str {
90        "Execute frontend code in an isolated container. \
91         Suitable for React, Vue, and other frontend framework tasks."
92    }
93
94    fn required_scopes(&self) -> &[&str] {
95        &["code:execute", "code:execute:container"]
96    }
97
98    fn parameters_schema(&self) -> Option<Value> {
99        Some(json!({
100            "type": "object",
101            "properties": {
102                "code": {
103                    "type": "string",
104                    "description": "Frontend source code to execute."
105                },
106                "input": {
107                    "description": "Optional JSON input."
108                }
109            },
110            "required": ["code"]
111        }))
112    }
113
114    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
115        let code = args["code"]
116            .as_str()
117            .ok_or_else(|| adk_core::AdkError::tool("missing 'code' parameter"))?
118            .to_string();
119
120        let input = args.get("input").cloned();
121
122        let request = ExecutionRequest {
123            language: ExecutionLanguage::JavaScript,
124            payload: ExecutionPayload::Source { code },
125            argv: vec![],
126            stdin: None,
127            input,
128            sandbox: SandboxPolicy::strict_rust(),
129            identity: None,
130        };
131
132        let result = self
133            .executor
134            .execute(request)
135            .await
136            .map_err(|e| adk_core::AdkError::tool(format!("Frontend execution failed: {e}")))?;
137
138        Ok(json!({
139            "status": result.status,
140            "stdout": result.stdout,
141            "stderr": result.stderr,
142            "output": result.output,
143            "exitCode": result.exit_code,
144            "durationMs": result.duration_ms,
145        }))
146    }
147}