Skip to main content

adk_code/vertex_sandbox/
types.rs

1//! Wire DTOs for the `sandboxEnvironments` surface and the chunk-protocol
2//! helpers implementing the code-execution conventions over `:execute`.
3
4use adk_core::Result;
5use adk_gcp::truncate_for_error;
6use base64::Engine as _;
7use base64::engine::general_purpose::STANDARD as BASE64;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use std::collections::BTreeMap;
11
12/// The `metadata.attributes` key naming a file chunk (value is base64).
13const FILE_NAME_ATTRIBUTE: &str = "file_name";
14/// MIME type of the code-input and console-output chunks.
15const JSON_MIME_TYPE: &str = "application/json";
16
17/// Lifecycle state of a sandbox environment (output only).
18///
19/// Only [`Running`](Self::Running) sandboxes accept `:execute` calls.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21pub enum SandboxState {
22    /// The state is unspecified.
23    #[serde(rename = "STATE_UNSPECIFIED")]
24    Unspecified,
25    /// The sandbox is being provisioned.
26    #[serde(rename = "STATE_PROVISIONING")]
27    Provisioning,
28    /// The sandbox is running and accepts `:execute` calls.
29    #[serde(rename = "STATE_RUNNING")]
30    Running,
31    /// The sandbox is being deprovisioned.
32    #[serde(rename = "STATE_DEPROVISIONING")]
33    Deprovisioning,
34    /// The sandbox has been terminated.
35    #[serde(rename = "STATE_TERMINATED")]
36    Terminated,
37    /// The sandbox has been deleted.
38    #[serde(rename = "STATE_DELETED")]
39    Deleted,
40    /// Forward-compatibility catch-all for states this crate predates.
41    #[serde(other, rename = "STATE_UNKNOWN")]
42    Unknown,
43}
44
45/// Machine shape of a code-execution sandbox.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
47pub enum MachineConfig {
48    /// The machine config is unspecified; the service picks the default.
49    #[serde(rename = "MACHINE_CONFIG_UNSPECIFIED")]
50    Unspecified,
51    /// 4 vCPUs, 4 GiB RAM.
52    #[serde(rename = "MACHINE_CONFIG_VCPU4_RAM4GIB")]
53    Vcpu4Ram4Gib,
54    /// Forward-compatibility catch-all for configs this crate predates.
55    #[serde(other, rename = "MACHINE_CONFIG_UNKNOWN")]
56    Unknown,
57}
58
59/// Language runtime of a code-execution sandbox.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
61pub enum CodeLanguage {
62    /// The language is unspecified; the service picks the default.
63    #[serde(rename = "LANGUAGE_UNSPECIFIED")]
64    Unspecified,
65    /// Python.
66    #[serde(rename = "LANGUAGE_PYTHON")]
67    Python,
68    /// JavaScript.
69    #[serde(rename = "LANGUAGE_JAVASCRIPT")]
70    Javascript,
71    /// Forward-compatibility catch-all for languages this crate predates.
72    #[serde(other, rename = "LANGUAGE_UNKNOWN")]
73    Unknown,
74}
75
76/// Spec of a code-execution sandbox environment.
77#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "camelCase")]
79pub struct CodeExecutionEnvironment {
80    /// Machine shape; the service default applies when omitted.
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub machine_config: Option<MachineConfig>,
83    /// Language runtime; the service default applies when omitted.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub code_language: Option<CodeLanguage>,
86}
87
88/// Spec of a computer-use sandbox environment (no fields).
89#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
90pub struct ComputerUseEnvironment {}
91
92/// The `sandbox_environment_category` oneof: exactly one category is set.
93#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "camelCase")]
95pub struct SandboxEnvironmentSpec {
96    /// A code-execution sandbox.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub code_execution_environment: Option<CodeExecutionEnvironment>,
99    /// A computer-use sandbox.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub computer_use_environment: Option<ComputerUseEnvironment>,
102}
103
104impl SandboxEnvironmentSpec {
105    /// A code-execution spec.
106    ///
107    /// # Example
108    ///
109    /// ```rust
110    /// use adk_code::vertex_sandbox::{CodeExecutionEnvironment, SandboxEnvironmentSpec};
111    ///
112    /// let spec = SandboxEnvironmentSpec::code_execution(CodeExecutionEnvironment::default());
113    /// assert!(spec.code_execution_environment.is_some());
114    /// ```
115    pub fn code_execution(environment: CodeExecutionEnvironment) -> Self {
116        Self { code_execution_environment: Some(environment), computer_use_environment: None }
117    }
118
119    /// A computer-use spec.
120    pub fn computer_use() -> Self {
121        Self {
122            code_execution_environment: None,
123            computer_use_environment: Some(ComputerUseEnvironment {}),
124        }
125    }
126}
127
128/// A `SandboxEnvironment` wire resource.
129///
130/// `state`, timestamps, `expire_time`, `connection_info`, and the snapshot
131/// fields are output only; `ttl` is input only (a Duration string such as
132/// `"3600s"`). On output the expiration oneof always carries `expire_time`.
133#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
134#[serde(rename_all = "camelCase")]
135pub struct SandboxEnvironment {
136    /// Resource name: `projects/*/locations/*/reasoningEngines/*/sandboxEnvironments/*`.
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub name: Option<String>,
139    /// Required user-supplied display name.
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub display_name: Option<String>,
142    /// Creation timestamp (output only, RFC 3339).
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub create_time: Option<String>,
145    /// Last-update timestamp (output only, RFC 3339).
146    #[serde(skip_serializing_if = "Option::is_none")]
147    pub update_time: Option<String>,
148    /// Lifecycle state (output only).
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub state: Option<SandboxState>,
151    /// Sandbox category spec.
152    #[serde(skip_serializing_if = "Option::is_none")]
153    pub spec: Option<SandboxEnvironmentSpec>,
154    /// Template the sandbox was created from, if any.
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub sandbox_environment_template: Option<Value>,
157    /// Connection details (output only; shape varies by category).
158    #[serde(skip_serializing_if = "Option::is_none")]
159    pub connection_info: Option<Value>,
160    /// Latest snapshot (output only).
161    #[serde(skip_serializing_if = "Option::is_none")]
162    pub latest_sandbox_environment_snapshot: Option<Value>,
163    /// Owner of the sandbox, if any.
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub owner: Option<Value>,
166    /// Snapshot to restore the sandbox from, if any.
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub sandbox_environment_snapshot: Option<Value>,
169    /// Expiration timestamp (output side of the expiration oneof, RFC 3339).
170    #[serde(skip_serializing_if = "Option::is_none")]
171    pub expire_time: Option<String>,
172    /// Time-to-live (input side of the expiration oneof, e.g. `"3600s"`).
173    #[serde(skip_serializing_if = "Option::is_none")]
174    pub ttl: Option<String>,
175}
176
177/// Input to [`create_sandbox`](super::VertexSandboxClient::create_sandbox).
178///
179/// # Example
180///
181/// ```rust
182/// use adk_code::vertex_sandbox::{
183///     CodeExecutionEnvironment, CodeLanguage, CreateSandboxRequest, SandboxEnvironmentSpec,
184/// };
185///
186/// let request = CreateSandboxRequest::new("my-sandbox")
187///     .with_ttl("3600s")
188///     .with_spec(SandboxEnvironmentSpec::code_execution(CodeExecutionEnvironment {
189///         machine_config: None,
190///         code_language: Some(CodeLanguage::Python),
191///     }));
192/// # let _ = request;
193/// ```
194#[derive(Debug, Clone, PartialEq)]
195pub struct CreateSandboxRequest {
196    pub(crate) display_name: String,
197    pub(crate) ttl: Option<String>,
198    pub(crate) spec: Option<SandboxEnvironmentSpec>,
199}
200
201impl CreateSandboxRequest {
202    /// Creates a request with the required display name.
203    pub fn new(display_name: impl Into<String>) -> Self {
204        Self { display_name: display_name.into(), ttl: None, spec: None }
205    }
206
207    /// Sets the time-to-live as a Duration string (e.g. `"3600s"`).
208    ///
209    /// The service documents no hard maximum — adk-python sends
210    /// `"31536000s"` (one year) — but sandboxes may lose state after
211    /// roughly 14 days of disuse. Every `:execute` call resets the TTL
212    /// server-side.
213    #[must_use]
214    pub fn with_ttl(mut self, ttl: impl Into<String>) -> Self {
215        self.ttl = Some(ttl.into());
216        self
217    }
218
219    /// Sets the sandbox category spec. Defaults to a code-execution
220    /// sandbox with service defaults when omitted.
221    #[must_use]
222    pub fn with_spec(mut self, spec: SandboxEnvironmentSpec) -> Self {
223        self.spec = Some(spec);
224        self
225    }
226
227    /// The `SandboxEnvironment` create body this request serializes to.
228    pub(crate) fn into_body(self) -> SandboxEnvironment {
229        SandboxEnvironment {
230            display_name: Some(self.display_name),
231            ttl: self.ttl,
232            spec: self.spec,
233            ..SandboxEnvironment::default()
234        }
235    }
236}
237
238/// Optional metadata carried by a [`Chunk`].
239#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
240pub struct ChunkMetadata {
241    /// Attribute map; every value is a base64-encoded string.
242    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
243    pub attributes: BTreeMap<String, String>,
244}
245
246/// One unit of `:execute` input or output.
247#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
248#[serde(rename_all = "camelCase")]
249pub struct Chunk {
250    /// MIME type. Required on input; may be absent on output file chunks.
251    #[serde(skip_serializing_if = "Option::is_none")]
252    pub mime_type: Option<String>,
253    /// Base64-encoded payload bytes.
254    #[serde(default)]
255    pub data: String,
256    /// Optional attribute metadata (e.g. `file_name` for file chunks).
257    #[serde(skip_serializing_if = "Option::is_none")]
258    pub metadata: Option<ChunkMetadata>,
259}
260
261/// An input file for [`execute_code`](super::VertexSandboxClient::execute_code).
262///
263/// # Example
264///
265/// ```rust
266/// use adk_code::vertex_sandbox::InputFile;
267///
268/// let file = InputFile::new("data.csv", "text/csv", b"a,b\n1,2\n".to_vec());
269/// assert_eq!(file.name, "data.csv");
270/// ```
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub struct InputFile {
273    /// Filename the sandbox sees.
274    pub name: String,
275    /// MIME type of the file contents.
276    pub mime_type: String,
277    /// Raw (not base64) file bytes.
278    pub data: Vec<u8>,
279}
280
281impl InputFile {
282    /// Creates an input file from its parts.
283    pub fn new(name: impl Into<String>, mime_type: impl Into<String>, data: Vec<u8>) -> Self {
284        Self { name: name.into(), mime_type: mime_type.into(), data }
285    }
286}
287
288/// A file the executed code wrote.
289#[derive(Debug, Clone, PartialEq, Eq)]
290pub struct OutputFile {
291    /// Filename reported by the sandbox.
292    pub name: String,
293    /// MIME type, when the sandbox reported one.
294    pub mime_type: Option<String>,
295    /// Raw (decoded) file bytes.
296    pub data: Vec<u8>,
297}
298
299/// Decoded result of one code execution.
300#[derive(Debug, Clone, Default, PartialEq, Eq)]
301pub struct SandboxExecutionResult {
302    /// Captured standard output.
303    pub stdout: String,
304    /// Captured standard error.
305    pub stderr: String,
306    /// Files the code wrote.
307    pub output_files: Vec<OutputFile>,
308}
309
310/// The `:execute` request body.
311#[derive(Debug, Serialize)]
312pub(crate) struct ExecuteRequest {
313    pub(crate) inputs: Vec<Chunk>,
314}
315
316/// The `:execute` response body.
317#[derive(Debug, Deserialize)]
318pub(crate) struct ExecuteResponse {
319    #[serde(default)]
320    pub(crate) outputs: Vec<Chunk>,
321}
322
323/// A `sandboxEnvironments.list` response page.
324#[derive(Debug, Deserialize)]
325#[serde(rename_all = "camelCase")]
326pub(crate) struct ListSandboxesResponse {
327    #[serde(default)]
328    pub(crate) sandbox_environments: Vec<SandboxEnvironment>,
329    #[serde(default)]
330    pub(crate) next_page_token: Option<String>,
331}
332
333/// Console-output payload carried by an `application/json` output chunk.
334///
335/// The wire keys are `msg_out`/`msg_err` (not `stdout`/`stderr`); unknown
336/// keys — such as `output_files` — are tolerated and ignored.
337#[derive(Debug, Deserialize)]
338struct ConsolePayload {
339    #[serde(default)]
340    msg_out: Option<String>,
341    #[serde(default)]
342    msg_err: Option<String>,
343}
344
345/// Encodes source code as the code-input chunk.
346///
347/// # Example
348///
349/// ```rust
350/// use adk_code::vertex_sandbox::encode_code_chunk;
351///
352/// let chunk = encode_code_chunk("print('hi')");
353/// assert_eq!(chunk.mime_type.as_deref(), Some("application/json"));
354/// ```
355pub fn encode_code_chunk(code: &str) -> Chunk {
356    let payload = serde_json::json!({ "code": code });
357    Chunk {
358        mime_type: Some(JSON_MIME_TYPE.to_string()),
359        data: BASE64.encode(payload.to_string()),
360        metadata: None,
361    }
362}
363
364/// Encodes an input file as a file chunk (`file_name` attribute set).
365///
366/// # Example
367///
368/// ```rust
369/// use adk_code::vertex_sandbox::{InputFile, encode_file_chunk};
370///
371/// let chunk = encode_file_chunk(&InputFile::new("a.txt", "text/plain", b"hi".to_vec()));
372/// assert!(chunk.metadata.unwrap().attributes.contains_key("file_name"));
373/// ```
374pub fn encode_file_chunk(file: &InputFile) -> Chunk {
375    let mut attributes = BTreeMap::new();
376    attributes.insert(FILE_NAME_ATTRIBUTE.to_string(), BASE64.encode(&file.name));
377    Chunk {
378        mime_type: Some(file.mime_type.clone()),
379        data: BASE64.encode(&file.data),
380        metadata: Some(ChunkMetadata { attributes }),
381    }
382}
383
384/// Decodes `:execute` output chunks into stdout, stderr, and output files.
385///
386/// Chunks carrying a `file_name` attribute become [`OutputFile`]s;
387/// `application/json` chunks without one carry `msg_out`/`msg_err` console
388/// text. Unrecognized chunks are skipped.
389///
390/// # Errors
391///
392/// Returns an error when chunk data or a `file_name` attribute is not
393/// valid base64, a filename is not UTF-8, or a console payload is not
394/// valid JSON.
395pub fn decode_output_chunks(outputs: &[Chunk]) -> Result<SandboxExecutionResult> {
396    let errors = super::errors();
397    let mut result = SandboxExecutionResult::default();
398    for chunk in outputs {
399        let file_name =
400            chunk.metadata.as_ref().and_then(|meta| meta.attributes.get(FILE_NAME_ATTRIBUTE));
401        if let Some(encoded_name) = file_name {
402            let name_bytes = BASE64.decode(encoded_name).map_err(|error| {
403                errors.invalid_response(format!(
404                    "vertex sandbox output chunk carries a file_name attribute that is not valid base64: {error}",
405                ))
406            })?;
407            let name = String::from_utf8(name_bytes).map_err(|_| {
408                errors.invalid_response(
409                    "vertex sandbox output chunk carries a file_name that is not valid UTF-8",
410                )
411            })?;
412            let data = BASE64.decode(&chunk.data).map_err(|error| {
413                errors.invalid_response(format!(
414                    "vertex sandbox output file '{}' data is not valid base64: {error}",
415                    truncate_for_error(&name),
416                ))
417            })?;
418            result.output_files.push(OutputFile { name, mime_type: chunk.mime_type.clone(), data });
419            continue;
420        }
421        if chunk.mime_type.as_deref() == Some(JSON_MIME_TYPE) {
422            let bytes = BASE64.decode(&chunk.data).map_err(|error| {
423                errors.invalid_response(format!(
424                    "vertex sandbox console output chunk data is not valid base64: {error}",
425                ))
426            })?;
427            let payload: ConsolePayload = serde_json::from_slice(&bytes).map_err(|error| {
428                errors.invalid_response(format!(
429                    "vertex sandbox console output chunk is not valid JSON: {error}",
430                ))
431            })?;
432            if let Some(out) = payload.msg_out {
433                result.stdout.push_str(&out);
434            }
435            if let Some(err) = payload.msg_err {
436                result.stderr.push_str(&err);
437            }
438            continue;
439        }
440        tracing::debug!(chunk.mime_type = ?chunk.mime_type, "skipping unrecognized output chunk");
441    }
442    Ok(result)
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448    use serde_json::json;
449
450    #[test]
451    fn code_chunk_encodes_the_json_code_convention() {
452        let chunk = encode_code_chunk("print('hi')");
453        assert_eq!(chunk.mime_type.as_deref(), Some(JSON_MIME_TYPE));
454        assert_eq!(chunk.metadata, None);
455        let decoded: Value = serde_json::from_slice(&BASE64.decode(&chunk.data).unwrap()).unwrap();
456        assert_eq!(decoded, json!({ "code": "print('hi')" }));
457    }
458
459    #[test]
460    fn file_chunk_carries_base64_name_and_bytes() {
461        let file = InputFile::new("data.csv", "text/csv", b"a,b\n".to_vec());
462        let chunk = encode_file_chunk(&file);
463        assert_eq!(chunk.mime_type.as_deref(), Some("text/csv"));
464        let attributes = chunk.metadata.unwrap().attributes;
465        assert_eq!(attributes.get(FILE_NAME_ATTRIBUTE).unwrap(), &BASE64.encode("data.csv"));
466        assert_eq!(BASE64.decode(&chunk.data).unwrap(), b"a,b\n");
467    }
468
469    #[test]
470    fn output_decoding_separates_console_and_files() {
471        let outputs = vec![
472            Chunk {
473                mime_type: Some(JSON_MIME_TYPE.to_string()),
474                data: BASE64.encode(
475                    json!({
476                        "msg_out": "hello\n",
477                        "msg_err": "warning\n",
478                        "output_files": ["ignored.txt"],
479                        "unknown_key": 42,
480                    })
481                    .to_string(),
482                ),
483                metadata: None,
484            },
485            Chunk {
486                mime_type: None,
487                data: BASE64.encode(b"bytes"),
488                metadata: Some(ChunkMetadata {
489                    attributes: BTreeMap::from([(
490                        FILE_NAME_ATTRIBUTE.to_string(),
491                        BASE64.encode("out.bin"),
492                    )]),
493                }),
494            },
495        ];
496        let result = decode_output_chunks(&outputs).unwrap();
497        assert_eq!(
498            result,
499            SandboxExecutionResult {
500                stdout: "hello\n".to_string(),
501                stderr: "warning\n".to_string(),
502                output_files: vec![OutputFile {
503                    name: "out.bin".to_string(),
504                    mime_type: None,
505                    data: b"bytes".to_vec(),
506                }],
507            },
508        );
509    }
510
511    #[test]
512    fn console_chunks_accumulate_across_outputs() {
513        let console = |payload: Value| Chunk {
514            mime_type: Some(JSON_MIME_TYPE.to_string()),
515            data: BASE64.encode(payload.to_string()),
516            metadata: None,
517        };
518        let outputs = vec![
519            console(json!({ "msg_out": "one" })),
520            console(json!({ "msg_out": "two", "msg_err": "err" })),
521        ];
522        let result = decode_output_chunks(&outputs).unwrap();
523        assert_eq!(result.stdout, "onetwo");
524        assert_eq!(result.stderr, "err");
525    }
526
527    #[test]
528    fn unrecognized_chunks_are_skipped() {
529        let outputs = vec![Chunk {
530            mime_type: Some("image/png".to_string()),
531            data: BASE64.encode(b"png-bytes"),
532            metadata: None,
533        }];
534        let result = decode_output_chunks(&outputs).unwrap();
535        assert_eq!(result, SandboxExecutionResult::default());
536    }
537
538    #[test]
539    fn invalid_base64_in_outputs_is_rejected() {
540        let outputs = vec![Chunk {
541            mime_type: Some(JSON_MIME_TYPE.to_string()),
542            data: "not base64!!!".to_string(),
543            metadata: None,
544        }];
545        let error = decode_output_chunks(&outputs).unwrap_err();
546        assert_eq!(error.code, "code.vertex_sandbox.invalid_response");
547    }
548
549    #[test]
550    fn unknown_enum_values_deserialize_to_the_catch_all() {
551        let state: SandboxState = serde_json::from_value(json!("STATE_HIBERNATED")).unwrap();
552        assert_eq!(state, SandboxState::Unknown);
553        let running: SandboxState = serde_json::from_value(json!("STATE_RUNNING")).unwrap();
554        assert_eq!(running, SandboxState::Running);
555    }
556
557    #[test]
558    fn create_body_serializes_camel_case_and_skips_absent_fields() {
559        let body = CreateSandboxRequest::new("default_sandbox")
560            .with_ttl("31536000s")
561            .with_spec(SandboxEnvironmentSpec::code_execution(CodeExecutionEnvironment::default()))
562            .into_body();
563        assert_eq!(
564            serde_json::to_value(&body).unwrap(),
565            json!({
566                "displayName": "default_sandbox",
567                "ttl": "31536000s",
568                "spec": { "codeExecutionEnvironment": {} },
569            }),
570        );
571    }
572}