Skip to main content

adk_code/vertex_sandbox/
executor.rs

1//! Per-session sandbox lifecycle management — adk-python
2//! `AgentEngineSandboxCodeExecutor` parity.
3
4use super::client::VertexSandboxClient;
5use super::types::{
6    CodeExecutionEnvironment, CreateSandboxRequest, InputFile, SandboxEnvironmentSpec,
7    SandboxExecutionResult, SandboxState,
8};
9use super::{DEFAULT_SANDBOX_DISPLAY_NAME, DEFAULT_SANDBOX_TTL, errors};
10use adk_core::Result;
11use std::collections::HashMap;
12use std::sync::Arc;
13use tokio::sync::RwLock;
14use tracing::debug;
15
16/// Where the executor runs code.
17#[derive(Debug, Clone)]
18enum ExecutorTarget {
19    /// A fixed, pre-provisioned sandbox used for every session.
20    Sandbox(String),
21    /// A reasoning engine under which sandboxes are created per session.
22    Engine(String),
23}
24
25/// Executes code in Agent Engine sandboxes with per-session lifecycle
26/// management, matching adk-python's `AgentEngineSandboxCodeExecutor`.
27///
28/// Two modes:
29///
30/// - **Fixed sandbox** ([`for_sandbox`](Self::for_sandbox)) — every session
31///   uses the given sandbox; execution fails when it is not running.
32/// - **Engine-managed** ([`for_engine`](Self::for_engine)) — a sandbox is
33///   created lazily per session (display name `default_sandbox`, TTL one
34///   year, code-execution spec with service defaults) and cached. On each
35///   execution the sandbox is re-fetched and recreated when it is missing
36///   or no longer `STATE_RUNNING`.
37///
38/// The session→sandbox map is guarded by an async lock; sandbox creation
39/// is serialized across sessions so concurrent first calls cannot create
40/// duplicates.
41///
42/// # Example
43///
44/// ```rust,no_run
45/// use adk_code::vertex_sandbox::{
46///     SandboxCodeExecutor, VertexSandboxClient, VertexSandboxConfig,
47/// };
48/// use std::sync::Arc;
49///
50/// # async fn run() -> adk_core::Result<()> {
51/// let client = Arc::new(VertexSandboxClient::new_with_adc(VertexSandboxConfig::new(
52///     "my-project",
53///     "us-central1",
54/// ))?);
55/// let executor = SandboxCodeExecutor::for_engine(client, "4242");
56/// let result = executor.execute_for_session("session-1", "print(1 + 1)", &[]).await?;
57/// assert_eq!(result.stdout, "2\n");
58/// # Ok(())
59/// # }
60/// ```
61pub struct SandboxCodeExecutor {
62    client: Arc<VertexSandboxClient>,
63    target: ExecutorTarget,
64    sessions: RwLock<HashMap<String, String>>,
65}
66
67impl SandboxCodeExecutor {
68    /// Uses one pre-provisioned sandbox for every session.
69    ///
70    /// When both a sandbox and an engine are available, prefer this
71    /// constructor — the sandbox wins in adk-python's executor too.
72    pub fn for_sandbox(client: Arc<VertexSandboxClient>, sandbox_name: impl Into<String>) -> Self {
73        Self {
74            client,
75            target: ExecutorTarget::Sandbox(sandbox_name.into()),
76            sessions: RwLock::new(HashMap::new()),
77        }
78    }
79
80    /// Creates sandboxes lazily per session under the given reasoning
81    /// engine (full resource name or bare numeric ID).
82    pub fn for_engine(client: Arc<VertexSandboxClient>, engine: impl Into<String>) -> Self {
83        Self {
84            client,
85            target: ExecutorTarget::Engine(engine.into()),
86            sessions: RwLock::new(HashMap::new()),
87        }
88    }
89
90    /// Executes code in the sandbox associated with `session_key`,
91    /// creating or recreating it first when necessary.
92    ///
93    /// # Errors
94    ///
95    /// Returns an error when the sandbox cannot be resolved, created, or
96    /// executed against, or when the outputs cannot be decoded.
97    pub async fn execute_for_session(
98        &self,
99        session_key: &str,
100        code: &str,
101        files: &[InputFile],
102    ) -> Result<SandboxExecutionResult> {
103        let sandbox = self.ensure_sandbox(session_key).await?;
104        self.client.execute_code(&sandbox, code, files).await
105    }
106
107    /// Resolves the sandbox for a session, applying the lazy
108    /// create/recreate semantics.
109    async fn ensure_sandbox(&self, session_key: &str) -> Result<String> {
110        match &self.target {
111            ExecutorTarget::Sandbox(name) => {
112                let sandbox = self.client.get_sandbox(name).await?;
113                if sandbox.state == Some(SandboxState::Running) {
114                    return Ok(name.clone());
115                }
116                Err(errors().unavailable(format!(
117                    "vertex sandbox '{name}' is not running (state {:?}); wait for provisioning to finish or provision a new sandbox",
118                    sandbox.state,
119                )))
120            }
121            ExecutorTarget::Engine(engine) => {
122                // The write lock is held across the check and the create so
123                // concurrent calls cannot race a duplicate sandbox into
124                // existence for the same session.
125                let mut sessions = self.sessions.write().await;
126                if let Some(cached) = sessions.get(session_key) {
127                    match self.client.get_sandbox(cached).await {
128                        Ok(sandbox) if sandbox.state == Some(SandboxState::Running) => {
129                            return Ok(cached.clone());
130                        }
131                        Ok(sandbox) => {
132                            debug!(
133                                sandbox.name = cached.as_str(),
134                                sandbox.state = ?sandbox.state,
135                                "cached sandbox is not running; recreating",
136                            );
137                        }
138                        Err(error) if error.is_not_found() => {
139                            debug!(
140                                sandbox.name = cached.as_str(),
141                                "cached sandbox no longer exists; recreating",
142                            );
143                        }
144                        Err(error) => return Err(error),
145                    }
146                }
147                let request = CreateSandboxRequest::new(DEFAULT_SANDBOX_DISPLAY_NAME)
148                    .with_ttl(DEFAULT_SANDBOX_TTL)
149                    .with_spec(SandboxEnvironmentSpec::code_execution(
150                        CodeExecutionEnvironment::default(),
151                    ));
152                let created = self.client.create_sandbox(engine, request).await?;
153                let name = created.name.ok_or_else(|| {
154                    errors().invalid_response(
155                        "vertex sandbox create returned a sandbox without a name; inspect the sandbox in Google Cloud",
156                    )
157                })?;
158                sessions.insert(session_key.to_string(), name.clone());
159                Ok(name)
160            }
161        }
162    }
163}