adk-code 0.6.0

Code execution substrate for ADK-Rust — typed executor abstraction, sandbox policy model, and built-in execution backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Core execution types for the code execution substrate.
//!
//! This module defines the typed primitives shared by all execution backends,
//! language-preset tools, and Studio integration:
//!
//! - [`ExecutionLanguage`] — supported execution languages
//! - [`ExecutionPayload`] — source code or guest module bytes
//! - [`ExecutionIsolation`] — backend isolation class
//! - [`SandboxPolicy`] — requested sandbox controls
//! - [`BackendCapabilities`] — what a backend can actually enforce
//! - [`ExecutionRequest`] — full execution request
//! - [`ExecutionResult`] — structured execution outcome
//! - [`ExecutionStatus`] — terminal execution status

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::PathBuf;
use std::time::Duration;

/// One megabyte in bytes, used as the default stdout/stderr limit.
const ONE_MB: usize = 1_048_576;

/// Supported execution languages.
///
/// `Rust` is the primary first-class language. Other languages are available
/// through appropriate backends.
///
/// # Example
///
/// ```rust
/// use adk_code::ExecutionLanguage;
///
/// let lang = ExecutionLanguage::Rust;
/// assert_eq!(lang, ExecutionLanguage::Rust);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ExecutionLanguage {
    /// Rust — the primary authored-code path.
    Rust,
    /// JavaScript — secondary scripting and transform support.
    JavaScript,
    /// WebAssembly guest module execution.
    Wasm,
    /// Python — container-backed execution.
    Python,
    /// Raw command execution (shell, interpreter, etc.).
    Command,
}

impl std::fmt::Display for ExecutionLanguage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Rust => write!(f, "Rust"),
            Self::JavaScript => write!(f, "JavaScript"),
            Self::Wasm => write!(f, "Wasm"),
            Self::Python => write!(f, "Python"),
            Self::Command => write!(f, "Command"),
        }
    }
}

/// Format of a precompiled guest module.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GuestModuleFormat {
    /// WebAssembly binary format.
    Wasm,
}

/// The code or module to execute.
///
/// Source payloads carry inline code strings. Guest module payloads carry
/// precompiled binary modules (e.g., `.wasm` files).
///
/// # Example
///
/// ```rust
/// use adk_code::ExecutionPayload;
///
/// let payload = ExecutionPayload::Source {
///     code: "fn run(input: serde_json::Value) -> serde_json::Value { input }".to_string(),
/// };
/// ```
#[derive(Debug, Clone)]
pub enum ExecutionPayload {
    /// Inline source code to compile and/or interpret.
    Source {
        /// The source code string.
        code: String,
    },
    /// A precompiled guest module (e.g., WASM).
    GuestModule {
        /// The binary format of the guest module.
        format: GuestModuleFormat,
        /// The raw module bytes.
        bytes: Vec<u8>,
    },
}

/// Backend isolation class.
///
/// Makes the isolation model explicit so that host-local and container-backed
/// execution cannot be presented as equivalent.
///
/// # Example
///
/// ```rust
/// use adk_code::ExecutionIsolation;
///
/// let iso = ExecutionIsolation::ContainerEphemeral;
/// assert_ne!(iso, ExecutionIsolation::HostLocal);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ExecutionIsolation {
    /// Execution runs in the same process (e.g., embedded JS engine).
    InProcess,
    /// Execution runs as a local host process without strong OS isolation.
    HostLocal,
    /// Execution runs in an ephemeral container destroyed after completion.
    ContainerEphemeral,
    /// Execution runs in a persistent container that survives across requests.
    ContainerPersistent,
    /// Execution runs on a remote provider-hosted service.
    ProviderHosted,
}

/// Network access policy for sandboxed execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NetworkPolicy {
    /// No network access allowed.
    Disabled,
    /// Network access is permitted.
    Enabled,
}

/// Filesystem access policy for sandboxed execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FilesystemPolicy {
    /// No filesystem access.
    None,
    /// Read-only access to a workspace root.
    WorkspaceReadOnly {
        /// The workspace root path.
        root: PathBuf,
    },
    /// Read-write access to a workspace root.
    WorkspaceReadWrite {
        /// The workspace root path.
        root: PathBuf,
    },
    /// Explicit path-level access control.
    Paths {
        /// Paths with read-only access.
        read_only: Vec<PathBuf>,
        /// Paths with read-write access.
        read_write: Vec<PathBuf>,
    },
}

/// Environment variable access policy for sandboxed execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EnvironmentPolicy {
    /// No environment variables exposed.
    None,
    /// Only the listed environment variable names are exposed.
    AllowList(Vec<String>),
}

/// Sandbox policy describing the requested execution constraints.
///
/// Backends compare this policy against their [`BackendCapabilities`] and
/// reject execution if they cannot enforce a requested control.
///
/// # Example
///
/// ```rust
/// use adk_code::SandboxPolicy;
///
/// let policy = SandboxPolicy::strict_rust();
/// assert_eq!(policy.max_stdout_bytes, 1_048_576);
/// ```
#[derive(Debug, Clone)]
pub struct SandboxPolicy {
    /// Network access policy.
    pub network: NetworkPolicy,
    /// Filesystem access policy.
    pub filesystem: FilesystemPolicy,
    /// Environment variable access policy.
    pub environment: EnvironmentPolicy,
    /// Maximum execution duration.
    pub timeout: Duration,
    /// Maximum bytes captured from stdout before truncation.
    pub max_stdout_bytes: usize,
    /// Maximum bytes captured from stderr before truncation.
    pub max_stderr_bytes: usize,
    /// Working directory for execution, if any.
    pub working_directory: Option<PathBuf>,
}

impl SandboxPolicy {
    /// Strict policy for Rust sandbox execution.
    ///
    /// - No network access
    /// - No filesystem access
    /// - No environment variables
    /// - 30-second timeout
    /// - 1 MB stdout/stderr limits
    pub fn strict_rust() -> Self {
        Self {
            network: NetworkPolicy::Disabled,
            filesystem: FilesystemPolicy::None,
            environment: EnvironmentPolicy::None,
            timeout: Duration::from_secs(30),
            max_stdout_bytes: ONE_MB,
            max_stderr_bytes: ONE_MB,
            working_directory: None,
        }
    }

    /// Host-local policy for backends that run on the host without isolation.
    ///
    /// Unlike [`strict_rust`](Self::strict_rust), this policy uses
    /// `NetworkPolicy::Enabled` and `FilesystemPolicy::None` so that
    /// host-local backends (which cannot enforce network or filesystem
    /// restrictions) pass policy validation. The trade-off is that the
    /// executed code has the same network and filesystem access as the
    /// host process.
    ///
    /// - Network access: allowed (host-local cannot restrict)
    /// - Filesystem access: none requested
    /// - Environment variables: none exposed
    /// - 30-second timeout
    /// - 1 MB stdout/stderr limits
    pub fn host_local() -> Self {
        Self {
            network: NetworkPolicy::Enabled,
            filesystem: FilesystemPolicy::None,
            environment: EnvironmentPolicy::None,
            timeout: Duration::from_secs(30),
            max_stdout_bytes: ONE_MB,
            max_stderr_bytes: ONE_MB,
            working_directory: None,
        }
    }

    /// Strict policy for embedded JavaScript execution.
    ///
    /// Same defaults as Rust but with a shorter 5-second timeout,
    /// appropriate for lightweight transforms and scripting.
    pub fn strict_js() -> Self {
        Self {
            network: NetworkPolicy::Disabled,
            filesystem: FilesystemPolicy::None,
            environment: EnvironmentPolicy::None,
            timeout: Duration::from_secs(5),
            max_stdout_bytes: ONE_MB,
            max_stderr_bytes: ONE_MB,
            working_directory: None,
        }
    }
}

impl Default for SandboxPolicy {
    /// Sensible defaults: no network, no filesystem, no env vars, 30s timeout, 1 MB limits.
    fn default() -> Self {
        Self::strict_rust()
    }
}

/// Capabilities that a backend can actually enforce.
///
/// This makes the isolation model explicit so callers and docs can distinguish
/// what a backend claims from what it can guarantee.
///
/// # Example
///
/// ```rust
/// use adk_code::{BackendCapabilities, ExecutionIsolation};
///
/// let caps = BackendCapabilities {
///     isolation: ExecutionIsolation::ContainerEphemeral,
///     enforce_network_policy: true,
///     enforce_filesystem_policy: true,
///     enforce_environment_policy: true,
///     enforce_timeout: true,
///     supports_structured_output: true,
///     supports_process_execution: false,
///     supports_persistent_workspace: false,
///     supports_interactive_sessions: false,
/// };
/// assert!(caps.enforce_network_policy);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BackendCapabilities {
    /// The isolation class this backend provides.
    pub isolation: ExecutionIsolation,
    /// Whether the backend can enforce network restrictions.
    pub enforce_network_policy: bool,
    /// Whether the backend can enforce filesystem restrictions.
    pub enforce_filesystem_policy: bool,
    /// Whether the backend can enforce environment variable restrictions.
    pub enforce_environment_policy: bool,
    /// Whether the backend can enforce execution timeouts.
    pub enforce_timeout: bool,
    /// Whether the backend supports structured JSON output.
    pub supports_structured_output: bool,
    /// Whether the backend supports spawning child processes.
    pub supports_process_execution: bool,
    /// Whether the backend supports persistent workspaces across requests.
    pub supports_persistent_workspace: bool,
    /// Whether the backend supports interactive/REPL-style sessions.
    pub supports_interactive_sessions: bool,
}

/// A full execution request.
///
/// Combines language, payload, sandbox policy, optional I/O, and identity
/// into a single typed request that backends can validate and execute.
///
/// # Example
///
/// ```rust
/// use adk_code::{ExecutionRequest, ExecutionLanguage, ExecutionPayload, SandboxPolicy};
///
/// let request = ExecutionRequest {
///     language: ExecutionLanguage::Rust,
///     payload: ExecutionPayload::Source {
///         code: r#"fn run(input: serde_json::Value) -> serde_json::Value { input }"#.to_string(),
///     },
///     argv: vec![],
///     stdin: None,
///     input: None,
///     sandbox: SandboxPolicy::strict_rust(),
///     identity: None,
/// };
/// ```
#[derive(Debug, Clone)]
pub struct ExecutionRequest {
    /// The target execution language.
    pub language: ExecutionLanguage,
    /// The code or module to execute.
    pub payload: ExecutionPayload,
    /// Command-line arguments passed to the executed program.
    pub argv: Vec<String>,
    /// Optional stdin bytes fed to the executed program.
    pub stdin: Option<Vec<u8>>,
    /// Optional structured JSON input injected through a controlled harness.
    pub input: Option<Value>,
    /// The sandbox policy for this execution.
    pub sandbox: SandboxPolicy,
    /// Optional execution identity for audit and telemetry correlation.
    pub identity: Option<String>,
}

/// Terminal status of an execution.
///
/// Distinguishes compile failures from runtime failures, timeouts, and rejections.
///
/// # Example
///
/// ```rust
/// use adk_code::ExecutionStatus;
///
/// let status = ExecutionStatus::CompileFailed;
/// assert_ne!(status, ExecutionStatus::Failed);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ExecutionStatus {
    /// Execution completed successfully.
    Success,
    /// Execution exceeded the configured timeout.
    Timeout,
    /// Compilation or build step failed (distinct from runtime failure).
    CompileFailed,
    /// Runtime execution failed.
    Failed,
    /// Execution was rejected before running (policy or scope check).
    Rejected,
}

/// Execution metadata for telemetry, audit, and artifact correlation.
///
/// Captures backend name, language, duration, status, and correlation identity
/// so that executions can be traced and audited across sessions and invocations.
///
/// # Example
///
/// ```rust
/// use adk_code::{ExecutionMetadata, ExecutionLanguage, ExecutionStatus, ExecutionIsolation};
///
/// let meta = ExecutionMetadata {
///     backend_name: "rust-sandbox".to_string(),
///     language: ExecutionLanguage::Rust,
///     isolation: ExecutionIsolation::HostLocal,
///     status: ExecutionStatus::Success,
///     duration_ms: 42,
///     identity: Some("inv-123".to_string()),
///     artifact_refs: vec![],
/// };
/// assert_eq!(meta.backend_name, "rust-sandbox");
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecutionMetadata {
    /// Name of the backend that executed the request.
    pub backend_name: String,
    /// Language that was executed.
    pub language: ExecutionLanguage,
    /// Isolation class of the backend.
    pub isolation: ExecutionIsolation,
    /// Terminal execution status.
    pub status: ExecutionStatus,
    /// Execution wall-clock duration in milliseconds.
    pub duration_ms: u64,
    /// Correlation identity (invocation ID, session ID, etc.) when available.
    pub identity: Option<String>,
    /// References to artifacts stored externally (e.g., large outputs).
    pub artifact_refs: Vec<ArtifactRef>,
}

/// Reference to an externally stored artifact.
///
/// When execution output exceeds inline size limits, the result can reference
/// artifacts stored through ADK artifact mechanisms instead of forcing large
/// binary data into inline JSON strings.
///
/// # Example
///
/// ```rust
/// use adk_code::ArtifactRef;
///
/// let artifact = ArtifactRef {
///     key: "stdout-full".to_string(),
///     size_bytes: 2_000_000,
///     content_type: Some("text/plain".to_string()),
/// };
/// assert_eq!(artifact.key, "stdout-full");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ArtifactRef {
    /// Artifact storage key or identifier.
    pub key: String,
    /// Size of the artifact in bytes.
    pub size_bytes: u64,
    /// MIME content type, if known.
    pub content_type: Option<String>,
}

/// Structured result of a code execution.
///
/// Captures stdout, stderr, structured output, truncation flags, exit code,
/// duration, and optional execution metadata so downstream consumers can
/// reason about outcomes reliably.
///
/// # Example
///
/// ```rust
/// use adk_code::{ExecutionResult, ExecutionStatus};
///
/// let result = ExecutionResult {
///     status: ExecutionStatus::Success,
///     stdout: "hello\n".to_string(),
///     stderr: String::new(),
///     output: Some(serde_json::json!({ "answer": 42 })),
///     exit_code: Some(0),
///     stdout_truncated: false,
///     stderr_truncated: false,
///     duration_ms: 37,
///     metadata: None,
/// };
/// assert_eq!(result.status, ExecutionStatus::Success);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecutionResult {
    /// Terminal execution status.
    pub status: ExecutionStatus,
    /// Captured stdout text (may be truncated).
    pub stdout: String,
    /// Captured stderr text (may be truncated).
    pub stderr: String,
    /// Optional structured JSON output from the executed code.
    pub output: Option<Value>,
    /// Process exit code, if available.
    pub exit_code: Option<i32>,
    /// Whether stdout was truncated due to size limits.
    pub stdout_truncated: bool,
    /// Whether stderr was truncated due to size limits.
    pub stderr_truncated: bool,
    /// Execution wall-clock duration in milliseconds.
    pub duration_ms: u64,
    /// Optional execution metadata for telemetry and audit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<ExecutionMetadata>,
}