Skip to content

Computer use CLI for AI agents

feat: add the sandbox command (#505)

Lahfirc559ecf7930c
diff --git a/AGENTS.md b/AGENTS.md
index 21b6223d1..f06bbe12e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -197,7 +197,8 @@ remain the transitive check.
its delivery disposition.
- Codes: `PERM_DENIED`, `ELEMENT_NOT_FOUND`, `APP_NOT_FOUND`, `ACTION_FAILED`, `ACTION_NOT_SUPPORTED`, `STALE_REF`,
`AMBIGUOUS_TARGET`, `WINDOW_NOT_FOUND`, `PLATFORM_NOT_SUPPORTED`, `TIMEOUT`, `INVALID_ARGS`,
- `NOTIFICATION_NOT_FOUND`, `SNAPSHOT_NOT_FOUND`, `POLICY_DENIED`, `APP_UNRESPONSIVE`, `INTERNAL`.
+ `NOTIFICATION_NOT_FOUND`, `SNAPSHOT_NOT_FOUND`, `SANDBOX_NOT_FOUND`, `POLICY_DENIED`, `APP_UNRESPONSIVE`,
+ `INTERNAL`.
- Exit codes: `0` success, `1` structured error, `2` argument or parse error.
## Output contract
@@ -269,11 +270,11 @@ Every command prints one envelope. `docs/json-output.md` holds the full contract
## Command surface
-60 commands spanning App/Window, Observation, Interaction, Scroll, Keyboard, Mouse, Notifications, Clipboard, Wait,
-System (including `session`, `trace`, `skills`) and Batch. 56 of the 60 command names are operational on macOS; the
-four held-input names (`key-down`, `key-up`, `mouse-down`, `mouse-up`) fail closed. Windows and Linux expose the same
-command names. Each platform's limits are in its skill (`skills/agent-desktop-macos/`, `skills/agent-desktop-windows/`,
-`skills/agent-desktop-linux/`).
+61 commands spanning App/Window, Observation, Interaction, Scroll, Keyboard, Mouse, Notifications, Clipboard, Wait,
+System (including `session`, `trace`, `skills`), Sandboxes (`sandbox`) and Batch.
+57 of the 61 command names are operational on macOS; the four held-input names (`key-down`, `key-up`, `mouse-down`,
+`mouse-up`) fail closed. Windows and Linux expose the same command names. Each platform's limits are in its skill
+(`skills/agent-desktop-macos/`, `skills/agent-desktop-windows/`, `skills/agent-desktop-linux/`).
## Definition of done
diff --git a/README.md b/README.md
index 32dee9630..7b592641a 100644
--- a/README.md
+++ b/README.md
@@ -121,11 +121,11 @@ Retry a failed command only when `error.disposition.retry` is `safe`. See [JSON
{ "mcpServers": { "agent-desktop": { "command": "agent-desktop", "args": ["mcp"] } } }
```
-Global flags given to `mcp`, such as `--session`, `--headed` or `--trace`, apply to every call.
+Global flags given to `mcp`, such as `--session`, `--headed` or `--trace`, apply to every call except `sandbox exec`, whose guest command takes its own flags.
## Commands
-agent-desktop has 60 command names, 56 operational commands. The other four (`key-down`, `key-up`, `mouse-down`, `mouse-up`) refuse to run until a daemon can release a held key or button. [Commands](https://agent-browser.dev/desktop/commands) documents each one.
+agent-desktop has 61 command names, 57 operational commands. The other four (`key-down`, `key-up`, `mouse-down`, `mouse-up`) refuse to run until a daemon can release a held key or button. [Commands](https://agent-browser.dev/desktop/commands) documents each one.
| Group | Commands |
|---|---|
@@ -137,6 +137,7 @@ agent-desktop has 60 command names, 56 operational commands. The other four (`ke
| Clipboard | `clipboard-get`, `clipboard-set`, `clipboard-clear` |
| Wait | `wait` |
| Sessions | `session`, `trace`, `cursor-overlay` |
+| Sandboxes | `sandbox` |
| System | `status`, `permissions`, `version`, `batch`, `skills` |
## Platform support
diff --git a/apps/docs/content/docs/errors-and-recovery.mdx b/apps/docs/content/docs/errors-and-recovery.mdx
index 6f5704a3b..3d18440b5 100644
--- a/apps/docs/content/docs/errors-and-recovery.mdx
+++ b/apps/docs/content/docs/errors-and-recovery.mdx
@@ -62,6 +62,7 @@ A failed command prints an envelope with `ok: false` and exits `1` (or `2` for a
<tr><td><code>INVALID_ARGS</code></td><td>An argument is invalid. Also returned for a bare <code>@eN</code> ref and an ended session.</td><td>Fix the input. Repeating the same arguments fails the same way.</td></tr>
<tr><td><code>NOTIFICATION_NOT_FOUND</code></td><td>The notification index or identity no longer matches.</td><td>Run <code>list-notifications</code> again.</td></tr>
<tr><td><code>SNAPSHOT_NOT_FOUND</code></td><td>The snapshot id is missing, pruned, or belongs to another <a href="/desktop/sessions">session</a> namespace.</td><td>Take a snapshot in the same session scope you act in, then use its refs.</td></tr>
+ <tr><td><code>SANDBOX_NOT_FOUND</code></td><td>No sandbox has that name.</td><td>Run <code>agent-desktop sandbox list</code> to see the sandboxes that exist.</td></tr>
<tr><td><code>POLICY_DENIED</code></td><td>Headless mode blocked a physical or headed path.</td><td>Do not switch modes to recover. See <a href="/desktop/guides/headed-mode">Headed mode</a>.</td></tr>
<tr><td><code>APP_UNRESPONSIVE</code></td><td>The application stopped responding.</td><td>Wait, take a fresh snapshot, then retry only if <code>disposition.retry</code> is <code>safe</code>.</td></tr>
<tr><td><code>INTERNAL</code></td><td>An unexpected error.</td><td>Read <code>message</code>. Retry once only if <code>disposition.retry</code> is <code>safe</code>.</td></tr>
diff --git a/apps/docs/content/docs/ffi/api.mdx b/apps/docs/content/docs/ffi/api.mdx
index f13e02848..08f9b27ca 100644
--- a/apps/docs/content/docs/ffi/api.mdx
+++ b/apps/docs/content/docs/ffi/api.mdx
@@ -15,7 +15,7 @@ Enum fields inside structs are stored as `int32_t`. The library validates each o
<tr><th>Enum</th><th>Values</th></tr>
</thead>
<tbody>
- <tr><td><code>AdResult</code></td><td><code>AD_RESULT_OK</code> 0, <code>AD_RESULT_ERR_PERM_DENIED</code> -1, <code>AD_RESULT_ERR_ELEMENT_NOT_FOUND</code> -2, <code>AD_RESULT_ERR_APP_NOT_FOUND</code> -3, <code>AD_RESULT_ERR_ACTION_FAILED</code> -4, <code>AD_RESULT_ERR_ACTION_NOT_SUPPORTED</code> -5, <code>AD_RESULT_ERR_STALE_REF</code> -6, <code>AD_RESULT_ERR_WINDOW_NOT_FOUND</code> -7, <code>AD_RESULT_ERR_PLATFORM_NOT_SUPPORTED</code> -8, <code>AD_RESULT_ERR_TIMEOUT</code> -9, <code>AD_RESULT_ERR_INVALID_ARGS</code> -10, <code>AD_RESULT_ERR_NOTIFICATION_NOT_FOUND</code> -11, <code>AD_RESULT_ERR_INTERNAL</code> -12, <code>AD_RESULT_ERR_SNAPSHOT_NOT_FOUND</code> -13, <code>AD_RESULT_ERR_POLICY_DENIED</code> -14, <code>AD_RESULT_ERR_AMBIGUOUS_TARGET</code> -15, <code>AD_RESULT_ERR_APP_UNRESPONSIVE</code> -16</td></tr>
+ <tr><td><code>AdResult</code></td><td><code>AD_RESULT_OK</code> 0, <code>AD_RESULT_ERR_PERM_DENIED</code> -1, <code>AD_RESULT_ERR_ELEMENT_NOT_FOUND</code> -2, <code>AD_RESULT_ERR_APP_NOT_FOUND</code> -3, <code>AD_RESULT_ERR_ACTION_FAILED</code> -4, <code>AD_RESULT_ERR_ACTION_NOT_SUPPORTED</code> -5, <code>AD_RESULT_ERR_STALE_REF</code> -6, <code>AD_RESULT_ERR_WINDOW_NOT_FOUND</code> -7, <code>AD_RESULT_ERR_PLATFORM_NOT_SUPPORTED</code> -8, <code>AD_RESULT_ERR_TIMEOUT</code> -9, <code>AD_RESULT_ERR_INVALID_ARGS</code> -10, <code>AD_RESULT_ERR_NOTIFICATION_NOT_FOUND</code> -11, <code>AD_RESULT_ERR_INTERNAL</code> -12, <code>AD_RESULT_ERR_SNAPSHOT_NOT_FOUND</code> -13, <code>AD_RESULT_ERR_POLICY_DENIED</code> -14, <code>AD_RESULT_ERR_AMBIGUOUS_TARGET</code> -15, <code>AD_RESULT_ERR_APP_UNRESPONSIVE</code> -16, <code>AD_RESULT_ERR_SANDBOX_NOT_FOUND</code> -17</td></tr>
<tr><td><code>AdImageFormat</code></td><td><code>AD_IMAGE_FORMAT_PNG</code> 0, <code>AD_IMAGE_FORMAT_JPG</code> 1</td></tr>
<tr><td><code>AdActionKind</code></td><td><code>AD_ACTION_KIND_CLICK</code> 0, <code>AD_ACTION_KIND_DOUBLE_CLICK</code> 1, <code>AD_ACTION_KIND_RIGHT_CLICK</code> 2, <code>AD_ACTION_KIND_TRIPLE_CLICK</code> 3, <code>AD_ACTION_KIND_SET_VALUE</code> 4, <code>AD_ACTION_KIND_SET_FOCUS</code> 5, <code>AD_ACTION_KIND_EXPAND</code> 6, <code>AD_ACTION_KIND_COLLAPSE</code> 7, <code>AD_ACTION_KIND_SELECT</code> 8, <code>AD_ACTION_KIND_TOGGLE</code> 9, <code>AD_ACTION_KIND_CHECK</code> 10, <code>AD_ACTION_KIND_UNCHECK</code> 11, <code>AD_ACTION_KIND_SCROLL</code> 12, <code>AD_ACTION_KIND_SCROLL_TO</code> 13, <code>AD_ACTION_KIND_PRESS_KEY</code> 14, <code>AD_ACTION_KIND_KEY_DOWN</code> 15, <code>AD_ACTION_KIND_KEY_UP</code> 16, <code>AD_ACTION_KIND_TYPE_TEXT</code> 17, <code>AD_ACTION_KIND_CLEAR</code> 18, <code>AD_ACTION_KIND_HOVER</code> 19, <code>AD_ACTION_KIND_DRAG</code> 20</td></tr>
<tr><td><code>AdDirection</code></td><td><code>AD_DIRECTION_UP</code> 0, <code>AD_DIRECTION_DOWN</code> 1, <code>AD_DIRECTION_LEFT</code> 2, <code>AD_DIRECTION_RIGHT</code> 3</td></tr>
diff --git a/apps/docs/content/docs/ffi/ownership-and-threading.mdx b/apps/docs/content/docs/ffi/ownership-and-threading.mdx
index dc8e07789..1b2edb801 100644
--- a/apps/docs/content/docs/ffi/ownership-and-threading.mdx
+++ b/apps/docs/content/docs/ffi/ownership-and-threading.mdx
@@ -93,7 +93,7 @@ ad_release_exact_window_fields(&win);
The strings stay valid across later successful calls on the same thread; only the next failing call replaces them, like POSIX `errno`. The slot is thread-local. Retry only when the retry disposition is `AD_RETRY_DISPOSITION_SAFE`, as described in [Errors and recovery](/desktop/errors-and-recovery#disposition).
-`AdResult` codes mirror the CLI's [error codes](/desktop/errors-and-recovery#error-codes): `AD_RESULT_ERR_PERM_DENIED` is -1 through `AD_RESULT_ERR_APP_UNRESPONSIVE` at -16. The full list is on the [API page](/desktop/ffi/api#enums). Treat any negative value outside that list as an unknown error, because new codes can be appended.
+`AdResult` codes mirror the CLI's [error codes](/desktop/errors-and-recovery#error-codes): `AD_RESULT_ERR_PERM_DENIED` is -1 through `AD_RESULT_ERR_SANDBOX_NOT_FOUND` at -17. The full list is on the [API page](/desktop/ffi/api#enums). Treat any negative value outside that list as an unknown error, because new codes can be appended.
### Two failure modes for JSON entrypoints
diff --git a/apps/docs/content/docs/guides/mcp.mdx b/apps/docs/content/docs/guides/mcp.mdx
index 79c960aba..de9e5bde3 100644
--- a/apps/docs/content/docs/guides/mcp.mdx
+++ b/apps/docs/content/docs/guides/mcp.mdx
@@ -51,6 +51,8 @@ A tool cannot pass a global flag. Commands that need a session, such as `trace`
A tool returns the command's JSON envelope as `structuredContent`, and the same JSON as text. `isError` is `true` when the envelope's `ok` is `false`, so read `error.code` and `error.disposition` exactly as you would from the CLI. A `screenshot` without an output path returns its PNG as an image block instead of base64 text.
+`desktop_sandbox_exec` is the exception, because the CLI passes the guest command's stdout and exit status through unchanged. Its text is the guest's own output, empty output included, and `isError` follows the guest's exit status. When the host itself fails, such as for a sandbox that does not exist, the CLI's error envelope arrives as that same text.
+
An unknown argument returns a tool error that names the accepted arguments, and a value of the wrong type returns an error that names the argument, so the model can correct the call.
## Start with the skills
diff --git a/crates/core/src/adapter/system.rs b/crates/core/src/adapter/system.rs
index 98e99604d..445df3d34 100644
--- a/crates/core/src/adapter/system.rs
+++ b/crates/core/src/adapter/system.rs
@@ -1,10 +1,11 @@
use crate::{
- AdapterError, AdapterSession, AppInfo, CursorOverlayControl, Deadline,
- DismissAllNotificationsRequest, DismissNotificationRequest, ImageBuffer, InteractionLease,
- InteractionPolicy, KeyCombo, NotificationActionRequest, NotificationFilter, NotificationInfo,
- OperationReport, PermissionReport, PermissionState, ProcessIdentity, SessionAffinity,
- SignalBaseline, SignalFilter, WindowInfo, WindowOp, actions::action_result::ActionResult,
- system::display_info::DisplayInfo, system::screenshot_target::ScreenshotTarget,
+ AdapterError, AdapterSession, AppInfo, CursorOverlayControl, Deadline, DeliverySemantics,
+ DismissAllNotificationsRequest, DismissNotificationRequest, ErrorCode, ImageBuffer,
+ InteractionLease, InteractionPolicy, KeyCombo, NotificationActionRequest, NotificationFilter,
+ NotificationInfo, OperationReport, PermissionReport, PermissionState, ProcessIdentity,
+ ProviderScriptOutput, ProviderScriptRequest, SessionAffinity, SignalBaseline, SignalFilter,
+ WindowInfo, WindowOp, actions::action_result::ActionResult, system::display_info::DisplayInfo,
+ system::screenshot_target::ScreenshotTarget,
};
pub trait SystemOps: Send + Sync {
@@ -118,6 +119,19 @@ pub trait SystemOps: Send + Sync {
Err(AdapterError::not_supported("process_state"))
}
+ /// Runs one provider script under the platform's bounded process runner.
+ fn run_provider_script(
+ &self,
+ _request: &ProviderScriptRequest,
+ ) -> Result<ProviderScriptOutput, AdapterError> {
+ Err(AdapterError::new(
+ ErrorCode::PlatformNotSupported,
+ "Sandboxes are not available on this platform yet.",
+ )
+ .with_suggestion("Run the command on macOS to use a sandbox provider.")
+ .with_disposition(DeliverySemantics::not_delivered()))
+ }
+
fn supported_surfaces(&self) -> Vec<crate::adapter::SnapshotSurface> {
Vec::new()
}
diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rs
index 1c13048ee..556a21ea0 100644
--- a/crates/core/src/commands/mod.rs
+++ b/crates/core/src/commands/mod.rs
@@ -54,6 +54,10 @@ pub mod query;
pub mod resize_window;
pub mod restore;
pub mod right_click;
+pub mod sandbox;
+pub mod sandbox_action;
+pub mod sandbox_install;
+mod sandbox_list;
pub mod screenshot;
#[cfg(test)]
mod screenshot_tests;
diff --git a/crates/core/src/commands/sandbox.rs b/crates/core/src/commands/sandbox.rs
new file mode 100644
index 000000000..f40c43854
--- /dev/null
+++ b/crates/core/src/commands/sandbox.rs
@@ -0,0 +1,253 @@
+use std::path::{Path, PathBuf};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+use serde_json::Value;
+
+use super::sandbox_action::SandboxAction;
+use crate::sandbox::exec_passthrough::ExecPassthrough;
+use crate::sandbox::provider_dirs::{SANDBOXES_DIR, resolve};
+use crate::sandbox::provider_protocol::{exec_outcome, parse_reply, provider_refused};
+use crate::sandbox::provider_run::{ProviderCall, success_value};
+use crate::sandbox::provider_settings::parse_settings;
+use crate::sandbox::provider_spec::ProviderSpec;
+use crate::sandbox::provider_table::find_provider;
+use crate::sandbox::sandbox_name::validate_sandbox_name;
+use crate::sandbox::sandbox_record::SandboxRecord;
+use crate::sandbox::sandbox_state::SandboxState;
+use crate::sandbox::sandbox_store;
+use crate::storage::state_root::resolve_configured_state_root;
+use crate::{AdapterError, AppError, DeliverySemantics, ErrorCode, PlatformAdapter};
+
+const CREATE_TIMEOUT: Duration = Duration::from_secs(60);
+const START_TIMEOUT: Duration = Duration::from_secs(60);
+const STOP_TIMEOUT: Duration = Duration::from_secs(30);
+const STATUS_TIMEOUT: Duration = Duration::from_secs(30);
+const REMOVE_TIMEOUT: Duration = Duration::from_secs(30);
+const EXEC_TIMEOUT: Duration = Duration::from_secs(300);
+
+type Target = (&'static ProviderSpec, PathBuf, PathBuf);
+
+pub fn execute(action: SandboxAction, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
+ let root = resolve_configured_state_root()?;
+ match action {
+ SandboxAction::Install { provider } => super::sandbox_install::execute(provider, adapter),
+ SandboxAction::Create {
+ name,
+ provider,
+ set,
+ } => create(&root, &name, &provider, &set, adapter),
+ SandboxAction::Start { name, set } => {
+ let settings = parse_settings(&set)?;
+ verb_value(&root, &name, ("start", START_TIMEOUT), &settings, adapter)
+ }
+ SandboxAction::Stop { name } => {
+ verb_value(&root, &name, ("stop", STOP_TIMEOUT), &[], adapter)
+ }
+ SandboxAction::Status { name } => {
+ verb_value(&root, &name, ("status", STATUS_TIMEOUT), &[], adapter)
+ }
+ SandboxAction::List => super::sandbox_list::execute(&root, adapter),
+ SandboxAction::Rm { name } => remove(&root, &name, adapter),
+ SandboxAction::Exec { name, .. } => Err(exec_without_envelope(&name)),
+ }
+}
+
+pub fn execute_exec(
+ name: String,
+ args: Vec<String>,
+ adapter: &dyn PlatformAdapter,
+) -> Result<ExecPassthrough, AppError> {
+ let root = resolve_configured_state_root()?;
+ let (spec, provider_dir, sandboxes_root) = locate(&root, &name)?;
+ let call = ProviderCall::new(spec, &provider_dir, &sandboxes_root, Some(&name), &[]);
+ let mut guest_args = vec!["exec".to_string(), name.clone(), "--".to_string()];
+ guest_args.extend(args);
+ let output = call.run(adapter, guest_args, EXEC_TIMEOUT)?;
+ exec_outcome(spec.name, &output)
+}
+
+fn create(
+ root: &Path,
+ name: &str,
+ provider: &str,
+ set: &[String],
+ adapter: &dyn PlatformAdapter,
+) -> Result<Value, AppError> {
+ validate_sandbox_name(name)?;
+ let spec = find_provider(provider)?;
+ let settings = parse_settings(set)?;
+ let (provider_dir, sandboxes_root) = resolve(root, spec)?;
+ let _busy = sandbox_store::hold(&sandboxes_root, name)?;
+ sandbox_store::create(
+ &sandboxes_root,
+ &SandboxRecord {
+ name: name.to_string(),
+ provider: provider.to_string(),
+ created_at: unix_seconds(),
+ },
+ )?;
+ let call = ProviderCall::new(spec, &provider_dir, &sandboxes_root, Some(name), &settings);
+ let output = call
+ .run(adapter, verb_args(name, "create"), CREATE_TIMEOUT)
+ .inspect_err(|error| {
+ if never_ran(error) {
+ discard_untouched_record(&sandboxes_root, name);
+ }
+ })?;
+ let refused = provider_refused(&output);
+ parse_reply(spec.name, Some(name), true, &output)
+ .and_then(|reply| {
+ if reply.state == SandboxState::Unavailable {
+ discard_untouched_record(&sandboxes_root, name);
+ Err(unavailable_refusal(reply.message))
+ } else {
+ Ok(success_value(name, Some(spec.name), reply))
+ }
+ })
+ .map_err(|error| {
+ if refused && discard_untouched_record(&sandboxes_root, name) {
+ not_delivered(error)
+ } else {
+ error
+ }
+ })
+}
+
+fn not_delivered(error: AppError) -> AppError {
+ match error {
+ AppError::Adapter(source) => {
+ AppError::Adapter(source.with_disposition(DeliverySemantics::not_delivered()))
+ }
+ other => other,
+ }
+}
+
+fn never_ran(error: &AppError) -> bool {
+ !matches!(error, AppError::Adapter(source) if source.disposition != DeliverySemantics::not_delivered())
+}
+
+/// Drops the record of a create the provider refused and reports whether it did. Every other failed create
+/// keeps its record, because the provider may have made something that only `rm` can clear.
+fn discard_untouched_record(sandboxes_root: &Path, name: &str) -> bool {
+ let dir = sandboxes_root.join(name);
+ let Ok(entries) = std::fs::read_dir(&dir) else {
+ return false;
+ };
+ let untouched = entries
+ .filter_map(Result::ok)
+ .all(|entry| entry.file_name() == sandbox_store::RECORD_FILE);
+ untouched && sandbox_store::remove(sandboxes_root, name).is_ok()
+}
+
+fn verb_value(
+ root: &Path,
+ name: &str,
+ (verb, timeout): (&str, Duration),
+ settings: &[(String, String)],
+ adapter: &dyn PlatformAdapter,
+) -> Result<Value, AppError> {
+ let (spec, provider_dir, sandboxes_root) = locate(root, name)?;
+ let _busy = match is_mutating(verb) {
+ true => Some(sandbox_store::hold(&sandboxes_root, name)?),
+ false => None,
+ };
+ let call = ProviderCall::new(spec, &provider_dir, &sandboxes_root, Some(name), settings);
+ let output = call.run(adapter, verb_args(name, verb), timeout)?;
+ let reply = parse_reply(spec.name, Some(name), is_mutating(verb), &output)?;
+ Ok(success_value(name, Some(spec.name), reply))
+}
+
+fn remove(root: &Path, name: &str, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
+ let (spec, provider_dir, sandboxes_root) = locate(root, name)?;
+ let _busy = sandbox_store::hold(&sandboxes_root, name)?;
+ let call = ProviderCall::new(spec, &provider_dir, &sandboxes_root, Some(name), &[]);
+ let running = call
+ .run(adapter, verb_args(name, "status"), STATUS_TIMEOUT)
+ .and_then(|output| parse_reply(spec.name, Some(name), false, &output))
+ .is_ok_and(|reply| reply.state == SandboxState::Running);
+ if running {
+ return Err(running_refusal(name));
+ }
+ let output = call.run(adapter, verb_args(name, "rm"), REMOVE_TIMEOUT)?;
+ let reply = parse_reply(spec.name, Some(name), true, &output)?;
+ sandbox_store::remove(&sandboxes_root, name)?;
+ Ok(success_value(name, Some(spec.name), reply))
+}
+
+fn locate(root: &Path, name: &str) -> Result<Target, AppError> {
+ let record = sandbox_store::load(&root.join(SANDBOXES_DIR), name)?;
+ let spec = recorded_provider(root, &record)?;
+ let (provider_dir, sandboxes_root) = resolve(root, spec)?;
+ Ok((spec, provider_dir, sandboxes_root))
+}
+
+pub(super) fn recorded_provider(
+ root: &Path,
+ record: &SandboxRecord,
+) -> Result<&'static ProviderSpec, AppError> {
+ find_provider(&record.provider).map_err(|_| {
+ sandbox_store::broken(
+ &root.join(SANDBOXES_DIR),
+ &record.name,
+ &format!(
+ "it records provider {}, which this build does not include",
+ record.provider
+ ),
+ )
+ })
+}
+
+pub(super) fn verb_args(name: &str, verb: &str) -> Vec<String> {
+ vec![verb.to_string(), name.to_string()]
+}
+
+fn is_mutating(verb: &str) -> bool {
+ matches!(verb, "create" | "start" | "stop" | "rm")
+}
+
+fn unix_seconds() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|elapsed| elapsed.as_secs())
+ .unwrap_or(0)
+}
+
+fn running_refusal(name: &str) -> AppError {
+ AppError::Adapter(
+ AdapterError::new(
+ ErrorCode::InvalidArgs,
+ format!("Sandbox {name} is running, so it was not removed."),
+ )
+ .with_suggestion(format!("Run `agent-desktop sandbox stop {name}` first."))
+ .with_disposition(DeliverySemantics::not_delivered()),
+ )
+}
+
+fn unavailable_refusal(message: String) -> AppError {
+ AppError::Adapter(
+ AdapterError::new(ErrorCode::PlatformNotSupported, message)
+ .with_suggestion("Run `agent-desktop sandbox install` to see what each provider needs.")
+ .with_disposition(DeliverySemantics::not_delivered()),
+ )
+}
+
+fn exec_without_envelope(name: &str) -> AppError {
+ AppError::Adapter(
+ AdapterError::new(
+ ErrorCode::ActionNotSupported,
+ "`sandbox exec` prints the sandboxed program's own output, so it has no data envelope of its own.",
+ )
+ .with_suggestion(format!(
+ "Run `agent-desktop sandbox exec {name} -- snapshot --app Finder` to run a command in the sandbox."
+ ))
+ .with_disposition(DeliverySemantics::not_delivered()),
+ )
+}
+
+#[cfg(test)]
+#[path = "sandbox_tests.rs"]
+mod tests;
+
+#[cfg(test)]
+#[path = "sandbox_guard_tests.rs"]
+mod guard_tests;
diff --git a/crates/core/src/commands/sandbox_action.rs b/crates/core/src/commands/sandbox_action.rs
new file mode 100644
index 000000000..d276208fc
--- /dev/null
+++ b/crates/core/src/commands/sandbox_action.rs
@@ -0,0 +1,29 @@
+#[derive(Debug, Clone)]
+pub enum SandboxAction {
+ Install {
+ provider: Option<String>,
+ },
+ Create {
+ name: String,
+ provider: String,
+ set: Vec<String>,
+ },
+ Start {
+ name: String,
+ set: Vec<String>,
+ },
+ Stop {
+ name: String,
+ },
+ Status {
+ name: String,
+ },
+ List,
+ Rm {
+ name: String,
+ },
+ Exec {
+ name: String,
+ args: Vec<String>,
+ },
+}
diff --git a/crates/core/src/commands/sandbox_guard_tests.rs b/crates/core/src/commands/sandbox_guard_tests.rs
new file mode 100644
index 000000000..64f036c63
--- /dev/null
+++ b/crates/core/src/commands/sandbox_guard_tests.rs
@@ -0,0 +1,138 @@
+use super::execute;
+use crate::commands::sandbox_action::SandboxAction;
+use crate::refs::refs_test_support::HomeGuard;
+use crate::sandbox::provider_test_support::ScriptedAdapter;
+use crate::sandbox::sandbox_record::SandboxRecord;
+use crate::sandbox::sandbox_store;
+use crate::{AdapterError, AppError, DeliverySemantics, ErrorCode};
+use std::path::PathBuf;
+
+const STOPPED: &str = r#"{"ok":true,"state":"stopped","message":"Sandbox dev-1 is stopped."}"#;
+const REFUSED: &str = r#"{"ok":false,"code":"INVALID_ARGS","message":"The provider refused.","suggestion":"Fix the settings."}"#;
+
+fn sandboxes_root(home: &HomeGuard) -> PathBuf {
+ home.path().join(".agent-desktop").join("sandboxes")
+}
+
+fn publish(home: &HomeGuard) -> PathBuf {
+ let record = SandboxRecord {
+ name: "dev-1".to_string(),
+ provider: "stub".to_string(),
+ created_at: 1,
+ };
+ sandbox_store::create(&sandboxes_root(home), &record).expect("record")
+}
+
+fn create_action() -> SandboxAction {
+ SandboxAction::Create {
+ name: "dev-1".to_string(),
+ provider: "stub".to_string(),
+ set: Vec::new(),
+ }
+}
+
+fn status_action() -> SandboxAction {
+ SandboxAction::Status {
+ name: "dev-1".to_string(),
+ }
+}
+
+fn disposition(error: AppError) -> DeliverySemantics {
+ match error {
+ AppError::Adapter(error) => error.disposition,
+ other => panic!("expected an adapter error, got {other:?}"),
+ }
+}
+
+#[test]
+fn a_broken_record_is_listed_with_the_directory_to_delete_and_reaches_no_provider() {
+ let home = HomeGuard::new();
+ let dir = publish(&home);
+ std::fs::write(dir.join(sandbox_store::RECORD_FILE), b"{not json").expect("corrupt record");
+ let adapter = ScriptedAdapter::new();
+
+ let listed = execute(SandboxAction::List, &adapter).expect("list");
+ let entry = &listed["sandboxes"][0];
+ assert_eq!(entry["state"], "broken");
+ let next = entry["next"].as_str().unwrap_or_default();
+ assert!(next.contains(&dir.display().to_string()), "next was {next}");
+
+ for action in [
+ status_action(),
+ SandboxAction::Rm {
+ name: "dev-1".to_string(),
+ },
+ ] {
+ let error = execute(action, &adapter).expect_err("a broken record is refused");
+ assert_eq!(error.suggestion(), Some(next));
+ }
+ assert!(adapter.requests().is_empty(), "the provider never ran");
+ assert!(dir.exists());
+}
+
+#[test]
+fn create_does_not_adopt_a_directory_that_holds_another_sandboxs_data() {
+ let home = HomeGuard::new();
+ let dir = sandboxes_root(&home).join("dev-1");
+ crate::storage::private_file_parent::ensure_private(&dir).expect("sandbox directory");
+ std::fs::write(dir.join("disk.img"), b"data").expect("provider data");
+ let adapter = ScriptedAdapter::new();
+
+ let error = execute(create_action(), &adapter).expect_err("the directory is taken");
+
+ assert_eq!(error.code(), "INVALID_ARGS");
+ assert!(adapter.requests().is_empty(), "the provider never ran");
+ assert!(!dir.join(sandbox_store::RECORD_FILE).exists());
+ assert!(dir.join("disk.img").exists());
+}
+
+#[test]
+fn a_refused_create_that_drops_its_record_reports_nothing_delivered() {
+ let home = HomeGuard::new();
+ let adapter = ScriptedAdapter::new().reply("create", REFUSED, 1);
+
+ let error = execute(create_action(), &adapter).expect_err("the provider refuses");
+
+ assert!(!sandboxes_root(&home).join("dev-1").exists());
+ assert_eq!(disposition(error), DeliverySemantics::not_delivered());
+}
+
+#[test]
+fn a_command_does_not_change_a_sandbox_another_command_is_changing() {
+ let home = HomeGuard::new();
+ publish(&home);
+ let _held = sandbox_store::hold(&sandboxes_root(&home), "dev-1").expect("first holder");
+ let adapter = ScriptedAdapter::new().reply("status", STOPPED, 0);
+
+ for action in [
+ SandboxAction::Rm {
+ name: "dev-1".to_string(),
+ },
+ SandboxAction::Start {
+ name: "dev-1".to_string(),
+ set: Vec::new(),
+ },
+ create_action(),
+ ] {
+ let error = execute(action, &adapter).expect_err("the sandbox is busy");
+ assert_eq!(disposition(error), DeliverySemantics::not_delivered());
+ }
+
+ assert!(adapter.requests().is_empty(), "the provider never ran");
+ execute(status_action(), &adapter).expect("reads are not blocked");
+}
+
+#[test]
+fn list_passes_on_what_a_failed_status_suggests_instead_of_advising_removal() {
+ let home = HomeGuard::new();
+ publish(&home);
+ let timeout = AdapterError::new(ErrorCode::Timeout, "The provider timed out.")
+ .with_suggestion("Run `agent-desktop sandbox status dev-1`.");
+ let adapter = ScriptedAdapter::new().fail("status", timeout);
+
+ let listed = execute(SandboxAction::List, &adapter).expect("list");
+
+ let next = listed["sandboxes"][0]["next"].as_str().unwrap_or_default();
+ assert!(next.contains("sandbox status dev-1"), "next was {next}");
+ assert!(!next.contains("sandbox rm"), "next was {next}");
+}
diff --git a/crates/core/src/commands/sandbox_install.rs b/crates/core/src/commands/sandbox_install.rs
new file mode 100644
index 000000000..68e1697c3
--- /dev/null
+++ b/crates/core/src/commands/sandbox_install.rs
@@ -0,0 +1,76 @@
+use std::path::Path;
+use std::time::Duration;
+
+use serde_json::{Value, json};
+
+use crate::sandbox::provider_dirs::resolve;
+use crate::sandbox::provider_protocol::parse_reply;
+use crate::sandbox::provider_reply::ProviderReply;
+use crate::sandbox::provider_run::{ProviderCall, success_value};
+use crate::sandbox::provider_spec::ProviderSpec;
+use crate::sandbox::provider_table::{PROVIDERS, find_provider};
+use crate::sandbox::sandbox_state::SandboxState;
+use crate::storage::state_root::resolve_configured_state_root;
+use crate::{AppError, PlatformAdapter};
+
+const INSTALL_TIMEOUT: Duration = Duration::from_secs(60);
+const CHECK_TIMEOUT: Duration = Duration::from_secs(30);
+
+pub fn execute(provider: Option<String>, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
+ let root = resolve_configured_state_root()?;
+ match provider {
+ Some(name) => install_one(&root, &name, adapter),
+ None => report_providers(&root, adapter),
+ }
+}
+
+fn install_one(root: &Path, name: &str, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
+ let spec = find_provider(name)?;
+ let (provider_dir, sandboxes_root) = resolve(root, spec)?;
+ let call = ProviderCall::new(spec, &provider_dir, &sandboxes_root, None, &[]);
+ let output = call.run(adapter, vec!["install".to_string()], INSTALL_TIMEOUT)?;
+ let reply = parse_reply(spec.name, None, true, &output)?;
+ Ok(success_value(spec.name, None, reply))
+}
+
+fn report_providers(root: &Path, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
+ let mut providers = Vec::with_capacity(PROVIDERS.len());
+ for spec in PROVIDERS {
+ providers.push(provider_entry(root, spec, adapter));
+ }
+ Ok(json!({ "providers": providers }))
+}
+
+fn provider_entry(root: &Path, spec: &ProviderSpec, adapter: &dyn PlatformAdapter) -> Value {
+ match check(root, spec, adapter) {
+ Ok(reply) => success_value(spec.name, None, reply),
+ Err(error) => unavailable_entry(spec, &error),
+ }
+}
+
+fn check(
+ root: &Path,
+ spec: &ProviderSpec,
+ adapter: &dyn PlatformAdapter,
+) -> Result<ProviderReply, AppError> {
+ let (provider_dir, sandboxes_root) = resolve(root, spec)?;
+ let call = ProviderCall::new(spec, &provider_dir, &sandboxes_root, None, &[]);
+ let output = call.run(adapter, vec!["check".to_string()], CHECK_TIMEOUT)?;
+ parse_reply(spec.name, None, false, &output)
+}
+
+fn unavailable_entry(spec: &ProviderSpec, error: &AppError) -> Value {
+ let mut value = json!({
+ "name": spec.name,
+ "state": SandboxState::Unavailable,
+ "message": error.to_string(),
+ });
+ if let (Some(next), Some(object)) = (error.suggestion(), value.as_object_mut()) {
+ object.insert("next".to_string(), Value::String(next.to_string()));
+ }
+ value
+}
+
+#[cfg(test)]
+#[path = "sandbox_install_tests.rs"]
+mod tests;
diff --git a/crates/core/src/commands/sandbox_install_tests.rs b/crates/core/src/commands/sandbox_install_tests.rs
new file mode 100644
index 000000000..4d492de81
--- /dev/null
+++ b/crates/core/src/commands/sandbox_install_tests.rs
@@ -0,0 +1,14 @@
+use super::execute;
+use crate::refs::refs_test_support::HomeGuard;
+use crate::sandbox::provider_test_support::ScriptedAdapter;
+
+#[test]
+fn an_unknown_provider_is_refused_before_any_script_runs() {
+ let _home = HomeGuard::new();
+ let adapter = ScriptedAdapter::new();
+
+ let error = execute(Some("nomad".to_string()), &adapter).expect_err("unknown provider");
+
+ assert_eq!(error.code(), "INVALID_ARGS");
+ assert!(adapter.requests().is_empty());
+}
diff --git a/crates/core/src/commands/sandbox_list.rs b/crates/core/src/commands/sandbox_list.rs
new file mode 100644
index 000000000..f6d57fd09
--- /dev/null
+++ b/crates/core/src/commands/sandbox_list.rs
@@ -0,0 +1,76 @@
+use std::path::Path;
+use std::time::Duration;
+
+use serde_json::{Value, json};
+
+use super::sandbox::{recorded_provider, verb_args};
+use crate::sandbox::provider_dirs::{SANDBOXES_DIR, resolve};
+use crate::sandbox::provider_protocol::parse_reply;
+use crate::sandbox::provider_reply::ProviderReply;
+use crate::sandbox::provider_run::{ProviderCall, success_value};
+use crate::sandbox::sandbox_record::SandboxRecord;
+use crate::sandbox::sandbox_state::SandboxState;
+use crate::sandbox::sandbox_store;
+use crate::{AppError, PlatformAdapter};
+
+const STATUS_TIMEOUT: Duration = Duration::from_secs(30);
+
+pub(super) fn execute(root: &Path, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
+ let entries = sandbox_store::list(&root.join(SANDBOXES_DIR))?;
+ let mut sandboxes = Vec::with_capacity(entries.len());
+ for entry in &entries {
+ match &entry.record {
+ Ok(record) => sandboxes.push(record_entry(root, record, adapter)),
+ Err(error) => sandboxes.push(broken_record_entry(&entry.name, error)),
+ }
+ }
+ Ok(json!({ "sandboxes": sandboxes }))
+}
+
+fn record_entry(root: &Path, record: &SandboxRecord, adapter: &dyn PlatformAdapter) -> Value {
+ match status_reply(root, record, adapter) {
+ Ok(reply) => success_value(&record.name, Some(&record.provider), reply),
+ Err(error) => broken_entry(record, &error),
+ }
+}
+
+fn status_reply(
+ root: &Path,
+ record: &SandboxRecord,
+ adapter: &dyn PlatformAdapter,
+) -> Result<ProviderReply, AppError> {
+ let spec = recorded_provider(root, record)?;
+ let (provider_dir, sandboxes_root) = resolve(root, spec)?;
+ let call = ProviderCall::new(
+ spec,
+ &provider_dir,
+ &sandboxes_root,
+ Some(&record.name),
+ &[],
+ );
+ let output = call.run(adapter, verb_args(&record.name, "status"), STATUS_TIMEOUT)?;
+ parse_reply(spec.name, Some(&record.name), false, &output)
+}
+
+fn broken_entry(record: &SandboxRecord, error: &AppError) -> Value {
+ broken_value(&record.name, Some(&record.provider), error)
+}
+
+fn broken_record_entry(name: &str, error: &AppError) -> Value {
+ broken_value(name, None, error)
+}
+
+fn broken_value(name: &str, provider: Option<&str>, error: &AppError) -> Value {
+ let mut value = json!({
+ "name": name,
+ "state": SandboxState::Broken,
+ "message": error.to_string(),
+ });
+ if let Some(next) = error.suggestion() {
+ value["next"] = json!(next);
+ }
+ if let Some(provider) = provider {
+ value["provider"] = json!(provider);
+ }
+ value
+}
diff --git a/crates/core/src/commands/sandbox_tests.rs b/crates/core/src/commands/sandbox_tests.rs
new file mode 100644
index 000000000..d9ddd61ca
--- /dev/null
+++ b/crates/core/src/commands/sandbox_tests.rs
@@ -0,0 +1,237 @@
+use super::execute;
+use crate::commands::sandbox_action::SandboxAction;
+use crate::refs::refs_test_support::HomeGuard;
+use crate::sandbox::provider_test_support::ScriptedAdapter;
+use crate::sandbox::sandbox_store;
+use crate::{AdapterError, AppError, DeliverySemantics};
+use std::path::PathBuf;
+
+const CREATED: &str = r#"{"ok":true,"state":"stopped","message":"Sandbox dev-1 is created.","next":"Run `agent-desktop sandbox start dev-1`."}"#;
+const STOPPED: &str = r#"{"ok":true,"state":"stopped","message":"Sandbox dev-1 is stopped."}"#;
+const RUNNING: &str = r#"{"ok":true,"state":"running","message":"Sandbox dev-1 is running."}"#;
+const REMOVED: &str = r#"{"ok":true,"state":"stopped","message":"Sandbox dev-1 is removed."}"#;
+const UNAVAILABLE: &str =
+ r#"{"ok":true,"state":"unavailable","message":"This Mac cannot run virtual machines."}"#;
+const UNREADABLE: &str = "the provider printed no reply";
+const RM_FAILED: &str = r#"{"ok":false,"code":"ACTION_FAILED","message":"The provider did not remove the sandbox.","suggestion":"Run `agent-desktop sandbox rm dev-1` again."}"#;
+
+fn rm_action() -> SandboxAction {
+ SandboxAction::Rm {
+ name: "dev-1".to_string(),
+ }
+}
+
+fn adapter_error(error: AppError) -> AdapterError {
+ match error {
+ AppError::Adapter(error) => error,
+ other => panic!("expected an adapter error, got {other:?}"),
+ }
+}
+
+fn create_action() -> SandboxAction {
+ SandboxAction::Create {
+ name: "dev-1".to_string(),
+ provider: "stub".to_string(),
+ set: Vec::new(),
+ }
+}
+
+fn sandboxes_root(home: &HomeGuard) -> PathBuf {
+ home.path().join(".agent-desktop").join("sandboxes")
+}
+
+fn env_value(request: &crate::ProviderScriptRequest, key: &str) -> Option<String> {
+ request
+ .env
+ .iter()
+ .find(|(name, _)| name == key)
+ .map(|(_, value)| value.clone())
+}
+
+#[test]
+fn provider_calls_carry_the_callers_working_directory() {
+ let home = HomeGuard::new();
+ let adapter = ScriptedAdapter::new().reply("create", CREATED, 0);
+ let caller = std::env::current_dir().expect("the caller working directory");
+
+ execute(create_action(), &adapter).expect("create");
+
+ let requests = adapter.requests();
+ let request = requests.first().expect("the provider create ran");
+ assert_eq!(
+ request.working_dir,
+ sandboxes_root(&home).join("dev-1"),
+ "the provider still runs inside the sandbox it owns"
+ );
+ assert_eq!(
+ env_value(request, "AD_CALLER_CWD").as_deref(),
+ Some(caller.to_str().expect("a utf-8 caller directory")),
+ "the provider sees the caller directory it was invoked from, not its own"
+ );
+}
+
+#[test]
+fn a_failed_create_leaves_no_record_unless_the_provider_left_files() {
+ {
+ let home = HomeGuard::new();
+ let adapter = ScriptedAdapter::new();
+
+ execute(create_action(), &adapter).expect_err("the provider create fails");
+
+ assert!(
+ !sandboxes_root(&home).join("dev-1").exists(),
+ "a failed create leaves no sandbox behind"
+ );
+ }
+
+ let home = HomeGuard::new();
+ let adapter = ScriptedAdapter::new().leaving("id_ed25519");
+
+ execute(create_action(), &adapter).expect_err("the provider create fails");
+
+ assert!(
+ sandbox_store::load(&sandboxes_root(&home), "dev-1").is_ok(),
+ "the record stays so status can report what the provider left"
+ );
+}
+
+#[test]
+fn a_create_the_provider_did_not_refuse_keeps_its_record_for_status_and_rm() {
+ let timed_out = ScriptedAdapter::new().fail(
+ "create",
+ crate::AdapterError::timeout("the provider did not answer"),
+ );
+ let unreadable = ScriptedAdapter::new().reply("create", "the provider crashed", 1);
+ let flooded = ScriptedAdapter::new().fail(
+ "create",
+ crate::AdapterError::new(
+ crate::ErrorCode::ActionFailed,
+ "the provider printed too much",
+ ),
+ );
+ let incomplete_success = ScriptedAdapter::new().reply("create", r#"{"ok":true}"#, 0);
+ let changed_then_failed = ScriptedAdapter::new().reply(
+ "create",
+ r#"{"ok":false,"code":"ACTION_FAILED","message":"The disk filled up.","suggestion":"Free space.","data":{"changed":true}}"#,
+ 1,
+ );
+
+ for adapter in [
+ timed_out,
+ unreadable,
+ flooded,
+ incomplete_success,
+ changed_then_failed,
+ ] {
+ let home = HomeGuard::new();
+
+ execute(create_action(), &adapter).expect_err("the create outcome is unknown");
+
+ assert!(
+ sandbox_store::load(&sandboxes_root(&home), "dev-1").is_ok(),
+ "the record stays so the sandbox still lists and can be removed"
+ );
+ }
+}
+
+#[test]
+fn create_on_a_provider_that_cannot_run_here_is_refused_and_leaves_no_record() {
+ let home = HomeGuard::new();
+ let adapter = ScriptedAdapter::new().reply("create", UNAVAILABLE, 0);
+
+ let error = execute(create_action(), &adapter).expect_err("the provider is unavailable");
+
+ assert_eq!(error.code(), "PLATFORM_NOT_SUPPORTED");
+ assert!(
+ !sandboxes_root(&home).join("dev-1").exists(),
+ "an unavailable provider leaves no sandbox behind"
+ );
+}
+
+#[test]
+fn removing_a_running_sandbox_is_refused_and_keeps_the_record() {
+ let home = HomeGuard::new();
+ let adapter = ScriptedAdapter::new()
+ .reply("create", CREATED, 0)
+ .reply("status", RUNNING, 0);
+ execute(create_action(), &adapter).expect("create");
+
+ let error =
+ adapter_error(execute(rm_action(), &adapter).expect_err("a running sandbox is refused"));
+
+ assert_eq!(error.code.as_str(), "INVALID_ARGS");
+ assert_eq!(error.disposition, DeliverySemantics::not_delivered());
+ assert_eq!(adapter.requests().len(), 2, "the rm verb never runs");
+ assert!(
+ sandbox_store::load(&sandboxes_root(&home), "dev-1").is_ok(),
+ "the record stays"
+ );
+}
+
+#[test]
+fn removing_a_stopped_sandbox_removes_the_record() {
+ let home = HomeGuard::new();
+ let adapter = ScriptedAdapter::new()
+ .reply("create", CREATED, 0)
+ .reply("status", STOPPED, 0)
+ .reply("rm", REMOVED, 0);
+ execute(create_action(), &adapter).expect("create");
+
+ execute(rm_action(), &adapter).expect("a stopped sandbox is removed");
+
+ assert_eq!(
+ sandbox_store::load(&sandboxes_root(&home), "dev-1")
+ .expect_err("the record is gone")
+ .code(),
+ "SANDBOX_NOT_FOUND"
+ );
+}
+
+#[test]
+fn a_broken_list_entry_can_still_be_removed() {
+ let home = HomeGuard::new();
+ let adapter = ScriptedAdapter::new()
+ .reply("create", CREATED, 0)
+ .reply("status", UNREADABLE, 0)
+ .reply("rm", REMOVED, 0);
+ execute(create_action(), &adapter).expect("create");
+
+ let listed = execute(SandboxAction::List, &adapter).expect("list");
+ assert_eq!(
+ listed["sandboxes"][0]["state"].as_str(),
+ Some("broken"),
+ "an unreadable status reports the record as broken"
+ );
+
+ execute(rm_action(), &adapter).expect("a broken record is removed through the provider");
+
+ assert_eq!(
+ sandbox_store::load(&sandboxes_root(&home), "dev-1")
+ .expect_err("the record is gone")
+ .code(),
+ "SANDBOX_NOT_FOUND"
+ );
+}
+
+#[test]
+fn a_failed_rm_keeps_the_record_for_another_attempt() {
+ let home = HomeGuard::new();
+ let adapter = ScriptedAdapter::new()
+ .reply("create", CREATED, 0)
+ .reply("status", UNREADABLE, 0)
+ .reply("rm", RM_FAILED, 0);
+ execute(create_action(), &adapter).expect("create");
+
+ let error = adapter_error(execute(rm_action(), &adapter).expect_err("the provider rm fails"));
+
+ assert_eq!(error.code.as_str(), "ACTION_FAILED");
+ assert_eq!(
+ error.disposition,
+ DeliverySemantics::unknown(),
+ "a failed mutating provider call leaves delivery unknown"
+ );
+ assert!(
+ sandbox_store::load(&sandboxes_root(&home), "dev-1").is_ok(),
+ "the record stays so the next rm can retry"
+ );
+}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index c88d0e79b..5306e6b5d 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -12,6 +12,7 @@ mod notifications;
pub mod ref_action;
pub mod refs;
pub mod response;
+pub mod sandbox;
pub mod session;
pub mod snapshot;
mod storage;
@@ -104,6 +105,9 @@ pub use response::error_code::ErrorCode;
pub use response::output::{ErrorPayload, Response};
pub use response::recovery_hint::RecoveryHint;
pub use response::retry_disposition::RetryDisposition;
+pub use sandbox::exec_passthrough::ExecPassthrough;
+pub use sandbox::provider_script_output::ProviderScriptOutput;
+pub use sandbox::provider_script_request::ProviderScriptRequest;
pub use session::interaction_lease::InteractionLease;
#[cfg(unix)]
pub use session::interaction_lease::{
diff --git a/crates/core/src/response/adapter_error.rs b/crates/core/src/response/adapter_error.rs
index e285d1b69..bcddf744e 100644
--- a/crates/core/src/response/adapter_error.rs
+++ b/crates/core/src/response/adapter_error.rs
@@ -370,6 +370,7 @@ mod tests {
ErrorCode::InvalidArgs,
ErrorCode::NotificationNotFound,
ErrorCode::SnapshotNotFound,
+ ErrorCode::SandboxNotFound,
ErrorCode::PolicyDenied,
ErrorCode::AppUnresponsive,
ErrorCode::Internal,
diff --git a/crates/core/src/response/error_code.rs b/crates/core/src/response/error_code.rs
index 7f46315f6..664694f7c 100644
--- a/crates/core/src/response/error_code.rs
+++ b/crates/core/src/response/error_code.rs
@@ -16,6 +16,7 @@ pub enum ErrorCode {
InvalidArgs,
NotificationNotFound,
SnapshotNotFound,
+ SandboxNotFound,
PolicyDenied,
AppUnresponsive,
Internal,
@@ -37,6 +38,7 @@ impl ErrorCode {
Self::InvalidArgs => "INVALID_ARGS",
Self::NotificationNotFound => "NOTIFICATION_NOT_FOUND",
Self::SnapshotNotFound => "SNAPSHOT_NOT_FOUND",
+ Self::SandboxNotFound => "SANDBOX_NOT_FOUND",
Self::PolicyDenied => "POLICY_DENIED",
Self::AppUnresponsive => "APP_UNRESPONSIVE",
Self::Internal => "INTERNAL",
diff --git a/crates/core/src/response/error_tests.rs b/crates/core/src/response/error_tests.rs
index f7a4a0a48..75c1dbea1 100644
--- a/crates/core/src/response/error_tests.rs
+++ b/crates/core/src/response/error_tests.rs
@@ -54,6 +54,7 @@ fn all_error_codes_as_str_and_serde_are_consistent() {
(ErrorCode::InvalidArgs, "INVALID_ARGS"),
(ErrorCode::NotificationNotFound, "NOTIFICATION_NOT_FOUND"),
(ErrorCode::SnapshotNotFound, "SNAPSHOT_NOT_FOUND"),
+ (ErrorCode::SandboxNotFound, "SANDBOX_NOT_FOUND"),
(ErrorCode::PolicyDenied, "POLICY_DENIED"),
(ErrorCode::AppUnresponsive, "APP_UNRESPONSIVE"),
(ErrorCode::Internal, "INTERNAL"),
diff --git a/crates/core/src/sandbox/exec_passthrough.rs b/crates/core/src/sandbox/exec_passthrough.rs
new file mode 100644
index 000000000..1efc91d62
--- /dev/null
+++ b/crates/core/src/sandbox/exec_passthrough.rs
@@ -0,0 +1,5 @@
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ExecPassthrough {
+ pub stdout: Vec<u8>,
+ pub status: i32,
+}
diff --git a/crates/core/src/sandbox/mod.rs b/crates/core/src/sandbox/mod.rs
new file mode 100644
index 000000000..aacc09ff2
--- /dev/null
+++ b/crates/core/src/sandbox/mod.rs
@@ -0,0 +1,20 @@
+//! Local sandbox domain: names, records, provider scripts, their files, and the reply protocol.
+
+pub(crate) mod exec_passthrough;
+pub(crate) mod provider_dirs;
+pub(crate) mod provider_files;
+pub(crate) mod provider_protocol;
+pub(crate) mod provider_reply;
+pub(crate) mod provider_run;
+pub(crate) mod provider_script_output;
+pub(crate) mod provider_script_request;
+pub(crate) mod provider_settings;
+pub(crate) mod provider_spec;
+pub(crate) mod provider_table;
+#[cfg(test)]
+pub(crate) mod provider_test_support;
+pub(crate) mod sandbox_entry;
+pub(crate) mod sandbox_name;
+pub(crate) mod sandbox_record;
+pub(crate) mod sandbox_state;
+pub(crate) mod sandbox_store;
diff --git a/crates/core/src/sandbox/provider_dirs.rs b/crates/core/src/sandbox/provider_dirs.rs
new file mode 100644
index 000000000..d82fad503
--- /dev/null
+++ b/crates/core/src/sandbox/provider_dirs.rs
@@ -0,0 +1,14 @@
+use std::path::{Path, PathBuf};
+
+use crate::AppError;
+use crate::sandbox::provider_files::materialize;
+use crate::sandbox::provider_spec::ProviderSpec;
+
+pub(crate) const PROVIDERS_DIR: &str = "providers";
+pub(crate) const SANDBOXES_DIR: &str = "sandboxes";
+
+/// The materialized provider directory and the root the sandboxes live under.
+pub(crate) fn resolve(root: &Path, spec: &ProviderSpec) -> Result<(PathBuf, PathBuf), AppError> {
+ let provider_dir = materialize(&root.join(PROVIDERS_DIR), spec)?;
+ Ok((provider_dir, root.join(SANDBOXES_DIR)))
+}
diff --git a/crates/core/src/sandbox/provider_files.rs b/crates/core/src/sandbox/provider_files.rs
new file mode 100644
index 000000000..afccf4e92
--- /dev/null
+++ b/crates/core/src/sandbox/provider_files.rs
@@ -0,0 +1,34 @@
+use crate::AppError;
+use crate::sandbox::provider_spec::ProviderSpec;
+use crate::storage::private_file::write_atomic;
+use crate::storage::private_file_parent::ensure_private;
+use rustc_hash::FxHasher;
+use std::hash::Hasher;
+use std::path::{Path, PathBuf};
+
+pub(crate) fn materialize(root: &Path, spec: &ProviderSpec) -> Result<PathBuf, AppError> {
+ let dir = root.join(spec.name).join(content_hash(spec));
+ ensure_private(&dir)?;
+ for (file, contents) in spec.files {
+ let path = dir.join(file);
+ if !path.is_file() {
+ write_atomic(&path, contents.as_bytes())?;
+ }
+ }
+ Ok(dir)
+}
+
+fn content_hash(spec: &ProviderSpec) -> String {
+ let mut hasher = FxHasher::default();
+ for (file, contents) in spec.files {
+ hasher.write_usize(file.len());
+ hasher.write(file.as_bytes());
+ hasher.write_usize(contents.len());
+ hasher.write(contents.as_bytes());
+ }
+ format!("{:016x}", hasher.finish())
+}
+
+#[cfg(test)]
+#[path = "provider_files_tests.rs"]
+mod tests;
diff --git a/crates/core/src/sandbox/provider_files_tests.rs b/crates/core/src/sandbox/provider_files_tests.rs
new file mode 100644
index 000000000..61b6d0148
--- /dev/null
+++ b/crates/core/src/sandbox/provider_files_tests.rs
@@ -0,0 +1,43 @@
+use super::materialize;
+use crate::sandbox::provider_spec::ProviderSpec;
+use std::path::PathBuf;
+
+struct Scratch(PathBuf);
+
+impl Scratch {
+ fn new(label: &str) -> Self {
+ Self(std::env::temp_dir().join(format!(
+ "agent-desktop-provider-files-{label}-{}",
+ crate::refs::new_snapshot_id()
+ )))
+ }
+}
+
+impl Drop for Scratch {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+}
+
+const DEMO: ProviderSpec = ProviderSpec {
+ name: "demo",
+ files: &[("provider.sh", "echo one\n")],
+};
+
+const EDITED: ProviderSpec = ProviderSpec {
+ name: "demo",
+ files: &[("provider.sh", "echo two\n")],
+};
+
+#[test]
+fn edited_contents_get_a_new_directory() {
+ let scratch = Scratch::new("edited");
+ let before = materialize(&scratch.0, &DEMO).unwrap();
+ let after = materialize(&scratch.0, &EDITED).unwrap();
+
+ assert_ne!(before, after);
+ assert_eq!(
+ std::fs::read_to_string(after.join("provider.sh")).unwrap(),
+ "echo two\n"
+ );
+}
diff --git a/crates/core/src/sandbox/provider_protocol.rs b/crates/core/src/sandbox/provider_protocol.rs
new file mode 100644
index 000000000..b3a65aa33
--- /dev/null
+++ b/crates/core/src/sandbox/provider_protocol.rs
@@ -0,0 +1,209 @@
+use serde_json::Value;
+
+use crate::sandbox::exec_passthrough::ExecPassthrough;
+use crate::sandbox::provider_reply::ProviderReply;
+use crate::sandbox::provider_script_output::ProviderScriptOutput;
+use crate::sandbox::sandbox_state::SandboxState;
+use crate::{AdapterError, AppError, DeliverySemantics, ErrorCode};
+
+const MAX_PLATFORM_DETAIL_CHARS: usize = 2000;
+const EXEC_PROVIDER_FAILURE_STATUS: i32 = 125;
+const LIST_SUGGESTION: &str =
+ "Run `agent-desktop sandbox list` to find the sandbox and run the command again.";
+
+/// Reads the last stdout line as a contract reply, mapping a failure object to an error.
+pub(crate) fn parse_reply(
+ provider: &str,
+ name: Option<&str>,
+ mutating: bool,
+ output: &ProviderScriptOutput,
+) -> Result<ProviderReply, AppError> {
+ let suggestion = next_step(name);
+ let value = reply_value(&output.stdout)
+ .ok_or_else(|| unreadable(provider, &suggestion, mutating, output))?;
+ match value.get("ok").and_then(Value::as_bool) {
+ Some(true) => success_reply(provider, &suggestion, mutating, &value, output),
+ Some(false) => Err(failure_error(provider, &suggestion, mutating, &value, output).into()),
+ None => Err(unreadable(provider, &suggestion, mutating, output).into()),
+ }
+}
+
+/// Passes the guest envelope through unchanged unless the provider reports its own failure.
+pub(crate) fn exec_outcome(
+ provider: &str,
+ output: &ProviderScriptOutput,
+) -> Result<ExecPassthrough, AppError> {
+ let Some(status) = output.status else {
+ return Err(missing_status(provider, output).into());
+ };
+ if status == EXEC_PROVIDER_FAILURE_STATUS
+ && let Some(error) = exec_failure(provider, output)
+ {
+ return Err(error.into());
+ }
+ Ok(ExecPassthrough {
+ stdout: output.stdout.clone(),
+ status,
+ })
+}
+
+fn success_reply(
+ provider: &str,
+ suggestion: &str,
+ mutating: bool,
+ value: &Value,
+ output: &ProviderScriptOutput,
+) -> Result<ProviderReply, AppError> {
+ let state = value
+ .get("state")
+ .and_then(Value::as_str)
+ .and_then(SandboxState::from_wire);
+ let message = value.get("message").and_then(Value::as_str);
+ let (Some(state), Some(message)) = (state, message) else {
+ return Err(unreadable(provider, suggestion, mutating, output).into());
+ };
+
+ Ok(ProviderReply {
+ state,
+ message: message.to_owned(),
+ next: value.get("next").and_then(Value::as_str).map(str::to_owned),
+ data: value.get("data").cloned(),
+ })
+}
+
+fn failure_error(
+ provider: &str,
+ suggestion: &str,
+ mutating: bool,
+ value: &Value,
+ output: &ProviderScriptOutput,
+) -> AdapterError {
+ let Some((code, message, script_suggestion)) = failure_fields(value) else {
+ return unreadable(provider, suggestion, mutating, output);
+ };
+
+ with_stderr(
+ AdapterError::new(map_code(code), message)
+ .with_suggestion(script_suggestion)
+ .with_disposition(disposition(mutating, no_change_reported(value))),
+ output,
+ )
+}
+
+fn exec_failure(provider: &str, output: &ProviderScriptOutput) -> Option<AdapterError> {
+ reply_value(&output.stdout)
+ .filter(|value| value.get("ok").and_then(Value::as_bool) == Some(false))
+ .filter(|value| failure_fields(value).is_some())
+ .map(|value| failure_error(provider, LIST_SUGGESTION, true, &value, output))
+}
+
+fn missing_status(provider: &str, output: &ProviderScriptOutput) -> AdapterError {
+ with_stderr(
+ AdapterError::new(
+ ErrorCode::ActionFailed,
+ format!(
+ "The {provider} provider stopped before agent-desktop could read its exit status."
+ ),
+ )
+ .with_suggestion(LIST_SUGGESTION)
+ .with_disposition(DeliverySemantics::unknown()),
+ output,
+ )
+}
+
+fn unreadable(
+ provider: &str,
+ suggestion: &str,
+ mutating: bool,
+ output: &ProviderScriptOutput,
+) -> AdapterError {
+ with_stderr(
+ AdapterError::new(
+ ErrorCode::ActionFailed,
+ format!("The {provider} provider returned output agent-desktop could not read."),
+ )
+ .with_suggestion(suggestion)
+ .with_disposition(disposition(mutating, false)),
+ output,
+ )
+}
+
+pub(crate) fn next_step(name: Option<&str>) -> String {
+ match name {
+ Some(name) => {
+ format!("Run `agent-desktop sandbox status {name}` to see its current state.")
+ }
+ None => {
+ "Run `agent-desktop sandbox install` to see each provider's current state.".to_string()
+ }
+ }
+}
+
+/// Whether the provider finished with a complete failure reply that does not say it changed anything.
+pub(crate) fn provider_refused(output: &ProviderScriptOutput) -> bool {
+ reply_value(&output.stdout).is_some_and(|value| {
+ value.get("ok").and_then(Value::as_bool) == Some(false)
+ && failure_fields(&value).is_some()
+ && value.pointer("/data/changed").and_then(Value::as_bool) != Some(true)
+ })
+}
+
+fn reply_value(stdout: &[u8]) -> Option<Value> {
+ let text = String::from_utf8_lossy(stdout);
+ let line = text.lines().rev().find(|line| !line.trim().is_empty())?;
+ serde_json::from_str(line).ok()
+}
+
+fn failure_fields(value: &Value) -> Option<(&str, &str, &str)> {
+ Some((
+ value.get("code")?.as_str()?,
+ value.get("message")?.as_str()?,
+ value.get("suggestion")?.as_str()?,
+ ))
+}
+
+fn map_code(code: &str) -> ErrorCode {
+ match code {
+ "INVALID_ARGS" => ErrorCode::InvalidArgs,
+ "PLATFORM_NOT_SUPPORTED" => ErrorCode::PlatformNotSupported,
+ "PERM_DENIED" => ErrorCode::PermDenied,
+ "TIMEOUT" => ErrorCode::Timeout,
+ "SANDBOX_NOT_FOUND" => ErrorCode::SandboxNotFound,
+ _ => ErrorCode::ActionFailed,
+ }
+}
+
+fn no_change_reported(value: &Value) -> bool {
+ value
+ .get("data")
+ .and_then(|data| data.get("changed"))
+ .and_then(Value::as_bool)
+ == Some(false)
+}
+
+fn disposition(mutating: bool, no_change: bool) -> DeliverySemantics {
+ if mutating && !no_change {
+ DeliverySemantics::unknown()
+ } else {
+ DeliverySemantics::not_delivered()
+ }
+}
+
+fn with_stderr(error: AdapterError, output: &ProviderScriptOutput) -> AdapterError {
+ match platform_detail(output) {
+ Some(detail) => error.with_platform_detail(detail),
+ None => error,
+ }
+}
+
+fn platform_detail(output: &ProviderScriptOutput) -> Option<String> {
+ let tail = output.stderr_tail.trim();
+ if tail.is_empty() {
+ return None;
+ }
+ Some(tail.chars().take(MAX_PLATFORM_DETAIL_CHARS).collect())
+}
+
+#[cfg(test)]
+#[path = "provider_protocol_tests.rs"]
+mod tests;
diff --git a/crates/core/src/sandbox/provider_protocol_tests.rs b/crates/core/src/sandbox/provider_protocol_tests.rs
new file mode 100644
index 000000000..1dfd6a6c3
--- /dev/null
+++ b/crates/core/src/sandbox/provider_protocol_tests.rs
@@ -0,0 +1,152 @@
+use serde_json::json;
+
+use crate::sandbox::provider_protocol::{exec_outcome, parse_reply};
+use crate::sandbox::provider_script_output::ProviderScriptOutput;
+use crate::{AdapterError, AppError, DeliverySemantics, ErrorCode};
+
+const UNREADABLE: &str = "The macos provider returned output agent-desktop could not read.";
+const NEXT_SUGGESTION: &str = "Run `agent-desktop sandbox list` to see your sandboxes.";
+
+fn output(stdout: &str, stderr: &str) -> ProviderScriptOutput {
+ ProviderScriptOutput {
+ status: Some(1),
+ stdout: stdout.as_bytes().to_vec(),
+ stderr_tail: stderr.to_owned(),
+ }
+}
+
+fn failure(code: &str, message: &str, suggestion: &str) -> String {
+ json!({
+ "ok": false,
+ "code": code,
+ "message": message,
+ "suggestion": suggestion,
+ })
+ .to_string()
+}
+
+fn adapter(error: AppError) -> AdapterError {
+ match error {
+ AppError::Adapter(error) => error,
+ other => panic!("expected an adapter error, got {other:?}"),
+ }
+}
+
+fn failed_reply(provider: &str, name: Option<&str>, mutating: bool, stdout: &str) -> AdapterError {
+ adapter(parse_reply(provider, name, mutating, &output(stdout, "")).unwrap_err())
+}
+
+#[test]
+fn unreadable_provider_output_is_action_failed_with_stderr_out_of_the_message() {
+ let stderr = "Error: image build failed\nexit status 1";
+ let unreadable = output("starting the build...\nnot json at all\n", stderr);
+ let error = adapter(parse_reply("macos", Some("dev"), false, &unreadable).unwrap_err());
+
+ assert_eq!(error.code, ErrorCode::ActionFailed);
+ assert_eq!(error.message, UNREADABLE);
+ assert_eq!(error.platform_detail.as_deref(), Some(stderr));
+ assert!(!error.message.contains("image build failed"));
+
+ for stdout in [
+ r#"{"ok":true}"#,
+ r#"{"ok":true,"state":"parked","message":"The dev sandbox is ready."}"#,
+ r#"{"ok":false,"code":"ACTION_FAILED","message":"The macos provider stopped."}"#,
+ "[1,2,3]",
+ ] {
+ let error = failed_reply("macos", Some("dev"), false, stdout);
+
+ assert_eq!(error.code, ErrorCode::ActionFailed, "{stdout}");
+ assert_eq!(error.message, UNREADABLE, "{stdout}");
+ }
+}
+
+#[test]
+fn a_failed_verb_reports_the_delivery_it_cannot_verify() {
+ let failed_mutation = failure(
+ "ACTION_FAILED",
+ "The macos provider could not start dev.",
+ NEXT_SUGGESTION,
+ );
+ assert_eq!(
+ failed_reply("macos", Some("dev"), true, &failed_mutation).disposition,
+ DeliverySemantics::unknown()
+ );
+
+ let unchanged = json!({
+ "ok": false,
+ "code": "ACTION_FAILED",
+ "message": "The macos provider could not start dev.",
+ "suggestion": NEXT_SUGGESTION,
+ "data": { "changed": false },
+ })
+ .to_string();
+ assert_eq!(
+ failed_reply("macos", Some("dev"), true, &unchanged).disposition,
+ DeliverySemantics::not_delivered()
+ );
+
+ let failed_read = failure(
+ "TIMEOUT",
+ "The macos provider did not answer.",
+ NEXT_SUGGESTION,
+ );
+ assert_eq!(
+ failed_reply("macos", Some("dev"), false, &failed_read).disposition,
+ DeliverySemantics::not_delivered()
+ );
+}
+
+#[test]
+fn exec_passes_a_guest_envelope_through_byte_for_byte() {
+ let mut guest =
+ br#"{"version":"2.5","ok":false,"command":"snapshot","error":{"code":"STALE_REF"}}"#
+ .to_vec();
+ guest.push(b'\n');
+ guest.push(0xff);
+ let output = ProviderScriptOutput {
+ status: Some(1),
+ stdout: guest.clone(),
+ stderr_tail: "the guest refused".to_owned(),
+ };
+
+ let passthrough = exec_outcome("macos", &output).unwrap();
+
+ assert_eq!(passthrough.stdout, guest);
+ assert_eq!(passthrough.status, 1);
+}
+
+#[test]
+fn exec_failures_report_the_sandbox_error_and_unknown_delivery() {
+ let provider_failure = failure(
+ "SANDBOX_NOT_FOUND",
+ "The sandbox dev does not exist.",
+ NEXT_SUGGESTION,
+ );
+ let output = ProviderScriptOutput {
+ status: Some(125),
+ stdout: provider_failure.into_bytes(),
+ stderr_tail: String::new(),
+ };
+ let error = adapter(exec_outcome("macos", &output).unwrap_err());
+ assert_eq!(error.code, ErrorCode::SandboxNotFound);
+ assert_eq!(error.message, "The sandbox dev does not exist.");
+ assert_eq!(error.disposition, DeliverySemantics::unknown());
+
+ let guest_exit = ProviderScriptOutput {
+ status: Some(125),
+ stdout: b"guest output\n".to_vec(),
+ stderr_tail: String::new(),
+ };
+ let passthrough = exec_outcome("macos", &guest_exit).unwrap();
+ assert_eq!(passthrough.stdout, b"guest output\n".to_vec());
+ assert_eq!(passthrough.status, 125);
+
+ let no_status = ProviderScriptOutput {
+ status: None,
+ stdout: Vec::new(),
+ stderr_tail: "ssh died".to_owned(),
+ };
+ let error = adapter(exec_outcome("macos", &no_status).unwrap_err());
+ assert_eq!(error.code, ErrorCode::ActionFailed);
+ assert_eq!(error.disposition, DeliverySemantics::unknown());
+}
diff --git a/crates/core/src/sandbox/provider_reply.rs b/crates/core/src/sandbox/provider_reply.rs
new file mode 100644
index 000000000..2990c40f7
--- /dev/null
+++ b/crates/core/src/sandbox/provider_reply.rs
@@ -0,0 +1,11 @@
+use serde_json::Value;
+
+use crate::sandbox::sandbox_state::SandboxState;
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct ProviderReply {
+ pub(crate) state: SandboxState,
+ pub(crate) message: String,
+ pub(crate) next: Option<String>,
+ pub(crate) data: Option<Value>,
+}
diff --git a/crates/core/src/sandbox/provider_run.rs b/crates/core/src/sandbox/provider_run.rs
new file mode 100644
index 000000000..26f813615
--- /dev/null
+++ b/crates/core/src/sandbox/provider_run.rs
@@ -0,0 +1,168 @@
+//! One provider script call: the request it builds, and the reply data commands return.
+
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use serde_json::{Map, Value, json};
+
+use crate::sandbox::provider_protocol::next_step;
+use crate::sandbox::provider_reply::ProviderReply;
+use crate::sandbox::provider_script_output::ProviderScriptOutput;
+use crate::sandbox::provider_script_request::ProviderScriptRequest;
+use crate::sandbox::provider_spec::ProviderSpec;
+use crate::{AdapterError, AppError, DeliverySemantics, ErrorCode, PlatformAdapter};
+
+const SCRIPT_FILE: &str = "provider.sh";
+
+/// One verb call against a provider, for a sandbox it owns or for the provider itself.
+pub(crate) struct ProviderCall<'a> {
+ pub(crate) spec: &'a ProviderSpec,
+ pub(crate) provider_dir: &'a Path,
+ pub(crate) sandboxes_root: &'a Path,
+ pub(crate) sandbox_name: Option<&'a str>,
+ pub(crate) settings: &'a [(String, String)],
+}
+
+impl<'a> ProviderCall<'a> {
+ pub(crate) fn new(
+ spec: &'a ProviderSpec,
+ provider_dir: &'a Path,
+ sandboxes_root: &'a Path,
+ sandbox_name: Option<&'a str>,
+ settings: &'a [(String, String)],
+ ) -> Self {
+ Self {
+ spec,
+ provider_dir,
+ sandboxes_root,
+ sandbox_name,
+ settings,
+ }
+ }
+
+ pub(crate) fn sandbox_dir(&self) -> Option<PathBuf> {
+ self.sandbox_name.map(|name| self.sandboxes_root.join(name))
+ }
+
+ /// Runs one verb and returns its raw output, with a deadline failure mapped to a plain error.
+ pub(crate) fn run(
+ &self,
+ adapter: &dyn PlatformAdapter,
+ argv: Vec<String>,
+ timeout: Duration,
+ ) -> Result<ProviderScriptOutput, AppError> {
+ let request = self.request(argv, timeout)?;
+ match adapter.run_provider_script(&request) {
+ Ok(output) => Ok(output),
+ Err(error) => Err(AppError::Adapter(self.deadline_error(error, &request.args))),
+ }
+ }
+
+ fn request(
+ &self,
+ argv: Vec<String>,
+ timeout: Duration,
+ ) -> Result<ProviderScriptRequest, AppError> {
+ let working_dir = self
+ .sandbox_dir()
+ .unwrap_or_else(|| self.provider_dir.to_path_buf());
+ Ok(ProviderScriptRequest {
+ script: self.provider_dir.join(SCRIPT_FILE),
+ args: argv,
+ env: self.env()?,
+ working_dir,
+ timeout,
+ })
+ }
+
+ fn env(&self) -> Result<Vec<(String, String)>, AppError> {
+ let mut env = vec![
+ (
+ "AD_PROVIDER_DIR".to_string(),
+ self.provider_dir.display().to_string(),
+ ),
+ (
+ "AD_VERSION".to_string(),
+ env!("CARGO_PKG_VERSION").to_string(),
+ ),
+ ("AD_BINARY".to_string(), binary_path()?),
+ ];
+ if let (Some(name), Some(dir)) = (self.sandbox_name, self.sandbox_dir()) {
+ env.push(("AD_SANDBOX_NAME".to_string(), name.to_string()));
+ env.push(("AD_SANDBOX_DIR".to_string(), dir.display().to_string()));
+ }
+ if let Ok(cwd) = std::env::current_dir()
+ && let Some(cwd) = cwd.to_str()
+ {
+ env.push(("AD_CALLER_CWD".to_string(), cwd.to_string()));
+ }
+ env.extend(self.settings.iter().cloned());
+ Ok(env)
+ }
+
+ fn deadline_error(&self, error: AdapterError, argv: &[String]) -> AdapterError {
+ if error.code != ErrorCode::Timeout {
+ return error;
+ }
+ let verb = argv.first().map(String::as_str).unwrap_or("check");
+ let provider = self.spec.name;
+ let suggestion = next_step(self.sandbox_name);
+ let timed_out = AdapterError::new(
+ ErrorCode::Timeout,
+ format!(
+ "The {provider} provider did not answer `{verb}` in time, so agent-desktop stopped waiting."
+ ),
+ )
+ .with_suggestion(suggestion)
+ .with_disposition(DeliverySemantics::unknown());
+ match error.platform_detail {
+ Some(detail) => timed_out.with_platform_detail(detail),
+ None => timed_out,
+ }
+ }
+}
+
+/// One provider reply as the command's data value.
+pub(crate) fn success_value(name: &str, provider: Option<&str>, reply: ProviderReply) -> Value {
+ let ProviderReply {
+ state,
+ message,
+ next,
+ data,
+ } = reply;
+ let mut value = json!({ "name": name, "state": state, "message": message });
+ let Some(object) = value.as_object_mut() else {
+ return value;
+ };
+ if let Some(provider) = provider {
+ object.insert("provider".to_string(), Value::String(provider.to_string()));
+ }
+ if let Some(next) = next {
+ object.insert("next".to_string(), Value::String(next));
+ }
+ if let Some(Value::Object(data)) = data {
+ merge(object, data);
+ }
+ value
+}
+
+fn merge(object: &mut Map<String, Value>, data: Map<String, Value>) {
+ for (key, value) in data {
+ object.entry(key).or_insert(value);
+ }
+}
+
+fn binary_path() -> Result<String, AppError> {
+ std::env::current_exe()
+ .map(|path| path.display().to_string())
+ .map_err(|_| {
+ AppError::Adapter(
+ AdapterError::new(
+ ErrorCode::Internal,
+ "agent-desktop could not find its own program path.",
+ )
+ .with_suggestion("Run the command from an installed agent-desktop program.")
+ .with_disposition(DeliverySemantics::not_delivered()),
+ )
+ })
+}
diff --git a/crates/core/src/sandbox/provider_script_output.rs b/crates/core/src/sandbox/provider_script_output.rs
new file mode 100644
index 000000000..9eaa8e903
--- /dev/null
+++ b/crates/core/src/sandbox/provider_script_output.rs
@@ -0,0 +1,6 @@
+#[derive(Debug, Clone)]
+pub struct ProviderScriptOutput {
+ pub status: Option<i32>,
+ pub stdout: Vec<u8>,
+ pub stderr_tail: String,
+}
diff --git a/crates/core/src/sandbox/provider_script_request.rs b/crates/core/src/sandbox/provider_script_request.rs
new file mode 100644
index 000000000..82c7ea50b
--- /dev/null
+++ b/crates/core/src/sandbox/provider_script_request.rs
@@ -0,0 +1,11 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+#[derive(Debug, Clone)]
+pub struct ProviderScriptRequest {
+ pub script: PathBuf,
+ pub args: Vec<String>,
+ pub env: Vec<(String, String)>,
+ pub working_dir: PathBuf,
+ pub timeout: Duration,
+}
diff --git a/crates/core/src/sandbox/provider_settings.rs b/crates/core/src/sandbox/provider_settings.rs
new file mode 100644
index 000000000..b18399748
--- /dev/null
+++ b/crates/core/src/sandbox/provider_settings.rs
@@ -0,0 +1,53 @@
+use crate::{AdapterError, AppError, ErrorCode};
+
+const MAX_KEY_LEN: usize = 32;
+const MAX_VALUE_BYTES: usize = 1024;
+
+pub(crate) fn parse_settings(pairs: &[String]) -> Result<Vec<(String, String)>, AppError> {
+ pairs.iter().map(|pair| parse_pair(pair)).collect()
+}
+
+fn parse_pair(pair: &str) -> Result<(String, String), AppError> {
+ let (key, value) = pair
+ .split_once('=')
+ .ok_or_else(|| invalid(pair, "must look like key=value"))?;
+ if !valid_key(key) {
+ return Err(invalid(
+ pair,
+ "has a key that is not lowercase letters, digits, or underscores starting with a letter",
+ ));
+ }
+ if value.len() > MAX_VALUE_BYTES {
+ return Err(invalid(pair, "has a value longer than 1024 bytes"));
+ }
+ if value.contains(['\0', '\n', '\r']) {
+ return Err(invalid(pair, "has a value with a NUL or a newline"));
+ }
+ Ok((
+ format!("AD_SET_{}", key.to_ascii_uppercase()),
+ value.to_string(),
+ ))
+}
+
+fn valid_key(key: &str) -> bool {
+ let bytes = key.as_bytes();
+ bytes.len() <= MAX_KEY_LEN
+ && bytes.first().is_some_and(|b| b.is_ascii_lowercase())
+ && bytes
+ .iter()
+ .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_')
+}
+
+fn invalid(pair: &str, reason: &str) -> AppError {
+ AppError::Adapter(
+ AdapterError::new(
+ ErrorCode::InvalidArgs,
+ format!("Setting {pair:?} {reason}."),
+ )
+ .with_suggestion("Pass each setting as --set key=value with a lowercase key, for example --set ipsw=/path/to/image.ipsw."),
+ )
+}
+
+#[cfg(test)]
+#[path = "provider_settings_tests.rs"]
+mod tests;
diff --git a/crates/core/src/sandbox/provider_settings_tests.rs b/crates/core/src/sandbox/provider_settings_tests.rs
new file mode 100644
index 000000000..e7daa840d
--- /dev/null
+++ b/crates/core/src/sandbox/provider_settings_tests.rs
@@ -0,0 +1,9 @@
+use super::parse_settings;
+
+#[test]
+fn rejects_an_uppercase_key_and_a_value_with_a_newline() {
+ let key = parse_settings(&["Key=v".to_string()]).unwrap_err();
+ assert_eq!(key.code(), "INVALID_ARGS");
+ let value = parse_settings(&["key=a\nb".to_string()]).unwrap_err();
+ assert_eq!(value.code(), "INVALID_ARGS");
+}
diff --git a/crates/core/src/sandbox/provider_spec.rs b/crates/core/src/sandbox/provider_spec.rs
new file mode 100644
index 000000000..5e43da570
--- /dev/null
+++ b/crates/core/src/sandbox/provider_spec.rs
@@ -0,0 +1,5 @@
+#[derive(Debug)]
+pub(crate) struct ProviderSpec {
+ pub(crate) name: &'static str,
+ pub(crate) files: &'static [(&'static str, &'static str)],
+}
diff --git a/crates/core/src/sandbox/provider_table.rs b/crates/core/src/sandbox/provider_table.rs
new file mode 100644
index 000000000..a3967f298
--- /dev/null
+++ b/crates/core/src/sandbox/provider_table.rs
@@ -0,0 +1,41 @@
+use crate::sandbox::provider_spec::ProviderSpec;
+use crate::{AdapterError, AppError, ErrorCode};
+
+#[cfg(not(test))]
+pub(crate) const PROVIDERS: &[ProviderSpec] = &[];
+
+#[cfg(test)]
+pub(crate) const PROVIDERS: &[ProviderSpec] = &[
+ ProviderSpec {
+ name: "stub",
+ files: &[("provider.sh", "#!/bin/sh\nexit 0\n")],
+ },
+ ProviderSpec {
+ name: "other",
+ files: &[("provider.sh", "#!/bin/sh\nexit 0\n")],
+ },
+];
+
+pub(crate) fn find_provider(name: &str) -> Result<&'static ProviderSpec, AppError> {
+ PROVIDERS
+ .iter()
+ .find(|spec| spec.name == name)
+ .ok_or_else(|| {
+ let known: Vec<&str> = PROVIDERS.iter().map(|spec| spec.name).collect();
+ let message = if known.is_empty() {
+ format!(
+ "Unknown sandbox provider {name}. This build includes no sandbox providers."
+ )
+ } else {
+ format!(
+ "Unknown sandbox provider {name}. Known providers: {}.",
+ known.join(", ")
+ )
+ };
+ AppError::Adapter(
+ AdapterError::new(ErrorCode::InvalidArgs, message).with_suggestion(
+ "Run `agent-desktop sandbox install` to see the providers and their states.",
+ ),
+ )
+ })
+}
diff --git a/crates/core/src/sandbox/provider_test_support.rs b/crates/core/src/sandbox/provider_test_support.rs
new file mode 100644
index 000000000..ea2a278d9
--- /dev/null
+++ b/crates/core/src/sandbox/provider_test_support.rs
@@ -0,0 +1,95 @@
+//! A scripted adapter double: it records every provider request and replays a canned reply per verb.
+
+use std::collections::HashMap;
+use std::sync::Mutex;
+
+use crate::adapter::{ActionOps, InputOps, ObservationOps, SystemOps};
+use crate::{AdapterError, ErrorCode, ProviderScriptOutput, ProviderScriptRequest};
+
+#[derive(Default)]
+pub(crate) struct ScriptedAdapter {
+ requests: Mutex<Vec<ProviderScriptRequest>>,
+ replies: Mutex<HashMap<String, Result<ProviderScriptOutput, AdapterError>>>,
+ left_file: Mutex<Option<String>>,
+}
+
+impl ScriptedAdapter {
+ pub(crate) fn new() -> Self {
+ Self::default()
+ }
+
+ pub(crate) fn reply(self, verb: &str, stdout: &str, status: i32) -> Self {
+ self.insert(verb, Ok(output(stdout, status)));
+ self
+ }
+
+ /// Makes every provider run leave `file` in the sandbox directory, as a provider that made something does.
+ pub(crate) fn leaving(self, file: &str) -> Self {
+ if let Ok(mut left_file) = self.left_file.lock() {
+ *left_file = Some(file.to_string());
+ }
+ self
+ }
+
+ fn leave_file(&self, request: &ProviderScriptRequest) {
+ let file = self.left_file.lock().ok().and_then(|file| file.clone());
+ let dir = request.env.iter().find(|(key, _)| key == "AD_SANDBOX_DIR");
+ if let (Some(file), Some((_, dir))) = (file, dir) {
+ let _ = std::fs::write(std::path::Path::new(dir).join(file), b"provider data");
+ }
+ }
+
+ pub(crate) fn fail(self, verb: &str, error: AdapterError) -> Self {
+ self.insert(verb, Err(error));
+ self
+ }
+
+ fn insert(&self, verb: &str, reply: Result<ProviderScriptOutput, AdapterError>) {
+ if let Ok(mut replies) = self.replies.lock() {
+ replies.insert(verb.to_string(), reply);
+ }
+ }
+
+ pub(crate) fn requests(&self) -> Vec<ProviderScriptRequest> {
+ self.requests
+ .lock()
+ .map(|requests| requests.clone())
+ .unwrap_or_default()
+ }
+}
+
+fn output(stdout: &str, status: i32) -> ProviderScriptOutput {
+ ProviderScriptOutput {
+ status: Some(status),
+ stdout: stdout.as_bytes().to_vec(),
+ stderr_tail: String::new(),
+ }
+}
+
+impl ObservationOps for ScriptedAdapter {}
+impl ActionOps for ScriptedAdapter {}
+impl InputOps for ScriptedAdapter {}
+
+impl SystemOps for ScriptedAdapter {
+ fn run_provider_script(
+ &self,
+ request: &ProviderScriptRequest,
+ ) -> Result<ProviderScriptOutput, AdapterError> {
+ if let Ok(mut requests) = self.requests.lock() {
+ requests.push(request.clone());
+ }
+ self.leave_file(request);
+ let verb = request.args.first().cloned().unwrap_or_default();
+ self.replies
+ .lock()
+ .ok()
+ .and_then(|replies| replies.get(&verb).cloned())
+ .unwrap_or_else(|| {
+ Err(AdapterError::new(
+ ErrorCode::ActionFailed,
+ format!("The stub adapter has no reply for {verb}."),
+ )
+ .with_disposition(crate::DeliverySemantics::not_delivered()))
+ })
+ }
+}
diff --git a/crates/core/src/sandbox/sandbox_entry.rs b/crates/core/src/sandbox/sandbox_entry.rs
new file mode 100644
index 000000000..8d83f776b
--- /dev/null
+++ b/crates/core/src/sandbox/sandbox_entry.rs
@@ -0,0 +1,8 @@
+use crate::AppError;
+use crate::sandbox::sandbox_record::SandboxRecord;
+
+/// One named sandbox directory and whether its record could be read.
+pub(crate) struct SandboxEntry {
+ pub(crate) name: String,
+ pub(crate) record: Result<SandboxRecord, AppError>,
+}
diff --git a/crates/core/src/sandbox/sandbox_name.rs b/crates/core/src/sandbox/sandbox_name.rs
new file mode 100644
index 000000000..5c03edba0
--- /dev/null
+++ b/crates/core/src/sandbox/sandbox_name.rs
@@ -0,0 +1,28 @@
+use crate::{AdapterError, AppError, ErrorCode};
+
+const MAX_NAME_LEN: usize = 32;
+
+pub(crate) fn validate_sandbox_name(name: &str) -> Result<(), AppError> {
+ let bytes = name.as_bytes();
+ let starts_well = bytes
+ .first()
+ .is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit());
+ let rest_well = bytes
+ .iter()
+ .skip(1)
+ .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-');
+ if starts_well && rest_well && bytes.len() <= MAX_NAME_LEN {
+ return Ok(());
+ }
+ Err(AppError::Adapter(
+ AdapterError::new(
+ ErrorCode::InvalidArgs,
+ "Sandbox names use 1 to 32 lowercase letters, digits, or dashes, starting with a letter or digit.",
+ )
+ .with_suggestion("Pick a name such as `dev-1`, then run the command again."),
+ ))
+}
+
+#[cfg(test)]
+#[path = "sandbox_name_tests.rs"]
+mod tests;
diff --git a/crates/core/src/sandbox/sandbox_name_tests.rs b/crates/core/src/sandbox/sandbox_name_tests.rs
new file mode 100644
index 000000000..d3320e5e4
--- /dev/null
+++ b/crates/core/src/sandbox/sandbox_name_tests.rs
@@ -0,0 +1,7 @@
+use super::validate_sandbox_name;
+
+#[test]
+fn rejects_uppercase_and_underscores_with_invalid_args() {
+ let error = validate_sandbox_name("Dev_1").unwrap_err();
+ assert_eq!(error.code(), "INVALID_ARGS");
+}
diff --git a/crates/core/src/sandbox/sandbox_record.rs b/crates/core/src/sandbox/sandbox_record.rs
new file mode 100644
index 000000000..a985b19a6
--- /dev/null
+++ b/crates/core/src/sandbox/sandbox_record.rs
@@ -0,0 +1,8 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub(crate) struct SandboxRecord {
+ pub(crate) name: String,
+ pub(crate) provider: String,
+ pub(crate) created_at: u64,
+}
diff --git a/crates/core/src/sandbox/sandbox_state.rs b/crates/core/src/sandbox/sandbox_state.rs
new file mode 100644
index 000000000..e008e99b6
--- /dev/null
+++ b/crates/core/src/sandbox/sandbox_state.rs
@@ -0,0 +1,30 @@
+use serde::Serialize;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum SandboxState {
+ Unavailable,
+ Missing,
+ Ready,
+ Working,
+ NeedsSetup,
+ Running,
+ Stopped,
+ Broken,
+}
+
+impl SandboxState {
+ pub(crate) fn from_wire(value: &str) -> Option<Self> {
+ match value {
+ "unavailable" => Some(Self::Unavailable),
+ "missing" => Some(Self::Missing),
+ "ready" => Some(Self::Ready),
+ "working" => Some(Self::Working),
+ "needs_setup" => Some(Self::NeedsSetup),
+ "running" => Some(Self::Running),
+ "stopped" => Some(Self::Stopped),
+ "broken" => Some(Self::Broken),
+ _ => None,
+ }
+ }
+}
diff --git a/crates/core/src/sandbox/sandbox_store.rs b/crates/core/src/sandbox/sandbox_store.rs
new file mode 100644
index 000000000..f0a5fbf9d
--- /dev/null
+++ b/crates/core/src/sandbox/sandbox_store.rs
@@ -0,0 +1,194 @@
+use crate::sandbox::sandbox_entry::SandboxEntry;
+use crate::sandbox::sandbox_name::validate_sandbox_name;
+use crate::sandbox::sandbox_record::SandboxRecord;
+use crate::storage::private_file::{read_private_bounded, write_atomic};
+use crate::storage::private_file_parent::ensure_private;
+use crate::{
+ AdapterError, AppError, Deadline, DeliverySemantics, ErrorCode, storage::file_lock::FileLock,
+};
+use std::io::ErrorKind;
+use std::path::{Path, PathBuf};
+
+pub(crate) const RECORD_FILE: &str = "sandbox.json";
+const CREATE_LOCK_FILE: &str = ".create.lock";
+const MAX_RECORD_BYTES: u64 = 4096;
+const BUSY_WAIT_MS: u64 = 200;
+
+pub(crate) fn create(root: &Path, record: &SandboxRecord) -> Result<PathBuf, AppError> {
+ validate_sandbox_name(&record.name)?;
+ ensure_private(root)?;
+ let _lock = FileLock::acquire(
+ &root.join(CREATE_LOCK_FILE),
+ Deadline::standard()?,
+ "sandbox record create",
+ )?;
+ let dir = root.join(&record.name);
+ if entry_exists(&dir)? && !is_crashed_publish(&dir) {
+ return Err(already_exists(&load(root, &record.name)?));
+ }
+ ensure_private(&dir)?;
+ write_atomic(&dir.join(RECORD_FILE), &serde_json::to_vec(record)?)?;
+ Ok(dir)
+}
+
+/// Takes the sandbox's lock, so only one command changes a sandbox at a time. A held lock fails at once.
+pub(crate) fn hold(root: &Path, name: &str) -> Result<FileLock, AppError> {
+ validate_sandbox_name(name)?;
+ ensure_private(root)?;
+ FileLock::acquire(
+ &root.join(format!(".{name}.lock")),
+ Deadline::after(BUSY_WAIT_MS)?,
+ "sandbox change",
+ )
+ .map_err(|_| busy(name))
+}
+
+/// Whether `dir` holds nothing but the temporaries of a record write that never finished.
+fn is_crashed_publish(dir: &Path) -> bool {
+ let is_directory = std::fs::symlink_metadata(dir).is_ok_and(|metadata| metadata.is_dir());
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return false;
+ };
+ is_directory
+ && entries.filter_map(Result::ok).all(|entry| {
+ let name = entry.file_name();
+ let name = name.to_string_lossy();
+ name.starts_with(&format!(".{RECORD_FILE}.")) && name.ends_with(".tmp")
+ })
+}
+
+fn entry_exists(path: &Path) -> Result<bool, AppError> {
+ match std::fs::symlink_metadata(path) {
+ Ok(_) => Ok(true),
+ Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
+ Err(error) => Err(error.into()),
+ }
+}
+
+pub(crate) fn load(root: &Path, name: &str) -> Result<SandboxRecord, AppError> {
+ validate_sandbox_name(name)?;
+ let dir = root.join(name);
+ match std::fs::symlink_metadata(&dir) {
+ Ok(metadata) if metadata.is_dir() => {}
+ Ok(_) => return Err(broken(root, name, "its entry is not a regular directory")),
+ Err(error) if error.kind() == ErrorKind::NotFound => return Err(not_found(name)),
+ Err(error) => return Err(broken(root, name, &error.to_string())),
+ }
+ match read_private_bounded(&dir.join(RECORD_FILE), MAX_RECORD_BYTES) {
+ Ok(bytes) => serde_json::from_slice(&bytes)
+ .ok()
+ .filter(|record: &SandboxRecord| record.name == name)
+ .ok_or_else(|| broken(root, name, "its record is malformed")),
+ Err(error) if error.kind() == ErrorKind::NotFound => {
+ Err(broken(root, name, "its record file is missing"))
+ }
+ Err(error) if error.kind() == ErrorKind::InvalidData => {
+ Err(broken(root, name, "its record is malformed"))
+ }
+ Err(error) => Err(broken(
+ root,
+ name,
+ &format!("its record was not read: {error}"),
+ )),
+ }
+}
+
+pub(crate) fn list(root: &Path) -> Result<Vec<SandboxEntry>, AppError> {
+ let entries = match std::fs::read_dir(root) {
+ Ok(entries) => entries,
+ Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
+ Err(error) => return Err(error.into()),
+ };
+ let mut sandboxes = Vec::new();
+ for entry in entries {
+ let entry = entry?;
+ if !entry.file_type()?.is_dir() {
+ continue;
+ }
+ let Ok(name) = entry.file_name().into_string() else {
+ continue;
+ };
+ if validate_sandbox_name(&name).is_err() {
+ continue;
+ }
+ let record = load(root, &name);
+ if record
+ .as_ref()
+ .is_err_and(|error| error.code() == ErrorCode::SandboxNotFound.as_str())
+ {
+ continue;
+ }
+ sandboxes.push(SandboxEntry { name, record });
+ }
+ sandboxes.sort_by(|a, b| a.name.cmp(&b.name));
+ Ok(sandboxes)
+}
+
+pub(crate) fn remove(root: &Path, name: &str) -> Result<(), AppError> {
+ validate_sandbox_name(name)?;
+ match std::fs::remove_dir_all(root.join(name)) {
+ Ok(()) => Ok(()),
+ Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(error.into()),
+ }
+}
+
+fn already_exists(record: &SandboxRecord) -> AppError {
+ AppError::Adapter(
+ AdapterError::new(
+ ErrorCode::InvalidArgs,
+ format!(
+ "A sandbox named {} already exists (provider {}).",
+ record.name, record.provider
+ ),
+ )
+ .with_suggestion(format!(
+ "Pick another name, or remove it first: run `agent-desktop sandbox list` and follow the entry for {}.",
+ record.name
+ ))
+ .with_disposition(DeliverySemantics::not_delivered()),
+ )
+}
+
+/// The one error for a sandbox agent-desktop cannot use. It has no provider to ask, so the way out is manual.
+pub(crate) fn broken(root: &Path, name: &str, reason: &str) -> AppError {
+ AppError::Adapter(
+ AdapterError::new(
+ ErrorCode::InvalidArgs,
+ format!("Sandbox {name} cannot be used: {reason}."),
+ )
+ .with_suggestion(format!(
+ "Stop anything the sandbox still runs, then delete {}.",
+ root.join(name).display()
+ ))
+ .with_disposition(DeliverySemantics::not_delivered()),
+ )
+}
+
+fn busy(name: &str) -> AppError {
+ AppError::Adapter(
+ AdapterError::new(
+ ErrorCode::ActionFailed,
+ format!("Another agent-desktop command is changing sandbox {name}."),
+ )
+ .with_suggestion(format!(
+ "Run `agent-desktop sandbox status {name}` and retry when that command has finished."
+ ))
+ .with_disposition(DeliverySemantics::not_delivered()),
+ )
+}
+
+pub(crate) fn not_found(name: &str) -> AppError {
+ AppError::Adapter(
+ AdapterError::new(
+ ErrorCode::SandboxNotFound,
+ format!("No sandbox named {name} exists."),
+ )
+ .with_suggestion("Run `agent-desktop sandbox list` to see the sandboxes that exist.")
+ .with_disposition(DeliverySemantics::not_delivered()),
+ )
+}
+
+#[cfg(test)]
+#[path = "sandbox_store_tests.rs"]
+mod tests;
diff --git a/crates/core/src/sandbox/sandbox_store_tests.rs b/crates/core/src/sandbox/sandbox_store_tests.rs
new file mode 100644
index 000000000..0baf1e4ef
--- /dev/null
+++ b/crates/core/src/sandbox/sandbox_store_tests.rs
@@ -0,0 +1,217 @@
+use super::{RECORD_FILE, create, list, load};
+use crate::sandbox::sandbox_record::SandboxRecord;
+use crate::storage::private_file::write_atomic;
+use crate::storage::private_file_parent::ensure_private;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Barrier};
+
+struct Scratch(PathBuf);
+
+impl Scratch {
+ fn new(label: &str) -> Self {
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-sandbox-store-{label}-{}",
+ crate::refs::new_snapshot_id()
+ ));
+ Self(path)
+ }
+
+ fn root(&self) -> PathBuf {
+ self.0.join("sandboxes")
+ }
+}
+
+impl Drop for Scratch {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+}
+
+fn record(name: &str, provider: &str, created_at: u64) -> SandboxRecord {
+ SandboxRecord {
+ name: name.to_string(),
+ provider: provider.to_string(),
+ created_at,
+ }
+}
+
+fn write_record(root: &Path, name: &str, bytes: &[u8]) {
+ ensure_private(&root.join(name)).expect("private sandbox directory");
+ write_atomic(&root.join(name).join(RECORD_FILE), bytes).expect("private record");
+}
+
+#[test]
+fn duplicate_create_fails_and_keeps_the_first_record() {
+ let scratch = Scratch::new("duplicate");
+ let root = scratch.root();
+ create(&root, &record("dev-1", "macos", 1)).unwrap();
+
+ let error = create(&root, &record("dev-1", "macos", 2)).unwrap_err();
+
+ assert_eq!(error.code(), "INVALID_ARGS");
+ let kept = load(&root, "dev-1").unwrap();
+ assert_eq!(kept.provider, "macos");
+ assert_eq!(kept.created_at, 1);
+}
+
+#[test]
+fn concurrent_creates_of_one_name_admit_exactly_one_and_refuse_the_rest_as_duplicates() {
+ let scratch = Scratch::new("concurrent");
+ let root: Arc<Path> = Arc::from(scratch.root().as_path());
+ let threads = 8;
+ let barrier = Arc::new(Barrier::new(threads));
+ let mut handles = Vec::new();
+ for index in 0..threads {
+ let root = Arc::clone(&root);
+ let barrier = Arc::clone(&barrier);
+ handles.push(std::thread::spawn(move || {
+ barrier.wait();
+ create(&root, &record("race", "macos", index as u64))
+ .map(|_| ())
+ .map_err(|error| error.code().to_string())
+ }));
+ }
+ let results: Vec<Result<(), String>> = handles
+ .into_iter()
+ .map(|handle| handle.join().unwrap())
+ .collect();
+ assert_eq!(results.iter().filter(|result| result.is_ok()).count(), 1);
+ for result in &results {
+ if let Err(code) = result {
+ assert_eq!(
+ code.as_str(),
+ "INVALID_ARGS",
+ "a losing create reports a duplicate"
+ );
+ }
+ }
+ assert_eq!(load(&root, "race").unwrap().name, "race");
+}
+
+#[test]
+fn malformed_record_is_kept_beside_a_healthy_one_and_non_sandboxes_are_skipped() {
+ let scratch = Scratch::new("list-malformed");
+ let root = scratch.root();
+ create(&root, &record("healthy", "macos", 1)).expect("healthy record");
+ write_record(&root, "broken", b"{not json");
+ std::fs::create_dir_all(root.join("Not-A-Sandbox")).expect("invalid name directory");
+
+ let entries = list(&root).expect("list");
+
+ let names: Vec<&str> = entries.iter().map(|entry| entry.name.as_str()).collect();
+ assert_eq!(
+ names,
+ ["broken", "healthy"],
+ "invalid names and files are skipped"
+ );
+ let broken = entries[0].record.as_ref().expect_err("malformed record");
+ assert_eq!(broken.code(), "INVALID_ARGS");
+ assert!(
+ broken.suggestion().is_some_and(
+ |suggestion| suggestion.contains(&root.join("broken").display().to_string())
+ ),
+ "the error names the directory to delete"
+ );
+ assert_eq!(
+ entries[1].record.as_ref().expect("healthy record").provider,
+ "macos"
+ );
+}
+
+#[test]
+fn empty_and_missing_records_are_kept_as_broken_directories() {
+ let scratch = Scratch::new("list-empty-missing");
+ let root = scratch.root();
+ write_record(&root, "empty", b"");
+ ensure_private(&root.join("missing")).expect("empty sandbox directory");
+
+ let entries = list(&root).expect("list");
+
+ assert_eq!(entries.len(), 2);
+ assert_eq!(entries[0].name, "empty");
+ assert_eq!(
+ entries[0].record.as_ref().expect_err("empty").code(),
+ "INVALID_ARGS"
+ );
+ assert_eq!(entries[1].name, "missing");
+ assert_eq!(
+ entries[1].record.as_ref().expect_err("missing").code(),
+ "INVALID_ARGS"
+ );
+}
+
+#[test]
+fn a_root_that_is_not_a_directory_is_an_error_not_an_empty_list() {
+ let scratch = Scratch::new("root-file");
+ std::fs::create_dir_all(&scratch.0).expect("scratch directory");
+ std::fs::write(scratch.root(), b"not a directory").expect("root file");
+
+ assert!(list(&scratch.root()).is_err());
+}
+
+#[test]
+fn subprocess_crash_before_record_publish() {
+ let Some(root) = std::env::var_os("AGENT_DESKTOP_CRASH_SANDBOX_ROOT") else {
+ return;
+ };
+ let root = PathBuf::from(root);
+ let _ = create(&root, &record("crash", "macos", 1));
+ panic!("crash failpoint did not abort");
+}
+
+#[test]
+fn a_crash_before_publish_leaves_no_record_and_the_next_create_publishes() {
+ let scratch = Scratch::new("crash");
+ let root = scratch.root();
+ let destination = root.join("crash").join(RECORD_FILE);
+ let status = std::process::Command::new(std::env::current_exe().unwrap())
+ .arg("--exact")
+ .arg("sandbox::sandbox_store::tests::subprocess_crash_before_record_publish")
+ .arg("--nocapture")
+ .env("AGENT_DESKTOP_CRASH_SANDBOX_ROOT", &root)
+ .env("AGENT_DESKTOP_TEST_CRASH_BEFORE_RENAME", &destination)
+ .status()
+ .unwrap();
+ assert!(!status.success(), "the failpoint aborts the writer");
+ assert_eq!(
+ load(&root, "crash")
+ .expect_err("nothing was published")
+ .code(),
+ "INVALID_ARGS"
+ );
+
+ create(&root, &record("crash", "macos", 1)).expect("a crashed publish is retryable");
+
+ assert_eq!(load(&root, "crash").unwrap().created_at, 1);
+}
+
+#[test]
+fn names_that_escape_the_root_are_refused() {
+ let scratch = Scratch::new("traversal");
+ let error = load(&scratch.root(), "../outside").unwrap_err();
+ assert_eq!(error.code(), "INVALID_ARGS");
+}
+
+#[test]
+fn a_record_that_names_another_sandbox_is_refused_as_malformed() {
+ let scratch = Scratch::new("renamed");
+ let root = scratch.root();
+ create(&root, &record("victim", "macos", 1)).unwrap();
+ let foreign = serde_json::to_vec(&record("victim", "macos", 2)).unwrap();
+ write_record(&root, "dev-1", &foreign);
+
+ assert_eq!(load(&root, "dev-1").unwrap_err().code(), "INVALID_ARGS");
+ let listed = list(&root).unwrap();
+ let entry = listed.iter().find(|entry| entry.name == "dev-1").unwrap();
+ assert!(entry.record.is_err(), "list never reports the other name");
+}
+
+#[test]
+fn removing_a_directory_the_provider_already_removed_succeeds() {
+ let scratch = Scratch::new("removed");
+ let root = scratch.root();
+ create(&root, &record("dev-1", "macos", 1)).unwrap();
+ std::fs::remove_dir_all(root.join("dev-1")).unwrap();
+
+ super::remove(&root, "dev-1").expect("nothing is left to remove");
+}
diff --git a/crates/core/src/trace/trace_artifacts_dispatch_budget_tests.rs b/crates/core/src/trace/trace_artifacts_dispatch_budget_tests.rs
index 624caf17e..13157e8d5 100644
--- a/crates/core/src/trace/trace_artifacts_dispatch_budget_tests.rs
+++ b/crates/core/src/trace/trace_artifacts_dispatch_budget_tests.rs
@@ -106,7 +106,7 @@ fn slow_pre_capture_preserves_dispatch_budget() {
ref_id: "@e1",
context: &context,
},
- ActionRequest::headless(Action::Click).with_timeout_ms(Some(500)),
+ ActionRequest::headless(Action::Click).with_timeout_ms(Some(ACTION_BUDGET_MS)),
crate::ref_action::ref_action_single::dispatch_resolved,
);
diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.h
index fccc48471..f2c181100 100644
--- a/crates/ffi/include/agent_desktop.h
+++ b/crates/ffi/include/agent_desktop.h
@@ -204,6 +204,7 @@ enum AdResult
AD_RESULT_ERR_POLICY_DENIED = -14,
AD_RESULT_ERR_AMBIGUOUS_TARGET = -15,
AD_RESULT_ERR_APP_UNRESPONSIVE = -16,
+ AD_RESULT_ERR_SANDBOX_NOT_FOUND = -17,
};
#ifndef __cplusplus
#if __STDC_VERSION__ >= 202311L
diff --git a/crates/ffi/src/error.rs b/crates/ffi/src/error.rs
index aff3ce321..c0492ceef 100644
--- a/crates/ffi/src/error.rs
+++ b/crates/ffi/src/error.rs
@@ -25,6 +25,7 @@ pub enum AdResult {
ErrPolicyDenied = -14,
ErrAmbiguousTarget = -15,
ErrAppUnresponsive = -16,
+ ErrSandboxNotFound = -17,
}
const _: () = assert!(AdResult::ErrPermDenied as i32 == -1);
@@ -43,6 +44,7 @@ const _: () = assert!(AdResult::ErrSnapshotNotFound as i32 == -13);
const _: () = assert!(AdResult::ErrPolicyDenied as i32 == -14);
const _: () = assert!(AdResult::ErrAmbiguousTarget as i32 == -15);
const _: () = assert!(AdResult::ErrAppUnresponsive as i32 == -16);
+const _: () = assert!(AdResult::ErrSandboxNotFound as i32 == -17);
enum MessageSource {
Owned(CString),
@@ -114,6 +116,7 @@ fn error_code_to_result(code: &ErrorCode) -> AdResult {
ErrorCode::SnapshotNotFound => AdResult::ErrSnapshotNotFound,
ErrorCode::PolicyDenied => AdResult::ErrPolicyDenied,
ErrorCode::AppUnresponsive => AdResult::ErrAppUnresponsive,
+ ErrorCode::SandboxNotFound => AdResult::ErrSandboxNotFound,
}
}
diff --git a/crates/ffi/src/error_tests.rs b/crates/ffi/src/error_tests.rs
index b6b49a692..c98a0ec97 100644
--- a/crates/ffi/src/error_tests.rs
+++ b/crates/ffi/src/error_tests.rs
@@ -45,6 +45,7 @@ fn result_discriminants_preserve_existing_abi_values() {
assert_eq!(AdResult::ErrPolicyDenied as i32, -14);
assert_eq!(AdResult::ErrAmbiguousTarget as i32, -15);
assert_eq!(AdResult::ErrAppUnresponsive as i32, -16);
+ assert_eq!(AdResult::ErrSandboxNotFound as i32, -17);
}
/// Reverse of `error_code_to_result`, kept solely to guard the bijection. The
@@ -72,6 +73,7 @@ fn error_code_origin(result: AdResult) -> Option<ErrorCode> {
AdResult::ErrPolicyDenied => ErrorCode::PolicyDenied,
AdResult::ErrAmbiguousTarget => ErrorCode::AmbiguousTarget,
AdResult::ErrAppUnresponsive => ErrorCode::AppUnresponsive,
+ AdResult::ErrSandboxNotFound => ErrorCode::SandboxNotFound,
})
}
@@ -94,6 +96,7 @@ fn error_code_and_ad_result_error_variants_stay_in_bijection() {
AdResult::ErrPolicyDenied,
AdResult::ErrAmbiguousTarget,
AdResult::ErrAppUnresponsive,
+ AdResult::ErrSandboxNotFound,
] {
let code = error_code_origin(result).expect("error variant must have an ErrorCode origin");
assert_eq!(
diff --git a/crates/linux/src/system/signal/signal_boundary_tests.rs b/crates/linux/src/system/signal/signal_boundary_tests.rs
index 68e4e74c4..f5d4ce33d 100644
--- a/crates/linux/src/system/signal/signal_boundary_tests.rs
+++ b/crates/linux/src/system/signal/signal_boundary_tests.rs
@@ -20,7 +20,8 @@ fn successor(code: &ErrorCode) -> Option<ErrorCode> {
ErrorCode::Timeout => Some(ErrorCode::InvalidArgs),
ErrorCode::InvalidArgs => Some(ErrorCode::NotificationNotFound),
ErrorCode::NotificationNotFound => Some(ErrorCode::SnapshotNotFound),
- ErrorCode::SnapshotNotFound => Some(ErrorCode::PolicyDenied),
+ ErrorCode::SnapshotNotFound => Some(ErrorCode::SandboxNotFound),
+ ErrorCode::SandboxNotFound => Some(ErrorCode::PolicyDenied),
ErrorCode::PolicyDenied => Some(ErrorCode::AppUnresponsive),
ErrorCode::AppUnresponsive => Some(ErrorCode::Internal),
ErrorCode::Internal => None,
diff --git a/crates/macos/src/system/adapter.rs b/crates/macos/src/system/adapter.rs
index a1a8d01d8..839fd27e5 100644
--- a/crates/macos/src/system/adapter.rs
+++ b/crates/macos/src/system/adapter.rs
@@ -2,8 +2,8 @@ use agent_desktop_core::{
ActionResult, AdapterError, Deadline, DismissAllNotificationsRequest,
DismissNotificationRequest, ImageBuffer, InteractionLease, NotificationActionRequest,
NotificationFilter, NotificationInfo, OperationReport, PermissionReport, ProcessIdentity,
- ScreenshotTarget, SignalBaseline, SignalFilter, SnapshotSurface, SystemOps, WindowInfo,
- WindowOp,
+ ProviderScriptOutput, ProviderScriptRequest, ScreenshotTarget, SignalBaseline, SignalFilter,
+ SnapshotSurface, SystemOps, WindowInfo, WindowOp,
};
use crate::adapter::MacOSAdapter;
@@ -126,6 +126,13 @@ impl SystemOps for MacOSAdapter {
crate::system::process::process_state::process_state_impl(process, deadline)
}
+ fn run_provider_script(
+ &self,
+ request: &ProviderScriptRequest,
+ ) -> Result<ProviderScriptOutput, AdapterError> {
+ crate::system::process::provider_script::run_provider_script(request)
+ }
+
fn supported_surfaces(&self) -> Vec<SnapshotSurface> {
crate::system::signals::supported_surfaces_impl()
}
diff --git a/crates/macos/src/system/process/interrupt.rs b/crates/macos/src/system/process/interrupt.rs
new file mode 100644
index 000000000..b583f584c
--- /dev/null
+++ b/crates/macos/src/system/process/interrupt.rs
@@ -0,0 +1,75 @@
+//! Stops the subprocess group in flight when a terminating signal arrives, so a cancelled command leaves no
+//! orphan: the group gets SIGTERM, a short grace, then SIGKILL, and only then does this process end.
+
+use std::sync::Once;
+use std::sync::atomic::{AtomicI32, Ordering};
+
+static ACTIVE_GROUP: AtomicI32 = AtomicI32::new(0);
+static INSTALL: Once = Once::new();
+const FORWARDED: [i32; 3] = [libc::SIGHUP, libc::SIGINT, libc::SIGTERM];
+const GRACE_POLLS: u32 = 40;
+const GRACE_POLL: libc::timespec = libc::timespec {
+ tv_sec: 0,
+ tv_nsec: 50_000_000,
+};
+
+/// Makes SIGHUP, SIGINT and SIGTERM stop the tracked subprocess group before they end this process. Only
+/// the CLI's sandbox path calls it, so a host application that loads the library keeps its own handlers.
+pub(super) fn forward_to_active_group() {
+ INSTALL.call_once(install);
+}
+
+/// Marks one subprocess group as the one a terminating signal must reach. Dropping it clears the mark.
+/// One group is tracked at a time, which matches how commands run their subprocesses.
+pub(super) struct ActiveGroup;
+
+impl ActiveGroup {
+ pub(super) fn track(process_group: i32) -> Self {
+ ACTIVE_GROUP.store(process_group, Ordering::SeqCst);
+ Self
+ }
+}
+
+impl Drop for ActiveGroup {
+ fn drop(&mut self) {
+ ACTIVE_GROUP.store(0, Ordering::SeqCst);
+ }
+}
+
+fn install() {
+ let handler = forward as extern "C" fn(i32) as libc::sighandler_t;
+ for signal in FORWARDED {
+ let previous = unsafe { libc::signal(signal, handler) };
+ if previous == libc::SIG_IGN {
+ unsafe { libc::signal(signal, libc::SIG_IGN) };
+ }
+ }
+}
+
+extern "C" fn forward(signal: i32) {
+ let group = ACTIVE_GROUP.load(Ordering::SeqCst);
+ if group > 0 {
+ stop_group(group);
+ }
+ unsafe {
+ libc::signal(signal, libc::SIG_DFL);
+ libc::raise(signal);
+ }
+}
+
+/// Uses only async-signal-safe calls, because it runs inside the signal handler.
+fn stop_group(group: i32) {
+ unsafe { libc::kill(-group, libc::SIGTERM) };
+ for _ in 0..GRACE_POLLS {
+ unsafe { libc::waitpid(group, std::ptr::null_mut(), libc::WNOHANG) };
+ if unsafe { libc::kill(-group, 0) } != 0 {
+ return;
+ }
+ unsafe { libc::nanosleep(&GRACE_POLL, std::ptr::null_mut()) };
+ }
+ unsafe { libc::kill(-group, libc::SIGKILL) };
+}
+
+#[cfg(test)]
+#[path = "interrupt_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/system/process/interrupt_tests.rs b/crates/macos/src/system/process/interrupt_tests.rs
new file mode 100644
index 000000000..9f64b7e4a
--- /dev/null
+++ b/crates/macos/src/system/process/interrupt_tests.rs
@@ -0,0 +1,82 @@
+use crate::system::process::run_with_timeout;
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+const PID_FILE_ENV: &str = "AD_INTERRUPT_TEST_PID_FILE";
+const SCRIPT_ENV: &str = "AD_INTERRUPT_TEST_SCRIPT";
+const OBEYS_TERM: &str = "echo $$ > \"$0\"; sleep 30; :";
+const IGNORES_TERM: &str = "trap '' TERM; echo $$ > \"$0\"; sleep 30; :";
+
+fn helper_name() -> String {
+ let module = module_path!();
+ let local = module.split_once("::").map_or(module, |(_, rest)| rest);
+ format!("{local}::helper_runs_a_slow_subprocess")
+}
+
+fn group_is_alive(process_group: i32) -> bool {
+ unsafe { libc::kill(-process_group, 0) == 0 }
+}
+
+#[test]
+#[ignore = "re-executed as a child by a_terminated_host_takes_its_subprocess_group_with_it"]
+fn helper_runs_a_slow_subprocess() {
+ let Some(pid_file) = std::env::var_os(PID_FILE_ENV) else {
+ return;
+ };
+ let script = std::env::var(SCRIPT_ENV).unwrap_or_default();
+ let mut command = Command::new("/bin/sh");
+ command.args(["-c", &script]).arg(pid_file);
+ super::forward_to_active_group();
+ let _ = run_with_timeout(&mut command, "helper", Duration::from_secs(30));
+}
+
+#[test]
+fn a_terminated_host_takes_its_subprocess_group_with_it() {
+ assert_group_dies_with_host("obeys", OBEYS_TERM);
+}
+
+#[test]
+fn a_terminated_host_kills_a_subprocess_group_that_ignores_sigterm() {
+ assert_group_dies_with_host("ignores", IGNORES_TERM);
+}
+
+fn assert_group_dies_with_host(label: &str, script: &str) {
+ let pid_file =
+ std::env::temp_dir().join(format!("ad-interrupt-{label}-{}", std::process::id()));
+ let _ = std::fs::remove_file(&pid_file);
+ let mut host = Command::new(std::env::current_exe().unwrap())
+ .args(["--ignored", "--exact", &helper_name()])
+ .env(PID_FILE_ENV, &pid_file)
+ .env(SCRIPT_ENV, script)
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .unwrap();
+ let deadline = Instant::now() + Duration::from_secs(20);
+ let process_group = loop {
+ let recorded = std::fs::read_to_string(&pid_file).unwrap_or_default();
+ if let Ok(pid) = recorded.trim().parse::<i32>() {
+ break pid;
+ }
+ assert!(Instant::now() < deadline, "the helper never started");
+ std::thread::sleep(Duration::from_millis(20));
+ };
+ let _ = std::fs::remove_file(&pid_file);
+ assert!(group_is_alive(process_group), "the subprocess is running");
+
+ unsafe { libc::kill(host.id() as i32, libc::SIGTERM) };
+ host.wait().unwrap();
+
+ let deadline = Instant::now() + Duration::from_secs(5);
+ while group_is_alive(process_group) && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ let survived = group_is_alive(process_group);
+ if survived {
+ unsafe { libc::kill(-process_group, libc::SIGKILL) };
+ }
+ assert!(
+ !survived,
+ "the subprocess group outlived its terminated host"
+ );
+}
diff --git a/crates/macos/src/system/process/mod.rs b/crates/macos/src/system/process/mod.rs
index dca44c028..5e2df5bb7 100644
--- a/crates/macos/src/system/process/mod.rs
+++ b/crates/macos/src/system/process/mod.rs
@@ -49,14 +49,16 @@ pub(crate) fn run_with_deadline(
})?;
configure_process_group(command);
command.stdout(Stdio::piped()).stderr(Stdio::piped());
- let mut child = command
- .spawn()
- .map_err(|error| AdapterError::internal(format!("{label}: {error}")))?;
+ let mut child = command.spawn().map_err(|error| {
+ AdapterError::internal(format!("{label}: {error}"))
+ .with_disposition(agent_desktop_core::DeliverySemantics::not_delivered())
+ })?;
let process_group = i32::try_from(child.id()).map_err(|_| {
let _ = child.kill();
let _ = child.wait();
AdapterError::internal(format!("{label}: child PID exceeds the macOS pid_t range"))
})?;
+ let _interrupt = interrupt::ActiveGroup::track(process_group);
let mut stdout = child.stdout.take().map(spawn_drain);
let mut stderr = child.stderr.take().map(spawn_drain);
@@ -324,11 +326,13 @@ fn output_limit_error(label: &str, stdout: &DrainResult, stderr: &DrainResult) -
}))
}
+mod interrupt;
pub(crate) mod legacy_host;
pub(crate) mod process_apps;
pub(crate) mod process_arguments;
pub(crate) mod process_identity;
pub(crate) mod process_state;
+pub(crate) mod provider_script;
#[cfg(all(test, unix))]
#[path = "process_tests.rs"]
mod tests;
diff --git a/crates/macos/src/system/process/provider_script.rs b/crates/macos/src/system/process/provider_script.rs
new file mode 100644
index 000000000..4430e986c
--- /dev/null
+++ b/crates/macos/src/system/process/provider_script.rs
@@ -0,0 +1,81 @@
+use agent_desktop_core::{AdapterError, ErrorCode, ProviderScriptOutput, ProviderScriptRequest};
+use std::os::unix::process::ExitStatusExt;
+use std::process::{Command, Stdio};
+use std::time::Instant;
+
+use super::run_with_deadline;
+
+const PROVIDER_SCRIPT_INHERITED_ENV: [&str; 3] = ["PATH", "HOME", "TMPDIR"];
+const TIMEOUT_MESSAGE: &str = "The provider script did not finish in time.";
+const TIMEOUT_SUGGESTION: &str = "Run `agent-desktop sandbox status` to check the sandbox.";
+
+pub(crate) fn run_provider_script(
+ request: &ProviderScriptRequest,
+) -> Result<ProviderScriptOutput, AdapterError> {
+ let deadline = Instant::now().checked_add(request.timeout).ok_or_else(|| {
+ AdapterError::timeout(TIMEOUT_MESSAGE).with_suggestion(TIMEOUT_SUGGESTION)
+ })?;
+ let mut command = Command::new("/bin/sh");
+ command.arg(&request.script).args(&request.args).env_clear();
+ for key in PROVIDER_SCRIPT_INHERITED_ENV {
+ if let Some(value) = std::env::var_os(key) {
+ command.env(key, value);
+ }
+ }
+ command.envs(request.env.iter().map(|(key, value)| (key, value)));
+ command
+ .current_dir(&request.working_dir)
+ .stdin(Stdio::null());
+
+ super::interrupt::forward_to_active_group();
+ let output = run_with_deadline(&mut command, "Provider script", deadline)
+ .map_err(|error| map_runner_error(error, request))?;
+ let stderr_start = output.stderr.len().saturating_sub(4096);
+
+ Ok(ProviderScriptOutput {
+ status: output
+ .status
+ .code()
+ .or_else(|| output.status.signal().map(|signal| 128 + signal)),
+ stdout: output.stdout,
+ stderr_tail: String::from_utf8_lossy(&output.stderr[stderr_start..]).into_owned(),
+ })
+}
+
+fn map_runner_error(mut error: AdapterError, request: &ProviderScriptRequest) -> AdapterError {
+ if error.code == ErrorCode::Timeout {
+ return AdapterError::timeout(TIMEOUT_MESSAGE).with_suggestion(TIMEOUT_SUGGESTION);
+ }
+ if error
+ .details
+ .as_ref()
+ .and_then(|details| details.get("kind"))
+ .and_then(serde_json::Value::as_str)
+ == Some("subprocess_output_limit")
+ {
+ return AdapterError::new(
+ ErrorCode::ActionFailed,
+ "The provider script printed more output than agent-desktop reads.",
+ )
+ .with_suggestion(format!(
+ "Check the log files in the working directory {}.",
+ request.working_dir.display()
+ ));
+ }
+
+ let detail = error.message.clone();
+ error.message = "The provider script could not be run.".to_owned();
+ error.suggestion = Some(format!(
+ "Check that the script at {} is readable and that {} is accessible.",
+ request.script.display(),
+ request.working_dir.display()
+ ));
+ if error.platform_detail.is_none() {
+ error.platform_detail = Some(detail);
+ }
+ error
+}
+
+#[cfg(all(test, unix))]
+#[path = "provider_script_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/system/process/provider_script_tests.rs b/crates/macos/src/system/process/provider_script_tests.rs
new file mode 100644
index 000000000..5ba762f47
--- /dev/null
+++ b/crates/macos/src/system/process/provider_script_tests.rs
@@ -0,0 +1,178 @@
+use super::run_provider_script;
+use agent_desktop_core::{ErrorCode, ProviderScriptRequest};
+use std::collections::HashSet;
+use std::ffi::OsString;
+use std::fs;
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+static TEMP_DIRECTORY_COUNTER: AtomicU64 = AtomicU64::new(0);
+
+struct TempDirectory(PathBuf);
+
+impl TempDirectory {
+ fn new() -> Self {
+ let timestamp = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let counter = TEMP_DIRECTORY_COUNTER.fetch_add(1, Ordering::Relaxed);
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-provider-script-{}-{timestamp}-{counter}",
+ std::process::id()
+ ));
+ fs::create_dir(&path).unwrap();
+ Self(path)
+ }
+
+ fn write_script(&self, name: &str, contents: &str) -> PathBuf {
+ let path = self.0.join(name);
+ fs::write(&path, contents).unwrap();
+ path
+ }
+}
+
+impl Drop for TempDirectory {
+ fn drop(&mut self) {
+ let _ = fs::remove_dir_all(&self.0);
+ }
+}
+
+struct EnvironmentGuard {
+ name: &'static str,
+ previous: Option<OsString>,
+}
+
+impl EnvironmentGuard {
+ fn set(name: &'static str, value: &str) -> Self {
+ let previous = std::env::var_os(name);
+ unsafe { std::env::set_var(name, value) };
+ Self { name, previous }
+ }
+}
+
+impl Drop for EnvironmentGuard {
+ fn drop(&mut self) {
+ if let Some(value) = self.previous.take() {
+ unsafe { std::env::set_var(self.name, value) };
+ } else {
+ unsafe { std::env::remove_var(self.name) };
+ }
+ }
+}
+
+struct ProcessCleanup(i32);
+
+impl Drop for ProcessCleanup {
+ fn drop(&mut self) {
+ unsafe { kill(self.0, 9) };
+ }
+}
+
+unsafe extern "C" {
+ fn kill(process: i32, signal: i32) -> i32;
+}
+
+fn process_exists(process: i32) -> bool {
+ unsafe { kill(process, 0) == 0 }
+}
+
+fn request(script: PathBuf, working_dir: PathBuf, timeout: Duration) -> ProviderScriptRequest {
+ ProviderScriptRequest {
+ script,
+ args: Vec::new(),
+ env: Vec::new(),
+ working_dir,
+ timeout,
+ }
+}
+
+#[test]
+fn script_timeout_kills_the_running_child() {
+ let directory = TempDirectory::new();
+ let pid_file = directory.0.join("pid");
+ let script = directory.write_script(
+ "timeout.sh",
+ "printf '%s\\n' \"$$\" > \"$1\"\nexec /bin/sleep 30\n",
+ );
+ let mut request = request(script, directory.0.clone(), Duration::from_secs(1));
+ request.args.push(pid_file.to_string_lossy().into_owned());
+
+ let error = run_provider_script(&request).expect_err("the script must time out");
+
+ assert_eq!(error.code, ErrorCode::Timeout);
+ let process = fs::read_to_string(pid_file)
+ .unwrap()
+ .trim()
+ .parse::<i32>()
+ .unwrap();
+ assert!(!process_exists(process));
+}
+
+#[test]
+fn script_detached_process_group_survives() {
+ let directory = TempDirectory::new();
+ let pid_file = directory.0.join("pid");
+ let script = directory.write_script(
+ "detached.sh",
+ "set -m\n/bin/sleep 30 >/dev/null 2>&1 &\nprintf '%s\\n' \"$!\" > \"$1\"\n",
+ );
+ let mut request = request(script, directory.0.clone(), Duration::from_secs(2));
+ request.args.push(pid_file.to_string_lossy().into_owned());
+
+ let started = Instant::now();
+ let output = run_provider_script(&request).unwrap();
+ let process = fs::read_to_string(pid_file)
+ .unwrap()
+ .trim()
+ .parse::<i32>()
+ .unwrap();
+ let _cleanup = ProcessCleanup(process);
+
+ assert_eq!(output.status, Some(0));
+ assert!(started.elapsed() < Duration::from_secs(2));
+ assert!(process_exists(process));
+}
+
+#[test]
+fn script_environment_is_limited_to_allowed_and_requested_values() {
+ const SENTINEL: &str = "AGENT_DESKTOP_PROVIDER_SCRIPT_SENTINEL";
+ const REQUEST_VALUE: &str = "AGENT_DESKTOP_PROVIDER_SCRIPT_REQUEST";
+ let _environment = EnvironmentGuard::set(SENTINEL, "caller-only");
+ let caller_environment = std::env::vars_os()
+ .map(|(name, value)| format!("{}={}", name.to_string_lossy(), value.to_string_lossy()))
+ .collect::<HashSet<_>>();
+ let directory = TempDirectory::new();
+ let script = directory.write_script("environment.sh", "env\n");
+ let mut request = request(script, directory.0.clone(), Duration::from_secs(2));
+ request
+ .env
+ .push((REQUEST_VALUE.to_owned(), "request-only".to_owned()));
+
+ let output = run_provider_script(&request).unwrap();
+ let child_environment = String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .map(str::to_owned)
+ .collect::<HashSet<_>>();
+ let allowed_names = HashSet::from(["PATH", "HOME", "TMPDIR", REQUEST_VALUE]);
+ let shell_names = HashSet::from(["PWD", "SHLVL", "_"]);
+ let leaked_caller_value = caller_environment.iter().find(|entry| {
+ let name = entry.split_once('=').map_or("", |(name, _)| name);
+ !allowed_names.contains(name)
+ && !shell_names.contains(name)
+ && child_environment.contains(*entry)
+ });
+
+ assert_eq!(output.status, Some(0));
+ assert!(child_environment.contains(&format!("{REQUEST_VALUE}=request-only")));
+ assert!(
+ leaked_caller_value.is_none(),
+ "provider script inherited caller-only environment value {leaked_caller_value:?}"
+ );
+ for name in ["PATH", "HOME", "TMPDIR"] {
+ if let Some(value) = std::env::var_os(name) {
+ assert!(child_environment.contains(&format!("{name}={}", value.to_string_lossy())));
+ }
+ }
+}
diff --git a/docs/json-output.md b/docs/json-output.md
index 03fadda8c..6c070e75e 100644
--- a/docs/json-output.md
+++ b/docs/json-output.md
@@ -58,6 +58,18 @@ recovery strategy from `recovery.strategy` only when `disposition.retry` is
`safe`; command strings from older envelopes must not be executed blindly.
The removed `retry_command` field has no compatibility alias.
+## Sandbox results
+
+`sandbox install` returns `data: {"providers": [...]}` and `sandbox list` returns `data: {"sandboxes": [...]}`. An entry has `name`, `state`, and `message`, with `next` when a further action is available; a sandbox entry, and the `data` of a single sandbox command, also carry `provider`. Provider-specific fields may appear beside these. `sandbox install <provider>` returns that entry as `data`. A build that includes no providers returns an empty `providers` array, and a command that names a provider fails with `INVALID_ARGS`. States are `unavailable`, `missing`, `ready`, `working`, `needs_setup`, `running`, `stopped`, and `broken`.
+
+A sandbox whose record is missing, malformed or unreadable, or names a provider this build does not include, is listed as `broken`, and every command on it returns `INVALID_ARGS`. agent-desktop has no provider to ask, so `next` and the error's `suggestion` name the sandbox directory to delete once nothing in it is still running. When the provider's own status check fails or times out, the entry is also `broken` and `next` carries that error's suggestion.
+
+A `sandbox create` that times out, or whose provider ends without a readable reply, keeps its record, because the provider may have made something. The sandbox stays in `sandbox list`; run `sandbox status <name>` to see what exists and `sandbox rm <name>` before creating that name again. A create the provider refuses leaves no record unless the provider left files in the sandbox directory. `create` never takes over a directory that already holds files.
+
+`create`, `start`, `stop` and `rm` on one sandbox run one at a time. A second one fails at once with `ACTION_FAILED` and `not_delivered`.
+
+`sandbox exec` passes the guest command's stdout and exit status through unchanged instead of adding an envelope; the guest's stderr is not passed through and the guest receives no stdin, so a guest command that reads `--stdin` gets empty input. A provider failure returns a host error envelope instead. agent-desktop reads at most 8 MiB from each of the guest's output streams; a command that prints more fails with `ACTION_FAILED`, so write large output to a file in the guest. A guest command that runs longer than 300 seconds fails with `TIMEOUT`. The host's session and agent id never reach the guest: the flags are refused before `sandbox exec`, and `AGENT_DESKTOP_SESSION` and `AGENT_DESKTOP_AGENT_ID` are not passed on. Give the guest command its own `--session` after `--`.
+
## Disposition values
Every error carries `disposition`, and commands that act on a target may also
@@ -196,6 +208,7 @@ After the core resolver chooses the element, the platform adapter lands it, and
| `STALE_REF` | Ref could not be re-identified in the live UI |
| `AMBIGUOUS_TARGET` | Ref recovery matched multiple plausible targets |
| `SNAPSHOT_NOT_FOUND` | Snapshot ID is missing or expired |
+| `SANDBOX_NOT_FOUND` | No sandbox has that name; run `agent-desktop sandbox list` to see the sandboxes that exist |
| `POLICY_DENIED` | Physical/headed path blocked by policy |
| `ACTION_FAILED` | Action rejected, or its observed result contradicted the request |
| `ACTION_NOT_SUPPORTED` | The target does not expose the requested action |
diff --git a/scripts/check_architecture.py b/scripts/check_architecture.py
index 3b9633a15..3b08676b5 100644
--- a/scripts/check_architecture.py
+++ b/scripts/check_architecture.py
@@ -30,8 +30,8 @@ PLATFORM_FILES = {"lib.rs", "adapter.rs"}
PLATFORM_OPTIONAL = {"adapter_tests.rs", "bin"}
CORE_TOP_FILES = {"lib.rs"}
CORE_DOMAINS = {"actionability", "actions", "adapter", "commands", "context", "cursor_overlay", "input",
- "locator", "notifications", "ref_action", "refs", "response", "session", "snapshot",
- "storage", "system", "trace", "tree", "wait"}
+ "locator", "notifications", "ref_action", "refs", "response", "sandbox", "session",
+ "snapshot", "storage", "system", "trace", "tree", "wait"}
BINARY_TOP_FILES = {"main.rs", "Cargo.toml"}
BINARY_DIRS = {"batch", "cli", "cli_args", "command_policy", "diagnostic", "dispatch", "mcp",
"tests", "visual_debug"}
@@ -101,6 +101,11 @@ TEST_MODULE = re.compile(r"#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]\s*(?:pub(?:\s*\([^
STR = re.compile(r"__S(\d+)__")
+PROVIDERS_DIR = "providers"
+PROVIDERS_SUFFIXES = {".sh", ".swift"}
+PROVIDERS_LISTENER = re.compile(
+ r"(?<![A-Za-z0-9_])(?:socket\s*\(|listen\s*\(|bind\s*\(|nc\s|socat|NWListener|VZVirtioSocket)")
+
class Source:
"""A Rust file as code (comments blanked, literals as __S<n>__) plus decoded literals."""
@@ -222,6 +227,20 @@ def rs_files(root):
yield os.path.join(base, f)
+def provider_files(root):
+ """Provider scripts under the top-level providers/ folder; none when it is absent."""
+ top = os.path.join(root, PROVIDERS_DIR)
+ if not os.path.isdir(top):
+ return []
+ found = []
+ for base, dirs, files in os.walk(top):
+ dirs[:] = sorted(d for d in dirs if d not in ("target", ".git", "node_modules"))
+ for f in sorted(files):
+ if os.path.splitext(f)[1] in PROVIDERS_SUFFIXES:
+ found.append(os.path.join(base, f))
+ return found
+
+
def has_files(path):
"""Directories that hold no file are leftovers git does not track."""
return any(files for _, _, files in os.walk(path))
@@ -392,6 +411,14 @@ def check(repo):
for stale in sorted(LISTENER_ALLOWLIST - serving):
err("G12", f"LISTENER_ALLOWLIST lists {stale}, which no longer opens a listener")
+ for path in provider_files(repo):
+ rel = os.path.relpath(path, repo).replace(os.sep, "/")
+ with open(path, encoding="utf-8", errors="replace") as fh:
+ hit = PROVIDERS_LISTENER.search(fh.read())
+ if hit:
+ err("G12", f"{rel} opens a listener ({hit.group(0).strip()}); a provider drives a desktop and "
+ "serves nothing, so a socket or listener here needs a review decision")
+
for p in PLATFORMS:
if not os.path.exists(os.path.join(repo, "crates", p, "Cargo.toml")):
continue
@@ -585,6 +612,8 @@ PLANTS = {
("crates/core/src/tree/mod.rs", "pub mod node;\n#[path = \"@ABS@/crates/core/src/input/mod.rs\"]\nmod misplaced;\n")],
}
PLANTS["G12"] = [
+ ("providers/macos/provider.sh", "#!/bin/sh\nsocat TCP-LISTEN:9000,fork EXEC:sh\n"),
+ ("providers/macos/vmhost.swift", "import Network\nlet l = try NWListener(using: .tcp)\n"),
("crates/macos/src/system/host.rs", "fn f() { let _ = std::os::unix::net::UnixListener::bind(\"/tmp/h.sock\"); }\n"),
("crates/core/src/system/host.rs", "fn f() { let _ = std::net::TcpListener::bind((\"127.0.0.1\", 0)); }\n"),
("crates/windows/src/system/host.rs", "fn f() { let _ = CreateNamedPipeW; }\n"),
diff --git a/skills/agent-desktop-ffi/references/error-handling.md b/skills/agent-desktop-ffi/references/error-handling.md
index 33c326b15..93e413653 100644
--- a/skills/agent-desktop-ffi/references/error-handling.md
+++ b/skills/agent-desktop-ffi/references/error-handling.md
@@ -100,6 +100,7 @@ release may add codes.
| `AD_RESULT_ERR_POLICY_DENIED` | -14 | Current action policy blocks this fallback |
| `AD_RESULT_ERR_AMBIGUOUS_TARGET` | -15 | Strict re-identification found multiple candidates; re-snapshot |
| `AD_RESULT_ERR_APP_UNRESPONSIVE` | -16 | Read-only liveness probe failed after an uncertain mutation |
+| `AD_RESULT_ERR_SANDBOX_NOT_FOUND` | -17 | No sandbox has that name; run `agent-desktop sandbox list` |
## Ref token validation
diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.md
index 010be62b3..99c0b7919 100644
--- a/skills/agent-desktop/references/commands-system.md
+++ b/skills/agent-desktop/references/commands-system.md
@@ -216,6 +216,14 @@ Multi-agent cursors (macOS and Windows): start with `session start --cursor --mu
- `--agent-id <id> cursor-overlay enable` saves a style for that agent. Do not add `--multi-agent` to it.
- `cursor-overlay disable` and `session end` stop every cursor in the session, even when you pass an agent id.
+## Sandboxes
+
+`agent-desktop sandbox install` lists the providers this build includes, and `agent-desktop sandbox list` lists the sandboxes with `name`, `state`, `message`, and `next`. A single sandbox command also returns its `provider`. A build can include no providers: `sandbox install` then returns an empty list, and a command that names a provider fails with `INVALID_ARGS`.
+
+A sandbox whose record is missing or malformed, or names a provider this build does not include, appears in `sandbox list` with `state: "broken"`, and every command on it returns `INVALID_ARGS`. `next` and `suggestion` name the directory to delete once nothing in it is still running. A sandbox whose status check failed is also `broken`; follow its `next`, which is not always a removal.
+
+`sandbox start <name> --window` shows the sandbox's desktop in a window on the host instead of running it headless, and `--set key=value` passes the provider an option for that start. `create`, `start`, `stop` and `rm` on one sandbox run one at a time; a second one fails with `ACTION_FAILED`. `sandbox exec` ends a guest command after 300 seconds with `TIMEOUT`. The host's session and agent id, from flags or from `AGENT_DESKTOP_SESSION` and `AGENT_DESKTOP_AGENT_ID`, do not apply in the guest; pass `--session` after `--`.
+
## status, permissions, version
- `status` returns adapter health, platform, the permission report, `supported_surfaces`, the latest snapshot (`snapshot_id`, `ref_count`), `session_id`, `tracing`, `state_root`.
diff --git a/src/batch/mod.rs b/src/batch/mod.rs
index 2baf98430..fa84ec03f 100644
--- a/src/batch/mod.rs
+++ b/src/batch/mod.rs
@@ -29,6 +29,10 @@ mod baseline_tests;
#[path = "open_system_surface_parity_tests.rs"]
mod open_system_surface_parity_tests;
+#[cfg(test)]
+#[path = "sandbox_tests.rs"]
+mod sandbox_tests;
+
pub(crate) fn execute(
args: BatchArgs,
adapter: &dyn PlatformAdapter,
@@ -105,6 +109,10 @@ pub(crate) fn parse_command(item: BatchCommand) -> Result<Commands, AppError> {
"Enable or disable it once for the selected session before running the batch.",
)),
"trace" => parse_trace(item.args).map(Commands::Trace),
+ "sandbox" => Err(AppError::invalid_input_with_suggestion(
+ "Run sandbox commands on their own, not inside batch.",
+ "Run 'agent-desktop sandbox' as its own call.",
+ )),
"batch" => Err(AppError::invalid_input_with_suggestion(
"Batch commands cannot be nested",
"Flatten nested batches into one top-level batch array",
diff --git a/src/batch/sandbox_tests.rs b/src/batch/sandbox_tests.rs
new file mode 100644
index 000000000..8d0018870
--- /dev/null
+++ b/src/batch/sandbox_tests.rs
@@ -0,0 +1,18 @@
+use agent_desktop_core::commands::batch::BatchCommand;
+
+use super::parse_command;
+
+fn item(command: &str) -> BatchCommand {
+ BatchCommand {
+ command: command.into(),
+ session: None,
+ args: serde_json::Value::Null,
+ }
+}
+
+#[test]
+fn sandbox_is_refused_inside_a_batch() {
+ let error = parse_command(item("sandbox")).expect_err("batch must refuse the command");
+
+ assert_eq!(error.code(), "INVALID_ARGS");
+}
diff --git a/src/cli/contract_command_surface_tests.rs b/src/cli/contract_command_surface_tests.rs
index 6b8d71ecd..4d12a93c2 100644
--- a/src/cli/contract_command_surface_tests.rs
+++ b/src/cli/contract_command_surface_tests.rs
@@ -20,6 +20,9 @@ const NON_COMMAND_MODULES: &[&str] = &[
"post_action_observation",
"query",
"find_live_test_support",
+ "sandbox_action",
+ "sandbox_install",
+ "sandbox_list",
"selector_observation",
"surface_scope",
"type_text_interval",
@@ -76,7 +79,7 @@ const SHARED_REF_ACTION_TESTS: &[&str] = &[
"uncheck",
];
-const BINARY_CONTRACT_TESTS: &[&str] = &["batch", "permissions", "version"];
+const BINARY_CONTRACT_TESTS: &[&str] = &["batch", "permissions", "sandbox", "version"];
const ADAPTER_PASSTHROUGH_COMMANDS: &[&str] = &[
"clipboard-clear",
@@ -158,7 +161,7 @@ fn macos_capability_count_includes_restored_notifications() {
let commands = cli_command_names();
assert_eq!(
commands.len(),
- 60,
+ 61,
"the published CLI command count changed; update capability documentation"
);
}
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 2f9a8fdc5..23152a187 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -20,6 +20,7 @@ use crate::cli_args::{
DismissAllNotificationsCliArgs, DismissNotificationCliArgs, ListNotificationsCliArgs,
NotificationActionCliArgs,
},
+ sandbox::SandboxArgs,
session::SessionArgs,
skills::SkillsArgs,
system::{
@@ -166,6 +167,10 @@ pub(crate) enum Commands {
CursorOverlay(CursorOverlayArgs),
#[command(about = "Read merged session trace timelines")]
Trace(TraceArgs),
+ #[command(
+ about = "Install providers and create, run, and remove local sandboxes (install, create, start, stop, status, list, rm, exec)"
+ )]
+ Sandbox(SandboxArgs),
}
#[derive(Clone, Copy)]
@@ -248,6 +253,7 @@ impl Commands {
Self::Session(_) => CommandMetadata::new("session", false),
Self::CursorOverlay(_) => CommandMetadata::new("cursor-overlay", false),
Self::Trace(_) => CommandMetadata::new("trace", false),
+ Self::Sandbox(_) => CommandMetadata::new("sandbox", false),
}
}
@@ -309,6 +315,11 @@ impl Commands {
!matches!(&args.action, crate::cli_args::session::SessionAction::List)
}
Self::CursorOverlay(_) => true,
+ Self::Sandbox(args) => !matches!(
+ &args.action,
+ crate::cli_args::sandbox::SandboxActionCli::List
+ | crate::cli_args::sandbox::SandboxActionCli::Status(_)
+ ),
Self::Trace(args) => {
matches!(&args.action, crate::cli_args::trace::TraceAction::Export(_))
}
diff --git a/src/cli_args/mod.rs b/src/cli_args/mod.rs
index 4040af241..6438f51d3 100644
--- a/src/cli_args/mod.rs
+++ b/src/cli_args/mod.rs
@@ -14,6 +14,7 @@ pub(crate) mod drag_target;
pub(crate) mod interaction;
pub(crate) mod mouse_wheel;
pub(crate) mod notifications;
+pub(crate) mod sandbox;
pub(crate) mod session;
pub(crate) mod skills;
mod snapshot;
diff --git a/src/cli_args/sandbox.rs b/src/cli_args/sandbox.rs
new file mode 100644
index 000000000..dda25eea6
--- /dev/null
+++ b/src/cli_args/sandbox.rs
@@ -0,0 +1,94 @@
+use clap::{Args, Subcommand};
+
+#[derive(Args, Debug)]
+pub(crate) struct SandboxArgs {
+ #[command(subcommand)]
+ pub action: SandboxActionCli,
+}
+
+#[derive(Subcommand, Debug)]
+pub(crate) enum SandboxActionCli {
+ #[command(about = "Report or install what a sandbox provider needs on this host")]
+ Install(SandboxInstallArgs),
+ #[command(about = "Create a sandbox, reusing whatever the provider already installed")]
+ Create(SandboxCreateArgs),
+ #[command(about = "Start a stopped sandbox")]
+ Start(SandboxStartArgs),
+ #[command(about = "Stop a running sandbox")]
+ Stop(SandboxNameArgs),
+ #[command(about = "Report one sandbox's state and its next command")]
+ Status(SandboxNameArgs),
+ #[command(about = "List every sandbox with its provider and state")]
+ List,
+ #[command(about = "Remove a stopped sandbox")]
+ Rm(SandboxNameArgs),
+ #[command(about = "Run agent-desktop inside a sandbox and pass its output through")]
+ Exec(SandboxExecArgs),
+}
+
+#[derive(Args, Debug)]
+pub(crate) struct SandboxInstallArgs {
+ #[arg(
+ value_name = "PROVIDER",
+ help = "Provider to install; omit it to report every provider's state"
+ )]
+ pub provider: Option<String>,
+}
+
+#[derive(Args, Debug)]
+pub(crate) struct SandboxNameArgs {
+ #[arg(help = "Sandbox name: lowercase letters, digits and hyphens")]
+ pub name: String,
+}
+
+#[derive(Args, Debug)]
+pub(crate) struct SandboxCreateArgs {
+ #[arg(help = "Sandbox name: lowercase letters, digits and hyphens")]
+ pub name: String,
+ #[arg(
+ long,
+ value_name = "PROVIDER",
+ help = "Provider that owns the sandbox; `sandbox install` lists the providers in this build"
+ )]
+ pub provider: String,
+ #[arg(
+ long = "set",
+ value_name = "KEY=VALUE",
+ help = "Provider option; repeat for more than one"
+ )]
+ pub set: Vec<String>,
+}
+
+#[derive(Args, Debug)]
+pub(crate) struct SandboxStartArgs {
+ #[arg(help = "Sandbox name: lowercase letters, digits and hyphens")]
+ pub name: String,
+ #[arg(
+ long,
+ help = "Show the sandbox's desktop in a window on this host instead of running it headless"
+ )]
+ pub window: bool,
+ #[arg(
+ long = "set",
+ value_name = "KEY=VALUE",
+ help = "Provider option for this start, such as title=<text>; repeat for more than one"
+ )]
+ pub set: Vec<String>,
+}
+
+#[derive(Args, Debug)]
+pub(crate) struct SandboxExecArgs {
+ #[arg(help = "Sandbox name: lowercase letters, digits and hyphens")]
+ pub name: String,
+ #[arg(
+ last = true,
+ required = true,
+ value_name = "ARGS",
+ help = "Arguments for agent-desktop inside the sandbox, after --"
+ )]
+ pub args: Vec<String>,
+}
+
+#[cfg(test)]
+#[path = "sandbox_tests.rs"]
+mod tests;
diff --git a/src/cli_args/sandbox_tests.rs b/src/cli_args/sandbox_tests.rs
new file mode 100644
index 000000000..846db036e
--- /dev/null
+++ b/src/cli_args/sandbox_tests.rs
@@ -0,0 +1,60 @@
+use clap::Parser;
+
+use super::SandboxActionCli;
+use crate::cli::{Cli, Commands};
+
+fn exec_action(argv: &[&str]) -> super::SandboxExecArgs {
+ let mut full = vec!["agent-desktop", "sandbox"];
+ full.extend_from_slice(argv);
+ let cli = Cli::try_parse_from(full).expect("the sandbox command parses");
+ let Commands::Sandbox(args) = cli.command.expect("the sandbox command is present") else {
+ panic!("expected the sandbox command");
+ };
+ let SandboxActionCli::Exec(exec) = args.action else {
+ panic!("expected the exec action");
+ };
+ exec
+}
+
+#[test]
+fn sandbox_exec_hands_every_argument_after_the_separator_to_the_guest() {
+ let exec = exec_action(&[
+ "exec",
+ "dev",
+ "--",
+ "snapshot",
+ "--app",
+ "Finder",
+ "--verbose",
+ ]);
+
+ assert_eq!(exec.name, "dev");
+ assert_eq!(exec.args, ["snapshot", "--app", "Finder", "--verbose"]);
+}
+
+#[test]
+fn sandbox_install_takes_an_optional_provider_and_no_settings() {
+ let cli = Cli::try_parse_from(["agent-desktop", "sandbox", "install", "macos"])
+ .expect("sandbox install parses");
+ assert!(matches!(
+ cli.command,
+ Some(Commands::Sandbox(super::SandboxArgs {
+ action: SandboxActionCli::Install(ref args),
+ })) if args.provider.as_deref() == Some("macos")
+ ));
+
+ let error = Cli::try_parse_from([
+ "agent-desktop",
+ "sandbox",
+ "install",
+ "macos",
+ "--set",
+ "binary=/tmp/agent-desktop",
+ ])
+ .expect_err("install takes no provider settings");
+ assert_eq!(error.exit_code(), 2);
+
+ let error = Cli::try_parse_from(["agent-desktop", "install"])
+ .expect_err("install is not a top-level command");
+ assert_eq!(error.exit_code(), 2);
+}
diff --git a/src/command_policy/mod.rs b/src/command_policy/mod.rs
index 03d8a995a..3044dffc1 100644
--- a/src/command_policy/mod.rs
+++ b/src/command_policy/mod.rs
@@ -19,6 +19,7 @@ pub(crate) fn policy_for(cmd: &Commands) -> PermissionNeed {
| Commands::Skills(_)
| Commands::Session(_)
| Commands::CursorOverlay(_)
+ | Commands::Sandbox(_)
| Commands::Trace(_) => None,
Commands::Status | Commands::Permissions(_) => None,
Commands::ListWindows(_) | Commands::ListDisplays | Commands::ListApps(_) => None,
@@ -248,6 +249,7 @@ fn validate_args(cmd: &Commands) -> Result<(), AppError> {
| Commands::Skills(_)
| Commands::Session(_)
| Commands::CursorOverlay(_)
+ | Commands::Sandbox(_)
| Commands::Trace(_) => {}
}
Ok(())
diff --git a/src/dispatch/mod.rs b/src/dispatch/mod.rs
index a81a55443..c3b61c782 100644
--- a/src/dispatch/mod.rs
+++ b/src/dispatch/mod.rs
@@ -8,6 +8,7 @@ mod notifications;
mod observation;
mod overlay_skipped;
mod parse;
+pub(crate) mod sandbox;
mod session;
mod system;
mod trace;
@@ -134,6 +135,7 @@ fn dispatch_command(
Commands::Session(args) => session::dispatch(args, adapter, context),
Commands::CursorOverlay(args) => cursor_overlay::dispatch(args, adapter, context),
Commands::Trace(args) => trace::dispatch(args, context),
+ Commands::Sandbox(args) => sandbox::dispatch(args, adapter),
};
if let Some(session_id) = overlay_session {
let _ = adapter.update_cursor_overlay(&CursorOverlayControl::show(session_id));
diff --git a/src/dispatch/sandbox.rs b/src/dispatch/sandbox.rs
new file mode 100644
index 000000000..f78666c78
--- /dev/null
+++ b/src/dispatch/sandbox.rs
@@ -0,0 +1,119 @@
+use agent_desktop_core::{
+ AppError, ExecPassthrough, PlatformAdapter, commands::sandbox,
+ commands::sandbox_action::SandboxAction,
+};
+use serde_json::Value;
+use std::io::Write;
+use std::process::ExitCode;
+
+use crate::cli_args::sandbox::{SandboxActionCli, SandboxArgs, SandboxExecArgs};
+
+pub(crate) fn dispatch(
+ args: SandboxArgs,
+ adapter: &dyn PlatformAdapter,
+) -> Result<Value, AppError> {
+ sandbox::execute(to_core(args.action), adapter)
+}
+
+fn reject_outer_options(cli: &crate::Cli) -> Result<(), AppError> {
+ let any_set = [
+ cli.visual_debug.verbose,
+ cli.visual_debug.debug,
+ cli.visual_debug.screenshot.is_some(),
+ cli.identity.session.is_some(),
+ cli.identity.agent_id.is_some(),
+ cli.trace.is_some(),
+ cli.trace_strict,
+ cli.interaction.headed,
+ cli.post_action_wait.wait_for.is_some(),
+ cli.post_action_wait.wait_for_gone.is_some(),
+ cli.post_action_wait.wait_timeout.is_some(),
+ ]
+ .contains(&true);
+ if !any_set {
+ return Ok(());
+ }
+ Err(AppError::invalid_input_with_suggestion(
+ "Options before `sandbox exec` are not applied inside the sandbox.",
+ "Put agent-desktop options after `--`, for example `agent-desktop sandbox exec dev -- snapshot --app Finder --session <id>`.",
+ ))
+}
+
+pub(crate) fn run_exec(
+ cli: &crate::Cli,
+ args: &SandboxExecArgs,
+ cmd_name: &str,
+ adapter: &dyn PlatformAdapter,
+) -> ExitCode {
+ match exec_passthrough(cli, args, adapter) {
+ Ok(passthrough) => match write_stdout(&passthrough.stdout) {
+ Ok(()) => exit_code(passthrough.status),
+ Err(error) => crate::report_output_failure(error),
+ },
+ Err(error) => crate::finish(cmd_name, Err(error)),
+ }
+}
+
+fn exec_passthrough(
+ cli: &crate::Cli,
+ args: &SandboxExecArgs,
+ adapter: &dyn PlatformAdapter,
+) -> Result<ExecPassthrough, AppError> {
+ reject_outer_options(cli)
+ .and_then(|()| {
+ agent_desktop_core::validate_state_root_env().map_err(crate::pre_dispatch_error)
+ })
+ .and_then(|()| sandbox::execute_exec(args.name.clone(), args.args.clone(), adapter))
+ .map_err(|error| {
+ let before_the_provider_ran = !matches!(error, AppError::Adapter(_));
+ super::disposition::settle_unknown_delivery(error, before_the_provider_ran)
+ })
+}
+
+fn write_stdout(bytes: &[u8]) -> std::io::Result<()> {
+ let stdout = std::io::stdout();
+ let mut writer = std::io::BufWriter::new(stdout.lock());
+ writer.write_all(bytes)?;
+ writer.flush()
+}
+
+fn exit_code(status: i32) -> ExitCode {
+ match u8::try_from(status) {
+ Ok(code) => ExitCode::from(code),
+ Err(_) => ExitCode::FAILURE,
+ }
+}
+
+fn to_core(action: SandboxActionCli) -> SandboxAction {
+ match action {
+ SandboxActionCli::Install(args) => SandboxAction::Install {
+ provider: args.provider,
+ },
+ SandboxActionCli::Create(create) => SandboxAction::Create {
+ name: create.name,
+ provider: create.provider,
+ set: create.set,
+ },
+ SandboxActionCli::Start(args) => SandboxAction::Start {
+ name: args.name,
+ set: args
+ .window
+ .then(|| "window=on".to_string())
+ .into_iter()
+ .chain(args.set)
+ .collect(),
+ },
+ SandboxActionCli::Stop(args) => SandboxAction::Stop { name: args.name },
+ SandboxActionCli::Status(args) => SandboxAction::Status { name: args.name },
+ SandboxActionCli::List => SandboxAction::List,
+ SandboxActionCli::Rm(args) => SandboxAction::Rm { name: args.name },
+ SandboxActionCli::Exec(exec) => SandboxAction::Exec {
+ name: exec.name,
+ args: exec.args,
+ },
+ }
+}
+
+#[cfg(test)]
+#[path = "sandbox_tests.rs"]
+mod tests;
diff --git a/src/dispatch/sandbox_tests.rs b/src/dispatch/sandbox_tests.rs
new file mode 100644
index 000000000..f008efd11
--- /dev/null
+++ b/src/dispatch/sandbox_tests.rs
@@ -0,0 +1,87 @@
+use agent_desktop_core::{AppError, ErrorCode};
+use clap::Parser;
+
+use super::reject_outer_options;
+
+#[test]
+fn outer_global_options_are_rejected_before_sandbox_exec() {
+ let plain =
+ crate::Cli::try_parse_from(["agent-desktop", "sandbox", "exec", "dev", "--", "version"])
+ .unwrap();
+ assert!(reject_outer_options(&plain).is_ok());
+
+ let outer = crate::Cli::try_parse_from([
+ "agent-desktop",
+ "--session",
+ "abc",
+ "sandbox",
+ "exec",
+ "dev",
+ "--",
+ "version",
+ ])
+ .unwrap();
+ let AppError::Adapter(error) = reject_outer_options(&outer).unwrap_err() else {
+ panic!("outer options must be an adapter error");
+ };
+
+ assert_eq!(error.code, ErrorCode::InvalidArgs);
+ assert!(
+ error.suggestion.is_some(),
+ "the refusal must say where the options go"
+ );
+}
+
+struct IdleAdapter;
+impl agent_desktop_core::ObservationOps for IdleAdapter {}
+impl agent_desktop_core::ActionOps for IdleAdapter {}
+impl agent_desktop_core::InputOps for IdleAdapter {}
+impl agent_desktop_core::SystemOps for IdleAdapter {}
+
+#[test]
+fn a_sandbox_exec_refusal_reports_that_nothing_was_delivered() {
+ let cli = crate::Cli::try_parse_from(["agent-desktop", "sandbox", "exec", "BAD", "--", "ls"])
+ .unwrap();
+ let Some(crate::cli::Commands::Sandbox(args)) = &cli.command else {
+ panic!("sandbox command");
+ };
+ let crate::cli_args::sandbox::SandboxActionCli::Exec(exec) = &args.action else {
+ panic!("exec action");
+ };
+
+ let AppError::Adapter(error) = super::exec_passthrough(&cli, exec, &IdleAdapter).unwrap_err()
+ else {
+ panic!("an invalid name must be an adapter error");
+ };
+
+ assert_eq!(error.code, ErrorCode::InvalidArgs);
+ assert_eq!(
+ error.disposition,
+ agent_desktop_core::DeliverySemantics::not_delivered()
+ );
+}
+
+#[test]
+fn sandbox_start_window_reaches_the_provider_as_a_setting_beside_the_others() {
+ let cli = crate::Cli::try_parse_from([
+ "agent-desktop",
+ "sandbox",
+ "start",
+ "dev-1",
+ "--window",
+ "--set",
+ "title=Review build",
+ ])
+ .unwrap();
+ let Some(crate::cli::Commands::Sandbox(args)) = cli.command else {
+ panic!("sandbox command");
+ };
+
+ let agent_desktop_core::commands::sandbox_action::SandboxAction::Start { set, .. } =
+ super::to_core(args.action)
+ else {
+ panic!("start action");
+ };
+
+ assert_eq!(set, ["window=on", "title=Review build"]);
+}
diff --git a/src/main.rs b/src/main.rs
index 112b30462..0a4ca6d48 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -25,6 +25,7 @@ use agent_desktop_core::{
};
use clap::{CommandFactory, FromArgMatches};
use cli::{Cli, Commands};
+use cli_args::sandbox::SandboxActionCli;
use cli_args::skills::SkillsAction;
use std::io::{BufWriter, Write};
use std::process::ExitCode;
@@ -105,6 +106,11 @@ fn run() -> ExitCode {
};
let cmd_name = cmd.name();
+ if let Commands::Sandbox(args) = &cmd
+ && let SandboxActionCli::Exec(exec) = &args.action
+ {
+ return dispatch::sandbox::run_exec(&cli, exec, cmd_name, &build_adapter());
+ }
let stdin = cli_args::stdin::input(&mut cmd).is_some();
if let Err(error) = cli_args::stdin::resolve_stdin_text(&mut cmd, std::io::stdin().lock()) {
return finish(cmd_name, Err(error));
diff --git a/src/mcp/call.rs b/src/mcp/call.rs
index fd5818800..9bc38a2de 100644
--- a/src/mcp/call.rs
+++ b/src/mcp/call.rs
@@ -2,14 +2,15 @@
use serde_json::{Map, Value, json};
use std::io::Read;
+use std::path::Path;
use std::process::{Command, Stdio};
use super::calls::Calls;
-use super::catalog::Tool;
+use super::catalog::{Output, Tool};
const CANCELLED: &str = "Cancelled";
-/// Runs `tool` with `arguments` for request `id`, prefixed by the server's own global flags, and returns a
+/// Runs `tool` with `arguments` for request `id`, carrying the server's own global flags, and returns a
/// `CallToolResult`. A cancelled call returns early; the caller sends no response for it.
pub(crate) fn call(
tool: &Tool,
@@ -26,13 +27,7 @@ pub(crate) fn call(
Ok(exe) => exe,
Err(error) => return error_result(&format!("Cannot locate agent-desktop: {error}")),
};
- let mut command = Command::new(exe);
- command
- .args(globals)
- .args(&argv)
- .stdin(Stdio::null())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped());
+ let mut command = child_command(&exe, tool, argv, globals);
let (stdout, stderr) = match calls.start(id, &mut command) {
None => return error_result(CANCELLED),
Some(Err(error)) => return error_result(&format!("Cannot run agent-desktop: {error}")),
@@ -45,19 +40,48 @@ pub(crate) fn call(
let Some(mut child) = calls.take(id) else {
return error_result(CANCELLED);
};
- let status = child
- .wait()
- .map_or_else(|error| error.to_string(), |status| status.to_string());
- match serde_json::from_slice::<Value>(&stdout) {
- Ok(envelope) => envelope_result(envelope),
- Err(_) => error_result(&format!(
- "agent-desktop {} exited with {status} and no JSON envelope: {}",
- tool.path.join(" "),
- String::from_utf8_lossy(&stderr).trim()
- )),
+ let status = child.wait();
+ let succeeded = status.as_ref().is_ok_and(|status| status.success());
+ let status = status.map_or_else(|error| error.to_string(), |status| status.to_string());
+ tool_result(tool, &stdout, &stderr, &status, succeeded)
+}
+
+/// Maps a child's output to a result by the kind of output its tool writes, never by what the bytes look like.
+/// A passthrough tool hands back its child's own stdout, empty output included, with its exit status.
+fn tool_result(tool: &Tool, stdout: &[u8], stderr: &[u8], status: &str, succeeded: bool) -> Value {
+ match tool.output {
+ Output::Passthrough => json!({
+ "content": [{ "type": "text", "text": String::from_utf8_lossy(stdout) }],
+ "isError": !succeeded,
+ }),
+ Output::Envelope => match serde_json::from_slice::<Value>(stdout) {
+ Ok(envelope) => envelope_result(envelope),
+ Err(_) => error_result(&format!(
+ "agent-desktop {} exited with {status} and no JSON envelope: {}",
+ tool.path.join(" "),
+ String::from_utf8_lossy(stderr).trim()
+ )),
+ },
}
}
+/// Builds the child command that runs `tool`. Server globals precede an ordinary tool. `sandbox exec` gets
+/// none: they describe this host, and the guest command carries its own flags after `--`.
+fn child_command(exe: &Path, tool: &Tool, argv: Vec<String>, globals: &[String]) -> Command {
+ let globals = match tool.path == ["sandbox", "exec"] {
+ true => &[],
+ false => globals,
+ };
+ let mut command = Command::new(exe);
+ command
+ .args(globals)
+ .args(argv)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ command
+}
+
fn read_all(pipe: Option<impl Read>) -> Vec<u8> {
let mut bytes = Vec::new();
if let Some(mut pipe) = pipe {
@@ -94,3 +118,7 @@ fn take_inline_image(envelope: &mut Value) -> Option<Value> {
fn error_result(message: &str) -> Value {
json!({ "content": [{ "type": "text", "text": message }], "isError": true })
}
+
+#[cfg(test)]
+#[path = "call_tests.rs"]
+mod tests;
diff --git a/src/mcp/call_tests.rs b/src/mcp/call_tests.rs
new file mode 100644
index 000000000..90d57d1c5
--- /dev/null
+++ b/src/mcp/call_tests.rs
@@ -0,0 +1,114 @@
+use super::*;
+use serde_json::json;
+use std::path::Path;
+
+fn tool_at(path: &[&str]) -> Tool {
+ super::super::catalog::tools()
+ .into_iter()
+ .find(|tool| tool.path == path)
+ .expect("tool exists")
+}
+
+fn child_args(tool: &Tool, arguments: Value, globals: &[&str]) -> Vec<String> {
+ let arguments = arguments.as_object().expect("arguments object");
+ let argv = tool.argv(arguments).expect("arguments build argv");
+ let globals = globals.iter().map(ToString::to_string).collect::<Vec<_>>();
+ child_command(Path::new("agent-desktop"), tool, argv, &globals)
+ .get_args()
+ .map(|arg| arg.to_string_lossy().into_owned())
+ .collect()
+}
+
+#[test]
+fn ordinary_tools_keep_server_globals_before_their_command() {
+ let tool = tool_at(&["snapshot"]);
+ let args = child_args(
+ &tool,
+ json!({ "app": "Finder" }),
+ &["--session=abc", "--headed"],
+ );
+ assert_eq!(
+ args,
+ ["--session=abc", "--headed", "snapshot", "--app=Finder"]
+ );
+}
+
+#[test]
+fn a_tool_without_an_envelope_reports_its_stderr() {
+ let tool = tool_at(&["version"]);
+ let result = tool_result(
+ &tool,
+ b"",
+ b"unexpected argument\n",
+ "exit status: 2",
+ false,
+ );
+ assert_eq!(result["isError"], true);
+ assert!(
+ result["content"][0]["text"]
+ .as_str()
+ .is_some_and(|text| text.contains("unexpected argument")),
+ "{result}"
+ );
+}
+
+#[test]
+fn sandbox_exec_gets_no_server_globals_and_keeps_guest_arguments_in_order() {
+ let tool = tool_at(&["sandbox", "exec"]);
+ let args = child_args(
+ &tool,
+ json!({ "name": "dev", "args": ["--headed", "type", "--", "@s8f3k2p9:e1", "--session=guest"] }),
+ &["--session=server", "--trace=/tmp/host"],
+ );
+ assert_eq!(
+ args,
+ [
+ "sandbox",
+ "exec",
+ "dev",
+ "--",
+ "--headed",
+ "type",
+ "--",
+ "@s8f3k2p9:e1",
+ "--session=guest",
+ ]
+ );
+}
+
+#[test]
+fn every_tool_but_sandbox_exec_reports_a_json_envelope() {
+ for tool in super::super::catalog::tools() {
+ let expected = match tool.path == ["sandbox", "exec"] {
+ true => Output::Passthrough,
+ false => Output::Envelope,
+ };
+ assert_eq!(tool.output, expected, "{}", tool.name);
+ }
+}
+
+#[test]
+fn silent_guest_output_is_an_empty_success() {
+ let tool = tool_at(&["sandbox", "exec"]);
+ let result = tool_result(&tool, b"", b"", "exit status: 0", true);
+ assert_eq!(result["content"][0]["text"], "");
+ assert_eq!(result["isError"], false);
+ assert!(result.get("structuredContent").is_none(), "{result}");
+}
+
+#[test]
+fn guest_json_is_passed_through_instead_of_being_read_as_the_host_envelope() {
+ let tool = tool_at(&["sandbox", "exec"]);
+ let result = tool_result(&tool, br#"{"a":1}"#, b"", "exit status: 0", true);
+ assert_eq!(result["content"][0]["text"], r#"{"a":1}"#);
+ assert_eq!(result["isError"], false);
+ assert!(result.get("structuredContent").is_none(), "{result}");
+}
+
+#[test]
+fn a_failed_guest_keeps_its_output_and_reports_the_failure() {
+ let tool = tool_at(&["sandbox", "exec"]);
+ let result = tool_result(&tool, b"boom\n", b"", "exit status: 3", false);
+ assert_eq!(result["content"][0]["text"], "boom\n");
+ assert_eq!(result["isError"], true);
+}
diff --git a/src/mcp/catalog.rs b/src/mcp/catalog.rs
index 718b1550e..79fc1b215 100644
--- a/src/mcp/catalog.rs
+++ b/src/mcp/catalog.rs
@@ -10,10 +10,23 @@ const TOOL_PREFIX: &str = "desktop";
const CLAP_HELP_SUBCOMMAND: &str = "help";
const MAX_COUNT: u64 = 16;
+/// The tools whose stdout carries their child's bytes instead of a JSON envelope.
+const PASSTHROUGH_TOOLS: &[&[&str]] = &[&["sandbox", "exec"]];
+
+/// How a tool's child reports its result on stdout.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Output {
+ /// The command's one JSON envelope, as every command but `sandbox exec` writes.
+ Envelope,
+ /// The guest command's own bytes and exit status, which the host passes through unchanged.
+ Passthrough,
+}
+
/// One leaf CLI command exposed as an MCP tool.
pub(crate) struct Tool {
pub name: String,
pub path: Vec<String>,
+ pub output: Output,
command: Command,
}
@@ -49,11 +62,26 @@ fn collect(command: &Command, mut path: Vec<String>, found: &mut Vec<Tool>) {
.replace('-', "_");
found.push(Tool {
name,
+ output: output_for(&path),
path,
command: command.clone(),
});
}
+fn output_for(path: &[String]) -> Output {
+ let passthrough = PASSTHROUGH_TOOLS.iter().any(|tool| {
+ tool.len() == path.len()
+ && tool
+ .iter()
+ .zip(path)
+ .all(|(part, name)| *part == name.as_str())
+ });
+ match passthrough {
+ true => Output::Passthrough,
+ false => Output::Envelope,
+ }
+}
+
impl Tool {
/// The MCP `Tool` object advertised by `tools/list`.
pub(crate) fn definition(&self) -> Value {
@@ -76,19 +104,43 @@ impl Tool {
/// Builds the CLI arguments, after the binary name, that run this command with `arguments`; a null value counts as omitted.
pub(crate) fn argv(&self, arguments: &Map<String, Value>) -> Result<Vec<String>, String> {
let mut argv = self.path.clone();
+ let has_last_positional = self.args().any(Arg::is_last_set);
let mut positionals = Vec::new();
+ let mut last_positionals = Vec::new();
for (key, value) in arguments.iter().filter(|(_, value)| !value.is_null()) {
let arg = self
.args()
.find(|arg| property_name(arg) == *key)
.ok_or_else(|| self.unknown_argument(key))?;
if arg.is_positional() {
- positionals.push((arg.get_index().unwrap_or(usize::MAX), scalars(key, value)?));
+ let positional = (arg.get_index().unwrap_or(usize::MAX), scalars(key, value)?);
+ if arg.is_last_set() {
+ last_positionals.push(positional);
+ } else {
+ positionals.push(positional);
+ }
} else {
push_option(&mut argv, arg, key, value)?;
}
}
- if !positionals.is_empty() {
+ if has_last_positional {
+ positionals.sort_by_key(|(index, _)| *index);
+ if let Some(flag_like) = positionals
+ .iter()
+ .flat_map(|(_, values)| values)
+ .find(|value| value.starts_with('-'))
+ {
+ return Err(format!(
+ "'{flag_like}' would be read as an option; it cannot start with '-'"
+ ));
+ }
+ argv.extend(positionals.into_iter().flat_map(|(_, values)| values));
+ if !last_positionals.is_empty() {
+ last_positionals.sort_by_key(|(index, _)| *index);
+ argv.push("--".to_string());
+ argv.extend(last_positionals.into_iter().flat_map(|(_, values)| values));
+ }
+ } else if !positionals.is_empty() {
positionals.sort_by_key(|(index, _)| *index);
argv.push("--".to_string());
argv.extend(positionals.into_iter().flat_map(|(_, values)| values));
diff --git a/src/mcp/catalog_tests.rs b/src/mcp/catalog_tests.rs
index ea00e0b0a..dd8979b1b 100644
--- a/src/mcp/catalog_tests.rs
+++ b/src/mcp/catalog_tests.rs
@@ -120,6 +120,61 @@ fn unknown_arguments_and_wrong_types_are_reported_not_passed_through() {
);
}
+#[test]
+fn sandbox_exec_keeps_nested_arguments_after_the_delimiter() {
+ let tool = tool_at(&["sandbox", "exec"]);
+ let nested_args = [
+ "snapshot".to_string(),
+ "--app".to_string(),
+ "Finder".to_string(),
+ "--headed".to_string(),
+ "--trace=/tmp/owned".to_string(),
+ "--session=x".to_string(),
+ ];
+ let mut arguments = Map::new();
+ arguments.insert("name".into(), Value::from("dev"));
+ arguments.insert(
+ "args".into(),
+ Value::Array(nested_args.iter().cloned().map(Value::String).collect()),
+ );
+
+ let argv = tool
+ .argv(&arguments)
+ .expect("sandbox exec arguments build argv");
+ let mut option_shaped = arguments.clone();
+ option_shaped.insert("name".into(), Value::from("--help"));
+ tool.argv(&option_shaped)
+ .expect_err("a name shaped like an option never reaches the host parser");
+ assert_eq!(
+ argv,
+ [
+ "sandbox",
+ "exec",
+ "dev",
+ "--",
+ "snapshot",
+ "--app",
+ "Finder",
+ "--headed",
+ "--trace=/tmp/owned",
+ "--session=x",
+ ]
+ );
+
+ let cli = parse(&tool, &arguments).expect("sandbox exec tool arguments parse");
+ assert!(!cli.interaction.headed);
+ assert!(cli.trace.is_none());
+ assert!(cli.identity.session.is_none());
+ let Some(crate::cli::Commands::Sandbox(args)) = cli.command else {
+ panic!("sandbox exec command");
+ };
+ let crate::cli_args::sandbox::SandboxActionCli::Exec(exec) = args.action else {
+ panic!("sandbox exec action");
+ };
+ assert_eq!(exec.name, "dev");
+ assert_eq!(exec.args, nested_args);
+}
+
fn tool_at(path: &[&str]) -> Tool {
tools()
.into_iter()
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index f1318ae18..92df3391a 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -22,12 +22,15 @@ const MAX_MESSAGE_BYTES: usize = 4 * 1024 * 1024;
const INSTRUCTIONS: &str = "\
agent-desktop reads native accessibility trees and operates desktop apps. Each tool runs the \
agent-desktop CLI command of the same name and returns its JSON envelope: ok with data, or ok \
-false with error; a call rejected before the command runs returns plain text. Read \
+false with error; a call rejected before the command runs returns plain text. desktop_sandbox_exec \
+is the exception: its text is the guest command's own stdout, empty included, and isError follows \
+the guest's exit status. Read \
desktop_skills_get with name \"desktop\" first for the observe-act loop, and with name \
\"platform\" for what differs on this OS. The skills use CLI syntax: `agent-desktop snapshot \
--app Finder` is desktop_snapshot with {\"app\": \"Finder\"}, and the input schema replaces \
--help. Global flags (--session, --agent-id, --headed, --wait-for, --trace) are fixed \
-by how this server was started and cannot be passed per call. Refs such as @s8f3k2p9:e1 come from \
+by how this server was started and cannot be passed per call; desktop_sandbox_exec gets none of \
+them, so put the guest command's flags in its args. Refs such as @s8f3k2p9:e1 come from \
desktop_snapshot and go stale when the UI changes: on STALE_REF or AMBIGUOUS_TARGET, snapshot \
again. Repeat an action only when its disposition.retry is \"safe\".";
diff --git a/src/tests/mcp_process.rs b/src/tests/mcp_process.rs
index 5c5460e80..8ed1788a8 100644
--- a/src/tests/mcp_process.rs
+++ b/src/tests/mcp_process.rs
@@ -86,6 +86,46 @@ fn mcp_server_global_flags_reach_every_call() {
);
}
+#[test]
+fn mcp_sandbox_exec_reaches_the_sandbox_when_the_server_has_globals() {
+ let name = format!("missing-{}", std::process::id());
+ let responses = serve(
+ &[
+ call(
+ 1,
+ "desktop_sandbox_exec",
+ json!({ "name": name, "args": ["snapshot", "--app", "Finder"] }),
+ ),
+ call(
+ 2,
+ "desktop_sandbox_exec",
+ json!({
+ "name": format!("{name}-guest"),
+ "args": ["--session=guest", "--headed", "snapshot", "--app", "Finder"],
+ }),
+ ),
+ ],
+ &[
+ "--session=server",
+ "--headed",
+ "--trace=/tmp/mcp-sandbox-trace",
+ ],
+ );
+ assert_eq!(responses.len(), 2, "{responses:?}");
+ for response in &responses {
+ let result = &response["result"];
+ assert_eq!(result["isError"], true, "{result}");
+ assert!(result.get("structuredContent").is_none(), "{result}");
+ let envelope: Value = serde_json::from_str(
+ result["content"][0]["text"]
+ .as_str()
+ .expect("exec passes the host's envelope through as text"),
+ )
+ .expect("the host's envelope is still JSON");
+ assert_eq!(envelope["error"]["code"], "SANDBOX_NOT_FOUND", "{result}");
+ }
+}
+
#[test]
fn malformed_messages_get_errors_and_the_server_keeps_serving() {
let responses = serve(