Skip to main content

everruns_contracts/
session_sandbox.rs

1//! Provider-neutral managed session sandbox contracts.
2
3use crate::tools::ToolExecutionResult;
4use serde::{Deserialize, Serialize};
5use serde_json::{Value, json};
6
7/// Capability id for the managed session sandbox capability.
8pub const SESSION_SANDBOX_CAPABILITY_ID: &str = "session_sandbox";
9/// Secret name used to persist the managed sandbox record for a session.
10pub const SESSION_SANDBOX_SECRET_NAME: &str = "session_sandbox";
11/// Default idle timeout for auto-pausing the managed sandbox.
12pub const DEFAULT_SESSION_SANDBOX_IDLE_TIMEOUT_SECS: u64 = 180;
13
14/// Session sandbox configuration.
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
16pub struct SessionSandboxConfig {
17    /// Concrete provider id (e.g. `daytona`).
18    pub provider: String,
19    /// Start the sandbox proactively when the session is created.
20    #[serde(default = "default_true")]
21    pub auto_start: bool,
22    /// Pause the sandbox after this much session inactivity.
23    #[serde(default = "default_idle_timeout")]
24    pub idle_pause_after_seconds: u64,
25    /// Whether the control plane should pause this sandbox when the timeout elapses.
26    #[serde(default = "default_true")]
27    pub idle_pause_enabled: bool,
28    /// Provider-specific extra configuration.
29    #[serde(default = "default_provider_config")]
30    pub provider_config: Value,
31    /// Optional one-time initialization commands executed after create.
32    #[serde(default)]
33    pub init: SessionSandboxInitConfig,
34}
35
36impl Default for SessionSandboxConfig {
37    fn default() -> Self {
38        Self {
39            provider: String::new(),
40            auto_start: true,
41            idle_pause_after_seconds: DEFAULT_SESSION_SANDBOX_IDLE_TIMEOUT_SECS,
42            idle_pause_enabled: true,
43            provider_config: default_provider_config(),
44            init: SessionSandboxInitConfig::default(),
45        }
46    }
47}
48
49/// One-time sandbox initialization.
50#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
51pub struct SessionSandboxInitConfig {
52    #[serde(default)]
53    pub commands: Vec<String>,
54}
55
56/// Runtime lifecycle status of the managed sandbox.
57#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
58#[serde(rename_all = "snake_case")]
59pub enum SessionSandboxStatus {
60    Running,
61    Paused,
62    /// The provider resource disappeared and must be replaced before use.
63    Lost,
64}
65
66/// Provider-owned physical environment instance record.
67#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
68pub struct SessionSandboxInstance {
69    /// Provider-specific stable identifier (e.g. Daytona sandbox id).
70    pub external_id: String,
71    /// Optional human-readable name.
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub display_name: Option<String>,
74    /// Optional default workspace path inside the sandbox.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub workspace_path: Option<String>,
77    /// Provider-specific non-secret payload needed for resume/ops.
78    #[serde(default)]
79    pub provider_state: Value,
80    /// Provider-specific non-secret metadata for UI/debugging.
81    #[serde(default)]
82    pub metadata: Value,
83}
84
85/// Persisted managed environment state.
86#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
87pub struct SessionSandboxState {
88    /// Hosted logical-sandbox identity and incarnation fence. Legacy secret
89    /// records omit it and acquire one when they are adopted into durable
90    /// control-plane state.
91    #[serde(skip)]
92    pub sandbox: Option<crate::sandbox_checkpoint::SandboxRef>,
93    pub provider: String,
94    pub status: SessionSandboxStatus,
95    pub instance: SessionSandboxInstance,
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub init_completed_at: Option<String>,
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub last_init_error: Option<String>,
100    pub created_at: String,
101    pub updated_at: String,
102}
103
104/// Provider-neutral exec request.
105#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
106pub struct SessionSandboxExecRequest {
107    pub command: String,
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub cwd: Option<String>,
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub timeout_ms: Option<u64>,
112    #[serde(default = "default_output_mode")]
113    pub output_mode: String,
114}
115
116/// Provider-neutral exec result.
117#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
118pub struct SessionSandboxExecResponse {
119    pub exit_code: i32,
120    pub stdout: String,
121    pub stderr: String,
122    pub success: bool,
123    pub truncated: bool,
124    pub total_lines: usize,
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub raw_output: Option<String>,
127    #[serde(skip_serializing_if = "Option::is_none")]
128    pub hint: Option<String>,
129}
130
131/// Provider-neutral file read result.
132#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
133pub struct SessionSandboxReadFileResponse {
134    pub path: String,
135    pub content: String,
136    pub encoding: String,
137}
138
139/// Provider-neutral file write result.
140#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
141pub struct SessionSandboxWriteFileResponse {
142    pub path: String,
143    pub bytes_written: usize,
144}
145
146/// Provider-neutral status view.
147#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
148pub struct SessionSandboxStatusResponse {
149    pub provider: String,
150    pub session_status: SessionSandboxStatus,
151    pub external_id: String,
152    #[serde(skip_serializing_if = "Option::is_none")]
153    pub display_name: Option<String>,
154    #[serde(skip_serializing_if = "Option::is_none")]
155    pub workspace_path: Option<String>,
156    #[serde(default)]
157    pub metadata: Value,
158}
159
160/// Session-scoped services used by a sandbox provider. Hosts supply the adapter;
161/// provider implementations never need a runtime or control-plane context type.
162#[async_trait::async_trait]
163pub trait SessionSandboxContext: Send + Sync {
164    fn session_id(&self) -> crate::typed_id::SessionId;
165
166    /// Clone the service handle for long-running lease heartbeats.
167    fn clone_context(&self) -> std::sync::Arc<dyn SessionSandboxContext>;
168
169    async fn connection_token(&self, provider: &str)
170    -> Result<Option<String>, ToolExecutionResult>;
171
172    /// Non-secret labels for resources created on behalf of this session.
173    async fn resource_labels(&self) -> serde_json::Map<String, Value>;
174
175    /// Refresh the cleanup lease, when the host supports leased resources.
176    async fn refresh_lease(&self, lease: SessionSandboxLease) -> Result<(), ToolExecutionResult>;
177
178    async fn release_lease(
179        &self,
180        provider: &str,
181        external_id: &str,
182    ) -> Result<(), ToolExecutionResult>;
183}
184
185/// Non-secret resource metadata for a sandbox cleanup lease. The context resolves
186/// the owner from its bound connection rather than accepting ownership input.
187#[derive(Debug, Clone)]
188pub struct SessionSandboxLease {
189    pub provider: String,
190    pub external_id: String,
191    pub display_name: Option<String>,
192    pub duration_seconds: u32,
193    pub metadata: Value,
194}
195
196/// Provider trait implemented by integration crates.
197#[async_trait::async_trait]
198pub trait SessionSandboxProvider: Send + Sync {
199    fn id(&self) -> &str;
200
201    async fn create(
202        &self,
203        context: &dyn SessionSandboxContext,
204        config: &SessionSandboxConfig,
205    ) -> Result<SessionSandboxInstance, ToolExecutionResult>;
206
207    async fn resume(
208        &self,
209        context: &dyn SessionSandboxContext,
210        config: &SessionSandboxConfig,
211        instance: &SessionSandboxInstance,
212    ) -> Result<SessionSandboxInstance, ToolExecutionResult>;
213
214    async fn pause(
215        &self,
216        context: &dyn SessionSandboxContext,
217        config: &SessionSandboxConfig,
218        instance: &SessionSandboxInstance,
219    ) -> Result<SessionSandboxInstance, ToolExecutionResult>;
220
221    async fn delete(
222        &self,
223        context: &dyn SessionSandboxContext,
224        config: &SessionSandboxConfig,
225        instance: &SessionSandboxInstance,
226    ) -> Result<(), ToolExecutionResult>;
227
228    async fn exec(
229        &self,
230        context: &dyn SessionSandboxContext,
231        config: &SessionSandboxConfig,
232        instance: &SessionSandboxInstance,
233        request: &SessionSandboxExecRequest,
234    ) -> Result<SessionSandboxExecResponse, ToolExecutionResult>;
235
236    async fn read_file(
237        &self,
238        context: &dyn SessionSandboxContext,
239        config: &SessionSandboxConfig,
240        instance: &SessionSandboxInstance,
241        path: &str,
242    ) -> Result<SessionSandboxReadFileResponse, ToolExecutionResult>;
243
244    async fn write_file(
245        &self,
246        context: &dyn SessionSandboxContext,
247        config: &SessionSandboxConfig,
248        instance: &SessionSandboxInstance,
249        path: &str,
250        content: &[u8],
251    ) -> Result<SessionSandboxWriteFileResponse, ToolExecutionResult>;
252
253    /// Persist the current workspace after a completed mutating operation.
254    /// Providers without disposable local filesystems may keep the default.
255    async fn checkpoint(
256        &self,
257        _context: &dyn SessionSandboxContext,
258        _config: &SessionSandboxConfig,
259        instance: &SessionSandboxInstance,
260    ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
261        Ok(instance.clone())
262    }
263
264    /// Point the provider's recovery state at `revision`, or clear it when
265    /// `None`, without touching the running workspace.
266    ///
267    /// Reconciliation decides which revision a session may recover to from the
268    /// checkpoint records; this is how that decision reaches the provider state
269    /// the restore actually reads. Providers with no recovery state keep the
270    /// default: there is nothing to rewind, and reconciliation is a no-op for
271    /// them.
272    async fn rewind_checkpoint(
273        &self,
274        _context: &dyn SessionSandboxContext,
275        _config: &SessionSandboxConfig,
276        instance: &SessionSandboxInstance,
277        _revision: Option<&str>,
278    ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
279        Ok(instance.clone())
280    }
281
282    async fn status(
283        &self,
284        context: &dyn SessionSandboxContext,
285        config: &SessionSandboxConfig,
286        state: &SessionSandboxState,
287    ) -> Result<SessionSandboxStatusResponse, ToolExecutionResult>;
288}
289
290/// Inventory registration point for concrete session sandbox providers.
291#[cfg(feature = "session-sandbox")]
292pub struct SessionSandboxProviderPlugin {
293    pub factory: fn() -> Box<dyn SessionSandboxProvider>,
294}
295
296#[cfg(feature = "session-sandbox")]
297inventory::collect!(SessionSandboxProviderPlugin);
298
299/// Look up a registered provider by id.
300#[cfg(feature = "session-sandbox")]
301pub fn create_session_sandbox_provider(
302    provider_id: &str,
303) -> Option<Box<dyn SessionSandboxProvider>> {
304    inventory::iter::<SessionSandboxProviderPlugin>
305        .into_iter()
306        .map(|plugin| (plugin.factory)())
307        .find(|provider| provider.id() == provider_id)
308}
309
310fn default_true() -> bool {
311    true
312}
313fn default_idle_timeout() -> u64 {
314    DEFAULT_SESSION_SANDBOX_IDLE_TIMEOUT_SECS
315}
316fn default_provider_config() -> Value {
317    json!({})
318}
319fn default_output_mode() -> String {
320    // EVE-489: persistence-first default for exec-style sandbox tools.
321    "auto".to_string()
322}