1use crate::tools::ToolExecutionResult;
4use serde::{Deserialize, Serialize};
5use serde_json::{Value, json};
6#[cfg(feature = "openapi")]
7use utoipa::ToSchema;
8use uuid::Uuid;
9
10pub const SESSION_SANDBOX_CAPABILITY_ID: &str = "session_sandbox";
12pub const SESSION_SANDBOX_SECRET_NAME: &str = "session_sandbox";
14pub const DEFAULT_SESSION_SANDBOX_IDLE_TIMEOUT_SECS: u64 = 180;
16
17pub const LABEL_EVERRUNS: &str = "everruns";
20pub const LABEL_MANAGED: &str = "everruns.managed";
24pub const LABEL_ORG_ID: &str = "everruns.org_id";
26pub const LABEL_SESSION_ID: &str = "everruns.session_id";
31
32#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
34pub struct SessionSandboxConfig {
35 pub provider: String,
37 #[serde(default = "default_true")]
39 pub auto_start: bool,
40 #[serde(default = "default_idle_timeout")]
42 pub idle_pause_after_seconds: u64,
43 #[serde(default = "default_true")]
45 pub idle_pause_enabled: bool,
46 #[serde(default)]
49 pub credential: SessionSandboxCredential,
50 #[serde(default = "default_provider_config")]
52 pub provider_config: Value,
53 #[serde(default)]
55 pub init: SessionSandboxInitConfig,
56}
57
58impl SessionSandboxConfig {
59 pub fn desktop(&self) -> Option<Value> {
66 match self.provider_config.get("desktop") {
67 Some(Value::Bool(true)) => Some(Value::Object(Default::default())),
68 Some(Value::Object(settings)) => {
69 let mut settings = settings.clone();
70 settings.remove(DESKTOP_RECORD_KEY);
71 Some(Value::Object(settings))
72 }
73 _ => None,
74 }
75 }
76
77 pub fn desktop_recording(&self) -> bool {
80 self.desktop().is_some()
81 && self
82 .provider_config
83 .get("desktop")
84 .and_then(|desktop| desktop.get(DESKTOP_RECORD_KEY))
85 .and_then(Value::as_bool)
86 .unwrap_or(true)
87 }
88}
89
90pub const DESKTOP_RECORD_KEY: &str = "record";
92
93pub type RecordingBody = futures::stream::BoxStream<'static, Result<Vec<u8>, String>>;
95
96pub struct DesktopRecording {
104 pub file_name: String,
106 pub duration_seconds: Option<f64>,
108 pub size_bytes: u64,
110 pub body: Option<RecordingBody>,
112 pub remove: futures::future::BoxFuture<'static, Result<(), String>>,
114}
115
116impl std::fmt::Debug for DesktopRecording {
117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118 f.debug_struct("DesktopRecording")
119 .field("file_name", &self.file_name)
120 .field("duration_seconds", &self.duration_seconds)
121 .field("size_bytes", &self.size_bytes)
122 .field("has_body", &self.body.is_some())
123 .finish_non_exhaustive()
124 }
125}
126
127impl Default for SessionSandboxConfig {
128 fn default() -> Self {
129 Self {
130 provider: String::new(),
131 auto_start: true,
132 idle_pause_after_seconds: DEFAULT_SESSION_SANDBOX_IDLE_TIMEOUT_SECS,
133 idle_pause_enabled: true,
134 credential: SessionSandboxCredential::default(),
135 provider_config: default_provider_config(),
136 init: SessionSandboxInitConfig::default(),
137 }
138 }
139}
140
141#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
143#[cfg_attr(feature = "openapi", derive(ToSchema))]
144#[serde(rename_all = "snake_case")]
145pub enum SessionSandboxCredentialSource {
146 #[default]
147 None,
148 SessionUser,
149 Agent,
150 Organization,
151 Platform,
154}
155
156#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
158#[cfg_attr(feature = "openapi", derive(ToSchema))]
159pub struct SessionSandboxCredential {
160 #[cfg_attr(feature = "openapi", schema(example = "session_user"))]
162 pub source: SessionSandboxCredentialSource,
163 #[serde(default, skip_serializing_if = "Option::is_none")]
165 #[cfg_attr(
166 feature = "openapi",
167 schema(example = "00000000-0000-0000-0000-000000000001")
168 )]
169 pub virtual_user_id: Option<Uuid>,
170 #[serde(default, skip_serializing_if = "Option::is_none")]
173 #[cfg_attr(
174 feature = "openapi",
175 schema(example = "00000000-0000-0000-0000-000000000002")
176 )]
177 pub connection_id: Option<Uuid>,
178}
179
180#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
182pub struct SessionSandboxInitConfig {
183 #[serde(default)]
184 pub commands: Vec<String>,
185}
186
187#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
189#[serde(rename_all = "snake_case")]
190pub enum SessionSandboxStatus {
191 Running,
192 Paused,
193 Lost,
195}
196
197#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
199pub struct SessionSandboxInstance {
200 pub external_id: String,
202 #[serde(skip_serializing_if = "Option::is_none")]
204 pub display_name: Option<String>,
205 #[serde(skip_serializing_if = "Option::is_none")]
207 pub workspace_path: Option<String>,
208 #[serde(default)]
210 pub provider_state: Value,
211 #[serde(default)]
213 pub metadata: Value,
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
218pub struct SessionSandboxState {
219 #[serde(skip)]
223 pub sandbox: Option<crate::sandbox_checkpoint::SandboxRef>,
224 pub provider: String,
225 pub status: SessionSandboxStatus,
226 pub instance: SessionSandboxInstance,
227 #[serde(skip_serializing_if = "Option::is_none")]
228 pub init_completed_at: Option<String>,
229 #[serde(skip_serializing_if = "Option::is_none")]
230 pub last_init_error: Option<String>,
231 pub created_at: String,
232 pub updated_at: String,
233}
234
235#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
237pub struct SessionSandboxExecRequest {
238 pub command: String,
239 #[serde(skip_serializing_if = "Option::is_none")]
240 pub cwd: Option<String>,
241 #[serde(skip_serializing_if = "Option::is_none")]
242 pub timeout_ms: Option<u64>,
243 #[serde(default = "default_output_mode")]
244 pub output_mode: String,
245}
246
247#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
249pub struct SessionSandboxExecResponse {
250 pub exit_code: i32,
251 pub stdout: String,
252 pub stderr: String,
253 pub success: bool,
254 pub truncated: bool,
255 pub total_lines: usize,
256 #[serde(skip_serializing_if = "Option::is_none")]
257 pub raw_output: Option<String>,
258 #[serde(skip_serializing_if = "Option::is_none")]
259 pub hint: Option<String>,
260}
261
262#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
264pub struct SessionSandboxReadFileResponse {
265 pub path: String,
266 pub content: String,
267 pub encoding: String,
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
272pub struct SessionSandboxWriteFileResponse {
273 pub path: String,
274 pub bytes_written: usize,
275}
276
277#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
279pub struct SessionSandboxStatusResponse {
280 pub provider: String,
281 pub session_status: SessionSandboxStatus,
282 pub external_id: String,
283 #[serde(skip_serializing_if = "Option::is_none")]
284 pub display_name: Option<String>,
285 #[serde(skip_serializing_if = "Option::is_none")]
286 pub workspace_path: Option<String>,
287 #[serde(default)]
288 pub metadata: Value,
289}
290
291#[async_trait::async_trait]
294pub trait SessionSandboxContext: Send + Sync {
295 fn session_id(&self) -> crate::typed_id::SessionId;
296
297 fn clone_context(&self) -> std::sync::Arc<dyn SessionSandboxContext>;
299
300 async fn connection_token(&self, provider: &str)
301 -> Result<Option<String>, ToolExecutionResult>;
302
303 async fn sandbox_connection_token(
307 &self,
308 provider: &str,
309 credential: &SessionSandboxCredential,
310 ) -> Result<Option<String>, ToolExecutionResult>;
311
312 async fn resource_labels(&self) -> serde_json::Map<String, Value>;
314
315 #[cfg(feature = "runtime")]
319 fn network_access(&self) -> Option<crate::runtime::network_access::NetworkAccessList> {
320 None
321 }
322
323 #[cfg(feature = "runtime")]
328 fn sandbox_proxy_credential(
329 &self,
330 _valid_for: std::time::Duration,
331 ) -> Result<Option<crate::runtime::SandboxProxyCredential>, ToolExecutionResult> {
332 Ok(None)
333 }
334
335 async fn managed_resource_labels(&self) -> serde_json::Map<String, Value> {
338 let mut labels = self.resource_labels().await;
339 labels.insert(LABEL_MANAGED.to_string(), json!("true"));
340 labels
341 }
342
343 async fn get_provider_secret(
347 &self,
348 _name: &str,
349 ) -> Result<Option<String>, ToolExecutionResult> {
350 Ok(None)
351 }
352
353 async fn set_provider_secret(
354 &self,
355 _name: &str,
356 _value: &str,
357 ) -> Result<(), ToolExecutionResult> {
358 Err(ToolExecutionResult::internal_error_msg(
359 "Sandbox provider secret storage is unavailable",
360 ))
361 }
362
363 async fn delete_provider_secret(&self, _name: &str) -> Result<(), ToolExecutionResult> {
364 Ok(())
365 }
366
367 async fn refresh_lease(&self, lease: SessionSandboxLease) -> Result<(), ToolExecutionResult>;
369
370 async fn release_lease(
371 &self,
372 provider: &str,
373 external_id: &str,
374 ) -> Result<(), ToolExecutionResult>;
375}
376
377#[derive(Debug, Clone)]
380pub struct SessionSandboxLease {
381 pub provider: String,
382 pub external_id: String,
383 pub display_name: Option<String>,
384 pub duration_seconds: u32,
385 pub credential: SessionSandboxCredential,
386 pub metadata: Value,
387}
388
389#[derive(Debug, Clone, PartialEq, Eq)]
391pub struct OwnedSandbox {
392 pub external_id: String,
393 pub labels: std::collections::BTreeMap<String, String>,
395 pub state: String,
397 pub active: bool,
399 pub created_at: Option<chrono::DateTime<chrono::Utc>>,
400}
401
402#[derive(Debug, Clone, PartialEq, Eq)]
404pub enum SandboxAdminError {
405 Unsupported,
407 Provider(String),
408}
409
410impl std::fmt::Display for SandboxAdminError {
411 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
412 match self {
413 Self::Unsupported => f.write_str("operation unsupported by this provider"),
414 Self::Provider(message) => f.write_str(message),
415 }
416 }
417}
418
419impl std::error::Error for SandboxAdminError {}
420
421#[async_trait::async_trait]
423pub trait SessionSandboxProvider: Send + Sync {
424 fn id(&self) -> &str;
425
426 async fn list_owned(
430 &self,
431 _token: &str,
432 _labels: &std::collections::BTreeMap<String, String>,
433 ) -> Result<Vec<OwnedSandbox>, SandboxAdminError> {
434 Err(SandboxAdminError::Unsupported)
435 }
436
437 async fn stop_by_id(&self, _token: &str, _external_id: &str) -> Result<(), SandboxAdminError> {
440 Err(SandboxAdminError::Unsupported)
441 }
442
443 async fn delete_by_id(
446 &self,
447 _token: &str,
448 _external_id: &str,
449 ) -> Result<(), SandboxAdminError> {
450 Err(SandboxAdminError::Unsupported)
451 }
452
453 async fn create(
454 &self,
455 context: &dyn SessionSandboxContext,
456 config: &SessionSandboxConfig,
457 ) -> Result<SessionSandboxInstance, ToolExecutionResult>;
458
459 async fn resume(
460 &self,
461 context: &dyn SessionSandboxContext,
462 config: &SessionSandboxConfig,
463 instance: &SessionSandboxInstance,
464 ) -> Result<SessionSandboxInstance, ToolExecutionResult>;
465
466 async fn pause(
467 &self,
468 context: &dyn SessionSandboxContext,
469 config: &SessionSandboxConfig,
470 instance: &SessionSandboxInstance,
471 ) -> Result<SessionSandboxInstance, ToolExecutionResult>;
472
473 async fn delete(
474 &self,
475 context: &dyn SessionSandboxContext,
476 config: &SessionSandboxConfig,
477 instance: &SessionSandboxInstance,
478 ) -> Result<(), ToolExecutionResult>;
479
480 async fn exec(
481 &self,
482 context: &dyn SessionSandboxContext,
483 config: &SessionSandboxConfig,
484 instance: &SessionSandboxInstance,
485 request: &SessionSandboxExecRequest,
486 ) -> Result<SessionSandboxExecResponse, ToolExecutionResult>;
487
488 async fn read_file(
489 &self,
490 context: &dyn SessionSandboxContext,
491 config: &SessionSandboxConfig,
492 instance: &SessionSandboxInstance,
493 path: &str,
494 ) -> Result<SessionSandboxReadFileResponse, ToolExecutionResult>;
495
496 async fn write_file(
497 &self,
498 context: &dyn SessionSandboxContext,
499 config: &SessionSandboxConfig,
500 instance: &SessionSandboxInstance,
501 path: &str,
502 content: &[u8],
503 ) -> Result<SessionSandboxWriteFileResponse, ToolExecutionResult>;
504
505 async fn checkpoint(
508 &self,
509 _context: &dyn SessionSandboxContext,
510 _config: &SessionSandboxConfig,
511 instance: &SessionSandboxInstance,
512 ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
513 Ok(instance.clone())
514 }
515
516 async fn rewind_checkpoint(
525 &self,
526 _context: &dyn SessionSandboxContext,
527 _config: &SessionSandboxConfig,
528 instance: &SessionSandboxInstance,
529 _revision: Option<&str>,
530 ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
531 Ok(instance.clone())
532 }
533
534 #[cfg(feature = "runtime")]
538 async fn open_desktop(
539 &self,
540 _context: &dyn SessionSandboxContext,
541 _config: &SessionSandboxConfig,
542 _instance: &SessionSandboxInstance,
543 _display: crate::runtime::computer_use::DisplaySize,
544 ) -> Result<Box<dyn crate::runtime::computer_use::ComputerSession>, ToolExecutionResult> {
545 Err(ToolExecutionResult::tool_error(format!(
546 "the {} sandbox has no desktop",
547 self.id()
548 )))
549 }
550
551 async fn collect_desktop_recordings(
556 &self,
557 _context: &dyn SessionSandboxContext,
558 _config: &SessionSandboxConfig,
559 _instance: &SessionSandboxInstance,
560 ) -> Result<Vec<DesktopRecording>, ToolExecutionResult> {
561 Ok(Vec::new())
562 }
563
564 async fn status(
565 &self,
566 context: &dyn SessionSandboxContext,
567 config: &SessionSandboxConfig,
568 state: &SessionSandboxState,
569 ) -> Result<SessionSandboxStatusResponse, ToolExecutionResult>;
570}
571
572#[cfg(feature = "session-sandbox")]
574pub struct SessionSandboxProviderPlugin {
575 pub factory: fn() -> Box<dyn SessionSandboxProvider>,
576}
577
578#[cfg(feature = "session-sandbox")]
579inventory::collect!(SessionSandboxProviderPlugin);
580
581#[cfg(feature = "session-sandbox")]
583pub fn create_session_sandbox_provider(
584 provider_id: &str,
585) -> Option<Box<dyn SessionSandboxProvider>> {
586 inventory::iter::<SessionSandboxProviderPlugin>
587 .into_iter()
588 .map(|plugin| (plugin.factory)())
589 .find(|provider| provider.id() == provider_id)
590}
591
592fn default_true() -> bool {
593 true
594}
595fn default_idle_timeout() -> u64 {
596 DEFAULT_SESSION_SANDBOX_IDLE_TIMEOUT_SECS
597}
598fn default_provider_config() -> Value {
599 json!({})
600}
601fn default_output_mode() -> String {
602 "auto".to_string()
604}
605
606#[cfg(test)]
607mod desktop_tests {
608 use super::*;
609
610 fn config(provider_config: Value) -> SessionSandboxConfig {
611 SessionSandboxConfig {
612 provider: "daytona".to_string(),
613 provider_config,
614 ..Default::default()
615 }
616 }
617
618 #[test]
619 fn desktops_are_recorded_unless_turned_off() {
620 assert!(config(json!({"desktop": true})).desktop_recording());
621 assert!(config(json!({"desktop": {"display_width": 800}})).desktop_recording());
622 assert!(!config(json!({"desktop": {"record": false}})).desktop_recording());
623 assert!(!config(json!({})).desktop_recording());
624 assert!(!config(json!({"desktop": false, "record": true})).desktop_recording());
625 }
626
627 #[test]
628 fn the_record_switch_is_not_a_computer_use_setting() {
629 let settings = config(json!({"desktop": {"record": false, "display_width": 800}}))
630 .desktop()
631 .unwrap();
632 assert_eq!(settings, json!({"display_width": 800}));
633 }
634}