adk_code/vertex_sandbox.rs
1//! Vertex AI Agent Engine sandbox client (`sandboxEnvironments`, v1beta1).
2//!
3//! A managed code-execution sandbox lives under a reasoning engine at
4//! `projects/*/locations/*/reasoningEngines/*/sandboxEnvironments/*`. This
5//! module provides:
6//!
7//! - **[`VertexSandboxClient`]** — the REST surface: create (LRO), get,
8//! list, delete (LRO), and the synchronous `:execute` method, plus
9//! [`execute_code`](VertexSandboxClient::execute_code) implementing the
10//! chunk conventions shared with adk-python and the Vertex AI SDK.
11//! - **[`SandboxCodeExecutor`]** — adk-python
12//! `AgentEngineSandboxCodeExecutor` parity: per-session lazy sandbox
13//! creation with recreate-on-not-running semantics.
14//! - **[`VertexSandboxTool`]** — an [`adk_core::Tool`] exposing sandbox
15//! code execution to LLM agents, keyed by the calling session.
16//!
17//! Transport, credential caching, LRO polling, and scope validation come
18//! from [`adk_gcp`].
19//!
20//! # Chunk conventions
21//!
22//! `:execute` exchanges opaque `Chunk` values. The code-execution
23//! conventions over them (adk-python/SDK parity):
24//!
25//! | Chunk | `mimeType` | `data` (base64 of) | `metadata.attributes` |
26//! |-------|------------|--------------------|-----------------------|
27//! | Code input | `application/json` | `{"code": "<source>"}` | — |
28//! | Input file | the file's MIME type | raw bytes | `file_name` = base64(filename) |
29//! | Console output | `application/json` | `{"msg_out": ..., "msg_err": ...}` | no `file_name` |
30//! | Output file | may be absent | raw bytes | `file_name` = base64(filename) |
31//!
32//! Files are limited to 100 MB per request and per response. The request
33//! side is enforced before sending; the response side is bounded by the
34//! client's response-size limit (140 MiB, covering base64 overhead).
35//!
36//! # Example
37//!
38//! ```rust,no_run
39//! use adk_code::vertex_sandbox::{
40//! CreateSandboxRequest, VertexSandboxClient, VertexSandboxConfig,
41//! };
42//!
43//! # async fn run() -> adk_core::Result<()> {
44//! let config = VertexSandboxConfig::new("my-project", "us-central1");
45//! let client = VertexSandboxClient::new_with_adc(config)?;
46//!
47//! let sandbox = client
48//! .create_sandbox("4242", CreateSandboxRequest::new("my-sandbox"))
49//! .await?;
50//! let name = sandbox.name.expect("created sandbox has a name");
51//!
52//! let result = client.execute_code(&name, "print('hello')", &[]).await?;
53//! assert_eq!(result.stdout, "hello\n");
54//!
55//! client.delete_sandbox(&name).await?;
56//! # Ok(())
57//! # }
58//! ```
59
60mod client;
61mod executor;
62mod tool;
63mod types;
64
65pub use client::VertexSandboxClient;
66pub use executor::SandboxCodeExecutor;
67pub use tool::VertexSandboxTool;
68pub use types::{
69 Chunk, ChunkMetadata, CodeExecutionEnvironment, CodeLanguage, ComputerUseEnvironment,
70 CreateSandboxRequest, InputFile, MachineConfig, OutputFile, SandboxEnvironment,
71 SandboxEnvironmentSpec, SandboxExecutionResult, SandboxState, decode_output_chunks,
72 encode_code_chunk, encode_file_chunk,
73};
74
75use adk_core::{ErrorComponent, Result};
76use adk_gcp::{GcpErrorCodes, GcpErrorContext};
77use std::time::Duration;
78
79/// Machine-readable error codes stamped on every vertex sandbox error.
80const CODES: GcpErrorCodes = GcpErrorCodes {
81 invalid_input: "code.vertex_sandbox.invalid_input",
82 unauthorized: "code.vertex_sandbox.unauthorized",
83 forbidden: "code.vertex_sandbox.forbidden",
84 not_found: "code.vertex_sandbox.not_found",
85 rate_limited: "code.vertex_sandbox.rate_limited",
86 timeout: "code.vertex_sandbox.timeout",
87 unavailable: "code.vertex_sandbox.unavailable",
88 credentials_unavailable: "code.vertex_sandbox.credentials_unavailable",
89 invalid_response: "code.vertex_sandbox.invalid_response",
90 invalid_request: "code.vertex_sandbox.invalid_request",
91 upstream_error: "code.vertex_sandbox.upstream_error",
92 operation_failed: "code.vertex_sandbox.operation_failed",
93};
94
95/// The error identity every vertex sandbox failure carries.
96pub(crate) fn errors() -> GcpErrorContext {
97 GcpErrorContext::new(ErrorComponent::Code, CODES, "vertex sandbox")
98}
99
100/// Maximum raw file bytes accepted per `:execute` request (100 MB).
101///
102/// The service enforces the same limit on responses; the client's
103/// response-size bound is set above the base64-encoded equivalent.
104pub const MAX_REQUEST_FILE_BYTES: usize = 100 * 1024 * 1024;
105
106/// Response-size bound: 100 MB of files survives base64 encoding (4/3
107/// overhead ≈ 133 MiB) plus JSON framing within 140 MiB.
108const MAX_RESPONSE_BYTES: usize = 140 * 1024 * 1024;
109
110/// Whole-request timeout: long-running code plus 100 MB uploads need more
111/// headroom than the adk-gcp default.
112const HTTP_REQUEST_TIMEOUT: Duration = Duration::from_secs(300);
113
114/// Sandbox provisioning routinely outlives the default 120 s LRO deadline.
115const CREATE_POLL_TIMEOUT: Duration = Duration::from_secs(300);
116
117/// Display name [`SandboxCodeExecutor`] uses for lazily created sandboxes
118/// (adk-python parity).
119pub const DEFAULT_SANDBOX_DISPLAY_NAME: &str = "default_sandbox";
120
121/// TTL [`SandboxCodeExecutor`] sends for lazily created sandboxes: one year,
122/// matching adk-python.
123///
124/// > **Note:** the service documents no hard TTL maximum, but sandboxes may
125/// > lose state after roughly 14 days of disuse. Every `:execute` call
126/// > resets the TTL server-side.
127pub const DEFAULT_SANDBOX_TTL: &str = "31536000s";
128
129/// Environment variable holding the GCP project (set inside deployed engines).
130const ENV_GOOGLE_CLOUD_PROJECT: &str = "GOOGLE_CLOUD_PROJECT";
131/// Environment variable holding the GCP location.
132const ENV_GOOGLE_CLOUD_LOCATION: &str = "GOOGLE_CLOUD_LOCATION";
133
134/// Configuration for [`VertexSandboxClient`].
135///
136/// Mirrors `VertexAiMemoryConfig`: project, location, optional endpoint
137/// override, and a [`from_env`](Self::from_env) constructor reading the
138/// platform's container environment.
139///
140/// # Example
141///
142/// ```rust
143/// use adk_code::vertex_sandbox::VertexSandboxConfig;
144///
145/// let config = VertexSandboxConfig::new("my-project", "us-central1");
146/// ```
147#[derive(Debug, Clone)]
148pub struct VertexSandboxConfig {
149 pub(crate) project_id: String,
150 pub(crate) location: String,
151 pub(crate) endpoint: Option<String>,
152}
153
154impl VertexSandboxConfig {
155 /// Creates a config for the given project and location.
156 pub fn new(project_id: impl Into<String>, location: impl Into<String>) -> Self {
157 Self { project_id: project_id.into(), location: location.into(), endpoint: None }
158 }
159
160 /// Builds a config from the environment variables the platform sets
161 /// inside deployed containers: `GOOGLE_CLOUD_PROJECT` and
162 /// `GOOGLE_CLOUD_LOCATION`. Values are trimmed; blank counts as missing.
163 ///
164 /// # Errors
165 ///
166 /// Returns an invalid-input error naming every missing or blank variable.
167 pub fn from_env() -> Result<Self> {
168 let read = |key: &str| {
169 std::env::var(key)
170 .ok()
171 .map(|value| value.trim().to_string())
172 .filter(|value| !value.is_empty())
173 };
174 let project_id = read(ENV_GOOGLE_CLOUD_PROJECT);
175 let location = read(ENV_GOOGLE_CLOUD_LOCATION);
176
177 match (project_id, location) {
178 (Some(project_id), Some(location)) => Ok(Self::new(project_id, location)),
179 (project_id, location) => {
180 let missing = [
181 (ENV_GOOGLE_CLOUD_PROJECT, project_id.is_none()),
182 (ENV_GOOGLE_CLOUD_LOCATION, location.is_none()),
183 ]
184 .into_iter()
185 .filter_map(|(key, is_missing)| is_missing.then_some(key))
186 .collect::<Vec<_>>()
187 .join(", ");
188 Err(errors().invalid_input(format!(
189 "missing or blank environment variable(s): {missing}. The Agent Engine platform sets these inside deployed containers; set them explicitly elsewhere, or construct the config with VertexSandboxConfig::new",
190 )))
191 }
192 }
193 }
194
195 /// Sets a custom API origin.
196 ///
197 /// The origin receives Google authorization headers plus executed code
198 /// and files. Use only a trusted HTTPS origin, or loopback HTTP for
199 /// local tests. Userinfo, paths, queries, and fragments are rejected
200 /// before transport.
201 #[must_use]
202 pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
203 self.endpoint = Some(endpoint.into());
204 self
205 }
206
207 pub(crate) fn endpoint(&self) -> String {
208 self.endpoint
209 .clone()
210 .unwrap_or_else(|| format!("https://{}-aiplatform.googleapis.com", self.location))
211 }
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217
218 #[test]
219 fn endpoint_defaults_to_regional_origin() {
220 let config = VertexSandboxConfig::new("p", "europe-west1");
221 assert_eq!(config.endpoint(), "https://europe-west1-aiplatform.googleapis.com");
222 let overridden = config.with_endpoint("http://127.0.0.1:8080");
223 assert_eq!(overridden.endpoint(), "http://127.0.0.1:8080");
224 }
225}