Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(spaces): Secure Spaces, child Spaces, conformance, space jobs and the macOS developer-tools image, behind experiments (#6306)

ddupont4715a723a450
diff --git a/.github/workflows/ci-cua-oci-spacesd.yml b/.github/workflows/ci-cua-oci-spacesd.yml
index 28e61a84b0..0f63ada8f2 100644
--- a/.github/workflows/ci-cua-oci-spacesd.yml
+++ b/.github/workflows/ci-cua-oci-spacesd.yml
@@ -20,6 +20,8 @@ on:
- "libs/cua/crates/cua-vmm/src/microvm/**"
- "libs/cua/crates/cua-daemon/src/local.rs"
- "tests/e2e/local-runtimes/tests/oci_any.rs"
+ - "tests/e2e/local-runtimes/tests/space_jobs.rs"
+ - "libs/cua/crates/cua-spaces/src/space_jobs.rs"
- ".github/workflows/ci-cua-oci-spacesd.yml"
push:
branches: [main]
@@ -115,3 +117,14 @@ jobs:
export CUA_HOME="$RUNNER_TEMP/cua-home"
mkdir -p "$CUA_HOME"
cargo test --locked --test oci_any -- --nocapture
+ - name: Background jobs in a Space
+ working-directory: tests/e2e/local-runtimes
+ env:
+ CUA_E2E_SPACE_JOBS: "1"
+ CUA_E2E_OCI_ANY_RUNTIME: runc
+ run: |
+ set -euo pipefail
+ export CUA_SPACESD_STATIC="$RUNNER_TEMP/static/cua-spacesd-linux-x86_64"
+ export CUA_HOME="$RUNNER_TEMP/cua-home-jobs"
+ mkdir -p "$CUA_HOME"
+ cargo test --locked --test space_jobs -- --nocapture
diff --git a/apps/cua-spaces-desktop/src/bridge/settings.ts b/apps/cua-spaces-desktop/src/bridge/settings.ts
index d6edabd716..e484d5b44f 100644
--- a/apps/cua-spaces-desktop/src/bridge/settings.ts
+++ b/apps/cua-spaces-desktop/src/bridge/settings.ts
@@ -96,9 +96,18 @@ export function experimentsPage(model: AppModel) {
return { ...page, sections: page.sections.map((s) => ({ ...s, rows: s.rows.filter((r) => !WEB_UI_ROWS.has(r.id)) })) };
}
+/** The experiments the daemon enforces (Secure Spaces, Child Spaces) as the cua home keeps them: what `cua experiments enable` set shows the next time Settings is read. */
+export function refreshDaemonExperiments(model: AppModel): void {
+ const kept = model.native.appSettingsLoad(model.settingsPath).experiments;
+ const now = model.settings.experiments;
+ if (kept.secureSpaces === now.secureSpaces && kept.childSpaces === now.childSpaces) return;
+ model.settings = { ...model.settings, experiments: { ...now, secureSpaces: kept.secureSpaces, childSpaces: kept.childSpaces } };
+}
+
/** `settings.get`'s answer: General, Experiments, the update channel (null:
* no updater), the global shortcut (null: none here) and the account app. */
export function settingsState(model: AppModel, parts: HostParts) {
+ refreshDaemonExperiments(model);
return {
page: encode(settingsPage(model, parts)),
experiments: encode(experimentsPage(model)),
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts
index e9134c3796..52ab04b274 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts
@@ -2109,6 +2109,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_delete_service": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_displays": {
args: [FfiType.Handle],
ret: FfiType.Handle,
@@ -2154,6 +2159,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_kept_services": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_list_tools": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2164,11 +2174,21 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_put_service": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_request_site_login": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_restart_service": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_route": {
args: [FfiType.Handle],
ret: FfiType.Handle,
@@ -2184,6 +2204,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_service_logs": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_services": {
args: [FfiType.Handle],
ret: FfiType.RustBuffer,
@@ -2214,11 +2239,21 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_start_service": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_stop_hotspot": {
args: [FfiType.Handle],
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_stop_service": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_stream_session": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2359,6 +2394,11 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_sdk_fn_method_spaces_ack_network_notice": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_add": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2524,6 +2564,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_delete_tree": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_delete_volume": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],
ret: FfiType.Handle,
@@ -2569,6 +2614,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_network": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_notifications": {
args: [FfiType.Handle, FfiType.Int8, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2584,6 +2634,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_orphans": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_persistent_agent_create": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2679,6 +2734,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_set_children": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_set_egress": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2689,6 +2749,16 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_set_network": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.Int8, FfiType.Int8],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_sdk_fn_method_spaces_set_tree_budget": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_space": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2709,6 +2779,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_tree_budget": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_volume_approve": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -4614,6 +4689,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_delete_service": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_displays": {
args: [],
ret: FfiType.UInt16,
@@ -4659,6 +4739,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_kept_services": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_list_tools": {
args: [],
ret: FfiType.UInt16,
@@ -4669,11 +4754,21 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_put_service": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_request_site_login": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_restart_service": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_route": {
args: [],
ret: FfiType.UInt16,
@@ -4689,6 +4784,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_service_logs": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_services": {
args: [],
ret: FfiType.UInt16,
@@ -4719,11 +4819,21 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_start_service": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_stop_hotspot": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_stop_service": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_stream_session": {
args: [],
ret: FfiType.UInt16,
@@ -4864,6 +4974,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_ack_network_notice": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_add": {
args: [],
ret: FfiType.UInt16,
@@ -5029,6 +5144,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_delete_tree": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_delete_volume": {
args: [],
ret: FfiType.UInt16,
@@ -5074,6 +5194,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_network": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_notifications": {
args: [],
ret: FfiType.UInt16,
@@ -5089,6 +5214,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_orphans": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_persistent_agent_create": {
args: [],
ret: FfiType.UInt16,
@@ -5184,6 +5314,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_set_children": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_set_egress": {
args: [],
ret: FfiType.UInt16,
@@ -5194,6 +5329,16 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_set_network": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_sdk_checksum_method_spaces_set_tree_budget": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_space": {
args: [],
ret: FfiType.UInt16,
@@ -5214,6 +5359,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_tree_budget": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_volume_approve": {
args: [],
ret: FfiType.UInt16,
@@ -6271,6 +6421,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_space_capabilities_json(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_sdk_fn_method_space_checkpoint(uniffiSelf: bigint, checkpoint: Uint8Array, pin: number): bigint;
uniffi_cua_sdk_fn_method_space_close_stream(uniffiSelf: bigint, mediaSessionId: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_space_delete_service(uniffiSelf: bigint, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_displays(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_space_download(uniffiSelf: bigint, remotePath: Uint8Array, destDir: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_fork(uniffiSelf: bigint, name: Uint8Array): bigint;
@@ -6280,19 +6431,25 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_space_id(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_sdk_fn_method_space_info(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_sdk_fn_method_space_join_presence(uniffiSelf: bigint, identity: Uint8Array, timeoutMs: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_space_kept_services(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_space_list_tools(uniffiSelf: bigint, service: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_open_stream(uniffiSelf: bigint, options: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_space_put_service(uniffiSelf: bigint, def: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_request_site_login(uniffiSelf: bigint, url: Uint8Array, options: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_space_restart_service(uniffiSelf: bigint, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_route(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_space_screenshot(uniffiSelf: bigint, options: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_send_file(uniffiSelf: bigint, localPath: Uint8Array, options: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_space_service_logs(uniffiSelf: bigint, name: Uint8Array, tailBytes: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_services(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_sdk_fn_method_space_set_presence_settings(uniffiSelf: bigint, cursorProbe: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_share(uniffiSelf: bigint, who: Uint8Array, role: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_shares(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_space_spacesd(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_sdk_fn_method_space_start_hotspot(uniffiSelf: bigint, setSystemProxy: Uint8Array, bypass: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_space_start_service(uniffiSelf: bigint, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_stop_hotspot(uniffiSelf: bigint): bigint;
+ uniffi_cua_sdk_fn_method_space_stop_service(uniffiSelf: bigint, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_stream_session(uniffiSelf: bigint, options: Uint8Array, frames: bigint, audio: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_supports(uniffiSelf: bigint, feature: Uint8Array, uniffi_out_err: UniffiRustCallStatus): number;
uniffi_cua_sdk_fn_method_space_teleport(uniffiSelf: bigint, app: Uint8Array, scope: Uint8Array, approver: bigint, requestId: Uint8Array): bigint;
@@ -6321,6 +6478,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_spacestreamsession_request_keyframe(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): void;
uniffi_cua_sdk_fn_method_spacestreamsession_send_text(uniffiSelf: bigint, json: Uint8Array, uniffi_out_err: UniffiRustCallStatus): void;
uniffi_cua_sdk_fn_method_spacestreamsession_stats(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_sdk_fn_method_spaces_ack_network_notice(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_add(uniffiSelf: bigint, url: Uint8Array, token: Uint8Array, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_add_with_service(uniffiSelf: bigint, url: Uint8Array, token: Uint8Array, name: Uint8Array, service: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_agent_capabilities(uniffiSelf: bigint): bigint;
@@ -6354,6 +6512,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_spaces_delete(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_delete_build(uniffiSelf: bigint, build: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_delete_many(uniffiSelf: bigint, ids: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_delete_tree(uniffiSelf: bigint, space: Uint8Array, keepChildren: number): bigint;
uniffi_cua_sdk_fn_method_spaces_delete_volume(uniffiSelf: bigint, name: Uint8Array, force: number): bigint;
uniffi_cua_sdk_fn_method_spaces_fork(uniffiSelf: bigint, source: Uint8Array, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_gpu_support(uniffiSelf: bigint, on: Uint8Array): bigint;
@@ -6363,9 +6522,11 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_spaces_list_known(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_spaces_list_tools_json(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_spaces_machine_health(uniffiSelf: bigint, machine: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_network(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_notifications(uniffiSelf: bigint, unreadOnly: number, sinceMs: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_notifications_ack(uniffiSelf: bigint, ids: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_notify_user(uniffiSelf: bigint, title: Uint8Array, body: Uint8Array, agent: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_orphans(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_spaces_persistent_agent_create(uniffiSelf: bigint, name: Uint8Array, harness: Uint8Array, space: Uint8Array, options: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_persistent_agent_remove(uniffiSelf: bigint, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_persistent_agent_save(uniffiSelf: bigint, name: Uint8Array): bigint;
@@ -6385,12 +6546,16 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_spaces_routine_remove(uniffiSelf: bigint, id: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_routine_set_enabled(uniffiSelf: bigint, id: Uint8Array, enabled: number): bigint;
uniffi_cua_sdk_fn_method_spaces_routines(uniffiSelf: bigint, agent: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_set_children(uniffiSelf: bigint, space: Uint8Array, enabled: number): bigint;
uniffi_cua_sdk_fn_method_spaces_set_egress(uniffiSelf: bigint, space: Uint8Array, policy: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_set_lifetime(uniffiSelf: bigint, space: Uint8Array, seconds: bigint, onExpire: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_set_network(uniffiSelf: bigint, space: Uint8Array, settings: Uint8Array, widen: number, tree: number): bigint;
+ uniffi_cua_sdk_fn_method_spaces_set_tree_budget(uniffiSelf: bigint, space: Uint8Array, limits: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_space(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_start(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_stop(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_suspend(uniffiSelf: bigint, space: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_tree_budget(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_volume_approve(uniffiSelf: bigint, requestId: Uint8Array, expiresInSecs: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_volume_audit(uniffiSelf: bigint, limit: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_volume_cache_clear(uniffiSelf: bigint): bigint;
@@ -6772,6 +6937,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_space_capabilities_json(): number;
uniffi_cua_sdk_checksum_method_space_checkpoint(): number;
uniffi_cua_sdk_checksum_method_space_close_stream(): number;
+ uniffi_cua_sdk_checksum_method_space_delete_service(): number;
uniffi_cua_sdk_checksum_method_space_displays(): number;
uniffi_cua_sdk_checksum_method_space_download(): number;
uniffi_cua_sdk_checksum_method_space_fork(): number;
@@ -6781,19 +6947,25 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_space_id(): number;
uniffi_cua_sdk_checksum_method_space_info(): number;
uniffi_cua_sdk_checksum_method_space_join_presence(): number;
+ uniffi_cua_sdk_checksum_method_space_kept_services(): number;
uniffi_cua_sdk_checksum_method_space_list_tools(): number;
uniffi_cua_sdk_checksum_method_space_open_stream(): number;
+ uniffi_cua_sdk_checksum_method_space_put_service(): number;
uniffi_cua_sdk_checksum_method_space_request_site_login(): number;
+ uniffi_cua_sdk_checksum_method_space_restart_service(): number;
uniffi_cua_sdk_checksum_method_space_route(): number;
uniffi_cua_sdk_checksum_method_space_screenshot(): number;
uniffi_cua_sdk_checksum_method_space_send_file(): number;
+ uniffi_cua_sdk_checksum_method_space_service_logs(): number;
uniffi_cua_sdk_checksum_method_space_services(): number;
uniffi_cua_sdk_checksum_method_space_set_presence_settings(): number;
uniffi_cua_sdk_checksum_method_space_share(): number;
uniffi_cua_sdk_checksum_method_space_shares(): number;
uniffi_cua_sdk_checksum_method_space_spacesd(): number;
uniffi_cua_sdk_checksum_method_space_start_hotspot(): number;
+ uniffi_cua_sdk_checksum_method_space_start_service(): number;
uniffi_cua_sdk_checksum_method_space_stop_hotspot(): number;
+ uniffi_cua_sdk_checksum_method_space_stop_service(): number;
uniffi_cua_sdk_checksum_method_space_stream_session(): number;
uniffi_cua_sdk_checksum_method_space_supports(): number;
uniffi_cua_sdk_checksum_method_space_teleport(): number;
@@ -6822,6 +6994,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_spacestreamsession_request_keyframe(): number;
uniffi_cua_sdk_checksum_method_spacestreamsession_send_text(): number;
uniffi_cua_sdk_checksum_method_spacestreamsession_stats(): number;
+ uniffi_cua_sdk_checksum_method_spaces_ack_network_notice(): number;
uniffi_cua_sdk_checksum_method_spaces_add(): number;
uniffi_cua_sdk_checksum_method_spaces_add_with_service(): number;
uniffi_cua_sdk_checksum_method_spaces_agent_capabilities(): number;
@@ -6855,6 +7028,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_spaces_delete(): number;
uniffi_cua_sdk_checksum_method_spaces_delete_build(): number;
uniffi_cua_sdk_checksum_method_spaces_delete_many(): number;
+ uniffi_cua_sdk_checksum_method_spaces_delete_tree(): number;
uniffi_cua_sdk_checksum_method_spaces_delete_volume(): number;
uniffi_cua_sdk_checksum_method_spaces_fork(): number;
uniffi_cua_sdk_checksum_method_spaces_gpu_support(): number;
@@ -6864,9 +7038,11 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_spaces_list_known(): number;
uniffi_cua_sdk_checksum_method_spaces_list_tools_json(): number;
uniffi_cua_sdk_checksum_method_spaces_machine_health(): number;
+ uniffi_cua_sdk_checksum_method_spaces_network(): number;
uniffi_cua_sdk_checksum_method_spaces_notifications(): number;
uniffi_cua_sdk_checksum_method_spaces_notifications_ack(): number;
uniffi_cua_sdk_checksum_method_spaces_notify_user(): number;
+ uniffi_cua_sdk_checksum_method_spaces_orphans(): number;
uniffi_cua_sdk_checksum_method_spaces_persistent_agent_create(): number;
uniffi_cua_sdk_checksum_method_spaces_persistent_agent_remove(): number;
uniffi_cua_sdk_checksum_method_spaces_persistent_agent_save(): number;
@@ -6886,12 +7062,16 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_spaces_routine_remove(): number;
uniffi_cua_sdk_checksum_method_spaces_routine_set_enabled(): number;
uniffi_cua_sdk_checksum_method_spaces_routines(): number;
+ uniffi_cua_sdk_checksum_method_spaces_set_children(): number;
uniffi_cua_sdk_checksum_method_spaces_set_egress(): number;
uniffi_cua_sdk_checksum_method_spaces_set_lifetime(): number;
+ uniffi_cua_sdk_checksum_method_spaces_set_network(): number;
+ uniffi_cua_sdk_checksum_method_spaces_set_tree_budget(): number;
uniffi_cua_sdk_checksum_method_spaces_space(): number;
uniffi_cua_sdk_checksum_method_spaces_start(): number;
uniffi_cua_sdk_checksum_method_spaces_stop(): number;
uniffi_cua_sdk_checksum_method_spaces_suspend(): number;
+ uniffi_cua_sdk_checksum_method_spaces_tree_budget(): number;
uniffi_cua_sdk_checksum_method_spaces_volume_approve(): number;
uniffi_cua_sdk_checksum_method_spaces_volume_audit(): number;
uniffi_cua_sdk_checksum_method_spaces_volume_cache_clear(): number;
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts
index f26687cc09..85be45529d 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts
@@ -13911,6 +13911,118 @@ const FfiConverterTypeNamedVolume = (() => {
return new FFIConverter();
})();
+/**
+ * A Space's network settings: a preset and the user's own lists. The host
+ * the Space runs on compiles them to rules it enforces outside the guest.
+ *
+ * - `internet` (the default): the public internet and the Space's own
+ * tree; this computer, your local network, cloud metadata, other trees
+ * and the cua daemon are blocked;
+ * - `none`: no network;
+ * - `localhost`: `internet`, plus this computer's localhost on
+ * `localhost_ports` (every port only with `all_localhost_ports`);
+ * - `lan`: `internet`, plus your local network (not this computer);
+ * - `custom`: `custom_base` (`internet` or `none`) plus `allow` and `deny`;
+ * - `unprotected`: everything but cloud metadata, other trees and the
+ * daemon.
+ *
+ * A runtime that can't protect a Space yet starts it without network and
+ * says so (`SpaceInfo.network_note`); it never starts it open unless the
+ * preset is `unprotected`.
+ */
+export type NetworkSettings = {
+ /**
+ * `internet`, `none`, `localhost`, `lan`, `custom` or `unprotected`;
+ * empty is `internet`.
+ */
+ preset: string,
+ /**
+ * `localhost`: the ports of this computer's localhost the Space may
+ * reach.
+ */
+ localhostPorts: Array<number>,
+ /**
+ * `localhost`: every port (the daemon's stay blocked).
+ */
+ allLocalhostPorts: boolean,
+ /**
+ * Destinations that stay reachable (addresses or CIDRs).
+ */
+ allow: Array<string>,
+ /**
+ * Destinations that are blocked (addresses, CIDRs or `all`).
+ */
+ deny: Array<string>,
+ /**
+ * `custom`: what it starts from, `internet` (empty) or `none`.
+ */
+ customBase: string,
+ /**
+ * Set when the Space was allowed more than its parent: who and when.
+ */
+ widenedBy?: string
+}
+
+/**
+ * Generated factory for {@link NetworkSettings} record objects.
+ */
+export const NetworkSettings = (() => {
+ const defaults = () => ({
+ preset: "",
+ localhostPorts: [],
+ allLocalhostPorts: false,
+ allow: [],
+ deny: [],
+ customBase: "",
+ widenedBy: undefined
+ });
+ const create = (() => {
+ return uniffiCreateRecord<NetworkSettings, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<NetworkSettings>,
+ });
+})();
+
+const FfiConverterTypeNetworkSettings = (() => {
+ type TypeName = NetworkSettings;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ preset: FfiConverterString.read(from),
+ localhostPorts: FfiConverterSequenceUInt16.read(from),
+ allLocalhostPorts: FfiConverterBool.read(from),
+ allow: FfiConverterSequenceString.read(from),
+ deny: FfiConverterSequenceString.read(from),
+ customBase: FfiConverterString.read(from),
+ widenedBy: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.preset, into);
+ FfiConverterSequenceUInt16.write(value.localhostPorts, into);
+ FfiConverterBool.write(value.allLocalhostPorts, into);
+ FfiConverterSequenceString.write(value.allow, into);
+ FfiConverterSequenceString.write(value.deny, into);
+ FfiConverterString.write(value.customBase, into);
+ FfiConverterOptionalString.write(value.widenedBy, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.preset) +
+ FfiConverterSequenceUInt16.allocationSize(value.localhostPorts) +
+ FfiConverterBool.allocationSize(value.allLocalhostPorts) +
+ FfiConverterSequenceString.allocationSize(value.allow) +
+ FfiConverterSequenceString.allocationSize(value.deny) +
+ FfiConverterString.allocationSize(value.customBase) +
+ FfiConverterOptionalString.allocationSize(value.widenedBy);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* One entry of the notifications feed.
*/
@@ -18006,6 +18118,166 @@ const FfiConverterTypeServiceEndpoint = (() => {
return new FFIConverter();
})();
+/**
+ * A Space's network as `cua network show` says it ([`Spaces::network`]).
+ */
+export type SpaceNetworkInfo = {
+ /**
+ * Its settings.
+ */
+ settings: NetworkSettings,
+ /**
+ * One plain line ("Internet only").
+ */
+ summary: string,
+ /**
+ * What the settings open beyond `internet`, one plain line each.
+ */
+ widenings: Array<string>,
+ /**
+ * `enforced` (rules on the host, outside the guest), `no_network`
+ * (its runtime can't protect it yet), `open` (No protection) or
+ * `refused`; empty when unknown (a Space another computer runs).
+ */
+ enforcement: string,
+ /**
+ * Where the rules are enforced, or why its network is cut.
+ */
+ point: string,
+ /**
+ * Why its network is not what was asked; `None` otherwise.
+ */
+ note?: string,
+ /**
+ * Its parent and its tree's top-level Space; `None` for a top-level
+ * Space.
+ */
+ parent?: string,
+ root?: string,
+ /**
+ * What no setting opens, in plain words.
+ */
+ alwaysBlocked: Array<string>,
+ /**
+ * An update changed its settings: say so once.
+ */
+ noticePending: boolean
+}
+
+/**
+ * Generated factory for {@link SpaceNetworkInfo} record objects.
+ */
+export const SpaceNetworkInfo = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SpaceNetworkInfo, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SpaceNetworkInfo>,
+ });
+})();
+
+const FfiConverterTypeSpaceNetworkInfo = (() => {
+ type TypeName = SpaceNetworkInfo;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ settings: FfiConverterTypeNetworkSettings.read(from),
+ summary: FfiConverterString.read(from),
+ widenings: FfiConverterSequenceString.read(from),
+ enforcement: FfiConverterString.read(from),
+ point: FfiConverterString.read(from),
+ note: FfiConverterOptionalString.read(from),
+ parent: FfiConverterOptionalString.read(from),
+ root: FfiConverterOptionalString.read(from),
+ alwaysBlocked: FfiConverterSequenceString.read(from),
+ noticePending: FfiConverterBool.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterTypeNetworkSettings.write(value.settings, into);
+ FfiConverterString.write(value.summary, into);
+ FfiConverterSequenceString.write(value.widenings, into);
+ FfiConverterString.write(value.enforcement, into);
+ FfiConverterString.write(value.point, into);
+ FfiConverterOptionalString.write(value.note, into);
+ FfiConverterOptionalString.write(value.parent, into);
+ FfiConverterOptionalString.write(value.root, into);
+ FfiConverterSequenceString.write(value.alwaysBlocked, into);
+ FfiConverterBool.write(value.noticePending, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterTypeNetworkSettings.allocationSize(value.settings) +
+ FfiConverterString.allocationSize(value.summary) +
+ FfiConverterSequenceString.allocationSize(value.widenings) +
+ FfiConverterString.allocationSize(value.enforcement) +
+ FfiConverterString.allocationSize(value.point) +
+ FfiConverterOptionalString.allocationSize(value.note) +
+ FfiConverterOptionalString.allocationSize(value.parent) +
+ FfiConverterOptionalString.allocationSize(value.root) +
+ FfiConverterSequenceString.allocationSize(value.alwaysBlocked) +
+ FfiConverterBool.allocationSize(value.noticePending);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * What [`Spaces::set_network`] did.
+ */
+export type SetNetworkResult = {
+ /**
+ * `now` (the running guest is under them) or `next_start`.
+ */
+ applied: string,
+ /**
+ * The Space's network after the change.
+ */
+ network: SpaceNetworkInfo
+}
+
+/**
+ * Generated factory for {@link SetNetworkResult} record objects.
+ */
+export const SetNetworkResult = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SetNetworkResult, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SetNetworkResult>,
+ });
+})();
+
+const FfiConverterTypeSetNetworkResult = (() => {
+ type TypeName = SetNetworkResult;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ applied: FfiConverterString.read(from),
+ network: FfiConverterTypeSpaceNetworkInfo.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.applied, into);
+ FfiConverterTypeSpaceNetworkInfo.write(value.network, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.applied) +
+ FfiConverterTypeSpaceNetworkInfo.allocationSize(value.network);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* One setup step.
*/
@@ -19181,6 +19453,22 @@ export type SpaceCreateOptions = {
* to enforce it makes the create fail.
*/
egress?: EgressPolicy,
+ /**
+ * Network settings (see [`NetworkSettings`]). `None`: what `network`
+ * and `egress` say (`internet` when neither says anything). A daemon
+ * too old to keep them makes the create fail.
+ */
+ networkSettings?: NetworkSettings,
+ /**
+ * Create it as a child of this Space (id or name): its network is no
+ * more open than its parent's, and it joins the parent's tree.
+ */
+ parent?: string,
+ /**
+ * With `parent`: let its network be more open than its parent's
+ * (recorded on the Space).
+ */
+ widen?: boolean,
/**
* With `on` a linked cloud (`aws`, `hetzner`, ...): the machine type
* its host must be (`c7g.xlarge`, `cax41`), a pin of the elastic
@@ -19190,7 +19478,12 @@ export type SpaceCreateOptions = {
/**
* With `on` a linked cloud: the region its host must be in.
*/
- region?: string
+ region?: string,
+ /**
+ * Lets the Space make child Spaces of its own ([`Spaces::set_children`]).
+ * `None`: off. Only a Space the machine of the runtime runs itself.
+ */
+ children?: boolean
}
/**
@@ -19224,8 +19517,12 @@ export const SpaceCreateOptions = (() => {
network: undefined,
labels: new Map(),
egress: undefined,
+ networkSettings: undefined,
+ parent: undefined,
+ widen: undefined,
instanceType: undefined,
- region: undefined
+ region: undefined,
+ children: undefined
});
const create = (() => {
return uniffiCreateRecord<SpaceCreateOptions, ReturnType<typeof defaults>>(defaults);
@@ -19268,8 +19565,12 @@ const FfiConverterTypeSpaceCreateOptions = (() => {
network: FfiConverterOptionalString.read(from),
labels: FfiConverterMapStringString.read(from),
egress: FfiConverterOptionalTypeEgressPolicy.read(from),
+ networkSettings: FfiConverterOptionalTypeNetworkSettings.read(from),
+ parent: FfiConverterOptionalString.read(from),
+ widen: FfiConverterOptionalBoolean.read(from),
instanceType: FfiConverterOptionalString.read(from),
- region: FfiConverterOptionalString.read(from)
+ region: FfiConverterOptionalString.read(from),
+ children: FfiConverterOptionalBoolean.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
@@ -19299,8 +19600,12 @@ const FfiConverterTypeSpaceCreateOptions = (() => {
FfiConverterOptionalString.write(value.network, into);
FfiConverterMapStringString.write(value.labels, into);
FfiConverterOptionalTypeEgressPolicy.write(value.egress, into);
+ FfiConverterOptionalTypeNetworkSettings.write(value.networkSettings, into);
+ FfiConverterOptionalString.write(value.parent, into);
+ FfiConverterOptionalBoolean.write(value.widen, into);
FfiConverterOptionalString.write(value.instanceType, into);
FfiConverterOptionalString.write(value.region, into);
+ FfiConverterOptionalBoolean.write(value.children, into);
}
allocationSize(value: TypeName): number {
return FfiConverterOptionalString.allocationSize(value.image) +
@@ -19329,8 +19634,12 @@ const FfiConverterTypeSpaceCreateOptions = (() => {
FfiConverterOptionalString.allocationSize(value.network) +
FfiConverterMapStringString.allocationSize(value.labels) +
FfiConverterOptionalTypeEgressPolicy.allocationSize(value.egress) +
+ FfiConverterOptionalTypeNetworkSettings.allocationSize(value.networkSettings) +
+ FfiConverterOptionalString.allocationSize(value.parent) +
+ FfiConverterOptionalBoolean.allocationSize(value.widen) +
FfiConverterOptionalString.allocationSize(value.instanceType) +
- FfiConverterOptionalString.allocationSize(value.region);
+ FfiConverterOptionalString.allocationSize(value.region) +
+ FfiConverterOptionalBoolean.allocationSize(value.children);
}
};
@@ -19785,6 +20094,36 @@ export type SpaceInfo = {
* Where `egress` is enforced; `None` without one.
*/
egressEnforced?: EgressEnforcement,
+ /**
+ * Its network settings; `None` for a Space this computer keeps no
+ * record of, or one created before they existed (it gets them on its
+ * next start).
+ */
+ network?: NetworkSettings,
+ /**
+ * Why its network is not what was asked, in plain words (a runtime
+ * that can't protect it yet started it without network); `None`
+ * otherwise.
+ */
+ networkNote?: string,
+ /**
+ * An update changed its network settings (an old Space moved to the
+ * new defaults): say so once.
+ */
+ networkNoticePending: boolean,
+ /**
+ * The Space it was created from, by id; `None` for a top-level Space.
+ */
+ parent?: string,
+ /**
+ * The top-level Space of its tree, by id; `None` for a top-level
+ * Space.
+ */
+ root?: string,
+ /**
+ * How far below its tree's top-level Space it is (0: top-level).
+ */
+ depth: number,
/**
* Named volumes mounted in the Space (see
* [`SpaceCreateOptions::volumes`]).
@@ -19852,6 +20191,12 @@ const FfiConverterTypeSpaceInfo = (() => {
createdAtUnix: FfiConverterInt64.read(from),
egress: FfiConverterTypeEgressPolicy.read(from),
egressEnforced: FfiConverterOptionalTypeEgressEnforcement.read(from),
+ network: FfiConverterOptionalTypeNetworkSettings.read(from),
+ networkNote: FfiConverterOptionalString.read(from),
+ networkNoticePending: FfiConverterBool.read(from),
+ parent: FfiConverterOptionalString.read(from),
+ root: FfiConverterOptionalString.read(from),
+ depth: FfiConverterUInt32.read(from),
volumes: FfiConverterSequenceTypeVolumeMount.read(from),
sharing: FfiConverterOptionalTypeSpaceSharing.read(from)
};
@@ -19887,6 +20232,12 @@ const FfiConverterTypeSpaceInfo = (() => {
FfiConverterInt64.write(value.createdAtUnix, into);
FfiConverterTypeEgressPolicy.write(value.egress, into);
FfiConverterOptionalTypeEgressEnforcement.write(value.egressEnforced, into);
+ FfiConverterOptionalTypeNetworkSettings.write(value.network, into);
+ FfiConverterOptionalString.write(value.networkNote, into);
+ FfiConverterBool.write(value.networkNoticePending, into);
+ FfiConverterOptionalString.write(value.parent, into);
+ FfiConverterOptionalString.write(value.root, into);
+ FfiConverterUInt32.write(value.depth, into);
FfiConverterSequenceTypeVolumeMount.write(value.volumes, into);
FfiConverterOptionalTypeSpaceSharing.write(value.sharing, into);
}
@@ -19921,6 +20272,12 @@ const FfiConverterTypeSpaceInfo = (() => {
FfiConverterInt64.allocationSize(value.createdAtUnix) +
FfiConverterTypeEgressPolicy.allocationSize(value.egress) +
FfiConverterOptionalTypeEgressEnforcement.allocationSize(value.egressEnforced) +
+ FfiConverterOptionalTypeNetworkSettings.allocationSize(value.network) +
+ FfiConverterOptionalString.allocationSize(value.networkNote) +
+ FfiConverterBool.allocationSize(value.networkNoticePending) +
+ FfiConverterOptionalString.allocationSize(value.parent) +
+ FfiConverterOptionalString.allocationSize(value.root) +
+ FfiConverterUInt32.allocationSize(value.depth) +
FfiConverterSequenceTypeVolumeMount.allocationSize(value.volumes) +
FfiConverterOptionalTypeSpaceSharing.allocationSize(value.sharing);
@@ -20334,6 +20691,81 @@ const FfiConverterTypeSpaceList = (() => {
return new FFIConverter();
})();
+/**
+ * A child Space whose parent is gone or out of reach ([`Spaces::orphans`]).
+ */
+export type SpaceOrphan = {
+ /**
+ * The child.
+ */
+ space: string,
+ /**
+ * Its parent's id.
+ */
+ parent: string,
+ /**
+ * `ending` (its parent is provably gone: it ends after the grace) or
+ * `listed` (not this computer's to judge: it stays until deleted or its
+ * own lifetime ends).
+ */
+ state: string,
+ /**
+ * Why.
+ */
+ why: string,
+ /**
+ * Seconds until it ends (`ending` only).
+ */
+ endsInSecs: bigint
+}
+
+/**
+ * Generated factory for {@link SpaceOrphan} record objects.
+ */
+export const SpaceOrphan = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SpaceOrphan, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SpaceOrphan>,
+ });
+})();
+
+const FfiConverterTypeSpaceOrphan = (() => {
+ type TypeName = SpaceOrphan;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ space: FfiConverterString.read(from),
+ parent: FfiConverterString.read(from),
+ state: FfiConverterString.read(from),
+ why: FfiConverterString.read(from),
+ endsInSecs: FfiConverterInt64.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.space, into);
+ FfiConverterString.write(value.parent, into);
+ FfiConverterString.write(value.state, into);
+ FfiConverterString.write(value.why, into);
+ FfiConverterInt64.write(value.endsInSecs, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.space) +
+ FfiConverterString.allocationSize(value.parent) +
+ FfiConverterString.allocationSize(value.state) +
+ FfiConverterString.allocationSize(value.why) +
+ FfiConverterInt64.allocationSize(value.endsInSecs);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* What [`Spaces::stop`] or [`Spaces::start`] did.
*/
@@ -20771,6 +21203,286 @@ const FfiConverterTypeSpaceSendFileReport = (() => {
return new FFIConverter();
})();
+/**
+ * A health check: exactly one of `http`, `tcp`, `command`.
+ */
+export type SpaceServiceProbe = {
+ /**
+ * A URL that answers 2xx or 3xx.
+ */
+ http?: string,
+ /**
+ * `host:port` that accepts a TCP connection.
+ */
+ tcp?: string,
+ /**
+ * A shell command that exits 0 when healthy.
+ */
+ command?: string,
+ /**
+ * Seconds between checks (default 10).
+ */
+ intervalSecs?: bigint,
+ /**
+ * Failed checks in a row that restart it (default 3).
+ */
+ failures?: number
+}
+
+/**
+ * Generated factory for {@link SpaceServiceProbe} record objects.
+ */
+export const SpaceServiceProbe = (() => {
+ const defaults = () => ({
+ http: undefined,
+ tcp: undefined,
+ command: undefined,
+ intervalSecs: undefined,
+ failures: undefined
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SpaceServiceProbe, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SpaceServiceProbe>,
+ });
+})();
+
+const FfiConverterTypeSpaceServiceProbe = (() => {
+ type TypeName = SpaceServiceProbe;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ http: FfiConverterOptionalString.read(from),
+ tcp: FfiConverterOptionalString.read(from),
+ command: FfiConverterOptionalString.read(from),
+ intervalSecs: FfiConverterOptionalUInt64.read(from),
+ failures: FfiConverterOptionalUInt32.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalString.write(value.http, into);
+ FfiConverterOptionalString.write(value.tcp, into);
+ FfiConverterOptionalString.write(value.command, into);
+ FfiConverterOptionalUInt64.write(value.intervalSecs, into);
+ FfiConverterOptionalUInt32.write(value.failures, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalString.allocationSize(value.http) +
+ FfiConverterOptionalString.allocationSize(value.tcp) +
+ FfiConverterOptionalString.allocationSize(value.command) +
+ FfiConverterOptionalUInt64.allocationSize(value.intervalSecs) +
+ FfiConverterOptionalUInt32.allocationSize(value.failures);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * A command a Space keeps running ([`Space::put_service`]).
+ */
+export type SpaceServiceDef = {
+ /**
+ * Name: lowercase letters, digits, `-`, `_`, `.` (1 to 63).
+ */
+ name: string,
+ /**
+ * The shell command line it runs.
+ */
+ command: string,
+ /**
+ * Extra environment.
+ */
+ env: Map<string, string>,
+ /**
+ * Working directory.
+ */
+ cwd?: string,
+ /**
+ * When it is started again: `always` (default), `on-failure` or
+ * `never`.
+ */
+ restart?: string,
+ /**
+ * A health check; failing it restarts the service.
+ */
+ probe?: SpaceServiceProbe,
+ /**
+ * Start it when the Space boots. `None`: yes.
+ */
+ startOnBoot?: boolean
+}
+
+/**
+ * Generated factory for {@link SpaceServiceDef} record objects.
+ */
+export const SpaceServiceDef = (() => {
+ const defaults = () => ({
+ env: new Map(),
+ cwd: undefined,
+ restart: undefined,
+ probe: undefined,
+ startOnBoot: undefined
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SpaceServiceDef, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SpaceServiceDef>,
+ });
+})();
+
+const FfiConverterTypeSpaceServiceDef = (() => {
+ type TypeName = SpaceServiceDef;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ name: FfiConverterString.read(from),
+ command: FfiConverterString.read(from),
+ env: FfiConverterMapStringString.read(from),
+ cwd: FfiConverterOptionalString.read(from),
+ restart: FfiConverterOptionalString.read(from),
+ probe: FfiConverterOptionalTypeSpaceServiceProbe.read(from),
+ startOnBoot: FfiConverterOptionalBoolean.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.name, into);
+ FfiConverterString.write(value.command, into);
+ FfiConverterMapStringString.write(value.env, into);
+ FfiConverterOptionalString.write(value.cwd, into);
+ FfiConverterOptionalString.write(value.restart, into);
+ FfiConverterOptionalTypeSpaceServiceProbe.write(value.probe, into);
+ FfiConverterOptionalBoolean.write(value.startOnBoot, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.name) +
+ FfiConverterString.allocationSize(value.command) +
+ FfiConverterMapStringString.allocationSize(value.env) +
+ FfiConverterOptionalString.allocationSize(value.cwd) +
+ FfiConverterOptionalString.allocationSize(value.restart) +
+ FfiConverterOptionalTypeSpaceServiceProbe.allocationSize(value.probe) +
+ FfiConverterOptionalBoolean.allocationSize(value.startOnBoot);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * A service and how it is doing ([`Space::services`]).
+ */
+export type SpaceServiceInfo = {
+ /**
+ * Name.
+ */
+ name: string,
+ /**
+ * The command line.
+ */
+ command: string,
+ /**
+ * `starting`, `running`, `unhealthy`, `backoff`, `stopped`, `exited`
+ * or `failed`.
+ */
+ state: string,
+ /**
+ * Its process, while it runs.
+ */
+ pid: number,
+ /**
+ * Starts after the first.
+ */
+ restarts: number,
+ /**
+ * How the last process ended, if one did.
+ */
+ lastEnd: string,
+ /**
+ * The last failed health check, if the last one failed.
+ */
+ probeError: string,
+ /**
+ * `always`, `on-failure` or `never`.
+ */
+ restart: string,
+ /**
+ * Starts when the Space boots.
+ */
+ startOnBoot: boolean,
+ /**
+ * Its log file in the Space.
+ */
+ logPath: string
+}
+
+/**
+ * Generated factory for {@link SpaceServiceInfo} record objects.
+ */
+export const SpaceServiceInfo = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SpaceServiceInfo, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SpaceServiceInfo>,
+ });
+})();
+
+const FfiConverterTypeSpaceServiceInfo = (() => {
+ type TypeName = SpaceServiceInfo;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ name: FfiConverterString.read(from),
+ command: FfiConverterString.read(from),
+ state: FfiConverterString.read(from),
+ pid: FfiConverterUInt32.read(from),
+ restarts: FfiConverterUInt32.read(from),
+ lastEnd: FfiConverterString.read(from),
+ probeError: FfiConverterString.read(from),
+ restart: FfiConverterString.read(from),
+ startOnBoot: FfiConverterBool.read(from),
+ logPath: FfiConverterString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.name, into);
+ FfiConverterString.write(value.command, into);
+ FfiConverterString.write(value.state, into);
+ FfiConverterUInt32.write(value.pid, into);
+ FfiConverterUInt32.write(value.restarts, into);
+ FfiConverterString.write(value.lastEnd, into);
+ FfiConverterString.write(value.probeError, into);
+ FfiConverterString.write(value.restart, into);
+ FfiConverterBool.write(value.startOnBoot, into);
+ FfiConverterString.write(value.logPath, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.name) +
+ FfiConverterString.allocationSize(value.command) +
+ FfiConverterString.allocationSize(value.state) +
+ FfiConverterUInt32.allocationSize(value.pid) +
+ FfiConverterUInt32.allocationSize(value.restarts) +
+ FfiConverterString.allocationSize(value.lastEnd) +
+ FfiConverterString.allocationSize(value.probeError) +
+ FfiConverterString.allocationSize(value.restart) +
+ FfiConverterBool.allocationSize(value.startOnBoot) +
+ FfiConverterString.allocationSize(value.logPath);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* One account a Space is shared with.
*/
@@ -23439,6 +24151,207 @@ const FfiConverterTypeTransferResult = (() => {
return new FFIConverter();
})();
+/**
+ * What a tree's children may hold and cost ([`Spaces::set_tree_budget`]).
+ * `None`: the default.
+ */
+export type TreeBudgetLimits = {
+ /**
+ * Child Spaces at once (default 16).
+ */
+ maxSpaces?: number,
+ /**
+ * vCPUs at once (default 16).
+ */
+ maxVcpus?: number,
+ /**
+ * Memory at once, MiB (default 32768).
+ */
+ maxMemoryMb?: bigint,
+ /**
+ * Cost per hour, in linked clouds (default 2.0).
+ */
+ usdPerHour?: number,
+ /**
+ * Cost in total (default: none).
+ */
+ usdTotal?: number
+}
+
+/**
+ * Generated factory for {@link TreeBudgetLimits} record objects.
+ */
+export const TreeBudgetLimits = (() => {
+ const defaults = () => ({
+ maxSpaces: undefined,
+ maxVcpus: undefined,
+ maxMemoryMb: undefined,
+ usdPerHour: undefined,
+ usdTotal: undefined
+ });
+ const create = (() => {
+ return uniffiCreateRecord<TreeBudgetLimits, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<TreeBudgetLimits>,
+ });
+})();
+
+const FfiConverterTypeTreeBudgetLimits = (() => {
+ type TypeName = TreeBudgetLimits;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ maxSpaces: FfiConverterOptionalUInt32.read(from),
+ maxVcpus: FfiConverterOptionalUInt32.read(from),
+ maxMemoryMb: FfiConverterOptionalUInt64.read(from),
+ usdPerHour: FfiConverterOptionalFloat64.read(from),
+ usdTotal: FfiConverterOptionalFloat64.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalUInt32.write(value.maxSpaces, into);
+ FfiConverterOptionalUInt32.write(value.maxVcpus, into);
+ FfiConverterOptionalUInt64.write(value.maxMemoryMb, into);
+ FfiConverterOptionalFloat64.write(value.usdPerHour, into);
+ FfiConverterOptionalFloat64.write(value.usdTotal, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalUInt32.allocationSize(value.maxSpaces) +
+ FfiConverterOptionalUInt32.allocationSize(value.maxVcpus) +
+ FfiConverterOptionalUInt64.allocationSize(value.maxMemoryMb) +
+ FfiConverterOptionalFloat64.allocationSize(value.usdPerHour) +
+ FfiConverterOptionalFloat64.allocationSize(value.usdTotal);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * A tree's budget and what its children use ([`Spaces::tree_budget`]).
+ */
+export type TreeBudget = {
+ /**
+ * The tree's top-level Space.
+ */
+ root: string,
+ /**
+ * What the owner set.
+ */
+ set: TreeBudgetLimits,
+ /**
+ * Child Spaces it may hold at once.
+ */
+ maxSpaces: number,
+ /**
+ * vCPUs it may hold at once.
+ */
+ maxVcpus: number,
+ /**
+ * Memory it may hold at once (MiB).
+ */
+ maxMemoryMb: bigint,
+ /**
+ * Cost per hour it may run at.
+ */
+ usdPerHour: number,
+ /**
+ * Cost in total it may reach, when capped.
+ */
+ usdTotal?: number,
+ /**
+ * Child Spaces now.
+ */
+ spaces: number,
+ /**
+ * vCPUs they hold.
+ */
+ vcpus: number,
+ /**
+ * Memory they hold (MiB).
+ */
+ memoryMb: bigint,
+ /**
+ * Cost per hour they run at.
+ */
+ usdPerHourUsed: number,
+ /**
+ * What they have cost so far.
+ */
+ usdSpent: number
+}
+
+/**
+ * Generated factory for {@link TreeBudget} record objects.
+ */
+export const TreeBudget = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<TreeBudget, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<TreeBudget>,
+ });
+})();
+
+const FfiConverterTypeTreeBudget = (() => {
+ type TypeName = TreeBudget;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ root: FfiConverterString.read(from),
+ set: FfiConverterTypeTreeBudgetLimits.read(from),
+ maxSpaces: FfiConverterUInt32.read(from),
+ maxVcpus: FfiConverterUInt32.read(from),
+ maxMemoryMb: FfiConverterUInt64.read(from),
+ usdPerHour: FfiConverterFloat64.read(from),
+ usdTotal: FfiConverterOptionalFloat64.read(from),
+ spaces: FfiConverterUInt32.read(from),
+ vcpus: FfiConverterUInt32.read(from),
+ memoryMb: FfiConverterUInt64.read(from),
+ usdPerHourUsed: FfiConverterFloat64.read(from),
+ usdSpent: FfiConverterFloat64.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.root, into);
+ FfiConverterTypeTreeBudgetLimits.write(value.set, into);
+ FfiConverterUInt32.write(value.maxSpaces, into);
+ FfiConverterUInt32.write(value.maxVcpus, into);
+ FfiConverterUInt64.write(value.maxMemoryMb, into);
+ FfiConverterFloat64.write(value.usdPerHour, into);
+ FfiConverterOptionalFloat64.write(value.usdTotal, into);
+ FfiConverterUInt32.write(value.spaces, into);
+ FfiConverterUInt32.write(value.vcpus, into);
+ FfiConverterUInt64.write(value.memoryMb, into);
+ FfiConverterFloat64.write(value.usdPerHourUsed, into);
+ FfiConverterFloat64.write(value.usdSpent, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.root) +
+ FfiConverterTypeTreeBudgetLimits.allocationSize(value.set) +
+ FfiConverterUInt32.allocationSize(value.maxSpaces) +
+ FfiConverterUInt32.allocationSize(value.maxVcpus) +
+ FfiConverterUInt64.allocationSize(value.maxMemoryMb) +
+ FfiConverterFloat64.allocationSize(value.usdPerHour) +
+ FfiConverterOptionalFloat64.allocationSize(value.usdTotal) +
+ FfiConverterUInt32.allocationSize(value.spaces) +
+ FfiConverterUInt32.allocationSize(value.vcpus) +
+ FfiConverterUInt64.allocationSize(value.memoryMb) +
+ FfiConverterFloat64.allocationSize(value.usdPerHourUsed) +
+ FfiConverterFloat64.allocationSize(value.usdSpent);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* Upload options.
*/
@@ -37829,6 +38742,10 @@ export interface SpaceLike {
* Closes a media session opened with [`Space::open_stream`].
*/
closeStream(mediaSessionId: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
+/**
+ * Stops a service and forgets it (its logs go too).
+ */
+ deleteService(name: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
/**
* The Space's displays, primary first, with their resolution in
* physical pixels.
@@ -37883,6 +38800,10 @@ export interface SpaceLike {
* roster.
*/
joinPresence(identity: PresenceIdentity, timeoutMs: bigint | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpacePresenceLike>;
+/**
+ * This Space's services.
+ */
+ keptServices(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<SpaceServiceInfo>>;
/**
* Tools of the Space's MCP service (`driver`, the default).
*/
@@ -37892,6 +38813,12 @@ export interface SpaceLike {
* to attach to.
*/
openStream(options: SpaceStreamOptions, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceStreamTicket>;
+/**
+ * Keeps a command running in this Space (replacing a service of that
+ * name): restarted by its policy when it ends or fails its health
+ * check, started when the Space boots, its output kept in a log file.
+ */
+ putService(def: SpaceServiceDef, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceServiceInfo>;
/**
* Signs in to a site in this Space's browser with a password the user
* saved in the Cua Keyvault. The first call files a request
@@ -37901,6 +38828,10 @@ export interface SpaceLike {
* declined request is an error. The password never reaches the caller.
*/
requestSiteLogin(url: string, options: SiteLoginOptions | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SiteLoginReport>;
+/**
+ * Restarts a service.
+ */
+ restartService(name: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceServiceInfo>;
/**
* Which way this Space's calls go now (see [`super::spacesd::SpacesdClient::route`]):
* `local …`, `direct …`, `relay …`, `mesh direct <ip:port> rtt <ms> ms`,
@@ -37920,6 +38851,10 @@ export interface SpaceLike {
* (TeleportService.ReceiveFiles, per-file SHA-256).
*/
sendFile(localPath: string, options: SpaceSendFileOptions, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceSendFileReport>;
+/**
+ * The end of a service's log (`tail_bytes` `None`: 64 KiB).
+ */
+ serviceLogs(name: string, tailBytes: bigint | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
/**
* The MCP services this Space exposes: `driver` when its spacesd has
* the tool registry, then every declared service (reached over generic
@@ -37953,10 +38888,18 @@ export interface SpaceLike {
* (default false here).
*/
startHotspot(setSystemProxy: boolean | undefined, bypass: Array<string> | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceHotspotStatus>;
+/**
+ * Starts a stopped service.
+ */
+ startService(name: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceServiceInfo>;
/**
* Stops this Space's hotspot. Returns the stopped Space ids.
*/
stopHotspot(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<string>>;
+/**
+ * Stops a service and keeps it stopped (also across a reboot).
+ */
+ stopService(name: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceServiceInfo>;
/**
* Opens a media session and delivers keyframe-gated encoded frames
* and audio to the sinks (one delivery thread; decoding stays with the
@@ -38593,6 +39536,36 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Stops a service and forgets it (its logs go too).
+ */
+ async deleteService(name: string, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_delete_service(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_void,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_void,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_void,
+ /*liftFunc:*/ (_v) => {},
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* The Space's displays, primary first, with their resolution in
* physical pixels.
@@ -38783,16 +39756,389 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * This Space's hotspot status.
+ * This Space's hotspot status.
+ */
+ async hotspotStatus(asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceHotspotStatus>> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_hotspot_status(
+ uniffiTypeSpaceObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeSpaceHotspotStatus.lift.bind(FfiConverterSequenceTypeSpaceHotspotStatus),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Id.
+ */
+ id(): string {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterString.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_id(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Connection-time snapshot; never refreshed. With spacesd, handshake
+ * `os`, `os_name`, `os_pretty_name` replace record values; missing/unknown
+ * families clear them. Other fields and non-spacesd services retain
+ * registry/discovery values. `Spaces.list()`/`Spaces.resolve()` remain record views.
+ */
+ info(): SpaceInfo {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterTypeSpaceInfo.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_info(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Joins presence. Waits up to `timeout_ms` (default 10 s) for the
+ * roster.
+ */
+ async joinPresence(identity: PresenceIdentity, timeoutMs: bigint | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SpacePresenceLike> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_join_presence(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterTypePresenceIdentity.lower(identity, nativeModule().rustbuffer_alloc),FfiConverterOptionalUInt64.lower(timeoutMs, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_u64,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_u64,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_u64,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_u64,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSpacePresence.lift.bind(FfiConverterTypeSpacePresence),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * This Space's services.
+ */
+ async keptServices(asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceServiceInfo>> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_kept_services(
+ uniffiTypeSpaceObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeSpaceServiceInfo.lift.bind(FfiConverterSequenceTypeSpaceServiceInfo),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Tools of the Space's MCP service (`driver`, the default).
+ */
+ async listTools(service: string | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceToolInfo>> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_list_tools(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalString.lower(service, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeSpaceToolInfo.lift.bind(FfiConverterSequenceTypeSpaceToolInfo),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Mints a media session (ticket + WebSocket URL) for another client
+ * to attach to.
+ */
+ async openStream(options: SpaceStreamOptions, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceStreamTicket> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_open_stream(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterTypeSpaceStreamOptions.lower(options, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSpaceStreamTicket.lift.bind(FfiConverterTypeSpaceStreamTicket),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Keeps a command running in this Space (replacing a service of that
+ * name): restarted by its policy when it ends or fails its health
+ * check, started when the Space boots, its output kept in a log file.
+ */
+ async putService(def: SpaceServiceDef, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceServiceInfo> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_put_service(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterTypeSpaceServiceDef.lower(def, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSpaceServiceInfo.lift.bind(FfiConverterTypeSpaceServiceInfo),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Signs in to a site in this Space's browser with a password the user
+ * saved in the Cua Keyvault. The first call files a request
+ * (`status == "pending"` with a `request_id`); the user approves it in
+ * Cua, then call again with that `request_id` and the Keyvault types
+ * the login through the Space's cua-driver (`status == "filled"`). A
+ * declined request is an error. The password never reaches the caller.
+ */
+ async requestSiteLogin(url: string, options: SiteLoginOptions | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SiteLoginReport> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_request_site_login(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(url, nativeModule().rustbuffer_alloc),FfiConverterOptionalTypeSiteLoginOptions.lower(options, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSiteLoginReport.lift.bind(FfiConverterTypeSiteLoginReport),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Restarts a service.
+ */
+ async restartService(name: string, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceServiceInfo> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_restart_service(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSpaceServiceInfo.lift.bind(FfiConverterTypeSpaceServiceInfo),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Which way this Space's calls go now (see [`super::spacesd::SpacesdClient::route`]):
+ * `local …`, `direct …`, `relay …`, `mesh direct <ip:port> rtt <ms> ms`,
+ * `mesh relayed` or `cloud`; empty when the Space runs no cua-spacesd.
+ * In daemon mode it is the daemon's connection to the Space.
+ */
+ async route(asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_route(
+ uniffiTypeSpaceObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Captures the Space's display: PNG at full size on the primary
+ * display unless `options` say otherwise (for a small preview,
+ * [`Space::thumbnail`] reads the shared cache instead). Fails with
+ * `CapabilityMissing` (`spacesd`) when the image runs no cua-spacesd.
*/
- async hotspotStatus(asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceHotspotStatus>> /*throws*/ {
+ async screenshot(options: ScreenshotOptions | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<Screenshot> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_hotspot_status(
- uniffiTypeSpaceObjectFactory.clonePointer(this)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_screenshot(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalTypeScreenshotOptions.lower(options, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -38804,86 +40150,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterSequenceTypeSpaceHotspotStatus.lift.bind(FfiConverterSequenceTypeSpaceHotspotStatus),
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- /*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
- );
- } catch (__error: any) {
- if (uniffiIsDebug && __error instanceof Error) {
- __error.stack = __stack;
- }
- throw __error;
- }
- }
-
-/**
- * Id.
- */
- id(): string {
- return ((__rb: Uint8Array) => {
- try {
- return FfiConverterString.lift(__rb);
- } finally {
- nativeModule().rustbuffer_free(__rb);
- }
- })(uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_id(
- uniffiTypeSpaceObjectFactory.clonePointer(this),
- callStatus);
- },
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- ));
- }
-
-/**
- * Connection-time snapshot; never refreshed. With spacesd, handshake
- * `os`, `os_name`, `os_pretty_name` replace record values; missing/unknown
- * families clear them. Other fields and non-spacesd services retain
- * registry/discovery values. `Spaces.list()`/`Spaces.resolve()` remain record views.
- */
- info(): SpaceInfo {
- return ((__rb: Uint8Array) => {
- try {
- return FfiConverterTypeSpaceInfo.lift(__rb);
- } finally {
- nativeModule().rustbuffer_free(__rb);
- }
- })(uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_info(
- uniffiTypeSpaceObjectFactory.clonePointer(this),
- callStatus);
- },
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- ));
- }
-
-/**
- * Joins presence. Waits up to `timeout_ms` (default 10 s) for the
- * roster.
- */
- async joinPresence(identity: PresenceIdentity, timeoutMs: bigint | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SpacePresenceLike> /*throws*/ {
- const __stack = uniffiIsDebug ? new Error().stack : undefined;
- try {
- return await uniffiRustCallAsync(
- /*rustCaller:*/ uniffiCaller,
- /*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_join_presence(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterTypePresenceIdentity.lower(identity, nativeModule().rustbuffer_alloc),FfiConverterOptionalUInt64.lower(timeoutMs, nativeModule().rustbuffer_alloc)
- );
- },
- /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_u64,
- /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_u64,
- /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_u64,
- /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_u64,
- // Async returns always go through the JS-side converter: the
- // FFI symbol returns the future handle (u64), and the user-level
- // RustBuffer comes back via the shared `rust_future_complete_*`
- // export. The bytes the runtime hands back must be deserialized
- // here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSpacePresence.lift.bind(FfiConverterTypeSpacePresence),
+ /*liftFunc:*/ FfiConverterTypeScreenshot.lift.bind(FfiConverterTypeScreenshot),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -38897,16 +40164,17 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Tools of the Space's MCP service (`driver`, the default).
+ * Drops a host file or folder into the Space's `~/Downloads[/subdir]`
+ * (TeleportService.ReceiveFiles, per-file SHA-256).
*/
- async listTools(service: string | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceToolInfo>> /*throws*/ {
+ async sendFile(localPath: string, options: SpaceSendFileOptions, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceSendFileReport> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_list_tools(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalString.lower(service, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_send_file(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(localPath, nativeModule().rustbuffer_alloc),FfiConverterTypeSpaceSendFileOptions.lower(options, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -38918,7 +40186,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterSequenceTypeSpaceToolInfo.lift.bind(FfiConverterSequenceTypeSpaceToolInfo),
+ /*liftFunc:*/ FfiConverterTypeSpaceSendFileReport.lift.bind(FfiConverterTypeSpaceSendFileReport),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -38932,17 +40200,16 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Mints a media session (ticket + WebSocket URL) for another client
- * to attach to.
+ * The end of a service's log (`tail_bytes` `None`: 64 KiB).
*/
- async openStream(options: SpaceStreamOptions, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceStreamTicket> /*throws*/ {
+ async serviceLogs(name: string, tailBytes: bigint | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_open_stream(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterTypeSpaceStreamOptions.lower(options, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_service_logs(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc),FfiConverterOptionalUInt64.lower(tailBytes, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -38954,7 +40221,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSpaceStreamTicket.lift.bind(FfiConverterTypeSpaceStreamTicket),
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -38968,71 +40235,48 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Signs in to a site in this Space's browser with a password the user
- * saved in the Cua Keyvault. The first call files a request
- * (`status == "pending"` with a `request_id`); the user approves it in
- * Cua, then call again with that `request_id` and the Keyvault types
- * the login through the Space's cua-driver (`status == "filled"`). A
- * declined request is an error. The password never reaches the caller.
+ * The MCP services this Space exposes: `driver` when its spacesd has
+ * the tool registry, then every declared service (reached over generic
+ * MCP; no spacesd needed).
*/
- async requestSiteLogin(url: string, options: SiteLoginOptions | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SiteLoginReport> /*throws*/ {
- const __stack = uniffiIsDebug ? new Error().stack : undefined;
- try {
- return await uniffiRustCallAsync(
- /*rustCaller:*/ uniffiCaller,
- /*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_request_site_login(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(url, nativeModule().rustbuffer_alloc),FfiConverterOptionalTypeSiteLoginOptions.lower(options, nativeModule().rustbuffer_alloc)
- );
+ services(): Array<string> {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterSequenceString.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_services(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),
+ callStatus);
},
- /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
- /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
- /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
- /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
- // Async returns always go through the JS-side converter: the
- // FFI symbol returns the future handle (u64), and the user-level
- // RustBuffer comes back via the shared `rust_future_complete_*`
- // export. The bytes the runtime hands back must be deserialized
- // here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSiteLoginReport.lift.bind(FfiConverterTypeSiteLoginReport),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- /*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
- );
- } catch (__error: any) {
- if (uniffiIsDebug && __error instanceof Error) {
- __error.stack = __stack;
- }
- throw __error;
- }
+ ));
}
/**
- * Which way this Space's calls go now (see [`super::spacesd::SpacesdClient::route`]):
- * `local …`, `direct …`, `relay …`, `mesh direct <ip:port> rtt <ms> ms`,
- * `mesh relayed` or `cloud`; empty when the Space runs no cua-spacesd.
- * In daemon mode it is the daemon's connection to the Space.
+ * Sets this Space's presence settings. `cursor_probe`: whether
+ * cua-spacesd may read the real cursor shape by briefly moving the idle
+ * guest pointer to a participant's position (on by default); `None`
+ * leaves it unchanged.
*/
- async route(asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ async setPresenceSettings(cursorProbe: boolean | undefined = undefined, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_route(
- uniffiTypeSpaceObjectFactory.clonePointer(this)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_set_presence_settings(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalBoolean.lower(cursorProbe, nativeModule().rustbuffer_alloc)
);
},
- /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
- /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
- /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
- /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
- // Async returns always go through the JS-side converter: the
- // FFI symbol returns the future handle (u64), and the user-level
- // RustBuffer comes back via the shared `rust_future_complete_*`
- // export. The bytes the runtime hands back must be deserialized
- // here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_void,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_void,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_void,
+ /*liftFunc:*/ (_v) => {},
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -39046,19 +40290,18 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Captures the Space's display: PNG at full size on the primary
- * display unless `options` say otherwise (for a small preview,
- * [`Space::thumbnail`] reads the shared cache instead). Fails with
- * `CapabilityMissing` (`spacesd`) when the image runs no cua-spacesd.
+ * Lets `who` (a verified email or an account id) watch (`viewer`,
+ * the default) or use (`editor`) this Space through the relay. A Space
+ * that is not a host is attached to the relay on its first share.
*/
- async screenshot(options: ScreenshotOptions | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<Screenshot> /*throws*/ {
+ async share(who: string, role: string | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceShares> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_screenshot(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalTypeScreenshotOptions.lower(options, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_share(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(who, nativeModule().rustbuffer_alloc),FfiConverterOptionalString.lower(role, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -39070,7 +40313,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeScreenshot.lift.bind(FfiConverterTypeScreenshot),
+ /*liftFunc:*/ FfiConverterTypeSpaceShares.lift.bind(FfiConverterTypeSpaceShares),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -39084,17 +40327,16 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Drops a host file or folder into the Space's `~/Downloads[/subdir]`
- * (TeleportService.ReceiveFiles, per-file SHA-256).
+ * Who this Space is shared with, and who of them is connected now.
*/
- async sendFile(localPath: string, options: SpaceSendFileOptions, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceSendFileReport> /*throws*/ {
+ async shares(asyncOpts_?: { signal: AbortSignal }): Promise<SpaceShares> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_send_file(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(localPath, nativeModule().rustbuffer_alloc),FfiConverterTypeSpaceSendFileOptions.lower(options, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_shares(
+ uniffiTypeSpaceObjectFactory.clonePointer(this)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -39106,7 +40348,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSpaceSendFileReport.lift.bind(FfiConverterTypeSpaceSendFileReport),
+ /*liftFunc:*/ FfiConverterTypeSpaceShares.lift.bind(FfiConverterTypeSpaceShares),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -39120,20 +40362,13 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * The MCP services this Space exposes: `driver` when its spacesd has
- * the tool registry, then every declared service (reached over generic
- * MCP; no spacesd needed).
+ * The cua-spacesd client over the connection this Space authenticated.
*/
- services(): Array<string> {
- return ((__rb: Uint8Array) => {
- try {
- return FfiConverterSequenceString.lift(__rb);
- } finally {
- nativeModule().rustbuffer_free(__rb);
- }
- })(uniffiCaller.rustCall(
+ spacesd(): SpacesdClientLike /*throws*/ {
+ return FfiConverterTypeSpacesdClient.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError),
/*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_services(
+ return nativeModule().uniffi_cua_sdk_fn_method_space_spacesd(
uniffiTypeSpaceObjectFactory.clonePointer(this),
callStatus);
},
@@ -39142,51 +40377,18 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Sets this Space's presence settings. `cursor_probe`: whether
- * cua-spacesd may read the real cursor shape by briefly moving the idle
- * guest pointer to a participant's position (on by default); `None`
- * leaves it unchanged.
- */
- async setPresenceSettings(cursorProbe: boolean | undefined = undefined, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
- const __stack = uniffiIsDebug ? new Error().stack : undefined;
- try {
- return await uniffiRustCallAsync(
- /*rustCaller:*/ uniffiCaller,
- /*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_set_presence_settings(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalBoolean.lower(cursorProbe, nativeModule().rustbuffer_alloc)
- );
- },
- /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,
- /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_void,
- /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_void,
- /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_void,
- /*liftFunc:*/ (_v) => {},
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- /*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
- );
- } catch (__error: any) {
- if (uniffiIsDebug && __error instanceof Error) {
- __error.stack = __stack;
- }
- throw __error;
- }
- }
-
-/**
- * Lets `who` (a verified email or an account id) watch (`viewer`,
- * the default) or use (`editor`) this Space through the relay. A Space
- * that is not a host is attached to the relay on its first share.
+ * Starts the reverse-SOCKS hotspot: this host serves the Space's
+ * egress. `set_system_proxy` points the guest's proxy settings at it
+ * (default false here).
*/
- async share(who: string, role: string | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceShares> /*throws*/ {
+ async startHotspot(setSystemProxy: boolean | undefined, bypass: Array<string> | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceHotspotStatus> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_share(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(who, nativeModule().rustbuffer_alloc),FfiConverterOptionalString.lower(role, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_start_hotspot(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalBoolean.lower(setSystemProxy, nativeModule().rustbuffer_alloc),FfiConverterOptionalSequenceString.lower(bypass, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -39198,7 +40400,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSpaceShares.lift.bind(FfiConverterTypeSpaceShares),
+ /*liftFunc:*/ FfiConverterTypeSpaceHotspotStatus.lift.bind(FfiConverterTypeSpaceHotspotStatus),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -39212,16 +40414,16 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Who this Space is shared with, and who of them is connected now.
+ * Starts a stopped service.
*/
- async shares(asyncOpts_?: { signal: AbortSignal }): Promise<SpaceShares> /*throws*/ {
+ async startService(name: string, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceServiceInfo> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_shares(
- uniffiTypeSpaceObjectFactory.clonePointer(this)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_start_service(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -39233,7 +40435,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSpaceShares.lift.bind(FfiConverterTypeSpaceShares),
+ /*liftFunc:*/ FfiConverterTypeSpaceServiceInfo.lift.bind(FfiConverterTypeSpaceServiceInfo),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -39247,33 +40449,16 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * The cua-spacesd client over the connection this Space authenticated.
- */
- spacesd(): SpacesdClientLike /*throws*/ {
- return FfiConverterTypeSpacesdClient.lift(uniffiCaller.rustCallWithError(
- /*liftError:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError),
- /*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_spacesd(
- uniffiTypeSpaceObjectFactory.clonePointer(this),
- callStatus);
- },
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- ));
- }
-
-/**
- * Starts the reverse-SOCKS hotspot: this host serves the Space's
- * egress. `set_system_proxy` points the guest's proxy settings at it
- * (default false here).
+ * Stops this Space's hotspot. Returns the stopped Space ids.
*/
- async startHotspot(setSystemProxy: boolean | undefined, bypass: Array<string> | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceHotspotStatus> /*throws*/ {
+ async stopHotspot(asyncOpts_?: { signal: AbortSignal }): Promise<Array<string>> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_start_hotspot(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalBoolean.lower(setSystemProxy, nativeModule().rustbuffer_alloc),FfiConverterOptionalSequenceString.lower(bypass, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_stop_hotspot(
+ uniffiTypeSpaceObjectFactory.clonePointer(this)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -39285,7 +40470,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSpaceHotspotStatus.lift.bind(FfiConverterTypeSpaceHotspotStatus),
+ /*liftFunc:*/ FfiConverterSequenceString.lift.bind(FfiConverterSequenceString),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -39299,16 +40484,16 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Stops this Space's hotspot. Returns the stopped Space ids.
+ * Stops a service and keeps it stopped (also across a reboot).
*/
- async stopHotspot(asyncOpts_?: { signal: AbortSignal }): Promise<Array<string>> /*throws*/ {
+ async stopService(name: string, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceServiceInfo> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_stop_hotspot(
- uniffiTypeSpaceObjectFactory.clonePointer(this)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_stop_service(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -39320,7 +40505,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterSequenceString.lift.bind(FfiConverterSequenceString),
+ /*liftFunc:*/ FfiConverterTypeSpaceServiceInfo.lift.bind(FfiConverterTypeSpaceServiceInfo),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -40502,6 +41687,11 @@ const FfiConverterTypeResourcesWatch = new FfiConverterObject(uniffiTypeResource
*/
export interface SpacesLike {
+/**
+ * Marks the one-time notice about the new network defaults as shown
+ * for `space` ([`SpaceNetworkInfo::notice_pending`]).
+ */
+ ackNetworkNotice(space: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
/**
* Adds a Space by URL (`http(s)://host:port`, `host:port`, or a
* Space id such as `local:<name>`) after a `GetCapabilities` handshake. Any other MCP
@@ -40682,7 +41872,8 @@ export interface SpacesLike {
createWithProgress(options: SpaceCreateOptions, listener: SpaceCreateListener, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceCreateResult>;
/**
* Deletes a Space's sandbox and forgets it (a Space added by address
- * is only forgotten). Returns what happened.
+ * is only forgotten). Its child Spaces are deleted first. Returns what
+ * happened.
*/
delete_(space: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
/**
@@ -40698,6 +41889,11 @@ export interface SpacesLike {
* order; one failure never stops the rest.
*/
deleteMany(ids: Array<string>, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<BulkResult>>;
+/**
+ * [`Spaces::delete`], with `keep_children`: its child Spaces become
+ * top-level Spaces and keep running instead of being deleted first.
+ */
+ deleteTree(space: string, keepChildren: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
/**
* Deletes the named volume `name` and its files (their history stays
* in the Cua Volume). Refused while Spaces mount it unless `force`.
@@ -40763,6 +41959,11 @@ export interface SpacesLike {
* offline, not yours, or runs a Cua that predates the check.
*/
machineHealth(machine: string | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<MachineHealth>;
+/**
+ * A Space's network: its settings, what they open, where they are
+ * enforced (or why its network is cut), and what is always blocked.
+ */
+ network(space: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceNetworkInfo>;
/**
* The notifications feed, newest first.
*/
@@ -40775,6 +41976,12 @@ export interface SpacesLike {
* Posts a notification to the Cua app. Returns its id.
*/
notifyUser(title: string, body: string | undefined, agent: string | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
+/**
+ * Child Spaces whose parent is gone or out of reach. The cua daemon
+ * ends a child only on proof its parent is gone (after a grace period);
+ * the rest are listed here and never ended by it.
+ */
+ orphans(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<SpaceOrphan>>;
/**
* Creates a persistent agent: `harness` working in `space`, its home at
* `agents/<name>/` in the Cua Volume.
@@ -40881,6 +42088,16 @@ export interface SpacesLike {
* Routines (of one agent, or all).
*/
routines(agent: string | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<RoutineInfo>>;
+/**
+ * Lets a Space make child Spaces of its own, or stops it. While on,
+ * `cua`, the SDKs and the agent's tools in that Space create, list and
+ * delete Spaces that belong to it (on the same computer, never wider
+ * than it, ending no later than it), through a channel only it can
+ * reach. Off ends its capability at once; children it made keep running
+ * until deleted or their lifetime ends. Only for a Space the machine of
+ * this runtime runs itself.
+ */
+ setChildren(space: string, enabled: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
/**
* Replaces a Space's egress policy; an empty one removes it (see
* [`EgressPolicy`]). Its host enforces it at once. A bad entry is
@@ -40896,6 +42113,20 @@ export interface SpacesLike {
* Embedded: recorded; the cua daemon on this machine enforces it.
*/
setLifetime(space: string, seconds: bigint, onExpire: string | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<bigint>;
+/**
+ * Replaces a Space's network settings (see [`NetworkSettings`]). A
+ * child stays within its parent's unless `widen`; `tree` gives its
+ * children the same settings. They hold at once where the runtime can
+ * change a running guest's network, else from its next start
+ * (`applied`). A Space another computer runs is `Unsupported`.
+ */
+ setNetwork(space: string, settings: NetworkSettings, widen: boolean, tree: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SetNetworkResult>;
+/**
+ * Sets the budget of `space`'s tree: how many child Spaces, vCPUs and
+ * memory its children may hold at once, and what they may cost. A child
+ * that does not fit is refused with what is left. All `None` removes it.
+ */
+ setTreeBudget(space: string, limits: TreeBudgetLimits, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<TreeBudget>;
/**
* A connected handle to a registered Space.
*/
@@ -40922,6 +42153,11 @@ export interface SpacesLike {
* then. [`Spaces::stop`] stops it instead and frees its memory.
*/
suspend(space: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpacePowerReport>;
+/**
+ * The budget of `space`'s tree (any Space of it) and what its
+ * children use now. Kept by the cua daemon.
+ */
+ treeBudget(space: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<TreeBudget>;
/**
* `volume_approve`: the request becomes a grant (with presence).
*/
@@ -41075,6 +42311,37 @@ private constructor(pointer: UniffiHandle) {
+/**
+ * Marks the one-time notice about the new network defaults as shown
+ * for `space` ([`SpaceNetworkInfo::notice_pending`]).
+ */
+ async ackNetworkNotice(space: string, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_ack_network_notice(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_void,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_void,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_void,
+ /*liftFunc:*/ (_v) => {},
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Adds a Space by URL (`http(s)://host:port`, `host:port`, or a
* Space id such as `local:<name>`) after a `GetCapabilities` handshake. Any other MCP
@@ -42185,7 +43452,8 @@ private constructor(pointer: UniffiHandle) {
/**
* Deletes a Space's sandbox and forgets it (a Space added by address
- * is only forgotten). Returns what happened.
+ * is only forgotten). Its child Spaces are deleted first. Returns what
+ * happened.
*/
async delete_(space: string, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
@@ -42294,6 +43562,42 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * [`Spaces::delete`], with `keep_children`: its child Spaces become
+ * top-level Spaces and keep running instead of being deleted first.
+ */
+ async deleteTree(space: string, keepChildren: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_delete_tree(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(keepChildren, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Deletes the named volume `name` and its files (their history stays
* in the Cua Volume). Refused while Spaces mount it unless `force`.
@@ -42638,6 +43942,42 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * A Space's network: its settings, what they open, where they are
+ * enforced (or why its network is cut), and what is always blocked.
+ */
+ async network(space: string, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceNetworkInfo> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_network(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSpaceNetworkInfo.lift.bind(FfiConverterTypeSpaceNetworkInfo),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* The notifications feed, newest first.
*/
@@ -42743,6 +44083,43 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Child Spaces whose parent is gone or out of reach. The cua daemon
+ * ends a child only on proof its parent is gone (after a grace period);
+ * the rest are listed here and never ended by it.
+ */
+ async orphans(asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceOrphan>> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_orphans(
+ uniffiTypeSpacesObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeSpaceOrphan.lift.bind(FfiConverterSequenceTypeSpaceOrphan),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Creates a persistent agent: `harness` working in `space`, its home at
* `agents/<name>/` in the Cua Volume.
@@ -43428,6 +44805,42 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Lets a Space make child Spaces of its own, or stops it. While on,
+ * `cua`, the SDKs and the agent's tools in that Space create, list and
+ * delete Spaces that belong to it (on the same computer, never wider
+ * than it, ending no later than it), through a channel only it can
+ * reach. Off ends its capability at once; children it made keep running
+ * until deleted or their lifetime ends. Only for a Space the machine of
+ * this runtime runs itself.
+ */
+ async setChildren(space: string, enabled: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_set_children(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(enabled, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_void,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_void,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_void,
+ /*liftFunc:*/ (_v) => {},
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Replaces a Space's egress policy; an empty one removes it (see
* [`EgressPolicy`]). Its host enforces it at once. A bad entry is
@@ -43500,6 +44913,82 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Replaces a Space's network settings (see [`NetworkSettings`]). A
+ * child stays within its parent's unless `widen`; `tree` gives its
+ * children the same settings. They hold at once where the runtime can
+ * change a running guest's network, else from its next start
+ * (`applied`). A Space another computer runs is `Unsupported`.
+ */
+ async setNetwork(space: string, settings: NetworkSettings, widen: boolean, tree: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<SetNetworkResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_set_network(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc),FfiConverterTypeNetworkSettings.lower(settings, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(widen, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(tree, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSetNetworkResult.lift.bind(FfiConverterTypeSetNetworkResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Sets the budget of `space`'s tree: how many child Spaces, vCPUs and
+ * memory its children may hold at once, and what they may cost. A child
+ * that does not fit is refused with what is left. All `None` removes it.
+ */
+ async setTreeBudget(space: string, limits: TreeBudgetLimits, asyncOpts_?: { signal: AbortSignal }): Promise<TreeBudget> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_set_tree_budget(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc),FfiConverterTypeTreeBudgetLimits.lower(limits, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeTreeBudget.lift.bind(FfiConverterTypeTreeBudget),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* A connected handle to a registered Space.
*/
@@ -43650,6 +45139,42 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * The budget of `space`'s tree (any Space of it) and what its
+ * children use now. Kept by the cua daemon.
+ */
+ async treeBudget(space: string, asyncOpts_?: { signal: AbortSignal }): Promise<TreeBudget> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_tree_budget(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeTreeBudget.lift.bind(FfiConverterTypeTreeBudget),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* `volume_approve`: the request becomes a grant (with presence).
*/
@@ -46386,6 +47911,9 @@ const FfiConverterSequenceTypeVolumeMount = new FfiConverterArray(FfiConverterTy
// FfiConverter for EgressPolicy | undefined
const FfiConverterOptionalTypeEgressPolicy = new FfiConverterOptional(FfiConverterTypeEgressPolicy);
+// FfiConverter for NetworkSettings | undefined
+const FfiConverterOptionalTypeNetworkSettings = new FfiConverterOptional(FfiConverterTypeNetworkSettings);
+
// FfiConverter for EgressEnforcement | undefined
const FfiConverterOptionalTypeEgressEnforcement = new FfiConverterOptional(FfiConverterTypeEgressEnforcement);
@@ -46407,6 +47935,9 @@ const FfiConverterSequenceTypeSpaceCreatingElsewhere = new FfiConverterArray(Ffi
// FfiConverter for Array<SpaceSentFile>
const FfiConverterSequenceTypeSpaceSentFile = new FfiConverterArray(FfiConverterTypeSpaceSentFile);
+// FfiConverter for SpaceServiceProbe | undefined
+const FfiConverterOptionalTypeSpaceServiceProbe = new FfiConverterOptional(FfiConverterTypeSpaceServiceProbe);
+
// FfiConverter for Array<SpaceShareEntry>
const FfiConverterSequenceTypeSpaceShareEntry = new FfiConverterArray(FfiConverterTypeSpaceShareEntry);
@@ -46569,6 +48100,9 @@ const FfiConverterOptionalTypePresencePoint = new FfiConverterOptional(FfiConver
// FfiConverter for Array<PresenceDrawable>
const FfiConverterSequenceTypePresenceDrawable = new FfiConverterArray(FfiConverterTypePresenceDrawable);
+// FfiConverter for Array<SpaceServiceInfo>
+const FfiConverterSequenceTypeSpaceServiceInfo = new FfiConverterArray(FfiConverterTypeSpaceServiceInfo);
+
// FfiConverter for Array<SpaceToolInfo>
const FfiConverterSequenceTypeSpaceToolInfo = new FfiConverterArray(FfiConverterTypeSpaceToolInfo);
@@ -46590,6 +48124,9 @@ const FfiConverterSequenceTypeSpacesHost = new FfiConverterArray(FfiConverterTyp
// FfiConverter for Array<NotificationInfo>
const FfiConverterSequenceTypeNotificationInfo = new FfiConverterArray(FfiConverterTypeNotificationInfo);
+// FfiConverter for Array<SpaceOrphan>
+const FfiConverterSequenceTypeSpaceOrphan = new FfiConverterArray(FfiConverterTypeSpaceOrphan);
+
// FfiConverter for PersistentAgentOptions | undefined
const FfiConverterOptionalTypePersistentAgentOptions = new FfiConverterOptional(FfiConverterTypePersistentAgentOptions);
@@ -47512,6 +49049,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_space_close_stream() !== 64912) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_close_stream");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_delete_service() !== 14460) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_delete_service");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_displays() !== 30039) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_displays");
}
@@ -47539,15 +49079,24 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_space_join_presence() !== 56636) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_join_presence");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_kept_services() !== 50248) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_kept_services");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_list_tools() !== 19376) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_list_tools");
}
if (nativeModule().uniffi_cua_sdk_checksum_method_space_open_stream() !== 19577) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_open_stream");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_put_service() !== 55111) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_put_service");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_request_site_login() !== 2223) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_request_site_login");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_restart_service() !== 63778) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_restart_service");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_route() !== 9790) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_route");
}
@@ -47557,6 +49106,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_space_send_file() !== 29056) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_send_file");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_service_logs() !== 48773) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_service_logs");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_services() !== 32496) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_services");
}
@@ -47575,9 +49127,15 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_space_start_hotspot() !== 44744) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_start_hotspot");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_start_service() !== 13576) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_start_service");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_stop_hotspot() !== 18254) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_stop_hotspot");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_stop_service() !== 14671) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_stop_service");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_stream_session() !== 61326) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_stream_session");
}
@@ -47662,6 +49220,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spacestreamsession_stats() !== 40219) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spacestreamsession_stats");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_ack_network_notice() !== 32926) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_ack_network_notice");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_add() !== 56308) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_add");
}
@@ -47752,7 +49313,7 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_create_with_progress() !== 28676) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_create_with_progress");
}
- if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_delete() !== 39986) {
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_delete() !== 4316) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_delete");
}
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_delete_build() !== 6500) {
@@ -47761,6 +49322,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_delete_many() !== 9087) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_delete_many");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_delete_tree() !== 29454) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_delete_tree");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_delete_volume() !== 11412) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_delete_volume");
}
@@ -47788,6 +49352,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_machine_health() !== 35352) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_machine_health");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_network() !== 41208) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_network");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_notifications() !== 10964) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_notifications");
}
@@ -47797,6 +49364,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_notify_user() !== 48805) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_notify_user");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_orphans() !== 23539) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_orphans");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_persistent_agent_create() !== 6521) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_persistent_agent_create");
}
@@ -47854,12 +49424,21 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_routines() !== 22768) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_routines");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_set_children() !== 63927) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_set_children");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_set_egress() !== 12366) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_set_egress");
}
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_set_lifetime() !== 62609) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_set_lifetime");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_set_network() !== 64671) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_set_network");
+ }
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_set_tree_budget() !== 8418) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_set_tree_budget");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_space() !== 26355) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_space");
}
@@ -47872,6 +49451,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_suspend() !== 23817) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_suspend");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_tree_budget() !== 58333) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_tree_budget");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_volume_approve() !== 8640) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_volume_approve");
}
@@ -48325,6 +49907,7 @@ export default Object.freeze({
FfiConverterTypeMediaSession,
FfiConverterTypeMediaStats,
FfiConverterTypeNamedVolume,
+ FfiConverterTypeNetworkSettings,
FfiConverterTypeNotificationInfo,
FfiConverterTypeOverlay,
FfiConverterTypeOverlayResult,
@@ -48384,6 +49967,7 @@ export default Object.freeze({
FfiConverterTypeScreenshotOptions,
FfiConverterTypeService,
FfiConverterTypeServiceEndpoint,
+ FfiConverterTypeSetNetworkResult,
FfiConverterTypeSetupStep,
FfiConverterTypeShare,
FfiConverterTypeShareAccess,
@@ -48408,6 +49992,8 @@ export default Object.freeze({
FfiConverterTypeSpaceHotspotStatus,
FfiConverterTypeSpaceInfo,
FfiConverterTypeSpaceList,
+ FfiConverterTypeSpaceNetworkInfo,
+ FfiConverterTypeSpaceOrphan,
FfiConverterTypeSpacePowerReport,
FfiConverterTypeSpacePresence,
FfiConverterTypeSpaceRelayRegistration,
@@ -48416,6 +50002,9 @@ export default Object.freeze({
FfiConverterTypeSpaceSendFileOptions,
FfiConverterTypeSpaceSendFileReport,
FfiConverterTypeSpaceSentFile,
+ FfiConverterTypeSpaceServiceDef,
+ FfiConverterTypeSpaceServiceInfo,
+ FfiConverterTypeSpaceServiceProbe,
FfiConverterTypeSpaceShareEntry,
FfiConverterTypeSpaceShares,
FfiConverterTypeSpaceSharing,
@@ -48460,6 +50049,8 @@ export default Object.freeze({
FfiConverterTypeTeleportReceipt,
FfiConverterTypeThreadView,
FfiConverterTypeTransferResult,
+ FfiConverterTypeTreeBudget,
+ FfiConverterTypeTreeBudgetLimits,
FfiConverterTypeUploadOptions,
FfiConverterTypeVideoFrame,
FfiConverterTypeViewerLink,
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
index 5798e67f85..f2603a10a5 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
@@ -4522,7 +4522,9 @@ export function appSettingsInputFromJson(json: string): AppSettingsInput /*throw
}
/**
- * Reads the settings file (defaults when missing or damaged).
+ * Reads the settings file (defaults when missing or damaged). The
+ * experiments the daemon enforces (Secure Spaces, Child Spaces) are what
+ * the cua home keeps, so `cua experiments enable` shows in the app.
*/
export function appSettingsLoad(path: string): AppSettings {
return ((__rb: Uint8Array) => {
@@ -4585,7 +4587,8 @@ export function appSettingsResolveNewUi(settings: AppSettings, version: string):
}
/**
- * Writes the settings file.
+ * Writes the settings file, and keeps the experiments the daemon enforces
+ * where it reads them (the cua home).
*/
export function appSettingsSave(path: string, settings: AppSettings): void /*throws*/ {uniffiCaller.rustCallWithError(
/*liftError:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError),
@@ -14565,7 +14568,18 @@ export type AppExperiments = {
* The shared web UI is the main window. Always on in the macOS shell
* ([`crate::settings::resolve_new_ui`]); kept for older files and builds.
*/
- webUi: boolean
+ webUi: boolean,
+ /**
+ * Secure Spaces: a Space reaches the internet and nothing else on the
+ * network unless it is opened. Off unless turned on; the daemon enforces
+ * it (the switch is kept in the cua home).
+ */
+ secureSpaces: boolean,
+ /**
+ * Child Spaces: a Space may make Spaces of its own. Off unless turned
+ * on; the daemon enforces it (the switch is kept in the cua home).
+ */
+ childSpaces: boolean
}
/**
@@ -14592,7 +14606,9 @@ const FfiConverterTypeAppExperiments = (() => {
cuaVolume: FfiConverterBool.read(from),
yourCloud: FfiConverterBool.read(from),
sharing: FfiConverterBool.read(from),
- webUi: FfiConverterBool.read(from)
+ webUi: FfiConverterBool.read(from),
+ secureSpaces: FfiConverterBool.read(from),
+ childSpaces: FfiConverterBool.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
@@ -14600,12 +14616,16 @@ const FfiConverterTypeAppExperiments = (() => {
FfiConverterBool.write(value.yourCloud, into);
FfiConverterBool.write(value.sharing, into);
FfiConverterBool.write(value.webUi, into);
+ FfiConverterBool.write(value.secureSpaces, into);
+ FfiConverterBool.write(value.childSpaces, into);
}
allocationSize(value: TypeName): number {
return FfiConverterBool.allocationSize(value.cuaVolume) +
FfiConverterBool.allocationSize(value.yourCloud) +
FfiConverterBool.allocationSize(value.sharing) +
- FfiConverterBool.allocationSize(value.webUi);
+ FfiConverterBool.allocationSize(value.webUi) +
+ FfiConverterBool.allocationSize(value.secureSpaces) +
+ FfiConverterBool.allocationSize(value.childSpaces);
}
};
@@ -71753,7 +71773,7 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_settings_input_from_json() !== 15437) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_settings_input_from_json");
}
- if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_settings_load() !== 42027) {
+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_settings_load() !== 48517) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_settings_load");
}
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_settings_page() !== 454) {
@@ -71762,7 +71782,7 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_settings_resolve_new_ui() !== 48081) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_settings_resolve_new_ui");
}
- if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_settings_save() !== 30129) {
+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_settings_save() !== 62204) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_settings_save");
}
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_settings_with_storage() !== 34252) {
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
index ea37e3374e..4c89be69ef 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
@@ -1949,6 +1949,17 @@ public final class AppModel {
// MARK: - Experiments
+ /// The experiments the daemon enforces (Secure Spaces, Child Spaces) as
+ /// the cua home keeps them: what `cua experiments enable` set shows here
+ /// the next time Settings is read.
+ public func refreshDaemonExperiments() {
+ let kept = appSettingsLoad(path: settingsPath).experiments
+ guard kept.secureSpaces != settings.experiments.secureSpaces
+ || kept.childSpaces != settings.experiments.childSpaces else { return }
+ settings.experiments.secureSpaces = kept.secureSpaces
+ settings.experiments.childSpaces = kept.childSpaces
+ }
+
/// Settings, Experiments: a switch and one line per experiment.
public var experimentsPage: AppSettingsPage { appExperimentsPage(experiments: settings.experiments) }
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index 32f0c5da59..d0eb180e84 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -604,7 +604,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
func relayHostnames() -> [String: String] { model.relayHostnames }
func settings() -> [String: Any] {
- [
+ model.refreshDaemonExperiments()
+ return [
"page": BridgeValue.encode(model.settingsPageWithStorage),
"experiments": BridgeValue.encode(model.experimentsPage),
// Settings → About's channel; null while this build has no updater.
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/FirstRunTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/FirstRunTests.swift
index b66709994e..6702716ed2 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/FirstRunTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/FirstRunTests.swift
@@ -25,7 +25,7 @@ struct FirstRunTests {
onboarding: OnboardingModel(statePath: state.path),
settingsPath: dir.appendingPathComponent("settings.json").path, telemetry: telemetry,
loginItem: loginItem)
- model.settings.experiments = AppExperiments(cuaVolume: false, yourCloud: false, sharing: true, webUi: true)
+ model.settings.experiments = AppExperiments(cuaVolume: false, yourCloud: false, sharing: true, webUi: true, secureSpaces: false, childSpaces: false)
let bridge = WebUIBridge(model: model, allowedOrigins: [])
bridge.notifySpaceReady = { _ in }
return (bridge, model, telemetry, state)
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift
index 2f6e32316b..2e1f47cdb7 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MainUIRouteTests.swift
@@ -21,7 +21,7 @@ struct MainUIRouteTests {
onboarding: OnboardingModel(statePath: dir.appendingPathComponent("onboarding.json").path),
settingsPath: dir.appendingPathComponent("settings.json").path,
telemetry: FixtureTelemetry())
- m.settings.experiments = AppExperiments(cuaVolume: true, yourCloud: false, sharing: false, webUi: true)
+ m.settings.experiments = AppExperiments(cuaVolume: true, yourCloud: false, sharing: false, webUi: true, secureSpaces: false, childSpaces: false)
return m
}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
index 419d9166f4..db53572b4d 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
@@ -432,7 +432,7 @@ struct ViewModelTests {
let telemetry = FixtureTelemetry()
let model = makeModel(telemetry: telemetry)
let toggles = model.experimentsPage.sections.flatMap(\.rows).filter { $0.kind == .toggle }
- #expect(toggles.map(\.id) == ["experiment:cua_volume", "experiment:your_cloud", "experiment:sharing"])
+ #expect(toggles.map(\.id) == ["experiment:cua_volume", "experiment:your_cloud", "experiment:sharing", "experiment:secure_spaces", "experiment:child_spaces"])
// Sharing and Your cloud are on unless turned off; no New UI row.
let onByDefault: Set<String> = ["experiment:sharing", "experiment:your_cloud"]
#expect(toggles.allSatisfy { r in
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
index 4833161bde..86a33c7008 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
@@ -47,7 +47,7 @@ struct WebUIHostTests {
}
@Test func coreRecordsEncodeAsPlainValues() {
- let x = AppExperiments(cuaVolume: true, yourCloud: false, sharing: false, webUi: true)
+ let x = AppExperiments(cuaVolume: true, yourCloud: false, sharing: false, webUi: true, secureSpaces: false, childSpaces: false)
let v = BridgeValue.encode(x) as? [String: Any]
#expect(v?["cuaVolume"] as? Bool == true)
#expect(v?["webUi"] as? Bool == true)
diff --git a/apps/cua-spaces-web/src/__tests__/settings-advanced.test.tsx b/apps/cua-spaces-web/src/__tests__/settings-advanced.test.tsx
index 7614c08f60..7826ea7c49 100644
--- a/apps/cua-spaces-web/src/__tests__/settings-advanced.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/settings-advanced.test.tsx
@@ -61,4 +61,11 @@ describe.skipIf(!wasmBuilt)("account usage and self-hosting in Settings (real ro
expect(form.querySelector('[data-host-field="relay"]')).toBeTruthy();
expect(form.querySelector('[data-host-field="direct"]')).toBeTruthy();
});
+
+ it("keeps the Secure Spaces and Child Spaces switches out of Labs until they are on", async () => {
+ const { router } = await mountApp("/settings/advanced", host);
+ await router.load();
+ await waitFor(() => expect(document.querySelector("[data-self-hosting]")).toBeTruthy());
+ expect(document.body.textContent).not.toMatch(/Secure Spaces|Child Spaces/);
+ });
});
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/experiments-defaults.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/experiments-defaults.test.ts
index d28b9ecb8f..7a069a2920 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/experiments-defaults.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/experiments-defaults.test.ts
@@ -6,7 +6,7 @@ import { readExperiments } from "../ops/volume";
describe("stored experiments", () => {
it("reads sharing and your cloud as on unless stored off, and the rest as off", () => {
- expect(readExperiments(undefined)).toEqual({ cuaVolume: false, yourCloud: true, sharing: true, webUi: false });
+ expect(readExperiments(undefined)).toEqual({ cuaVolume: false, yourCloud: true, sharing: true, webUi: false, secureSpaces: false, childSpaces: false });
expect(readExperiments(JSON.stringify({ cuaVolume: true }))).toMatchObject({ cuaVolume: true, sharing: true });
expect(readExperiments(JSON.stringify({ sharing: false }))).toMatchObject({ sharing: false });
expect(readExperiments(JSON.stringify({ yourCloud: false }))).toMatchObject({ yourCloud: false });
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/volume.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/volume.ts
index cca8057d77..d9b9ae19df 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo/volume.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/volume.ts
@@ -39,7 +39,7 @@ export interface DemoVolumeState {
export function demoVolumeState(now: number, onboarded: boolean, platform: DemoPlatform = MAC_DEMO_PLATFORM): DemoVolumeState {
return {
- experiments: { cuaVolume: true, yourCloud: true, sharing: true, webUi: false },
+ experiments: { cuaVolume: true, yourCloud: true, sharing: true, webUi: false, secureSpaces: false, childSpaces: false },
requests: [
{ id: "req-research", principal: "agent:researcher", prefix: "agents/writer/outputs/", mode: "r", reason: "Cite the launch draft in the weekly summary" },
],
diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
index 891cc2c6ee..3700e478f7 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -1679,6 +1679,12 @@
},
"webUi": {
"type": "boolean"
+ },
+ "secureSpaces": {
+ "type": "boolean"
+ },
+ "childSpaces": {
+ "type": "boolean"
}
}
},
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index c1fad318b8..a973512663 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -406,7 +406,7 @@ const SettingsShape = ref(
const ExperimentsShape = ref(
"Experiments",
- obj<Experiments>()({ cuaVolume: opt(bool), yourCloud: opt(bool), sharing: opt(bool), webUi: opt(bool) }),
+ obj<Experiments>()({ cuaVolume: opt(bool), yourCloud: opt(bool), sharing: opt(bool), webUi: opt(bool), secureSpaces: opt(bool), childSpaces: opt(bool) }),
);
const RepoCacheShape = ref(
diff --git a/apps/cua-spaces-web/src/bridge/contracts/volume.ts b/apps/cua-spaces-web/src/bridge/contracts/volume.ts
index e05d4d6bce..b683d121db 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/volume.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/volume.ts
@@ -28,9 +28,13 @@ export interface Experiments {
yourCloud?: boolean;
sharing?: boolean;
webUi?: boolean;
+ /** Secure Spaces: a Space reaches the internet and nothing else on the network unless opened. Off unless turned on; the daemon enforces it. */
+ secureSpaces?: boolean;
+ /** Child Spaces: a Space may make Spaces of its own. Off unless turned on; the daemon enforces it. */
+ childSpaces?: boolean;
}
-export const NO_EXPERIMENTS: Required<Experiments> = { cuaVolume: false, yourCloud: true, sharing: true, webUi: false };
+export const NO_EXPERIMENTS: Required<Experiments> = { cuaVolume: false, yourCloud: true, sharing: true, webUi: false, secureSpaces: false, childSpaces: false };
/* ---- The daemon's answers (volume_*) ---------------------------------------- */
diff --git a/apps/cua-spaces-web/src/bridge/ops/settings.ts b/apps/cua-spaces-web/src/bridge/ops/settings.ts
index cee357bbe0..fc788984c5 100644
--- a/apps/cua-spaces-web/src/bridge/ops/settings.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/settings.ts
@@ -318,6 +318,8 @@ const EXPERIMENT_ROWS: Record<keyof Experiments, string> = {
yourCloud: "experiment:your_cloud",
sharing: "experiment:sharing",
webUi: "experiment:web_ui",
+ secureSpaces: "experiment:secure_spaces",
+ childSpaces: "experiment:child_spaces",
};
/**
diff --git a/apps/cua-spaces-web/src/bridge/ops/volume.ts b/apps/cua-spaces-web/src/bridge/ops/volume.ts
index f80993026d..151c09bee2 100644
--- a/apps/cua-spaces-web/src/bridge/ops/volume.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/volume.ts
@@ -132,6 +132,8 @@ export function readExperiments(raw: string | undefined): Experiments {
yourCloud: stored.yourCloud !== false,
sharing: stored.sharing !== false,
webUi: stored.webUi === true,
+ secureSpaces: stored.secureSpaces === true,
+ childSpaces: stored.childSpaces === true,
};
} catch {
return NO_EXPERIMENTS;
diff --git a/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx b/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx
index 719d65acb0..7fd3a000f1 100644
--- a/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx
+++ b/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx
@@ -18,7 +18,13 @@ const SELF_HOSTED = "self-hosted";
const BETA_HELP = "New features sooner, with rough edges. Back on Stable, this version stays until a newer stable release.";
/** Experiments that stay as Labs. "Your cloud" and "Sharing" have no switch any more: the plan decides on the server. */
-const LABS = new Set(["experiment:cua_volume"]);
+const LABS = new Set(["experiment:cua_volume", "experiment:secure_spaces", "experiment:child_spaces"]);
+
+/** Experiments that have no switch here until they are on (`cua experiments enable <name>`): the app shows the switch once the experiment is on, so it can be turned off. */
+const SHOWN_ONCE_ON = new Set(["experiment:secure_spaces", "experiment:child_spaces"]);
+
+/** Whether a core switch row reads on. */
+const isOn = (r: CoreRow) => r.options.some((o) => o.id === "on" && o.active);
/**
* Settings, Advanced: early releases, Labs, which software runs Spaces on
@@ -134,9 +140,11 @@ function Labs() {
const { data, chooseExperiment } = useExperiments();
const askFirst = useFlag("spaces_ask_first_home");
const thisMacOk = useThisMacConfirmed();
- const rows = (data?.page?.sections.flatMap((s) => s.rows) ?? []).filter((r) => LABS.has(r.id));
+ const rows = (data?.page?.sections.flatMap((s) => s.rows) ?? []).filter((r) => LABS.has(r.id) && (!SHOWN_ONCE_ON.has(r.id) || isOn(r)));
const note: Record<string, string> = {
"experiment:cua_volume": "Memory and files your agents share across every Space.",
+ "experiment:secure_spaces": "A Space reaches the internet and nothing else on your network unless you open it.",
+ "experiment:child_spaces": "A Space can make Spaces of its own, inside a budget you set.",
};
return (
<SettingsGroup title="Labs">
diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lock
index 71ae9083eb..2f5450d023 100644
--- a/apps/cua-spaces/src-tauri/Cargo.lock
+++ b/apps/cua-spaces/src-tauri/Cargo.lock
@@ -1849,6 +1849,7 @@ dependencies = [
"cua-spacesd-client",
"cua-vmm",
"futures-util",
+ "hmac 0.12.1",
"http",
"http-body-util",
"humantime",
diff --git a/docs/content/docs/cua-cli/reference/cli/account-and-setup.mdx b/docs/content/docs/cua-cli/reference/cli/account-and-setup.mdx
index d6306f1d33..63270759ab 100644
--- a/docs/content/docs/cua-cli/reference/cli/account-and-setup.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/account-and-setup.mdx
@@ -42,6 +42,10 @@ description: "Sign in and out, user defaults, the cua daemon, health checks and
| [`cua telemetry show-last`](#cua-telemetry-show-last) | Print the last events this computer queued or sent, exactly as sent. |
| [`cua telemetry reset-id`](#cua-telemetry-reset-id) | Delete the anonymous install id and salt (new ones are created on the next event). |
| [`cua telemetry schema`](#cua-telemetry-schema) | Every event and property that may be sent, with its allowed values. |
+| [`cua experiments`](#cua-experiments) | Features that are still being built, one switch each: `list`, `enable`, `disable`. |
+| [`cua experiments list`](#cua-experiments-list) | Every experiment and whether it is on. |
+| [`cua experiments enable`](#cua-experiments-enable) | Turn an experiment on. |
+| [`cua experiments disable`](#cua-experiments-disable) | Turn an experiment off. |
Every command also accepts the [global options](/cua-cli/reference/cli#global-options).
@@ -587,6 +591,65 @@ cua telemetry schema [OPTIONS]
cua telemetry schema --json
```
+## `cua experiments`
+
+Features that are still being built, one switch each: `list`, `enable`, `disable`.
+
+```text output
+cua experiments [OPTIONS] <COMMAND>
+```
+
+### `cua experiments list`
+
+Every experiment and whether it is on.
+
+```text output
+cua experiments list [OPTIONS]
+```
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-experiments-list"
+cua experiments list
+cua experiments list --json
+```
+
+### `cua experiments enable`
+
+Turn an experiment on.
+
+```text output
+cua experiments enable [OPTIONS] <NAME>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<NAME>` | string | required | The experiment's name, as `cua experiments` lists it. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-experiments-enable"
+cua experiments enable secure-spaces
+```
+
+### `cua experiments disable`
+
+Turn an experiment off. Nothing it made is deleted.
+
+```text output
+cua experiments disable [OPTIONS] <NAME>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<NAME>` | string | required | The experiment's name, as `cua experiments` lists it. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-experiments-disable"
+cua experiments disable secure-spaces
+```
+
## Exit codes
| Code | Meaning |
diff --git a/docs/content/docs/cua-cli/reference/cli/computers-and-teams.mdx b/docs/content/docs/cua-cli/reference/cli/computers-and-teams.mdx
new file mode 100644
index 0000000000..0f680fb83e
--- /dev/null
+++ b/docs/content/docs/cua-cli/reference/cli/computers-and-teams.mdx
@@ -0,0 +1,1174 @@
+---
+title: "Computers and teams"
+description: "Your computers, unattended access on this computer, teams, sharing, your remote use this month, and a cua-spacesd by URL."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:cua-cli
+ Source: cua dump-docs --type cli
+ Version: 0.10.1
+*/}
+
+| Command | Description |
+| --- | --- |
+| [`cua machines`](#cua-machines) | Your computers on the relay: remove one that is gone. |
+| [`cua machines rm`](#cua-machines-rm) | Remove a computer that is gone: its row leaves your relay directory, then the signed-in device with exactly its name is revoked (never this device; nothing when several match). |
+| [`cua host`](#cua-host) | Unattended access to this computer (setup, status, stop, start, remove). |
+| [`cua host setup`](#cua-host-setup) | Set this computer up for unattended access: install cua-spacesd as a service that joins the cua.ai relay as your account (default) or serves on a direct ip:port. |
+| [`cua host pair`](#cua-host-pair) | Make a one-time code (with a link and the install command) that adds another computer to your account: run the command it prints on that computer. |
+| [`cua host config`](#cua-host-config) | Show or change what this computer shares: its own desktop, and whether it creates Spaces for your other devices. |
+| [`cua host cache`](#cua-host-cache) | What the repo cache holds, and empty it. |
+| [`cua host cache status`](#cua-host-cache-status) | What the repo cache holds: repositories, size and what the last week saved. |
+| [`cua host cache fill`](#cua-host-cache-fill) | Copy one public repository into the cache now, instead of when a Space first clones it (or bring a copy up to date). |
+| [`cua host cache clear`](#cua-host-cache-clear) | Delete every repository the cache holds. |
+| [`cua host status`](#cua-host-status) | Show whether this computer is set up, the service, and who is connected. |
+| [`cua host stop`](#cua-host-stop) | Stop sharing: disconnect everyone and refuse new connections. |
+| [`cua host start`](#cua-host-start) | Start sharing again after `stop`. |
+| [`cua host share`](#cua-host-share) | Share a relay computer (this one, or `--machine`) with people in your team (id or verified email). |
+| [`cua host unshare`](#cua-host-unshare) | Stop sharing a relay computer with accounts; their open connections are cut. |
+| [`cua host migrate`](#cua-host-migrate) | macOS: move the host service into the Cua Spaces app, as its "Cua Spaces Helper" login item, from the LaunchAgent that older versions installed. |
+| [`cua host remove`](#cua-host-remove) | Unregister from the relay, uninstall the service and delete the host configuration (asks first). |
+| [`cua devices`](#cua-devices) | This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what. |
+| [`cua devices status`](#cua-devices-status) | This device: enrolled, waiting for approval, or not enrolled. |
+| [`cua devices enroll`](#cua-devices-enroll) | Enroll this device. |
+| [`cua devices approve`](#cua-devices-approve) | Approve a new device (or re-verify an expired one) from this enrolled device, by the code it shows or by its id. |
+| [`cua devices ls`](#cua-devices-ls) | Your signed-in machines and their state. |
+| [`cua devices rename`](#cua-devices-rename) | Rename a device. |
+| [`cua devices revoke`](#cua-devices-revoke) | Revoke a device: it can no longer list or reach your computers. |
+| [`cua devices audit`](#cua-devices-audit) | Who accessed what, and when: enrollments, device sessions, computer access (yours and by accounts you share with), sharing changes. |
+| [`cua team`](#cua-team) | Teams (organizations of your cua.ai account) share computers with every member and their agents. |
+| [`cua team create`](#cua-team-create) | Create a team; you are its owner. |
+| [`cua team ls`](#cua-team-ls) | Your teams. |
+| [`cua team show`](#cua-team-show) | A team: plan, members, computers, open invites and devices. |
+| [`cua team invite`](#cua-team-invite) | Invite someone by email: cua.ai emails them an invitation. |
+| [`cua team join`](#cua-team-join) | After accepting an emailed invitation: take the role it offered. |
+| [`cua team leave`](#cua-team-leave) | Leave a team. |
+| [`cua team remove-member`](#cua-team-remove-member) | Remove a member (owner or admin; admins cannot remove admins). |
+| [`cua team set-role`](#cua-team-set-role) | Make a member an admin, or an admin a member (owner). |
+| [`cua team devices`](#cua-team-devices) | Member devices and whether they may open team computers. |
+| [`cua team approve`](#cua-team-approve) | Approve a member device so it can open team computers. |
+| [`cua team deny`](#cua-team-deny) | Decline a member device (it can no longer open team computers). |
+| [`cua team request`](#cua-team-request) | Ask the team's admins to approve this device. |
+| [`cua team add-machine`](#cua-team-add-machine) | Make a Space (or a computer you host) a team computer: every member and their agents see it and can open it. |
+| [`cua team remove-machine`](#cua-team-remove-machine) | Take a computer off the team. |
+| [`cua team audit`](#cua-team-audit) | The team's audit log. |
+| [`cua team delete`](#cua-team-delete) | Delete a team (owner; cancel its subscription first). |
+| [`cua usage`](#cua-usage) | Your remote use this month: live sessions, remote hours, and your plan. |
+| [`cua spacesd`](#cua-spacesd) | Talk to a cua-spacesd directly by URL. |
+| [`cua spacesd caps`](#cua-spacesd-caps) | Print capabilities. |
+| [`cua spacesd exec`](#cua-spacesd-exec) | Run a command (argv, no shell). |
+| [`cua spacesd cp`](#cua-spacesd-cp) | Copy files: `cua spacesd cp <URL> local :remote` uploads, `cua spacesd cp <URL> :remote local` downloads. |
+| [`cua spacesd shell`](#cua-spacesd-shell) | Interactive shell (PTY). |
+| [`cua spacesd targets`](#cua-spacesd-targets) | List streamable targets (displays, and windows with --windows). |
+| [`cua spacesd call`](#cua-spacesd-call) | Call any cua.env.v1 RPC with a proto3-JSON body. |
+| [`cua share`](#cua-share) | Share a link to a port, a file or a folder that opens on your other signed-in devices (never localhost): `cua share 3000`, `cua share ./report.html`, `cua share ls`, `cua share stop ID`. |
+| [`cua share ls`](#cua-share-ls) | List the active shares. |
+| [`cua share stop`](#cua-share-stop) | Stop a share (its link stops working at once), or `all`. |
+| [`cua share check`](#cua-share-check) | Open a share's link once, as its owner, and say what came back. |
+
+Every command also accepts the [global options](/cua-cli/reference/cli#global-options).
+
+## `cua machines`
+
+Your computers on the relay: remove one that is gone.
+
+```text output
+cua machines [OPTIONS] <COMMAND>
+```
+
+### `cua machines rm`
+
+Remove a computer that is gone: its row leaves your relay directory, then the signed-in device with exactly its name is revoked (never this device; nothing when several match). A computer that is connected now is refused: run `cua host remove` on it.
+
+```text output
+cua machines rm [OPTIONS] <NAME>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<NAME>` | string | required | The computer's name, machine id or `relay:<id>` (`cua spaces ls`). |
+
+| Flag | Short | Type | Default | Description |
+| --- | --- | --- | --- | --- |
+| <span id="cua-machines-rm--yes"></span>`--yes` | `-y` | boolean | `false` | Remove without asking. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-machines-rm"
+cua machines rm old-laptop
+cua machines rm relay:0123abcd4567ef89 --yes --json
+```
+
+## `cua host`
+
+Unattended access to this computer (setup, status, stop, start, remove).
+
+```text output
+cua host [OPTIONS] <COMMAND>
+```
+
+### `cua host setup`
+
+Set this computer up for unattended access: install cua-spacesd as a service that joins the cua.ai relay as your account (default) or serves on a direct ip:port. By default it shares this computer's desktop and, on a computer set up for the first time through the relay, provides Spaces to your devices (a host in your pool: `cua run` jobs and `--on auto` Spaces can run here, within its limits). `--share` picks what it shares: `desktop`, `spaces` (its own desktop stays private), `both` or `none`; `cua host config` changes it later. A computer set up before keeps what it provides. Running it again with the same options changes nothing (a stopped service starts again).
+
+```text output
+cua host setup [OPTIONS]
+```
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-host-setup--pair"></span>`--pair` | string | | Join with a one-time pairing code (or add-machine link) made in the Cua Spaces app or with `cua host pair`, instead of signing in here. The computer joins the account (or team) that made it. |
+| <span id="cua-host-setup--name"></span>`--name` | string | | Display name (default: the host name). |
+| <span id="cua-host-setup--allow"></span>`--allow` | string | | Also allow this account (id or email). Repeatable. |
+| <span id="cua-host-setup--driver-bin"></span>`--driver-bin` | path | | cua-spacesd binary (default $CUA_SPACESD_BIN, a bundled one, or the release download). |
+| <span id="cua-host-setup--runner"></span>`--runner` | string | `auto` | auto \| systemd \| launchd \| app-helper \| windows-task \| process. On a Mac with the Cua Spaces app, auto is app-helper: the service runs as the app's own login item ("Cua Spaces"). |
+| <span id="cua-host-setup--share"></span>`--share` | `desktop` \| `spaces` \| `both` \| `none` | | What this computer shares: its own desktop (screen, input, shell, files), the Spaces it creates for your enrolled devices (Lume macOS VMs, Docker Linux containers), both, or neither (refused). Default: the desktop, plus Spaces on a new relay setup; a computer set up before keeps what it provides. |
+| <span id="cua-host-setup--max-spaces"></span>`--max-spaces` | integer | | Provided Spaces at once (default 4; 0: no limit). |
+| <span id="cua-host-setup--remote"></span>`--remote` | boolean | `false` | When sign-in is needed, use a device code to approve it in a browser on another computer. The account session is not saved. |
+| <span id="cua-host-setup--dedicated"></span>`--dedicated` | boolean | `false` | This computer exists only for Cua work (a cloud instance made for it; `cua cloud add aws` sets its hosts up this way): jobs may run in its own Space (`kind = "machine"`), with its GPU and drivers as they are. Never on a computer you also use: there jobs run in macOS VMs or containers. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-setup"
+# Join the cua.ai relay as your account (shares this desktop and provides Spaces to your devices)
+cua host setup
+
+# Share this desktop only
+cua host setup --share desktop
+
+# A spare computer: do not share its desktop, run Spaces for your devices
+cua host setup --share spaces --name "Mac mini (spare)"
+
+# Add this computer with a one-time code from the Cua Spaces app (Add a computer) or `cua host pair`: no sign-in needed here
+cua host setup --pair K7QM-4XPB-2RHD
+```
+
+### `cua host pair`
+
+Make a one-time code (with a link and the install command) that adds another computer to your account: run the command it prints on that computer. Codes work once and expire (30 minutes by default). Run from an enrolled device.
+
+```text output
+cua host pair [OPTIONS]
+```
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-host-pair--team"></span>`--team` | string | | Add the computer to this team (id, alias or name; owner or admin): waits until the computer joins, then makes it a team computer. |
+| <span id="cua-host-pair--name"></span>`--name` | string | | Name the computer gets (default: its own host name). |
+| <span id="cua-host-pair--expires"></span>`--expires` | integer | `30` | Minutes until the code expires (1 to 1440). |
+| <span id="cua-host-pair--revoke"></span>`--revoke` | string | | Revoke an unused code by id (`pc_…`). |
+| <span id="cua-host-pair--no-wait"></span>`--no-wait` | boolean | `false` | With --team: print the code and exit instead of waiting; add the computer later with `cua team add-machine <team> relay:<id>`. |
+| <span id="cua-host-pair--list"></span>`--list` | boolean | `false` | List your codes (used, unused, revoked, expired) instead. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-pair"
+cua host pair
+cua host pair --name build-box --expires 60
+cua host pair --list
+cua host pair --revoke pc_0123456789abcdef
+
+# Add the computer to a team: waits for it to join, then adds it
+cua host pair --team AIGIS
+```
+
+### `cua host config`
+
+Show or change what this computer shares: its own desktop, and whether it creates Spaces for your other devices.
+
+```text output
+cua host config [OPTIONS]
+```
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-host-config--desktop"></span>`--desktop` | `on` \| `off` | | Share this computer's own desktop: on \| off. |
+| <span id="cua-host-config--provide-spaces"></span>`--provide-spaces` | `on` \| `off` | | Create Spaces for your enrolled devices: on \| off. |
+| <span id="cua-host-config--max-spaces"></span>`--max-spaces` | integer | | Provided Spaces at once (0: no limit). |
+| <span id="cua-host-config--max-macos-vms"></span>`--max-macos-vms` | integer | | macOS VMs at once, 0 to 2 (Apple's license allows two per Mac). |
+| <span id="cua-host-config--max-memory"></span>`--max-memory` | integer | | Memory in GB the Spaces other machines create here may use in total (0: no limit). |
+| <span id="cua-host-config--max-disk"></span>`--max-disk` | integer | | Disk in GB the Spaces other machines create here may use in total (0: no limit). |
+| <span id="cua-host-config--max-run-time"></span>`--max-run-time` | integer | | Minutes a Space created here by another machine may run before it is stopped (0: no limit). |
+| <span id="cua-host-config--repo-cache"></span>`--repo-cache` | `on` \| `off` | | The repo cache: on \| off. It keeps verified copies of public git repositories on this machine so a repeat `git clone` in a Space starts from one (never private repositories, never anything off this machine's disk). |
+| <span id="cua-host-config--repo-cache-size"></span>`--repo-cache-size` | string | | The most disk the repo cache may use, in GB (`auto`: the smaller of 5 GB and a tenth of the free disk). The least recently used repositories go first. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-config"
+cua host config
+
+# Stop sharing this desktop; keep providing Spaces
+cua host config --desktop off --provide-spaces on
+cua host config --max-spaces 6
+
+# Give the Spaces other machines create here at most 32 GB of memory and 200 GB of disk in total, and stop each after 8 hours (0: no limit)
+cua host config --max-memory 32 --max-disk 200 --max-run-time 480
+
+# Keep no copies of public git repositories on this machine, or at most 2 GB
+cua host config --repo-cache off
+cua host config --repo-cache on --repo-cache-size 2
+```
+
+### `cua host cache`
+
+What the repo cache holds, and empty it.
+
+```text output
+cua host cache [OPTIONS] <COMMAND>
+```
+
+#### `cua host cache status`
+
+What the repo cache holds: repositories, size and what the last week saved.
+
+```text output
+cua host cache status [OPTIONS]
+```
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-cache-status"
+cua host cache status
+```
+
+#### `cua host cache fill`
+
+Copy one public repository into the cache now, instead of when a Space first clones it (or bring a copy up to date). A repository that needs a sign-in is never cached.
+
+```text output
+cua host cache fill [OPTIONS] <URL>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<URL>` | string | required | The repository's `https` address. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-cache-fill"
+cua host cache fill https://github.com/vitejs/vite
+```
+
+#### `cua host cache clear`
+
+Delete every repository the cache holds. They are copied again the next time a Space clones them.
+
+```text output
+cua host cache clear [OPTIONS]
+```
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-cache-clear"
+cua host cache clear
+```
+
+### `cua host status`
+
+Show whether this computer is set up, the service, and who is connected.
+
+```text output
+cua host status [OPTIONS]
+```
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-status"
+cua host status
+```
+
+### `cua host stop`
+
+Stop sharing: disconnect everyone and refuse new connections.
+
+```text output
+cua host stop [OPTIONS]
+```
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-stop"
+cua host stop
+```
+
+### `cua host start`
+
+Start sharing again after `stop`.
+
+```text output
+cua host start [OPTIONS]
+```
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-start"
+cua host start
+```
+
+### `cua host share`
+
+Share a relay computer (this one, or `--machine`) with people in your team (id or verified email). Run from an enrolled device; every change is in the owner's audit log (`cua devices audit`).
+
+```text output
+cua host share [OPTIONS] <WHO>...
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<WHO>...` | string | required | Accounts to add. Repeatable. Repeatable. |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-host-share--machine"></span>`--machine` | string | | Computer id (default: this computer). Alias: `--computer`. |
+| <span id="cua-host-share--yes"></span>`--yes` | boolean | `false` | Do not ask for confirmation. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-share"
+cua host share [email protected]
+cua host share [email protected] --machine 0123abcd4567ef89 --yes
+```
+
+### `cua host unshare`
+
+Stop sharing a relay computer with accounts; their open connections are cut.
+
+```text output
+cua host unshare [OPTIONS] <WHO>...
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<WHO>...` | string | required | Accounts to remove. Repeatable. Repeatable. |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-host-unshare--machine"></span>`--machine` | string | | Computer id (default: this computer). Alias: `--computer`. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-unshare"
+cua host unshare [email protected]
+```
+
+### `cua host migrate`
+
+macOS: move the host service into the Cua Spaces app, as its "Cua Spaces Helper" login item, from the LaunchAgent that older versions installed. This machine keeps its id, registration and Spaces; if the helper does not take over, the old service is put back. macOS then asks once for Screen Recording and Accessibility for Cua Spaces Helper.
+
+```text output
+cua host migrate [OPTIONS]
+```
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-host-migrate--force"></span>`--force` | boolean | `false` | Try again even if a move failed before with this version. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-migrate"
+cua host migrate
+
+# Try again after a move that was rolled back
+cua host migrate --force
+```
+
+### `cua host remove`
+
+Unregister from the relay, uninstall the service and delete the host configuration (asks first).
+
+```text output
+cua host remove [OPTIONS]
+```
+
+| Flag | Short | Type | Default | Description |
+| --- | --- | --- | --- | --- |
+| <span id="cua-host-remove--force"></span>`--force` | `-f` | boolean | `false` | Skip the confirmation prompt. Required when there is no terminal to ask on (scripts, agents): without it nothing is removed. |
+| <span id="cua-host-remove--uninstalling"></span>`--uninstalling` | | boolean | `false` | For an uninstall of Cua Spaces: turns off the Spaces this computer provides and takes them off the relay too, instead of refusing while it provides any. The Spaces and their data stay on this computer. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-host-remove"
+cua host remove
+
+# Without the prompt (required in scripts and agents)
+cua host remove --force
+```
+
+## `cua devices`
+
+This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what.
+
+```text output
+cua devices [OPTIONS] <COMMAND>
+```
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-devices"
+cua devices enroll
+cua devices approve K7QX-M2RP
+cua devices ls
+cua devices audit
+```
+
+### `cua devices status`
+
+This device: enrolled, waiting for approval, or not enrolled.
+
+```text output
+cua devices status [OPTIONS]
+```
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-devices-status"
+cua devices status
+```
+
+### `cua devices enroll`
+
+Enroll this device. Right after a fresh `cua auth login` it enrolls at once (and replaces this computer's older device key, if any); otherwise it shows a one-time code to approve from an enrolled device (`cua devices approve <code>` or the Cua Spaces app).
+
+```text output
+cua devices enroll [OPTIONS]
+```
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-devices-enroll--name"></span>`--name` | string | | Display name (default: the host name). |
+| <span id="cua-devices-enroll--wait"></span>`--wait` | boolean | `false` | Wait (up to 10 minutes) until an enrolled device approves. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-devices-enroll"
+cua devices enroll
+cua devices enroll --name "work laptop" --wait
+```
+
+### `cua devices approve`
+
+Approve a new device (or re-verify an expired one) from this enrolled device, by the code it shows or by its id.
+
+```text output
+cua devices approve [OPTIONS] [CODE]
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<CODE>` | string | optional | The one-time code the new device shows, or its device id (`dev_…`, from `cua devices ls`). |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-devices-approve--device"></span>`--device` | string | | Or the device id (`cua devices ls`). |
+| <span id="cua-devices-approve--yes"></span>`--yes` | boolean | `false` | Do not ask for confirmation. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-devices-approve"
+cua devices approve K7QX-M2RP
+cua devices approve dev_0123456789abcdef01234567
+```
+
+### `cua devices ls`
+
+Your signed-in machines and their state.
+
+```text output
+cua devices ls [OPTIONS]
+```
+
+Alias: `cua devices list`.
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-devices-ls"
+cua devices ls
+cua devices ls --json
+```
+
+### `cua devices rename`
+
+Rename a device.
+
+```text output
+cua devices rename [OPTIONS] <ID> <NAME>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<ID>` | string | required | Device id. |
+| `<NAME>` | string | required | New name. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-devices-rename"
+cua devices rename dev_0123456789abcdef01234567 "work phone"
+```
+
+### `cua devices revoke`
+
+Revoke a device: it can no longer list or reach your computers.
+
+```text output
+cua devices revoke [OPTIONS] <ID>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<ID>` | string | required | Device id. |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-devices-revoke--yes"></span>`--yes` | boolean | `false` | Do not ask for confirmation. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-devices-revoke"
+cua devices revoke dev_0123456789abcdef01234567
+```
+
+### `cua devices audit`
+
+Who accessed what, and when: enrollments, device sessions, computer access (yours and by accounts you share with), sharing changes.
+
+```text output
+cua devices audit [OPTIONS]
+```
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-devices-audit--limit"></span>`--limit` | integer | `50` | Newest events to show. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-devices-audit"
+cua devices audit
+cua devices audit --limit 20 --json
+```
+
+## `cua team`
+
+Teams (organizations of your cua.ai account) share computers with every member and their agents. Owners and admins invite by email, approve member devices and add computers.
+
+```text output
+cua team [OPTIONS] <COMMAND>
+```
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team"
+cua team create AIGIS
+cua team invite AIGIS [email protected]
+cua team add-machine AIGIS local:build-box
+cua team approve AIGIS dev_0123456789abcdef01234567
+cua team show AIGIS
+```
+
+### `cua team create`
+
+Create a team; you are its owner. Buy Teams for it at app.cua.ai to add computers.
+
+```text output
+cua team create [OPTIONS] <NAME>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<NAME>` | string | required | Team name. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-create"
+cua team create "AIGIS"
+```
+
+### `cua team ls`
+
+Your teams.
+
+```text output
+cua team ls [OPTIONS]
+```
+
+Alias: `cua team list`.
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-ls"
+cua team ls
+cua team ls --json
+```
+
+### `cua team show`
+
+A team: plan, members, computers, open invites and devices.
+
+```text output
+cua team show [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-show"
+cua team show AIGIS
+```
+
+### `cua team invite`
+
+Invite someone by email: cua.ai emails them an invitation. Manage invites at app.cua.ai/team.
+
+```text output
+cua team invite [OPTIONS] <TEAM> <EMAIL>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+| `<EMAIL>` | string | required | Their email. |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-team-invite--role"></span>`--role` | `member` \| `admin` | `member` | `member` or `admin` (only the owner invites admins). |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-invite"
+cua team invite AIGIS [email protected]
+cua team invite AIGIS [email protected] --role admin
+```
+
+### `cua team join`
+
+After accepting an emailed invitation: take the role it offered. Run `cua auth login` first so your session lists the team.
+
+```text output
+cua team join [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-join"
+cua team join AIGIS
+```
+
+### `cua team leave`
+
+Leave a team.
+
+```text output
+cua team leave [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-leave"
+cua team leave AIGIS
+```
+
+### `cua team remove-member`
+
+Remove a member (owner or admin; admins cannot remove admins).
+
+```text output
+cua team remove-member [OPTIONS] <TEAM> <WHO>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+| `<WHO>` | string | required | Their email or account id. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-remove-member"
+cua team remove-member AIGIS [email protected]
+```
+
+### `cua team set-role`
+
+Make a member an admin, or an admin a member (owner).
+
+```text output
+cua team set-role [OPTIONS] <TEAM> <WHO> <ROLE>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+| `<WHO>` | string | required | Their email or account id. |
+| `<ROLE>` | `member` \| `admin` | required | `member` or `admin`. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-set-role"
+cua team set-role AIGIS [email protected] admin
+```
+
+### `cua team devices`
+
+Member devices and whether they may open team computers.
+
+```text output
+cua team devices [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-devices"
+cua team devices AIGIS
+```
+
+### `cua team approve`
+
+Approve a member device so it can open team computers.
+
+```text output
+cua team approve [OPTIONS] <TEAM> <DEVICE>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+| `<DEVICE>` | string | required | Device id (`cua team devices`). |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-approve"
+cua team approve AIGIS dev_0123456789abcdef01234567
+```
+
+### `cua team deny`
+
+Decline a member device (it can no longer open team computers).
+
+```text output
+cua team deny [OPTIONS] <TEAM> <DEVICE>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+| `<DEVICE>` | string | required | Device id. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-deny"
+cua team deny AIGIS dev_0123456789abcdef01234567
+```
+
+### `cua team request`
+
+Ask the team's admins to approve this device.
+
+```text output
+cua team request [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-request"
+cua team request AIGIS
+```
+
+### `cua team add-machine`
+
+Make a Space (or a computer you host) a team computer: every member and their agents see it and can open it. Macs, Linux and Windows computers all can. Each Space is added on its own: adding a host does not add the Spaces it provides.
+
+```text output
+cua team add-machine [OPTIONS] <TEAM> <SPACE>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+| `<SPACE>` | string | required | Space id or name (`relay:<id>` for a computer you host). |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-team-add-machine--yes"></span>`--yes` | boolean | `false` | Confirm without a prompt. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-add-machine"
+cua team add-machine AIGIS local:build-box
+cua team add-machine AIGIS relay:0123abcd4567ef89 --yes
+```
+
+### `cua team remove-machine`
+
+Take a computer off the team.
+
+```text output
+cua team remove-machine [OPTIONS] <TEAM> <COMPUTER>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+| `<COMPUTER>` | string | required | The computer (`relay:<id>` or its id, as `cua team show` lists it). |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-remove-machine"
+cua team remove-machine AIGIS relay:0123abcd4567ef89
+```
+
+### `cua team audit`
+
+The team's audit log. Audit export is coming soon; for now see the account app (app.cua.ai).
+
+```text output
+cua team audit [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-team-audit--limit"></span>`--limit` | integer | `50` | Newest events to show (when export arrives). |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-audit"
+cua team audit AIGIS
+```
+
+### `cua team delete`
+
+Delete a team (owner; cancel its subscription first). Its computers stay yours.
+
+```text output
+cua team delete [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id, alias or name. |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-team-delete--yes"></span>`--yes` | boolean | `false` | Do not ask for confirmation. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-delete"
+cua team delete AIGIS --yes
+```
+
+## `cua usage`
+
+Your remote use this month: live sessions, remote hours, and your plan. Remote hours are time spent using your computers from somewhere else; using a computer from itself is free.
+
+```text output
+cua usage [OPTIONS]
+```
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-usage"
+cua usage
+cua usage --json
+```
+
+## `cua spacesd`
+
+Talk to a cua-spacesd directly by URL.
+
+```text output
+cua spacesd [OPTIONS] <COMMAND>
+```
+
+### `cua spacesd caps`
+
+Print capabilities.
+
+```text output
+cua spacesd caps [OPTIONS] <URL>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<URL>` | string | required | spacesd URL (`http://host:port`). |
+
+| Flag | Type | Default | Env var | Description |
+| --- | --- | --- | --- | --- |
+| <span id="cua-spacesd-caps--token"></span>`--token` | string | | `CUA_ENV_TOKEN` | spacesd token. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-spacesd-caps"
+cua spacesd caps http://127.0.0.1:3211
+```
+
+### `cua spacesd exec`
+
+Run a command (argv, no shell).
+
+```text output
+cua spacesd exec [OPTIONS] <URL> <COMMAND>...
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<URL>` | string | required | spacesd URL (`http://host:port`). |
+| `<COMMAND>...` | string | required | Program and arguments. Repeatable. |
+
+| Flag | Short | Type | Default | Env var | Description |
+| --- | --- | --- | --- | --- | --- |
+| <span id="cua-spacesd-exec--user"></span>`--user` | | string | | | Run as this guest user. |
+| <span id="cua-spacesd-exec--cwd"></span>`--cwd` | | string | | | Start in this guest directory. |
+| <span id="cua-spacesd-exec--timeout"></span>`--timeout` | | integer | | | Stop the command after this many seconds (0: no limit). |
+| <span id="cua-spacesd-exec--token"></span>`--token` | | string | | `CUA_ENV_TOKEN` | spacesd token. |
+| <span id="cua-spacesd-exec--stdin"></span>`--stdin` | `-i` | boolean | `false` | | Stream: run the command as argv (no shell), forward this command's stdin, write stdout and stderr as they arrive, set no time limit, pass SIGINT/SIGTERM/SIGHUP on, and kill the command when this process ends. Exits with the command's status (128 + n for signal n). |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-spacesd-exec"
+cua spacesd exec http://127.0.0.1:3211 uname -a
+
+# A long-lived stdio stream (stdin forwarded, no time limit, killed with this command)
+cua spacesd exec -i http://127.0.0.1:3211 cat
+```
+
+### `cua spacesd cp`
+
+Copy files: `cua spacesd cp <URL> local :remote` uploads, `cua spacesd cp <URL> :remote local` downloads.
+
+```text output
+cua spacesd cp [OPTIONS] <URL> <SRC> <DST>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<URL>` | string | required | spacesd URL (`http://host:port`). |
+| `<SRC>` | string | required | Source: a local path, or `:/guest/path`. |
+| `<DST>` | string | required | Destination: a local path, or `:/guest/path`. |
+
+| Flag | Type | Default | Env var | Description |
+| --- | --- | --- | --- | --- |
+| <span id="cua-spacesd-cp--token"></span>`--token` | string | | `CUA_ENV_TOKEN` | spacesd token. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-spacesd-cp"
+# Upload
+cua spacesd cp http://127.0.0.1:3211 ./notes.txt :/tmp/notes.txt
+
+# Download
+cua spacesd cp http://127.0.0.1:3211 :/tmp/notes.txt ./notes.txt
+```
+
+### `cua spacesd shell`
+
+Interactive shell (PTY).
+
+```text output
+cua spacesd shell [OPTIONS] <URL>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<URL>` | string | required | spacesd URL (`http://host:port`). |
+
+| Flag | Type | Default | Env var | Description |
+| --- | --- | --- | --- | --- |
+| <span id="cua-spacesd-shell--token"></span>`--token` | string | | `CUA_ENV_TOKEN` | spacesd token. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-spacesd-shell"
+cua spacesd shell http://127.0.0.1:3211
+```
+
+### `cua spacesd targets`
+
+List streamable targets (displays, and windows with --windows).
+
+```text output
+cua spacesd targets [OPTIONS] <URL>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<URL>` | string | required | spacesd URL (`http://host:port`). |
+
+| Flag | Type | Default | Env var | Description |
+| --- | --- | --- | --- | --- |
+| <span id="cua-spacesd-targets--token"></span>`--token` | string | | `CUA_ENV_TOKEN` | spacesd token. |
+| <span id="cua-spacesd-targets--windows"></span>`--windows` | boolean | `false` | | Include window targets. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-spacesd-targets"
+cua spacesd targets http://127.0.0.1:3211 --windows
+```
+
+### `cua spacesd call`
+
+Call any cua.env.v1 RPC with a proto3-JSON body.
+
+```text output
+cua spacesd call [OPTIONS] <URL> <METHOD> [BODY]
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<URL>` | string | required | spacesd URL (`http://host:port`). |
+| `<METHOD>` | string | required | `Service/Method`. |
+| `<BODY>` | string | `{}` | Request body (proto3 JSON). |
+
+| Flag | Type | Default | Env var | Description |
+| --- | --- | --- | --- | --- |
+| <span id="cua-spacesd-call--token"></span>`--token` | string | | `CUA_ENV_TOKEN` | spacesd token. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-spacesd-call"
+cua spacesd call http://127.0.0.1:3211 SystemService/GetCapabilities
+```
+
+## `cua share`
+
+Share a link to a port, a file or a folder that opens on your other signed-in devices (never localhost): `cua share 3000`, `cua share ./report.html`, `cua share ls`, `cua share stop ID`.
+
+```text output
+cua share [OPTIONS] <TARGET>
+ cua share <COMMAND>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TARGET>` | string | required | What to share: a port (`3000`), a port in a Space (`space:NAME:3000`), or a file or folder (`./report.html`, `./build/`). Paths are read-only; use `./ls` for a file called `ls`. |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-share--ttl"></span>`--ttl` | string | | How long the share lasts (`10m`, `1h`, 60s to 24h). Public shares default to 1h; the others have no end unless you set one. |
+| <span id="cua-share--name"></span>`--name` | string | | A name for `cua share ls` (and `cua share stop NAME`). |
+| <span id="cua-share--team"></span>`--team` | boolean | `false` | Share with the members of your team. |
+| <span id="cua-share--public"></span>`--public` | boolean | `false` | Anyone with the link can open it. Expires (default 1h, 60s to 24h). |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-share"
+# A dev server on this machine, for your own devices (phone included)
+cua share 3000
+
+# A port inside a Space
+cua share space:dev:3000
+
+# A report or a folder, read-only
+cua share ./report.html
+cua share ./build/
+
+# Members of your team
+cua share 3000 --team
+
+# Anyone with the link, for an hour
+cua share ./report.html --public --ttl 1h
+
+# What is shared, and stop it
+cua share ls
+cua share stop share-1a2b3c4d5e6f
+cua share stop all
+```
+
+### `cua share ls`
+
+List the active shares.
+
+```text output
+cua share ls [OPTIONS]
+```
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-share-ls"
+# What is shared right now
+cua share ls
+
+# The same as JSON
+cua share ls --json
+```
+
+### `cua share stop`
+
+Stop a share (its link stops working at once), or `all`.
+
+```text output
+cua share stop [OPTIONS] <ID>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<ID>` | string | required | The share's id or name from `cua share ls`, or `all`. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-share-stop"
+# Stop one share by its id
+cua share stop share-1a2b3c4d5e6f
+
+# Stop everything this machine shares
+cua share stop all
+```
+
+### `cua share check`
+
+Open a share's link once, as its owner, and say what came back.
+
+```text output
+cua share check [OPTIONS] <ID> [PATH]
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<ID>` | string | required | The share's id or name. |
+| `<PATH>` | string | optional | A path below the link to open. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-share-check"
+# Does the link load?
+cua share check share-1a2b3c4d5e6f
+
+# Open a page below the link
+cua share check share-1a2b3c4d5e6f /index.html
+```
+
+## Exit codes
+
+| Code | Meaning |
+| --- | --- |
+| `0` | Success. |
+| `1` | Failure, or `cua do` reported an error. |
+| `2` | Invalid argument, or an ambiguous sandbox name (qualify it: `local:NAME`). |
+| `3` | Not found: sandbox, window, skill or image (or an image not published yet). |
+| `4` | Not supported, or not configured (for example no provider credentials). |
+| `5` | No cua-spacesd answered, or a transport failure. |
+| `6` | Unauthenticated or permission denied (by Cua or your cloud account). |
+| `7` | Not enough free disk space (see `cua cache`). |
+| `8` | No room on the machine: its VMs are at their memory or CPU limit, or it is low on memory. |
+| `130` | Cancelled (Ctrl-C during a create): what it made was removed. |
diff --git a/docs/content/docs/cua-cli/reference/cli/index.mdx b/docs/content/docs/cua-cli/reference/cli/index.mdx
index d78fd23cad..5b8d8ca60c 100644
--- a/docs/content/docs/cua-cli/reference/cli/index.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/index.mdx
@@ -18,20 +18,28 @@ Run `cua <command> --help` for the build you have.
## Commands
-### Spaces, computers and teams
+### Spaces
-Your Spaces and machines, unattended access on this machine, devices, teams, your remote use this month, and a cua-spacesd by URL. [Reference](/cua-cli/reference/cli/spaces-and-computers).
+Your Spaces, what they can reach, and keeping commands running in them. [Reference](/cua-cli/reference/cli/spaces-and-computers).
| Command | Description | Subcommands |
| --- | --- | --- |
-| <span id="cua-spaces"></span><span id="cua-spaces-ls"></span><span id="cua-spaces-add"></span><span id="cua-spaces-create"></span><span id="cua-spaces-prewarm"></span><span id="cua-spaces-egress"></span><span id="cua-spaces-cancel"></span><span id="cua-spaces-gpus"></span><span id="cua-spaces-delete"></span><span id="cua-spaces-stop"></span><span id="cua-spaces-suspend"></span><span id="cua-spaces-resize"></span><span id="cua-spaces-start"></span><span id="cua-spaces-rm"></span><span id="cua-spaces-rename"></span><span id="cua-spaces-share"></span><span id="cua-spaces-unshare"></span><span id="cua-spaces-shares"></span><span id="cua-spaces-relay-register"></span><span id="cua-spaces-relay-unregister"></span>[`cua spaces`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces) | Spaces: registered ones and your computers on the relay. | [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-ls), [`add`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-add), [`create`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-create), [`prewarm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-prewarm), [`egress`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-egress), [`cancel`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-cancel), [`gpus`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-gpus), [`delete`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-delete), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-stop), [`suspend`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-suspend), [`resize`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-resize), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-start), [`rm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rm), [`rename`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rename), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-unshare), [`shares`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-shares), [`relay-register`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-register), [`relay-unregister`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-unregister) |
-| <span id="cua-machines"></span><span id="cua-machines-rm"></span>[`cua machines`](/cua-cli/reference/cli/spaces-and-computers#cua-machines) | Your computers on the relay: remove one that is gone. | [`rm`](/cua-cli/reference/cli/spaces-and-computers#cua-machines-rm) |
-| <span id="cua-host"></span><span id="cua-host-setup"></span><span id="cua-host-pair"></span><span id="cua-host-config"></span><span id="cua-host-cache"></span><span id="cua-host-cache-status"></span><span id="cua-host-cache-fill"></span><span id="cua-host-cache-clear"></span><span id="cua-host-status"></span><span id="cua-host-stop"></span><span id="cua-host-start"></span><span id="cua-host-share"></span><span id="cua-host-unshare"></span><span id="cua-host-migrate"></span><span id="cua-host-remove"></span>[`cua host`](/cua-cli/reference/cli/spaces-and-computers#cua-host) | Unattended access to this computer (setup, status, stop, start, remove). | [`setup`](/cua-cli/reference/cli/spaces-and-computers#cua-host-setup), [`pair`](/cua-cli/reference/cli/spaces-and-computers#cua-host-pair), [`config`](/cua-cli/reference/cli/spaces-and-computers#cua-host-config), [`cache`](/cua-cli/reference/cli/spaces-and-computers#cua-host-cache), [`cache status`](/cua-cli/reference/cli/spaces-and-computers#cua-host-cache-status), [`cache fill`](/cua-cli/reference/cli/spaces-and-computers#cua-host-cache-fill), [`cache clear`](/cua-cli/reference/cli/spaces-and-computers#cua-host-cache-clear), [`status`](/cua-cli/reference/cli/spaces-and-computers#cua-host-status), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-host-stop), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-host-start), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-host-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-host-unshare), [`migrate`](/cua-cli/reference/cli/spaces-and-computers#cua-host-migrate), [`remove`](/cua-cli/reference/cli/spaces-and-computers#cua-host-remove) |
-| <span id="cua-devices"></span><span id="cua-devices-status"></span><span id="cua-devices-enroll"></span><span id="cua-devices-approve"></span><span id="cua-devices-ls"></span><span id="cua-devices-rename"></span><span id="cua-devices-revoke"></span><span id="cua-devices-audit"></span>[`cua devices`](/cua-cli/reference/cli/spaces-and-computers#cua-devices) | This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what. | [`status`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-status), [`enroll`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-enroll), [`approve`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-approve), [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-ls), [`rename`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-rename), [`revoke`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-revoke), [`audit`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-audit) |
-| <span id="cua-team"></span><span id="cua-team-create"></span><span id="cua-team-ls"></span><span id="cua-team-show"></span><span id="cua-team-invite"></span><span id="cua-team-join"></span><span id="cua-team-leave"></span><span id="cua-team-remove-member"></span><span id="cua-team-set-role"></span><span id="cua-team-devices"></span><span id="cua-team-approve"></span><span id="cua-team-deny"></span><span id="cua-team-request"></span><span id="cua-team-add-machine"></span><span id="cua-team-remove-machine"></span><span id="cua-team-audit"></span><span id="cua-team-delete"></span>[`cua team`](/cua-cli/reference/cli/spaces-and-computers#cua-team) | Teams (organizations of your cua.ai account) share computers with every member and their agents. | [`create`](/cua-cli/reference/cli/spaces-and-computers#cua-team-create), [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-team-ls), [`show`](/cua-cli/reference/cli/spaces-and-computers#cua-team-show), [`invite`](/cua-cli/reference/cli/spaces-and-computers#cua-team-invite), [`join`](/cua-cli/reference/cli/spaces-and-computers#cua-team-join), [`leave`](/cua-cli/reference/cli/spaces-and-computers#cua-team-leave), [`remove-member`](/cua-cli/reference/cli/spaces-and-computers#cua-team-remove-member), [`set-role`](/cua-cli/reference/cli/spaces-and-computers#cua-team-set-role), [`devices`](/cua-cli/reference/cli/spaces-and-computers#cua-team-devices), [`approve`](/cua-cli/reference/cli/spaces-and-computers#cua-team-approve), [`deny`](/cua-cli/reference/cli/spaces-and-computers#cua-team-deny), [`request`](/cua-cli/reference/cli/spaces-and-computers#cua-team-request), [`add-machine`](/cua-cli/reference/cli/spaces-and-computers#cua-team-add-machine), [`remove-machine`](/cua-cli/reference/cli/spaces-and-computers#cua-team-remove-machine), [`audit`](/cua-cli/reference/cli/spaces-and-computers#cua-team-audit), [`delete`](/cua-cli/reference/cli/spaces-and-computers#cua-team-delete) |
-| <span id="cua-usage"></span>[`cua usage`](/cua-cli/reference/cli/spaces-and-computers#cua-usage) | Your remote use this month: live sessions, remote hours, and your plan. | |
-| <span id="cua-spacesd"></span><span id="cua-spacesd-caps"></span><span id="cua-spacesd-exec"></span><span id="cua-spacesd-cp"></span><span id="cua-spacesd-shell"></span><span id="cua-spacesd-targets"></span><span id="cua-spacesd-call"></span>[`cua spacesd`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd) | Talk to a cua-spacesd directly by URL. | [`caps`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd-caps), [`exec`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd-exec), [`cp`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd-cp), [`shell`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd-shell), [`targets`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd-targets), [`call`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd-call) |
-| <span id="cua-share"></span><span id="cua-share-ls"></span><span id="cua-share-stop"></span><span id="cua-share-check"></span>[`cua share`](/cua-cli/reference/cli/spaces-and-computers#cua-share) | Share a link to a port, a file or a folder that opens on your other signed-in devices (never localhost): `cua share 3000`, `cua share ./report.html`, `cua share ls`, `cua share stop ID`. | [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-share-ls), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-share-stop), [`check`](/cua-cli/reference/cli/spaces-and-computers#cua-share-check) |
+| <span id="cua-spaces"></span><span id="cua-spaces-ls"></span><span id="cua-spaces-add"></span><span id="cua-spaces-create"></span><span id="cua-spaces-prewarm"></span><span id="cua-spaces-egress"></span><span id="cua-spaces-children"></span><span id="cua-spaces-budget"></span><span id="cua-spaces-orphans"></span><span id="cua-spaces-service"></span><span id="cua-spaces-service-add"></span><span id="cua-spaces-service-ls"></span><span id="cua-spaces-service-logs"></span><span id="cua-spaces-service-start"></span><span id="cua-spaces-service-stop"></span><span id="cua-spaces-service-restart"></span><span id="cua-spaces-service-rm"></span><span id="cua-spaces-cancel"></span><span id="cua-spaces-gpus"></span><span id="cua-spaces-delete"></span><span id="cua-spaces-stop"></span><span id="cua-spaces-suspend"></span><span id="cua-spaces-resize"></span><span id="cua-spaces-start"></span><span id="cua-spaces-rm"></span><span id="cua-spaces-rename"></span><span id="cua-spaces-share"></span><span id="cua-spaces-unshare"></span><span id="cua-spaces-shares"></span><span id="cua-spaces-relay-register"></span><span id="cua-spaces-relay-unregister"></span>[`cua spaces`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces) | Spaces: registered ones and your computers on the relay. | [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-ls), [`add`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-add), [`create`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-create), [`prewarm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-prewarm), [`egress`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-egress), [`children`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-children), [`budget`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-budget), [`orphans`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-orphans), [`service`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service), [`service add`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-add), [`service ls`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-ls), [`service logs`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-logs), [`service start`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-start), [`service stop`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-stop), [`service restart`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-restart), [`service rm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-rm), [`cancel`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-cancel), [`gpus`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-gpus), [`delete`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-delete), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-stop), [`suspend`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-suspend), [`resize`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-resize), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-start), [`rm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rm), [`rename`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rename), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-unshare), [`shares`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-shares), [`relay-register`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-register), [`relay-unregister`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-unregister) |
+| <span id="cua-network"></span><span id="cua-network-show"></span><span id="cua-network-set"></span><span id="cua-network-log"></span>[`cua network`](/cua-cli/reference/cli/spaces-and-computers#cua-network) | What a Space can reach on the network, and changing it: `show`, `set`, `log`. | [`show`](/cua-cli/reference/cli/spaces-and-computers#cua-network-show), [`set`](/cua-cli/reference/cli/spaces-and-computers#cua-network-set), [`log`](/cua-cli/reference/cli/spaces-and-computers#cua-network-log) |
+
+### Computers and teams
+
+Your computers, unattended access on this computer, teams, sharing, your remote use this month, and a cua-spacesd by URL. [Reference](/cua-cli/reference/cli/computers-and-teams).
+
+| Command | Description | Subcommands |
+| --- | --- | --- |
+| <span id="cua-machines"></span><span id="cua-machines-rm"></span>[`cua machines`](/cua-cli/reference/cli/computers-and-teams#cua-machines) | Your computers on the relay: remove one that is gone. | [`rm`](/cua-cli/reference/cli/computers-and-teams#cua-machines-rm) |
+| <span id="cua-host"></span><span id="cua-host-setup"></span><span id="cua-host-pair"></span><span id="cua-host-config"></span><span id="cua-host-cache"></span><span id="cua-host-cache-status"></span><span id="cua-host-cache-fill"></span><span id="cua-host-cache-clear"></span><span id="cua-host-status"></span><span id="cua-host-stop"></span><span id="cua-host-start"></span><span id="cua-host-share"></span><span id="cua-host-unshare"></span><span id="cua-host-migrate"></span><span id="cua-host-remove"></span>[`cua host`](/cua-cli/reference/cli/computers-and-teams#cua-host) | Unattended access to this computer (setup, status, stop, start, remove). | [`setup`](/cua-cli/reference/cli/computers-and-teams#cua-host-setup), [`pair`](/cua-cli/reference/cli/computers-and-teams#cua-host-pair), [`config`](/cua-cli/reference/cli/computers-and-teams#cua-host-config), [`cache`](/cua-cli/reference/cli/computers-and-teams#cua-host-cache), [`cache status`](/cua-cli/reference/cli/computers-and-teams#cua-host-cache-status), [`cache fill`](/cua-cli/reference/cli/computers-and-teams#cua-host-cache-fill), [`cache clear`](/cua-cli/reference/cli/computers-and-teams#cua-host-cache-clear), [`status`](/cua-cli/reference/cli/computers-and-teams#cua-host-status), [`stop`](/cua-cli/reference/cli/computers-and-teams#cua-host-stop), [`start`](/cua-cli/reference/cli/computers-and-teams#cua-host-start), [`share`](/cua-cli/reference/cli/computers-and-teams#cua-host-share), [`unshare`](/cua-cli/reference/cli/computers-and-teams#cua-host-unshare), [`migrate`](/cua-cli/reference/cli/computers-and-teams#cua-host-migrate), [`remove`](/cua-cli/reference/cli/computers-and-teams#cua-host-remove) |
+| <span id="cua-devices"></span><span id="cua-devices-status"></span><span id="cua-devices-enroll"></span><span id="cua-devices-approve"></span><span id="cua-devices-ls"></span><span id="cua-devices-rename"></span><span id="cua-devices-revoke"></span><span id="cua-devices-audit"></span>[`cua devices`](/cua-cli/reference/cli/computers-and-teams#cua-devices) | This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what. | [`status`](/cua-cli/reference/cli/computers-and-teams#cua-devices-status), [`enroll`](/cua-cli/reference/cli/computers-and-teams#cua-devices-enroll), [`approve`](/cua-cli/reference/cli/computers-and-teams#cua-devices-approve), [`ls`](/cua-cli/reference/cli/computers-and-teams#cua-devices-ls), [`rename`](/cua-cli/reference/cli/computers-and-teams#cua-devices-rename), [`revoke`](/cua-cli/reference/cli/computers-and-teams#cua-devices-revoke), [`audit`](/cua-cli/reference/cli/computers-and-teams#cua-devices-audit) |
+| <span id="cua-team"></span><span id="cua-team-create"></span><span id="cua-team-ls"></span><span id="cua-team-show"></span><span id="cua-team-invite"></span><span id="cua-team-join"></span><span id="cua-team-leave"></span><span id="cua-team-remove-member"></span><span id="cua-team-set-role"></span><span id="cua-team-devices"></span><span id="cua-team-approve"></span><span id="cua-team-deny"></span><span id="cua-team-request"></span><span id="cua-team-add-machine"></span><span id="cua-team-remove-machine"></span><span id="cua-team-audit"></span><span id="cua-team-delete"></span>[`cua team`](/cua-cli/reference/cli/computers-and-teams#cua-team) | Teams (organizations of your cua.ai account) share computers with every member and their agents. | [`create`](/cua-cli/reference/cli/computers-and-teams#cua-team-create), [`ls`](/cua-cli/reference/cli/computers-and-teams#cua-team-ls), [`show`](/cua-cli/reference/cli/computers-and-teams#cua-team-show), [`invite`](/cua-cli/reference/cli/computers-and-teams#cua-team-invite), [`join`](/cua-cli/reference/cli/computers-and-teams#cua-team-join), [`leave`](/cua-cli/reference/cli/computers-and-teams#cua-team-leave), [`remove-member`](/cua-cli/reference/cli/computers-and-teams#cua-team-remove-member), [`set-role`](/cua-cli/reference/cli/computers-and-teams#cua-team-set-role), [`devices`](/cua-cli/reference/cli/computers-and-teams#cua-team-devices), [`approve`](/cua-cli/reference/cli/computers-and-teams#cua-team-approve), [`deny`](/cua-cli/reference/cli/computers-and-teams#cua-team-deny), [`request`](/cua-cli/reference/cli/computers-and-teams#cua-team-request), [`add-machine`](/cua-cli/reference/cli/computers-and-teams#cua-team-add-machine), [`remove-machine`](/cua-cli/reference/cli/computers-and-teams#cua-team-remove-machine), [`audit`](/cua-cli/reference/cli/computers-and-teams#cua-team-audit), [`delete`](/cua-cli/reference/cli/computers-and-teams#cua-team-delete) |
+| <span id="cua-usage"></span>[`cua usage`](/cua-cli/reference/cli/computers-and-teams#cua-usage) | Your remote use this month: live sessions, remote hours, and your plan. | |
+| <span id="cua-spacesd"></span><span id="cua-spacesd-caps"></span><span id="cua-spacesd-exec"></span><span id="cua-spacesd-cp"></span><span id="cua-spacesd-shell"></span><span id="cua-spacesd-targets"></span><span id="cua-spacesd-call"></span>[`cua spacesd`](/cua-cli/reference/cli/computers-and-teams#cua-spacesd) | Talk to a cua-spacesd directly by URL. | [`caps`](/cua-cli/reference/cli/computers-and-teams#cua-spacesd-caps), [`exec`](/cua-cli/reference/cli/computers-and-teams#cua-spacesd-exec), [`cp`](/cua-cli/reference/cli/computers-and-teams#cua-spacesd-cp), [`shell`](/cua-cli/reference/cli/computers-and-teams#cua-spacesd-shell), [`targets`](/cua-cli/reference/cli/computers-and-teams#cua-spacesd-targets), [`call`](/cua-cli/reference/cli/computers-and-teams#cua-spacesd-call) |
+| <span id="cua-share"></span><span id="cua-share-ls"></span><span id="cua-share-stop"></span><span id="cua-share-check"></span>[`cua share`](/cua-cli/reference/cli/computers-and-teams#cua-share) | Share a link to a port, a file or a folder that opens on your other signed-in devices (never localhost): `cua share 3000`, `cua share ./report.html`, `cua share ls`, `cua share stop ID`. | [`ls`](/cua-cli/reference/cli/computers-and-teams#cua-share-ls), [`stop`](/cua-cli/reference/cli/computers-and-teams#cua-share-stop), [`check`](/cua-cli/reference/cli/computers-and-teams#cua-share-check) |
### Files, teleport and keys
@@ -101,6 +109,7 @@ Sign in and out, user defaults, the cua daemon, health checks and usage telemetr
| <span id="cua-daemon"></span><span id="cua-daemon-start"></span><span id="cua-daemon-stop"></span><span id="cua-daemon-reap"></span><span id="cua-daemon-status"></span><span id="cua-daemon-mcp"></span>[`cua daemon`](/cua-cli/reference/cli/account-and-setup#cua-daemon) | The cua daemon. | [`start`](/cua-cli/reference/cli/account-and-setup#cua-daemon-start), [`stop`](/cua-cli/reference/cli/account-and-setup#cua-daemon-stop), [`reap`](/cua-cli/reference/cli/account-and-setup#cua-daemon-reap), [`status`](/cua-cli/reference/cli/account-and-setup#cua-daemon-status), [`mcp`](/cua-cli/reference/cli/account-and-setup#cua-daemon-mcp) |
| <span id="cua-doctor"></span><span id="cua-doctor-parity"></span>[`cua doctor`](/cua-cli/reference/cli/account-and-setup#cua-doctor) | Check the host, an image and a sandbox's guest in one report (`cua doctor [REF]`), or eval parity between two variants (`cua doctor parity A B`). | [`parity`](/cua-cli/reference/cli/account-and-setup#cua-doctor-parity) |
| <span id="cua-telemetry"></span><span id="cua-telemetry-status"></span><span id="cua-telemetry-on"></span><span id="cua-telemetry-off"></span><span id="cua-telemetry-show-last"></span><span id="cua-telemetry-reset-id"></span><span id="cua-telemetry-schema"></span>[`cua telemetry`](/cua-cli/reference/cli/account-and-setup#cua-telemetry) | Anonymous usage telemetry (status, on, off, show-last, reset-id, schema). | [`status`](/cua-cli/reference/cli/account-and-setup#cua-telemetry-status), [`on`](/cua-cli/reference/cli/account-and-setup#cua-telemetry-on), [`off`](/cua-cli/reference/cli/account-and-setup#cua-telemetry-off), [`show-last`](/cua-cli/reference/cli/account-and-setup#cua-telemetry-show-last), [`reset-id`](/cua-cli/reference/cli/account-and-setup#cua-telemetry-reset-id), [`schema`](/cua-cli/reference/cli/account-and-setup#cua-telemetry-schema) |
+| <span id="cua-experiments"></span><span id="cua-experiments-list"></span><span id="cua-experiments-enable"></span><span id="cua-experiments-disable"></span>[`cua experiments`](/cua-cli/reference/cli/account-and-setup#cua-experiments) | Features that are still being built, one switch each: `list`, `enable`, `disable`. | [`list`](/cua-cli/reference/cli/account-and-setup#cua-experiments-list), [`enable`](/cua-cli/reference/cli/account-and-setup#cua-experiments-enable), [`disable`](/cua-cli/reference/cli/account-and-setup#cua-experiments-disable) |
### Your pool
diff --git a/docs/content/docs/cua-cli/reference/cli/meta.json b/docs/content/docs/cua-cli/reference/cli/meta.json
index eb7d234096..a1ad7aeb1a 100644
--- a/docs/content/docs/cua-cli/reference/cli/meta.json
+++ b/docs/content/docs/cua-cli/reference/cli/meta.json
@@ -3,6 +3,7 @@
"pages": [
"index",
"spaces-and-computers",
+ "computers-and-teams",
"files-teleport-and-keys",
"sandboxes",
"images-and-clouds",
diff --git a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx
index 4c8d95c197..58cbe9f40c 100644
--- a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx
@@ -1,6 +1,6 @@
---
-title: "Spaces, computers and teams"
-description: "Your Spaces and machines, unattended access on this machine, devices, teams, your remote use this month, and a cua-spacesd by URL."
+title: "Spaces"
+description: "Your Spaces, what they can reach, and keeping commands running in them."
---
{/*
@@ -18,6 +18,17 @@ description: "Your Spaces and machines, unattended access on this machine, devic
| [`cua spaces create`](#cua-spaces-create) | Create Spaces: on this computer, on one of your computers that provides Spaces (`cua host setup --share spaces` there), or in your own cloud account. |
| [`cua spaces prewarm`](#cua-spaces-prewarm) | Keep Spaces of one image ready where the elastic pool puts them, so the next creates of that shape start in a fraction of a second (`--list` shows the prewarms, `--remove ID` ends one). |
| [`cua spaces egress`](#cua-spaces-egress) | Choose which destinations a Space may reach: block some, or block everything except a few. |
+| [`cua spaces children`](#cua-spaces-children) | Let a Space make child Spaces of its own, or stop it. |
+| [`cua spaces budget`](#cua-spaces-budget) | Show or set a tree's budget: how many child Spaces, vCPUs and memory its children may hold at once, and what they may cost. |
+| [`cua spaces orphans`](#cua-spaces-orphans) | List child Spaces whose parent is gone or out of reach. |
+| [`cua spaces service`](#cua-spaces-service) | Keep a command running in a Space: started again when it exits or fails its health check (with a backoff), started when the Space boots, its output kept in a log file in the Space. |
+| [`cua spaces service add`](#cua-spaces-service-add) | Keep a command running (replaces a service of that name). |
+| [`cua spaces service ls`](#cua-spaces-service-ls) | List a Space's services. |
+| [`cua spaces service logs`](#cua-spaces-service-logs) | Show the end of a service's log. |
+| [`cua spaces service start`](#cua-spaces-service-start) | Start a stopped service. |
+| [`cua spaces service stop`](#cua-spaces-service-stop) | Stop a service and keep it stopped. |
+| [`cua spaces service restart`](#cua-spaces-service-restart) | Restart a service. |
+| [`cua spaces service rm`](#cua-spaces-service-rm) | Stop a service and forget it. |
| [`cua spaces cancel`](#cua-spaces-cancel) | Cancel a create that is still running (here, in the daemon, or in another terminal): it stops and what it made is removed. |
| [`cua spaces gpus`](#cua-spaces-gpus) | The GPU options each runtime offers on this computer (or in your own cloud account). |
| [`cua spaces delete`](#cua-spaces-delete) | Delete a Space's sandbox (on this computer, on the computer that provides it, or in your own cloud account) and forget it (asks first). |
@@ -32,60 +43,10 @@ description: "Your Spaces and machines, unattended access on this machine, devic
| [`cua spaces shares`](#cua-spaces-shares) | Who a Space is shared with, and who of them is connected now. |
| [`cua spaces relay-register`](#cua-spaces-relay-register) | Publish a Space on the relay for your other devices (a phone off this network): its own driver dials out, as `cua host setup` does for this computer. |
| [`cua spaces relay-unregister`](#cua-spaces-relay-unregister) | Take a Space off the relay (every share with it ends). |
-| [`cua machines`](#cua-machines) | Your computers on the relay: remove one that is gone. |
-| [`cua machines rm`](#cua-machines-rm) | Remove a computer that is gone: its row leaves your relay directory, then the signed-in device with exactly its name is revoked (never this device; nothing when several match). |
-| [`cua host`](#cua-host) | Unattended access to this computer (setup, status, stop, start, remove). |
-| [`cua host setup`](#cua-host-setup) | Set this computer up for unattended access: install cua-spacesd as a service that joins the cua.ai relay as your account (default) or serves on a direct ip:port. |
-| [`cua host pair`](#cua-host-pair) | Make a one-time code (with a link and the install command) that adds another computer to your account: run the command it prints on that computer. |
-| [`cua host config`](#cua-host-config) | Show or change what this computer shares: its own desktop, and whether it creates Spaces for your other devices. |
-| [`cua host cache`](#cua-host-cache) | What the repo cache holds, and empty it. |
-| [`cua host cache status`](#cua-host-cache-status) | What the repo cache holds: repositories, size and what the last week saved. |
-| [`cua host cache fill`](#cua-host-cache-fill) | Copy one public repository into the cache now, instead of when a Space first clones it (or bring a copy up to date). |
-| [`cua host cache clear`](#cua-host-cache-clear) | Delete every repository the cache holds. |
-| [`cua host status`](#cua-host-status) | Show whether this computer is set up, the service, and who is connected. |
-| [`cua host stop`](#cua-host-stop) | Stop sharing: disconnect everyone and refuse new connections. |
-| [`cua host start`](#cua-host-start) | Start sharing again after `stop`. |
-| [`cua host share`](#cua-host-share) | Share a relay computer (this one, or `--machine`) with people in your team (id or verified email). |
-| [`cua host unshare`](#cua-host-unshare) | Stop sharing a relay computer with accounts; their open connections are cut. |
-| [`cua host migrate`](#cua-host-migrate) | macOS: move the host service into the Cua Spaces app, as its "Cua Spaces Helper" login item, from the LaunchAgent that older versions installed. |
-| [`cua host remove`](#cua-host-remove) | Unregister from the relay, uninstall the service and delete the host configuration (asks first). |
-| [`cua devices`](#cua-devices) | This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what. |
-| [`cua devices status`](#cua-devices-status) | This device: enrolled, waiting for approval, or not enrolled. |
-| [`cua devices enroll`](#cua-devices-enroll) | Enroll this device. |
-| [`cua devices approve`](#cua-devices-approve) | Approve a new device (or re-verify an expired one) from this enrolled device, by the code it shows or by its id. |
-| [`cua devices ls`](#cua-devices-ls) | Your signed-in machines and their state. |
-| [`cua devices rename`](#cua-devices-rename) | Rename a device. |
-| [`cua devices revoke`](#cua-devices-revoke) | Revoke a device: it can no longer list or reach your computers. |
-| [`cua devices audit`](#cua-devices-audit) | Who accessed what, and when: enrollments, device sessions, computer access (yours and by accounts you share with), sharing changes. |
-| [`cua team`](#cua-team) | Teams (organizations of your cua.ai account) share computers with every member and their agents. |
-| [`cua team create`](#cua-team-create) | Create a team; you are its owner. |
-| [`cua team ls`](#cua-team-ls) | Your teams. |
-| [`cua team show`](#cua-team-show) | A team: plan, members, computers, open invites and devices. |
-| [`cua team invite`](#cua-team-invite) | Invite someone by email: cua.ai emails them an invitation. |
-| [`cua team join`](#cua-team-join) | After accepting an emailed invitation: take the role it offered. |
-| [`cua team leave`](#cua-team-leave) | Leave a team. |
-| [`cua team remove-member`](#cua-team-remove-member) | Remove a member (owner or admin; admins cannot remove admins). |
-| [`cua team set-role`](#cua-team-set-role) | Make a member an admin, or an admin a member (owner). |
-| [`cua team devices`](#cua-team-devices) | Member devices and whether they may open team computers. |
-| [`cua team approve`](#cua-team-approve) | Approve a member device so it can open team computers. |
-| [`cua team deny`](#cua-team-deny) | Decline a member device (it can no longer open team computers). |
-| [`cua team request`](#cua-team-request) | Ask the team's admins to approve this device. |
-| [`cua team add-machine`](#cua-team-add-machine) | Make a Space (or a computer you host) a team computer: every member and their agents see it and can open it. |
-| [`cua team remove-machine`](#cua-team-remove-machine) | Take a computer off the team. |
-| [`cua team audit`](#cua-team-audit) | The team's audit log. |
-| [`cua team delete`](#cua-team-delete) | Delete a team (owner; cancel its subscription first). |
-| [`cua usage`](#cua-usage) | Your remote use this month: live sessions, remote hours, and your plan. |
-| [`cua spacesd`](#cua-spacesd) | Talk to a cua-spacesd directly by URL. |
-| [`cua spacesd caps`](#cua-spacesd-caps) | Print capabilities. |
-| [`cua spacesd exec`](#cua-spacesd-exec) | Run a command (argv, no shell). |
-| [`cua spacesd cp`](#cua-spacesd-cp) | Copy files: `cua spacesd cp <URL> local :remote` uploads, `cua spacesd cp <URL> :remote local` downloads. |
-| [`cua spacesd shell`](#cua-spacesd-shell) | Interactive shell (PTY). |
-| [`cua spacesd targets`](#cua-spacesd-targets) | List streamable targets (displays, and windows with --windows). |
-| [`cua spacesd call`](#cua-spacesd-call) | Call any cua.env.v1 RPC with a proto3-JSON body. |
-| [`cua share`](#cua-share) | Share a link to a port, a file or a folder that opens on your other signed-in devices (never localhost): `cua share 3000`, `cua share ./report.html`, `cua share ls`, `cua share stop ID`. |
-| [`cua share ls`](#cua-share-ls) | List the active shares. |
-| [`cua share stop`](#cua-share-stop) | Stop a share (its link stops working at once), or `all`. |
-| [`cua share check`](#cua-share-check) | Open a share's link once, as its owner, and say what came back. |
+| [`cua network`](#cua-network) | What a Space can reach on the network, and changing it: `show`, `set`, `log`. |
+| [`cua network show`](#cua-network-show) | What a Space can reach: its preset, what it opens, where it is enforced, and what is always blocked. |
+| [`cua network set`](#cua-network-set) | Change what a Space can reach. |
+| [`cua network log`](#cua-network-log) | What a Space tried to reach and was blocked, most recent first. |
Every command also accepts the [global options](/cua-cli/reference/cli#global-options).
@@ -115,6 +76,7 @@ Alias: `cua spaces list`.
| --- | --- | --- | --- |
| <span id="cua-spaces-ls--label"></span>`--label` | string | | Only Spaces with this label (`key=value`; repeat to require several). Repeatable. |
| <span id="cua-spaces-ls--no-size"></span>`--no-size` | boolean | `false` | Do not measure what each Space takes on this computer's disk (that walk can take a moment with many Spaces). |
+| <span id="cua-spaces-ls--tree"></span>`--tree` | boolean | `false` | List child Spaces under their parent, indented (otherwise the parent's row counts them). |
**Examples**
@@ -184,10 +146,14 @@ cua spaces create [OPTIONS] [IMAGE]
| <span id="cua-spaces-create--region"></span>`--region` | string | | The cloud region or location of that host (default: the pool picks, near you). |
| <span id="cua-spaces-create--volume"></span>`--volume` | string | | Mount a named volume of Cua Volume in the Space: `NAME:PATH[:ro]`, or `NAME/SUBFOLDER:PATH[:ro]` for a folder of it. Repeat for several. Make one with `cua volume named create`. Repeatable. |
| <span id="cua-spaces-create--label"></span>`--label` | string | | A label to keep with the Space (`key=value`; repeat for more; up to 64, keys up to 63 bytes, values up to 256, none empty). Not with `--durable`. Repeatable. |
-| <span id="cua-spaces-create--egress-deny"></span>`--egress-deny` | string | | Block this destination from the guest's first instruction (IP, CIDR or `all`; repeat for more). Enforced by the host, outside the guest. See `cua spaces egress`. Repeatable. |
-| <span id="cua-spaces-create--egress-allow"></span>`--egress-allow` | string | | Keep this destination reachable where --egress-deny blocks it. Repeatable. |
+| <span id="cua-spaces-create--network"></span>`--network` | string | | Its network: `internet` (the default: the internet and its own tree; this computer, your local network, cloud metadata and other trees are blocked), `none`, `localhost:5432,3000` (also this computer's localhost on those ports), `lan` (also your local network), `custom` / `custom:none` (with --allow/--deny), or `unprotected` (No protection). Enforced by the host, outside the guest. See `cua network`. |
+| <span id="cua-spaces-create--deny"></span>`--deny` | string | | Block this destination (IP, CIDR or `all`; repeat for more). Alias: `--egress-deny`. Repeatable. |
+| <span id="cua-spaces-create--allow"></span>`--allow` | string | | Allow this destination, also where a block covers it (IP or CIDR; repeat for more). Alias: `--egress-allow`. Repeatable. |
+| <span id="cua-spaces-create--parent"></span>`--parent` | string | | Create it as a child of this Space: it joins the parent's tree (they reach each other) and its network is no more open than the parent's. With `--parent`, the children are deleted, stopped and suspended with it. |
| <span id="cua-spaces-create--durable"></span>`--durable` | boolean | `false` | Keep it on your machines (with `--on auto`): when its machine goes away it is created again on another one, with the same name (its disk starts fresh). `cua spaces delete <name>` deletes it for good. |
+| <span id="cua-spaces-create--children"></span>`--children` | boolean | `false` | Let it make child Spaces of its own: `cua`, the SDKs and the agent's tools in it create, list and delete Spaces that belong to it, on this computer, never wider than it (`cua spaces children`). Agent runs turn this on by themselves. |
| <span id="cua-spaces-create--forkable"></span>`--forkable` | boolean | `false` | A fork source (a "bake" Space): a local QEMU VM's guest RAM is a shared file, so `cua sb checkpoint` takes milliseconds and forks of its checkpoints share its pages. Other kinds ignore it. |
+| <span id="cua-spaces-create--widen"></span>`--widen` | boolean | `false` | With --parent: let its network be more open than its parent's (recorded on the Space). |
**Examples**
@@ -280,1388 +246,602 @@ cua spaces egress studio --deny all --allow 1.1.1.1 --allow 203.0.113.0/24
cua spaces egress studio --clear
```
-### `cua spaces cancel`
-
-Cancel a create that is still running (here, in the daemon, or in another terminal): it stops and what it made is removed. Finished image downloads stay cached. Ctrl-C during `cua spaces create` does the same.
-
-```text output
-cua spaces cancel [OPTIONS] <SPACE>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | The id the Space will have (`local:<name>`, printed when the create starts) or its name. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-cancel"
-cua spaces cancel local:space-1a2b3c
-cua spaces cancel studio
-```
-
-### `cua spaces gpus`
-
-The GPU options each runtime offers on this computer (or in your own cloud account).
-
-```text output
-cua spaces gpus [OPTIONS]
-```
-
-| Flag | Type | Default | Description |
-| --- | --- | --- | --- |
-| <span id="cua-spaces-gpus--on"></span>`--on` | string | | `local` (default), `aws`, `gcp` or `modal`. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-gpus"
-cua spaces gpus
-cua spaces gpus --json
-```
-
-### `cua spaces delete`
-
-Delete a Space's sandbox (on this computer, on the computer that provides it, or in your own cloud account) and forget it (asks first).
-
-```text output
-cua spaces delete [OPTIONS] <SPACE>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | Space id or name. |
-
-| Flag | Short | Type | Default | Description |
-| --- | --- | --- | --- | --- |
-| <span id="cua-spaces-delete--force"></span>`--force` | `-f` | boolean | `false` | Skip the confirmation (required without a terminal). |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-delete"
-cua spaces delete relay:space-0123456789abcdef
-cua spaces delete local:studio --force
-```
-
-### `cua spaces stop`
-
-Turn a Space off: a local VM (QEMU or Lume) or a Space one of your computers provides is stopped, keeping its disk and freeing its memory, and so is a Space in your own cloud (`--on aws`, `gcp`: compute billing stops; `hetzner`: still billed). A local container is stopped or suspended as its runtime can. `cua spaces suspend` keeps a local Space's memory instead. Modal sandboxes and Spaces added by address cannot be turned off.
-
-```text output
-cua spaces stop [OPTIONS] <SPACE>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | Space id or name. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-stop"
-cua spaces stop local:studio
-cua spaces stop relay:space-0123456789abcdef --json
-```
-
-### `cua spaces suspend`
-
-Suspend a local Space (a container or QEMU VM): its memory is kept, and stays in use, so it resumes where it was with `cua spaces start`. `cua spaces stop` frees the memory instead.
-
-```text output
-cua spaces suspend [OPTIONS] <SPACE>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | Space id or name. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-suspend"
-cua spaces suspend local:studio
-```
-
-### `cua spaces resize`
-
-Give a local VM Space more or fewer vCPUs, more or less memory, or a bigger disk. It shuts down and boots again from its own disk (a stopped one boots): its files stay, its running processes do not. A disk never shrinks.
-
-```text output
-cua spaces resize [OPTIONS] <SPACE>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | Space id or name. |
-
-| Flag | Type | Default | Description |
-| --- | --- | --- | --- |
-| <span id="cua-spaces-resize--cpus"></span>`--cpus` | integer | | vCPUs. |
-| <span id="cua-spaces-resize--memory-mb"></span>`--memory-mb` | integer | | Memory in MiB. |
-| <span id="cua-spaces-resize--disk-gb"></span>`--disk-gb` | integer | | Grow the disk to this many GiB. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-resize"
-cua spaces resize local:builder --memory-mb 24576
-cua spaces resize builder --cpus 8 --disk-gb 200 --json
-```
-
-### `cua spaces start`
-
-Turn a Space back on: resume a suspended one or boot a stopped one.
-
-```text output
-cua spaces start [OPTIONS] <SPACE>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | Space id or name. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-start"
-cua spaces start local:studio
-cua spaces start studio --json
-```
-
-### `cua spaces rm`
-
-Forget a registered Space and its stored token. The sandbox keeps running. A Space cua created (on this computer or in a cloud) is refused while its sandbox exists: use `cua spaces delete` (or `stop`). The `relay:<computer>` record of a Space that registered itself and is gone (not connected) also leaves your relay directory.
-
-```text output
-cua spaces rm [OPTIONS] <SPACE>
-```
-
-Alias: `cua spaces remove`.
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | Space id, address or display name (as `cua spaces ls` shows). |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-rm"
-cua spaces rm direct:10.0.0.5:3211
-cua spaces rm studio
-```
-
-### `cua spaces rename`
-
-Give a Space a new name; its id stays the same. Lowercase letters, digits and dashes, as at create. A Space you shared, or one of your computers provides, is renamed on the relay too, so your other devices and the people it is shared with see the new name. Only its owner can rename a Space.
-
-```text output
-cua spaces rename [OPTIONS] <SPACE> <NAME>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | Space id or name (as `cua spaces ls` shows). |
-| `<NAME>` | string | required | The new name. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-rename"
-cua spaces rename local:studio design-review
-cua spaces rename relay:space-0123456789abcdef ci-runner
-```
-
-### `cua spaces share`
-
-Let someone in your team watch (viewer) or use (editor) a Space, through the relay. They open it as `relay:<computer>`. Sharing is for teams: you need a team, and they must be in it (or share with the whole team as `team:<id>`).
-
-```text output
-cua spaces share [OPTIONS] <SPACE> <WHO>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | Space id, address or display name. |
-| `<WHO>` | string | required | Their email (verified by cua.ai) or account id, in your team; or `team:<id>` for the whole team. |
-
-| Flag | Short | Type | Default | Description |
-| --- | --- | --- | --- | --- |
-| <span id="cua-spaces-share--role"></span>`--role` | | `viewer` \| `editor` | `viewer` | `viewer`: presence and a view-only stream. `editor`: full use. |
-| <span id="cua-spaces-share--yes"></span>`--yes` | `-y` | boolean | `false` | Confirm without a terminal prompt. Without a daemon the share happens at once. A running daemon still asks with Touch ID or your password on this computer; without a terminal, `--yes` says someone will answer there (otherwise the command fails at once instead of waiting for a prompt nobody sees). |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-share"
-cua spaces share local:studio [email protected]
-cua spaces share local:studio [email protected] --role editor
-cua spaces share relay:0123abcd4567ef89 acct-42 --role viewer
-
-# The whole team, to watch
-cua spaces share local:studio team:acme --role viewer
-
-# From a script or agent: confirm with Touch ID or your password here
-cua spaces share local:studio [email protected] --yes
-```
-
-### `cua spaces unshare`
-
-Stop sharing a Space with one account at once, or with everyone.
-
-```text output
-cua spaces unshare [OPTIONS] <SPACE> [WHO]
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | Space id, address or display name. |
-| `<WHO>` | string | optional | Their email or account id. |
-
-| Flag | Type | Default | Description |
-| --- | --- | --- | --- |
-| <span id="cua-spaces-unshare--all"></span>`--all` | boolean | `false` | Stop sharing with everyone (the Space leaves the relay). |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-unshare"
-cua spaces unshare local:studio [email protected]
-cua spaces unshare local:studio --all
-```
-
-### `cua spaces shares`
-
-Who a Space is shared with, and who of them is connected now.
-
-```text output
-cua spaces shares [OPTIONS] <SPACE>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | Space id, address or display name. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-shares"
-cua spaces shares local:studio
-cua spaces shares local:studio --json
-```
-
-### `cua spaces relay-register`
-
-Publish a Space on the relay for your other devices (a phone off this network): its own driver dials out, as `cua host setup` does for this computer. Nobody else gets in until you share it.
-
-```text output
-cua spaces relay-register [OPTIONS] <SPACE>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | Space id, address or display name. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-relay-register"
-cua spaces relay-register local:studio
-```
-
-### `cua spaces relay-unregister`
-
-Take a Space off the relay (every share with it ends). With a `relay:<computer>` id, removes that computer's record from your relay directory: a Space that registered itself (also after it was deleted), or a computer of yours that is gone. Only its owner can.
-
-```text output
-cua spaces relay-unregister [OPTIONS] <SPACE>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<SPACE>` | string | required | Space id, address or display name. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spaces-relay-unregister"
-cua spaces relay-unregister local:studio
-cua spaces relay-unregister relay:space-0123abcd4567ef89
-```
-
-## `cua machines`
-
-Your computers on the relay: remove one that is gone.
-
-```text output
-cua machines [OPTIONS] <COMMAND>
-```
-
-### `cua machines rm`
-
-Remove a computer that is gone: its row leaves your relay directory, then the signed-in device with exactly its name is revoked (never this device; nothing when several match). A computer that is connected now is refused: run `cua host remove` on it.
-
-```text output
-cua machines rm [OPTIONS] <NAME>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<NAME>` | string | required | The computer's name, machine id or `relay:<id>` (`cua spaces ls`). |
-
-| Flag | Short | Type | Default | Description |
-| --- | --- | --- | --- | --- |
-| <span id="cua-machines-rm--yes"></span>`--yes` | `-y` | boolean | `false` | Remove without asking. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-machines-rm"
-cua machines rm old-laptop
-cua machines rm relay:0123abcd4567ef89 --yes --json
-```
-
-## `cua host`
-
-Unattended access to this computer (setup, status, stop, start, remove).
-
-```text output
-cua host [OPTIONS] <COMMAND>
-```
-
-### `cua host setup`
-
-Set this computer up for unattended access: install cua-spacesd as a service that joins the cua.ai relay as your account (default) or serves on a direct ip:port. By default it shares this computer's desktop and, on a computer set up for the first time through the relay, provides Spaces to your devices (a host in your pool: `cua run` jobs and `--on auto` Spaces can run here, within its limits). `--share` picks what it shares: `desktop`, `spaces` (its own desktop stays private), `both` or `none`; `cua host config` changes it later. A computer set up before keeps what it provides. Running it again with the same options changes nothing (a stopped service starts again).
-
-```text output
-cua host setup [OPTIONS]
-```
-
-| Flag | Type | Default | Description |
-| --- | --- | --- | --- |
-| <span id="cua-host-setup--pair"></span>`--pair` | string | | Join with a one-time pairing code (or add-machine link) made in the Cua Spaces app or with `cua host pair`, instead of signing in here. The computer joins the account (or team) that made it. |
-| <span id="cua-host-setup--name"></span>`--name` | string | | Display name (default: the host name). |
-| <span id="cua-host-setup--allow"></span>`--allow` | string | | Also allow this account (id or email). Repeatable. |
-| <span id="cua-host-setup--driver-bin"></span>`--driver-bin` | path | | cua-spacesd binary (default $CUA_SPACESD_BIN, a bundled one, or the release download). |
-| <span id="cua-host-setup--runner"></span>`--runner` | string | `auto` | auto \| systemd \| launchd \| app-helper \| windows-task \| process. On a Mac with the Cua Spaces app, auto is app-helper: the service runs as the app's own login item ("Cua Spaces"). |
-| <span id="cua-host-setup--share"></span>`--share` | `desktop` \| `spaces` \| `both` \| `none` | | What this computer shares: its own desktop (screen, input, shell, files), the Spaces it creates for your enrolled devices (Lume macOS VMs, Docker Linux containers), both, or neither (refused). Default: the desktop, plus Spaces on a new relay setup; a computer set up before keeps what it provides. |
-| <span id="cua-host-setup--max-spaces"></span>`--max-spaces` | integer | | Provided Spaces at once (default 4; 0: no limit). |
-| <span id="cua-host-setup--remote"></span>`--remote` | boolean | `false` | When sign-in is needed, use a device code to approve it in a browser on another computer. The account session is not saved. |
-| <span id="cua-host-setup--dedicated"></span>`--dedicated` | boolean | `false` | This computer exists only for Cua work (a cloud instance made for it; `cua cloud add aws` sets its hosts up this way): jobs may run in its own Space (`kind = "machine"`), with its GPU and drivers as they are. Never on a computer you also use: there jobs run in macOS VMs or containers. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-setup"
-# Join the cua.ai relay as your account (shares this desktop and provides Spaces to your devices)
-cua host setup
-
-# Share this desktop only
-cua host setup --share desktop
-
-# A spare computer: do not share its desktop, run Spaces for your devices
-cua host setup --share spaces --name "Mac mini (spare)"
-
-# Add this computer with a one-time code from the Cua Spaces app (Add a computer) or `cua host pair`: no sign-in needed here
-cua host setup --pair K7QM-4XPB-2RHD
-```
-
-### `cua host pair`
-
-Make a one-time code (with a link and the install command) that adds another computer to your account: run the command it prints on that computer. Codes work once and expire (30 minutes by default). Run from an enrolled device.
-
-```text output
-cua host pair [OPTIONS]
-```
-
-| Flag | Type | Default | Description |
-| --- | --- | --- | --- |
-| <span id="cua-host-pair--team"></span>`--team` | string | | Add the computer to this team (id, alias or name; owner or admin): waits until the computer joins, then makes it a team computer. |
-| <span id="cua-host-pair--name"></span>`--name` | string | | Name the computer gets (default: its own host name). |
-| <span id="cua-host-pair--expires"></span>`--expires` | integer | `30` | Minutes until the code expires (1 to 1440). |
-| <span id="cua-host-pair--revoke"></span>`--revoke` | string | | Revoke an unused code by id (`pc_…`). |
-| <span id="cua-host-pair--no-wait"></span>`--no-wait` | boolean | `false` | With --team: print the code and exit instead of waiting; add the computer later with `cua team add-machine <team> relay:<id>`. |
-| <span id="cua-host-pair--list"></span>`--list` | boolean | `false` | List your codes (used, unused, revoked, expired) instead. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-pair"
-cua host pair
-cua host pair --name build-box --expires 60
-cua host pair --list
-cua host pair --revoke pc_0123456789abcdef
-
-# Add the computer to a team: waits for it to join, then adds it
-cua host pair --team AIGIS
-```
-
-### `cua host config`
-
-Show or change what this computer shares: its own desktop, and whether it creates Spaces for your other devices.
-
-```text output
-cua host config [OPTIONS]
-```
-
-| Flag | Type | Default | Description |
-| --- | --- | --- | --- |
-| <span id="cua-host-config--desktop"></span>`--desktop` | `on` \| `off` | | Share this computer's own desktop: on \| off. |
-| <span id="cua-host-config--provide-spaces"></span>`--provide-spaces` | `on` \| `off` | | Create Spaces for your enrolled devices: on \| off. |
-| <span id="cua-host-config--max-spaces"></span>`--max-spaces` | integer | | Provided Spaces at once (0: no limit). |
-| <span id="cua-host-config--max-macos-vms"></span>`--max-macos-vms` | integer | | macOS VMs at once, 0 to 2 (Apple's license allows two per Mac). |
-| <span id="cua-host-config--max-memory"></span>`--max-memory` | integer | | Memory in GB the Spaces other machines create here may use in total (0: no limit). |
-| <span id="cua-host-config--max-disk"></span>`--max-disk` | integer | | Disk in GB the Spaces other machines create here may use in total (0: no limit). |
-| <span id="cua-host-config--max-run-time"></span>`--max-run-time` | integer | | Minutes a Space created here by another machine may run before it is stopped (0: no limit). |
-| <span id="cua-host-config--repo-cache"></span>`--repo-cache` | `on` \| `off` | | The repo cache: on \| off. It keeps verified copies of public git repositories on this machine so a repeat `git clone` in a Space starts from one (never private repositories, never anything off this machine's disk). |
-| <span id="cua-host-config--repo-cache-size"></span>`--repo-cache-size` | string | | The most disk the repo cache may use, in GB (`auto`: the smaller of 5 GB and a tenth of the free disk). The least recently used repositories go first. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-config"
-cua host config
-
-# Stop sharing this desktop; keep providing Spaces
-cua host config --desktop off --provide-spaces on
-cua host config --max-spaces 6
-
-# Give the Spaces other machines create here at most 32 GB of memory and 200 GB of disk in total, and stop each after 8 hours (0: no limit)
-cua host config --max-memory 32 --max-disk 200 --max-run-time 480
-
-# Keep no copies of public git repositories on this machine, or at most 2 GB
-cua host config --repo-cache off
-cua host config --repo-cache on --repo-cache-size 2
-```
-
-### `cua host cache`
-
-What the repo cache holds, and empty it.
-
-```text output
-cua host cache [OPTIONS] <COMMAND>
-```
-
-#### `cua host cache status`
-
-What the repo cache holds: repositories, size and what the last week saved.
-
-```text output
-cua host cache status [OPTIONS]
-```
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-cache-status"
-cua host cache status
-```
-
-#### `cua host cache fill`
-
-Copy one public repository into the cache now, instead of when a Space first clones it (or bring a copy up to date). A repository that needs a sign-in is never cached.
-
-```text output
-cua host cache fill [OPTIONS] <URL>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<URL>` | string | required | The repository's `https` address. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-cache-fill"
-cua host cache fill https://github.com/vitejs/vite
-```
-
-#### `cua host cache clear`
-
-Delete every repository the cache holds. They are copied again the next time a Space clones them.
-
-```text output
-cua host cache clear [OPTIONS]
-```
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-cache-clear"
-cua host cache clear
-```
-
-### `cua host status`
-
-Show whether this computer is set up, the service, and who is connected.
-
-```text output
-cua host status [OPTIONS]
-```
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-status"
-cua host status
-```
-
-### `cua host stop`
-
-Stop sharing: disconnect everyone and refuse new connections.
-
-```text output
-cua host stop [OPTIONS]
-```
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-stop"
-cua host stop
-```
-
-### `cua host start`
-
-Start sharing again after `stop`.
-
-```text output
-cua host start [OPTIONS]
-```
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-start"
-cua host start
-```
-
-### `cua host share`
-
-Share a relay computer (this one, or `--machine`) with people in your team (id or verified email). Run from an enrolled device; every change is in the owner's audit log (`cua devices audit`).
-
-```text output
-cua host share [OPTIONS] <WHO>...
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<WHO>...` | string | required | Accounts to add. Repeatable. Repeatable. |
-
-| Flag | Type | Default | Description |
-| --- | --- | --- | --- |
-| <span id="cua-host-share--machine"></span>`--machine` | string | | Computer id (default: this computer). Alias: `--computer`. |
-| <span id="cua-host-share--yes"></span>`--yes` | boolean | `false` | Do not ask for confirmation. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-share"
-cua host share [email protected]
-cua host share [email protected] --machine 0123abcd4567ef89 --yes
-```
-
-### `cua host unshare`
-
-Stop sharing a relay computer with accounts; their open connections are cut.
-
-```text output
-cua host unshare [OPTIONS] <WHO>...
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<WHO>...` | string | required | Accounts to remove. Repeatable. Repeatable. |
-
-| Flag | Type | Default | Description |
-| --- | --- | --- | --- |
-| <span id="cua-host-unshare--machine"></span>`--machine` | string | | Computer id (default: this computer). Alias: `--computer`. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-unshare"
-cua host unshare [email protected]
-```
-
-### `cua host migrate`
-
-macOS: move the host service into the Cua Spaces app, as its "Cua Spaces Helper" login item, from the LaunchAgent that older versions installed. This machine keeps its id, registration and Spaces; if the helper does not take over, the old service is put back. macOS then asks once for Screen Recording and Accessibility for Cua Spaces Helper.
-
-```text output
-cua host migrate [OPTIONS]
-```
-
-| Flag | Type | Default | Description |
-| --- | --- | --- | --- |
-| <span id="cua-host-migrate--force"></span>`--force` | boolean | `false` | Try again even if a move failed before with this version. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-migrate"
-cua host migrate
-
-# Try again after a move that was rolled back
-cua host migrate --force
-```
-
-### `cua host remove`
-
-Unregister from the relay, uninstall the service and delete the host configuration (asks first).
-
-```text output
-cua host remove [OPTIONS]
-```
-
-| Flag | Short | Type | Default | Description |
-| --- | --- | --- | --- | --- |
-| <span id="cua-host-remove--force"></span>`--force` | `-f` | boolean | `false` | Skip the confirmation prompt. Required when there is no terminal to ask on (scripts, agents): without it nothing is removed. |
-| <span id="cua-host-remove--uninstalling"></span>`--uninstalling` | | boolean | `false` | For an uninstall of Cua Spaces: turns off the Spaces this computer provides and takes them off the relay too, instead of refusing while it provides any. The Spaces and their data stay on this computer. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-host-remove"
-cua host remove
-
-# Without the prompt (required in scripts and agents)
-cua host remove --force
-```
-
-## `cua devices`
-
-This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what.
-
-```text output
-cua devices [OPTIONS] <COMMAND>
-```
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-devices"
-cua devices enroll
-cua devices approve K7QX-M2RP
-cua devices ls
-cua devices audit
-```
-
-### `cua devices status`
-
-This device: enrolled, waiting for approval, or not enrolled.
-
-```text output
-cua devices status [OPTIONS]
-```
-
-**Examples**
+### `cua spaces children`
-```bash test="cli-shape" id="ref-cua-devices-status"
-cua devices status
-```
-
-### `cua devices enroll`
-
-Enroll this device. Right after a fresh `cua auth login` it enrolls at once (and replaces this computer's older device key, if any); otherwise it shows a one-time code to approve from an enrolled device (`cua devices approve <code>` or the Cua Spaces app).
+Let a Space make child Spaces of its own, or stop it. While on, `cua`, the SDKs and the agent's tools inside it create, list and delete Spaces that belong to it: on this computer, with its egress rules, ending no later than it, through a channel only it can reach. Off ends its capability at once; children it made keep running until deleted or their lifetime ends.
```text output
-cua devices enroll [OPTIONS]
+cua spaces children [OPTIONS] <SPACE> <STATE>
```
-| Flag | Type | Default | Description |
+| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-devices-enroll--name"></span>`--name` | string | | Display name (default: the host name). |
-| <span id="cua-devices-enroll--wait"></span>`--wait` | boolean | `false` | Wait (up to 10 minutes) until an enrolled device approves. |
+| `<SPACE>` | string | required | Space id or name. |
+| `<STATE>` | `on` \| `off` | required | `on` or `off`. |
**Examples**
-```bash test="cli-shape" id="ref-cua-devices-enroll"
-cua devices enroll
-cua devices enroll --name "work laptop" --wait
+```bash test="cli-shape" id="ref-cua-spaces-children"
+cua spaces children studio on
+cua spaces children studio off
```
-### `cua devices approve`
+### `cua spaces budget`
-Approve a new device (or re-verify an expired one) from this enrolled device, by the code it shows or by its id.
+Show or set a tree's budget: how many child Spaces, vCPUs and memory its children may hold at once, and what they may cost. A child that does not fit is refused with what is left. Without flags it shows the budget and what the children use.
```text output
-cua devices approve [OPTIONS] [CODE]
+cua spaces budget [OPTIONS] <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<CODE>` | string | optional | The one-time code the new device shows, or its device id (`dev_…`, from `cua devices ls`). |
+| `<SPACE>` | string | required | Any Space of the tree (id or name). |
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-devices-approve--device"></span>`--device` | string | | Or the device id (`cua devices ls`). |
-| <span id="cua-devices-approve--yes"></span>`--yes` | boolean | `false` | Do not ask for confirmation. |
+| <span id="cua-spaces-budget--spaces"></span>`--spaces` | integer | | Child Spaces at once (default 16). |
+| <span id="cua-spaces-budget--cpus"></span>`--cpus` | integer | | vCPUs at once (default 16). |
+| <span id="cua-spaces-budget--memory"></span>`--memory` | integer | | Memory at once, in MiB (default 32768). |
+| <span id="cua-spaces-budget--usd-per-hour"></span>`--usd-per-hour` | number | | Cost per hour in linked clouds, in dollars (default 2). |
+| <span id="cua-spaces-budget--usd-total"></span>`--usd-total` | number | | Cost in total, in dollars (default: none). |
+| <span id="cua-spaces-budget--clear"></span>`--clear` | boolean | `false` | Back to the defaults. |
**Examples**
-```bash test="cli-shape" id="ref-cua-devices-approve"
-cua devices approve K7QX-M2RP
-cua devices approve dev_0123456789abcdef01234567
+```bash test="cli-shape" id="ref-cua-spaces-budget"
+cua spaces budget studio
+cua spaces budget studio --spaces 32 --cpus 64 --memory 131072
+cua spaces budget studio --usd-per-hour 5 --usd-total 50
+cua spaces budget studio --clear
```
-### `cua devices ls`
+### `cua spaces orphans`
-Your signed-in machines and their state.
+List child Spaces whose parent is gone or out of reach. The daemon ends a child only on proof its parent is gone, after a grace period; the others stay until you delete them or their lifetime ends.
```text output
-cua devices ls [OPTIONS]
+cua spaces orphans [OPTIONS]
```
-Alias: `cua devices list`.
-
**Examples**
-```bash test="cli-shape" id="ref-cua-devices-ls"
-cua devices ls
-cua devices ls --json
+```bash test="cli-shape" id="ref-cua-spaces-orphans"
+cua spaces orphans
```
-### `cua devices rename`
+### `cua spaces service`
-Rename a device.
+Keep a command running in a Space: started again when it exits or fails its health check (with a backoff), started when the Space boots, its output kept in a log file in the Space.
```text output
-cua devices rename [OPTIONS] <ID> <NAME>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<ID>` | string | required | Device id. |
-| `<NAME>` | string | required | New name. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-devices-rename"
-cua devices rename dev_0123456789abcdef01234567 "work phone"
+cua spaces service [OPTIONS] <COMMAND>
```
-### `cua devices revoke`
+#### `cua spaces service add`
-Revoke a device: it can no longer list or reach your computers.
+Keep a command running (replaces a service of that name).
```text output
-cua devices revoke [OPTIONS] <ID>
+cua spaces service add [OPTIONS] <SPACE> <NAME> -- <COMMAND>...
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<ID>` | string | required | Device id. |
+| `<SPACE>` | string | required | Space id or name. |
+| `<NAME>` | string | required | Service name (lowercase letters, digits, `-`, `_`, `.`). |
+| `<COMMAND>...` | string | required | The command (after `--`). Repeatable. |
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-devices-revoke--yes"></span>`--yes` | boolean | `false` | Do not ask for confirmation. |
+| <span id="cua-spaces-service-add--restart"></span>`--restart` | `always` \| `on-failure` \| `never` | `always` | When to start it again: always, on-failure or never. |
+| <span id="cua-spaces-service-add--http"></span>`--http` | string | | Health check: a URL that answers 2xx or 3xx. |
+| <span id="cua-spaces-service-add--tcp"></span>`--tcp` | string | | Health check: `host:port` that accepts a connection. |
+| <span id="cua-spaces-service-add--check"></span>`--check` | string | | Health check: a shell command that exits 0 when healthy. |
+| <span id="cua-spaces-service-add--env"></span>`--env` | string | | `KEY=VALUE` for its environment (repeat for more). Repeatable. |
+| <span id="cua-spaces-service-add--cwd"></span>`--cwd` | string | | Working directory in the Space. |
+| <span id="cua-spaces-service-add--no-boot"></span>`--no-boot` | boolean | `false` | Do not start it when the Space boots. |
**Examples**
-```bash test="cli-shape" id="ref-cua-devices-revoke"
-cua devices revoke dev_0123456789abcdef01234567
+```bash test="cli-shape" id="ref-cua-spaces-service-add"
+cua spaces service add studio web -- python3 -m http.server 8080
+cua spaces service add studio web --http http://127.0.0.1:8080/ -- python3 -m http.server 8080
+cua spaces service add studio job --restart on-failure -- ./run.sh
```
-### `cua devices audit`
+#### `cua spaces service ls`
-Who accessed what, and when: enrollments, device sessions, computer access (yours and by accounts you share with), sharing changes.
+List a Space's services.
```text output
-cua devices audit [OPTIONS]
+cua spaces service ls [OPTIONS] <SPACE>
```
-| Flag | Type | Default | Description |
+| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-devices-audit--limit"></span>`--limit` | integer | `50` | Newest events to show. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-devices-audit"
-cua devices audit
-cua devices audit --limit 20 --json
-```
-
-## `cua team`
-
-Teams (organizations of your cua.ai account) share computers with every member and their agents. Owners and admins invite by email, approve member devices and add computers.
-
-```text output
-cua team [OPTIONS] <COMMAND>
-```
+| `<SPACE>` | string | required | Space id or name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team"
-cua team create AIGIS
-cua team invite AIGIS [email protected]
-cua team add-machine AIGIS local:build-box
-cua team approve AIGIS dev_0123456789abcdef01234567
-cua team show AIGIS
+```bash test="cli-shape" id="ref-cua-spaces-service-ls"
+cua spaces service ls studio
```
-### `cua team create`
+#### `cua spaces service logs`
-Create a team; you are its owner. Buy Teams for it at app.cua.ai to add computers.
+Show the end of a service's log.
```text output
-cua team create [OPTIONS] <NAME>
+cua spaces service logs [OPTIONS] <SPACE> <NAME>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<NAME>` | string | required | Team name. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-team-create"
-cua team create "AIGIS"
-```
-
-### `cua team ls`
-
-Your teams.
-
-```text output
-cua team ls [OPTIONS]
-```
-
-Alias: `cua team list`.
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-team-ls"
-cua team ls
-cua team ls --json
-```
-
-### `cua team show`
-
-A team: plan, members, computers, open invites and devices.
-
-```text output
-cua team show [OPTIONS] <TEAM>
-```
+| `<SPACE>` | string | required | Space id or name. |
+| `<NAME>` | string | required | Service name. |
-| Argument | Type | Default | Description |
+| Flag | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
+| <span id="cua-spaces-service-logs--tail"></span>`--tail` | integer | `65536` | Bytes from the end. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-show"
-cua team show AIGIS
+```bash test="cli-shape" id="ref-cua-spaces-service-logs"
+cua spaces service logs studio web
```
-### `cua team invite`
+#### `cua spaces service start`
-Invite someone by email: cua.ai emails them an invitation. Manage invites at app.cua.ai/team.
+Start a stopped service.
```text output
-cua team invite [OPTIONS] <TEAM> <EMAIL>
+cua spaces service start [OPTIONS] <SPACE> <NAME>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
-| `<EMAIL>` | string | required | Their email. |
-
-| Flag | Type | Default | Description |
-| --- | --- | --- | --- |
-| <span id="cua-team-invite--role"></span>`--role` | `member` \| `admin` | `member` | `member` or `admin` (only the owner invites admins). |
+| `<SPACE>` | string | required | Space id or name. |
+| `<NAME>` | string | required | Service name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-invite"
-cua team invite AIGIS [email protected]
-cua team invite AIGIS [email protected] --role admin
+```bash test="cli-shape" id="ref-cua-spaces-service-start"
+cua spaces service start studio web
```
-### `cua team join`
+#### `cua spaces service stop`
-After accepting an emailed invitation: take the role it offered. Run `cua auth login` first so your session lists the team.
+Stop a service and keep it stopped.
```text output
-cua team join [OPTIONS] <TEAM>
+cua spaces service stop [OPTIONS] <SPACE> <NAME>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
+| `<SPACE>` | string | required | Space id or name. |
+| `<NAME>` | string | required | Service name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-join"
-cua team join AIGIS
+```bash test="cli-shape" id="ref-cua-spaces-service-stop"
+cua spaces service stop studio web
```
-### `cua team leave`
+#### `cua spaces service restart`
-Leave a team.
+Restart a service.
```text output
-cua team leave [OPTIONS] <TEAM>
+cua spaces service restart [OPTIONS] <SPACE> <NAME>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
+| `<SPACE>` | string | required | Space id or name. |
+| `<NAME>` | string | required | Service name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-leave"
-cua team leave AIGIS
+```bash test="cli-shape" id="ref-cua-spaces-service-restart"
+cua spaces service restart studio web
```
-### `cua team remove-member`
+#### `cua spaces service rm`
-Remove a member (owner or admin; admins cannot remove admins).
+Stop a service and forget it.
```text output
-cua team remove-member [OPTIONS] <TEAM> <WHO>
+cua spaces service rm [OPTIONS] <SPACE> <NAME>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
-| `<WHO>` | string | required | Their email or account id. |
+| `<SPACE>` | string | required | Space id or name. |
+| `<NAME>` | string | required | Service name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-remove-member"
-cua team remove-member AIGIS [email protected]
+```bash test="cli-shape" id="ref-cua-spaces-service-rm"
+cua spaces service rm studio web
```
-### `cua team set-role`
+### `cua spaces cancel`
-Make a member an admin, or an admin a member (owner).
+Cancel a create that is still running (here, in the daemon, or in another terminal): it stops and what it made is removed. Finished image downloads stay cached. Ctrl-C during `cua spaces create` does the same.
```text output
-cua team set-role [OPTIONS] <TEAM> <WHO> <ROLE>
+cua spaces cancel [OPTIONS] <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
-| `<WHO>` | string | required | Their email or account id. |
-| `<ROLE>` | `member` \| `admin` | required | `member` or `admin`. |
+| `<SPACE>` | string | required | The id the Space will have (`local:<name>`, printed when the create starts) or its name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-set-role"
-cua team set-role AIGIS [email protected] admin
+```bash test="cli-shape" id="ref-cua-spaces-cancel"
+cua spaces cancel local:space-1a2b3c
+cua spaces cancel studio
```
-### `cua team devices`
+### `cua spaces gpus`
-Member devices and whether they may open team computers.
+The GPU options each runtime offers on this computer (or in your own cloud account).
```text output
-cua team devices [OPTIONS] <TEAM>
+cua spaces gpus [OPTIONS]
```
-| Argument | Type | Default | Description |
+| Flag | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
+| <span id="cua-spaces-gpus--on"></span>`--on` | string | | `local` (default), `aws`, `gcp` or `modal`. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-devices"
-cua team devices AIGIS
+```bash test="cli-shape" id="ref-cua-spaces-gpus"
+cua spaces gpus
+cua spaces gpus --json
```
-### `cua team approve`
+### `cua spaces delete`
-Approve a member device so it can open team computers.
+Delete a Space's sandbox (on this computer, on the computer that provides it, or in your own cloud account) and forget it (asks first).
```text output
-cua team approve [OPTIONS] <TEAM> <DEVICE>
+cua spaces delete [OPTIONS] <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
-| `<DEVICE>` | string | required | Device id (`cua team devices`). |
+| `<SPACE>` | string | required | Space id or name. |
+
+| Flag | Short | Type | Default | Description |
+| --- | --- | --- | --- | --- |
+| <span id="cua-spaces-delete--force"></span>`--force` | `-f` | boolean | `false` | Skip the confirmation (required without a terminal). |
+| <span id="cua-spaces-delete--keep-children"></span>`--keep-children` | | boolean | `false` | Keep its child Spaces: they become top-level Spaces and keep running (otherwise they are deleted first). |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-approve"
-cua team approve AIGIS dev_0123456789abcdef01234567
+```bash test="cli-shape" id="ref-cua-spaces-delete"
+cua spaces delete relay:space-0123456789abcdef
+cua spaces delete local:studio --force
```
-### `cua team deny`
+### `cua spaces stop`
-Decline a member device (it can no longer open team computers).
+Turn a Space off: a local VM (QEMU or Lume) or a Space one of your computers provides is stopped, keeping its disk and freeing its memory, and so is a Space in your own cloud (`--on aws`, `gcp`: compute billing stops; `hetzner`: still billed). A local container is stopped or suspended as its runtime can. `cua spaces suspend` keeps a local Space's memory instead. Modal sandboxes and Spaces added by address cannot be turned off.
```text output
-cua team deny [OPTIONS] <TEAM> <DEVICE>
+cua spaces stop [OPTIONS] <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
-| `<DEVICE>` | string | required | Device id. |
+| `<SPACE>` | string | required | Space id or name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-deny"
-cua team deny AIGIS dev_0123456789abcdef01234567
+```bash test="cli-shape" id="ref-cua-spaces-stop"
+cua spaces stop local:studio
+cua spaces stop relay:space-0123456789abcdef --json
```
-### `cua team request`
+### `cua spaces suspend`
-Ask the team's admins to approve this device.
+Suspend a local Space (a container or QEMU VM): its memory is kept, and stays in use, so it resumes where it was with `cua spaces start`. `cua spaces stop` frees the memory instead.
```text output
-cua team request [OPTIONS] <TEAM>
+cua spaces suspend [OPTIONS] <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
+| `<SPACE>` | string | required | Space id or name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-request"
-cua team request AIGIS
+```bash test="cli-shape" id="ref-cua-spaces-suspend"
+cua spaces suspend local:studio
```
-### `cua team add-machine`
+### `cua spaces resize`
-Make a Space (or a computer you host) a team computer: every member and their agents see it and can open it. Macs, Linux and Windows computers all can. Each Space is added on its own: adding a host does not add the Spaces it provides.
+Give a local VM Space more or fewer vCPUs, more or less memory, or a bigger disk. It shuts down and boots again from its own disk (a stopped one boots): its files stay, its running processes do not. A disk never shrinks.
```text output
-cua team add-machine [OPTIONS] <TEAM> <SPACE>
+cua spaces resize [OPTIONS] <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
-| `<SPACE>` | string | required | Space id or name (`relay:<id>` for a computer you host). |
+| `<SPACE>` | string | required | Space id or name. |
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-team-add-machine--yes"></span>`--yes` | boolean | `false` | Confirm without a prompt. |
+| <span id="cua-spaces-resize--cpus"></span>`--cpus` | integer | | vCPUs. |
+| <span id="cua-spaces-resize--memory-mb"></span>`--memory-mb` | integer | | Memory in MiB. |
+| <span id="cua-spaces-resize--disk-gb"></span>`--disk-gb` | integer | | Grow the disk to this many GiB. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-add-machine"
-cua team add-machine AIGIS local:build-box
-cua team add-machine AIGIS relay:0123abcd4567ef89 --yes
+```bash test="cli-shape" id="ref-cua-spaces-resize"
+cua spaces resize local:builder --memory-mb 24576
+cua spaces resize builder --cpus 8 --disk-gb 200 --json
```
-### `cua team remove-machine`
+### `cua spaces start`
-Take a computer off the team.
+Turn a Space back on: resume a suspended one or boot a stopped one.
```text output
-cua team remove-machine [OPTIONS] <TEAM> <COMPUTER>
+cua spaces start [OPTIONS] <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
-| `<COMPUTER>` | string | required | The computer (`relay:<id>` or its id, as `cua team show` lists it). |
+| `<SPACE>` | string | required | Space id or name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-remove-machine"
-cua team remove-machine AIGIS relay:0123abcd4567ef89
+```bash test="cli-shape" id="ref-cua-spaces-start"
+cua spaces start local:studio
+cua spaces start studio --json
```
-### `cua team audit`
+### `cua spaces rm`
-The team's audit log. Audit export is coming soon; for now see the account app (app.cua.ai).
+Forget a registered Space and its stored token. The sandbox keeps running. A Space cua created (on this computer or in a cloud) is refused while its sandbox exists: use `cua spaces delete` (or `stop`). The `relay:<computer>` record of a Space that registered itself and is gone (not connected) also leaves your relay directory.
```text output
-cua team audit [OPTIONS] <TEAM>
+cua spaces rm [OPTIONS] <SPACE>
```
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
+Alias: `cua spaces remove`.
-| Flag | Type | Default | Description |
+| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-team-audit--limit"></span>`--limit` | integer | `50` | Newest events to show (when export arrives). |
+| `<SPACE>` | string | required | Space id, address or display name (as `cua spaces ls` shows). |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-audit"
-cua team audit AIGIS
+```bash test="cli-shape" id="ref-cua-spaces-rm"
+cua spaces rm direct:10.0.0.5:3211
+cua spaces rm studio
```
-### `cua team delete`
+### `cua spaces rename`
-Delete a team (owner; cancel its subscription first). Its computers stay yours.
+Give a Space a new name; its id stays the same. Lowercase letters, digits and dashes, as at create. A Space you shared, or one of your computers provides, is renamed on the relay too, so your other devices and the people it is shared with see the new name. Only its owner can rename a Space.
```text output
-cua team delete [OPTIONS] <TEAM>
+cua spaces rename [OPTIONS] <SPACE> <NAME>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id, alias or name. |
-
-| Flag | Type | Default | Description |
-| --- | --- | --- | --- |
-| <span id="cua-team-delete--yes"></span>`--yes` | boolean | `false` | Do not ask for confirmation. |
+| `<SPACE>` | string | required | Space id or name (as `cua spaces ls` shows). |
+| `<NAME>` | string | required | The new name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-team-delete"
-cua team delete AIGIS --yes
+```bash test="cli-shape" id="ref-cua-spaces-rename"
+cua spaces rename local:studio design-review
+cua spaces rename relay:space-0123456789abcdef ci-runner
```
-## `cua usage`
+### `cua spaces share`
-Your remote use this month: live sessions, remote hours, and your plan. Remote hours are time spent using your computers from somewhere else; using a computer from itself is free.
+Let someone in your team watch (viewer) or use (editor) a Space, through the relay. They open it as `relay:<computer>`. Sharing is for teams: you need a team, and they must be in it (or share with the whole team as `team:<id>`).
```text output
-cua usage [OPTIONS]
+cua spaces share [OPTIONS] <SPACE> <WHO>
```
-**Examples**
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<SPACE>` | string | required | Space id, address or display name. |
+| `<WHO>` | string | required | Their email (verified by cua.ai) or account id, in your team; or `team:<id>` for the whole team. |
-```bash test="cli-shape" id="ref-cua-usage"
-cua usage
-cua usage --json
-```
+| Flag | Short | Type | Default | Description |
+| --- | --- | --- | --- | --- |
+| <span id="cua-spaces-share--role"></span>`--role` | | `viewer` \| `editor` | `viewer` | `viewer`: presence and a view-only stream. `editor`: full use. |
+| <span id="cua-spaces-share--yes"></span>`--yes` | `-y` | boolean | `false` | Confirm without a terminal prompt. Without a daemon the share happens at once. A running daemon still asks with Touch ID or your password on this computer; without a terminal, `--yes` says someone will answer there (otherwise the command fails at once instead of waiting for a prompt nobody sees). |
-## `cua spacesd`
+**Examples**
-Talk to a cua-spacesd directly by URL.
+```bash test="cli-shape" id="ref-cua-spaces-share"
+cua spaces share local:studio [email protected]
+cua spaces share local:studio [email protected] --role editor
+cua spaces share relay:0123abcd4567ef89 acct-42 --role viewer
-```text output
-cua spacesd [OPTIONS] <COMMAND>
+# The whole team, to watch
+cua spaces share local:studio team:acme --role viewer
+
+# From a script or agent: confirm with Touch ID or your password here
+cua spaces share local:studio [email protected] --yes
```
-### `cua spacesd caps`
+### `cua spaces unshare`
-Print capabilities.
+Stop sharing a Space with one account at once, or with everyone.
```text output
-cua spacesd caps [OPTIONS] <URL>
+cua spaces unshare [OPTIONS] <SPACE> [WHO]
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<URL>` | string | required | spacesd URL (`http://host:port`). |
+| `<SPACE>` | string | required | Space id, address or display name. |
+| `<WHO>` | string | optional | Their email or account id. |
-| Flag | Type | Default | Env var | Description |
-| --- | --- | --- | --- | --- |
-| <span id="cua-spacesd-caps--token"></span>`--token` | string | | `CUA_ENV_TOKEN` | spacesd token. |
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-spaces-unshare--all"></span>`--all` | boolean | `false` | Stop sharing with everyone (the Space leaves the relay). |
**Examples**
-```bash test="cli-shape" id="ref-cua-spacesd-caps"
-cua spacesd caps http://127.0.0.1:3211
+```bash test="cli-shape" id="ref-cua-spaces-unshare"
+cua spaces unshare local:studio [email protected]
+cua spaces unshare local:studio --all
```
-### `cua spacesd exec`
+### `cua spaces shares`
-Run a command (argv, no shell).
+Who a Space is shared with, and who of them is connected now.
```text output
-cua spacesd exec [OPTIONS] <URL> <COMMAND>...
+cua spaces shares [OPTIONS] <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<URL>` | string | required | spacesd URL (`http://host:port`). |
-| `<COMMAND>...` | string | required | Program and arguments. Repeatable. |
-
-| Flag | Short | Type | Default | Env var | Description |
-| --- | --- | --- | --- | --- | --- |
-| <span id="cua-spacesd-exec--user"></span>`--user` | | string | | | Run as this guest user. |
-| <span id="cua-spacesd-exec--cwd"></span>`--cwd` | | string | | | Start in this guest directory. |
-| <span id="cua-spacesd-exec--timeout"></span>`--timeout` | | integer | | | Stop the command after this many seconds (0: no limit). |
-| <span id="cua-spacesd-exec--token"></span>`--token` | | string | | `CUA_ENV_TOKEN` | spacesd token. |
-| <span id="cua-spacesd-exec--stdin"></span>`--stdin` | `-i` | boolean | `false` | | Stream: run the command as argv (no shell), forward this command's stdin, write stdout and stderr as they arrive, set no time limit, pass SIGINT/SIGTERM/SIGHUP on, and kill the command when this process ends. Exits with the command's status (128 + n for signal n). |
+| `<SPACE>` | string | required | Space id, address or display name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-spacesd-exec"
-cua spacesd exec http://127.0.0.1:3211 uname -a
-
-# A long-lived stdio stream (stdin forwarded, no time limit, killed with this command)
-cua spacesd exec -i http://127.0.0.1:3211 cat
+```bash test="cli-shape" id="ref-cua-spaces-shares"
+cua spaces shares local:studio
+cua spaces shares local:studio --json
```
-### `cua spacesd cp`
+### `cua spaces relay-register`
-Copy files: `cua spacesd cp <URL> local :remote` uploads, `cua spacesd cp <URL> :remote local` downloads.
+Publish a Space on the relay for your other devices (a phone off this network): its own driver dials out, as `cua host setup` does for this computer. Nobody else gets in until you share it.
```text output
-cua spacesd cp [OPTIONS] <URL> <SRC> <DST>
+cua spaces relay-register [OPTIONS] <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<URL>` | string | required | spacesd URL (`http://host:port`). |
-| `<SRC>` | string | required | Source: a local path, or `:/guest/path`. |
-| `<DST>` | string | required | Destination: a local path, or `:/guest/path`. |
-
-| Flag | Type | Default | Env var | Description |
-| --- | --- | --- | --- | --- |
-| <span id="cua-spacesd-cp--token"></span>`--token` | string | | `CUA_ENV_TOKEN` | spacesd token. |
+| `<SPACE>` | string | required | Space id, address or display name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-spacesd-cp"
-# Upload
-cua spacesd cp http://127.0.0.1:3211 ./notes.txt :/tmp/notes.txt
-
-# Download
-cua spacesd cp http://127.0.0.1:3211 :/tmp/notes.txt ./notes.txt
+```bash test="cli-shape" id="ref-cua-spaces-relay-register"
+cua spaces relay-register local:studio
```
-### `cua spacesd shell`
+### `cua spaces relay-unregister`
-Interactive shell (PTY).
+Take a Space off the relay (every share with it ends). With a `relay:<computer>` id, removes that computer's record from your relay directory: a Space that registered itself (also after it was deleted), or a computer of yours that is gone. Only its owner can.
```text output
-cua spacesd shell [OPTIONS] <URL>
+cua spaces relay-unregister [OPTIONS] <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<URL>` | string | required | spacesd URL (`http://host:port`). |
-
-| Flag | Type | Default | Env var | Description |
-| --- | --- | --- | --- | --- |
-| <span id="cua-spacesd-shell--token"></span>`--token` | string | | `CUA_ENV_TOKEN` | spacesd token. |
+| `<SPACE>` | string | required | Space id, address or display name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-spacesd-shell"
-cua spacesd shell http://127.0.0.1:3211
+```bash test="cli-shape" id="ref-cua-spaces-relay-unregister"
+cua spaces relay-unregister local:studio
+cua spaces relay-unregister relay:space-0123abcd4567ef89
```
-### `cua spacesd targets`
+## `cua network`
-List streamable targets (displays, and windows with --windows).
+What a Space can reach on the network, and changing it: `show`, `set`, `log`. An experiment: see `cua experiments`.
```text output
-cua spacesd targets [OPTIONS] <URL>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<URL>` | string | required | spacesd URL (`http://host:port`). |
-
-| Flag | Type | Default | Env var | Description |
-| --- | --- | --- | --- | --- |
-| <span id="cua-spacesd-targets--token"></span>`--token` | string | | `CUA_ENV_TOKEN` | spacesd token. |
-| <span id="cua-spacesd-targets--windows"></span>`--windows` | boolean | `false` | | Include window targets. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-spacesd-targets"
-cua spacesd targets http://127.0.0.1:3211 --windows
+cua network [OPTIONS] <COMMAND>
```
-### `cua spacesd call`
+### `cua network show`
-Call any cua.env.v1 RPC with a proto3-JSON body.
+What a Space can reach: its preset, what it opens, where it is enforced, and what is always blocked.
```text output
-cua spacesd call [OPTIONS] <URL> <METHOD> [BODY]
+cua network show [OPTIONS] <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<URL>` | string | required | spacesd URL (`http://host:port`). |
-| `<METHOD>` | string | required | `Service/Method`. |
-| `<BODY>` | string | `{}` | Request body (proto3 JSON). |
-
-| Flag | Type | Default | Env var | Description |
-| --- | --- | --- | --- | --- |
-| <span id="cua-spacesd-call--token"></span>`--token` | string | | `CUA_ENV_TOKEN` | spacesd token. |
+| `<SPACE>` | string | required | Space id or name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-spacesd-call"
-cua spacesd call http://127.0.0.1:3211 SystemService/GetCapabilities
+```bash test="cli-shape" id="ref-cua-network-show"
+cua network show studio
+cua network show local:studio --json
```
-## `cua share`
+### `cua network set`
-Share a link to a port, a file or a folder that opens on your other signed-in devices (never localhost): `cua share 3000`, `cua share ./report.html`, `cua share ls`, `cua share stop ID`.
+Change what a Space can reach. A child Space stays within its parent's unless `--widen`.
```text output
-cua share [OPTIONS] <TARGET>
- cua share <COMMAND>
+cua network set [OPTIONS] --network <PRESET> <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TARGET>` | string | required | What to share: a port (`3000`), a port in a Space (`space:NAME:3000`), or a file or folder (`./report.html`, `./build/`). Paths are read-only; use `./ls` for a file called `ls`. |
+| `<SPACE>` | string | required | Space id or name. |
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-share--ttl"></span>`--ttl` | string | | How long the share lasts (`10m`, `1h`, 60s to 24h). Public shares default to 1h; the others have no end unless you set one. |
-| <span id="cua-share--name"></span>`--name` | string | | A name for `cua share ls` (and `cua share stop NAME`). |
-| <span id="cua-share--team"></span>`--team` | boolean | `false` | Share with the members of your team. |
-| <span id="cua-share--public"></span>`--public` | boolean | `false` | Anyone with the link can open it. Expires (default 1h, 60s to 24h). |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-share"
-# A dev server on this machine, for your own devices (phone included)
-cua share 3000
-
-# A port inside a Space
-cua share space:dev:3000
-
-# A report or a folder, read-only
-cua share ./report.html
-cua share ./build/
-
-# Members of your team
-cua share 3000 --team
-
-# Anyone with the link, for an hour
-cua share ./report.html --public --ttl 1h
-
-# What is shared, and stop it
-cua share ls
-cua share stop share-1a2b3c4d5e6f
-cua share stop all
-```
-
-### `cua share ls`
-
-List the active shares.
-
-```text output
-cua share ls [OPTIONS]
-```
+| <span id="cua-network-set--network"></span>`--network` | string | required | `internet`, `none`, `localhost:<ports>` (or `localhost:all`), `lan`, `custom`, `custom:none` or `unprotected` (No protection). |
+| <span id="cua-network-set--allow"></span>`--allow` | string | | Allow this destination (IP or CIDR; repeat for more). Repeatable. |
+| <span id="cua-network-set--deny"></span>`--deny` | string | | Block this destination (IP, CIDR or `all`; repeat for more). Repeatable. |
+| <span id="cua-network-set--widen"></span>`--widen` | boolean | `false` | A child Space: let it reach more than its parent (recorded on the Space). |
+| <span id="cua-network-set--tree"></span>`--tree` | boolean | `false` | Its child Spaces get the same settings (each within its parent's). |
**Examples**
-```bash test="cli-shape" id="ref-cua-share-ls"
-# What is shared right now
-cua share ls
-
-# The same as JSON
-cua share ls --json
-```
-
-### `cua share stop`
-
-Stop a share (its link stops working at once), or `all`.
-
-```text output
-cua share stop [OPTIONS] <ID>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<ID>` | string | required | The share's id or name from `cua share ls`, or `all`. |
+```bash test="cli-shape" id="ref-cua-network-set"
+# This computer's Postgres and dev server only
+cua network set studio --network localhost:5432,3000
-**Examples**
+# Your local network too
+cua network set studio --network lan
-```bash test="cli-shape" id="ref-cua-share-stop"
-# Stop one share by its id
-cua share stop share-1a2b3c4d5e6f
+# Only these destinations
+cua network set studio --network custom:none --allow 140.82.112.0/20
-# Stop everything this machine shares
-cua share stop all
+# Back to the default
+cua network set studio --network internet
```
-### `cua share check`
+### `cua network log`
-Open a share's link once, as its owner, and say what came back.
+What a Space tried to reach and was blocked, most recent first.
```text output
-cua share check [OPTIONS] <ID> [PATH]
+cua network log [OPTIONS] <SPACE>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<ID>` | string | required | The share's id or name. |
-| `<PATH>` | string | optional | A path below the link to open. |
+| `<SPACE>` | string | required | Space id or name. |
**Examples**
-```bash test="cli-shape" id="ref-cua-share-check"
-# Does the link load?
-cua share check share-1a2b3c4d5e6f
-
-# Open a page below the link
-cua share check share-1a2b3c4d5e6f /index.html
+```bash test="cli-shape" id="ref-cua-network-log"
+cua network log studio
```
## Exit codes
diff --git a/docs/content/docs/cua-cli/reference/index.mdx b/docs/content/docs/cua-cli/reference/index.mdx
index 78142db66a..fa4226d6ad 100644
--- a/docs/content/docs/cua-cli/reference/index.mdx
+++ b/docs/content/docs/cua-cli/reference/index.mdx
@@ -15,7 +15,8 @@ description: "Every cua command and every cua MCP tool, generated from the CLI d
| Command group | Description |
| --- | --- |
| [`cua`](/cua-cli/reference/cli) | Synopsis, global options, exit codes and every command. |
-| [Spaces, computers and teams](/cua-cli/reference/cli/spaces-and-computers) | Your Spaces and machines, unattended access on this machine, devices, teams, your remote use this month, and a cua-spacesd by URL. |
+| [Spaces](/cua-cli/reference/cli/spaces-and-computers) | Your Spaces, what they can reach, and keeping commands running in them. |
+| [Computers and teams](/cua-cli/reference/cli/computers-and-teams) | Your computers, unattended access on this computer, teams, sharing, your remote use this month, and a cua-spacesd by URL. |
| [Files, teleport and keys](/cua-cli/reference/cli/files-teleport-and-keys) | Cua Volume files and sharing, moving an app session into a sandbox, and the Cua Keyvault. |
| [Sandboxes](/cua-cli/reference/cli/sandboxes) | Create, reach and delete sandboxes; local runtimes, disk cleanup and the sandbox viewer. |
| [Images and your cloud](/cua-cli/reference/cli/images-and-clouds) | Pull, build, push and publish images, and the cloud account you link for machines. |
diff --git a/docs/content/docs/cua-cli/reference/mcp-tools.mdx b/docs/content/docs/cua-cli/reference/mcp-tools.mdx
index 55562d1178..4670a40928 100644
--- a/docs/content/docs/cua-cli/reference/mcp-tools.mdx
+++ b/docs/content/docs/cua-cli/reference/mcp-tools.mdx
@@ -30,6 +30,8 @@ Full entries: [Space lifecycle](/spaces/reference/spaces#space-lifecycle).
| <span id="remove_space"></span>[`remove_space`](/spaces/reference/spaces#remove_space) | Forget a registered Space without touching it. |
| <span id="list_spaces"></span>[`list_spaces`](/spaces/reference/spaces#list_spaces) | List the Spaces this connection can see. |
| <span id="create_space"></span>[`create_space`](/spaces/reference/spaces#create_space) | Create a Space: a new sandbox on this computer, on one of your computers, or in the cloud. |
+| <span id="network_show"></span>[`network_show`](/spaces/reference/spaces#network_show) | Show a Space's network: preset, what it opens, where it is enforced, what is always blocked. |
+| <span id="network_set"></span>[`network_set`](/spaces/reference/spaces#network_set) | Tighten a Space's network: internet, none or custom lists. |
| <span id="delete_space"></span>[`delete_space`](/spaces/reference/spaces#delete_space) | Delete a Space's sandbox and forget it. |
| <span id="stop_space"></span>[`stop_space`](/spaces/reference/spaces#stop_space) | Turn a Space off: stop it (disk kept, memory freed) or, with suspend, suspend it (memory kept). |
| <span id="resize_space"></span>[`resize_space`](/spaces/reference/spaces#resize_space) | Change a Space's vCPUs, memory or disk size. |
@@ -42,6 +44,7 @@ Full entries: [Commands and files](/spaces/reference/spaces#commands-and-files).
| Tool | Description |
| --- | --- |
| <span id="space_bash"></span>[`space_bash`](/spaces/reference/spaces#space_bash) | Run a shell command inside the Space. |
+| <span id="space_job"></span>[`space_job`](/spaces/reference/spaces#space_job) | Run a long command in the Space as a background job: tail its log, cancel it, or get woken when it ends. |
| <span id="space_write"></span>[`space_write`](/spaces/reference/spaces#space_write) | Write literal text to a path inside the Space. |
| <span id="upload"></span>[`upload`](/spaces/reference/spaces#upload) | Send a local file or folder into the Space. |
| <span id="send_file"></span>[`send_file`](/spaces/reference/spaces#send_file) | Send a host file or folder into the Space's Downloads, verified by sha256 on arrival. |
@@ -68,6 +71,7 @@ Full entries: [Services](/spaces/reference/spaces#services).
| --- | --- |
| <span id="list_tools"></span>[`list_tools`](/spaces/reference/spaces#list_tools) | List the MCP services and tools reachable inside the Space. |
| <span id="call_tool"></span>[`call_tool`](/spaces/reference/spaces#call_tool) | Call a service tool inside the Space. |
+| <span id="space_service"></span>[`space_service`](/spaces/reference/spaces#space_service) | Keep a command running in the Space: restarts, health checks, start on boot, logs. |
### Agents
@@ -191,38 +195,38 @@ Full entries: [Cua Volume](/spaces/reference/agents#cua-volume).
### Sharing
-Full entries: [Sharing](/spaces/reference/spaces#sharing).
+Full entries: [Sharing](/spaces/reference/sharing-and-cloud#sharing).
| Tool | Description |
| --- | --- |
-| <span id="share_space"></span>[`share_space`](/spaces/reference/spaces#share_space) | Let someone in your team watch or edit a Space. |
-| <span id="unshare_space"></span>[`unshare_space`](/spaces/reference/spaces#unshare_space) | Stop sharing a Space with an account, or with everyone. |
-| <span id="space_shares"></span>[`space_shares`](/spaces/reference/spaces#space_shares) | List who a Space is shared with. |
-| <span id="relay_register_space"></span>[`relay_register_space`](/spaces/reference/spaces#relay_register_space) | Publish a Space on the relay for the account's other devices. |
-| <span id="relay_unregister_space"></span>[`relay_unregister_space`](/spaces/reference/spaces#relay_unregister_space) | Take a Space off the relay. |
+| <span id="share_space"></span>[`share_space`](/spaces/reference/sharing-and-cloud#share_space) | Let someone in your team watch or edit a Space. |
+| <span id="unshare_space"></span>[`unshare_space`](/spaces/reference/sharing-and-cloud#unshare_space) | Stop sharing a Space with an account, or with everyone. |
+| <span id="space_shares"></span>[`space_shares`](/spaces/reference/sharing-and-cloud#space_shares) | List who a Space is shared with. |
+| <span id="relay_register_space"></span>[`relay_register_space`](/spaces/reference/sharing-and-cloud#relay_register_space) | Publish a Space on the relay for the account's other devices. |
+| <span id="relay_unregister_space"></span>[`relay_unregister_space`](/spaces/reference/sharing-and-cloud#relay_unregister_space) | Take a Space off the relay. |
### Your cloud
-Full entries: [Your cloud](/spaces/reference/spaces#your-cloud).
+Full entries: [Your cloud](/spaces/reference/sharing-and-cloud#your-cloud).
| Tool | Description |
| --- | --- |
-| <span id="cloud_status"></span>[`cloud_status`](/spaces/reference/spaces#cloud_status) | List your clouds (AWS, Google Cloud, Hetzner, Modal): found credentials, the connected account and region, what each can run at what hourly cost, and what Cua created there. |
-| <span id="cloud_connect"></span>[`cloud_connect`](/spaces/reference/spaces#cloud_connect) | Connect a cloud account Spaces can be created in. |
-| <span id="cloud_test"></span>[`cloud_test`](/spaces/reference/spaces#cloud_test) | Check a cloud account without creating anything. |
-| <span id="cloud_disconnect"></span>[`cloud_disconnect`](/spaces/reference/spaces#cloud_disconnect) | Forget a connected cloud account (deleting what Cua created there first, with delete=true). |
-| <span id="cloud_sweep"></span>[`cloud_sweep`](/spaces/reference/spaces#cloud_sweep) | Find and delete what Cua left in your clouds. |
-| <span id="cloud_plan"></span>[`cloud_plan`](/spaces/reference/spaces#cloud_plan) | Show (or apply) the elastic pool's plan for some Spaces: where they go, which machines it adds, and the cost. |
-| <span id="cloud_hosts"></span>[`cloud_hosts`](/spaces/reference/spaces#cloud_hosts) | List the hosts the elastic pool added in your clouds. |
-| <span id="cloud_add_host"></span>[`cloud_add_host`](/spaces/reference/spaces#cloud_add_host) | Add hosts to your pool in a linked cloud. |
-| <span id="cloud_remove_host"></span>[`cloud_remove_host`](/spaces/reference/spaces#cloud_remove_host) | Remove hosts this home added to your pool. |
-| <span id="cloud_budget"></span>[`cloud_budget`](/spaces/reference/spaces#cloud_budget) | Read or set the elastic pool's budget and autoscale switch. |
-| <span id="cloud_reconcile"></span>[`cloud_reconcile`](/spaces/reference/spaces#cloud_reconcile) | Run the elastic pool's scale-in pass now. |
-| <span id="prewarm"></span>[`prewarm`](/spaces/reference/spaces#prewarm) | Keep Spaces of one shape ready where the elastic pool puts them, so the next creates start in a fraction of a second. |
-| <span id="prewarm_list"></span>[`prewarm_list`](/spaces/reference/spaces#prewarm_list) | List the prewarms and how many Spaces each keeps ready. |
-| <span id="prewarm_remove"></span>[`prewarm_remove`](/spaces/reference/spaces#prewarm_remove) | End a prewarm: its ready Spaces go. |
-| <span id="cloud_audit"></span>[`cloud_audit`](/spaces/reference/spaces#cloud_audit) | Read the log of what Cua did in your clouds. |
-| <span id="cloud_cost"></span>[`cloud_cost`](/spaces/reference/spaces#cloud_cost) | Estimate what Cua's machines in your clouds cost, by Space, agent, day or cloud. |
+| <span id="cloud_status"></span>[`cloud_status`](/spaces/reference/sharing-and-cloud#cloud_status) | List your clouds (AWS, Google Cloud, Hetzner, Modal): found credentials, the connected account and region, what each can run at what hourly cost, and what Cua created there. |
+| <span id="cloud_connect"></span>[`cloud_connect`](/spaces/reference/sharing-and-cloud#cloud_connect) | Connect a cloud account Spaces can be created in. |
+| <span id="cloud_test"></span>[`cloud_test`](/spaces/reference/sharing-and-cloud#cloud_test) | Check a cloud account without creating anything. |
+| <span id="cloud_disconnect"></span>[`cloud_disconnect`](/spaces/reference/sharing-and-cloud#cloud_disconnect) | Forget a connected cloud account (deleting what Cua created there first, with delete=true). |
+| <span id="cloud_sweep"></span>[`cloud_sweep`](/spaces/reference/sharing-and-cloud#cloud_sweep) | Find and delete what Cua left in your clouds. |
+| <span id="cloud_plan"></span>[`cloud_plan`](/spaces/reference/sharing-and-cloud#cloud_plan) | Show (or apply) the elastic pool's plan for some Spaces: where they go, which machines it adds, and the cost. |
+| <span id="cloud_hosts"></span>[`cloud_hosts`](/spaces/reference/sharing-and-cloud#cloud_hosts) | List the hosts the elastic pool added in your clouds. |
+| <span id="cloud_add_host"></span>[`cloud_add_host`](/spaces/reference/sharing-and-cloud#cloud_add_host) | Add hosts to your pool in a linked cloud. |
+| <span id="cloud_remove_host"></span>[`cloud_remove_host`](/spaces/reference/sharing-and-cloud#cloud_remove_host) | Remove hosts this home added to your pool. |
+| <span id="cloud_budget"></span>[`cloud_budget`](/spaces/reference/sharing-and-cloud#cloud_budget) | Read or set the elastic pool's budget and autoscale switch. |
+| <span id="cloud_reconcile"></span>[`cloud_reconcile`](/spaces/reference/sharing-and-cloud#cloud_reconcile) | Run the elastic pool's scale-in pass now. |
+| <span id="prewarm"></span>[`prewarm`](/spaces/reference/sharing-and-cloud#prewarm) | Keep Spaces of one shape ready where the elastic pool puts them, so the next creates start in a fraction of a second. |
+| <span id="prewarm_list"></span>[`prewarm_list`](/spaces/reference/sharing-and-cloud#prewarm_list) | List the prewarms and how many Spaces each keeps ready. |
+| <span id="prewarm_remove"></span>[`prewarm_remove`](/spaces/reference/sharing-and-cloud#prewarm_remove) | End a prewarm: its ready Spaces go. |
+| <span id="cloud_audit"></span>[`cloud_audit`](/spaces/reference/sharing-and-cloud#cloud_audit) | Read the log of what Cua did in your clouds. |
+| <span id="cloud_cost"></span>[`cloud_cost`](/spaces/reference/sharing-and-cloud#cloud_cost) | Estimate what Cua's machines in your clouds cost, by Space, agent, day or cloud. |
## Image tools
@@ -1216,5 +1220,5 @@ Tools are gated by `--permissions` (or `CUA_MCP_PERMISSIONS`), a comma-separated
| `sandbox:all` | 11 permissions | `sandbox:list`, `sandbox:get` |
| `share:all` | `share:create`, `share:read`, `share:stop` | `share:read` |
| `skills:all` | `skills:list`, `skills:read`, `skills:record`, `skills:delete` | `skills:list`, `skills:read` |
-| `spaces:all` | 113 permissions | 36 permissions |
+| `spaces:all` | 117 permissions | 37 permissions |
| `teleport:all` | `teleport:browser` | none |
diff --git a/docs/content/docs/cua-sdk/guides/egress.mdx b/docs/content/docs/cua-sdk/guides/egress.mdx
index 2223abaf24..2b6a9acd64 100644
--- a/docs/content/docs/cua-sdk/guides/egress.mdx
+++ b/docs/content/docs/cua-sdk/guides/egress.mdx
@@ -1,60 +1,97 @@
---
-title: Limit where a Space connects (egress policies)
-description: Allow and deny lists of addresses for a Space's outbound connections, enforced by the host outside the guest, from the first instruction.
+title: A Space's network
+description: What a Space can reach, enforced by the host outside the guest. With Secure Spaces on, the internet and its own tree, never this computer, your local network or cloud metadata.
---
-An egress policy says which destinations a Space may open connections to. The machine the Space runs on enforces it outside the guest, so nothing in the guest, root included, can change it: there are no rules inside the guest to flush.
+Secure Spaces is an [experiment](/spaces/guides/experiments) and is off until you turn it on with `cua experiments enable secure-spaces`. While it is off, Spaces keep the open network they have always had, and only the older allow and deny lists (see the last heading) apply. The rest of this page describes the experiment.
+
+With Secure Spaces on, every Space starts on **Internet only**. It reaches the public internet and the other Spaces of its own tree. It can't reach this computer, your local network, cloud metadata endpoints, Spaces of other trees or the Cua daemon. The machine the Space runs on enforces this outside the guest, from its first instruction. Nothing in the guest, root included, can change it: there are no rules inside the guest to flush.
```python skip="local-vm"
import cua
spaces = cua.embedded().spaces()
-created = await spaces.create(cua.SpaceCreateOptions(
- on="local",
- egress=cua.EgressPolicy(allow=["1.1.1.1"], deny=["all"]),
-))
+created = await spaces.create(cua.SpaceCreateOptions(on="local"))
space = created.space
-assert space.egress_enforced == cua.EgressEnforcement.HOST
-
-# Replace it while the Space runs (an empty policy removes it).
-await spaces.set_egress(space.id, cua.EgressPolicy(deny=["10.0.0.0/8"]))
+print(space.network.preset) # "internet"
+
+# Only GitHub's addresses, nothing else.
+await spaces.set_network(
+ space.id,
+ cua.NetworkSettings(preset="custom", custom_base="none", allow=["140.82.112.0/20"]),
+ widen=False,
+ tree=False,
+)
+
+# What it can reach now, in plain words.
+info = await spaces.network(space.id)
+print(info.summary, info.enforcement, info.always_blocked)
```
-## The policy
+From the command line, `cua spaces create --network lan` picks a preset, and `cua network show` and `cua network set` read and change it later.
+
+## Presets
+
+| Preset | Reaches |
+| --- | --- |
+| `internet` (default) | The public internet and its own tree. |
+| `none` | Nothing. Cua still reaches the Space to run commands and show its screen. |
+| `localhost:5432,3000` | `internet`, plus this computer's localhost on the ports you list. `localhost:all` opens every port, which also opens the Docker API, databases and local AI servers, so name the ports when you can. |
+| `lan` | `internet`, plus your local network. This computer itself stays closed. |
+| `custom` | `internet` plus your own `allow` and `deny` lists. `custom:none` starts from no network instead. |
+| `unprotected` | Everything but the always-blocked list. Use it only where a runtime can't protect the Space and you need the network anyway. |
+
+`allow` and `deny` take IPv4 and IPv6 addresses and CIDRs (`deny` also takes `all`). A deny blocks; an allow is an exception to a deny and to the default blocks. A hostname is refused, because the rules are by address. A name that resolves to a blocked address, such as one that points at `127.0.0.1` or `10.0.0.1`, stays blocked: the rules judge the address the guest connects to.
+
+## Always blocked
+
+No preset or list opens these:
-- Every `deny` entry blocks that destination; every `allow` entry is an exception that wins over `deny`. `deny=["all"]` with `allow=["1.1.1.1"]` leaves only 1.1.1.1 reachable.
-- An `allow` list alone blocks nothing. Both lists empty: no policy.
-- Entries are IPv4 or IPv6 addresses and CIDRs; `all` is `0.0.0.0/0` and `::/0`. A hostname is refused (`InvalidArgument`): rules are by address.
-- The destination is the address the guest sends to. DNS works while the resolver the guest uses is allowed: on a VM that is its virtual network's own resolver (`10.0.2.3` under QEMU, `172.16.0.1` in a Firecracker microVM); a container uses its engine's resolvers.
-- Never filtered: loopback inside the guest, replies to connections made to the guest (cua-spacesd, published ports), IPv6 neighbor discovery.
+- cloud metadata (`169.254.169.254`, `169.254.170.2`, `fd00:ec2::254`, `168.63.129.16`, `100.100.100.200`);
+- Spaces in other trees;
+- the Cua daemon on this computer;
+- this computer's own addresses, except the localhost ports the `localhost` preset lists.
+
+## Blocked unless a preset opens them
+
+Private networks (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`), link-local, unique-local IPv6, loopback, CGNAT (`100.64.0.0/10`, which covers Tailscale), multicast and other reserved ranges. `lan` opens the private, link-local and unique-local ranges. A custom `allow` can open one of them too, and `cua network show` then names what it opens ("Allows your local network (192.168.1.0/24)").
+
+DNS keeps working: the runtime's own resolver stays open on port 53.
+
+## Trees
+
+A Space created with a parent (`cua spaces create --parent studio`, or `parent=` in the SDK) joins its parent's tree. Spaces of one tree reach each other; other trees are blocked. A child's network is never more open than its parent's: its settings are cut down to what both allow. `--widen` lets it reach more, and the Space records who widened it and when. Tightening a parent tightens its children.
## Where it is enforced
-| Space | Enforced by |
-| --- | --- |
-| Container, runc or gVisor (any Docker engine, also the built-in runtime on a Mac) | nftables in the engine's own network namespace, on the Space's bridge port |
-| Firecracker microVM (Linux) | iptables in the network namespace pasta creates around the VM |
-| QEMU VM (Linux) | iptables in the network namespace pasta creates around QEMU |
-| A Space one of your machines provides (`on="host:..."`, `on="auto"`) | that machine, as above |
-| macOS VM, `vz` or Apple Containerization microVM, QEMU on macOS or Windows | refused (`Unsupported`): filtering them needs root (pf, WFP) |
-| Cua Cloud, your own cloud account (AWS, Google Cloud, Modal), a Space added by address | refused (`Unsupported`): no host-side point cua controls |
+| Space | Enforced by | Without protection |
+| --- | --- | --- |
+| Container, runc or gVisor (any Docker engine, also the built-in runtime on a Mac) | nftables in the engine's own network namespace, on the Space's bridge port; each tree gets its own Docker network | |
+| Firecracker microVM (Linux) | iptables in the network namespace pasta creates around the VM | |
+| QEMU VM (Linux) | iptables in the network namespace pasta creates around QEMU | |
+| A Space one of your computers provides | that computer, as above | |
+| `vz` microVM (Mac), QEMU on macOS or Windows | not yet | starts with no network; `unprotected` opens it |
+| macOS VM, Apple Containerization microVM | not yet | refused; `unprotected` starts it |
+| Your own cloud account (AWS, Google Cloud, Modal) | not yet | refused; `unprotected` creates it |
-`SpaceInfo.egress_enforced` is `host` for a Space with a policy. A machine whose cua predates egress policies never gets a Space with one: the create fails and the Space it made is deleted.
+A runtime that can't protect a Space never starts it open on its own. `cua network show` and `SpaceInfo.network_note` say why a Space has no network.
## Lifetime
-- The policy is in place before the guest's first instruction: a container's rules exist before it starts (keyed by the MAC address it is created with), a VM's namespace holds them before the VM boots.
-- It survives stop and start, suspend and resume, a restart of the daemon, forks and checkpoints (a fork inherits its source's policy).
-- `set_egress` applies at once. A running QEMU VM started without a policy first moves into its own namespace: its memory is carried over to a new QEMU process in a moment, and connections through the old one end.
+- The rules are in place before the guest's first instruction.
+- They survive stop and start, suspend and resume, a restart of the daemon, forks and checkpoints. A fork keeps its source's network and tree.
+- `set_network` applies at once where the runtime can change a running guest's network (containers, Linux VMs), and otherwise at the Space's next start. The result says which (`applied`).
+- An agent working through Cua's MCP tools can only tighten a Space's network. Opening more is yours to do, with `cua network set` or in the app.
-## What changes for a Space with a policy
+## Spaces from before network settings
-- A container created with a policy has no raw sockets (`CAP_NET_RAW`); `ping` still works through ICMP datagram sockets. Other containers on the same engine reach it only through the host (published ports), not directly over the bridge.
-- A QEMU VM with a policy reaches nothing on the host's loopback through `10.0.2.2`.
+Once Secure Spaces is on, a Space created before network settings moves to them at its next start: one with no egress policy gets `internet`, one with a policy gets `custom` with its lists kept, and one created with `network="none"` gets `none`. `cua network show` says so once. Turn the experiment off again and Spaces go back to the open network at their next start; nothing is deleted.
## Requirements
- Containers: `nft` (nftables) where the container engine runs.
- VMs on Linux: `pasta` (the passt package) and unprivileged user namespaces. Ubuntu 24.04 restricts those to programs with an AppArmor profile; allow pasta with one that grants `userns`, or set `kernel.apparmor_restrict_unprivileged_userns=0`.
-To check a policy from inside a Space as root: `nft flush ruleset; iptables -F` changes nothing, and a raw packet to a denied address gets no answer.
+To check it from inside a Space as root: `nft flush ruleset; iptables -F` changes nothing, a raw socket can't be opened in a container, and a connection to this computer's address times out.
+
+The older `egress` allow and deny lists (`SpaceCreateOptions.egress`, `set_egress`, `--egress-allow`, `--egress-deny`) still work: they are the lists of a `custom` network.
diff --git a/docs/content/docs/cua-sdk/guides/your-cloud.mdx b/docs/content/docs/cua-sdk/guides/your-cloud.mdx
index a9da9af9f6..dbe85f6651 100644
--- a/docs/content/docs/cua-sdk/guides/your-cloud.mdx
+++ b/docs/content/docs/cua-sdk/guides/your-cloud.mdx
@@ -218,7 +218,7 @@ does not stop the charge (see [Notes for each cloud](#notes-for-each-cloud)).
Agents use the same `create_space` tool with `on="aws"`, and `cloud_status`,
`cloud_test`, `cloud_connect`, `cloud_disconnect`, `cloud_sweep` and
`cloud_audit` from the
-[Spaces contract](/spaces/reference/spaces#your-cloud).
+[Spaces contract](/spaces/reference/sharing-and-cloud#your-cloud).
## What Cua creates
diff --git a/docs/content/docs/cua-sdk/reference/errors.mdx b/docs/content/docs/cua-sdk/reference/errors.mdx
index f90c70c631..bd54137b97 100644
--- a/docs/content/docs/cua-sdk/reference/errors.mdx
+++ b/docs/content/docs/cua-sdk/reference/errors.mdx
@@ -180,7 +180,7 @@ message names what is missing.
**Message** `unsupported: <detail>`
-**Raised by** [`Sandbox.guest_sh`](/cua-sdk/reference/spacesd#sandboxguest_sh), [`Sandbox.resize`](/cua-sdk/reference/sandbox/lifecycle#sandboxresize), [`Spaces.set_egress`](/cua-sdk/reference/spaces/lifetime#spacesset_egress), [`resolve_image`](/cua-sdk/reference/image#resolve_image)
+**Raised by** [`Sandbox.guest_sh`](/cua-sdk/reference/spacesd#sandboxguest_sh), [`Sandbox.resize`](/cua-sdk/reference/sandbox/lifecycle#sandboxresize), [`Spaces.set_egress`](/cua-sdk/reference/spaces/lifetime#spacesset_egress), [`Spaces.set_network`](/cua-sdk/reference/spaces/network#spacesset_network), [`resolve_image`](/cua-sdk/reference/image#resolve_image)
## `SpacesdNotAvailable`
diff --git a/docs/content/docs/cua-sdk/reference/index.mdx b/docs/content/docs/cua-sdk/reference/index.mdx
index bd580697df..c0c7aebd9e 100644
--- a/docs/content/docs/cua-sdk/reference/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/index.mdx
@@ -56,6 +56,10 @@ The Cua SDK in Python, TypeScript, Swift, Kotlin and Rust, all generated from th
| Page | Covers |
| --- | --- |
| [Spaces](/cua-sdk/reference/spaces) | The Spaces registry: create, add, resolve, delete and remove Spaces, their create options, and agent runs in a Space. |
+| [Space records](/cua-sdk/reference/spaces/info) | What a Space listing returns, and the Spaces tools `cua mcp` serves with the typed method that covers each. |
+| [Network settings (experiment)](/cua-sdk/reference/spaces/network) | What a Space can reach: its network preset, the allow and deny lists, and deleting a Space together with its children. |
+| [Child Spaces (experiment)](/cua-sdk/reference/spaces/children) | Let a Space make Spaces of its own, set the budget of its tree and list orphans. |
+| [Kept commands (experiment)](/cua-sdk/reference/spaces/services) | Keep a command running in a Space: restarts, health checks, start on boot and logs. |
| [Power and resize](/cua-sdk/reference/spaces/resize) | Stop, suspend and start a Space, and change a local VM's CPU, memory or disk while keeping its files. |
| [Lifetime and egress](/cua-sdk/reference/spaces/lifetime) | How long a Space lives and which destinations it may reach, set after it exists. |
| [Space](/cua-sdk/reference/spaces/space) | A connected Space: shell, files, tools, windows, icons, displays, the hotspot and teleport. |
@@ -99,4 +103,4 @@ The Cua SDK in Python, TypeScript, Swift, Kotlin and Rust, all generated from th
| --- | --- |
| [Protocol](/cua-sdk/reference/protocol) | The gRPC contracts of cua-spacesd (`cua.env.v1`) and the cua daemon (`cua.daemon.v1`). |
-356 items, 437 methods. The [Types](/cua-sdk/reference/types) page lists them.
+365 items, 452 methods. The [Types](/cua-sdk/reference/types) page lists them.
diff --git a/docs/content/docs/cua-sdk/reference/protocol/daemon-egress.mdx b/docs/content/docs/cua-sdk/reference/protocol/daemon-egress.mdx
index a5716cbacc..9b5c93f29f 100644
--- a/docs/content/docs/cua-sdk/reference/protocol/daemon-egress.mdx
+++ b/docs/content/docs/cua-sdk/reference/protocol/daemon-egress.mdx
@@ -48,6 +48,91 @@ Response for `SpaceService.SetSpaceEgress`.
No fields.
+### NetworkSettings
+
+A Space's network settings: a preset, the user's own lists, and what the
+host compiles them to. `Space.network_settings` and
+`CreateSpaceRequest.network_settings` carry it. The presets:
+
+- "internet" (the default): the public internet and the Space's own
+ tree; the host, the local network, cloud metadata, other trees and the
+ daemon are blocked;
+- "none": no network;
+- "localhost": "internet", plus the host's loopback on
+ `localhost_ports` (every port only with `all_localhost_ports`);
+- "lan": "internet", plus the local network (not the host itself);
+- "custom": `custom_base` ("internet" or "none") plus `allow` and `deny`;
+- "unprotected": everything but cloud metadata, other trees and the
+ daemon.
+
+`allow` and `deny` apply on top of any preset but "none": an allow is an
+exception to a deny and to the default blocks (not the host itself, which
+only "localhost" opens).
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `preset` | 1 | `string` | The preset word; empty is "internet". |
+| `localhost_ports` | 2 | repeated `uint32` | "localhost": the host loopback ports the Space may reach. |
+| `all_localhost_ports` | 3 | `bool` | "localhost": every port (the daemon's stay blocked). |
+| `allow` | 4 | repeated `string` | Destinations that stay reachable (addresses or CIDRs). |
+| `deny` | 5 | repeated `string` | Destinations that are blocked (addresses, CIDRs or "all"). |
+| `custom_base` | 6 | `string` | "custom": what it starts from, "internet" (empty) or "none". |
+| `widened_by` | 7 | `string` | Set when the Space was allowed more than its parent: who and when. |
+
+### SpaceNetworkInfo
+
+A Space's network as `cua network show` says it.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `settings` | 1 | [`NetworkSettings`](#networksettings) | Its settings. |
+| `summary` | 2 | `string` | One plain line ("Internet only"). |
+| `widenings` | 3 | repeated `string` | What the settings open beyond "internet", one plain line each. |
+| `enforcement` | 4 | `string` | "enforced" (rules on the host, outside the guest), "no_network" (its runtime can't protect it yet, so it has none), "open" (No protection) or "refused"; empty when unknown (a Space another machine runs). |
+| `point` | 5 | `string` | Where the rules are enforced, or why its network is cut, for people. |
+| `note` | 6 | `string` | Why its network is not what was asked, in plain words. |
+| `parent` | 7 | `string` | Its parent and its tree's top-level Space (ids); empty for a top-level Space. |
+| `root` | 8 | `string` | Its tree's top-level Space. |
+| `always_blocked` | 9 | repeated `string` | What no setting opens, in plain words. |
+| `notice_pending` | 10 | `bool` | An update changed its settings; say so once. |
+
+### GetSpaceNetworkRequest
+
+Request for `SpaceService.GetSpaceNetwork`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `space` | 1 | `string` | Space. |
+| `ack_notice` | 2 | `bool` | The caller showed the one-time notice about new network defaults: don't show it again. |
+
+### GetSpaceNetworkResponse
+
+Response for `SpaceService.GetSpaceNetwork`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `network` | 1 | [`SpaceNetworkInfo`](#spacenetworkinfo) | The Space's network. |
+
+### SetSpaceNetworkRequest
+
+Request for `SpaceService.SetSpaceNetwork`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `space` | 1 | `string` | Space. |
+| `settings` | 2 | [`NetworkSettings`](#networksettings) | The whole settings. |
+| `widen` | 3 | `bool` | A child: let it be more open than its parent (recorded). |
+| `tree` | 4 | `bool` | Its children take the same settings (each within its parent's). |
+
+### SetSpaceNetworkResponse
+
+Response for `SpaceService.SetSpaceNetwork`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `applied` | 1 | `string` | "now" or "next_start". |
+| `network` | 2 | [`SpaceNetworkInfo`](#spacenetworkinfo) | The Space's network after the change. |
+
## Types in `cua/env/v1/host_egress.proto`
### HostEgressPolicy
@@ -78,3 +163,19 @@ Response for `HostSpacesService.SetHostSpaceEgress`.
| Field | # | Type | Description |
| --- | --- | --- | --- |
| `enforced` | 1 | `string` | Where the policy is enforced: "host"; empty after a removal. |
+
+### HostNetworkSettings
+
+A Space's network settings (`cua.daemon.v1.NetworkSettings`), as
+`CreateHostSpaceRequest.network_settings` carries them to the host that
+creates the Space and enforces them.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `preset` | 1 | `string` | The preset word; empty is "internet". |
+| `localhost_ports` | 2 | repeated `uint32` | "localhost": the host loopback ports the Space may reach. |
+| `all_localhost_ports` | 3 | `bool` | "localhost": every port. |
+| `allow` | 4 | repeated `string` | Destinations that stay reachable. |
+| `deny` | 5 | repeated `string` | Destinations that are blocked. |
+| `custom_base` | 6 | `string` | "custom": "internet" (empty) or "none". |
+| `widened_by` | 7 | `string` | Set when the Space was allowed more than its parent. |
diff --git a/docs/content/docs/cua-sdk/reference/protocol/daemon-spaces.mdx b/docs/content/docs/cua-sdk/reference/protocol/daemon-spaces.mdx
index 6646013b5b..67e2345152 100644
--- a/docs/content/docs/cua-sdk/reference/protocol/daemon-spaces.mdx
+++ b/docs/content/docs/cua-sdk/reference/protocol/daemon-spaces.mdx
@@ -54,6 +54,12 @@ without touching it.
| [`DeleteBuild`](#spaceservicedeletebuild) | [`DeleteBuildRequest`](/cua-sdk/reference/protocol/daemon-builds#deletebuildrequest) | [`DeleteBuildResponse`](/cua-sdk/reference/protocol/daemon-builds#deletebuildresponse) | unary |
| [`SetSpaceLifetime`](#spaceservicesetspacelifetime) | [`SetSpaceLifetimeRequest`](#setspacelifetimerequest) | [`SetSpaceLifetimeResponse`](#setspacelifetimeresponse) | unary |
| [`SetSpaceEgress`](#spaceservicesetspaceegress) | [`SetSpaceEgressRequest`](/cua-sdk/reference/protocol/daemon-egress#setspaceegressrequest) | [`SetSpaceEgressResponse`](/cua-sdk/reference/protocol/daemon-egress#setspaceegressresponse) | unary |
+| [`GetSpaceNetwork`](#spaceservicegetspacenetwork) | [`GetSpaceNetworkRequest`](/cua-sdk/reference/protocol/daemon-egress#getspacenetworkrequest) | [`GetSpaceNetworkResponse`](/cua-sdk/reference/protocol/daemon-egress#getspacenetworkresponse) | unary |
+| [`SetSpaceNetwork`](#spaceservicesetspacenetwork) | [`SetSpaceNetworkRequest`](/cua-sdk/reference/protocol/daemon-egress#setspacenetworkrequest) | [`SetSpaceNetworkResponse`](/cua-sdk/reference/protocol/daemon-egress#setspacenetworkresponse) | unary |
+| [`SetSpaceChildren`](#spaceservicesetspacechildren) | [`SetSpaceChildrenRequest`](#setspacechildrenrequest) | [`SetSpaceChildrenResponse`](#setspacechildrenresponse) | unary |
+| [`GetTreeBudget`](#spaceservicegettreebudget) | [`GetTreeBudgetRequest`](#gettreebudgetrequest) | [`GetTreeBudgetResponse`](#gettreebudgetresponse) | unary |
+| [`SetTreeBudget`](#spaceservicesettreebudget) | [`SetTreeBudgetRequest`](#settreebudgetrequest) | [`SetTreeBudgetResponse`](#settreebudgetresponse) | unary |
+| [`ListOrphans`](#spaceservicelistorphans) | [`ListOrphansRequest`](#listorphansrequest) | [`ListOrphansResponse`](#listorphansresponse) | unary |
| [`ConnectSpace`](#spaceserviceconnectspace) | [`ConnectSpaceRequest`](#connectspacerequest) | [`ConnectSpaceResponse`](#connectspaceresponse) | unary |
| [`ListSpaceTools`](#spaceservicelistspacetools) | [`ListSpaceToolsRequest`](#listspacetoolsrequest) | [`ListSpaceToolsResponse`](#listspacetoolsresponse) | unary |
| [`CallSpaceTool`](#spaceservicecallspacetool) | [`CallSpaceToolRequest`](#callspacetoolrequest) | [`CallSpaceToolResponse`](#callspacetoolresponse) | unary |
@@ -169,7 +175,8 @@ wizard's GPU row; `gpu` of `CreateSpace`).
`/cua.daemon.v1.SpaceService/DeleteSpace`, unary: [`DeleteSpaceRequest`](#deletespacerequest) to [`DeleteSpaceResponse`](#deletespaceresponse).
Deletes a Space's sandbox and forgets it. A Space added by address
-(`direct:`, `relay:`) is only forgotten: cua did not create it.
+(`direct:`, `relay:`) is only forgotten: cua did not create it. Its
+child Spaces are deleted first, unless `keep_children`.
### SpaceService.DeleteSpaces
@@ -239,6 +246,51 @@ one). When it passes, this daemon deletes the Space (or turns it off,
Replaces a Space's egress policy (empty removes it).
+### SpaceService.GetSpaceNetwork
+
+`/cua.daemon.v1.SpaceService/GetSpaceNetwork`, unary: [`GetSpaceNetworkRequest`](/cua-sdk/reference/protocol/daemon-egress#getspacenetworkrequest) to [`GetSpaceNetworkResponse`](/cua-sdk/reference/protocol/daemon-egress#getspacenetworkresponse).
+
+A Space's network: its settings, what they open, where they are
+enforced (or why its network is cut), and what is always blocked.
+
+### SpaceService.SetSpaceNetwork
+
+`/cua.daemon.v1.SpaceService/SetSpaceNetwork`, unary: [`SetSpaceNetworkRequest`](/cua-sdk/reference/protocol/daemon-egress#setspacenetworkrequest) to [`SetSpaceNetworkResponse`](/cua-sdk/reference/protocol/daemon-egress#setspacenetworkresponse).
+
+Replaces a Space's network settings (a child's stay within its
+parent's unless `widen`).
+
+### SpaceService.SetSpaceChildren
+
+`/cua.daemon.v1.SpaceService/SetSpaceChildren`, unary: [`SetSpaceChildrenRequest`](#setspacechildrenrequest) to [`SetSpaceChildrenResponse`](#setspacechildrenresponse).
+
+Lets a Space make child Spaces of its own, or stops it. Turning it off
+ends the Space's spawn capability at once; children it already made
+keep running until they are deleted or their lifetime ends.
+
+### SpaceService.GetTreeBudget
+
+`/cua.daemon.v1.SpaceService/GetTreeBudget`, unary: [`GetTreeBudgetRequest`](#gettreebudgetrequest) to [`GetTreeBudgetResponse`](#gettreebudgetresponse).
+
+A tree's budget (kept on its top-level Space) and what its children
+use now. `space` may be any Space of the tree.
+
+### SpaceService.SetTreeBudget
+
+`/cua.daemon.v1.SpaceService/SetTreeBudget`, unary: [`SetTreeBudgetRequest`](#settreebudgetrequest) to [`SetTreeBudgetResponse`](#settreebudgetresponse).
+
+Sets a tree's budget: how many child Spaces, vCPUs and memory its
+children may hold at once, and what they may cost. Unset limits take
+the defaults; all unset removes the budget.
+
+### SpaceService.ListOrphans
+
+`/cua.daemon.v1.SpaceService/ListOrphans`, unary: [`ListOrphansRequest`](#listorphansrequest) to [`ListOrphansResponse`](#listorphansresponse).
+
+Child Spaces whose parent is gone, or not this machine's to judge: the
+ones it ends after a grace period (only on proof the parent is gone)
+and the ones it only lists.
+
### SpaceService.ConnectSpace
`/cua.daemon.v1.SpaceService/ConnectSpace`, unary: [`ConnectSpaceRequest`](#connectspacerequest) to [`ConnectSpaceResponse`](#connectspaceresponse).
@@ -423,6 +475,14 @@ A registered Space.
| `image_config` | 28 | `string` | JSON image configuration of a Space made from a build. |
| `sharing` | 32 | [`SpaceSharing`](#spacesharing) | A Space that is a machine on the relay: who owns it and who else has it, as this account sees it. Unset for other Spaces. Filled in when listed, not stored. |
| `display_name` | 33 | `string` | The name it was given with `RenameSpace`; empty when it keeps the one it was created with (`name`). Apps show this one when it is set. A Space that is a machine on the relay is renamed there, so its `name` changes instead. |
+| `network_settings` | 34 | [`NetworkSettings`](/cua-sdk/reference/protocol/daemon-egress#networksettings) | Its network settings. Unset for a Space created before they existed (it gets them on its next start). |
+| `network_note` | 35 | `string` | Why its network is not what was asked, in plain words (a runtime that can't protect it yet started it without network). Empty otherwise. |
+| `parent` | 36 | `string` | The Space it was created from (a child), by id; empty for a top-level Space. |
+| `root` | 37 | `string` | The top-level Space of its tree, by id; empty for a top-level Space. |
+| `network_notice_pending` | 38 | `bool` | Its network settings changed by an update (an old Space moved to the new defaults); apps and the CLI say so once. |
+| `depth` | 39 | `uint32` | How far below its tree's top-level Space it is: 0 for a top-level Space, 1 for its children, ... |
+| `origin` | 40 | `string` | How it was made: "user", "child" or "fork-batch:&lt;id&gt;". |
+| `children` | 43 | `bool` | The Space may make child Spaces of its own (`SetSpaceChildren`): `cua`, the SDKs and the agent's tools in it create, list and delete Spaces that belong to it, on a channel only it can reach. |
### SpaceSharing
@@ -780,6 +840,7 @@ Request for `SpaceService.DeleteSpace`.
| Field | # | Type | Description |
| --- | --- | --- | --- |
| `space` | 1 | `string` | Space. |
+| `keep_children` | 2 | `bool` | Keep its child Spaces: they become top-level Spaces and keep running. Unset: they are deleted first. |
### DeleteSpaceResponse
@@ -991,6 +1052,27 @@ Request for `SpaceService.CreateSpace`.
| `volumes` | 25 | repeated [`VolumeMount`](/cua-sdk/reference/protocol/env-stream#volumemount) | Named volumes of Cua Volume to mount in the Space. |
| `instance_type` | 26 | `string` | Cloud host machine type (a pin). |
| `region` | 27 | `string` | Cloud host region (a pin). |
+| `network_settings` | 28 | [`NetworkSettings`](/cua-sdk/reference/protocol/daemon-egress#networksettings) | Network settings. Unset: what `network` and `egress` say ("internet" when neither says anything). |
+| `parent` | 29 | `string` | Create it as a child of this Space (id or name): its network is no more open than the parent's. |
+| `widen` | 32 | `bool` | With `parent`: let it be more open than its parent (recorded on the Space). (30 and 31 are kept for other create options.) |
+| `children` | 33 | optional `bool` | Let the Space make child Spaces of its own (`SetSpaceChildren`). Unset: off. |
+
+### SetSpaceChildrenRequest
+
+Request for `SpaceService.SetSpaceChildren`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `space` | 1 | `string` | Id or name. |
+| `enabled` | 2 | `bool` | On or off. |
+
+### SetSpaceChildrenResponse
+
+Response for `SpaceService.SetSpaceChildren`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `space` | 1 | [`Space`](#space) | The Space as it is now. |
### CreateSpaceStreamRequest
@@ -1054,6 +1136,96 @@ Response for `SpaceService.GetGpuSupport`.
| --- | --- | --- | --- |
| `runtimes` | 1 | repeated [`GpuSupport`](#gpusupport) | One entry per runtime of the location. |
+### TreeBudgetLimits
+
+What a tree's children may hold and cost. Unset: the default.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `max_spaces` | 1 | optional `uint32` | Child Spaces at once (default 16). |
+| `max_vcpus` | 2 | optional `uint32` | vCPUs at once (default 16). |
+| `max_memory_mb` | 3 | optional `uint64` | Memory at once, MiB (default 32768). |
+| `usd_per_hour` | 4 | optional `double` | Cost per hour of what runs at once, in linked clouds (default 2.0). |
+| `usd_total` | 5 | optional `double` | Cost in total (default: no total cap). |
+
+### GetTreeBudgetRequest
+
+Request for `SpaceService.GetTreeBudget`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `space` | 1 | `string` | Any Space of the tree (id or name). |
+
+### SetTreeBudgetRequest
+
+Request for `SpaceService.SetTreeBudget`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `space` | 1 | `string` | Any Space of the tree (id or name); the budget is kept on its root. |
+| `limits` | 2 | [`TreeBudgetLimits`](#treebudgetlimits) | The limits. |
+
+### GetTreeBudgetResponse
+
+Response for `SpaceService.GetTreeBudget`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `budget` | 1 | [`TreeBudget`](#treebudget) | The budget and use. |
+
+### SetTreeBudgetResponse
+
+Response for `SpaceService.SetTreeBudget`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `budget` | 1 | [`TreeBudget`](#treebudget) | The budget and use. |
+
+### TreeBudget
+
+A tree's budget and use.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `root` | 1 | `string` | The tree's top-level Space. |
+| `set` | 2 | [`TreeBudgetLimits`](#treebudgetlimits) | What the owner set (unset fields take the default). |
+| `max_spaces` | 3 | `uint32` | Child Spaces it may hold at once. |
+| `max_vcpus` | 4 | `uint32` | vCPUs it may hold at once. |
+| `max_memory_mb` | 5 | `uint64` | Memory it may hold at once (MiB). |
+| `usd_per_hour` | 6 | `double` | Cost per hour it may run at. |
+| `usd_total` | 7 | optional `double` | Cost in total it may reach, when capped. |
+| `spaces` | 8 | `uint32` | Child Spaces now (creates in flight included). |
+| `vcpus` | 9 | `uint32` | vCPUs they hold. |
+| `memory_mb` | 10 | `uint64` | Memory they hold (MiB). |
+| `usd_per_hour_used` | 11 | `double` | Cost per hour they run at. |
+| `usd_spent` | 12 | `double` | What its children have cost so far. |
+
+### ListOrphansRequest
+
+Request for `SpaceService.ListOrphans`.
+
+No fields.
+
+### Orphan
+
+A child Space whose parent is gone or out of reach.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `space` | 1 | `string` | The child. |
+| `parent` | 2 | `string` | Its parent's id. |
+| `state` | 3 | `string` | "ending": its parent is provably gone and it ends after the grace; "listed": its parent is not this machine's to judge, so it stays until deleted or its own lifetime ends. |
+| `why` | 4 | `string` | Why, in words. |
+| `ends_in_secs` | 5 | `int64` | Seconds until it ends ("ending" only). |
+
+### ListOrphansResponse
+
+Response for `SpaceService.ListOrphans`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `orphans` | 1 | repeated [`Orphan`](#orphan) | By child id. |
+
## Types in `cua/daemon/v1/daemon.proto`
### DaemonErrorInfo
diff --git a/docs/content/docs/cua-sdk/reference/protocol/env-host-spaces.mdx b/docs/content/docs/cua-sdk/reference/protocol/env-host-spaces.mdx
index d1edb7bd2f..4ec41625e2 100644
--- a/docs/content/docs/cua-sdk/reference/protocol/env-host-spaces.mdx
+++ b/docs/content/docs/cua-sdk/reference/protocol/env-host-spaces.mdx
@@ -341,6 +341,7 @@ Request for `HostSpacesService.CreateHostSpace`.
| `fork_source` | 11 | `string` | Fork this checkpoint instead of creating from `image`. |
| `headless` | 14 | `bool` | No desktop (`cua.daemon.v1.CreateSpaceRequest.headless`). |
| `egress` | 19 | [`HostEgressPolicy`](/cua-sdk/reference/protocol/daemon-egress#hostegresspolicy) | Egress policy, enforced by the host from the guest's first instruction. A host that does not enforce it leaves `HostSpace.egress_enforced` empty. |
+| `network_settings` | 20 | [`HostNetworkSettings`](/cua-sdk/reference/protocol/daemon-egress#hostnetworksettings) | Network settings, compiled and enforced by the host. Unset: what `network` and `egress` say. |
| `routed` | 13 | `bool` | Reached through this host's channel (no relay machine of its own). |
| `env` | 15 | map of `string` to `string` | Guest environment; the host's driver settings win on a clash. |
| `gpu` | 16 | `string` | A GPU option of the host's runtime; empty: none. |
diff --git a/docs/content/docs/cua-sdk/reference/protocol/env-process.mdx b/docs/content/docs/cua-sdk/reference/protocol/env-process.mdx
index 527416e188..0959bc87d7 100644
--- a/docs/content/docs/cua-sdk/reference/protocol/env-process.mdx
+++ b/docs/content/docs/cua-sdk/reference/protocol/env-process.mdx
@@ -47,6 +47,11 @@ lets a reconnecting client drop output it has already seen.
| [`ResizePty`](#processserviceresizepty) | [`ResizePtyRequest`](#resizeptyrequest) | [`ResizePtyResponse`](#resizeptyresponse) | unary |
| [`GetExecRecord`](#processservicegetexecrecord) | [`GetExecRecordRequest`](#getexecrecordrequest) | [`GetExecRecordResponse`](#getexecrecordresponse) | unary |
| [`AdvanceEpoch`](#processserviceadvanceepoch) | [`AdvanceEpochRequest`](#advanceepochrequest) | [`AdvanceEpochResponse`](#advanceepochresponse) | unary |
+| [`PutService`](#processserviceputservice) | [`PutServiceRequest`](#putservicerequest) | [`PutServiceResponse`](#putserviceresponse) | unary |
+| [`DeleteService`](#processservicedeleteservice) | [`DeleteServiceRequest`](#deleteservicerequest) | [`DeleteServiceResponse`](#deleteserviceresponse) | unary |
+| [`ListServices`](#processservicelistservices) | [`ListServicesRequest`](#listservicesrequest) | [`ListServicesResponse`](#listservicesresponse) | unary |
+| [`ControlService`](#processservicecontrolservice) | [`ControlServiceRequest`](#controlservicerequest) | [`ControlServiceResponse`](#controlserviceresponse) | unary |
+| [`GetServiceLogs`](#processservicegetservicelogs) | [`GetServiceLogsRequest`](#getservicelogsrequest) | [`GetServiceLogsResponse`](#getservicelogsresponse) | unary |
### ProcessService.StartProcess
@@ -124,6 +129,41 @@ lower non-zero `StartProcessRequest.epoch` is killed (SIGKILL to its
process group), and later requests carrying a lower epoch fail with
FAILED_PRECONDITION / `ERROR_REASON_STALE_EPOCH`.
+### ProcessService.PutService
+
+`/cua.env.v1.ProcessService/PutService`, unary: [`PutServiceRequest`](#putservicerequest) to [`PutServiceResponse`](#putserviceresponse).
+
+Keeps a command running as a named service: started at once, started
+again by its restart policy when it exits or fails its health check,
+started when cua-spacesd starts (after the guest boots) unless
+`start_on_boot` is false, and its output kept in log files. Putting a
+name that exists replaces it (the old process is stopped first).
+
+### ProcessService.DeleteService
+
+`/cua.env.v1.ProcessService/DeleteService`, unary: [`DeleteServiceRequest`](#deleteservicerequest) to [`DeleteServiceResponse`](#deleteserviceresponse).
+
+Stops a service and forgets it (its log files go too).
+
+### ProcessService.ListServices
+
+`/cua.env.v1.ProcessService/ListServices`, unary: [`ListServicesRequest`](#listservicesrequest) to [`ListServicesResponse`](#listservicesresponse).
+
+Lists services with their state.
+
+### ProcessService.ControlService
+
+`/cua.env.v1.ProcessService/ControlService`, unary: [`ControlServiceRequest`](#controlservicerequest) to [`ControlServiceResponse`](#controlserviceresponse).
+
+Starts, stops or restarts a service. A stopped service stays stopped
+until started (also across a restart of cua-spacesd).
+
+### ProcessService.GetServiceLogs
+
+`/cua.env.v1.ProcessService/GetServiceLogs`, unary: [`GetServiceLogsRequest`](#getservicelogsrequest) to [`GetServiceLogsResponse`](#getservicelogsresponse).
+
+The end of a service's log.
+
## FilesystemService
`cua.env.v1.FilesystemService`
@@ -602,6 +642,131 @@ Response for `ProcessService.AdvanceEpoch`.
| `epoch` | 1 | `uint64` | The current epoch after the call. |
| `killed` | 2 | `uint32` | Running processes killed because they carried a lower epoch. |
+### HealthProbe
+
+How a service's health is checked. Set exactly one of `exec`, `http`,
+`tcp`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `exec` | 1 | [`ProcessConfig`](#processconfig) | A command that exits 0 when the service is healthy. |
+| `http` | 2 | `string` | A URL that answers 2xx or 3xx (`http://127.0.0.1:8080/health`). |
+| `tcp` | 3 | `string` | A port that accepts a TCP connection (`127.0.0.1:5432`). |
+| `interval` | 4 | `google.protobuf.Duration` | Between checks. Unset: 10 seconds. |
+| `timeout` | 5 | `google.protobuf.Duration` | For one check. Unset: 5 seconds. |
+| `failure_threshold` | 6 | `uint32` | Failed checks in a row that mark it unhealthy and restart it. 0: 3. |
+| `start_period` | 7 | `google.protobuf.Duration` | Grace after a start before the first check counts. Unset: 10 seconds. |
+
+### ServiceSpec
+
+A service: a named command kept running.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `name` | 1 | `string` | Name: lowercase letters, digits, `-`, `_` and `.`, 1 to 63 of them, starting with a letter or digit. |
+| `config` | 2 | [`ProcessConfig`](#processconfig) | What to run (`timeout` is ignored). |
+| `restart` | 3 | [`RestartPolicy`](#restartpolicy) | When it is started again. Unset: always. |
+| `backoff_min` | 4 | `google.protobuf.Duration` | First wait before a restart; it doubles on each quick failure. Unset: 1 second. |
+| `backoff_max` | 5 | `google.protobuf.Duration` | Longest wait before a restart. Unset: 60 seconds. |
+| `probe` | 6 | [`HealthProbe`](#healthprobe) | Health check. Unset: the service is healthy while it runs. |
+| `start_on_boot` | 7 | optional `bool` | Start it when cua-spacesd starts. Unset: true. |
+| `log_max_bytes` | 8 | `uint64` | Size at which the log file is rotated (one older file is kept). 0: 10 MiB. |
+
+### ServiceStatus
+
+A service and how it is doing.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `spec` | 1 | [`ServiceSpec`](#servicespec) | What it runs. |
+| `state` | 2 | [`ServiceState`](#servicestate) | Where it is. |
+| `pid` | 3 | `uint32` | Its current process, while it runs. |
+| `restarts` | 4 | `uint32` | Starts after the first one. |
+| `started_at` | 5 | `google.protobuf.Timestamp` | When the current (or last) process started. |
+| `last_end` | 6 | [`ProcessEnd`](#processend) | How the last process ended. |
+| `probe_error` | 7 | `string` | The last failed health check, empty when the last one passed. |
+| `next_start_at` | 8 | `google.protobuf.Timestamp` | When it starts again (state `SERVICE_STATE_BACKOFF`). |
+| `log_path` | 9 | `string` | Its log file in the guest. |
+
+### PutServiceRequest
+
+Request for `ProcessService.PutService`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `spec` | 1 | [`ServiceSpec`](#servicespec) | The service. |
+
+### PutServiceResponse
+
+Response for `ProcessService.PutService`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `service` | 1 | [`ServiceStatus`](#servicestatus) | Its state right after it was put. |
+
+### DeleteServiceRequest
+
+Request for `ProcessService.DeleteService`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `name` | 1 | `string` | Name. |
+
+### DeleteServiceResponse
+
+Response for `ProcessService.DeleteService`.
+
+No fields.
+
+### ListServicesRequest
+
+Request for `ProcessService.ListServices`.
+
+No fields.
+
+### ListServicesResponse
+
+Response for `ProcessService.ListServices`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `services` | 1 | repeated [`ServiceStatus`](#servicestatus) | By name. |
+
+### ControlServiceRequest
+
+Request for `ProcessService.ControlService`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `name` | 1 | `string` | Name. |
+| `action` | 2 | [`ServiceAction`](#serviceaction) | What to do. |
+
+### ControlServiceResponse
+
+Response for `ProcessService.ControlService`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `service` | 1 | [`ServiceStatus`](#servicestatus) | Its state after the action. |
+
+### GetServiceLogsRequest
+
+Request for `ProcessService.GetServiceLogs`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `name` | 1 | `string` | Name. |
+| `tail_bytes` | 2 | `uint64` | How many bytes from the end. 0: 64 KiB; at most 4 MiB. |
+
+### GetServiceLogsResponse
+
+Response for `ProcessService.GetServiceLogs`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `data` | 1 | `bytes` | The end of its output (stdout and stderr interleaved as written). |
+| `truncated` | 2 | `bool` | True when older output was left out. |
+
### ProcessState
Lifecycle state of a managed process.
@@ -646,6 +811,43 @@ Lifecycle of an exec ledger entry.
| `EXEC_STATE_EXITED` | 2 | Exited (or could not start); `ExecRecord.end` says how. |
| `EXEC_STATE_LOST` | 3 | Was running when the server stopped: the outcome is unknown. |
+### RestartPolicy
+
+When a service is started again.
+
+| Value | # | Description |
+| --- | --- | --- |
+| `RESTART_POLICY_UNSPECIFIED` | 0 | Unset: `RESTART_POLICY_ALWAYS`. |
+| `RESTART_POLICY_ALWAYS` | 1 | Whenever it ends, however it ends. |
+| `RESTART_POLICY_ON_FAILURE` | 2 | When it ends with a non-zero code, a signal, or a failed health check. |
+| `RESTART_POLICY_NEVER` | 3 | Never: it runs once. |
+
+### ServiceState
+
+Where a service is.
+
+| Value | # | Description |
+| --- | --- | --- |
+| `SERVICE_STATE_UNSPECIFIED` | 0 | Not reported. |
+| `SERVICE_STATE_STARTING` | 1 | Starting (or waiting for its first health check). |
+| `SERVICE_STATE_RUNNING` | 2 | Running, and healthy when it has a check. |
+| `SERVICE_STATE_UNHEALTHY` | 3 | Running, but its last checks failed. |
+| `SERVICE_STATE_BACKOFF` | 4 | Ended; waiting `next_start_at` to start again. |
+| `SERVICE_STATE_STOPPED` | 5 | Stopped by a caller. |
+| `SERVICE_STATE_EXITED` | 6 | Ended and its policy does not start it again. |
+| `SERVICE_STATE_FAILED` | 7 | Could not be started (the command does not exist, ...). |
+
+### ServiceAction
+
+What `ControlService` does.
+
+| Value | # | Description |
+| --- | --- | --- |
+| `SERVICE_ACTION_UNSPECIFIED` | 0 | Not set (refused). |
+| `SERVICE_ACTION_START` | 1 | Start it (no-op when it runs). |
+| `SERVICE_ACTION_STOP` | 2 | Stop it and keep it stopped. |
+| `SERVICE_ACTION_RESTART` | 3 | Stop it, then start it. |
+
## Types in `cua/env/v1/filesystem.proto`
### EntryInfo
diff --git a/docs/content/docs/cua-sdk/reference/protocol/env-stream.mdx b/docs/content/docs/cua-sdk/reference/protocol/env-stream.mdx
index 749bdcd9a1..ee27c229af 100644
--- a/docs/content/docs/cua-sdk/reference/protocol/env-stream.mdx
+++ b/docs/content/docs/cua-sdk/reference/protocol/env-stream.mdx
@@ -195,6 +195,11 @@ and gRPC-Web-only networks.
guest loopback relays each outbound connection over the client's
WebSocket, and the client dials it from its own network. Replaces the
unauthenticated rcdp-socks.
+- Spawn: the guest-to-host channel of child Spaces. A listener on guest
+ loopback relays each connection over the WebSocket of the host that runs
+ the Space, which serves this Space's own children (create, list, delete)
+ and nothing else. The host knows which Space a connection comes from by
+ the WebSocket it opened, never by anything the guest says.
| RPC | Request | Response | Kind |
| --- | --- | --- | --- |
@@ -204,6 +209,9 @@ and gRPC-Web-only networks.
| [`StartHotspot`](#tunnelservicestarthotspot) | [`StartHotspotRequest`](#starthotspotrequest) | [`StartHotspotResponse`](#starthotspotresponse) | unary |
| [`StopHotspot`](#tunnelservicestophotspot) | [`StopHotspotRequest`](#stophotspotrequest) | [`StopHotspotResponse`](#stophotspotresponse) | unary |
| [`GetHotspotStatus`](#tunnelservicegethotspotstatus) | [`GetHotspotStatusRequest`](#gethotspotstatusrequest) | [`GetHotspotStatusResponse`](#gethotspotstatusresponse) | unary |
+| [`StartSpawn`](#tunnelservicestartspawn) | [`StartSpawnRequest`](#startspawnrequest) | [`StartSpawnResponse`](#startspawnresponse) | unary |
+| [`StopSpawn`](#tunnelservicestopspawn) | [`StopSpawnRequest`](#stopspawnrequest) | [`StopSpawnResponse`](#stopspawnresponse) | unary |
+| [`GetSpawnStatus`](#tunnelservicegetspawnstatus) | [`GetSpawnStatusRequest`](#getspawnstatusrequest) | [`GetSpawnStatusResponse`](#getspawnstatusresponse) | unary |
### TunnelService.Forward
@@ -242,6 +250,26 @@ Stops the hotspot.
Reports hotspot state and counters.
+### TunnelService.StartSpawn
+
+`/cua.env.v1.TunnelService/StartSpawn`, unary: [`StartSpawnRequest`](#startspawnrequest) to [`StartSpawnResponse`](#startspawnresponse).
+
+Starts the spawn channel and installs the Space's spawn capability.
+Only a caller holding the Space's own token (the host that runs it) may
+call it; starting it again replaces the channel and the capability.
+
+### TunnelService.StopSpawn
+
+`/cua.env.v1.TunnelService/StopSpawn`, unary: [`StopSpawnRequest`](#stopspawnrequest) to [`StopSpawnResponse`](#stopspawnresponse).
+
+Stops the spawn channel and removes the capability from the guest.
+
+### TunnelService.GetSpawnStatus
+
+`/cua.env.v1.TunnelService/GetSpawnStatus`, unary: [`GetSpawnStatusRequest`](#getspawnstatusrequest) to [`GetSpawnStatusResponse`](#getspawnstatusresponse).
+
+Reports the spawn channel's state.
+
## VolumeService
`cua.env.v1.VolumeService`
@@ -1171,6 +1199,61 @@ Response for `TunnelService.GetHotspotStatus`.
| `bytes_out` | 6 | `uint64` | Bytes sent from the guest through the hotspot. |
| `bytes_in` | 7 | `uint64` | Bytes received into the guest through the hotspot. |
+### StartSpawnRequest
+
+Request for `TunnelService.StartSpawn`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `capability` | 1 | `string` | The Space's spawn capability, minted by its host. The guest writes it to the token file (0600, owner: the user cua-spacesd runs as) for clients in the Space to present on the spawn listener. |
+| `ticket_ttl` | 2 | `google.protobuf.Duration` | How long the ticket accepts the host's WebSocket. Unset means 60 seconds. |
+| `space_id` | 3 | `string` | The Space's id, for the environment of new processes (`CUA_SPACE`). |
+
+### StartSpawnResponse
+
+Response for `TunnelService.StartSpawn`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `spawn_id` | 1 | `string` | Spawn channel id. |
+| `ticket` | 2 | `string` | Ticket for the spawn WebSocket. |
+| `ws_path` | 3 | `string` | WebSocket path relative to the spacesd base URL, including the ticket, for example "/spawn?ticket=…". The host keeps this socket open; the listener refuses connections while it is closed. |
+| `address` | 4 | `string` | Guest-side listener, as a URL clients in the Space use as their cua daemon, for example "http://127.0.0.1:41234". |
+| `token_path` | 5 | `string` | Where the guest wrote the capability. |
+| `address_path` | 6 | `string` | Where the guest wrote the listener's address (one line). |
+
+### StopSpawnRequest
+
+Request for `TunnelService.StopSpawn`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `spawn_id` | 1 | `string` | Which channel. Empty stops the current one. |
+
+### StopSpawnResponse
+
+Response for `TunnelService.StopSpawn`.
+
+No fields.
+
+### GetSpawnStatusRequest
+
+Request for `TunnelService.GetSpawnStatus`.
+
+No fields.
+
+### GetSpawnStatusResponse
+
+Response for `TunnelService.GetSpawnStatus`.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `started` | 1 | `bool` | A channel is started. |
+| `attached` | 2 | `bool` | The host's WebSocket is attached. |
+| `spawn_id` | 3 | `string` | Channel id, when started. |
+| `address` | 4 | `string` | Guest-side listener URL, when started. |
+| `active_connections` | 5 | `uint32` | Open relayed connections. |
+
### HotspotState
Hotspot state.
diff --git a/docs/content/docs/cua-sdk/reference/protocol/index.mdx b/docs/content/docs/cua-sdk/reference/protocol/index.mdx
index cc00038a6b..060a187fb3 100644
--- a/docs/content/docs/cua-sdk/reference/protocol/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/protocol/index.mdx
@@ -39,7 +39,7 @@ Tickets go in `?ticket=` or the WebSocket subprotocol `cua.ticket.<ticket>`. Tic
| Service | Package | Page | RPCs |
| --- | --- | --- | --- |
| [`SystemService`](/cua-sdk/reference/protocol/env-system#systemservice) | `cua.env.v1` | [System, diagnostics and shared types](/cua-sdk/reference/protocol/env-system) | 10 |
-| [`ProcessService`](/cua-sdk/reference/protocol/env-process#processservice) | `cua.env.v1` | [Processes and files](/cua-sdk/reference/protocol/env-process) | 10 |
+| [`ProcessService`](/cua-sdk/reference/protocol/env-process#processservice) | `cua.env.v1` | [Processes and files](/cua-sdk/reference/protocol/env-process) | 15 |
| [`FilesystemService`](/cua-sdk/reference/protocol/env-process#filesystemservice) | `cua.env.v1` | [Processes and files](/cua-sdk/reference/protocol/env-process) | 16 |
| [`ComputerService`](/cua-sdk/reference/protocol/env-computer#computerservice) | `cua.env.v1` | [Computer, windows and accessibility](/cua-sdk/reference/protocol/env-computer) | 7 |
| [`DriverService`](/cua-sdk/reference/protocol/env-computer#driverservice) | `cua.env.v1` | [Computer, windows and accessibility](/cua-sdk/reference/protocol/env-computer) | 2 |
@@ -48,7 +48,7 @@ Tickets go in `?ticket=` or the WebSocket subprotocol `cua.ticket.<ticket>`. Tic
| [`StreamService`](/cua-sdk/reference/protocol/env-stream#streamservice) | `cua.env.v1` | [Streams, teleport and tunnels](/cua-sdk/reference/protocol/env-stream) | 5 |
| [`PresenceService`](/cua-sdk/reference/protocol/env-stream#presenceservice) | `cua.env.v1` | [Streams, teleport and tunnels](/cua-sdk/reference/protocol/env-stream) | 3 |
| [`TeleportService`](/cua-sdk/reference/protocol/env-stream#teleportservice) | `cua.env.v1` | [Streams, teleport and tunnels](/cua-sdk/reference/protocol/env-stream) | 7 |
-| [`TunnelService`](/cua-sdk/reference/protocol/env-stream#tunnelservice) | `cua.env.v1` | [Streams, teleport and tunnels](/cua-sdk/reference/protocol/env-stream) | 6 |
+| [`TunnelService`](/cua-sdk/reference/protocol/env-stream#tunnelservice) | `cua.env.v1` | [Streams, teleport and tunnels](/cua-sdk/reference/protocol/env-stream) | 9 |
| [`VolumeService`](/cua-sdk/reference/protocol/env-stream#volumeservice) | `cua.env.v1` | [Streams, teleport and tunnels](/cua-sdk/reference/protocol/env-stream) | 3 |
| [`HostSpacesService`](/cua-sdk/reference/protocol/env-host-spaces#hostspacesservice) | `cua.env.v1` | [Host Spaces](/cua-sdk/reference/protocol/env-host-spaces) | 9 |
| [`HostJobsService`](/cua-sdk/reference/protocol/env-host-spaces#hostjobsservice) | `cua.env.v1` | [Host Spaces](/cua-sdk/reference/protocol/env-host-spaces) | 4 |
@@ -59,7 +59,7 @@ Tickets go in `?ticket=` or the WebSocket subprotocol `cua.ticket.<ticket>`. Tic
| [`SandboxService`](/cua-sdk/reference/protocol/daemon#sandboxservice) | `cua.daemon.v1` | [Cua daemon: sandboxes and runtimes](/cua-sdk/reference/protocol/daemon) | 27 |
| [`PoolService`](/cua-sdk/reference/protocol/daemon#poolservice) | `cua.daemon.v1` | [Cua daemon: sandboxes and runtimes](/cua-sdk/reference/protocol/daemon) | 4 |
| [`RuntimeService`](/cua-sdk/reference/protocol/daemon#runtimeservice) | `cua.daemon.v1` | [Cua daemon: sandboxes and runtimes](/cua-sdk/reference/protocol/daemon) | 5 |
-| [`SpaceService`](/cua-sdk/reference/protocol/daemon-spaces#spaceservice) | `cua.daemon.v1` | [Daemon: Spaces and service](/cua-sdk/reference/protocol/daemon-spaces) | 33 |
+| [`SpaceService`](/cua-sdk/reference/protocol/daemon-spaces#spaceservice) | `cua.daemon.v1` | [Daemon: Spaces and service](/cua-sdk/reference/protocol/daemon-spaces) | 39 |
| [`DaemonService`](/cua-sdk/reference/protocol/daemon-spaces#daemonservice) | `cua.daemon.v1` | [Daemon: Spaces and service](/cua-sdk/reference/protocol/daemon-spaces) | 3 |
## Metadata and HTTP routes
@@ -75,6 +75,12 @@ Well-known metadata keys and HTTP paths (`cua_proto::metadata`).
| `MEDIA_WS_PATH` | `/media` | Media WebSocket path (ticket-authenticated). |
| `TUNNEL_WS_PATH` | `/tunnel` | TCP-over-WebSocket tunnel path (ticket-authenticated). |
| `HOTSPOT_WS_PATH` | `/hotspot` | Reverse-SOCKS hotspot WebSocket path (ticket-authenticated). |
+| `SPAWN_WS_PATH` | `/spawn` | Spawn channel WebSocket path (ticket-authenticated): the host that runs the Space serves its child-Space API over it. |
+| `SPAWN_TOKEN_FILE` | `spawn-token` | File (in a [`spawn_dirs`] directory) holding a Space's spawn capability. |
+| `SPAWN_ADDRESS_FILE` | `spawn-address` | File (in a [`spawn_dirs`] directory) holding the spawn listener's URL. |
+| `ENV_SPACE` | `CUA_SPACE` | Environment of processes in a Space: its id. |
+| `ENV_SPAWN` | `CUA_SPAWN` | Environment of processes in a Space: the spawn listener's URL. |
+| `ENV_SPAWN_TOKEN_FILE` | `CUA_SPAWN_TOKEN_FILE` | Environment of processes in a Space: the capability's file. |
| `VOLUME_WS_PATH` | `/volume` | Cua Volume WebSocket path (ticket-authenticated): the client serves the guest's volume mount over it. |
| `FILES_PATH` | `/files` | Signed-URL file route. |
| `MCP_PATH` | `/mcp` | Streamable-HTTP MCP endpoint for the cua-driver tool registry. |
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx
index 97c79dbf20..a1a75c919f 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx
@@ -18,7 +18,7 @@ The cua SDK: the only `#[uniffi::export]` crate of `libs/cua`.
These are the objects, records, enums and functions the language bindings export, documented once in the [Cua SDK reference](/cua-sdk/reference), whose Rust tabs show each signature. Objects are `Arc<T>` handles whose methods are `async fn` returning `Result<_, CuaError>`, records are structs with public fields, and names are snake_case.
-[`agent_event_category`](/cua-sdk/reference/agents#agent_event_category), [`agent_harnesses`](/cua-sdk/reference/agents#agent_harnesses), [`AgentActionReport`](/cua-sdk/reference/spaces/agents#agentactionreport-record), [`AgentArtifact`](/cua-sdk/reference/agents#agentartifact-record), [`AgentDelivery`](/cua-sdk/reference/spaces/persistent-agents#agentdelivery-record), [`AgentEvent`](/cua-sdk/reference/agents#agentevent-record), [`AgentEventPage`](/cua-sdk/reference/agents#agenteventpage-record), [`AgentFile`](/cua-sdk/reference/agents#agentfile-record), [`AgentInfo`](/cua-sdk/reference/agent-setup#agentinfo-record), [`AgentMcpServer`](/cua-sdk/reference/agent-setup#agentmcpserver-record), [`AgentPauseReport`](/cua-sdk/reference/spaces/persistent-agents#agentpausereport-record), [`AgentResumeReport`](/cua-sdk/reference/spaces/persistent-agents#agentresumereport-record), [`AgentRun`](/cua-sdk/reference/agents#agentrun), [`AgentRunInfo`](/cua-sdk/reference/agents#agentruninfo-record), [`AgentRunMcpServer`](/cua-sdk/reference/agents#agentrunmcpserver-record), [`AgentRunOptions`](/cua-sdk/reference/agents#agentrunoptions-record), [`AgentRunResult`](/cua-sdk/reference/agents#agentrunresult-record), [`AgentRunStatus`](/cua-sdk/reference/spaces/agents#agentrunstatus-record), [`Agents`](/cua-sdk/reference/agents#agents), [`AgentSetup`](/cua-sdk/reference/agent-setup#agentsetup), [`AgentSetupChange`](/cua-sdk/reference/agent-setup#agentsetupchange-enum), [`AgentSetupOutcome`](/cua-sdk/reference/agent-setup#agentsetupoutcome-record), [`AgentSetupTarget`](/cua-sdk/reference/agent-setup#agentsetuptarget-enum), [`AgentStartReport`](/cua-sdk/reference/spaces/agents#agentstartreport-record), [`AgentTranscript`](/cua-sdk/reference/agents#agenttranscript), [`AgentTranscriptItem`](/cua-sdk/reference/agents#agenttranscriptitem-record), [`ambiguous_sandbox_candidates`](/cua-sdk/reference/sandbox/lifecycle#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/computer#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/computer#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BakeForkCheck`](/cua-sdk/reference/sandbox/bake#bakeforkcheck-record), [`BakeOptions`](/cua-sdk/reference/sandbox/bake#bakeoptions-record), [`BakeSummary`](/cua-sdk/reference/sandbox/bake#bakesummary-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-record), [`BuildImageConfig`](/cua-sdk/reference/spaces/build#buildimageconfig-record), [`BuildInfo`](/cua-sdk/reference/spaces/build#buildinfo-record), [`BuildListener`](/cua-sdk/reference/spaces/build#buildlistener), [`BuildOptions`](/cua-sdk/reference/spaces/build#buildoptions-record), [`BuildProgress`](/cua-sdk/reference/spaces/build#buildprogress-record), [`BuildResult`](/cua-sdk/reference/spaces/build#buildresult-record), [`BuildStep`](/cua-sdk/reference/spaces/build#buildstep-enum), [`BuildStepResult`](/cua-sdk/reference/spaces/build#buildstepresult-record), [`BulkResult`](/cua-sdk/reference/spaces/sharing#bulkresult-record), [`BundledSkill`](/cua-sdk/reference/agent-setup#bundledskill-record), [`canonical_image`](/cua-sdk/reference/image#canonical_image), [`canonical_image_tier`](/cua-sdk/reference/image#canonical_image_tier), [`check_placement`](/cua-sdk/reference/cua#check_placement), [`CheckpointSummary`](/cua-sdk/reference/sandbox/checkpoints#checkpointsummary-record), [`CloudAuditEntry`](/cua-sdk/reference/spaces/persistent-agents#cloudauditentry-record), [`CloudCheck`](/cua-sdk/reference/spaces/persistent-agents#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/persistent-agents#cloudconnected-record), [`CloudConnectOptions`](/cua-sdk/reference/spaces/persistent-agents#cloudconnectoptions-record), [`CloudCostReport`](/cua-sdk/reference/spaces/persistent-agents#cloudcostreport-record), [`CloudCostRow`](/cua-sdk/reference/spaces/persistent-agents#cloudcostrow-record), [`CloudCredentials`](/cua-sdk/reference/spaces/persistent-agents#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/persistent-agents#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/persistent-agents#cloudkind-record), [`CloudNext`](/cua-sdk/reference/spaces/persistent-agents#cloudnext-record), [`CloudProvider`](/cua-sdk/reference/spaces/persistent-agents#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/persistent-agents#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/persistent-agents#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/persistent-agents#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/persistent-agents#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-record), [`ComputerResources`](/cua-sdk/reference/spaces/resources#computerresources-record), [`config_get`](/cua-sdk/reference/cua#config_get), [`config_list`](/cua-sdk/reference/cua#config_list), [`config_path`](/cua-sdk/reference/cua#config_path), [`config_set`](/cua-sdk/reference/cua#config_set), [`config_unset`](/cua-sdk/reference/cua#config_unset), [`ConfigEntry`](/cua-sdk/reference/cua#configentry-record), [`Container`](/cua-sdk/reference/image#container-record), [`contrib_providers_built`](/cua-sdk/reference/sandbox#contrib_providers_built), [`Cua`](/cua-sdk/reference/cua#cua), [`CuaConfig`](/cua-sdk/reference/cua#cuaconfig-record), [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record), [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum), [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record), [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/host#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record), [`DiskLevel`](/cua-sdk/reference/spaces/resources#disklevel-enum), [`DiskOnHost`](/cua-sdk/reference/spaces/resources#diskonhost-record), [`DiskWarning`](/cua-sdk/reference/spaces/resources#diskwarning-record), [`DoctorReport`](/cua-sdk/reference/cua#doctorreport-record), [`DriveAccessRequest`](/cua-sdk/reference/spaces/volume#driveaccessrequest-record), [`DriveAudit`](/cua-sdk/reference/spaces/volume#driveaudit-record), [`DriveAuditEvent`](/cua-sdk/reference/spaces/volume#driveauditevent-record), [`DriveCacheStats`](/cua-sdk/reference/spaces/volume#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume#drivedevice-record), [`DriveEntry`](/cua-sdk/reference/spaces/volume#driveentry-record), [`DriveFile`](/cua-sdk/reference/spaces/volume#drivefile-record), [`DriveFileSync`](/cua-sdk/reference/spaces/volume#drivefilesync-record), [`DriveGrant`](/cua-sdk/reference/spaces/volume#drivegrant-record), [`DriveListing`](/cua-sdk/reference/spaces/volume#drivelisting-record), [`DriveMountStatus`](/cua-sdk/reference/spaces/volume#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`EgressEnforcement`](/cua-sdk/reference/spaces/space#egressenforcement-enum), [`EgressPolicy`](/cua-sdk/reference/spaces#egresspolicy-record), [`ElasticAssignment`](/cua-sdk/reference/spaces/elastic#elasticassignment-record), [`ElasticBudget`](/cua-sdk/reference/spaces/elastic#elasticbudget-record), [`ElasticBudgetUpdate`](/cua-sdk/reference/spaces/elastic#elasticbudgetupdate-record), [`ElasticDecision`](/cua-sdk/reference/spaces/elastic#elasticdecision-record), [`ElasticHost`](/cua-sdk/reference/spaces/elastic#elastichost-record), [`ElasticNewHost`](/cua-sdk/reference/spaces/elastic#elasticnewhost-record), [`ElasticPlan`](/cua-sdk/reference/spaces/elastic#elasticplan-record), [`ElasticPlanRequest`](/cua-sdk/reference/spaces/elastic#elasticplanrequest-record), [`ElasticRemoved`](/cua-sdk/reference/spaces/elastic#elasticremoved-record), [`ElasticUnplaced`](/cua-sdk/reference/spaces/elastic#elasticunplaced-record), [`ForkBatch`](/cua-sdk/reference/sandbox/fork-batch#forkbatch), [`ForkBatchEvent`](/cua-sdk/reference/sandbox/fork-batch#forkbatchevent-enum), [`ForkBatchItem`](/cua-sdk/reference/sandbox/fork-batch#forkbatchitem-record), [`ForkBatchPlacement`](/cua-sdk/reference/sandbox/fork-batch#forkbatchplacement-record), [`ForkBatchResult`](/cua-sdk/reference/sandbox/fork-batch#forkbatchresult-record), [`ForkBatchSummary`](/cua-sdk/reference/sandbox/fork-batch#forkbatchsummary-record), [`ForkGroup`](/cua-sdk/reference/sandbox/fork-batch#forkgroup-record), [`ForkManyOptions`](/cua-sdk/reference/sandbox/fork-batch#forkmanyoptions-record), [`FrameSink`](/cua-sdk/reference/spacesd/computer#framesink), [`GpuOption`](/cua-sdk/reference/spaces#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/spacesd#guestdisplay), [`GuestUsage`](/cua-sdk/reference/spaces/resources#guestusage-record), [`HomeTransfer`](/cua-sdk/reference/spaces/persistent-agents#hometransfer-record), [`Host`](/cua-sdk/reference/spaces/host#host), [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record), [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record), [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record), [`HostServiceMigration`](/cua-sdk/reference/spaces/host#hostservicemigration-record), [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record), [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record), [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record), [`HostStatus`](/cua-sdk/reference/spaces/host#hoststatus-record), [`HttpHeader`](/cua-sdk/reference/services#httpheader-record), [`HttpResponse`](/cua-sdk/reference/services#httpresponse-record), [`image_alias`](/cua-sdk/reference/image#image_alias), [`ImageBuild`](/cua-sdk/reference/image#imagebuild-record), [`ImageInfo`](/cua-sdk/reference/image#imageinfo-record), [`ImageLayer`](/cua-sdk/reference/image#imagelayer-enum), [`Local`](/cua-sdk/reference/cua#local), [`LocalImage`](/cua-sdk/reference/cua#localimage-record), [`LocalStorage`](/cua-sdk/reference/cua#localstorage-record), [`LocationInfo`](/cua-sdk/reference/cua#locationinfo-record), [`locations`](/cua-sdk/reference/cua#locations), [`LoginAttempt`](/cua-sdk/reference/auth#loginattempt), [`LoginMethod`](/cua-sdk/reference/auth#loginmethod-enum), [`MachineHealth`](/cua-sdk/reference/spaces/host#machinehealth-record), [`MachineHealthCheck`](/cua-sdk/reference/spaces/host#machinehealthcheck-record), [`may_have_session`](/cua-sdk/reference/auth#may_have_session), [`mcp_connect`](/cua-sdk/reference/services#mcp_connect), [`mcp_connect_url`](/cua-sdk/reference/services#mcp_connect_url), [`McpClient`](/cua-sdk/reference/services#mcpclient), [`McpConfig`](/cua-sdk/reference/services#mcpconfig-record), [`MediaBridge`](/cua-sdk/reference/spacesd/computer#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/computer#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record), [`NamedVolume`](/cua-sdk/reference/spaces/volume#namedvolume-record), [`normalize_image`](/cua-sdk/reference/image#normalize_image), [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record), [`omarchy_image`](/cua-sdk/reference/image#omarchy_image), [`Overlay`](/cua-sdk/reference/sandbox#overlay-record), [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record), [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PoolCreateOptions`](/cua-sdk/reference/image#poolcreateoptions-record), [`PortForward`](/cua-sdk/reference/services#portforward), [`presence_color`](/cua-sdk/reference/spaces/streams#presence_color), [`presence_conformance_json`](/cua-sdk/reference/spaces/streams#presence_conformance_json), [`presence_cursor_art`](/cua-sdk/reference/spaces/streams#presence_cursor_art), [`presence_cursor_art_all`](/cua-sdk/reference/spaces/streams#presence_cursor_art_all), [`presence_cursor_art_svg`](/cua-sdk/reference/spaces/streams#presence_cursor_art_svg), [`presence_now_ms`](/cua-sdk/reference/spaces/streams#presence_now_ms), [`presence_text_color`](/cua-sdk/reference/spaces/streams#presence_text_color), [`PresenceCursor`](/cua-sdk/reference/spaces/streams#presencecursor-record), [`PresenceDrawable`](/cua-sdk/reference/spaces/streams#presencedrawable-record), [`PresenceEvent`](/cua-sdk/reference/spaces/streams#presenceevent-record), [`PresenceIdentity`](/cua-sdk/reference/spaces/streams#presenceidentity-record), [`PresenceMember`](/cua-sdk/reference/spaces/streams#presencemember-record), [`PresenceParticipant`](/cua-sdk/reference/spaces/streams#presenceparticipant-record), [`PresencePoint`](/cua-sdk/reference/spaces/streams#presencepoint-record), [`PresenceView`](/cua-sdk/reference/spaces/streams#presenceview), [`Prewarm`](/cua-sdk/reference/spaces/elastic#prewarm-record), [`PrewarmOptions`](/cua-sdk/reference/spaces/elastic#prewarmoptions-record), [`PrewarmPlacement`](/cua-sdk/reference/spaces/elastic#prewarmplacement-record), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/image#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/host#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record), [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record), [`ReplayMode`](/cua-sdk/reference/spacesd/shell#replaymode-enum), [`repo_cache_clear`](/cua-sdk/reference/repo-cache#repo_cache_clear), [`repo_cache_status`](/cua-sdk/reference/repo-cache#repo_cache_status), [`RepoCacheStatus`](/cua-sdk/reference/repo-cache#repocachestatus-record), [`resolve_image`](/cua-sdk/reference/image#resolve_image), [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret), [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record), [`ResourcesEvent`](/cua-sdk/reference/spaces/resources#resourcesevent-enum), [`ResourcesListener`](/cua-sdk/reference/spaces/resources#resourceslistener), [`ResourcesSnapshot`](/cua-sdk/reference/spaces/resources#resourcessnapshot-record), [`ResourcesUpdate`](/cua-sdk/reference/spaces/resources#resourcesupdate-record), [`ResourcesWatch`](/cua-sdk/reference/spaces/resources#resourceswatch), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum), [`RuntimeDetected`](/cua-sdk/reference/runtime-kinds#runtimedetected-record), [`RuntimeKindState`](/cua-sdk/reference/runtime-kinds#runtimekindstate-record), [`RuntimePathProbe`](/cua-sdk/reference/runtime-kinds#runtimepathprobe-record), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record), [`Sandboxes`](/cua-sdk/reference/sandbox#sandboxes), [`SandboxInfo`](/cua-sdk/reference/sandbox#sandboxinfo-record), [`SandboxListing`](/cua-sdk/reference/sandbox#sandboxlisting-record), [`SandboxPhase`](/cua-sdk/reference/sandbox#sandboxphase-enum), [`SandboxPool`](/cua-sdk/reference/image#sandboxpool-record), [`SandboxRefParts`](/cua-sdk/reference/sandbox/lifecycle#sandboxrefparts-record), [`SandboxStatus`](/cua-sdk/reference/sandbox#sandboxstatus-enum), [`Service`](/cua-sdk/reference/services#service), [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record), [`SetupStep`](/cua-sdk/reference/cua#setupstep-record), [`Share`](/cua-sdk/reference/share#share-record), [`ShareAccess`](/cua-sdk/reference/share#shareaccess-enum), [`ShareCheck`](/cua-sdk/reference/share#sharecheck-record), [`SharedBase`](/cua-sdk/reference/spaces/space#sharedbase-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`SnapshotFallbackOptions`](/cua-sdk/reference/sandbox/fork-batch#snapshotfallbackoptions-record), [`SnapshotSyncProgress`](/cua-sdk/reference/sandbox/fork-batch#snapshotsyncprogress-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces/agents#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/space#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/space#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces#spacecreateresult-record), [`SpaceCreatingElsewhere`](/cua-sdk/reference/spaces/space#spacecreatingelsewhere-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record), [`SpaceList`](/cua-sdk/reference/spaces/list-watch#spacelist-record), [`SpacePowerReport`](/cua-sdk/reference/spaces/resize#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/relay-registration#spacerelayregistration-record), [`SpaceResizeReport`](/cua-sdk/reference/spaces/resize#spaceresizereport-record), [`SpaceResources`](/cua-sdk/reference/spaces/resources#spaceresources-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`SpacesdDownload`](/cua-sdk/reference/spacesd#spacesddownload), [`SpacesdForward`](/cua-sdk/reference/spacesd#spacesdforward), [`SpacesdHttpHeader`](/cua-sdk/reference/spacesd#spacesdhttpheader-record), [`SpacesdHttpRequest`](/cua-sdk/reference/spacesd#spacesdhttprequest-record), [`SpacesdHttpResponse`](/cua-sdk/reference/spacesd#spacesdhttpresponse-record), [`SpacesdProcess`](/cua-sdk/reference/spacesd/shell#spacesdprocess), [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record), [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record), [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record), [`SpaceShareEntry`](/cua-sdk/reference/spaces/sharing#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/sharing#spaceshares-record), [`SpaceSharing`](/cua-sdk/reference/spaces/sharing#spacesharing-record), [`SpacesHost`](/cua-sdk/reference/spaces/host#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/host#spaceshostlimit-record), [`SpacesHostLoad`](/cua-sdk/reference/spaces/host#spaceshostload-record), [`SpacesListListener`](/cua-sdk/reference/spaces/list-watch#spaceslistlistener), [`SpacesListWatch`](/cua-sdk/reference/spaces/list-watch#spaceslistwatch), [`SpacesToolMethod`](/cua-sdk/reference/spaces#spacestoolmethod-record), [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record), [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession), [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record), [`SpaceStreamTicket`](/cua-sdk/reference/spaces/streams#spacestreamticket-record), [`SpaceTeamShare`](/cua-sdk/reference/spaces/sharing#spaceteamshare-record), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceTransport`](/cua-sdk/reference/spaces/channel#spacetransport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/space#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/cua#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/auth#streamstatsreport-record), [`telemetry_acknowledge_link_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_link_notice), [`telemetry_acknowledge_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/auth#telemetry_flush), [`telemetry_link_notice`](/cua-sdk/reference/auth#telemetry_link_notice), [`telemetry_link_notice_due`](/cua-sdk/reference/auth#telemetry_link_notice_due), [`telemetry_link_state`](/cua-sdk/reference/auth#telemetry_link_state), [`telemetry_notice_text`](/cua-sdk/reference/auth#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/auth#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/auth#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/auth#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/auth#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/auth#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/auth#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/auth#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/auth#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/auth#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/auth#telemetry_status), [`telemetry_sync_account`](/cua-sdk/reference/auth#telemetry_sync_account), [`telemetry_use_app_notice`](/cua-sdk/reference/auth#telemetry_use_app_notice), [`TelemetryLinkNotice`](/cua-sdk/reference/auth#telemetrylinknotice-record), [`TelemetryStatus`](/cua-sdk/reference/auth#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/space#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/space#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/space#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/space#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/space#teleportreceipt-record), [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record), [`VolumeMount`](/cua-sdk/reference/spaces/volume#volumemount-record).
+[`agent_event_category`](/cua-sdk/reference/agents#agent_event_category), [`agent_harnesses`](/cua-sdk/reference/agents#agent_harnesses), [`AgentActionReport`](/cua-sdk/reference/spaces/agents#agentactionreport-record), [`AgentArtifact`](/cua-sdk/reference/agents#agentartifact-record), [`AgentDelivery`](/cua-sdk/reference/spaces/persistent-agents#agentdelivery-record), [`AgentEvent`](/cua-sdk/reference/agents#agentevent-record), [`AgentEventPage`](/cua-sdk/reference/agents#agenteventpage-record), [`AgentFile`](/cua-sdk/reference/agents#agentfile-record), [`AgentInfo`](/cua-sdk/reference/agent-setup#agentinfo-record), [`AgentMcpServer`](/cua-sdk/reference/agent-setup#agentmcpserver-record), [`AgentPauseReport`](/cua-sdk/reference/spaces/persistent-agents#agentpausereport-record), [`AgentResumeReport`](/cua-sdk/reference/spaces/persistent-agents#agentresumereport-record), [`AgentRun`](/cua-sdk/reference/agents#agentrun), [`AgentRunInfo`](/cua-sdk/reference/agents#agentruninfo-record), [`AgentRunMcpServer`](/cua-sdk/reference/agents#agentrunmcpserver-record), [`AgentRunOptions`](/cua-sdk/reference/agents#agentrunoptions-record), [`AgentRunResult`](/cua-sdk/reference/agents#agentrunresult-record), [`AgentRunStatus`](/cua-sdk/reference/spaces/agents#agentrunstatus-record), [`Agents`](/cua-sdk/reference/agents#agents), [`AgentSetup`](/cua-sdk/reference/agent-setup#agentsetup), [`AgentSetupChange`](/cua-sdk/reference/agent-setup#agentsetupchange-enum), [`AgentSetupOutcome`](/cua-sdk/reference/agent-setup#agentsetupoutcome-record), [`AgentSetupTarget`](/cua-sdk/reference/agent-setup#agentsetuptarget-enum), [`AgentStartReport`](/cua-sdk/reference/spaces/agents#agentstartreport-record), [`AgentTranscript`](/cua-sdk/reference/agents#agenttranscript), [`AgentTranscriptItem`](/cua-sdk/reference/agents#agenttranscriptitem-record), [`ambiguous_sandbox_candidates`](/cua-sdk/reference/sandbox/lifecycle#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/computer#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/computer#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BakeForkCheck`](/cua-sdk/reference/sandbox/bake#bakeforkcheck-record), [`BakeOptions`](/cua-sdk/reference/sandbox/bake#bakeoptions-record), [`BakeSummary`](/cua-sdk/reference/sandbox/bake#bakesummary-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-record), [`BuildImageConfig`](/cua-sdk/reference/spaces/build#buildimageconfig-record), [`BuildInfo`](/cua-sdk/reference/spaces/build#buildinfo-record), [`BuildListener`](/cua-sdk/reference/spaces/build#buildlistener), [`BuildOptions`](/cua-sdk/reference/spaces/build#buildoptions-record), [`BuildProgress`](/cua-sdk/reference/spaces/build#buildprogress-record), [`BuildResult`](/cua-sdk/reference/spaces/build#buildresult-record), [`BuildStep`](/cua-sdk/reference/spaces/build#buildstep-enum), [`BuildStepResult`](/cua-sdk/reference/spaces/build#buildstepresult-record), [`BulkResult`](/cua-sdk/reference/spaces/sharing#bulkresult-record), [`BundledSkill`](/cua-sdk/reference/agent-setup#bundledskill-record), [`canonical_image`](/cua-sdk/reference/image#canonical_image), [`canonical_image_tier`](/cua-sdk/reference/image#canonical_image_tier), [`check_placement`](/cua-sdk/reference/cua#check_placement), [`CheckpointSummary`](/cua-sdk/reference/sandbox/checkpoints#checkpointsummary-record), [`CloudAuditEntry`](/cua-sdk/reference/spaces/persistent-agents#cloudauditentry-record), [`CloudCheck`](/cua-sdk/reference/spaces/persistent-agents#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/persistent-agents#cloudconnected-record), [`CloudConnectOptions`](/cua-sdk/reference/spaces/persistent-agents#cloudconnectoptions-record), [`CloudCostReport`](/cua-sdk/reference/spaces/persistent-agents#cloudcostreport-record), [`CloudCostRow`](/cua-sdk/reference/spaces/persistent-agents#cloudcostrow-record), [`CloudCredentials`](/cua-sdk/reference/spaces/persistent-agents#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/persistent-agents#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/persistent-agents#cloudkind-record), [`CloudNext`](/cua-sdk/reference/spaces/persistent-agents#cloudnext-record), [`CloudProvider`](/cua-sdk/reference/spaces/persistent-agents#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/persistent-agents#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/persistent-agents#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/persistent-agents#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/persistent-agents#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-record), [`ComputerResources`](/cua-sdk/reference/spaces/resources#computerresources-record), [`config_get`](/cua-sdk/reference/cua#config_get), [`config_list`](/cua-sdk/reference/cua#config_list), [`config_path`](/cua-sdk/reference/cua#config_path), [`config_set`](/cua-sdk/reference/cua#config_set), [`config_unset`](/cua-sdk/reference/cua#config_unset), [`ConfigEntry`](/cua-sdk/reference/cua#configentry-record), [`Container`](/cua-sdk/reference/image#container-record), [`contrib_providers_built`](/cua-sdk/reference/sandbox#contrib_providers_built), [`Cua`](/cua-sdk/reference/cua#cua), [`CuaConfig`](/cua-sdk/reference/cua#cuaconfig-record), [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record), [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum), [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record), [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/host#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record), [`DiskLevel`](/cua-sdk/reference/spaces/resources#disklevel-enum), [`DiskOnHost`](/cua-sdk/reference/spaces/resources#diskonhost-record), [`DiskWarning`](/cua-sdk/reference/spaces/resources#diskwarning-record), [`DoctorReport`](/cua-sdk/reference/cua#doctorreport-record), [`DriveAccessRequest`](/cua-sdk/reference/spaces/volume#driveaccessrequest-record), [`DriveAudit`](/cua-sdk/reference/spaces/volume#driveaudit-record), [`DriveAuditEvent`](/cua-sdk/reference/spaces/volume#driveauditevent-record), [`DriveCacheStats`](/cua-sdk/reference/spaces/volume#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume#drivedevice-record), [`DriveEntry`](/cua-sdk/reference/spaces/volume#driveentry-record), [`DriveFile`](/cua-sdk/reference/spaces/volume#drivefile-record), [`DriveFileSync`](/cua-sdk/reference/spaces/volume#drivefilesync-record), [`DriveGrant`](/cua-sdk/reference/spaces/volume#drivegrant-record), [`DriveListing`](/cua-sdk/reference/spaces/volume#drivelisting-record), [`DriveMountStatus`](/cua-sdk/reference/spaces/volume#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`EgressEnforcement`](/cua-sdk/reference/spaces/space#egressenforcement-enum), [`EgressPolicy`](/cua-sdk/reference/spaces#egresspolicy-record), [`ElasticAssignment`](/cua-sdk/reference/spaces/elastic#elasticassignment-record), [`ElasticBudget`](/cua-sdk/reference/spaces/elastic#elasticbudget-record), [`ElasticBudgetUpdate`](/cua-sdk/reference/spaces/elastic#elasticbudgetupdate-record), [`ElasticDecision`](/cua-sdk/reference/spaces/elastic#elasticdecision-record), [`ElasticHost`](/cua-sdk/reference/spaces/elastic#elastichost-record), [`ElasticNewHost`](/cua-sdk/reference/spaces/elastic#elasticnewhost-record), [`ElasticPlan`](/cua-sdk/reference/spaces/elastic#elasticplan-record), [`ElasticPlanRequest`](/cua-sdk/reference/spaces/elastic#elasticplanrequest-record), [`ElasticRemoved`](/cua-sdk/reference/spaces/elastic#elasticremoved-record), [`ElasticUnplaced`](/cua-sdk/reference/spaces/elastic#elasticunplaced-record), [`ForkBatch`](/cua-sdk/reference/sandbox/fork-batch#forkbatch), [`ForkBatchEvent`](/cua-sdk/reference/sandbox/fork-batch#forkbatchevent-enum), [`ForkBatchItem`](/cua-sdk/reference/sandbox/fork-batch#forkbatchitem-record), [`ForkBatchPlacement`](/cua-sdk/reference/sandbox/fork-batch#forkbatchplacement-record), [`ForkBatchResult`](/cua-sdk/reference/sandbox/fork-batch#forkbatchresult-record), [`ForkBatchSummary`](/cua-sdk/reference/sandbox/fork-batch#forkbatchsummary-record), [`ForkGroup`](/cua-sdk/reference/sandbox/fork-batch#forkgroup-record), [`ForkManyOptions`](/cua-sdk/reference/sandbox/fork-batch#forkmanyoptions-record), [`FrameSink`](/cua-sdk/reference/spacesd/computer#framesink), [`GpuOption`](/cua-sdk/reference/spaces#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/spacesd#guestdisplay), [`GuestUsage`](/cua-sdk/reference/spaces/resources#guestusage-record), [`HomeTransfer`](/cua-sdk/reference/spaces/persistent-agents#hometransfer-record), [`Host`](/cua-sdk/reference/spaces/host#host), [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record), [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record), [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record), [`HostServiceMigration`](/cua-sdk/reference/spaces/host#hostservicemigration-record), [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record), [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record), [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record), [`HostStatus`](/cua-sdk/reference/spaces/host#hoststatus-record), [`HttpHeader`](/cua-sdk/reference/services#httpheader-record), [`HttpResponse`](/cua-sdk/reference/services#httpresponse-record), [`image_alias`](/cua-sdk/reference/image#image_alias), [`ImageBuild`](/cua-sdk/reference/image#imagebuild-record), [`ImageInfo`](/cua-sdk/reference/image#imageinfo-record), [`ImageLayer`](/cua-sdk/reference/image#imagelayer-enum), [`Local`](/cua-sdk/reference/cua#local), [`LocalImage`](/cua-sdk/reference/cua#localimage-record), [`LocalStorage`](/cua-sdk/reference/cua#localstorage-record), [`LocationInfo`](/cua-sdk/reference/cua#locationinfo-record), [`locations`](/cua-sdk/reference/cua#locations), [`LoginAttempt`](/cua-sdk/reference/auth#loginattempt), [`LoginMethod`](/cua-sdk/reference/auth#loginmethod-enum), [`MachineHealth`](/cua-sdk/reference/spaces/host#machinehealth-record), [`MachineHealthCheck`](/cua-sdk/reference/spaces/host#machinehealthcheck-record), [`may_have_session`](/cua-sdk/reference/auth#may_have_session), [`mcp_connect`](/cua-sdk/reference/services#mcp_connect), [`mcp_connect_url`](/cua-sdk/reference/services#mcp_connect_url), [`McpClient`](/cua-sdk/reference/services#mcpclient), [`McpConfig`](/cua-sdk/reference/services#mcpconfig-record), [`MediaBridge`](/cua-sdk/reference/spacesd/computer#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/computer#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record), [`NamedVolume`](/cua-sdk/reference/spaces/volume#namedvolume-record), [`NetworkSettings`](/cua-sdk/reference/spaces/network#networksettings-record), [`normalize_image`](/cua-sdk/reference/image#normalize_image), [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record), [`omarchy_image`](/cua-sdk/reference/image#omarchy_image), [`Overlay`](/cua-sdk/reference/sandbox#overlay-record), [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record), [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PoolCreateOptions`](/cua-sdk/reference/image#poolcreateoptions-record), [`PortForward`](/cua-sdk/reference/services#portforward), [`presence_color`](/cua-sdk/reference/spaces/streams#presence_color), [`presence_conformance_json`](/cua-sdk/reference/spaces/streams#presence_conformance_json), [`presence_cursor_art`](/cua-sdk/reference/spaces/streams#presence_cursor_art), [`presence_cursor_art_all`](/cua-sdk/reference/spaces/streams#presence_cursor_art_all), [`presence_cursor_art_svg`](/cua-sdk/reference/spaces/streams#presence_cursor_art_svg), [`presence_now_ms`](/cua-sdk/reference/spaces/streams#presence_now_ms), [`presence_text_color`](/cua-sdk/reference/spaces/streams#presence_text_color), [`PresenceCursor`](/cua-sdk/reference/spaces/streams#presencecursor-record), [`PresenceDrawable`](/cua-sdk/reference/spaces/streams#presencedrawable-record), [`PresenceEvent`](/cua-sdk/reference/spaces/streams#presenceevent-record), [`PresenceIdentity`](/cua-sdk/reference/spaces/streams#presenceidentity-record), [`PresenceMember`](/cua-sdk/reference/spaces/streams#presencemember-record), [`PresenceParticipant`](/cua-sdk/reference/spaces/streams#presenceparticipant-record), [`PresencePoint`](/cua-sdk/reference/spaces/streams#presencepoint-record), [`PresenceView`](/cua-sdk/reference/spaces/streams#presenceview), [`Prewarm`](/cua-sdk/reference/spaces/elastic#prewarm-record), [`PrewarmOptions`](/cua-sdk/reference/spaces/elastic#prewarmoptions-record), [`PrewarmPlacement`](/cua-sdk/reference/spaces/elastic#prewarmplacement-record), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/image#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/host#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record), [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record), [`ReplayMode`](/cua-sdk/reference/spacesd/shell#replaymode-enum), [`repo_cache_clear`](/cua-sdk/reference/repo-cache#repo_cache_clear), [`repo_cache_status`](/cua-sdk/reference/repo-cache#repo_cache_status), [`RepoCacheStatus`](/cua-sdk/reference/repo-cache#repocachestatus-record), [`resolve_image`](/cua-sdk/reference/image#resolve_image), [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret), [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record), [`ResourcesEvent`](/cua-sdk/reference/spaces/resources#resourcesevent-enum), [`ResourcesListener`](/cua-sdk/reference/spaces/resources#resourceslistener), [`ResourcesSnapshot`](/cua-sdk/reference/spaces/resources#resourcessnapshot-record), [`ResourcesUpdate`](/cua-sdk/reference/spaces/resources#resourcesupdate-record), [`ResourcesWatch`](/cua-sdk/reference/spaces/resources#resourceswatch), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum), [`RuntimeDetected`](/cua-sdk/reference/runtime-kinds#runtimedetected-record), [`RuntimeKindState`](/cua-sdk/reference/runtime-kinds#runtimekindstate-record), [`RuntimePathProbe`](/cua-sdk/reference/runtime-kinds#runtimepathprobe-record), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record), [`Sandboxes`](/cua-sdk/reference/sandbox#sandboxes), [`SandboxInfo`](/cua-sdk/reference/sandbox#sandboxinfo-record), [`SandboxListing`](/cua-sdk/reference/sandbox#sandboxlisting-record), [`SandboxPhase`](/cua-sdk/reference/sandbox#sandboxphase-enum), [`SandboxPool`](/cua-sdk/reference/image#sandboxpool-record), [`SandboxRefParts`](/cua-sdk/reference/sandbox/lifecycle#sandboxrefparts-record), [`SandboxStatus`](/cua-sdk/reference/sandbox#sandboxstatus-enum), [`Service`](/cua-sdk/reference/services#service), [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record), [`SetNetworkResult`](/cua-sdk/reference/spaces/network#setnetworkresult-record), [`SetupStep`](/cua-sdk/reference/cua#setupstep-record), [`Share`](/cua-sdk/reference/share#share-record), [`ShareAccess`](/cua-sdk/reference/share#shareaccess-enum), [`ShareCheck`](/cua-sdk/reference/share#sharecheck-record), [`SharedBase`](/cua-sdk/reference/spaces/space#sharedbase-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`SnapshotFallbackOptions`](/cua-sdk/reference/sandbox/fork-batch#snapshotfallbackoptions-record), [`SnapshotSyncProgress`](/cua-sdk/reference/sandbox/fork-batch#snapshotsyncprogress-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces/agents#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/space#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/space#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces#spacecreateresult-record), [`SpaceCreatingElsewhere`](/cua-sdk/reference/spaces/space#spacecreatingelsewhere-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces/info#spaceinfo-record), [`SpaceList`](/cua-sdk/reference/spaces/list-watch#spacelist-record), [`SpaceNetworkInfo`](/cua-sdk/reference/spaces/network#spacenetworkinfo-record), [`SpaceOrphan`](/cua-sdk/reference/spaces/children#spaceorphan-record), [`SpacePowerReport`](/cua-sdk/reference/spaces/resize#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/relay-registration#spacerelayregistration-record), [`SpaceResizeReport`](/cua-sdk/reference/spaces/resize#spaceresizereport-record), [`SpaceResources`](/cua-sdk/reference/spaces/resources#spaceresources-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces/info#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`SpacesdDownload`](/cua-sdk/reference/spacesd#spacesddownload), [`SpacesdForward`](/cua-sdk/reference/spacesd#spacesdforward), [`SpacesdHttpHeader`](/cua-sdk/reference/spacesd#spacesdhttpheader-record), [`SpacesdHttpRequest`](/cua-sdk/reference/spacesd#spacesdhttprequest-record), [`SpacesdHttpResponse`](/cua-sdk/reference/spacesd#spacesdhttpresponse-record), [`SpacesdProcess`](/cua-sdk/reference/spacesd/shell#spacesdprocess), [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record), [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record), [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record), [`SpaceServiceDef`](/cua-sdk/reference/spaces/services#spaceservicedef-record), [`SpaceServiceInfo`](/cua-sdk/reference/spaces/services#spaceserviceinfo-record), [`SpaceServiceProbe`](/cua-sdk/reference/spaces/services#spaceserviceprobe-record), [`SpaceShareEntry`](/cua-sdk/reference/spaces/sharing#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/sharing#spaceshares-record), [`SpaceSharing`](/cua-sdk/reference/spaces/sharing#spacesharing-record), [`SpacesHost`](/cua-sdk/reference/spaces/host#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/host#spaceshostlimit-record), [`SpacesHostLoad`](/cua-sdk/reference/spaces/host#spaceshostload-record), [`SpacesListListener`](/cua-sdk/reference/spaces/list-watch#spaceslistlistener), [`SpacesListWatch`](/cua-sdk/reference/spaces/list-watch#spaceslistwatch), [`SpacesToolMethod`](/cua-sdk/reference/spaces/info#spacestoolmethod-record), [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record), [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession), [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record), [`SpaceStreamTicket`](/cua-sdk/reference/spaces/streams#spacestreamticket-record), [`SpaceTeamShare`](/cua-sdk/reference/spaces/sharing#spaceteamshare-record), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceTransport`](/cua-sdk/reference/spaces/channel#spacetransport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/space#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/cua#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/auth#streamstatsreport-record), [`telemetry_acknowledge_link_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_link_notice), [`telemetry_acknowledge_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/auth#telemetry_flush), [`telemetry_link_notice`](/cua-sdk/reference/auth#telemetry_link_notice), [`telemetry_link_notice_due`](/cua-sdk/reference/auth#telemetry_link_notice_due), [`telemetry_link_state`](/cua-sdk/reference/auth#telemetry_link_state), [`telemetry_notice_text`](/cua-sdk/reference/auth#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/auth#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/auth#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/auth#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/auth#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/auth#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/auth#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/auth#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/auth#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/auth#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/auth#telemetry_status), [`telemetry_sync_account`](/cua-sdk/reference/auth#telemetry_sync_account), [`telemetry_use_app_notice`](/cua-sdk/reference/auth#telemetry_use_app_notice), [`TelemetryLinkNotice`](/cua-sdk/reference/auth#telemetrylinknotice-record), [`TelemetryStatus`](/cua-sdk/reference/auth#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/space#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/space#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/space#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/space#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/space#teleportreceipt-record), [`TreeBudget`](/cua-sdk/reference/spaces/children#treebudget-record), [`TreeBudgetLimits`](/cua-sdk/reference/spaces/children#treebudgetlimits-record), [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record), [`VolumeMount`](/cua-sdk/reference/spaces/volume#volumemount-record).
## Types
diff --git a/docs/content/docs/cua-sdk/reference/spaces/children.mdx b/docs/content/docs/cua-sdk/reference/spaces/children.mdx
new file mode 100644
index 0000000000..4d83fd5e42
--- /dev/null
+++ b/docs/content/docs/cua-sdk/reference/spaces/children.mdx
@@ -0,0 +1,272 @@
+---
+title: "Child Spaces (experiment)"
+description: "Let a Space make Spaces of its own, set the budget of its tree and list orphans."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:cua-sdk
+ Source: cua-bindgen docs (UniFFI metadata of libcua_sdk)
+ Version: 0.10.1
+*/}
+
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+These calls belong to the Child Spaces experiment (`cua experiments enable child-spaces`) and are refused while it is off. `set_children` lets a Space make children through a channel only it can reach; `tree_budget` and `set_tree_budget` bound what a tree may hold and spend; `orphans` lists children whose parent is gone. See [Child Spaces](/spaces/guides/child-spaces).
+
+## Children
+
+Methods of [`Spaces`](/cua-sdk/reference/spaces#spaces).
+
+### `Spaces.set_children`
+
+Lets a Space make child Spaces of its own, or stops it. While on,
+`cua`, the SDKs and the agent's tools in that Space create, list and
+delete Spaces that belong to it (on the same computer, never wider
+than it, ending no later than it), through a channel only it can
+reach. Off ends its capability at once; children it made keep running
+until deleted or their lifetime ends. Only for a Space the machine of
+this runtime runs itself.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def set_children(self, space: str, enabled: bool) -> None
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+setChildren(space: string, enabled: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<void>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func setChildren(space: String, enabled: Bool) async throws
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun setChildren(space: String, enabled: Boolean)
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn set_children(&self, space: String, enabled: bool) -> Result<(), CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `space` | `String` | required |
+| `enabled` | `bool` | required |
+
+**Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Spaces.tree_budget`
+
+The budget of `space`'s tree (any Space of it) and what its
+children use now. Kept by the cua daemon.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def tree_budget(self, space: str) -> TreeBudget
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+treeBudget(space: string, asyncOpts_?: { signal: AbortSignal }): Promise<TreeBudget>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func treeBudget(space: String) async throws -> TreeBudget
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun treeBudget(space: String): TreeBudget
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn tree_budget(&self, space: String) -> Result<TreeBudget, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `space` | `String` | required |
+
+**Returns** [`TreeBudget`](#treebudget-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Spaces.set_tree_budget`
+
+Sets the budget of `space`'s tree: how many child Spaces, vCPUs and
+memory its children may hold at once, and what they may cost. A child
+that does not fit is refused with what is left. All `None` removes it.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def set_tree_budget(self, space: str, limits: TreeBudgetLimits) -> TreeBudget
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+setTreeBudget(space: string, limits: TreeBudgetLimits, asyncOpts_?: { signal: AbortSignal }): Promise<TreeBudget>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func setTreeBudget(space: String, limits: TreeBudgetLimits) async throws -> TreeBudget
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun setTreeBudget(space: String, limits: TreeBudgetLimits): TreeBudget
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn set_tree_budget(&self, space: String, limits: TreeBudgetLimits) -> Result<TreeBudget, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `space` | `String` | required |
+| `limits` | [`TreeBudgetLimits`](#treebudgetlimits-record) | required |
+
+**Returns** [`TreeBudget`](#treebudget-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Spaces.orphans`
+
+Child Spaces whose parent is gone or out of reach. The cua daemon
+ends a child only on proof its parent is gone (after a grace period);
+the rest are listed here and never ended by it.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def orphans(self) -> List[SpaceOrphan]
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+orphans(asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceOrphan>>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func orphans() async throws -> [SpaceOrphan]
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun orphans(): List<SpaceOrphan>
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn orphans(&self) -> Result<Vec<SpaceOrphan>, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+**Returns** [`Vec<SpaceOrphan>`](#spaceorphan-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+## `TreeBudget` record
+
+A tree's budget and what its children use (`Spaces.tree_budget`).
+
+Returned by [`Spaces.set_tree_budget`](#spacesset_tree_budget), [`Spaces.tree_budget`](#spacestree_budget).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `root` | `String` | | The tree's top-level Space. |
+| `set` | [`TreeBudgetLimits`](#treebudgetlimits-record) | | What the owner set. |
+| `max_spaces` / `maxSpaces` | `u32` | | Child Spaces it may hold at once. |
+| `max_vcpus` / `maxVcpus` | `u32` | | vCPUs it may hold at once. |
+| `max_memory_mb` / `maxMemoryMb` | `u64` | | Memory it may hold at once (MiB). |
+| `usd_per_hour` / `usdPerHour` | `f64` | | Cost per hour it may run at. |
+| `usd_total` / `usdTotal` | `Option<f64>` | | Cost in total it may reach, when capped. |
+| `spaces` | `u32` | | Child Spaces now. |
+| `vcpus` | `u32` | | vCPUs they hold. |
+| `memory_mb` / `memoryMb` | `u64` | | Memory they hold (MiB). |
+| `usd_per_hour_used` / `usdPerHourUsed` | `f64` | | Cost per hour they run at. |
+| `usd_spent` / `usdSpent` | `f64` | | What they have cost so far. |
+
+## `TreeBudgetLimits` record
+
+What a tree's children may hold and cost (`Spaces.set_tree_budget`).
+`None`: the default.
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `max_spaces` / `maxSpaces` | `Option<u32>` | `None` | Child Spaces at once (default 16). |
+| `max_vcpus` / `maxVcpus` | `Option<u32>` | `None` | vCPUs at once (default 16). |
+| `max_memory_mb` / `maxMemoryMb` | `Option<u64>` | `None` | Memory at once, MiB (default 32768). |
+| `usd_per_hour` / `usdPerHour` | `Option<f64>` | `None` | Cost per hour, in linked clouds (default 2.0). |
+| `usd_total` / `usdTotal` | `Option<f64>` | `None` | Cost in total (default: none). |
+
+## `SpaceOrphan` record
+
+A child Space whose parent is gone or out of reach (`Spaces.orphans`).
+
+Returned by [`Spaces.orphans`](#spacesorphans).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `space` | `String` | | The child. |
+| `parent` | `String` | | Its parent's id. |
+| `state` | `String` | | `ending` (its parent is provably gone: it ends after the grace) or `listed` (not this computer's to judge: it stays until deleted or its own lifetime ends). |
+| `why` | `String` | | Why. |
+| `ends_in_secs` / `endsInSecs` | `i64` | | Seconds until it ends (`ending` only). |
diff --git a/docs/content/docs/cua-sdk/reference/spaces/index.mdx b/docs/content/docs/cua-sdk/reference/spaces/index.mdx
index a32601d110..9f8b9cd6be 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/index.mdx
@@ -43,6 +43,7 @@ Returned by [`Cua.spaces`](/cua-sdk/reference/cua#cua).
| [`start`](#spacesstart) | Turns a Space on again: resumes a suspended one, boots a stopped one (a Space one of your machines provides joins the relay again), and leaves a running one as it is. |
| [`stop`](#spacesstop) | Turns a Space off the way its provider can (`SpaceInfo.power`): stops it, keeping its disk and freeing its memory (a local VM; a Space one of your machines provides, which that machine stops), or suspends it, keeping its memory (a local container that cannot stop). `Spaces.suspend` suspends a local container or QEMU VM on purpose. |
| [`suspend`](#spacessuspend) | Suspends a local Space (a container or a QEMU VM), keeping its memory: it resumes where it was, and its memory stays in use until then. `Spaces.stop` stops it instead and frees its memory. |
+| [`ack_network_notice`](/cua-sdk/reference/spaces/network#spacesack_network_notice) | Marks the one-time notice about the new network defaults as shown for `space` (`SpaceNetworkInfo.notice_pending`). |
| [`agent_capabilities`](/cua-sdk/reference/spaces/agents#spacesagent_capabilities) | What every agent harness is and cannot do (`agent_capabilities`), as JSON. |
| [`agent_pause`](/cua-sdk/reference/spaces/persistent-agents#spacesagent_pause) | Pauses a persistent agent: run, routines and (local) Space. |
| [`agent_resume`](/cua-sdk/reference/spaces/persistent-agents#spacesagent_resume) | Resumes a paused persistent agent; with `prompt`, starts a run. |
@@ -69,13 +70,16 @@ Returned by [`Cua.spaces`](/cua-sdk/reference/cua#cua).
| [`create_volume`](/cua-sdk/reference/spaces/volume#spacescreate_volume) | Creates the empty named volume `name` (1 to 63 of `a-z`, `0-9`, `.`, `_`, `-`). |
| [`delete_build`](/cua-sdk/reference/spaces/build#spacesdelete_build) | Deletes a build: its tags and the layer checkpoints no other build uses. |
| [`delete_many`](/cua-sdk/reference/spaces/sharing#spacesdelete_many) | Deletes several Spaces (`Spaces.delete` each), at most three at a time, turning running ones off first. |
+| [`delete_tree`](/cua-sdk/reference/spaces/network#spacesdelete_tree) | `Spaces.delete`, with `keep_children`: its child Spaces become top-level Spaces and keep running instead of being deleted first. |
| [`delete_volume`](/cua-sdk/reference/spaces/volume#spacesdelete_volume) | Deletes the named volume `name` and its files (their history stays in the Cua Volume). |
| [`fork`](/cua-sdk/reference/sandbox/checkpoints#spacesfork) | Starts Space `name` from `source` (a Space id such as `local:<name>`, a sandbox name, a checkpoint name, or the tag of a build (`Spaces.build`) or its checkpoint; a sandbox wins) and returns it connected. |
| [`leave_many`](/cua-sdk/reference/spaces/sharing#spacesleave_many) | Takes this account off Spaces shared with it (through the relay): a direct share ends, a team's Space leaves this account's list. |
| [`machine_health`](/cua-sdk/reference/spaces/host#spacesmachine_health) | A machine's health as its own cua daemon checks it: Local Network access (and which app macOS holds responsible), free disk, virtualization, memory left by running Spaces, the permissions sharing its desktop needs. |
+| [`network`](/cua-sdk/reference/spaces/network#spacesnetwork) | A Space's network: its settings, what they open, where they are enforced (or why its network is cut), and what is always blocked. |
| [`notifications`](/cua-sdk/reference/spaces/persistent-agents#spacesnotifications) | The notifications feed, newest first. |
| [`notifications_ack`](/cua-sdk/reference/spaces/persistent-agents#spacesnotifications_ack) | Marks notifications read (every one when `ids` is empty). |
| [`notify_user`](/cua-sdk/reference/spaces/persistent-agents#spacesnotify_user) | Posts a notification to the Cua app. |
+| [`orphans`](/cua-sdk/reference/spaces/children#spacesorphans) | Child Spaces whose parent is gone or out of reach. |
| [`persistent_agent_create`](/cua-sdk/reference/spaces/persistent-agents#spacespersistent_agent_create) | Creates a persistent agent: `harness` working in `space`, its home at `agents/<name>/` in the Cua Volume. |
| [`persistent_agent_remove`](/cua-sdk/reference/spaces/persistent-agents#spacespersistent_agent_remove) | Forgets a persistent agent (its home stays in the drive). |
| [`persistent_agent_save`](/cua-sdk/reference/spaces/persistent-agents#spacespersistent_agent_save) | Saves a persistent agent's home into the drive now. |
@@ -92,8 +96,12 @@ Returned by [`Cua.spaces`](/cua-sdk/reference/cua#cua).
| [`routine_remove`](/cua-sdk/reference/spaces/persistent-agents#spacesroutine_remove) | Deletes a routine. |
| [`routine_set_enabled`](/cua-sdk/reference/spaces/persistent-agents#spacesroutine_set_enabled) | Turns a routine on or off. |
| [`routines`](/cua-sdk/reference/spaces/persistent-agents#spacesroutines) | Routines (of one agent, or all). |
+| [`set_children`](/cua-sdk/reference/spaces/children#spacesset_children) | Lets a Space make child Spaces of its own, or stops it. |
| [`set_egress`](/cua-sdk/reference/spaces/lifetime#spacesset_egress) | Replaces a Space's egress policy; an empty one removes it (see `EgressPolicy`). |
| [`set_lifetime`](/cua-sdk/reference/spaces/lifetime#spacesset_lifetime) | Gives a Space a lifetime of `seconds` from now, replacing any earlier one: when it passes, the cua daemon deletes the Space (`on_expire` `"delete"`, the default) or turns it off (`"suspend"`), whether or not this process is still running. |
+| [`set_network`](/cua-sdk/reference/spaces/network#spacesset_network) | Replaces a Space's network settings (see `NetworkSettings`). |
+| [`set_tree_budget`](/cua-sdk/reference/spaces/children#spacesset_tree_budget) | Sets the budget of `space`'s tree: how many child Spaces, vCPUs and memory its children may hold at once, and what they may cost. |
+| [`tree_budget`](/cua-sdk/reference/spaces/children#spacestree_budget) | The budget of `space`'s tree (any Space of it) and what its children use now. |
| [`volume_approve`](/cua-sdk/reference/spaces/volume#spacesvolume_approve) | `volume_approve`: the request becomes a grant (with presence). |
| [`volume_audit`](/cua-sdk/reference/spaces/volume#spacesvolume_audit) | `volume_audit`: the newest events (default 50) and whether the log verified. |
| [`volume_cache_clear`](/cua-sdk/reference/spaces/volume#spacesvolume_cache_clear) | `volume_cache_clear`: drops every cached block. |
@@ -175,7 +183,7 @@ pub async fn add(&self, url: String, token: Option<String>, name: Option<String>
| `token` | `Option<String>` | required |
| `name` | `Option<String>` | required |
-**Returns** [`SpaceInfo`](#spaceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+**Returns** [`SpaceInfo`](/cua-sdk/reference/spaces/info#spaceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
**Example**
@@ -280,7 +288,7 @@ pub async fn add_with_service(&self, url: String, token: Option<String>, name: O
| `name` | `Option<String>` | required |
| `service` | `Option<String>` | required |
-**Returns** [`SpaceInfo`](#spaceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+**Returns** [`SpaceInfo`](/cua-sdk/reference/spaces/info#spaceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
### `Spaces.call_tool_json`
@@ -498,7 +506,8 @@ pub async fn create_with_progress(&self, options: SpaceCreateOptions, listener:
### `Spaces.delete`
Deletes a Space's sandbox and forgets it (a Space added by address
-is only forgotten). Returns what happened.
+is only forgotten). Its child Spaces are deleted first. Returns what
+happened.
<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
<Tab value="Python">
@@ -688,7 +697,7 @@ pub async fn list(&self) -> Result<Vec<SpaceInfo>, CuaError>
</Tab>
</Tabs>
-**Returns** [`Vec<SpaceInfo>`](#spaceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+**Returns** [`Vec<SpaceInfo>`](/cua-sdk/reference/spaces/info#spaceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
### `Spaces.list_known`
@@ -892,7 +901,7 @@ pub async fn rename(&self, space: String, name: String) -> Result<SpaceInfo, Cua
| `space` | `String` | required |
| `name` | `String` | required |
-**Returns** [`SpaceInfo`](#spaceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors) ([`InvalidArgument`](/cua-sdk/reference/errors#invalidargument), [`PermissionDenied`](/cua-sdk/reference/errors#permissiondenied))
+**Returns** [`SpaceInfo`](/cua-sdk/reference/spaces/info#spaceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors) ([`InvalidArgument`](/cua-sdk/reference/errors#invalidargument), [`PermissionDenied`](/cua-sdk/reference/errors#permissiondenied))
### `Spaces.resolve`
@@ -941,7 +950,7 @@ pub async fn resolve(&self, space: String) -> Result<SpaceInfo, CuaError>
| --- | --- | --- |
| `space` | `String` | required |
-**Returns** [`SpaceInfo`](#spaceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+**Returns** [`SpaceInfo`](/cua-sdk/reference/spaces/info#spaceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
### `Spaces.space`
@@ -1149,103 +1158,6 @@ pub async fn suspend(&self, space: String) -> Result<SpacePowerReport, CuaError>
**Returns** [`SpacePowerReport`](/cua-sdk/reference/spaces/resize#spacepowerreport-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
-## `SpaceInfo` record
-
-A registered Space.
-
-Returned by [`Space.info`](/cua-sdk/reference/spaces/space#space), [`Spaces.add`](#spacesadd), [`Spaces.add_with_service`](#spacesadd_with_service), [`Spaces.list`](#spaceslist), [`Spaces.rename`](#spacesrename), [`Spaces.resolve`](#spacesresolve).
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `id` | `String` | | Id, for example `direct:10.0.0.5:3211` or `cloud:<name>` (the sandbox ref scheme). |
-| `name` | `String` | | Display name. |
-| `display_name` / `displayName` | `String` | `""` | The name it was given with `Spaces.rename`, which apps show in place of `name`; empty when it keeps the one it was created with. A Space that is a machine on the relay is renamed there, so its `name` changes instead. |
-| `provider` | `String` | | `cloud`, `local`, `direct` or `relay` (the location words). |
-| `spacesd_version` / `spacesdVersion` | `String` | | spacesd version at the last handshake. |
-| `features` | `Vec<String>` | | Supported features at the last handshake. |
-| `os` | `String` | | Guest OS family at the last handshake: `linux`, `macos`, `windows`, or empty when not reported. |
-| `os_name` / `osName` | `String` | | Guest OS product or distribution at the last handshake ("Ubuntu", "macOS"), or empty when not reported. |
-| `os_pretty_name` / `osPrettyName` | `String` | | The guest's full OS string at the last handshake ("Ubuntu 24.04.3 LTS", "macOS 26.5.2 (25F84)"), or empty from older drivers. |
-| `image` | `String` | | The image the sandbox runs ("ghcr.io/trycua/linux:24.04"), or empty when unknown (a Space added by address). |
-| `image_digest` / `imageDigest` | `String` | | The digest of the variant that runs ("sha256:..."), or empty. |
-| `kind` | `String` | | `container`, `vm` or `microvm`, or empty when unknown. |
-| `arch` | `String` | | The guest's CPU architecture (`arm64`, `amd64`), or empty when unknown. |
-| `services` | `Vec<String>` | | Declared services (never `env`), reachable with `list_tools` / `call_tool` (`service`). A Space without cua-spacesd has an empty `features` list and only these. |
-| `added_at` / `addedAt` | `Option<String>` | | When it was added (RFC 3339). |
-| `host` | `String` | | For a Space one of your machines provides (created with `on="host:<machine>"`): that host's relay machine id; empty otherwise. Lists group these Spaces under their host. |
-| `host_name` / `hostName` | `String` | | The host's display name, when known. |
-| `power` | `String` | | How it turns off and on again (`Spaces.stop`, `Spaces.start`): `suspend` (its memory is kept), `stop` (its disk is kept), or empty when it cannot (a cloud Space, a Space added by address). |
-| `power_state` / `powerState` | `String` | | `running`, `suspended` or `stopped` as cua last recorded it; empty when unknown (a Space one of your machines provides answers while it runs). |
-| `cloud` | `String` | | A Space in your own cloud: the provider (`aws`, `gcp`, `hetzner`, `modal`); empty otherwise. |
-| `cloud_place` / `cloudPlace` | `String` | | Where it runs ("AWS · us-west-2"). |
-| `cloud_delete` / `cloudDelete` | `String` | | How `delete` would delete it permanently from here: `here` (this device created it), `host:<machine>` (the device that created it, through the relay) or `elsewhere` (only there; `remove` keeps it). Empty for other Spaces. |
-| `durable` | `String` | `""` | A durable Space (`SpaceCreateOptions.durable`): its name. It is created again on another of your machines when its machine goes away, and keeps this name. Empty for other Spaces. |
-| `stop_reason` / `stopReason` | `String` | `""` | Why a local Space stopped without being asked to, in plain words ("out of memory", "killed", "exited with code 1"); empty otherwise, and once it is started again. |
-| `labels` | `HashMap<String, String>` | | Labels set at create (`SpaceCreateOptions.labels`). |
-| `expires_at_unix` / `expiresAtUnix` | `i64` | | When the Space ends (Unix seconds), as set by `Spaces.set_lifetime`; 0 when it has none. |
-| `on_expire` / `onExpire` | `String` | | What happens then: `delete` or `suspend`; empty without a lifetime. |
-| `created_at_unix` / `createdAtUnix` | `i64` | | When the Space was created (Unix seconds; the time it was added, for a Space added by address); 0 when unknown. |
-| `egress` | [`EgressPolicy`](#egresspolicy-record) | | The egress policy last set on the Space; empty when it has none. |
-| `egress_enforced` / `egressEnforced` | [`Option<EgressEnforcement>`](/cua-sdk/reference/spaces/space#egressenforcement-enum) | | Where `egress` is enforced; `None` without one. |
-| `volumes` | [`Vec<VolumeMount>`](/cua-sdk/reference/spaces/volume#volumemount-record) | | Named volumes mounted in the Space (see `SpaceCreateOptions.volumes`). |
-| `sharing` | [`Option<SpaceSharing>`](/cua-sdk/reference/spaces/sharing#spacesharing-record) | `None` | A Space that is a machine on the relay: who owns it and who else has it, as this account sees it. `None` for other Spaces. |
-
-## `spaces_tool_methods`
-
-Which SDK method covers each Spaces contract tool. Language test suites
-check every listed method exists on the generated class.
-
-<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
-<Tab value="Python">
-
-```python
-def spaces_tool_methods() -> List[SpacesToolMethod]
-```
-
-</Tab>
-<Tab value="TypeScript">
-
-```ts
-function spacesToolMethods(): Array<SpacesToolMethod>
-```
-
-</Tab>
-<Tab value="Swift">
-
-```swift
-func spacesToolMethods() -> [SpacesToolMethod]
-```
-
-</Tab>
-<Tab value="Kotlin">
-
-```kotlin
-fun spacesToolMethods(): List<SpacesToolMethod>
-```
-
-</Tab>
-<Tab value="Rust">
-
-```rust
-pub fn spaces_tool_methods() -> Vec<SpacesToolMethod>
-```
-
-</Tab>
-</Tabs>
-
-**Returns** [`Vec<SpacesToolMethod>`](#spacestoolmethod-record)
-
-## `SpacesToolMethod` record
-
-One row of `SPACES_TOOL_METHODS`.
-
-Returned by [`spaces_tool_methods`](#spaces_tool_methods).
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `tool` | `String` | | Contract tool name. |
-| `method` | `String` | | `Class.method` (Rust / Python spelling; camelCase in TS, Swift and Kotlin). |
-
## Create options
`Spaces.create` takes `SpaceCreateOptions` (with an `EgressPolicy` for the destinations a Linux Space may reach) and returns a `SpaceCreateResult`. A `SpaceCreateListener` receives `SpaceCreateProgress` while it runs; `Spaces.cancel_create` stops it. `GpuSupport` says whether a location offers GPU acceleration.
@@ -1283,8 +1195,12 @@ as sandboxes.
| `network` | `Option<String>` | `None` | Guest network: `default` (unset) gives outbound network; `none` gives none (QEMU VMs, here or on one of your machines; published ports and cua-spacesd still reach the guest). Not with `durable` or `reuse`. A daemon or machine whose cua is too old to enforce `none` is refused (`CapabilityMissing`) and the Space it made is deleted. |
| `labels` | `HashMap<String, String>` | `[:]` | Labels kept with the Space and returned in `SpaceInfo.labels`: at most 64; keys and values are not empty (UTF-8); keys up to 63 bytes, values up to 256. Not with `durable` or `reuse`. The device that creates the Space keeps them (also for `host:` and `auto`). |
| `egress` | [`Option<EgressPolicy>`](#egresspolicy-record) | `None` | Egress policy (see `EgressPolicy`), enforced by the host the Space runs on from the guest's first instruction. A kind or location with no host-side point refuses it (`Unsupported`) before anything is created. Not with `durable`, `reuse` or `wait = false`; a daemon too old to enforce it makes the create fail. |
+| `network_settings` / `networkSettings` | [`Option<NetworkSettings>`](/cua-sdk/reference/spaces/network#networksettings-record) | `None` | Network settings (see `NetworkSettings`). `None`: what `network` and `egress` say (`internet` when neither says anything). A daemon too old to keep them makes the create fail. |
+| `parent` | `Option<String>` | `None` | Create it as a child of this Space (id or name): its network is no more open than its parent's, and it joins the parent's tree. |
+| `widen` | `Option<bool>` | `None` | With `parent`: let its network be more open than its parent's (recorded on the Space). |
| `instance_type` / `instanceType` | `Option<String>` | `None` | With `on` a linked cloud (`aws`, `hetzner`, ...): the machine type its host must be (`c7g.xlarge`, `cax41`), a pin of the elastic pool's solve. `None`: the pool picks the cheapest that fits. |
| `region` | `Option<String>` | `None` | With `on` a linked cloud: the region its host must be in. |
+| `children` | `Option<bool>` | `None` | Lets the Space make child Spaces of its own (`Spaces.set_children`). `None`: off. Only a Space the machine of the runtime runs itself. |
## `EgressPolicy` record
@@ -1320,7 +1236,7 @@ Returned by [`Spaces.create`](#spacescreate), [`Spaces.create_with_progress`](#s
| Field | Type | Default | Description |
| --- | --- | --- | --- |
-| `space` | [`Option<SpaceInfo>`](#spaceinfo-record) | | The Space, once ready. |
+| `space` | [`Option<SpaceInfo>`](/cua-sdk/reference/spaces/info#spaceinfo-record) | | The Space, once ready. |
| `pending_id` / `pendingId` | `Option<String>` | | With `wait = false`: the id the Space will have. |
| `reused` | `bool` | | `reuse` returned an existing Space. |
diff --git a/docs/content/docs/cua-sdk/reference/spaces/info.mdx b/docs/content/docs/cua-sdk/reference/spaces/info.mdx
new file mode 100644
index 0000000000..8ec5560f64
--- /dev/null
+++ b/docs/content/docs/cua-sdk/reference/spaces/info.mdx
@@ -0,0 +1,118 @@
+---
+title: "Space records"
+description: "What a Space listing returns, and the Spaces tools `cua mcp` serves with the typed method that covers each."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:cua-sdk
+ Source: cua-bindgen docs (UniFFI metadata of libcua_sdk)
+ Version: 0.10.1
+*/}
+
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+`SpaceInfo` is one row of a Spaces listing. `spaces_tool_methods` lists every Spaces tool with the method of `Spaces` or `Space` that covers it.
+
+## `SpaceInfo` record
+
+A registered Space.
+
+Returned by [`Space.info`](/cua-sdk/reference/spaces/space#space), [`Spaces.add`](/cua-sdk/reference/spaces#spacesadd), [`Spaces.add_with_service`](/cua-sdk/reference/spaces#spacesadd_with_service), [`Spaces.list`](/cua-sdk/reference/spaces#spaceslist), [`Spaces.rename`](/cua-sdk/reference/spaces#spacesrename), [`Spaces.resolve`](/cua-sdk/reference/spaces#spacesresolve).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `id` | `String` | | Id, for example `direct:10.0.0.5:3211` or `cloud:<name>` (the sandbox ref scheme). |
+| `name` | `String` | | Display name. |
+| `display_name` / `displayName` | `String` | `""` | The name it was given with `Spaces.rename`, which apps show in place of `name`; empty when it keeps the one it was created with. A Space that is a machine on the relay is renamed there, so its `name` changes instead. |
+| `provider` | `String` | | `cloud`, `local`, `direct` or `relay` (the location words). |
+| `spacesd_version` / `spacesdVersion` | `String` | | spacesd version at the last handshake. |
+| `features` | `Vec<String>` | | Supported features at the last handshake. |
+| `os` | `String` | | Guest OS family at the last handshake: `linux`, `macos`, `windows`, or empty when not reported. |
+| `os_name` / `osName` | `String` | | Guest OS product or distribution at the last handshake ("Ubuntu", "macOS"), or empty when not reported. |
+| `os_pretty_name` / `osPrettyName` | `String` | | The guest's full OS string at the last handshake ("Ubuntu 24.04.3 LTS", "macOS 26.5.2 (25F84)"), or empty from older drivers. |
+| `image` | `String` | | The image the sandbox runs ("ghcr.io/trycua/linux:24.04"), or empty when unknown (a Space added by address). |
+| `image_digest` / `imageDigest` | `String` | | The digest of the variant that runs ("sha256:..."), or empty. |
+| `kind` | `String` | | `container`, `vm` or `microvm`, or empty when unknown. |
+| `arch` | `String` | | The guest's CPU architecture (`arm64`, `amd64`), or empty when unknown. |
+| `services` | `Vec<String>` | | Declared services (never `env`), reachable with `list_tools` / `call_tool` (`service`). A Space without cua-spacesd has an empty `features` list and only these. |
+| `added_at` / `addedAt` | `Option<String>` | | When it was added (RFC 3339). |
+| `host` | `String` | | For a Space one of your machines provides (created with `on="host:<machine>"`): that host's relay machine id; empty otherwise. Lists group these Spaces under their host. |
+| `host_name` / `hostName` | `String` | | The host's display name, when known. |
+| `power` | `String` | | How it turns off and on again (`Spaces.stop`, `Spaces.start`): `suspend` (its memory is kept), `stop` (its disk is kept), or empty when it cannot (a cloud Space, a Space added by address). |
+| `power_state` / `powerState` | `String` | | `running`, `suspended` or `stopped` as cua last recorded it; empty when unknown (a Space one of your machines provides answers while it runs). |
+| `cloud` | `String` | | A Space in your own cloud: the provider (`aws`, `gcp`, `hetzner`, `modal`); empty otherwise. |
+| `cloud_place` / `cloudPlace` | `String` | | Where it runs ("AWS · us-west-2"). |
+| `cloud_delete` / `cloudDelete` | `String` | | How `delete` would delete it permanently from here: `here` (this device created it), `host:<machine>` (the device that created it, through the relay) or `elsewhere` (only there; `remove` keeps it). Empty for other Spaces. |
+| `durable` | `String` | `""` | A durable Space (`SpaceCreateOptions.durable`): its name. It is created again on another of your machines when its machine goes away, and keeps this name. Empty for other Spaces. |
+| `stop_reason` / `stopReason` | `String` | `""` | Why a local Space stopped without being asked to, in plain words ("out of memory", "killed", "exited with code 1"); empty otherwise, and once it is started again. |
+| `labels` | `HashMap<String, String>` | | Labels set at create (`SpaceCreateOptions.labels`). |
+| `expires_at_unix` / `expiresAtUnix` | `i64` | | When the Space ends (Unix seconds), as set by `Spaces.set_lifetime`; 0 when it has none. |
+| `on_expire` / `onExpire` | `String` | | What happens then: `delete` or `suspend`; empty without a lifetime. |
+| `created_at_unix` / `createdAtUnix` | `i64` | | When the Space was created (Unix seconds; the time it was added, for a Space added by address); 0 when unknown. |
+| `egress` | [`EgressPolicy`](/cua-sdk/reference/spaces#egresspolicy-record) | | The egress policy last set on the Space; empty when it has none. |
+| `egress_enforced` / `egressEnforced` | [`Option<EgressEnforcement>`](/cua-sdk/reference/spaces/space#egressenforcement-enum) | | Where `egress` is enforced; `None` without one. |
+| `network` | [`Option<NetworkSettings>`](/cua-sdk/reference/spaces/network#networksettings-record) | | Its network settings; `None` for a Space this computer keeps no record of, or one created before they existed (it gets them on its next start). |
+| `network_note` / `networkNote` | `Option<String>` | | Why its network is not what was asked, in plain words (a runtime that can't protect it yet started it without network); `None` otherwise. |
+| `network_notice_pending` / `networkNoticePending` | `bool` | | An update changed its network settings (an old Space moved to the new defaults): say so once. |
+| `parent` | `Option<String>` | | The Space it was created from, by id; `None` for a top-level Space. |
+| `root` | `Option<String>` | | The top-level Space of its tree, by id; `None` for a top-level Space. |
+| `depth` | `u32` | | How far below its tree's top-level Space it is (0: top-level). |
+| `volumes` | [`Vec<VolumeMount>`](/cua-sdk/reference/spaces/volume#volumemount-record) | | Named volumes mounted in the Space (see `SpaceCreateOptions.volumes`). |
+| `sharing` | [`Option<SpaceSharing>`](/cua-sdk/reference/spaces/sharing#spacesharing-record) | `None` | A Space that is a machine on the relay: who owns it and who else has it, as this account sees it. `None` for other Spaces. |
+
+## `spaces_tool_methods`
+
+Which SDK method covers each Spaces contract tool. Language test suites
+check every listed method exists on the generated class.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+def spaces_tool_methods() -> List[SpacesToolMethod]
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+function spacesToolMethods(): Array<SpacesToolMethod>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func spacesToolMethods() -> [SpacesToolMethod]
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+fun spacesToolMethods(): List<SpacesToolMethod>
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn spaces_tool_methods() -> Vec<SpacesToolMethod>
+```
+
+</Tab>
+</Tabs>
+
+**Returns** [`Vec<SpacesToolMethod>`](#spacestoolmethod-record)
+
+## `SpacesToolMethod` record
+
+One row of `SPACES_TOOL_METHODS`.
+
+Returned by [`spaces_tool_methods`](#spaces_tool_methods).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `tool` | `String` | | Contract tool name. |
+| `method` | `String` | | `Class.method` (Rust / Python spelling; camelCase in TS, Swift and Kotlin). |
diff --git a/docs/content/docs/cua-sdk/reference/spaces/list-watch.mdx b/docs/content/docs/cua-sdk/reference/spaces/list-watch.mdx
index 5a45a3b569..4f1b56ea4c 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/list-watch.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/list-watch.mdx
@@ -80,7 +80,7 @@ Returned by [`Spaces.list_known`](/cua-sdk/reference/spaces#spaceslist_known).
| Field | Type | Default | Description |
| --- | --- | --- | --- |
-| `spaces` | [`Vec<SpaceInfo>`](/cua-sdk/reference/spaces#spaceinfo-record) | | This machine's Spaces, and the account's other computers' as far as they answered (the last known ones meanwhile). |
+| `spaces` | [`Vec<SpaceInfo>`](/cua-sdk/reference/spaces/info#spaceinfo-record) | | This machine's Spaces, and the account's other computers' as far as they answered (the last known ones meanwhile). |
| `incomplete` | `bool` | | Some of the account's computers have not answered yet: the list may grow, and an empty one is not "no Spaces". Always false from a daemon that predates it (it answers once every computer did). |
| `reaching` | `u32` | | How many computers are still being reached (0 when unknown). |
| `stale` | `bool` | | The other computers' rows are the last known ones, not yet confirmed by the relay. |
diff --git a/docs/content/docs/cua-sdk/reference/spaces/meta.json b/docs/content/docs/cua-sdk/reference/spaces/meta.json
index 657a81e31b..7365dba826 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/meta.json
+++ b/docs/content/docs/cua-sdk/reference/spaces/meta.json
@@ -1,6 +1,10 @@
{
"title": "Spaces",
"pages": [
+ "info",
+ "network",
+ "children",
+ "services",
"resize",
"lifetime",
"space",
diff --git a/docs/content/docs/cua-sdk/reference/spaces/network.mdx b/docs/content/docs/cua-sdk/reference/spaces/network.mdx
new file mode 100644
index 0000000000..d3db626684
--- /dev/null
+++ b/docs/content/docs/cua-sdk/reference/spaces/network.mdx
@@ -0,0 +1,286 @@
+---
+title: "Network settings (experiment)"
+description: "What a Space can reach: its network preset, the allow and deny lists, and deleting a Space together with its children."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:cua-sdk
+ Source: cua-bindgen docs (UniFFI metadata of libcua_sdk)
+ Version: 0.10.1
+*/}
+
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+These calls belong to the Secure Spaces experiment (`cua experiments enable secure-spaces`) and are refused while it is off. `Spaces.network` says what a Space can reach and where that is enforced, `set_network` changes it (a child Space stays within its parent's unless widened), and `delete_tree` deletes a Space with or without its children. See [A Space's network](/cua-sdk/guides/egress).
+
+## Network
+
+Methods of [`Spaces`](/cua-sdk/reference/spaces#spaces).
+
+### `Spaces.network`
+
+A Space's network: its settings, what they open, where they are
+enforced (or why its network is cut), and what is always blocked.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def network(self, space: str) -> SpaceNetworkInfo
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+network(space: string, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceNetworkInfo>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func network(space: String) async throws -> SpaceNetworkInfo
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun network(space: String): SpaceNetworkInfo
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn network(&self, space: String) -> Result<SpaceNetworkInfo, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `space` | `String` | required |
+
+**Returns** [`SpaceNetworkInfo`](#spacenetworkinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Spaces.ack_network_notice`
+
+Marks the one-time notice about the new network defaults as shown
+for `space` (`SpaceNetworkInfo.notice_pending`).
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def ack_network_notice(self, space: str) -> None
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+ackNetworkNotice(space: string, asyncOpts_?: { signal: AbortSignal }): Promise<void>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func ackNetworkNotice(space: String) async throws
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun ackNetworkNotice(space: String)
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn ack_network_notice(&self, space: String) -> Result<(), CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `space` | `String` | required |
+
+**Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Spaces.set_network`
+
+Replaces a Space's network settings (see `NetworkSettings`). A
+child stays within its parent's unless `widen`; `tree` gives its
+children the same settings. They hold at once where the runtime can
+change a running guest's network, else from its next start
+(`applied`). A Space another computer runs is `Unsupported`.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def set_network(self, space: str, settings: NetworkSettings, widen: bool, tree: bool) -> SetNetworkResult
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+setNetwork(space: string, settings: NetworkSettings, widen: boolean, tree: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<SetNetworkResult>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func setNetwork(space: String, settings: NetworkSettings, widen: Bool, tree: Bool) async throws -> SetNetworkResult
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun setNetwork(space: String, settings: NetworkSettings, widen: Boolean, tree: Boolean): SetNetworkResult
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn set_network(&self, space: String, settings: NetworkSettings, widen: bool, tree: bool) -> Result<SetNetworkResult, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `space` | `String` | required |
+| `settings` | [`NetworkSettings`](#networksettings-record) | required |
+| `widen` | `bool` | required |
+| `tree` | `bool` | required |
+
+**Returns** [`SetNetworkResult`](#setnetworkresult-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors) ([`Unsupported`](/cua-sdk/reference/errors#unsupported))
+
+### `Spaces.delete_tree`
+
+`Spaces.delete`, with `keep_children`: its child Spaces become
+top-level Spaces and keep running instead of being deleted first.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def delete_tree(self, space: str, keep_children: bool) -> str
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+deleteTree(space: string, keepChildren: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<string>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func deleteTree(space: String, keepChildren: Bool) async throws -> String
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun deleteTree(space: String, keepChildren: Boolean): String
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn delete_tree(&self, space: String, keep_children: bool) -> Result<String, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `space` | `String` | required |
+| `keep_children` | `bool` | required |
+
+**Returns** `String` · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+## `NetworkSettings` record
+
+A Space's network settings: a preset and the user's own lists. The host
+the Space runs on compiles them to rules it enforces outside the guest.
+
+- `internet` (the default): the public internet and the Space's own
+tree; this computer, your local network, cloud metadata, other trees
+and the cua daemon are blocked;
+- `none`: no network;
+- `localhost`: `internet`, plus this computer's localhost on
+`localhost_ports` (every port only with `all_localhost_ports`);
+- `lan`: `internet`, plus your local network (not this computer);
+- `custom`: `custom_base` (`internet` or `none`) plus `allow` and `deny`;
+- `unprotected`: everything but cloud metadata, other trees and the
+daemon.
+
+A runtime that can't protect a Space yet starts it without network and
+says so (`SpaceInfo.network_note`); it never starts it open unless the
+preset is `unprotected`.
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `preset` | `String` | `""` | `internet`, `none`, `localhost`, `lan`, `custom` or `unprotected`; empty is `internet`. |
+| `localhost_ports` / `localhostPorts` | `Vec<u16>` | `[]` | `localhost`: the ports of this computer's localhost the Space may reach. |
+| `all_localhost_ports` / `allLocalhostPorts` | `bool` | `false` | `localhost`: every port (the daemon's stay blocked). |
+| `allow` | `Vec<String>` | `[]` | Destinations that stay reachable (addresses or CIDRs). |
+| `deny` | `Vec<String>` | `[]` | Destinations that are blocked (addresses, CIDRs or `all`). |
+| `custom_base` / `customBase` | `String` | `""` | `custom`: what it starts from, `internet` (empty) or `none`. |
+| `widened_by` / `widenedBy` | `Option<String>` | `None` | Set when the Space was allowed more than its parent: who and when. |
+
+## `SpaceNetworkInfo` record
+
+A Space's network as `cua network show` says it (`Spaces.network`).
+
+Returned by [`Spaces.network`](#spacesnetwork).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `settings` | [`NetworkSettings`](#networksettings-record) | | Its settings. |
+| `summary` | `String` | | One plain line ("Internet only"). |
+| `widenings` | `Vec<String>` | | What the settings open beyond `internet`, one plain line each. |
+| `enforcement` | `String` | | `enforced` (rules on the host, outside the guest), `no_network` (its runtime can't protect it yet), `open` (No protection) or `refused`; empty when unknown (a Space another computer runs). |
+| `point` | `String` | | Where the rules are enforced, or why its network is cut. |
+| `note` | `Option<String>` | | Why its network is not what was asked; `None` otherwise. |
+| `parent` | `Option<String>` | | Its parent and its tree's top-level Space; `None` for a top-level Space. |
+| `root` | `Option<String>` | | |
+| `always_blocked` / `alwaysBlocked` | `Vec<String>` | | What no setting opens, in plain words. |
+| `notice_pending` / `noticePending` | `bool` | | An update changed its settings: say so once. |
+
+## `SetNetworkResult` record
+
+What `Spaces.set_network` did.
+
+Returned by [`Spaces.set_network`](#spacesset_network).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `applied` | `String` | | `now` (the running guest is under them) or `next_start`. |
+| `network` | [`SpaceNetworkInfo`](#spacenetworkinfo-record) | | The Space's network after the change. |
diff --git a/docs/content/docs/cua-sdk/reference/spaces/services.mdx b/docs/content/docs/cua-sdk/reference/spaces/services.mdx
new file mode 100644
index 0000000000..d745436680
--- /dev/null
+++ b/docs/content/docs/cua-sdk/reference/spaces/services.mdx
@@ -0,0 +1,406 @@
+---
+title: "Kept commands (experiment)"
+description: "Keep a command running in a Space: restarts, health checks, start on boot and logs."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:cua-sdk
+ Source: cua-bindgen docs (UniFFI metadata of libcua_sdk)
+ Version: 0.10.1
+*/}
+
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+These calls belong to the Child Spaces experiment (`cua experiments enable child-spaces`) for adding a service; listing, stopping and removing work either way. See [Keep a command running](/spaces/guides/keep-a-command-running).
+
+## Services
+
+Methods of [`Space`](/cua-sdk/reference/spaces/space#space).
+
+### `Space.put_service`
+
+Keeps a command running in this Space (replacing a service of that
+name): restarted by its policy when it ends or fails its health
+check, started when the Space boots, its output kept in a log file.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def put_service(self, _def: SpaceServiceDef) -> SpaceServiceInfo
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+putService(def: SpaceServiceDef, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceServiceInfo>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func putService(def: SpaceServiceDef) async throws -> SpaceServiceInfo
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun putService(def: SpaceServiceDef): SpaceServiceInfo
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn put_service(&self, def: SpaceServiceDef) -> Result<SpaceServiceInfo, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `def` | [`SpaceServiceDef`](#spaceservicedef-record) | required |
+
+**Returns** [`SpaceServiceInfo`](#spaceserviceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Space.kept_services`
+
+This Space's services.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def kept_services(self) -> List[SpaceServiceInfo]
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+keptServices(asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceServiceInfo>>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func keptServices() async throws -> [SpaceServiceInfo]
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun keptServices(): List<SpaceServiceInfo>
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn kept_services(&self) -> Result<Vec<SpaceServiceInfo>, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+**Returns** [`Vec<SpaceServiceInfo>`](#spaceserviceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Space.start_service`
+
+Starts a stopped service.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def start_service(self, name: str) -> SpaceServiceInfo
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+startService(name: string, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceServiceInfo>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func startService(name: String) async throws -> SpaceServiceInfo
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun startService(name: String): SpaceServiceInfo
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn start_service(&self, name: String) -> Result<SpaceServiceInfo, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `name` | `String` | required |
+
+**Returns** [`SpaceServiceInfo`](#spaceserviceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Space.stop_service`
+
+Stops a service and keeps it stopped (also across a reboot).
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def stop_service(self, name: str) -> SpaceServiceInfo
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+stopService(name: string, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceServiceInfo>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func stopService(name: String) async throws -> SpaceServiceInfo
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun stopService(name: String): SpaceServiceInfo
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn stop_service(&self, name: String) -> Result<SpaceServiceInfo, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `name` | `String` | required |
+
+**Returns** [`SpaceServiceInfo`](#spaceserviceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Space.restart_service`
+
+Restarts a service.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def restart_service(self, name: str) -> SpaceServiceInfo
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+restartService(name: string, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceServiceInfo>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func restartService(name: String) async throws -> SpaceServiceInfo
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun restartService(name: String): SpaceServiceInfo
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn restart_service(&self, name: String) -> Result<SpaceServiceInfo, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `name` | `String` | required |
+
+**Returns** [`SpaceServiceInfo`](#spaceserviceinfo-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Space.delete_service`
+
+Stops a service and forgets it (its logs go too).
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def delete_service(self, name: str) -> None
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+deleteService(name: string, asyncOpts_?: { signal: AbortSignal }): Promise<void>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func deleteService(name: String) async throws
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun deleteService(name: String)
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn delete_service(&self, name: String) -> Result<(), CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `name` | `String` | required |
+
+**Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Space.service_logs`
+
+The end of a service's log (`tail_bytes` `None`: 64 KiB).
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def service_logs(self, name: str, tail_bytes: Optional[int]) -> str
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+serviceLogs(name: string, tailBytes: bigint | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<string>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func serviceLogs(name: String, tailBytes: UInt64?) async throws -> String
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun serviceLogs(name: String, tailBytes: ULong?): String
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn service_logs(&self, name: String, tail_bytes: Option<u64>) -> Result<String, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `name` | `String` | required |
+| `tail_bytes` | `Option<u64>` | required |
+
+**Returns** `String` · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+## `SpaceServiceDef` record
+
+A command a Space keeps running (`Space.put_service`).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `name` | `String` | | Name: lowercase letters, digits, `-`, `_`, `.` (1 to 63). |
+| `command` | `String` | | The shell command line it runs. |
+| `env` | `HashMap<String, String>` | `[:]` | Extra environment. |
+| `cwd` | `Option<String>` | `None` | Working directory. |
+| `restart` | `Option<String>` | `None` | When it is started again: `always` (default), `on-failure` or `never`. |
+| `probe` | [`Option<SpaceServiceProbe>`](#spaceserviceprobe-record) | `None` | A health check; failing it restarts the service. |
+| `start_on_boot` / `startOnBoot` | `Option<bool>` | `None` | Start it when the Space boots. `None`: yes. |
+
+## `SpaceServiceProbe` record
+
+A health check: exactly one of `http`, `tcp`, `command`.
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `http` | `Option<String>` | `None` | A URL that answers 2xx or 3xx. |
+| `tcp` | `Option<String>` | `None` | `host:port` that accepts a TCP connection. |
+| `command` | `Option<String>` | `None` | A shell command that exits 0 when healthy. |
+| `interval_secs` / `intervalSecs` | `Option<u64>` | `None` | Seconds between checks (default 10). |
+| `failures` | `Option<u32>` | `None` | Failed checks in a row that restart it (default 3). |
+
+## `SpaceServiceInfo` record
+
+A service and how it is doing (`Space.services`).
+
+Returned by [`Space.kept_services`](#spacekept_services), [`Space.put_service`](#spaceput_service), [`Space.restart_service`](#spacerestart_service), [`Space.start_service`](#spacestart_service), [`Space.stop_service`](#spacestop_service).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `name` | `String` | | Name. |
+| `command` | `String` | | The command line. |
+| `state` | `String` | | `starting`, `running`, `unhealthy`, `backoff`, `stopped`, `exited` or `failed`. |
+| `pid` | `u32` | | Its process, while it runs. |
+| `restarts` | `u32` | | Starts after the first. |
+| `last_end` / `lastEnd` | `String` | | How the last process ended, if one did. |
+| `probe_error` / `probeError` | `String` | | The last failed health check, if the last one failed. |
+| `restart` | `String` | | `always`, `on-failure` or `never`. |
+| `start_on_boot` / `startOnBoot` | `bool` | | Starts when the Space boots. |
+| `log_path` / `logPath` | `String` | | Its log file in the Space. |
diff --git a/docs/content/docs/cua-sdk/reference/spaces/space.mdx b/docs/content/docs/cua-sdk/reference/spaces/space.mdx
index 1ffbc78b25..6a6d2588bc 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/space.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/space.mdx
@@ -52,15 +52,22 @@ Returned by [`Space.fork`](/cua-sdk/reference/sandbox/checkpoints#spacefork), [`
| [`attach_stream`](/cua-sdk/reference/spaces/streams#spaceattach_stream) | Attaches to a ticket from `Self.open_stream` and delivers the media socket's encoded frames and audio packets to the sinks as they arrive. |
| [`checkpoint`](/cua-sdk/reference/sandbox/checkpoints#spacecheckpoint) | Saves this Space's state as checkpoint `checkpoint` (the sandbox API's `Sandboxes.checkpoint`): it keeps running, and `Spaces.fork(checkpoint, name)` (this machine) or `Spaces.create` with image `checkpoint:<name>` (any of your machines) starts new Spaces from it. |
| [`close_stream`](/cua-sdk/reference/spaces/streams#spaceclose_stream) | Closes a media session opened with `Space.open_stream`. |
+| [`delete_service`](/cua-sdk/reference/spaces/services#spacedelete_service) | Stops a service and forgets it (its logs go too). |
| [`displays`](/cua-sdk/reference/spaces/space#spacedisplays) | The Space's displays, primary first, with their resolution in physical pixels. |
| [`fork`](/cua-sdk/reference/sandbox/checkpoints#spacefork) | Starts Space `name`, a fork of this one (with its memory when it is running), and returns it connected. |
| [`forward`](/cua-sdk/reference/spaces/channel#spaceforward) | Forwards a free loopback port on this machine to guest `port` over this Space's own connection (cua-spacesd's tunnel): the same path its calls take, so a Space one of your machines provides on your LAN is reached directly, and never through a port opened on that machine's network. |
| [`join_presence`](/cua-sdk/reference/spaces/streams#spacejoin_presence) | Joins presence. |
+| [`kept_services`](/cua-sdk/reference/spaces/services#spacekept_services) | This Space's services. |
| [`open_stream`](/cua-sdk/reference/spaces/streams#spaceopen_stream) | Mints a media session (ticket + WebSocket URL) for another client to attach to. |
+| [`put_service`](/cua-sdk/reference/spaces/services#spaceput_service) | Keeps a command running in this Space (replacing a service of that name): restarted by its policy when it ends or fails its health check, started when the Space boots, its output kept in a log file. |
+| [`restart_service`](/cua-sdk/reference/spaces/services#spacerestart_service) | Restarts a service. |
| [`route`](/cua-sdk/reference/spaces/channel#spaceroute) | Which way this Space's calls go now (see `super.spacesd.SpacesdClient.route`): `local …`, `direct …`, `relay …`, `mesh direct <ip:port> rtt <ms> ms`, `mesh relayed` or `cloud`; empty when the Space runs no cua-spacesd. |
+| [`service_logs`](/cua-sdk/reference/spaces/services#spaceservice_logs) | The end of a service's log (`tail_bytes` `None`: 64 KiB). |
| [`share`](/cua-sdk/reference/spaces/sharing#spaceshare) | Lets `who` (a verified email or an account id) watch (`viewer`, the default) or use (`editor`) this Space through the relay. |
| [`shares`](/cua-sdk/reference/spaces/sharing#spaceshares) | Who this Space is shared with, and who of them is connected now. |
| [`spacesd`](/cua-sdk/reference/spacesd#spacespacesd) | The cua-spacesd client over the connection this Space authenticated. |
+| [`start_service`](/cua-sdk/reference/spaces/services#spacestart_service) | Starts a stopped service. |
+| [`stop_service`](/cua-sdk/reference/spaces/services#spacestop_service) | Stops a service and keeps it stopped (also across a reboot). |
| [`stream_session`](/cua-sdk/reference/spaces/streams#spacestream_session) | Opens a media session and delivers keyframe-gated encoded frames and audio to the sinks (one delivery thread; decoding stays with the caller). |
| [`teleport`](/cua-sdk/reference/spaces/space#spaceteleport) | Teleports `app`'s session into this Space. |
| [`teleport_manifest`](/cua-sdk/reference/spaces/space#spaceteleport_manifest) | What teleporting `app` (`full` or `tabs`) would move from this host. |
@@ -75,7 +82,7 @@ Returned by [`Space.fork`](/cua-sdk/reference/sandbox/checkpoints#spacefork), [`
| Accessor | Returns | Description |
| --- | --- | --- |
| `id()` | `String` | Id. |
-| `info()` | [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record) | Connection-time snapshot; never refreshed. With spacesd, handshake `os`, `os_name`, `os_pretty_name` replace record values; missing/unknown families clear them. Other fields and non-spacesd services retain registry/discovery values. `Spaces.list()`/`Spaces.resolve()` remain record views. |
+| `info()` | [`SpaceInfo`](/cua-sdk/reference/spaces/info#spaceinfo-record) | Connection-time snapshot; never refreshed. With spacesd, handshake `os`, `os_name`, `os_pretty_name` replace record values; missing/unknown families clear them. Other fields and non-spacesd services retain registry/discovery values. `Spaces.list()`/`Spaces.resolve()` remain record views. |
| `services()` | `Vec<String>` | The MCP services this Space exposes: `driver` when its spacesd has the tool registry, then every declared service (reached over generic MCP; no spacesd needed). |
### `Space.bash`
diff --git a/docs/content/docs/cua-sdk/reference/types.mdx b/docs/content/docs/cua-sdk/reference/types.mdx
index 80198224b6..fd168f4a82 100644
--- a/docs/content/docs/cua-sdk/reference/types.mdx
+++ b/docs/content/docs/cua-sdk/reference/types.mdx
@@ -48,7 +48,7 @@ Renamed members: in Kotlin, objects implement `AutoCloseable`, whose `close()` f
## All items
-328 items. Methods are listed on their object.
+337 items. Methods are listed on their object.
The 10 items of Batched forks are listed on [its page](/cua-sdk/reference/sandbox/fork-batch#all-items).
@@ -217,6 +217,7 @@ The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/ref
| [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession) | object | A live media session. |
| [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record) | record | Delivery counters. |
| [`NamedVolume`](/cua-sdk/reference/spaces/volume#namedvolume-record) | record | A named volume of Cua Volume (`Spaces.volumes`). |
+| [`NetworkSettings`](/cua-sdk/reference/spaces/network#networksettings-record) | record | A Space's network settings: a preset and the user's own lists. |
| [`normalize_image`](/cua-sdk/reference/image#normalize_image) | function | Normalises a reference like the docker CLI (`python` is `docker.io/library/python:latest`). |
| [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record) | record | One entry of the notifications feed. |
| [`omarchy_image`](/cua-sdk/reference/image#omarchy_image) | function | The Omarchy image, `ghcr.io/trycua/omarchy:<channel>` (default `edge`; also `rc`, `stable`): Omarchy (Arch Linux, Hyprland) with cua-spacesd, as an… |
@@ -287,6 +288,7 @@ The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/ref
| [`ScreenshotOptions`](/cua-sdk/reference/spacesd/computer#screenshotoptions-record) | record | Screenshot options. |
| [`Service`](/cua-sdk/reference/services#service) | object | A named service of a sandbox. |
| [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record) | record | Where a sandbox service is reachable from this process. |
+| [`SetNetworkResult`](/cua-sdk/reference/spaces/network#setnetworkresult-record) | record | What `Spaces.set_network` did. |
| [`SetupStep`](/cua-sdk/reference/cua#setupstep-record) | record | One setup step. |
| [`Share`](/cua-sdk/reference/share#share-record) | record | One share. |
| [`ShareAccess`](/cua-sdk/reference/share#shareaccess-enum) | enum | Who may open a share. |
@@ -307,14 +309,16 @@ The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/ref
| [`SpaceCreatingElsewhere`](/cua-sdk/reference/spaces/space#spacecreatingelsewhere-record) | record | A Space another of your computers is creating (`SpaceList.creating`). |
| [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record) | record | One of a Space's displays (`Space.displays`). |
| [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record) | record | Hotspot state. |
-| [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record) | record | A registered Space. |
+| [`SpaceInfo`](/cua-sdk/reference/spaces/info#spaceinfo-record) | record | A registered Space. |
| [`SpaceList`](/cua-sdk/reference/spaces/list-watch#spacelist-record) | record | The Spaces known now (`Spaces.list_known`) and how far the read got. |
+| [`SpaceNetworkInfo`](/cua-sdk/reference/spaces/network#spacenetworkinfo-record) | record | A Space's network as `cua network show` says it (`Spaces.network`). |
+| [`SpaceOrphan`](/cua-sdk/reference/spaces/children#spaceorphan-record) | record | A child Space whose parent is gone or out of reach (`Spaces.orphans`). |
| [`SpacePowerReport`](/cua-sdk/reference/spaces/resize#spacepowerreport-record) | record | What `Spaces.stop` or `Spaces.start` did. |
| [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence) | object | A joined presence session. |
| [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/relay-registration#spacerelayregistration-record) | record | A Space published on the relay (`Spaces.relay_register`). |
| [`SpaceResizeReport`](/cua-sdk/reference/spaces/resize#spaceresizereport-record) | record | What `Spaces.resize` did: the shape the Space has now. |
| [`Spaces`](/cua-sdk/reference/spaces#spaces) | object | The Spaces registry: add a machine by URL, provision a local one, and get `Space` handles. |
-| [`spaces_tool_methods`](/cua-sdk/reference/spaces#spaces_tool_methods) | function | Which SDK method covers each Spaces contract tool. |
+| [`spaces_tool_methods`](/cua-sdk/reference/spaces/info#spaces_tool_methods) | function | Which SDK method covers each Spaces contract tool. |
| [`SpacesdCapabilities`](/cua-sdk/reference/spacesd#spacesdcapabilities-record) | record | `SystemService.GetCapabilities`, summarized. |
| [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient) | object | Client for one cua-spacesd. |
| [`SpacesdCommand`](/cua-sdk/reference/spacesd/shell#spacesdcommand-record) | record | A command to run in the guest. |
@@ -328,6 +332,9 @@ The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/ref
| [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record) | record | Options for `Space.send_file`. |
| [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record) | record | Result of `Space.send_file`. |
| [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record) | record | One file placed by `Space.send_file`. |
+| [`SpaceServiceDef`](/cua-sdk/reference/spaces/services#spaceservicedef-record) | record | A command a Space keeps running (`Space.put_service`). |
+| [`SpaceServiceInfo`](/cua-sdk/reference/spaces/services#spaceserviceinfo-record) | record | A service and how it is doing (`Space.services`). |
+| [`SpaceServiceProbe`](/cua-sdk/reference/spaces/services#spaceserviceprobe-record) | record | A health check: exactly one of `http`, `tcp`, `command`. |
| [`SpaceShareEntry`](/cua-sdk/reference/spaces/sharing#spaceshareentry-record) | record | One account a Space is shared with. |
| [`SpaceShares`](/cua-sdk/reference/spaces/sharing#spaceshares-record) | record | Who a Space is shared with. |
| [`SpaceSharing`](/cua-sdk/reference/spaces/sharing#spacesharing-record) | record | Who a Space belongs to and who else has it, as this account sees it (`SpaceInfo.sharing`). |
@@ -336,7 +343,7 @@ The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/ref
| [`SpacesHostLoad`](/cua-sdk/reference/spaces/host#spaceshostload-record) | record | How busy one of your machines is (its job runner's view). |
| [`SpacesListListener`](/cua-sdk/reference/spaces/list-watch#spaceslistlistener) | object | Hears that the Space list changed (`Spaces.watch_list`). |
| [`SpacesListWatch`](/cua-sdk/reference/spaces/list-watch#spaceslistwatch) | object | A running `Spaces.watch_list`. |
-| [`SpacesToolMethod`](/cua-sdk/reference/spaces#spacestoolmethod-record) | record | One row of `SPACES_TOOL_METHODS`. |
+| [`SpacesToolMethod`](/cua-sdk/reference/spaces/info#spacestoolmethod-record) | record | One row of `SPACES_TOOL_METHODS`. |
| [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record) | record | What to stream and how. |
| [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession) | object | A live Space media session (see `Space.stream_session`). |
| [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record) | record | Delivery counters of a `SpaceStreamSession`. |
@@ -381,6 +388,8 @@ The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/ref
| [`thread_view_of`](/cua-sdk/reference/spaces/persistent-agents#thread_view_of) | function | The `view` of one thread entry or task, given as JSON (an element of `thread_read`'s `entries` or `tasks`, or `thread_inbox`'s `tasks`): none when it… |
| [`ThreadView`](/cua-sdk/reference/spaces/persistent-agents#threadview-record) | record | What a person was looking at in a Space as they posted to its thread: the Space's desktop, or one of its windows. |
| [`TransferResult`](/cua-sdk/reference/spacesd/files#transferresult-record) | record | Result of an upload or download. |
+| [`TreeBudget`](/cua-sdk/reference/spaces/children#treebudget-record) | record | A tree's budget and what its children use (`Spaces.tree_budget`). |
+| [`TreeBudgetLimits`](/cua-sdk/reference/spaces/children#treebudgetlimits-record) | record | What a tree's children may hold and cost (`Spaces.set_tree_budget`). |
| [`UploadOptions`](/cua-sdk/reference/spacesd/files#uploadoptions-record) | record | Upload options. |
| [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record) | record | One encoded video access unit. |
| [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record) | record | A link to the sandbox desktop in the cua-spacesd HTML5 viewer. |
diff --git a/docs/content/docs/spaces/concepts/meta.json b/docs/content/docs/spaces/concepts/meta.json
index b2d929697c..5db5ab9a5a 100644
--- a/docs/content/docs/spaces/concepts/meta.json
+++ b/docs/content/docs/spaces/concepts/meta.json
@@ -3,6 +3,7 @@
"pages": [
"how-spaces-works",
"machines-and-spaces",
- "space-kinds"
+ "space-kinds",
+ "runtime-conformance"
]
}
diff --git a/docs/content/docs/spaces/concepts/runtime-conformance.mdx b/docs/content/docs/spaces/concepts/runtime-conformance.mdx
new file mode 100644
index 0000000000..512fda054a
--- /dev/null
+++ b/docs/content/docs/spaces/concepts/runtime-conformance.mdx
@@ -0,0 +1,108 @@
+---
+title: 'One Space on every runtime'
+description: 'What every runtime owes a Space (network policy, DNS, registry sign-in, child Spaces, downloads, readiness), what each one refuses and why, and how Cua checks it.'
+---
+
+A Space behaves the same wherever it runs. The same default network holds,
+names resolve, a private image pulls with your registry sign-in, a home makes
+and deletes child Spaces, the guest can download what it needs, and a Space is
+ready when it answers. This page lists those promises, says what each runtime
+does with them, and shows how Cua checks them.
+
+## What every runtime owes a Space
+
+- **The default network holds.** The Space reaches the internet and its own
+ tree. It does not reach this computer, your local network, cloud metadata
+ or the Spaces of other trees. The host enforces it, outside the guest, so
+ nothing inside the Space (root included) can change it.
+- **Names resolve.** Lookups work in the guest for IPv4 and IPv6.
+- **The guest can download.** The coding app's package (about 100 MB)
+ downloads inside the Space under the default network.
+- **A private image pulls.** Cua pulls with the registry credential the
+ daemon holds (`CUA_REGISTRY_USERNAME` and `CUA_REGISTRY_PASSWORD` in its
+ environment, `GITHUB_TOKEN` for ghcr.io, or `docker login`), the same way
+ for every runtime. Cua never writes it outside its own home.
+- **A home makes child Spaces.** Inside a home, `cua spaces create`, `ls` and
+ `delete` work through the daemon's channel, within the tree's budget, and
+ every request is audited.
+- **A coding agent session starts.** The app installs and the agent answers.
+- **Ready means answering.** Time to ready is measured from the create call
+ to a Space that answers.
+- **Delete leaves nothing.** No Space, process, container or network remains.
+
+A runtime that cannot keep a promise refuses it at once, in plain words that
+say what to use instead. A refusal that comes late, or a Space that starts
+without the promise, is a bug.
+
+## What each runtime says
+
+| Runtime | Guest | Default network | Pause | Checkpoint and fork | KVM |
+|---|---|---|---|---|---|
+| `builtin-gvisor` | linux | enforced on macos, enforced on windows | yes | yes | no |
+| `builtin-runc` | linux | enforced on macos, enforced on windows | yes | yes | no |
+| `engine-gvisor` | linux | enforced on linux | yes | yes | no |
+| `engine-runc` | linux | enforced on linux | yes | yes | no |
+| `firecracker-microvm` | linux | enforced on linux | yes | yes | yes |
+| `vz-microvm` | linux | refused on macos | yes | yes | no |
+| `containerization-microvm` | linux | refused on macos | no | no | no |
+| `qemu-vm` | linux | enforced on linux, refused on macos, refused on windows | yes | yes | no |
+| `lume-macos-vm` | macos | refused on macos | no | no | no |
+
+Pause, checkpoint and fork are what the runtime can do with a running Space.
+Where a runtime cannot, asking for one is refused with a reason. The built-in
+runtimes run on this computer's built-in Linux runtime; `engine-` runtimes run
+on a container engine you run on a Linux host.
+
+### Where the default network is not enforced yet
+
+The default network is the Secure Spaces experiment
+(`cua experiments enable secure-spaces`); this page describes a Space with it
+on. A runtime that cannot enforce it never starts a Space open by accident.
+Apple's Containerization puts every guest on Apple's vmnet network. Only `pf`
+can filter that network, and `pf` needs root. A firewall inside the guest
+would not hold against the Space's own root, so Cua does not offer one as the
+default network: a Space there starts only with No protection, and a request
+for the default network is refused with that reason. A `vz` microVM, QEMU on
+macOS and Windows, and a macOS VM are the same for now.
+
+Images still pull the same way on Apple's Containerization. Cua pulls the
+image itself, with your registry credential and its shared layer cache, and
+loads it into Apple's image store, because Apple's `container image pull` can
+only use a login kept in your keychain and refuses a private package. The
+first start on a Mac downloads Apple's `container` and its guest kernel before
+an image could begin, so the image's layers download at the same time; on a
+slow link that download is most of the wait, and every start after it takes
+about a second. Guests use your computer's resolvers, then public ones: the resolver
+that `container` sets up answers every IPv6 lookup as truncated and serves no
+TCP, so lookups for both families used to fail.
+
+## How Cua keeps the promises the same
+
+The promises live in shared layers, and a runtime supplies only how the guest
+is reached.
+
+- The default network is compiled once from the Space's settings
+ (`cua_vmm::network`) and enforced where the runtime allows: the container
+ engine's own network namespace or the namespace around a Linux VM.
+- Registry sign-in and the layer cache live in `cua-image`. A runtime that
+ pulls with its own credentials receives the image as an archive instead.
+- Child Spaces use a channel the host opens into the guest's `cua-spacesd`:
+ the guest never holds the daemon's token and nothing new listens on the
+ host.
+- Readiness is a probe on the guest's `cua-spacesd` at the address the
+ runtime gives.
+
+## Check it yourself
+
+Every runtime is listed in one roster (`cua_vmm::conformance`), and a test
+fails the build when a backend is added without an entry. The same cases run
+against each entry. The hermetic tests run the ones that need no machine
+(Apple's `container` has a fake). The live run is opt-in, uses an isolated
+Cua home and its own daemon, deletes what it makes, and writes a matrix:
+
+```bash skip="no-runner"
+CUA=/path/to/cua libs/cua/scripts/conformance/run.py --entry vz-microvm --out results/
+```
+
+The roster and what each entry must do is `libs/cua/scripts/conformance/entries.json`,
+generated from the registry.
diff --git a/docs/content/docs/spaces/guides/child-spaces.mdx b/docs/content/docs/spaces/guides/child-spaces.mdx
new file mode 100644
index 0000000000..7f74edeb38
--- /dev/null
+++ b/docs/content/docs/spaces/guides/child-spaces.mdx
@@ -0,0 +1,112 @@
+---
+title: Child Spaces
+description: 'Let a Space make Spaces of its own: an agent inside it creates, uses and deletes children, without your account and without reaching anything else.'
+---
+
+import { Tabs, Tab } from 'fumadocs-ui/components/tabs';
+
+A Space can make Spaces of its own. An agent working inside it can fork 32
+copies to run a benchmark, start a fresh machine to test a build, or try a
+change on a clean desktop, then delete them. These are its children: they
+belong to it, and it can reach nothing else.
+
+Child Spaces is an [experiment](/spaces/guides/experiments) and is off until you
+turn it on with `cua experiments enable child-spaces`. While it is off, no Space
+can make children and the commands on this page stay out of `--help`. An agent
+run turns this on for its Space by itself once the experiment is on. For any
+other Space you turn it on yourself.
+
+## Turn it on
+
+<Tabs items={['CLI', 'SDK']}>
+ <Tab value="CLI">
+ ```bash test="cli-shape" id="children-on"
+ cua spaces create linux --name studio --children
+ cua spaces children studio on
+ cua spaces children studio off
+ ```
+ </Tab>
+ <Tab value="SDK">
+ ```python skip="no-runner"
+ import cua
+
+ spaces = cua.auto().spaces()
+ await spaces.create(cua.SpaceCreateOptions(name="studio", children=True))
+ await spaces.set_children("studio", False)
+ ```
+ </Tab>
+</Tabs>
+
+Off ends the Space's right to make children at once. Children it already
+made keep running until they are deleted or their time runs out.
+
+## Inside the Space
+
+Nothing to set up. The same commands and tools work, and every Space they
+make is a child of this one:
+
+```bash skip="no-runner"
+cua spaces create linux --name worker
+cua spaces ls
+cua sb exec worker -- make test
+cua spaces rm worker
+```
+
+An agent gets the same as tools in its Space's own MCP server:
+`create_space`, `fork_space`, `list_spaces`, `space_bash`, `stop_space`,
+`start_space` and `delete_space`. Code that uses the SDK
+(`cua.auto()`) works too.
+
+## What a child gets
+
+- **Where.** A child runs on the same computer as its parent unless it asks
+ for `--on auto` (the least-loaded of your computers and linked clouds),
+ `--on host:<name>` or a linked cloud (`--on aws`). This computer's cua daemon
+ creates it with your own sign-in and cloud links. The Space asking never
+ holds them. A Windows child needs a machine with virtualization: a Windows
+ PC of yours, or a cloud host that offers it. Hetzner Cloud servers can't
+ run VMs, so Windows children don't go there.
+- **No wider network.** It keeps its parent's egress rules. A request for
+ wider ones is refused.
+- **Cost counted.** A child in a linked cloud counts what it adds per hour
+ against its tree's budget and your account's cloud budget. The stricter
+ one wins.
+- **No longer life.** It ends when its parent would, and after 4 hours at
+ most unless you give it longer.
+- **Limited depth.** A child may make children of its own, two levels
+ below the Space you made. Deeper requests are refused.
+
+## A budget per tree
+
+Each tree has a budget: how many child Spaces, vCPUs and memory its
+children may hold at once, and what they may cost. The defaults are 16
+Spaces, 16 vCPUs, 32 GiB and $2 an hour, so a runaway loop stays cheap.
+A child that does not fit is refused with what is left, in words an agent
+can act on. Creates in flight reserve their share first, so two at once
+can't pass the budget together.
+
+```bash test="cli-shape" id="children-budget"
+cua spaces budget studio
+cua spaces budget studio --spaces 32 --cpus 64 --memory 131072
+cua spaces budget studio --clear
+```
+
+Inside a Space, `cua spaces budget` shows its own tree's budget and use.
+Only you can change it.
+
+## What a Space can't do
+
+The channel a Space uses answers for its own children and nothing else.
+
+- **Other Spaces.** Your other Spaces, its parent and its siblings look
+ the same as a Space that does not exist.
+- **Your account.** It holds no account sign-in, cloud link or key, so it
+ can't share, connect clouds or reach your other computers.
+- **A copied capability.** The capability it holds works only on its own
+ channel. A copy taken from a snapshot, a fork or another Space is
+ refused.
+
+The channel is not a network port. The Space's own cua-spacesd keeps it on
+the Space's loopback and hands each connection to this computer's cua daemon
+over the connection the daemon opened. The daemon knows which Space is
+asking from the connection, never from what the Space says.
diff --git a/docs/content/docs/spaces/guides/experiments.mdx b/docs/content/docs/spaces/guides/experiments.mdx
new file mode 100644
index 0000000000..11895f87f7
--- /dev/null
+++ b/docs/content/docs/spaces/guides/experiments.mdx
@@ -0,0 +1,29 @@
+---
+title: Experiments
+description: Features that are still being built are off until you turn them on, one switch each, with the cua experiments command or in the app's Settings.
+---
+
+An experiment is a feature that works but is still being built. It is off until you turn it on, and turning it off puts everything back the way it was before: nothing the experiment made is deleted, and the commands and settings it added disappear from help and from the app.
+
+## Turn one on or off
+
+```bash skip="no-runner"
+cua experiments list # every experiment and whether it is on
+cua experiments enable secure-spaces
+cua experiments disable secure-spaces
+```
+
+The switches live in the Cua home (`experiments/<name>`), so the command, the daemon and the Spaces apps agree. In the app, a switch for these two appears under Settings, Advanced, Labs once the experiment is on (turn it on with the command first); a change made with the command shows there the next time the app starts. To turn one on for a single process, set `CUA_EXPERIMENTS=secure-spaces` (or `-secure-spaces` to force it off).
+
+A command that belongs to an experiment that is off is left out of `--help`. If you run it anyway it says which experiment to turn on.
+
+## The experiments
+
+| Name | What it does |
+| --- | --- |
+| `child-spaces` | A Space makes Spaces of its own, inside a budget for its tree, and keeps a command running. See [Child Spaces](/spaces/guides/child-spaces) and [Keep a command running](/spaces/guides/keep-a-command-running). |
+| `secure-spaces` | A Space reaches the internet and its own tree and nothing else on your network unless you open it, with a network setting for each Space. See [A Space's network](/cua-sdk/guides/egress). |
+
+## Turning one off
+
+Turning an experiment off takes effect for the Spaces you start or create afterwards. A running Space keeps the network it started with until it restarts, and a Space made while Secure Spaces was on keeps the protection it was made with. A Space made before you turned Secure Spaces on stays on the open network it had; to move it to the secure one it has to be recreated, which loses its files, so Cua refuses to restart it while the experiment is on and tells you the two ways forward (turn the experiment off to keep using it, or copy what you need out and delete it). Turning an experiment back on later brings back the settings you chose.
diff --git a/docs/content/docs/spaces/guides/ip-options-guard.mdx b/docs/content/docs/spaces/guides/ip-options-guard.mdx
new file mode 100644
index 0000000000..04534c5235
--- /dev/null
+++ b/docs/content/docs/spaces/guides/ip-options-guard.mdx
@@ -0,0 +1,61 @@
+---
+title: IPv4 options guard for Linux VM Spaces
+description: 'Why Cua Linux VM images drop inbound IPv4 packets that carry IP options, which CVE it mitigates, what it changes, and when it goes away.'
+---
+
+Cua Linux VM images ship a small firewall rule that drops inbound IPv4 packets
+carrying IP options (Record Route, Timestamp, loose and strict source route)
+before they reach TCP. It is an interim mitigation for CVE-2026-98432, a Linux
+kernel use-after-free that a remote peer can trigger by sending a TCP SYN with
+Record Route or Timestamp options to a listening socket and then racing a
+retransmitted SYN. The kernel fix is in upstream releases 5.10.272, 5.15.223,
+6.1.190, 6.6.159, 6.12.113, 6.18.56, 7.2.10 and 7.3. Ubuntu 24.04 has not
+shipped it yet, so the guard closes the gap until the image carries a fixed
+kernel.
+
+## Which Spaces have it
+
+Every Space that boots its own Linux kernel: the Linux image (slim, full and
+docker tiers), the Omarchy VM image and the OSWorld VM image. Container Spaces
+share the kernel of the machine they run on, and gVisor Spaces use gVisor's own
+network stack, so the guard does not apply to them. Update the machine's kernel
+to cover container Spaces.
+
+A default Space accepts no inbound connections, so it is not reachable by this
+bug. The guard matters for a Space that exposes a port, for Spaces on a shared
+network, and for a Space you run in your own cloud account.
+
+## What it does
+
+A systemd unit, `cua-ipopts.service`, loads an nftables table named
+`cua_ipopts` early in boot, before the network comes up. The table has one
+chain on the prerouting hook that drops any IPv4 packet with a header longer
+than 20 bytes, which is the only way a packet can carry IP options. IGMP is
+left alone. Nothing else is changed: TCP, UDP, ICMP and your own firewall rules
+behave as before. The one visible effect is that `ping -R` and `ping -T`, which
+send those options on purpose, get no reply.
+
+The unit only ever adds and removes its own table, so a firewall you configure
+later (ufw, Docker, your own nftables rules) is not disturbed. If you enable
+`nftables.service` with a `flush ruleset` line, the unit is ordered after it so
+the guard is loaded again on boot. The unit also sets
+`net.ipv4.conf.*.accept_source_route` to 0.
+
+## Check it
+
+Inside the Space:
+
+```bash skip="no-runner"
+systemctl is-active cua-ipopts.service
+sudo nft list table ip cua_ipopts
+```
+
+The counter on the drop rule rises when a packet with options arrives.
+
+## When it is removed
+
+The guard is removed from an image once the image's kernel is at or above the
+fixed version for its series: Ubuntu 24.04 `linux-image-virtual` 6.8.0-149 or
+later, and an Omarchy snapshot whose Arch `linux` package is a fixed release.
+Until then, rebuilding an image keeps it in place. To turn it off yourself in a
+Space you control, run `sudo systemctl disable --now cua-ipopts.service`.
diff --git a/docs/content/docs/spaces/guides/keep-a-command-running.mdx b/docs/content/docs/spaces/guides/keep-a-command-running.mdx
new file mode 100644
index 0000000000..9c82a04e9e
--- /dev/null
+++ b/docs/content/docs/spaces/guides/keep-a-command-running.mdx
@@ -0,0 +1,87 @@
+---
+title: Keep a command running
+description: 'Run a server, a worker or a bot in a Space and have it restarted when it stops, checked while it runs, and started again when the Space boots.'
+---
+
+import { Tabs, Tab } from 'fumadocs-ui/components/tabs';
+
+Keeping a command running is part of the [Child Spaces experiment](/spaces/guides/experiments): turn it on with `cua experiments enable child-spaces` before you add a service. Listing, stopping and removing services work whether it is on or off.
+
+A service is a command a Space keeps running. Its cua-spacesd starts it,
+starts it again when it ends, restarts it when its health check fails,
+starts it when the Space boots, and keeps its output in a log file in the
+Space.
+
+## Add a service
+
+<Tabs items={['CLI', 'MCP', 'SDK']}>
+ <Tab value="CLI">
+ ```bash test="cli-shape" id="service-add"
+ cua spaces service add studio web -- python3 -m http.server 8080
+ cua spaces service add studio web --http http://127.0.0.1:8080/ -- python3 -m http.server 8080
+ cua spaces service add studio job --restart on-failure -- ./run.sh
+ ```
+
+ The command comes after `--`. `--restart` is `always` (the default),
+ `on-failure` or `never`. `--http`, `--tcp` or `--check` adds a health
+ check. `--no-boot` leaves it off when the Space boots.
+ </Tab>
+ <Tab value="MCP">
+ ```text output
+ space_service {space: "studio", action: "add", name: "web",
+ command: "python3 -m http.server 8080",
+ http: "http://127.0.0.1:8080/"}
+ ```
+ </Tab>
+ <Tab value="SDK">
+ ```python skip="no-runner"
+ import cua
+
+ space = await cua.auto().spaces().space("studio")
+ await space.put_service(cua.SpaceServiceDef(
+ name="web",
+ command="python3 -m http.server 8080",
+ probe=cua.SpaceServiceProbe(http="http://127.0.0.1:8080/"),
+ ))
+ ```
+ </Tab>
+</Tabs>
+
+Adding a name that exists replaces that service. The old process is
+stopped first.
+
+## Check on it
+
+```bash test="cli-shape" id="service-check"
+cua spaces service ls studio
+cua spaces service logs studio web
+```
+
+`ls` shows each service's state: `running`, `unhealthy`, `backoff` (it
+ended and waits to start again), `stopped`, `exited` (its policy does not
+start it again) or `failed` (it could not start). It also shows how many
+times it restarted and how its last run ended.
+
+## How restarts work
+
+- **When it ends.** With `always` it starts again however it ended. With
+ `on-failure` it starts again after a non-zero exit, a signal or a failed
+ health check.
+- **Waiting.** The wait before a restart starts at 1 second and doubles
+ after each quick failure, up to a minute. A run of a minute or more
+ resets it.
+- **Health checks.** A check runs every 10 seconds. Three failures in a
+ row stop the process (TERM, then KILL after 10 seconds), and its policy
+ starts it again. Checks in its first 10 seconds don't count.
+
+## Stop, start, remove
+
+```bash test="cli-shape" id="service-control"
+cua spaces service stop studio web
+cua spaces service start studio web
+cua spaces service restart studio web
+cua spaces service rm studio web
+```
+
+A stopped service stays stopped, also after the Space reboots, until you
+start it. `rm` stops it and removes its logs.
diff --git a/docs/content/docs/spaces/guides/long-running-jobs.mdx b/docs/content/docs/spaces/guides/long-running-jobs.mdx
new file mode 100644
index 0000000000..f86a5d466f
--- /dev/null
+++ b/docs/content/docs/spaces/guides/long-running-jobs.mdx
@@ -0,0 +1,121 @@
+---
+title: Long-running jobs and agents that coordinate
+description: 'Start a build or test run in a Space that keeps going when you disconnect, tail its log, and get woken in the Space thread when it ends. Plus the thread conventions agents in a parent Space and its child Spaces use to share work.'
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+A build, a test suite or a wait on CI can take twenty minutes. A command run
+with `space_bash` holds the call open for all of it, and it is gone if you
+disconnect. A **job** is a command that lives in the Space instead: it has an
+id, a log you can read from any offset, an exit status and timing, and it keeps
+running when you stop, close the laptop or restart the Space's daemon.
+
+Jobs are one MCP tool, `space_job`, with an `action`. They work the same in
+every Space, whatever it runs on (container, gVisor, microVM, VM or cloud),
+because a job is files and a small runner in the Space, not a feature of one
+runtime. Linux and macOS Spaces only.
+
+## Start a job and walk away
+
+```text output
+space_job {space: "local:dev", action: "start", name: "unit tests",
+ command: "make test", cwd: "/work/app", notify: true}
+```
+
+The call returns at once with a job id and `state: "running"`. With `notify:
+true` the daemon follows the job. When it ends, the Space's thread gets one
+message in a fixed shape and, if you are an agent member of the Space, you
+receive it as your next task:
+
+```text output
+JOB j6c1f0a2b9d3e exited exit=0 12m55s log=48210B | unit tests
+
+End of the log:
+...
+Read more with space_job {action: "logs", job: "j6c1f0a2b9d3e", offset: <byte>} ...
+```
+
+So an agent starts the job, posts one line in the thread saying what it
+started, and ends its turn. Nothing polls. If the person is the one who
+started it (not an agent), they get a notification instead.
+
+## Read, wait, cancel
+
+| `action` | What it does |
+| --- | --- |
+| `start` | Begin a job: `command` (or `until`), and optionally `name`, `cwd`, `env`, `timeout` in seconds, `notify`, `wake`. |
+| `logs` | Read the log from `offset` (default: the end). Returns `text`, `next_offset` and `more`. `follow_ms` (at most 25000) waits for new output or for the job to end. |
+| `status` | The state, exit code, timing, and the end of the log. |
+| `cancel` | Stop the job and everything it started: TERM, then KILL after five seconds. |
+| `list` | The Space's jobs, newest first. |
+
+A job's `state` is `running`, `exited` (with `exit_code`), `cancelled`,
+`timed_out`, or `lost`. `lost` means the job's runner is gone without having
+recorded an end, for example because the Space itself was restarted; nothing
+is made up about the result.
+
+Output is stdout and stderr together, in one log. Offsets are bytes, so a
+reader can tail without losing or repeating anything: pass the `next_offset`
+you were given as the next `offset`.
+
+## Wait for something that is not your command
+
+`until` makes the job a watcher. It ends when the condition holds, so
+`notify` wakes you at that moment.
+
+| `until` | Ends when |
+| --- | --- |
+| `{file: "/work/out/done"}` | the path exists |
+| `{port: 5432}` | the port accepts connections (`host` defaults to 127.0.0.1) |
+| `{command: "test -s report.json"}` | the command exits 0 |
+| `{pr_checks: "owner/repo#123"}` | the pull request's required checks have finished: exit 0 if they pass, 1 if one fails (needs `gh` signed in inside the Space) |
+
+Set `timeout` so a condition that never holds does not wait forever.
+
+## What survives
+
+| Event | The job |
+| --- | --- |
+| You disconnect, or your agent's turn ends | keeps running |
+| The Space's daemon (`cua-spacesd`) restarts | keeps running, and the log and result are still there |
+| The Cua daemon on your computer restarts | still followed; `notify` is stored on disk and resumes |
+| The Space is stopped and started | the job is `lost` unless the guest kept its processes (a suspended Space does) |
+
+Finished jobs are kept for seven days.
+
+<Callout type="info">
+ Jobs run with the same permissions as `space_bash`: a command that would ask
+ first through `space_bash` asks first when you start it as a job.
+</Callout>
+
+## Agents that share a Space
+
+Agents that work in the same Space, or in a parent Space and the child Spaces it
+started, coordinate in the Space's thread. There is no other service: the thread
+is the channel, and a short convention keeps agents from overwriting each other.
+It is part of the instructions every agent member receives, and of the bundled
+`cua-spaces` skill:
+
+1. Before you start, read the thread and note what others have claimed.
+2. Post `CLAIM <what> | files: <paths or branch> | until: <when>` for what you
+ will change. Do not edit files or branches another agent's live claim
+ covers: @mention the owner and wait for the reply.
+3. A claim is live until its `until` passes or its owner posts `DONE` or
+ `RELEASE`. Once it has expired you may take it, and you say so in the
+ thread.
+4. Report with one structured line: `DONE <what> | <result> | next: <step>` or
+ `BLOCKED <what> | needs: <thing> | from @who`.
+5. Keep messages short, one @mention per request, and never your own name.
+
+A parent agent that starts agents in child Spaces gives each of them a join
+link for the parent's thread (see [Agents from a link](/spaces/guides/agents-from-a-link)),
+so the group reads and posts in one place. The examples above are only
+examples: the convention is the same for any task.
+
+An @mention is how one agent wakes another, and it is limited on purpose: a
+chain stops after three agent to agent hops from a person's message, and a Space
+allows twenty agent to agent wakes a minute (see
+[Thread and member tools](/spaces/reference/threads)). A job ending is not an
+agent to agent hop: it is the daemon, so a long job always wakes the agent that
+started it.
diff --git a/docs/content/docs/spaces/guides/macos-developer-tools.mdx b/docs/content/docs/spaces/guides/macos-developer-tools.mdx
new file mode 100644
index 0000000000..81072ae0d5
--- /dev/null
+++ b/docs/content/docs/spaces/guides/macos-developer-tools.mdx
@@ -0,0 +1,106 @@
+---
+title: macOS Space with developer tools
+description: 'A macOS Space where an agent can build and test iOS and macOS apps with Xcode and the iOS Simulator, how Cua makes it from the Xcode already on your Mac, what it needs, and why it is never downloaded.'
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+The macOS Space with developer tools is a macOS Space where an agent can build
+and test Apple software with no setup. It has Xcode, the iOS Simulator with an
+iPhone ready to boot, the Metal toolchain, Rust with the iOS targets, CocoaPods,
+XcodeGen, sccache, Node with pnpm, Git and the GitHub CLI. The agent inside can
+run `xcodebuild`, boot the Simulator, drive it with the same computer-use tools
+it uses on any Space, and take screenshots of what it built.
+
+Like every macOS Space it runs on a Mac with Apple silicon, as a virtual
+machine, and it comes with the Cua Spaces tools and the permissions the agent
+needs to see and control the screen already granted.
+
+## Ask for it
+
+You do not pick an image or run a setup step. Ask for a macOS Space to develop
+Apple software and Cua uses this one.
+
+```bash skip="no-runner"
+cua sandbox create macos --tier dev
+```
+
+In the SDK it is `Image.macos(tier="xcode")`. `dev` and `xcode` are the same
+tier. The first time, Cua builds it on your Mac and shows its progress while it
+does. Every Space after that starts from the finished image in seconds, the way
+any other macOS Space does.
+
+## Where it comes from
+
+The image is published and pulled like the other macOS Space images: the first
+time you ask for it, Cua downloads it with progress and checks your free disk
+first, and every Space after that is a clone of it that starts in seconds. It
+is built by Cua's image pipeline, which gets Xcode from the pinned Xcode on its
+own build Mac. No Apple account is involved on your side.
+
+If the published image is not available, or you would rather use the Xcode you
+already have on your Mac, Cua builds the same image locally from the regular
+macOS Space image and your Xcode. Set `CUA_DEV_IMAGE=local` to prefer that.
+
+1. It starts from the regular macOS Space image it already keeps for you.
+2. It copies in the newest Xcode on your Mac, or the one Xcode selects. If
+ there is no installed Xcode it looks for an Xcode `.xip` you downloaded, in
+ `~/XcodesCache` and then `~/Downloads`.
+3. Inside the Space, Xcode downloads the matching iOS Simulator runtime from
+ Apple. That download needs no account.
+4. The remaining tools come from their public releases, each checked against a
+ pinned checksum.
+
+Your Xcode is only read.
+
+<Callout type="info">
+ Xcode and the iOS Simulator runtimes in this image are Apple software under
+ Apple's license, and the image is for use on Apple-branded hardware. It runs
+ only on a Mac with Apple silicon, and Cua refuses to pull it anywhere else.
+</Callout>
+
+<Callout type="info">
+ If the published image is not available and the Mac has no Xcode, creating
+ the Space stops at once and says what to do: install Xcode from the App Store,
+ or download the `.xip` from developer.apple.com and put it in `~/XcodesCache`,
+ then ask again. Apple requires a sign-in for that download, which Cua does not
+ do for you.
+</Callout>
+
+## What it needs
+
+The image adds about 27 GB on the Mac (measured with Xcode 26.6). Cua checks
+before it starts and stops early with how much is missing and how to make room:
+remove Spaces and images you no longer use with `cua cache prune`, or empty the
+Trash. The macOS Space image and the finished developer image are shared by every
+Space you create from them; a Space itself adds only what the agent writes.
+
+macOS runs at most two virtual machines at a time on one Mac, so a Space with
+developer tools counts as one of the two.
+
+## Using it
+
+Once the Space is running, the agent works as it would on a Mac of its own.
+
+```bash skip="no-runner"
+xcodegen generate
+xcodebuild -scheme MyApp -destination 'platform=iOS Simulator,name=Cua iPhone' test
+xcrun simctl boot "Cua iPhone"
+```
+
+The Space has a Simulator device named `Cua iPhone`, already booted once so its
+first real boot is quick. Developer mode is on, so the debugger and Instruments
+do not ask for a password, and Xcode does not stop to ask whether to trust Swift
+package plug-ins and macros.
+
+Rust projects that target iOS build with `cargo build --target aarch64-apple-ios-sim`.
+sccache is installed, so set `RUSTC_WRAPPER=sccache` to keep a repeat build fast.
+
+## For maintainers
+
+The image is built and published by the macOS image pipeline like the other
+tiers (`libs/images/macos`). The fallback recipe is
+`libs/images/macos/derive-local.sh` with the tier script
+`libs/images/macos/files/tier-xcode.sh`, and every version is pinned in
+`libs/images/macos/versions.env`. The catalog entry lists the full macOS image
+it falls back to as `derived_from`.
diff --git a/docs/content/docs/spaces/meta.json b/docs/content/docs/spaces/meta.json
index 86e2075212..266b17299b 100644
--- a/docs/content/docs/spaces/meta.json
+++ b/docs/content/docs/spaces/meta.json
@@ -7,6 +7,7 @@
"concepts/how-spaces-works",
"concepts/machines-and-spaces",
"concepts/space-kinds",
+ "concepts/runtime-conformance",
"---Get started---",
"guides/install",
"guides/connect-your-agent",
@@ -24,6 +25,7 @@
"guides/keyvault",
"guides/cua-volume",
"guides/repo-cache",
+ "guides/macos-developer-tools",
"guides/sandbox-sdks",
"guides/create-a-space-with-the-sdk",
"---Agents in a Space---",
@@ -32,11 +34,16 @@
"guides/agent-memory-and-identity",
"guides/agent-schedules",
"guides/keep-an-agent-running",
+ "guides/child-spaces",
+ "guides/keep-a-command-running",
+ "guides/long-running-jobs",
"---Keep it working---",
"guides/troubleshoot",
+ "guides/experiments",
"guides/uninstall",
"---Advanced---",
"guides/relay-security",
+ "guides/ip-options-guard",
"guides/your-tailnet",
"examples",
"reference"
diff --git a/docs/content/docs/spaces/reference/index.mdx b/docs/content/docs/spaces/reference/index.mdx
index 06200d7d78..9c7834bd1d 100644
--- a/docs/content/docs/spaces/reference/index.mdx
+++ b/docs/content/docs/spaces/reference/index.mdx
@@ -10,7 +10,7 @@ description: "Every Spaces tool by category, with parameters, results, errors an
Version: 0.9.0
*/}
-The Spaces contract: 114 tools with the same names and schemas on every surface: `cua mcp`, `cua daemon mcp` and the Spaces SDKs. Contract 0.9.0, MCP protocol revision 2025-06-18, transports `mcp_stdio` and `mcp_streamable_http`. Experimental: names and shapes can change between minor versions.
+The Spaces contract: 118 tools with the same names and schemas on every surface: `cua mcp`, `cua daemon mcp` and the Spaces SDKs. Contract 0.9.0, MCP protocol revision 2025-06-18, transports `mcp_stdio` and `mcp_streamable_http`. Experimental: names and shapes can change between minor versions.
## Tools
@@ -24,6 +24,8 @@ Register, provision, list and release Spaces.
| [`remove_space`](/spaces/reference/spaces#remove_space) | Forget a registered Space without touching it. | mutating, idempotent |
| [`list_spaces`](/spaces/reference/spaces#list_spaces) | List the Spaces this connection can see. | read-only, idempotent |
| [`create_space`](/spaces/reference/spaces#create_space) | Create a Space: a new sandbox on this computer, on one of your computers, or in the cloud. | destructive |
+| [`network_show`](/spaces/reference/spaces#network_show) | Show a Space's network: preset, what it opens, where it is enforced, what is always blocked. | read-only, idempotent |
+| [`network_set`](/spaces/reference/spaces#network_set) | Tighten a Space's network: internet, none or custom lists. Opening more is the user's to do. | mutating, idempotent |
| [`delete_space`](/spaces/reference/spaces#delete_space) | Delete a Space's sandbox and forget it. | destructive |
| [`stop_space`](/spaces/reference/spaces#stop_space) | Turn a Space off: stop it (disk kept, memory freed) or, with suspend, suspend it (memory kept). | mutating, idempotent |
| [`resize_space`](/spaces/reference/spaces#resize_space) | Change a Space's vCPUs, memory or disk size. | mutating, idempotent |
@@ -36,6 +38,7 @@ Run shell commands and move files in and out of a Space.
| Tool | Description | Effect |
| --- | --- | --- |
| [`space_bash`](/spaces/reference/spaces#space_bash) | Run a shell command inside the Space. | destructive |
+| [`space_job`](/spaces/reference/spaces#space_job) | Run a long command in the Space as a background job: tail its log, cancel it, or get woken when it ends. | destructive |
| [`space_write`](/spaces/reference/spaces#space_write) | Write literal text to a path inside the Space. | destructive |
| [`upload`](/spaces/reference/spaces#upload) | Send a local file or folder into the Space. | destructive |
| [`send_file`](/spaces/reference/spaces#send_file) | Send a host file or folder into the Space's Downloads, verified by sha256 on arrival. | destructive |
@@ -62,6 +65,7 @@ Discover and call the MCP services inside a Space.
| --- | --- | --- |
| [`list_tools`](/spaces/reference/spaces#list_tools) | List the MCP services and tools reachable inside the Space. | read-only, idempotent |
| [`call_tool`](/spaces/reference/spaces#call_tool) | Call a service tool inside the Space. | destructive |
+| [`space_service`](/spaces/reference/spaces#space_service) | Keep a command running in the Space: restarts, health checks, start on boot, logs. | destructive |
### [Agents](/spaces/reference/agents#agents)
@@ -183,41 +187,41 @@ Read and write the volume every Space and agent shares, decide who may reach wha
| [`volume_cache_set`](/spaces/reference/agents#volume_cache_set) | Set the Cua Volume block cache's size cap. | mutating, idempotent |
| [`volume_cache_clear`](/spaces/reference/agents#volume_cache_clear) | Clear the Cua Volume block cache. | mutating, idempotent |
-### [Sharing](/spaces/reference/spaces#sharing)
+### [Sharing](/spaces/reference/sharing-and-cloud#sharing)
Let other cua.ai accounts watch or edit a Space, through the relay.
| Tool | Description | Effect |
| --- | --- | --- |
-| [`share_space`](/spaces/reference/spaces#share_space) | Let someone in your team watch or edit a Space. | mutating, idempotent |
-| [`unshare_space`](/spaces/reference/spaces#unshare_space) | Stop sharing a Space with an account, or with everyone. | mutating, idempotent |
-| [`space_shares`](/spaces/reference/spaces#space_shares) | List who a Space is shared with. | read-only, idempotent |
-| [`relay_register_space`](/spaces/reference/spaces#relay_register_space) | Publish a Space on the relay for the account's other devices. | mutating, idempotent |
-| [`relay_unregister_space`](/spaces/reference/spaces#relay_unregister_space) | Take a Space off the relay. | mutating, idempotent |
+| [`share_space`](/spaces/reference/sharing-and-cloud#share_space) | Let someone in your team watch or edit a Space. | mutating, idempotent |
+| [`unshare_space`](/spaces/reference/sharing-and-cloud#unshare_space) | Stop sharing a Space with an account, or with everyone. | mutating, idempotent |
+| [`space_shares`](/spaces/reference/sharing-and-cloud#space_shares) | List who a Space is shared with. | read-only, idempotent |
+| [`relay_register_space`](/spaces/reference/sharing-and-cloud#relay_register_space) | Publish a Space on the relay for the account's other devices. | mutating, idempotent |
+| [`relay_unregister_space`](/spaces/reference/sharing-and-cloud#relay_unregister_space) | Take a Space off the relay. | mutating, idempotent |
-### [Your cloud](/spaces/reference/spaces#your-cloud)
+### [Your cloud](/spaces/reference/sharing-and-cloud#your-cloud)
Create Spaces in your own AWS, Google Cloud, Hetzner or Modal account: connect it, check it, and clean up what Cua created there.
| Tool | Description | Effect |
| --- | --- | --- |
-| [`cloud_status`](/spaces/reference/spaces#cloud_status) | List your clouds (AWS, Google Cloud, Hetzner, Modal): found credentials, the connected account and region, what each can run at what hourly cost, and what Cua created there. | read-only, idempotent |
-| [`cloud_connect`](/spaces/reference/spaces#cloud_connect) | Connect a cloud account Spaces can be created in. | mutating, idempotent |
-| [`cloud_test`](/spaces/reference/spaces#cloud_test) | Check a cloud account without creating anything. | read-only, idempotent |
-| [`cloud_disconnect`](/spaces/reference/spaces#cloud_disconnect) | Forget a connected cloud account (deleting what Cua created there first, with delete=true). | destructive |
-| [`cloud_approve`](/spaces/reference/spaces#cloud_approve) | Approve (or deny) what an agent asked for on a cloud: its link or its raised limits. For a person only. | destructive |
-| [`cloud_sweep`](/spaces/reference/spaces#cloud_sweep) | Find and delete what Cua left in your clouds. | destructive |
-| [`cloud_plan`](/spaces/reference/spaces#cloud_plan) | Show (or apply) the elastic pool's plan for some Spaces: where they go, which machines it adds, and the cost. | destructive |
-| [`cloud_hosts`](/spaces/reference/spaces#cloud_hosts) | List the hosts the elastic pool added in your clouds. | read-only, idempotent |
-| [`cloud_add_host`](/spaces/reference/spaces#cloud_add_host) | Add hosts to your pool in a linked cloud. | destructive |
-| [`cloud_remove_host`](/spaces/reference/spaces#cloud_remove_host) | Remove hosts this home added to your pool. | destructive |
-| [`cloud_budget`](/spaces/reference/spaces#cloud_budget) | Read or set the elastic pool's budget and autoscale switch. | mutating, idempotent |
-| [`cloud_reconcile`](/spaces/reference/spaces#cloud_reconcile) | Run the elastic pool's scale-in pass now. | destructive |
-| [`prewarm`](/spaces/reference/spaces#prewarm) | Keep Spaces of one shape ready where the elastic pool puts them, so the next creates start in a fraction of a second. | destructive |
-| [`prewarm_list`](/spaces/reference/spaces#prewarm_list) | List the prewarms and how many Spaces each keeps ready. | read-only, idempotent |
-| [`prewarm_remove`](/spaces/reference/spaces#prewarm_remove) | End a prewarm: its ready Spaces go. | mutating, idempotent |
-| [`cloud_audit`](/spaces/reference/spaces#cloud_audit) | Read the log of what Cua did in your clouds. | read-only, idempotent |
-| [`cloud_cost`](/spaces/reference/spaces#cloud_cost) | Estimate what Cua's machines in your clouds cost, by Space, agent, day or cloud. | read-only, idempotent |
+| [`cloud_status`](/spaces/reference/sharing-and-cloud#cloud_status) | List your clouds (AWS, Google Cloud, Hetzner, Modal): found credentials, the connected account and region, what each can run at what hourly cost, and what Cua created there. | read-only, idempotent |
+| [`cloud_connect`](/spaces/reference/sharing-and-cloud#cloud_connect) | Connect a cloud account Spaces can be created in. | mutating, idempotent |
+| [`cloud_test`](/spaces/reference/sharing-and-cloud#cloud_test) | Check a cloud account without creating anything. | read-only, idempotent |
+| [`cloud_disconnect`](/spaces/reference/sharing-and-cloud#cloud_disconnect) | Forget a connected cloud account (deleting what Cua created there first, with delete=true). | destructive |
+| [`cloud_approve`](/spaces/reference/sharing-and-cloud#cloud_approve) | Approve (or deny) what an agent asked for on a cloud: its link or its raised limits. For a person only. | destructive |
+| [`cloud_sweep`](/spaces/reference/sharing-and-cloud#cloud_sweep) | Find and delete what Cua left in your clouds. | destructive |
+| [`cloud_plan`](/spaces/reference/sharing-and-cloud#cloud_plan) | Show (or apply) the elastic pool's plan for some Spaces: where they go, which machines it adds, and the cost. | destructive |
+| [`cloud_hosts`](/spaces/reference/sharing-and-cloud#cloud_hosts) | List the hosts the elastic pool added in your clouds. | read-only, idempotent |
+| [`cloud_add_host`](/spaces/reference/sharing-and-cloud#cloud_add_host) | Add hosts to your pool in a linked cloud. | destructive |
+| [`cloud_remove_host`](/spaces/reference/sharing-and-cloud#cloud_remove_host) | Remove hosts this home added to your pool. | destructive |
+| [`cloud_budget`](/spaces/reference/sharing-and-cloud#cloud_budget) | Read or set the elastic pool's budget and autoscale switch. | mutating, idempotent |
+| [`cloud_reconcile`](/spaces/reference/sharing-and-cloud#cloud_reconcile) | Run the elastic pool's scale-in pass now. | destructive |
+| [`prewarm`](/spaces/reference/sharing-and-cloud#prewarm) | Keep Spaces of one shape ready where the elastic pool puts them, so the next creates start in a fraction of a second. | destructive |
+| [`prewarm_list`](/spaces/reference/sharing-and-cloud#prewarm_list) | List the prewarms and how many Spaces each keeps ready. | read-only, idempotent |
+| [`prewarm_remove`](/spaces/reference/sharing-and-cloud#prewarm_remove) | End a prewarm: its ready Spaces go. | mutating, idempotent |
+| [`cloud_audit`](/spaces/reference/sharing-and-cloud#cloud_audit) | Read the log of what Cua did in your clouds. | read-only, idempotent |
+| [`cloud_cost`](/spaces/reference/sharing-and-cloud#cloud_cost) | Estimate what Cua's machines in your clouds cost, by Space, agent, day or cloud. | read-only, idempotent |
## Space ids
@@ -299,7 +303,7 @@ An argument is missing, malformed or out of range.
Fix: Check the call against the tool's input schema; the message names the argument.
-Listed by [`resize_space`](/spaces/reference/spaces#resize_space), [`thread_join`](/spaces/reference/threads#thread_join), [`thread_join_code_create`](/spaces/reference/threads#thread_join_code_create), [`thread_join_code_cancel`](/spaces/reference/threads#thread_join_code_cancel), [`volume_storage_set`](/spaces/reference/agents#volume_storage_set), [`volume_cache_set`](/spaces/reference/agents#volume_cache_set), [`relay_unregister_space`](/spaces/reference/spaces#relay_unregister_space), [`cloud_connect`](/spaces/reference/spaces#cloud_connect), [`cloud_approve`](/spaces/reference/spaces#cloud_approve), [`cloud_add_host`](/spaces/reference/spaces#cloud_add_host), [`cloud_budget`](/spaces/reference/spaces#cloud_budget), [`prewarm`](/spaces/reference/spaces#prewarm).
+Listed by [`network_show`](/spaces/reference/spaces#network_show), [`network_set`](/spaces/reference/spaces#network_set), [`resize_space`](/spaces/reference/spaces#resize_space), [`space_service`](/spaces/reference/spaces#space_service), [`thread_join`](/spaces/reference/threads#thread_join), [`thread_join_code_create`](/spaces/reference/threads#thread_join_code_create), [`thread_join_code_cancel`](/spaces/reference/threads#thread_join_code_cancel), [`volume_storage_set`](/spaces/reference/agents#volume_storage_set), [`volume_cache_set`](/spaces/reference/agents#volume_cache_set), [`relay_unregister_space`](/spaces/reference/sharing-and-cloud#relay_unregister_space), [`cloud_connect`](/spaces/reference/sharing-and-cloud#cloud_connect), [`cloud_approve`](/spaces/reference/sharing-and-cloud#cloud_approve), [`cloud_add_host`](/spaces/reference/sharing-and-cloud#cloud_add_host), [`cloud_budget`](/spaces/reference/sharing-and-cloud#cloud_budget), [`prewarm`](/spaces/reference/sharing-and-cloud#prewarm).
#### not_found
@@ -307,7 +311,7 @@ No Space, run, window, service, tool or file with that id.
Fix: List what exists first (list_spaces, agent_list, list_space_windows, list_tools).
-Listed by [`thread_join_code_cancel`](/spaces/reference/threads#thread_join_code_cancel), [`volume_sync_resolve`](/spaces/reference/agents#volume_sync_resolve), [`cloud_remove_host`](/spaces/reference/spaces#cloud_remove_host).
+Listed by [`network_show`](/spaces/reference/spaces#network_show), [`network_set`](/spaces/reference/spaces#network_set), [`space_job`](/spaces/reference/spaces#space_job), [`space_service`](/spaces/reference/spaces#space_service), [`thread_join_code_cancel`](/spaces/reference/threads#thread_join_code_cancel), [`volume_sync_resolve`](/spaces/reference/agents#volume_sync_resolve), [`cloud_remove_host`](/spaces/reference/sharing-and-cloud#cloud_remove_host).
#### spacesd_not_available
@@ -321,6 +325,8 @@ The Space's cua-spacesd reports a feature this tool needs as unsupported; the me
Fix: Use a Space whose spacesd supports the feature (see the tool's `requires`).
+Listed by [`space_service`](/spaces/reference/spaces#space_service).
+
#### host_capability_missing
A prerequisite on this computer is missing: a local runtime, an operator display or app-session providers.
@@ -333,7 +339,7 @@ The operation does not apply to this kind of Space.
Fix: Use a tool that serves the Space's provider (see the tool's `providers`).
-Listed by [`stop_space`](/spaces/reference/spaces#stop_space), [`resize_space`](/spaces/reference/spaces#resize_space), [`start_space`](/spaces/reference/spaces#start_space).
+Listed by [`network_set`](/spaces/reference/spaces#network_set), [`stop_space`](/spaces/reference/spaces#stop_space), [`resize_space`](/spaces/reference/spaces#resize_space), [`start_space`](/spaces/reference/spaces#start_space), [`space_job`](/spaces/reference/spaces#space_job).
#### unauthenticated
@@ -341,7 +347,7 @@ The Space's spacesd or the cua.ai relay rejected the token.
Fix: Re-add the Space with a valid token, or sign in again with `cua auth login`.
-Listed by [`add_space`](/spaces/reference/spaces#add_space), [`list_spaces`](/spaces/reference/spaces#list_spaces), [`share_space`](/spaces/reference/spaces#share_space), [`unshare_space`](/spaces/reference/spaces#unshare_space), [`space_shares`](/spaces/reference/spaces#space_shares), [`relay_register_space`](/spaces/reference/spaces#relay_register_space), [`relay_unregister_space`](/spaces/reference/spaces#relay_unregister_space).
+Listed by [`add_space`](/spaces/reference/spaces#add_space), [`list_spaces`](/spaces/reference/spaces#list_spaces), [`share_space`](/spaces/reference/sharing-and-cloud#share_space), [`unshare_space`](/spaces/reference/sharing-and-cloud#unshare_space), [`space_shares`](/spaces/reference/sharing-and-cloud#space_shares), [`relay_register_space`](/spaces/reference/sharing-and-cloud#relay_register_space), [`relay_unregister_space`](/spaces/reference/sharing-and-cloud#relay_unregister_space).
#### permission_denied
@@ -349,7 +355,7 @@ The signed-in account may not reach that relay computer.
Fix: Sign in with the account that owns the computer.
-Listed by [`stop_space`](/spaces/reference/spaces#stop_space), [`start_space`](/spaces/reference/spaces#start_space), [`thread_import`](/spaces/reference/threads#thread_import), [`agent_set_rights`](/spaces/reference/threads#agent_set_rights), [`thread_join`](/spaces/reference/threads#thread_join), [`thread_join_code_create`](/spaces/reference/threads#thread_join_code_create), [`thread_join_code_cancel`](/spaces/reference/threads#thread_join_code_cancel), [`thread_join_redeem`](/spaces/reference/threads#thread_join_redeem), [`thread_settings`](/spaces/reference/threads#thread_settings), [`thread_device_revoke`](/spaces/reference/threads#thread_device_revoke), [`share_space`](/spaces/reference/spaces#share_space), [`unshare_space`](/spaces/reference/spaces#unshare_space), [`relay_unregister_space`](/spaces/reference/spaces#relay_unregister_space).
+Listed by [`stop_space`](/spaces/reference/spaces#stop_space), [`start_space`](/spaces/reference/spaces#start_space), [`thread_import`](/spaces/reference/threads#thread_import), [`agent_set_rights`](/spaces/reference/threads#agent_set_rights), [`thread_join`](/spaces/reference/threads#thread_join), [`thread_join_code_create`](/spaces/reference/threads#thread_join_code_create), [`thread_join_code_cancel`](/spaces/reference/threads#thread_join_code_cancel), [`thread_join_redeem`](/spaces/reference/threads#thread_join_redeem), [`thread_settings`](/spaces/reference/threads#thread_settings), [`thread_device_revoke`](/spaces/reference/threads#thread_device_revoke), [`share_space`](/spaces/reference/sharing-and-cloud#share_space), [`unshare_space`](/spaces/reference/sharing-and-cloud#unshare_space), [`relay_unregister_space`](/spaces/reference/sharing-and-cloud#relay_unregister_space).
#### ambiguous_host
@@ -365,7 +371,7 @@ The host is at a capacity limit: two macOS VMs per Mac (Apple's macOS license, e
Fix: Delete a Space on that host (delete_space), pick another computer, or create a Linux Space instead.
-Listed by [`create_space`](/spaces/reference/spaces#create_space), [`cloud_plan`](/spaces/reference/spaces#cloud_plan), [`prewarm`](/spaces/reference/spaces#prewarm).
+Listed by [`create_space`](/spaces/reference/spaces#create_space), [`cloud_plan`](/spaces/reference/sharing-and-cloud#cloud_plan), [`prewarm`](/spaces/reference/sharing-and-cloud#prewarm).
#### host_capacity
@@ -453,7 +459,7 @@ Starting, stopping or deleting the Space's sandbox failed.
Fix: Check the local runtime (`cua doctor`) or the cloud pool, then retry.
-Listed by [`create_space`](/spaces/reference/spaces#create_space), [`delete_space`](/spaces/reference/spaces#delete_space), [`stop_space`](/spaces/reference/spaces#stop_space), [`resize_space`](/spaces/reference/spaces#resize_space), [`start_space`](/spaces/reference/spaces#start_space), [`agent_pause`](/spaces/reference/agents#agent_pause), [`agent_resume`](/spaces/reference/agents#agent_resume).
+Listed by [`create_space`](/spaces/reference/spaces#create_space), [`network_set`](/spaces/reference/spaces#network_set), [`delete_space`](/spaces/reference/spaces#delete_space), [`stop_space`](/spaces/reference/spaces#stop_space), [`resize_space`](/spaces/reference/spaces#resize_space), [`start_space`](/spaces/reference/spaces#start_space), [`agent_pause`](/spaces/reference/agents#agent_pause), [`agent_resume`](/spaces/reference/agents#agent_resume).
#### cloud
@@ -461,7 +467,7 @@ Your cloud account refused or failed a call Cua made for a Space there (AWS, Goo
Fix: Fix what the message names in that account (`cua cloud test <provider>` checks without creating anything), or connect another region or project.
-Listed by [`stop_space`](/spaces/reference/spaces#stop_space), [`start_space`](/spaces/reference/spaces#start_space), [`cloud_connect`](/spaces/reference/spaces#cloud_connect), [`cloud_test`](/spaces/reference/spaces#cloud_test), [`cloud_disconnect`](/spaces/reference/spaces#cloud_disconnect), [`cloud_approve`](/spaces/reference/spaces#cloud_approve), [`cloud_sweep`](/spaces/reference/spaces#cloud_sweep), [`cloud_plan`](/spaces/reference/spaces#cloud_plan), [`cloud_hosts`](/spaces/reference/spaces#cloud_hosts), [`cloud_add_host`](/spaces/reference/spaces#cloud_add_host), [`cloud_remove_host`](/spaces/reference/spaces#cloud_remove_host), [`cloud_reconcile`](/spaces/reference/spaces#cloud_reconcile), [`prewarm`](/spaces/reference/spaces#prewarm), [`prewarm_list`](/spaces/reference/spaces#prewarm_list), [`prewarm_remove`](/spaces/reference/spaces#prewarm_remove).
+Listed by [`stop_space`](/spaces/reference/spaces#stop_space), [`start_space`](/spaces/reference/spaces#start_space), [`cloud_connect`](/spaces/reference/sharing-and-cloud#cloud_connect), [`cloud_test`](/spaces/reference/sharing-and-cloud#cloud_test), [`cloud_disconnect`](/spaces/reference/sharing-and-cloud#cloud_disconnect), [`cloud_approve`](/spaces/reference/sharing-and-cloud#cloud_approve), [`cloud_sweep`](/spaces/reference/sharing-and-cloud#cloud_sweep), [`cloud_plan`](/spaces/reference/sharing-and-cloud#cloud_plan), [`cloud_hosts`](/spaces/reference/sharing-and-cloud#cloud_hosts), [`cloud_add_host`](/spaces/reference/sharing-and-cloud#cloud_add_host), [`cloud_remove_host`](/spaces/reference/sharing-and-cloud#cloud_remove_host), [`cloud_reconcile`](/spaces/reference/sharing-and-cloud#cloud_reconcile), [`prewarm`](/spaces/reference/sharing-and-cloud#prewarm), [`prewarm_list`](/spaces/reference/sharing-and-cloud#prewarm_list), [`prewarm_remove`](/spaces/reference/sharing-and-cloud#prewarm_remove).
#### relay
@@ -469,7 +475,7 @@ The cua.ai relay directory failed.
Fix: Retry; check `cua auth status`.
-Listed by [`list_spaces`](/spaces/reference/spaces#list_spaces), [`stop_space`](/spaces/reference/spaces#stop_space), [`start_space`](/spaces/reference/spaces#start_space), [`share_space`](/spaces/reference/spaces#share_space), [`unshare_space`](/spaces/reference/spaces#unshare_space), [`space_shares`](/spaces/reference/spaces#space_shares), [`relay_register_space`](/spaces/reference/spaces#relay_register_space), [`relay_unregister_space`](/spaces/reference/spaces#relay_unregister_space).
+Listed by [`list_spaces`](/spaces/reference/spaces#list_spaces), [`stop_space`](/spaces/reference/spaces#stop_space), [`start_space`](/spaces/reference/spaces#start_space), [`share_space`](/spaces/reference/sharing-and-cloud#share_space), [`unshare_space`](/spaces/reference/sharing-and-cloud#unshare_space), [`space_shares`](/spaces/reference/sharing-and-cloud#space_shares), [`relay_register_space`](/spaces/reference/sharing-and-cloud#relay_register_space), [`relay_unregister_space`](/spaces/reference/sharing-and-cloud#relay_unregister_space).
#### mcp
diff --git a/docs/content/docs/spaces/reference/meta.json b/docs/content/docs/spaces/reference/meta.json
index d07e0c02c8..bdafe79a05 100644
--- a/docs/content/docs/spaces/reference/meta.json
+++ b/docs/content/docs/spaces/reference/meta.json
@@ -3,6 +3,7 @@
"pages": [
"index",
"spaces",
+ "sharing-and-cloud",
"agents",
"threads"
]
diff --git a/docs/content/docs/spaces/reference/sharing-and-cloud.mdx b/docs/content/docs/spaces/reference/sharing-and-cloud.mdx
new file mode 100644
index 0000000000..787ecfc7f7
--- /dev/null
+++ b/docs/content/docs/spaces/reference/sharing-and-cloud.mdx
@@ -0,0 +1,758 @@
+---
+title: "Sharing and cloud tools"
+description: "Share a Space with other accounts, and create Spaces in your own cloud: the tools with their parameters, results and errors."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:spaces
+ Source: libs/cua/spaces-contract/manifest.json
+ Version: 0.9.0
+*/}
+
+## Sharing
+
+Let other cua.ai accounts watch or edit a Space, through the relay.
+
+| Tool | Description |
+| --- | --- |
+| [`share_space`](#share_space) | Let someone in your team watch or edit a Space. |
+| [`unshare_space`](#unshare_space) | Stop sharing a Space with an account, or with everyone. |
+| [`space_shares`](#space_shares) | List who a Space is shared with. |
+| [`relay_register_space`](#relay_register_space) | Publish a Space on the relay for the account's other devices. |
+| [`relay_unregister_space`](#relay_unregister_space) | Take a Space off the relay. |
+
+### share_space
+
+Let someone in your team watch or edit a Space.
+
+Shares the Space through the cua.ai relay with one person in your own team, by verified email or account id, or with the whole team as `team:<id>` (as a viewer or an editor). Sharing is for teams: an account in no team gets `sharing_needs_team` ("Sharing is for teams. Start a team to share this Space."), and someone outside your team gets `share_outside_team`. The same allowlist and device enrollment `cua host share` uses. A viewer joins presence with their own named cursor and watches a view-only stream: the Space's driver refuses their input, shell, files and MCP. An editor gets full use, and their input is a human session. Sharing again changes the role. A host (`relay:<id>`) is shared directly; any other Space (local, cloud, or added by address) is attached to the relay on its first share: its own driver dials out, so it needs no inbound port. Invitees open `invitee_space`.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:share_space`; mutating, idempotent |
+| Requires (this computer) | `relay_account` |
+| Swift SDK | `space.sharing.share(with:role:)` |
+| Rust | `Spaces::share_space` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `role` | `string` | `viewer` | `viewer` (presence with their own cursor and a view-only stream) or `editor` (full use; their input is a human session). Default `viewer`. |
+| `space` | `string` | required | Space id or name. |
+| `who` | `string` | required | Who: the email address (verified by cua.ai) or account id of someone in your own team, or `team:<id>` for the whole team (as `viewer` or `editor`). Sharing is for teams: it needs a team on the Teams plan, and a whole-team share needs a team owner or admin who owns the Space. |
+
+#### Result
+
+JSON: `space`, `machine` (the relay computer it is shared as; empty when not shared), `invitee_space` (what the people it is shared with open: `relay:<computer>`), `url`, `online` and `shares` (each `who`, `role`: viewer or editor, and `connected`).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`host_capability_missing`](/spaces/reference#host_capability_missing), [`relay`](/spaces/reference#relay), [`permission_denied`](/spaces/reference#permission_denied), [`unauthenticated`](/spaces/reference#unauthenticated)
+
+#### Notes
+
+- Viewers and editors are enforced by the Space's own cua-spacesd, not by the caller; a Space whose driver predates relay_attach reports capability_missing.
+
+### unshare_space
+
+Stop sharing a Space with an account, or with everyone.
+
+Removes one account (or everyone) at once: the relay cuts their open streams and refuses new calls. With no `who`, the Space stops being shared and a Space that is not a host leaves the relay.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:unshare_space`; mutating, idempotent |
+| Requires (this computer) | `relay_account` |
+| Swift SDK | `space.sharing.unshare(_:)` |
+| Rust | `Spaces::unshare_space` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `space` | `string` | required | Space id or name. |
+| `who` | `string` | none | The email or account id to remove. Default: everyone (the Space stops being shared; a Space that is not a host leaves the relay). |
+
+#### Result
+
+JSON: `space`, `machine` (the relay computer it is shared as; empty when not shared), `invitee_space` (what the people it is shared with open: `relay:<computer>`), `url`, `online` and `shares` (each `who`, `role`: viewer or editor, and `connected`).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`host_capability_missing`](/spaces/reference#host_capability_missing), [`relay`](/spaces/reference#relay), [`permission_denied`](/spaces/reference#permission_denied), [`unauthenticated`](/spaces/reference#unauthenticated)
+
+### space_shares
+
+List who a Space is shared with.
+
+Who the Space is shared with, in which role, and who of them is connected through the relay now.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:space_shares`, in `spaces:readonly`; read-only, idempotent |
+| Requires (this computer) | `relay_account` |
+| Swift SDK | `space.sharing.shares()` |
+| Rust | `Spaces::space_shares` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `audit` | `integer` | `0` | Also return this many of the newest owner-side audit lines. Default 0. At least 0. |
+| `space` | `string` | required | Space id or name. |
+
+#### Result
+
+JSON: the shares (see share_space) and, with `audit`, `audit`: the newest owner-side lines (`ts_ms`, `action`: share, unshare, attach or detach, `space`, `detail`).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`host_capability_missing`](/spaces/reference#host_capability_missing), [`relay`](/spaces/reference#relay), [`unauthenticated`](/spaces/reference#unauthenticated)
+
+### relay_register_space
+
+Publish a Space on the relay for the account's other devices.
+
+Publishes the Space as a computer of the signed-in account on the cua.ai relay, the way `cua host setup` publishes this computer: the Space's own driver joins the relay over outbound WSS with a computer token the account registered, so no inbound port is opened. The account's other devices (a phone off this network, the Cua app on another computer) then open `relay_space`; nobody else can until share_space adds them. Idempotent, and it re-attaches a Space that restarted. Needs a driver with relay_attach (a host is already registered).
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:relay_register_space`; mutating, idempotent |
+| Requires (this computer) | `relay_account` |
+| Swift SDK | `spaces.relay.register(_:)` |
+| Rust | `Spaces::relay_register` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `space` | `string` | required | Space id or name. |
+
+#### Result
+
+JSON: `space`, `relay_space` (`relay:<computer>`: how the account's other devices reach it), `machine`, `url` and `online`.
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`host_capability_missing`](/spaces/reference#host_capability_missing), [`relay`](/spaces/reference#relay), [`unauthenticated`](/spaces/reference#unauthenticated)
+
+### relay_unregister_space
+
+Take a Space off the relay.
+
+Takes the Space off the relay: its driver leaves and its computer is removed, with every share. A `relay:<computer>` id removes that computer's record from the relay directory, which only its owner may do: a Space that registered itself (also after it was deleted), or a computer that is no longer connected. A host that is connected now is taken off with `cua host remove` on that computer instead.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:relay_unregister_space`; mutating, idempotent |
+| Requires (this computer) | `relay_account` |
+| Swift SDK | `spaces.relay.unregister(_:)` |
+| Rust | `Spaces::relay_unregister` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `space` | `string` | required | Space id or name. |
+
+#### Result
+
+JSON: `space` and `unregistered` (false when it was not on the relay).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`host_capability_missing`](/spaces/reference#host_capability_missing), [`relay`](/spaces/reference#relay), [`unauthenticated`](/spaces/reference#unauthenticated), [`permission_denied`](/spaces/reference#permission_denied)
+
+## Your cloud
+
+Create Spaces in your own AWS, Google Cloud, Hetzner or Modal account: connect it, check it, and clean up what Cua created there.
+
+| Tool | Description |
+| --- | --- |
+| [`cloud_status`](#cloud_status) | List your clouds (AWS, Google Cloud, Hetzner, Modal): found credentials, the connected account and region, what each can run at what hourly cost, and what Cua created there. |
+| [`cloud_connect`](#cloud_connect) | Connect a cloud account Spaces can be created in. |
+| [`cloud_test`](#cloud_test) | Check a cloud account without creating anything. |
+| [`cloud_disconnect`](#cloud_disconnect) | Forget a connected cloud account (deleting what Cua created there first, with delete=true). |
+| [`cloud_approve`](#cloud_approve) | Approve (or deny) what an agent asked for on a cloud: its link or its raised limits. For a person only. |
+| [`cloud_sweep`](#cloud_sweep) | Find and delete what Cua left in your clouds. |
+| [`cloud_plan`](#cloud_plan) | Show (or apply) the elastic pool's plan for some Spaces: where they go, which machines it adds, and the cost. |
+| [`cloud_hosts`](#cloud_hosts) | List the hosts the elastic pool added in your clouds. |
+| [`cloud_add_host`](#cloud_add_host) | Add hosts to your pool in a linked cloud. |
+| [`cloud_remove_host`](#cloud_remove_host) | Remove hosts this home added to your pool. |
+| [`cloud_budget`](#cloud_budget) | Read or set the elastic pool's budget and autoscale switch. |
+| [`cloud_reconcile`](#cloud_reconcile) | Run the elastic pool's scale-in pass now. |
+| [`prewarm`](#prewarm) | Keep Spaces of one shape ready where the elastic pool puts them, so the next creates start in a fraction of a second. |
+| [`prewarm_list`](#prewarm_list) | List the prewarms and how many Spaces each keeps ready. |
+| [`prewarm_remove`](#prewarm_remove) | End a prewarm: its ready Spaces go. |
+| [`cloud_audit`](#cloud_audit) | Read the log of what Cua did in your clouds. |
+| [`cloud_cost`](#cloud_cost) | Estimate what Cua's machines in your clouds cost, by Space, agent, day or cloud. |
+
+### cloud_status
+
+List your clouds (AWS, Google Cloud, Hetzner, Modal): found credentials, the connected account and region, what each can run at what hourly cost, and what Cua created there.
+
+Sandboxes and Spaces can run in the user's own cloud account: on="aws" (EC2), "azure" (Azure Virtual Machines), "gcp" (Compute Engine), "hetzner" (Hetzner Cloud) or "modal" (Modal Sandboxes). EC2, Azure, Compute Engine and Hetzner Cloud start one small VM or server per sandbox that runs the image with Docker; Modal runs one Modal sandbox. Hetzner Cloud servers have no /dev/kvm, so Hetzner runs container images only (Windows and other VM images are refused). Either way the guest's cua-spacesd dials out to the cua.ai relay as a computer of the signed-in account (no inbound port), and the Space is that computer, relay:&lt;computer&gt;. AWS and Google Cloud use their own CLI sign-in or, with auth="oidc", no stored key at all (Cua's issuer signs short-lived tokens the account trusts); Azure always links that way; Modal uses its CLI sign-in; Hetzner uses a project API token (Read & Write), and Modal can take its token too: cloud_connect seals it to the account's devices (Cua's servers keep only ciphertext; no tool returns it), or keeps Hetzner's in this device's Cua credential store (auth="cli"). Connect it first with cloud_connect (the user decides; it costs money in their account). Everything Cua creates is tagged cua-managed=true with this cua home's cua-owner and an expiry, recorded under the cua home, deleted with its sandbox, and ends itself at its expiry (a Hetzner server, which cannot delete itself, shuts down and is billed until cloud_sweep or delete_space removes it); cloud_sweep removes leftovers, and the daemon runs that sweep by itself every 15 minutes (CUA_CLOUD_SWEEP_SECS; 0 turns it off). cloud_disconnect refuses while Cua resources still run there unless delete=true; cloud_audit lists what Cua did.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_status`, in `spaces:readonly`; read-only, idempotent |
+| Swift SDK | `spaces.cloud.status(provider:)` |
+| Rust | `cua_cloud::Clouds::status` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `provider` | `string` | none | Only this cloud (`aws`, `azure`, `gcp`, `hetzner`, `modal`). Default: every one. |
+
+#### Result
+
+JSON: `default_on`, `providers` (each `name`, `title`, `tier` (`vm`: a VM that provides Spaces, `sandbox`: one sandbox per Space), `connected`, `default`, `credentials` (`found`, `source`), `account`, `profile`, `region`, `zone`, `project`, `environment`, `label` ("AWS · us-west-2"), `ttl_hours`, `kinds` (each `image`, `kind`, `supported`, `reason`, `machine_type`, `usd_per_hour`), `auth` (`cli`, `oidc` or `sealed` once connected), `status` (`connected`, `waiting-for-approval`, `not-connected`, or `failed` when the link was revoked), `budget_usd_month` and `max_size` when set, `spent_month` (estimated US dollars this calendar month), `running` (machines Cua runs there now), `approval` (`connection` or `limits` while a person's approval is pending, else absent) and, for `sealed`, `holders` (the devices that can open the API token now; at least one must be online for machines to be made there unattended)) and `resources` (what Cua created: `provider`, `id`, `type`, `space`, `region`, `state`, `created`, `expires`, `expired`).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument)
+
+### cloud_connect
+
+Connect a cloud account Spaces can be created in.
+
+Without auth it keeps how the cloud is linked already (an OIDC or sealed link stays so, so a run that only changes budget_usd_month or max_size never falls back to a CLI sign-in); a cloud not linked yet, or auth="cli", runs cloud_test first and connects only when every check passes, storing the profile, region, project or environment names under the cua home (never a key: the cloud's own CLI sign-in stays where it is). auth="oidc" links AWS, Google Cloud or Azure with no stored key (Azure is always oidc; a Google Cloud project_number implies it): it never prompts and is idempotent, so call it again with the same arguments until `status` is `connected`, following `next` each time. It needs budget_usd_month first. Until the account is named it returns needs-trust and the trust step: a page for the person (AWS: the trust stack, then ask for the 12-digit account_id; Google Cloud: Cloud Shell and the trust script, then ask for the project_number it prints; Azure: Deploy to Azure, then ask for the outputs subscription_id, tenant_id and client_id), or, when an agent asks on a machine signed in to gcloud or az, the exact command to run. Once named, the link is recorded on Cua's issuer and check=true proves it (a check token, the exchange with the cloud, a dry run, permission check or validate; nothing is created) and saves it. Hetzner and Modal with a token and budget_usd_month seal the token to the account's devices (auth="sealed", the default on a device with the account's pool keys): it is checked first (nothing is created), Cua's servers keep only ciphertext, any device of the account opens it in memory when it calls the cloud, and no tool ever returns it; on another device, auth="sealed" without a token links the account's sealed token. A link, token or limit raise made by an agent returns waiting-for-approval until a person approves it in Cua Spaces. budget_usd_month and max_size (`4x16`) also apply to CLI links: machines past them are refused before any cloud call. With make_default, create_space without `on` creates there (`default.on`).
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_connect`; mutating, idempotent |
+| Swift SDK | `spaces.cloud.connect(_:makeDefault:ttlHours:)` |
+| Rust | `cua_cloud::Clouds::connect` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `account_id` | `string` | none | AWS `oidc`: the 12-digit account id the trust stack is in (the person who created it knows it). |
+| `agent` | `string` | none | The agent making the change (Cua's agent runtime and the cua CLI set it). An agent's link, or a limit it raises, waits for a person's approval in Cua Spaces. |
+| `auth` | `string` | `sealed` | How Cua reaches the cloud: `cli` (the cloud CLI's sign-in, or for Hetzner a token kept on this device), `oidc` (AWS, Google Cloud, Azure: Cua's issuer signs short-lived tokens the account trusts; no key is stored anywhere; Azure is always `oidc`) or `sealed` (Hetzner, Modal: the API token is sealed to the account's devices and Cua's servers keep only ciphertext; with no `token` it seals the one this device has, or links the account's sealed token). Default: `sealed` for Hetzner and Modal when this device has the account's pool keys and a budget is given (or the link is sealed already), else `cli`. |
+| `budget_usd_month` | `number` | none | The most Cua may spend there per calendar month, US dollars. New machines are refused once it is reached; stopping and deleting always works. Needed before the first machine of an `oidc` link. |
+| `check` | `boolean` | none | `oidc`: run the check that proves the link works (a check token, the exchange with the cloud, a dry run; nothing is created). The link is saved only once it passes. |
+| `client_id` | `string` | none | Azure: the client id of the `cua-spaces` managed identity (its `clientId` output). |
+| `environment` | `string` | none | Modal environment (default: the profile's). |
+| `make_default` | `boolean` | `false` | Also make it the default location (`default.on`). Default false. |
+| `max_size` | `string` | none | The largest machine Cua may create there: `<vCPUs>x<GB>`, for example `4x16`. |
+| `profile` | `string` | none | AWS: the profile in `~/.aws/config` (default: `default`, or `AWS_PROFILE`). Modal: the profile in `~/.modal.toml` (default: the active one). |
+| `project` | `string` | none | GCP project id (default: `gcloud config get project`). Hetzner and Modal with a sealed token: a name for the project or workspace (default `default`), to tell several apart. |
+| `project_number` | `string` | none | Google Cloud `oidc`: the project number (the trust script prints it; giving it implies `oidc`). The project id is `target.project`. |
+| `provider` | `string` | required | `aws`, `azure`, `gcp`, `hetzner` or `modal`. |
+| `region` | `string` | none | AWS region (default: the profile's, else `us-west-2`), Hetzner location (default `fsn1`), GCP region (default `us-central1`) or Azure region (default `westus2`). |
+| `resource_group` | `string` | none | Azure: the resource group Cua works in, and the only one its roles reach (default `cua-spaces`). |
+| `role_arn` | `string` | none | AWS `oidc`: the role ARN, only when it is not named `cua-spaces`. |
+| `service_account` | `string` | none | Google Cloud `oidc`: a service account to act as. Default: none, the federated identity calls Google directly. |
+| `subscription_id` | `string` | none | Azure: the subscription id (the trust template's `subscriptionId` output). |
+| `tenant_id` | `string` | none | Azure: the Microsoft Entra tenant id (its `tenantId` output). |
+| `token` | `string` | none | Hetzner: the project's Read & Write API token (default: `HCLOUD_TOKEN`, the saved token, or the `hcloud` CLI's context). Modal: `<token id>:<token secret>`. Secret: never logged or returned; sealed to the account's devices on connect (or, Hetzner with `auth: cli`, saved in this device's Cua credential store). |
+| `ttl_hours` | `integer` | `8` | Every Space created there deletes itself after this many hours (the instance or sandbox terminates, the sweeper removes what is left). Default 8; 0 keeps Spaces until you delete them (Modal caps a sandbox at 24). At least 0. |
+| `zone` | `string` | none | GCP zone in the region (default: its `-a` zone). |
+
+#### Result
+
+JSON: the cloud as `cloud_status` lists it, whose `status` is the outcome (`connected`, `needs-trust`, `checking`, `waiting-for-approval` or `failed`), plus `checks` (each `name`, `ok`, `detail`), `next` (absent when connected; `run`: the exact command for the agent, or `open`: a page for a person, with `paste` when there is a command to paste there, and `why`) and `verify` (the command that confirms it).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
+
+### cloud_test
+
+Check a cloud account without creating anything.
+
+Creates nothing: it signs in with the cloud's own CLI credentials (or, for a link without a stored key, a token from Cua's issuer exchanged with the cloud), asks the cloud to validate a create without doing it (AWS DryRun, Google Cloud permission checks, an Azure deployment validate), and reads quotas. A failed check says what to fix.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_test`, in `spaces:readonly`; read-only, idempotent |
+| Swift SDK | `spaces.cloud.test(_:)` |
+| Rust | `cua_cloud::Clouds::test` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `environment` | `string` | none | Modal environment (default: the profile's). |
+| `profile` | `string` | none | AWS: the profile in `~/.aws/config` (default: `default`, or `AWS_PROFILE`). Modal: the profile in `~/.modal.toml` (default: the active one). |
+| `project` | `string` | none | GCP project id (default: `gcloud config get project`). Hetzner and Modal with a sealed token: a name for the project or workspace (default `default`), to tell several apart. |
+| `provider` | `string` | required | `aws`, `azure`, `gcp`, `hetzner` or `modal`. |
+| `region` | `string` | none | AWS region (default: the profile's, else `us-west-2`), Hetzner location (default `fsn1`), GCP region (default `us-central1`) or Azure region (default `westus2`). |
+| `token` | `string` | none | Hetzner: the project's Read & Write API token (default: `HCLOUD_TOKEN`, the saved token, or the `hcloud` CLI's context). Modal: `<token id>:<token secret>`. Secret: never logged or returned; sealed to the account's devices on connect (or, Hetzner with `auth: cli`, saved in this device's Cua credential store). |
+| `zone` | `string` | none | GCP zone in the region (default: its `-a` zone). |
+
+#### Result
+
+JSON: `provider`, `ok`, `account` (the account, project or workspace the credentials reach) and `checks` (each `name`, `ok`, `detail`: credentials, permissions by dry run, quota, the region and machine types).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
+
+### cloud_disconnect
+
+Forget a connected cloud account (deleting what Cua created there first, with delete=true).
+
+Refuses (a `cloud` error listing them) while Cua-created instances or sandboxes still run in that cloud, because a disconnected cloud is no longer swept and they would bill unseen. With delete=true it first deletes everything Cua created there (the same tag and record checks as cloud_sweep with all=true), then asks the cloud again and forgets the connection (and `default.on` when it named this cloud) only when nothing is left; if something remains it keeps the connection and says what. Nothing that Cua did not create is ever touched.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_disconnect`; destructive |
+| Swift SDK | `spaces.cloud.disconnect(_:delete:)` |
+| Rust | `cua_cloud::Clouds::disconnect` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `delete` | `boolean` | `false` | Delete everything Cua created in that cloud first, and disconnect only once the cloud confirms nothing is left. Default false: the call is refused (listing them) while Cua resources still run there. |
+| `provider` | `string` | required | `aws`, `azure`, `gcp`, `hetzner` or `modal`. |
+
+#### Result
+
+JSON: `provider`, `disconnected`, `deleted` (with delete=true: the receipt, each resource deleted first) and `left` (resources Cua still records there).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
+
+### cloud_approve
+
+Approve (or deny) what an agent asked for on a cloud: its link or its raised limits. For a person only.
+
+Only for a person, never for an agent: no MCP server lists or runs it, the daemon refuses it when it runs for an agent, and Cua's issuer refuses an agent's proof. It approves what an agent asked for on that cloud (its link, or a raise of its budget or largest machine; see `approval`, `approval_agent`, `pending_budget_usd_month` and `pending_max_size` in cloud_status), or with deny=true declines it: a raise is dropped and the limits in force stay; a link never approved is disconnected.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_approve`; destructive |
+| Swift SDK | `spaces.cloud.approve(_:deny:)` |
+| Rust | `cua_cloud::Clouds::approve` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `deny` | `boolean` | `false` | Decline instead: an agent's raise is dropped (the limits in force stay), an agent's link that was never approved is disconnected. Default false. |
+| `provider` | `string` | required | `aws`, `gcp`, `hetzner` or `modal`. |
+
+#### Result
+
+JSON: the cloud as `cloud_status` lists it once approved or denied (`status`, `approval` empty, the limits in force).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
+
+### cloud_sweep
+
+Find and delete what Cua left in your clouds.
+
+Acts only on resources that carry Cua's tags (cua-managed=true and this device's cua-owner) and that this cua home recorded, or that carry this device's owner id: never on anything else in the account. Default dry_run=true lists what it would delete: expired Spaces (past their ttl), resources whose Space is gone, and with all=true every Cua resource there.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_sweep`; destructive |
+| Swift SDK | `spaces.cloud.sweep(provider:dryRun:all:)` |
+| Rust | `cua_cloud::Clouds::sweep` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `all` | `boolean` | `false` | Also delete Cua resources that have not expired yet (every Space in that cloud). Default false: only expired ones, and resources no Space refers to any more. |
+| `dry_run` | `boolean` | `true` | List what would be deleted without deleting it. Default true. |
+| `provider` | `string` | none | Only this cloud. Default: every connected one. |
+
+#### Result
+
+JSON: `dry_run` and `resources`, each `provider`, `id`, `type`, `space`, `expires`, `action` (`delete`, `deleted`, `keep` or `failed`) and `reason`.
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
+
+### cloud_plan
+
+Show (or apply) the elastic pool's plan for some Spaces: where they go, which machines it adds, and the cost.
+
+The elastic pool places Spaces with on="auto" (or on a linked cloud) by one solve: the user's devices first (free), then cloud hosts already running, then new cloud hosts (provider x type x region) at the least cost that fits the image's needs (kind, KVM, arch, size learned from earlier Spaces), the start-time goal, the relay's machine limit and the budget (cloud_budget). Idle cloud hosts go at the end of their paid time. cloud_plan shows the decision without doing it; pins (provider, region, instance_type, hosts, no_scale, devices_only, max_usd_per_hour) are constraints of the same solve, so an agent can inspect, adjust and apply.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_plan`; destructive |
+| Swift SDK | `spaces.cloud.plan(_:)` |
+| Rust | `Spaces::elastic_plan` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `apply` | `boolean` | `false` | Add the machines the plan needs (they join the pool; create the Spaces with on="auto"). Default false: plan only. |
+| `caller` | `string` | none | Who asks: `interactive` (one Space someone waits on), `batch`, `compat` or `persistent_agent`. Default: interactive for one Space, batch for more. |
+| `count` | `integer` | `1` | How many Spaces. Default 1. At least 0. |
+| `cpus` | `integer` | none | vCPUs each. Default: what Spaces of this image used before, else the image's size. At least 0. |
+| `devices_only` | `boolean` | none | Only the user's own devices. |
+| `duration_secs` | `integer` | none | Expected lifetime, seconds. At least 0. |
+| `hosts` | `integer` | none | Exactly this many new machines. At least 0. |
+| `image` | `string` | none | Image (`linux`, `windows`, an OCI reference). Default: linux. |
+| `instance_type` | `string` | none | Only this machine type. |
+| `kind` | `string` | none | `container`, `vm` or `microvm`. Default: from the image. |
+| `max_usd_per_hour` | `number` | none | A $/hour cap for this plan (default: the budget's). |
+| `memory_mb` | `integer` | none | Memory each, MiB. At least 0. |
+| `no_scale` | `boolean` | none | Add no machines (place on what runs). |
+| `provider` | `string` | none | Only this cloud. |
+| `region` | `string` | none | Only this region. |
+| `together` | `boolean` | none | Keep them on one machine (forks of one checkpoint). |
+
+#### Result
+
+JSON: `plan` (`assignments`: `group`, `target` (`on`: `host` with `name`, or `new` with `index`), `count`; `new_hosts`: `provider`, `type_name`, `region`, `usd_per_hour`, `boot_secs`, `billed_secs`; `unplaced` with `reason`; `added_usd_per_hour`, `projected_usd`, `lower_bound_usd`, `solver`, `ready_in_secs`, `explain`), `groups` (the demand it detected) and `pool` (`hosts`, `cloud`, `offers`, `constraints`, `month_usd`); with apply, `added` (the hosts added).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud), [`limit_exceeded`](/spaces/reference#limit_exceeded)
+
+### cloud_hosts
+
+List the hosts the elastic pool added in your clouds.
+
+The hosts the elastic pool (or cloud_add_host) added in the user's linked clouds: machines that provide Spaces to the pool, with their live cost.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_hosts`, in `spaces:readonly`; read-only, idempotent |
+| Swift SDK | `spaces.cloud.hosts()` |
+| Rust | `cua_cloud::Clouds::hosts` |
+
+#### Parameters
+
+No parameters.
+
+#### Result
+
+JSON array: each host `name`, `provider`, `type_name`, `region`, `id`, `machine`, `state` (`creating`, `booting`, `joined`, `cordoned`, `offline`, `gone`), `started`, `expires`, `usd_per_hour`, `billing_step_secs`, `billing_min_secs`, `pinned`.
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
+
+### cloud_add_host
+
+Add hosts to your pool in a linked cloud.
+
+Adds hosts by hand (pinned: the scaler never removes them); it costs money in the user's account. Each host is tagged and recorded first, installs cua, joins the pool and ends at its TTL. cloud_remove_host removes it.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_add_host`; destructive |
+| Swift SDK | `spaces.cloud.addHost(_:)` |
+| Rust | `cua_cloud::Clouds::add_host` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `count` | `integer` | `1` | How many, 1 to 10. Default 1. At least 0. |
+| `instance_type` | `string` | required | Machine type (`cloud_plan` and `cloud_status` list them). |
+| `provider` | `string` | required | `aws`, `azure`, `gcp` or `hetzner`. |
+| `region` | `string` | none | Region. Default: the connection's. |
+| `ttl_hours` | `integer` | `24` | Hours until each ends on its own, 1 to 168. Default 24. At least 0. |
+
+#### Result
+
+JSON array: the hosts added (see cloud_hosts).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
+
+### cloud_remove_host
+
+Remove hosts this home added to your pool.
+
+Deletes the hosts' machines (only ones this cua home added and tagged) and their relay entries. The Spaces on them end.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_remove_host`; destructive |
+| Swift SDK | `spaces.cloud.removeHost(_:)` |
+| Rust | `cua_cloud::Clouds::remove_host` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `names` | `string[]` | required | Their names (`hetzner-1`). |
+
+#### Result
+
+JSON: `removed` (names) and `failed` (each `name`, `error`).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud), [`not_found`](/spaces/reference#not_found)
+
+### cloud_budget
+
+Read or set the elastic pool's budget and autoscale switch.
+
+The caps the elastic pool keeps to: it never adds a machine that would take the clouds' cost over max_usd_per_hour or this month's spend over monthly_usd, and with autoscale false it adds none. Fields given are set; the rest stay.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_budget`; mutating, idempotent |
+| Swift SDK | `spaces.cloud.budget(_:)` |
+| Rust | `Spaces::set_elastic_policy` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `allow_metal` | `boolean` | none | Let one small VM Space buy a KVM metal host (dollars an hour). Off: such a request is refused with the reason; batches of forks may still buy one. |
+| `autoscale` | `boolean` | none | Add and remove cloud hosts by itself. |
+| `max_new_hosts` | `integer` | none | Most hosts one placement adds. At least 0. |
+| `max_usd_per_hour` | `number` | none | Most USD per hour your clouds may cost at once. |
+| `monthly_usd` | `number` | none | Most USD per calendar month on elastic hosts. |
+| `warm` | `boolean` | none | Keep an idle host warm when demand predicts a Space soon. |
+
+#### Result
+
+JSON: `policy` (`autoscale`, `max_usd_per_hour`, `monthly_usd`, `max_new_hosts`, `warm`, `interactive_slo_secs`, `routed`, `allow_metal`), `month_usd` (spent this month on elastic hosts), `running_usd_per_hour` and `hosts` (how many run).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument)
+
+### cloud_reconcile
+
+Run the elastic pool's scale-in pass now.
+
+One scale-in pass now (the daemon runs one every 30 s): idle hosts go at the end of the time already paid, the least-used one is cordoned when the others have room.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_reconcile`; destructive |
+| Swift SDK | `spaces.cloud.reconcile()` |
+| Rust | `Spaces::elastic_reconcile` |
+
+#### Parameters
+
+No parameters.
+
+#### Result
+
+JSON array: each `host` and `action` (`action`: `keep` with `until` and `reason`, `cordon` with `reason`, or `remove` with `reason` and `saves_usd`).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
+
+### prewarm
+
+Keep Spaces of one shape ready where the elastic pool puts them, so the next creates start in a fraction of a second.
+
+A prewarm keeps count Spaces of one shape (image, kind, cpus, memory_mb) ready on the machines the elastic pool picks (the same solve as on="auto": devices first, then hosts with room, then new cloud machines, under the budget and pins). Any later create of that shape on those machines claims one in a fraction of a second, through every surface, with no extra argument; the pool keeps count ready until ttl_secs. A prewarm the budget, quotas or pins cannot fit is refused and buys nothing. End it with prewarm_remove when the burst is over.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:prewarm`; destructive |
+| Swift SDK | `spaces.prewarm(_:)` |
+| Rust | `Spaces::prewarm` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `count` | `integer` | `1` | How many to keep ready, 1 to 256. Default 1. At least 0. |
+| `cpus` | `integer` | none | vCPUs each. Default: the size Spaces of this image use. At least 0. |
+| `image` | `string` | required | Image (`linux`, an OCI reference). |
+| `instance_type` | `string` | none | Only this cloud machine type. |
+| `kind` | `string` | none | `container`, `vm` or `microvm`. Default: the image's. |
+| `memory_mb` | `integer` | none | Memory each, MiB. At least 0. |
+| `on` | `string` | none | Where: `auto` (default: your devices first, then hosts with room, then new cloud machines), `local`, a linked cloud or `host:<machine>`. |
+| `region` | `string` | none | Only this cloud region. |
+| `ttl_secs` | `integer` | none | Seconds to keep them (default 3600, at most 604800). At least 0. |
+
+#### Result
+
+JSON: `id`, `image`, `kind`, `cpus`, `memory_mb`, `count`, `ready`, `placements` (`host`, `machine`, `count`, `ready`), `expires_at` (unix seconds) and `new_hosts` (hosts added for it).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`limit_exceeded`](/spaces/reference#limit_exceeded), [`cloud`](/spaces/reference#cloud)
+
+### prewarm_list
+
+List the prewarms and how many Spaces each keeps ready.
+
+A prewarm keeps count Spaces of one shape (image, kind, cpus, memory_mb) ready on the machines the elastic pool picks (the same solve as on="auto": devices first, then hosts with room, then new cloud machines, under the budget and pins). Any later create of that shape on those machines claims one in a fraction of a second, through every surface, with no extra argument; the pool keeps count ready until ttl_secs. A prewarm the budget, quotas or pins cannot fit is refused and buys nothing. End it with prewarm_remove when the burst is over.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:prewarm_list`, in `spaces:readonly`; read-only, idempotent |
+| Swift SDK | `spaces.prewarms()` |
+| Rust | `Spaces::prewarms` |
+
+#### Parameters
+
+No parameters.
+
+#### Result
+
+JSON array of prewarms, as `prewarm` returns them, with `ready` counted now.
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
+
+### prewarm_remove
+
+End a prewarm: its ready Spaces go.
+
+A prewarm keeps count Spaces of one shape (image, kind, cpus, memory_mb) ready on the machines the elastic pool picks (the same solve as on="auto": devices first, then hosts with room, then new cloud machines, under the budget and pins). Any later create of that shape on those machines claims one in a fraction of a second, through every surface, with no extra argument; the pool keeps count ready until ttl_secs. A prewarm the budget, quotas or pins cannot fit is refused and buys nothing. End it with prewarm_remove when the burst is over.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:prewarm_remove`; mutating, idempotent |
+| Swift SDK | `spaces.removePrewarm(_:)` |
+| Rust | `Spaces::remove_prewarm` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `id` | `string` | required | The prewarm (`pw-xxxxxx`). |
+
+#### Result
+
+JSON: `removed` (false when there was no such prewarm).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
+
+### cloud_audit
+
+Read the log of what Cua did in your clouds.
+
+Reads the append-only audit log under the cua home (cloud/audit.jsonl, rotated at 5 MB): every connect, disconnect, resource recorded before its create, created, confirmed and deleted (by you, by a sweep, by the automatic sweep, by disconnect with delete), and each budget alert (`budget_alert`). These entries have `source` `device`. For clouds linked to the account (OIDC or a sealed token) it adds what Cua's issuer recorded, with `source` `account`: tokens issued or refused, links made, approved, changed and revoked. It never holds a secret or a token. provider narrows it to one cloud. Default limit 50.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_audit`, in `spaces:readonly`; read-only, idempotent |
+| Swift SDK | `spaces.cloud.audit(limit:)` |
+| Rust | `cua_cloud::Clouds::audit` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `limit` | `integer` | none | How many of the newest entries (default 50, at most 1000). At least 0. |
+| `provider` | `string` | none | Only this cloud (`aws`, `gcp`, `hetzner`, `modal`). Default: every one. |
+
+#### Result
+
+JSON array, oldest first, newest last: each `ts` (RFC 3339), `action` (`connect`, `disconnect`, `resource_recorded`, `resource_created`, `resource_confirmed`, `resource_deleted`), `provider`, `kind`, `id`, `space`, `actor` (`user`, `sweep`, `auto-sweep`, `disconnect`, `rollback`), `outcome` (`ok`, `failed`, `refused`) and `detail`.
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument)
+
+### cloud_cost
+
+Estimate what Cua's machines in your clouds cost, by Space, agent, day or cloud.
+
+Estimates what the machines Cua created cost: each one's list price times how long it ran inside the window, from the machines still recorded and the usage log of the ones gone (cloud/usage.jsonl under the cua home). by=`space`, `agent` (who started it: an agent's name, `user`, or `unknown` for machines recorded before that was kept), `day` (UTC) or `cloud`. since defaults to the first of this month. It is an estimate: the cloud's own bill is the final word. Pool hosts count under `pool hosts`.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:cloud_cost`, in `spaces:readonly`; read-only, idempotent |
+| Swift SDK | `spaces.cloud.cost(by:since:provider:)` |
+| Rust | `cua_cloud::Clouds::cost` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `by` | `string` | `space` | One row per `space`, `agent`, `day` (UTC) or `cloud`. Default `space`. |
+| `provider` | `string` | none | Only this cloud (`aws`, `gcp`, `hetzner`, `modal`). Default: every one. |
+| `since` | `string` | none | The first day counted, `YYYY-MM-DD` (UTC). Default: the first of this month. |
+
+#### Result
+
+JSON: `by`, `since` (`YYYY-MM-DD`), `until` (RFC 3339), `rows` (each `key`: the Space, agent, day or cloud; `usd`: estimated US dollars; `hours`: machine hours; `machines`: how many ran), by day oldest first, otherwise costliest first, and `total_usd`.
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument)
diff --git a/docs/content/docs/spaces/reference/spaces.mdx b/docs/content/docs/spaces/reference/spaces.mdx
index 718f39a009..0da5ddbda9 100644
--- a/docs/content/docs/spaces/reference/spaces.mdx
+++ b/docs/content/docs/spaces/reference/spaces.mdx
@@ -1,6 +1,6 @@
---
title: "Spaces tools"
-description: "Create, run, stream, share and serve from a Space: the Spaces tools with their parameters, results and errors."
+description: "Create, run, stream and serve from a Space: the Spaces tools with their parameters, results and errors."
---
{/*
@@ -20,6 +20,8 @@ Register, provision, list and release Spaces.
| [`remove_space`](#remove_space) | Forget a registered Space without touching it. |
| [`list_spaces`](#list_spaces) | List the Spaces this connection can see. |
| [`create_space`](#create_space) | Create a Space: a new sandbox on this computer, on one of your computers, or in the cloud. |
+| [`network_show`](#network_show) | Show a Space's network: preset, what it opens, where it is enforced, what is always blocked. |
+| [`network_set`](#network_set) | Tighten a Space's network: internet, none or custom lists. Opening more is the user's to do. |
| [`delete_space`](#delete_space) | Delete a Space's sandbox and forget it. |
| [`stop_space`](#stop_space) | Turn a Space off: stop it (disk kept, memory freed) or, with suspend, suspend it (memory kept). |
| [`resize_space`](#resize_space) | Change a Space's vCPUs, memory or disk size. |
@@ -134,8 +136,10 @@ Creates a new sandbox where `on` says (local: this computer, free; aws, azure, g
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
+| `allow` | `string[]` | none | Destinations to allow (addresses or CIDRs) on top of `network`. |
| `command` | `string[]` | none | Entrypoint override (argv), for example `["python", "-m", "my_mcp", "--port", "8765"]`. |
| `count` | `integer` | none | How many Spaces to create, 1 to 8 (default 1), all with the same settings (a name gets `-2`, `-3`, ... suffixes). With more than one the result is an array. At least 0. |
+| `deny` | `string[]` | none | Destinations to block (addresses, CIDRs or `all`). |
| `durable` | `boolean` | `false` | Keep it on the user's machines (with `on` `auto`): when its machine goes away it is created again on another one, with the same name (its disk starts fresh); `list_spaces` shows it with `durable` (its name), and `delete_space` deletes it for good. Default false. |
| `env` | `map of string` | none | Guest environment variables. |
| `image` | `string` | none | Guest image. Default: the canonical Linux image (`ghcr.io/trycua/linux:24.04`), whose variant follows the kind. |
@@ -143,7 +147,9 @@ Creates a new sandbox where `on` says (local: this computer, free; aws, azure, g
| `kind` | `"auto" \| "container" \| "vm" \| "microvm"` | `auto` | What kind of computer. Default `auto` (from the image). `auto`: From the image: macOS and Windows images are VMs, an image with a container rootfs is a container, a disk-only image is a VM. `container`: A container (gVisor, or runc locally). `vm`: A virtual machine (QEMU or Lume locally, KubeVirt in the cloud). `microvm`: A microVM: the image's container rootfs booted with its own kernel (Firecracker on Linux with KVM; on a Mac, Virtualization.framework or Apple's Containerization). |
| `labels` | `map of string` | none | Labels kept with the Space and shown by `list_spaces` (`labels`): up to 64 pairs; keys and values are not empty; keys up to 63 bytes, values up to 256. Not with `durable` or `reuse`. |
| `name` | `string` | none | Name. Default: a generated `space-<hex>`. |
+| `network` | `string` | none | Its network: `internet` (default: the internet and its own tree; this computer, the local network, cloud metadata and other trees are blocked), `none`, or `custom` / `custom:none` with `allow` and `deny`. Presets that open more (`localhost:<ports>`, `lan`, `unprotected`) are the user's to choose: refused here. |
| `on` | `string` | none | Where it runs: `local` (this computer, free), `auto` (the least-loaded of the user's computers that can take it: this one and the ones signed in to the user's account that provide Spaces, Modal only when connected and no computer has room), `aws`, `gcp` or `modal` (your own cloud account, billed there), or `host:<computer>`: one of the user's own computers that provides Spaces (`cua host setup --share both` on it), named by id or by words from its name ("host:spare mac mini" matches "Mac mini (spare)" or `dillons-mac-mini`). Default: the user's default location (`cua config set default.on`, `CUA_DEFAULT_ON`), else `local`; never `auto` unless asked. Not `direct:<addr>`: that is one already-running Space at a fixed address, attached with `add_space`, not a host this can create on. An existing computer is added with `add_space`, not created. |
+| `parent` | `string` | none | Create it as a child of this Space (id or name): it joins the parent's tree, and its network is no more open than the parent's. |
| `region` | `string` | none | With `on` a linked cloud: the region (Hetzner location) its host must be in. Default: any the cloud offers. |
| `reuse` | `boolean` | `false` | Return a reachable registered Space in the same location that has the requested services instead of creating one (get-or-create). Default false. |
| `runtime` | `string` | `auto` | Which engine. Default `auto`: the safest one for the location and kind. Local: `gvisor` or `runc` (containers), `qemu` or `lume` (VMs). Cloud: `gvisor` (containers), `kubevirt` (VMs). Anything else fails with `invalid_placement`, listing the valid values. |
@@ -164,6 +170,68 @@ JSON: the registered Space, `phase: "ready"` and `reused` (true when `reuse` ret
- Local needs a container engine, QEMU or Lume (`cua runtime doctor`).
+### network_show
+
+Show a Space's network: preset, what it opens, where it is enforced, what is always blocked.
+
+Shows a Space's network: its preset (`internet` by default: the internet and its own tree, with this computer, the local network, cloud metadata and other trees blocked), what it opens beyond that, where the rules are enforced (outside the guest), or why it has no network (a runtime that can't protect it yet starts it without network), and what is always blocked. When a connection fails, check here before retrying: a blocked destination stays blocked.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:network_show`, in `spaces:readonly`; read-only, idempotent |
+| Swift SDK | `Spaces.network(space)` |
+| Rust | `Spaces::network_info` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `space` | `string` | required | Space id or name. |
+
+#### Result
+
+JSON: `settings` (preset, lists), `summary`, `widenings` (what it opens beyond internet), `enforcement` (`enforced`, `no_network`, `open`, `refused`), `point`, `note`, `parent`, `root`, `always_blocked`, `notice_pending`.
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox)
+
+### network_set
+
+Tighten a Space's network: internet, none or custom lists. Opening more is the user's to do.
+
+Changes a Space's network to `internet`, `none`, or `custom` (from internet) / `custom:none` with `allow` and `deny` (addresses or CIDRs). It can only tighten: anything that opens more than the Space has now (this computer's localhost, the local network, No protection, an allow beyond its preset) is refused; the user does that with `cua network set` or the app. A child stays within its parent's. tree=true gives its children the same settings. Applies at once where the runtime can, else at the Space's next start (`applied`).
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:network_set`; mutating, idempotent |
+| Swift SDK | `Spaces.set_network(space, settings, widen, tree)` |
+| Rust | `Spaces::set_network` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `allow` | `string[]` | none | Destinations to allow (addresses or CIDRs). |
+| `deny` | `string[]` | none | Destinations to block (addresses, CIDRs or `all`). |
+| `network` | `string` | required | `internet`, `none`, or `custom` / `custom:none` with `allow` and `deny`. Opening more than the Space has now is the user's to do (`cua network set`, or the app): refused here. |
+| `space` | `string` | required | Space id or name. |
+| `tree` | `boolean` | none | Its child Spaces take the same settings (each within its parent's). |
+
+#### Result
+
+JSON: `applied` (`now` or `next_start`) and `network` (as network_show).
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`wrong_provider`](/spaces/reference#wrong_provider), [`sandbox`](/spaces/reference#sandbox)
+
### delete_space
Delete a Space's sandbox and forget it.
@@ -295,6 +363,7 @@ Run shell commands and move files in and out of a Space.
| Tool | Description |
| --- | --- |
| [`space_bash`](#space_bash) | Run a shell command inside the Space. |
+| [`space_job`](#space_job) | Run a long command in the Space as a background job: tail its log, cancel it, or get woken when it ends. |
| [`space_write`](#space_write) | Write literal text to a path inside the Space. |
| [`upload`](#upload) | Send a local file or folder into the Space. |
| [`send_file`](#send_file) | Send a host file or folder into the Space's Downloads, verified by sha256 on arrival. |
@@ -331,6 +400,58 @@ Text: stdout, then `[stderr]` and stderr, then `[exit N]`.
[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`timeout`](/spaces/reference#timeout)
+### space_job
+
+Run a long command in the Space as a background job: tail its log, cancel it, or get woken when it ends.
+
+Use this instead of space_bash for anything that takes more than a minute (builds, test suites, installs, waiting on CI). `start` returns a job id at once and the command keeps running when you stop, disconnect, or the Space's daemon restarts. Read it with `logs` (pass the returned `next_offset` as `offset` to read on; `follow_ms` waits for output) or `status`; stop it with `cancel`; `list` shows the Space's jobs. Pass `notify: true` to be woken: the Space's thread gets one message `JOB <id> <state> exit=<n> ...` with the end of the log, and as an agent member you receive it as your next turn, so you can end your turn instead of polling. `until` makes a job that waits for a file, a port, a command or a pull request's required checks; its end is the condition. Output is stdout and stderr together. Linux and macOS guests.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:space_job`; destructive |
+| Swift SDK | `Space.job(_:)` |
+| Rust | `Space::job` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `action` | `string` | required | `start` (begin a job), `status` (state and the end of its log), `logs` (read the log from a byte offset), `cancel` (stop it) or `list` (this Space's jobs, newest first). |
+| `command` | `string` | none | `start`: the command line, run with `/bin/sh -c` in the background. It keeps running when you or your connection go away. Give this or `until`. |
+| `cwd` | `string` | none | `start`: the directory to run in. Default: the Space user's home. |
+| `env` | `map of string` | none | `start`: environment variables for the command. |
+| `follow_ms` | `integer` | `0` | `logs`: when there is nothing new after `offset` and the job is running, wait up to this many milliseconds (at most 25000) for output or for the job to end. Default 0. At least 0. |
+| `job` | `string` | none | `status`, `logs`, `cancel`: the job id `start` returned. |
+| `limit` | `integer` | none | `logs`: most bytes to return (default 16000, at most 262144). At least 0. |
+| `name` | `string` | none | `start`: a short label for the job ("unit tests"), shown in listings and in the message that wakes you. |
+| `notify` | `boolean` | `false` | `start`: wake me when the job ends. The Space's thread gets one message with the job's result and the end of its log, addressed to you when you are an agent member of the Space (so you can finish your turn and sleep), and the person gets a notification. Default false. |
+| `offset` | `integer` | none | `logs`: the byte offset to read from (the `next_offset` of the previous call). Without it: the last `limit` bytes. At least 0. |
+| `space` | `string` | required | Space id or name. |
+| `timeout` | `integer` | none | `start`: seconds before the job is stopped. Default: none. At least 0. |
+| `until` | `object` | none | `start`: wait for a condition instead of running `command`. The job ends when the condition holds (exit 0), or after `timeout`. |
+| `until.command` | `string` | none | Wait for this shell command to exit 0. |
+| `until.file` | `string` | none | Wait for this path to exist in the Space. |
+| `until.host` | `string` | `127.0` | With `port`: the host. Default 127.0.0.1. |
+| `until.interval` | `integer` | `5` | Seconds between checks (1 to 300). Default 5 (30 for `pr_checks`). At least 0. |
+| `until.port` | `integer` | none | Wait for this TCP port to accept connections (on `host`, default 127.0.0.1). 0 to 65535. |
+| `until.pr_checks` | `string` | none | Wait for a GitHub pull request's required checks to finish with `gh` (signed in inside the Space): a number, a URL or `owner/repo#123`. The job exits 0 when they pass and 1 when one fails. |
+| `wake` | `string` | none | `start` with `notify`: the agent member to wake instead of you. |
+
+#### Result
+
+JSON. `start`: `job`, `state`, `log_command` and a `hint`. `status`, `logs`: `job`, `name`, `state` (`running`, `exited`, `cancelled`, `timed_out` or `lost`), `exit_code`, `signal`, `started_at` and `ended_at` (unix seconds), `elapsed_s`, `size` (log bytes), and for `logs` `offset`, `next_offset`, `text` and `more`. `cancel`: the final status. `list`: `jobs`.
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`wrong_provider`](/spaces/reference#wrong_provider)
+
+#### Notes
+
+- A job is a command that outlives the call, the connection and a restart of the Space's daemon; its state is files in the Space (`~/.cua/jobs/<id>`). Guests that are not Windows.
+
### space_write
Write literal text to a path inside the Space.
@@ -696,6 +817,7 @@ Discover and call the MCP services inside a Space.
| --- | --- |
| [`list_tools`](#list_tools) | List the MCP services and tools reachable inside the Space. |
| [`call_tool`](#call_tool) | Call a service tool inside the Space. |
+| [`space_service`](#space_service) | Keep a command running in the Space: restarts, health checks, start on boot, logs. |
### list_tools
@@ -764,6 +886,44 @@ The called tool's own result, unchanged: its content parts (images included), `s
- Open world twice over: the callee is a tool the SDK has never seen.
+### space_service
+
+Keep a command running in the Space: restarts, health checks, start on boot, logs.
+
+Keeps a command running in the Space: cua-spacesd starts it at once, starts it again by its `restart` policy when it ends (waiting longer after each quick failure, up to a minute), restarts it when its health check (`http`, `tcp` or `check`, one of them) fails 3 times in a row, starts it when the Space boots unless start_on_boot is false, and keeps its output in a log file in the Space (`logs`). `stop` keeps it stopped, across a reboot too, until `start`. `add` with a name that exists replaces it.
+
+| | |
+| --- | --- |
+| Providers | all (cloud, local, direct, relay) |
+| Platforms | all (macos, windows, linux) |
+| Metering | free |
+| Approval | permission `spaces:space_service`; destructive |
+| Swift SDK | `space.keepRunning.service(_:)` |
+| Rust | `Space::keep_service` |
+
+#### Parameters
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `action` | `string` | required | `add` (or replace), `list`, `start`, `stop`, `restart`, `remove` or `logs`. |
+| `check` | `string` | none | `add`: health check, a shell command that exits 0 when healthy. |
+| `command` | `string` | none | `add`: the shell command line to keep running. |
+| `http` | `string` | none | `add`: health check, a URL that answers 2xx or 3xx. |
+| `name` | `string` | none | Service name (every action but `list`): lowercase letters, digits, `-`, `_` and `.`. |
+| `restart` | `string` | none | `add`: when to start it again: `always` (default), `on-failure` or `never`. |
+| `space` | `string` | required | Space id or name. |
+| `start_on_boot` | `boolean` | none | `add`: start it when the Space boots (default true). |
+| `tail_bytes` | `integer` | none | `logs`: bytes from the end (default 64 KiB). At least 0. |
+| `tcp` | `string` | none | `add`: health check, `host:port` that accepts a connection. |
+
+#### Result
+
+JSON: `add`, `start`, `stop` and `restart` give the service (`name`, `command`, `state`, `pid`, `restarts`, `last_end`, `probe_error`, `restart`, `start_on_boot`, `log_path`); `list` gives `services`; `logs` gives `logs` (text); `remove` gives `removed`.
+
+#### Errors
+
+[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`capability_missing`](/spaces/reference#capability_missing)
+
## Hotspot
Share this computer's network with a Space.
@@ -865,750 +1025,3 @@ JSON: `{"hotspots": [...]}`, each shaped like hotspot_start's result.
#### Errors
[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`spacesd_not_available`](/spaces/reference#spacesd_not_available), [`capability_missing`](/spaces/reference#capability_missing)
-
-## Sharing
-
-Let other cua.ai accounts watch or edit a Space, through the relay.
-
-| Tool | Description |
-| --- | --- |
-| [`share_space`](#share_space) | Let someone in your team watch or edit a Space. |
-| [`unshare_space`](#unshare_space) | Stop sharing a Space with an account, or with everyone. |
-| [`space_shares`](#space_shares) | List who a Space is shared with. |
-| [`relay_register_space`](#relay_register_space) | Publish a Space on the relay for the account's other devices. |
-| [`relay_unregister_space`](#relay_unregister_space) | Take a Space off the relay. |
-
-### share_space
-
-Let someone in your team watch or edit a Space.
-
-Shares the Space through the cua.ai relay with one person in your own team, by verified email or account id, or with the whole team as `team:<id>` (as a viewer or an editor). Sharing is for teams: an account in no team gets `sharing_needs_team` ("Sharing is for teams. Start a team to share this Space."), and someone outside your team gets `share_outside_team`. The same allowlist and device enrollment `cua host share` uses. A viewer joins presence with their own named cursor and watches a view-only stream: the Space's driver refuses their input, shell, files and MCP. An editor gets full use, and their input is a human session. Sharing again changes the role. A host (`relay:<id>`) is shared directly; any other Space (local, cloud, or added by address) is attached to the relay on its first share: its own driver dials out, so it needs no inbound port. Invitees open `invitee_space`.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:share_space`; mutating, idempotent |
-| Requires (this computer) | `relay_account` |
-| Swift SDK | `space.sharing.share(with:role:)` |
-| Rust | `Spaces::share_space` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `role` | `string` | `viewer` | `viewer` (presence with their own cursor and a view-only stream) or `editor` (full use; their input is a human session). Default `viewer`. |
-| `space` | `string` | required | Space id or name. |
-| `who` | `string` | required | Who: the email address (verified by cua.ai) or account id of someone in your own team, or `team:<id>` for the whole team (as `viewer` or `editor`). Sharing is for teams: it needs a team on the Teams plan, and a whole-team share needs a team owner or admin who owns the Space. |
-
-#### Result
-
-JSON: `space`, `machine` (the relay computer it is shared as; empty when not shared), `invitee_space` (what the people it is shared with open: `relay:<computer>`), `url`, `online` and `shares` (each `who`, `role`: viewer or editor, and `connected`).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`host_capability_missing`](/spaces/reference#host_capability_missing), [`relay`](/spaces/reference#relay), [`permission_denied`](/spaces/reference#permission_denied), [`unauthenticated`](/spaces/reference#unauthenticated)
-
-#### Notes
-
-- Viewers and editors are enforced by the Space's own cua-spacesd, not by the caller; a Space whose driver predates relay_attach reports capability_missing.
-
-### unshare_space
-
-Stop sharing a Space with an account, or with everyone.
-
-Removes one account (or everyone) at once: the relay cuts their open streams and refuses new calls. With no `who`, the Space stops being shared and a Space that is not a host leaves the relay.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:unshare_space`; mutating, idempotent |
-| Requires (this computer) | `relay_account` |
-| Swift SDK | `space.sharing.unshare(_:)` |
-| Rust | `Spaces::unshare_space` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `space` | `string` | required | Space id or name. |
-| `who` | `string` | none | The email or account id to remove. Default: everyone (the Space stops being shared; a Space that is not a host leaves the relay). |
-
-#### Result
-
-JSON: `space`, `machine` (the relay computer it is shared as; empty when not shared), `invitee_space` (what the people it is shared with open: `relay:<computer>`), `url`, `online` and `shares` (each `who`, `role`: viewer or editor, and `connected`).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`host_capability_missing`](/spaces/reference#host_capability_missing), [`relay`](/spaces/reference#relay), [`permission_denied`](/spaces/reference#permission_denied), [`unauthenticated`](/spaces/reference#unauthenticated)
-
-### space_shares
-
-List who a Space is shared with.
-
-Who the Space is shared with, in which role, and who of them is connected through the relay now.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:space_shares`, in `spaces:readonly`; read-only, idempotent |
-| Requires (this computer) | `relay_account` |
-| Swift SDK | `space.sharing.shares()` |
-| Rust | `Spaces::space_shares` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `audit` | `integer` | `0` | Also return this many of the newest owner-side audit lines. Default 0. At least 0. |
-| `space` | `string` | required | Space id or name. |
-
-#### Result
-
-JSON: the shares (see share_space) and, with `audit`, `audit`: the newest owner-side lines (`ts_ms`, `action`: share, unshare, attach or detach, `space`, `detail`).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`host_capability_missing`](/spaces/reference#host_capability_missing), [`relay`](/spaces/reference#relay), [`unauthenticated`](/spaces/reference#unauthenticated)
-
-### relay_register_space
-
-Publish a Space on the relay for the account's other devices.
-
-Publishes the Space as a computer of the signed-in account on the cua.ai relay, the way `cua host setup` publishes this computer: the Space's own driver joins the relay over outbound WSS with a computer token the account registered, so no inbound port is opened. The account's other devices (a phone off this network, the Cua app on another computer) then open `relay_space`; nobody else can until share_space adds them. Idempotent, and it re-attaches a Space that restarted. Needs a driver with relay_attach (a host is already registered).
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:relay_register_space`; mutating, idempotent |
-| Requires (this computer) | `relay_account` |
-| Swift SDK | `spaces.relay.register(_:)` |
-| Rust | `Spaces::relay_register` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `space` | `string` | required | Space id or name. |
-
-#### Result
-
-JSON: `space`, `relay_space` (`relay:<computer>`: how the account's other devices reach it), `machine`, `url` and `online`.
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`host_capability_missing`](/spaces/reference#host_capability_missing), [`relay`](/spaces/reference#relay), [`unauthenticated`](/spaces/reference#unauthenticated)
-
-### relay_unregister_space
-
-Take a Space off the relay.
-
-Takes the Space off the relay: its driver leaves and its computer is removed, with every share. A `relay:<computer>` id removes that computer's record from the relay directory, which only its owner may do: a Space that registered itself (also after it was deleted), or a computer that is no longer connected. A host that is connected now is taken off with `cua host remove` on that computer instead.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:relay_unregister_space`; mutating, idempotent |
-| Requires (this computer) | `relay_account` |
-| Swift SDK | `spaces.relay.unregister(_:)` |
-| Rust | `Spaces::relay_unregister` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `space` | `string` | required | Space id or name. |
-
-#### Result
-
-JSON: `space` and `unregistered` (false when it was not on the relay).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`not_found`](/spaces/reference#not_found), [`ambiguous_sandbox`](/spaces/reference#ambiguous_sandbox), [`host_capability_missing`](/spaces/reference#host_capability_missing), [`relay`](/spaces/reference#relay), [`unauthenticated`](/spaces/reference#unauthenticated), [`permission_denied`](/spaces/reference#permission_denied)
-
-## Your cloud
-
-Create Spaces in your own AWS, Google Cloud, Hetzner or Modal account: connect it, check it, and clean up what Cua created there.
-
-| Tool | Description |
-| --- | --- |
-| [`cloud_status`](#cloud_status) | List your clouds (AWS, Google Cloud, Hetzner, Modal): found credentials, the connected account and region, what each can run at what hourly cost, and what Cua created there. |
-| [`cloud_connect`](#cloud_connect) | Connect a cloud account Spaces can be created in. |
-| [`cloud_test`](#cloud_test) | Check a cloud account without creating anything. |
-| [`cloud_disconnect`](#cloud_disconnect) | Forget a connected cloud account (deleting what Cua created there first, with delete=true). |
-| [`cloud_approve`](#cloud_approve) | Approve (or deny) what an agent asked for on a cloud: its link or its raised limits. For a person only. |
-| [`cloud_sweep`](#cloud_sweep) | Find and delete what Cua left in your clouds. |
-| [`cloud_plan`](#cloud_plan) | Show (or apply) the elastic pool's plan for some Spaces: where they go, which machines it adds, and the cost. |
-| [`cloud_hosts`](#cloud_hosts) | List the hosts the elastic pool added in your clouds. |
-| [`cloud_add_host`](#cloud_add_host) | Add hosts to your pool in a linked cloud. |
-| [`cloud_remove_host`](#cloud_remove_host) | Remove hosts this home added to your pool. |
-| [`cloud_budget`](#cloud_budget) | Read or set the elastic pool's budget and autoscale switch. |
-| [`cloud_reconcile`](#cloud_reconcile) | Run the elastic pool's scale-in pass now. |
-| [`prewarm`](#prewarm) | Keep Spaces of one shape ready where the elastic pool puts them, so the next creates start in a fraction of a second. |
-| [`prewarm_list`](#prewarm_list) | List the prewarms and how many Spaces each keeps ready. |
-| [`prewarm_remove`](#prewarm_remove) | End a prewarm: its ready Spaces go. |
-| [`cloud_audit`](#cloud_audit) | Read the log of what Cua did in your clouds. |
-| [`cloud_cost`](#cloud_cost) | Estimate what Cua's machines in your clouds cost, by Space, agent, day or cloud. |
-
-### cloud_status
-
-List your clouds (AWS, Google Cloud, Hetzner, Modal): found credentials, the connected account and region, what each can run at what hourly cost, and what Cua created there.
-
-Sandboxes and Spaces can run in the user's own cloud account: on="aws" (EC2), "azure" (Azure Virtual Machines), "gcp" (Compute Engine), "hetzner" (Hetzner Cloud) or "modal" (Modal Sandboxes). EC2, Azure, Compute Engine and Hetzner Cloud start one small VM or server per sandbox that runs the image with Docker; Modal runs one Modal sandbox. Hetzner Cloud servers have no /dev/kvm, so Hetzner runs container images only (Windows and other VM images are refused). Either way the guest's cua-spacesd dials out to the cua.ai relay as a computer of the signed-in account (no inbound port), and the Space is that computer, relay:&lt;computer&gt;. AWS and Google Cloud use their own CLI sign-in or, with auth="oidc", no stored key at all (Cua's issuer signs short-lived tokens the account trusts); Azure always links that way; Modal uses its CLI sign-in; Hetzner uses a project API token (Read & Write), and Modal can take its token too: cloud_connect seals it to the account's devices (Cua's servers keep only ciphertext; no tool returns it), or keeps Hetzner's in this device's Cua credential store (auth="cli"). Connect it first with cloud_connect (the user decides; it costs money in their account). Everything Cua creates is tagged cua-managed=true with this cua home's cua-owner and an expiry, recorded under the cua home, deleted with its sandbox, and ends itself at its expiry (a Hetzner server, which cannot delete itself, shuts down and is billed until cloud_sweep or delete_space removes it); cloud_sweep removes leftovers, and the daemon runs that sweep by itself every 15 minutes (CUA_CLOUD_SWEEP_SECS; 0 turns it off). cloud_disconnect refuses while Cua resources still run there unless delete=true; cloud_audit lists what Cua did.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_status`, in `spaces:readonly`; read-only, idempotent |
-| Swift SDK | `spaces.cloud.status(provider:)` |
-| Rust | `cua_cloud::Clouds::status` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `provider` | `string` | none | Only this cloud (`aws`, `azure`, `gcp`, `hetzner`, `modal`). Default: every one. |
-
-#### Result
-
-JSON: `default_on`, `providers` (each `name`, `title`, `tier` (`vm`: a VM that provides Spaces, `sandbox`: one sandbox per Space), `connected`, `default`, `credentials` (`found`, `source`), `account`, `profile`, `region`, `zone`, `project`, `environment`, `label` ("AWS · us-west-2"), `ttl_hours`, `kinds` (each `image`, `kind`, `supported`, `reason`, `machine_type`, `usd_per_hour`), `auth` (`cli`, `oidc` or `sealed` once connected), `status` (`connected`, `waiting-for-approval`, `not-connected`, or `failed` when the link was revoked), `budget_usd_month` and `max_size` when set, `spent_month` (estimated US dollars this calendar month), `running` (machines Cua runs there now), `approval` (`connection` or `limits` while a person's approval is pending, else absent) and, for `sealed`, `holders` (the devices that can open the API token now; at least one must be online for machines to be made there unattended)) and `resources` (what Cua created: `provider`, `id`, `type`, `space`, `region`, `state`, `created`, `expires`, `expired`).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument)
-
-### cloud_connect
-
-Connect a cloud account Spaces can be created in.
-
-Without auth it keeps how the cloud is linked already (an OIDC or sealed link stays so, so a run that only changes budget_usd_month or max_size never falls back to a CLI sign-in); a cloud not linked yet, or auth="cli", runs cloud_test first and connects only when every check passes, storing the profile, region, project or environment names under the cua home (never a key: the cloud's own CLI sign-in stays where it is). auth="oidc" links AWS, Google Cloud or Azure with no stored key (Azure is always oidc; a Google Cloud project_number implies it): it never prompts and is idempotent, so call it again with the same arguments until `status` is `connected`, following `next` each time. It needs budget_usd_month first. Until the account is named it returns needs-trust and the trust step: a page for the person (AWS: the trust stack, then ask for the 12-digit account_id; Google Cloud: Cloud Shell and the trust script, then ask for the project_number it prints; Azure: Deploy to Azure, then ask for the outputs subscription_id, tenant_id and client_id), or, when an agent asks on a machine signed in to gcloud or az, the exact command to run. Once named, the link is recorded on Cua's issuer and check=true proves it (a check token, the exchange with the cloud, a dry run, permission check or validate; nothing is created) and saves it. Hetzner and Modal with a token and budget_usd_month seal the token to the account's devices (auth="sealed", the default on a device with the account's pool keys): it is checked first (nothing is created), Cua's servers keep only ciphertext, any device of the account opens it in memory when it calls the cloud, and no tool ever returns it; on another device, auth="sealed" without a token links the account's sealed token. A link, token or limit raise made by an agent returns waiting-for-approval until a person approves it in Cua Spaces. budget_usd_month and max_size (`4x16`) also apply to CLI links: machines past them are refused before any cloud call. With make_default, create_space without `on` creates there (`default.on`).
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_connect`; mutating, idempotent |
-| Swift SDK | `spaces.cloud.connect(_:makeDefault:ttlHours:)` |
-| Rust | `cua_cloud::Clouds::connect` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `account_id` | `string` | none | AWS `oidc`: the 12-digit account id the trust stack is in (the person who created it knows it). |
-| `agent` | `string` | none | The agent making the change (Cua's agent runtime and the cua CLI set it). An agent's link, or a limit it raises, waits for a person's approval in Cua Spaces. |
-| `auth` | `string` | `sealed` | How Cua reaches the cloud: `cli` (the cloud CLI's sign-in, or for Hetzner a token kept on this device), `oidc` (AWS, Google Cloud, Azure: Cua's issuer signs short-lived tokens the account trusts; no key is stored anywhere; Azure is always `oidc`) or `sealed` (Hetzner, Modal: the API token is sealed to the account's devices and Cua's servers keep only ciphertext; with no `token` it seals the one this device has, or links the account's sealed token). Default: `sealed` for Hetzner and Modal when this device has the account's pool keys and a budget is given (or the link is sealed already), else `cli`. |
-| `budget_usd_month` | `number` | none | The most Cua may spend there per calendar month, US dollars. New machines are refused once it is reached; stopping and deleting always works. Needed before the first machine of an `oidc` link. |
-| `check` | `boolean` | none | `oidc`: run the check that proves the link works (a check token, the exchange with the cloud, a dry run; nothing is created). The link is saved only once it passes. |
-| `client_id` | `string` | none | Azure: the client id of the `cua-spaces` managed identity (its `clientId` output). |
-| `environment` | `string` | none | Modal environment (default: the profile's). |
-| `make_default` | `boolean` | `false` | Also make it the default location (`default.on`). Default false. |
-| `max_size` | `string` | none | The largest machine Cua may create there: `<vCPUs>x<GB>`, for example `4x16`. |
-| `profile` | `string` | none | AWS: the profile in `~/.aws/config` (default: `default`, or `AWS_PROFILE`). Modal: the profile in `~/.modal.toml` (default: the active one). |
-| `project` | `string` | none | GCP project id (default: `gcloud config get project`). Hetzner and Modal with a sealed token: a name for the project or workspace (default `default`), to tell several apart. |
-| `project_number` | `string` | none | Google Cloud `oidc`: the project number (the trust script prints it; giving it implies `oidc`). The project id is `target.project`. |
-| `provider` | `string` | required | `aws`, `azure`, `gcp`, `hetzner` or `modal`. |
-| `region` | `string` | none | AWS region (default: the profile's, else `us-west-2`), Hetzner location (default `fsn1`), GCP region (default `us-central1`) or Azure region (default `westus2`). |
-| `resource_group` | `string` | none | Azure: the resource group Cua works in, and the only one its roles reach (default `cua-spaces`). |
-| `role_arn` | `string` | none | AWS `oidc`: the role ARN, only when it is not named `cua-spaces`. |
-| `service_account` | `string` | none | Google Cloud `oidc`: a service account to act as. Default: none, the federated identity calls Google directly. |
-| `subscription_id` | `string` | none | Azure: the subscription id (the trust template's `subscriptionId` output). |
-| `tenant_id` | `string` | none | Azure: the Microsoft Entra tenant id (its `tenantId` output). |
-| `token` | `string` | none | Hetzner: the project's Read & Write API token (default: `HCLOUD_TOKEN`, the saved token, or the `hcloud` CLI's context). Modal: `<token id>:<token secret>`. Secret: never logged or returned; sealed to the account's devices on connect (or, Hetzner with `auth: cli`, saved in this device's Cua credential store). |
-| `ttl_hours` | `integer` | `8` | Every Space created there deletes itself after this many hours (the instance or sandbox terminates, the sweeper removes what is left). Default 8; 0 keeps Spaces until you delete them (Modal caps a sandbox at 24). At least 0. |
-| `zone` | `string` | none | GCP zone in the region (default: its `-a` zone). |
-
-#### Result
-
-JSON: the cloud as `cloud_status` lists it, whose `status` is the outcome (`connected`, `needs-trust`, `checking`, `waiting-for-approval` or `failed`), plus `checks` (each `name`, `ok`, `detail`), `next` (absent when connected; `run`: the exact command for the agent, or `open`: a page for a person, with `paste` when there is a command to paste there, and `why`) and `verify` (the command that confirms it).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
-
-### cloud_test
-
-Check a cloud account without creating anything.
-
-Creates nothing: it signs in with the cloud's own CLI credentials (or, for a link without a stored key, a token from Cua's issuer exchanged with the cloud), asks the cloud to validate a create without doing it (AWS DryRun, Google Cloud permission checks, an Azure deployment validate), and reads quotas. A failed check says what to fix.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_test`, in `spaces:readonly`; read-only, idempotent |
-| Swift SDK | `spaces.cloud.test(_:)` |
-| Rust | `cua_cloud::Clouds::test` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `environment` | `string` | none | Modal environment (default: the profile's). |
-| `profile` | `string` | none | AWS: the profile in `~/.aws/config` (default: `default`, or `AWS_PROFILE`). Modal: the profile in `~/.modal.toml` (default: the active one). |
-| `project` | `string` | none | GCP project id (default: `gcloud config get project`). Hetzner and Modal with a sealed token: a name for the project or workspace (default `default`), to tell several apart. |
-| `provider` | `string` | required | `aws`, `azure`, `gcp`, `hetzner` or `modal`. |
-| `region` | `string` | none | AWS region (default: the profile's, else `us-west-2`), Hetzner location (default `fsn1`), GCP region (default `us-central1`) or Azure region (default `westus2`). |
-| `token` | `string` | none | Hetzner: the project's Read & Write API token (default: `HCLOUD_TOKEN`, the saved token, or the `hcloud` CLI's context). Modal: `<token id>:<token secret>`. Secret: never logged or returned; sealed to the account's devices on connect (or, Hetzner with `auth: cli`, saved in this device's Cua credential store). |
-| `zone` | `string` | none | GCP zone in the region (default: its `-a` zone). |
-
-#### Result
-
-JSON: `provider`, `ok`, `account` (the account, project or workspace the credentials reach) and `checks` (each `name`, `ok`, `detail`: credentials, permissions by dry run, quota, the region and machine types).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
-
-### cloud_disconnect
-
-Forget a connected cloud account (deleting what Cua created there first, with delete=true).
-
-Refuses (a `cloud` error listing them) while Cua-created instances or sandboxes still run in that cloud, because a disconnected cloud is no longer swept and they would bill unseen. With delete=true it first deletes everything Cua created there (the same tag and record checks as cloud_sweep with all=true), then asks the cloud again and forgets the connection (and `default.on` when it named this cloud) only when nothing is left; if something remains it keeps the connection and says what. Nothing that Cua did not create is ever touched.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_disconnect`; destructive |
-| Swift SDK | `spaces.cloud.disconnect(_:delete:)` |
-| Rust | `cua_cloud::Clouds::disconnect` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `delete` | `boolean` | `false` | Delete everything Cua created in that cloud first, and disconnect only once the cloud confirms nothing is left. Default false: the call is refused (listing them) while Cua resources still run there. |
-| `provider` | `string` | required | `aws`, `azure`, `gcp`, `hetzner` or `modal`. |
-
-#### Result
-
-JSON: `provider`, `disconnected`, `deleted` (with delete=true: the receipt, each resource deleted first) and `left` (resources Cua still records there).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
-
-### cloud_approve
-
-Approve (or deny) what an agent asked for on a cloud: its link or its raised limits. For a person only.
-
-Only for a person, never for an agent: no MCP server lists or runs it, the daemon refuses it when it runs for an agent, and Cua's issuer refuses an agent's proof. It approves what an agent asked for on that cloud (its link, or a raise of its budget or largest machine; see `approval`, `approval_agent`, `pending_budget_usd_month` and `pending_max_size` in cloud_status), or with deny=true declines it: a raise is dropped and the limits in force stay; a link never approved is disconnected.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_approve`; destructive |
-| Swift SDK | `spaces.cloud.approve(_:deny:)` |
-| Rust | `cua_cloud::Clouds::approve` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `deny` | `boolean` | `false` | Decline instead: an agent's raise is dropped (the limits in force stay), an agent's link that was never approved is disconnected. Default false. |
-| `provider` | `string` | required | `aws`, `gcp`, `hetzner` or `modal`. |
-
-#### Result
-
-JSON: the cloud as `cloud_status` lists it once approved or denied (`status`, `approval` empty, the limits in force).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
-
-### cloud_sweep
-
-Find and delete what Cua left in your clouds.
-
-Acts only on resources that carry Cua's tags (cua-managed=true and this device's cua-owner) and that this cua home recorded, or that carry this device's owner id: never on anything else in the account. Default dry_run=true lists what it would delete: expired Spaces (past their ttl), resources whose Space is gone, and with all=true every Cua resource there.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_sweep`; destructive |
-| Swift SDK | `spaces.cloud.sweep(provider:dryRun:all:)` |
-| Rust | `cua_cloud::Clouds::sweep` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `all` | `boolean` | `false` | Also delete Cua resources that have not expired yet (every Space in that cloud). Default false: only expired ones, and resources no Space refers to any more. |
-| `dry_run` | `boolean` | `true` | List what would be deleted without deleting it. Default true. |
-| `provider` | `string` | none | Only this cloud. Default: every connected one. |
-
-#### Result
-
-JSON: `dry_run` and `resources`, each `provider`, `id`, `type`, `space`, `expires`, `action` (`delete`, `deleted`, `keep` or `failed`) and `reason`.
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
-
-### cloud_plan
-
-Show (or apply) the elastic pool's plan for some Spaces: where they go, which machines it adds, and the cost.
-
-The elastic pool places Spaces with on="auto" (or on a linked cloud) by one solve: the user's devices first (free), then cloud hosts already running, then new cloud hosts (provider x type x region) at the least cost that fits the image's needs (kind, KVM, arch, size learned from earlier Spaces), the start-time goal, the relay's machine limit and the budget (cloud_budget). Idle cloud hosts go at the end of their paid time. cloud_plan shows the decision without doing it; pins (provider, region, instance_type, hosts, no_scale, devices_only, max_usd_per_hour) are constraints of the same solve, so an agent can inspect, adjust and apply.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_plan`; destructive |
-| Swift SDK | `spaces.cloud.plan(_:)` |
-| Rust | `Spaces::elastic_plan` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `apply` | `boolean` | `false` | Add the machines the plan needs (they join the pool; create the Spaces with on="auto"). Default false: plan only. |
-| `caller` | `string` | none | Who asks: `interactive` (one Space someone waits on), `batch`, `compat` or `persistent_agent`. Default: interactive for one Space, batch for more. |
-| `count` | `integer` | `1` | How many Spaces. Default 1. At least 0. |
-| `cpus` | `integer` | none | vCPUs each. Default: what Spaces of this image used before, else the image's size. At least 0. |
-| `devices_only` | `boolean` | none | Only the user's own devices. |
-| `duration_secs` | `integer` | none | Expected lifetime, seconds. At least 0. |
-| `hosts` | `integer` | none | Exactly this many new machines. At least 0. |
-| `image` | `string` | none | Image (`linux`, `windows`, an OCI reference). Default: linux. |
-| `instance_type` | `string` | none | Only this machine type. |
-| `kind` | `string` | none | `container`, `vm` or `microvm`. Default: from the image. |
-| `max_usd_per_hour` | `number` | none | A $/hour cap for this plan (default: the budget's). |
-| `memory_mb` | `integer` | none | Memory each, MiB. At least 0. |
-| `no_scale` | `boolean` | none | Add no machines (place on what runs). |
-| `provider` | `string` | none | Only this cloud. |
-| `region` | `string` | none | Only this region. |
-| `together` | `boolean` | none | Keep them on one machine (forks of one checkpoint). |
-
-#### Result
-
-JSON: `plan` (`assignments`: `group`, `target` (`on`: `host` with `name`, or `new` with `index`), `count`; `new_hosts`: `provider`, `type_name`, `region`, `usd_per_hour`, `boot_secs`, `billed_secs`; `unplaced` with `reason`; `added_usd_per_hour`, `projected_usd`, `lower_bound_usd`, `solver`, `ready_in_secs`, `explain`), `groups` (the demand it detected) and `pool` (`hosts`, `cloud`, `offers`, `constraints`, `month_usd`); with apply, `added` (the hosts added).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud), [`limit_exceeded`](/spaces/reference#limit_exceeded)
-
-### cloud_hosts
-
-List the hosts the elastic pool added in your clouds.
-
-The hosts the elastic pool (or cloud_add_host) added in the user's linked clouds: machines that provide Spaces to the pool, with their live cost.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_hosts`, in `spaces:readonly`; read-only, idempotent |
-| Swift SDK | `spaces.cloud.hosts()` |
-| Rust | `cua_cloud::Clouds::hosts` |
-
-#### Parameters
-
-No parameters.
-
-#### Result
-
-JSON array: each host `name`, `provider`, `type_name`, `region`, `id`, `machine`, `state` (`creating`, `booting`, `joined`, `cordoned`, `offline`, `gone`), `started`, `expires`, `usd_per_hour`, `billing_step_secs`, `billing_min_secs`, `pinned`.
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
-
-### cloud_add_host
-
-Add hosts to your pool in a linked cloud.
-
-Adds hosts by hand (pinned: the scaler never removes them); it costs money in the user's account. Each host is tagged and recorded first, installs cua, joins the pool and ends at its TTL. cloud_remove_host removes it.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_add_host`; destructive |
-| Swift SDK | `spaces.cloud.addHost(_:)` |
-| Rust | `cua_cloud::Clouds::add_host` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `count` | `integer` | `1` | How many, 1 to 10. Default 1. At least 0. |
-| `instance_type` | `string` | required | Machine type (`cloud_plan` and `cloud_status` list them). |
-| `provider` | `string` | required | `aws`, `azure`, `gcp` or `hetzner`. |
-| `region` | `string` | none | Region. Default: the connection's. |
-| `ttl_hours` | `integer` | `24` | Hours until each ends on its own, 1 to 168. Default 24. At least 0. |
-
-#### Result
-
-JSON array: the hosts added (see cloud_hosts).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
-
-### cloud_remove_host
-
-Remove hosts this home added to your pool.
-
-Deletes the hosts' machines (only ones this cua home added and tagged) and their relay entries. The Spaces on them end.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_remove_host`; destructive |
-| Swift SDK | `spaces.cloud.removeHost(_:)` |
-| Rust | `cua_cloud::Clouds::remove_host` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `names` | `string[]` | required | Their names (`hetzner-1`). |
-
-#### Result
-
-JSON: `removed` (names) and `failed` (each `name`, `error`).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud), [`not_found`](/spaces/reference#not_found)
-
-### cloud_budget
-
-Read or set the elastic pool's budget and autoscale switch.
-
-The caps the elastic pool keeps to: it never adds a machine that would take the clouds' cost over max_usd_per_hour or this month's spend over monthly_usd, and with autoscale false it adds none. Fields given are set; the rest stay.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_budget`; mutating, idempotent |
-| Swift SDK | `spaces.cloud.budget(_:)` |
-| Rust | `Spaces::set_elastic_policy` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `allow_metal` | `boolean` | none | Let one small VM Space buy a KVM metal host (dollars an hour). Off: such a request is refused with the reason; batches of forks may still buy one. |
-| `autoscale` | `boolean` | none | Add and remove cloud hosts by itself. |
-| `max_new_hosts` | `integer` | none | Most hosts one placement adds. At least 0. |
-| `max_usd_per_hour` | `number` | none | Most USD per hour your clouds may cost at once. |
-| `monthly_usd` | `number` | none | Most USD per calendar month on elastic hosts. |
-| `warm` | `boolean` | none | Keep an idle host warm when demand predicts a Space soon. |
-
-#### Result
-
-JSON: `policy` (`autoscale`, `max_usd_per_hour`, `monthly_usd`, `max_new_hosts`, `warm`, `interactive_slo_secs`, `routed`, `allow_metal`), `month_usd` (spent this month on elastic hosts), `running_usd_per_hour` and `hosts` (how many run).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument)
-
-### cloud_reconcile
-
-Run the elastic pool's scale-in pass now.
-
-One scale-in pass now (the daemon runs one every 30 s): idle hosts go at the end of the time already paid, the least-used one is cordoned when the others have room.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_reconcile`; destructive |
-| Swift SDK | `spaces.cloud.reconcile()` |
-| Rust | `Spaces::elastic_reconcile` |
-
-#### Parameters
-
-No parameters.
-
-#### Result
-
-JSON array: each `host` and `action` (`action`: `keep` with `until` and `reason`, `cordon` with `reason`, or `remove` with `reason` and `saves_usd`).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
-
-### prewarm
-
-Keep Spaces of one shape ready where the elastic pool puts them, so the next creates start in a fraction of a second.
-
-A prewarm keeps count Spaces of one shape (image, kind, cpus, memory_mb) ready on the machines the elastic pool picks (the same solve as on="auto": devices first, then hosts with room, then new cloud machines, under the budget and pins). Any later create of that shape on those machines claims one in a fraction of a second, through every surface, with no extra argument; the pool keeps count ready until ttl_secs. A prewarm the budget, quotas or pins cannot fit is refused and buys nothing. End it with prewarm_remove when the burst is over.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:prewarm`; destructive |
-| Swift SDK | `spaces.prewarm(_:)` |
-| Rust | `Spaces::prewarm` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `count` | `integer` | `1` | How many to keep ready, 1 to 256. Default 1. At least 0. |
-| `cpus` | `integer` | none | vCPUs each. Default: the size Spaces of this image use. At least 0. |
-| `image` | `string` | required | Image (`linux`, an OCI reference). |
-| `instance_type` | `string` | none | Only this cloud machine type. |
-| `kind` | `string` | none | `container`, `vm` or `microvm`. Default: the image's. |
-| `memory_mb` | `integer` | none | Memory each, MiB. At least 0. |
-| `on` | `string` | none | Where: `auto` (default: your devices first, then hosts with room, then new cloud machines), `local`, a linked cloud or `host:<machine>`. |
-| `region` | `string` | none | Only this cloud region. |
-| `ttl_secs` | `integer` | none | Seconds to keep them (default 3600, at most 604800). At least 0. |
-
-#### Result
-
-JSON: `id`, `image`, `kind`, `cpus`, `memory_mb`, `count`, `ready`, `placements` (`host`, `machine`, `count`, `ready`), `expires_at` (unix seconds) and `new_hosts` (hosts added for it).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`limit_exceeded`](/spaces/reference#limit_exceeded), [`cloud`](/spaces/reference#cloud)
-
-### prewarm_list
-
-List the prewarms and how many Spaces each keeps ready.
-
-A prewarm keeps count Spaces of one shape (image, kind, cpus, memory_mb) ready on the machines the elastic pool picks (the same solve as on="auto": devices first, then hosts with room, then new cloud machines, under the budget and pins). Any later create of that shape on those machines claims one in a fraction of a second, through every surface, with no extra argument; the pool keeps count ready until ttl_secs. A prewarm the budget, quotas or pins cannot fit is refused and buys nothing. End it with prewarm_remove when the burst is over.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:prewarm_list`, in `spaces:readonly`; read-only, idempotent |
-| Swift SDK | `spaces.prewarms()` |
-| Rust | `Spaces::prewarms` |
-
-#### Parameters
-
-No parameters.
-
-#### Result
-
-JSON array of prewarms, as `prewarm` returns them, with `ready` counted now.
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
-
-### prewarm_remove
-
-End a prewarm: its ready Spaces go.
-
-A prewarm keeps count Spaces of one shape (image, kind, cpus, memory_mb) ready on the machines the elastic pool picks (the same solve as on="auto": devices first, then hosts with room, then new cloud machines, under the budget and pins). Any later create of that shape on those machines claims one in a fraction of a second, through every surface, with no extra argument; the pool keeps count ready until ttl_secs. A prewarm the budget, quotas or pins cannot fit is refused and buys nothing. End it with prewarm_remove when the burst is over.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:prewarm_remove`; mutating, idempotent |
-| Swift SDK | `spaces.removePrewarm(_:)` |
-| Rust | `Spaces::remove_prewarm` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `id` | `string` | required | The prewarm (`pw-xxxxxx`). |
-
-#### Result
-
-JSON: `removed` (false when there was no such prewarm).
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument), [`cloud`](/spaces/reference#cloud)
-
-### cloud_audit
-
-Read the log of what Cua did in your clouds.
-
-Reads the append-only audit log under the cua home (cloud/audit.jsonl, rotated at 5 MB): every connect, disconnect, resource recorded before its create, created, confirmed and deleted (by you, by a sweep, by the automatic sweep, by disconnect with delete), and each budget alert (`budget_alert`). These entries have `source` `device`. For clouds linked to the account (OIDC or a sealed token) it adds what Cua's issuer recorded, with `source` `account`: tokens issued or refused, links made, approved, changed and revoked. It never holds a secret or a token. provider narrows it to one cloud. Default limit 50.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_audit`, in `spaces:readonly`; read-only, idempotent |
-| Swift SDK | `spaces.cloud.audit(limit:)` |
-| Rust | `cua_cloud::Clouds::audit` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `limit` | `integer` | none | How many of the newest entries (default 50, at most 1000). At least 0. |
-| `provider` | `string` | none | Only this cloud (`aws`, `gcp`, `hetzner`, `modal`). Default: every one. |
-
-#### Result
-
-JSON array, oldest first, newest last: each `ts` (RFC 3339), `action` (`connect`, `disconnect`, `resource_recorded`, `resource_created`, `resource_confirmed`, `resource_deleted`), `provider`, `kind`, `id`, `space`, `actor` (`user`, `sweep`, `auto-sweep`, `disconnect`, `rollback`), `outcome` (`ok`, `failed`, `refused`) and `detail`.
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument)
-
-### cloud_cost
-
-Estimate what Cua's machines in your clouds cost, by Space, agent, day or cloud.
-
-Estimates what the machines Cua created cost: each one's list price times how long it ran inside the window, from the machines still recorded and the usage log of the ones gone (cloud/usage.jsonl under the cua home). by=`space`, `agent` (who started it: an agent's name, `user`, or `unknown` for machines recorded before that was kept), `day` (UTC) or `cloud`. since defaults to the first of this month. It is an estimate: the cloud's own bill is the final word. Pool hosts count under `pool hosts`.
-
-| | |
-| --- | --- |
-| Providers | all (cloud, local, direct, relay) |
-| Platforms | all (macos, windows, linux) |
-| Metering | free |
-| Approval | permission `spaces:cloud_cost`, in `spaces:readonly`; read-only, idempotent |
-| Swift SDK | `spaces.cloud.cost(by:since:provider:)` |
-| Rust | `cua_cloud::Clouds::cost` |
-
-#### Parameters
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `by` | `string` | `space` | One row per `space`, `agent`, `day` (UTC) or `cloud`. Default `space`. |
-| `provider` | `string` | none | Only this cloud (`aws`, `gcp`, `hetzner`, `modal`). Default: every one. |
-| `since` | `string` | none | The first day counted, `YYYY-MM-DD` (UTC). Default: the first of this month. |
-
-#### Result
-
-JSON: `by`, `since` (`YYYY-MM-DD`), `until` (RFC 3339), `rows` (each `key`: the Space, agent, day or cloud; `usd`: estimated US dollars; `hours`: machine hours; `machines`: how many ran), by day oldest first, otherwise costliest first, and `total_usd`.
-
-#### Errors
-
-[`invalid_argument`](/spaces/reference#invalid_argument)
diff --git a/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock
index 8719bcc450..696fa77e3b 100644
--- a/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock
+++ b/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock
@@ -1840,6 +1840,7 @@ dependencies = [
"cua-spacesd-client",
"cua-vmm",
"futures-util",
+ "hmac 0.12.1",
"http",
"http-body-util",
"humantime",
diff --git a/examples/streaming/rust/Cargo.lock b/examples/streaming/rust/Cargo.lock
index 84734c8a3b..5527e20059 100644
--- a/examples/streaming/rust/Cargo.lock
+++ b/examples/streaming/rust/Cargo.lock
@@ -1475,6 +1475,7 @@ dependencies = [
"cua-spacesd-client",
"cua-vmm",
"futures-util",
+ "hmac 0.12.1",
"http",
"http-body-util",
"humantime",
diff --git a/libs/cua-spacesd/crates/cua-spacesd-doctor/src/checks/mcp.rs b/libs/cua-spacesd/crates/cua-spacesd-doctor/src/checks/mcp.rs
index e2ae303915..b6bc6e17a2 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-doctor/src/checks/mcp.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-doctor/src/checks/mcp.rs
@@ -142,11 +142,16 @@ pub async fn run(ctx: &Ctx, rec: &mut Recorder<'_>) {
)
}
};
+ // The child-Space tools are the MCP server's alone (they call the
+ // Space's spawn channel); DriverService does not list them.
let mcp: BTreeSet<String> = listed["result"]["tools"]
.as_array()
.map(|a| {
a.iter()
.filter_map(|t| t["name"].as_str().map(str::to_owned))
+ .filter(|n| {
+ !cua_spacesd_server::services::spawn_tools::TOOLS.contains(&n.as_str())
+ })
.collect()
})
.unwrap_or_default();
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/README.md b/libs/cua-spacesd/crates/cua-spacesd-server/README.md
index db072337a2..5fb2eb7583 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/README.md
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/README.md
@@ -12,6 +12,7 @@ The gRPC, gRPC-Web and HTTP server core of `cua-spacesd`. One TCP port
| `POST /mcp` | root token (either header) | streamable-HTTP MCP over the cua-driver registry (`cua_driver_core::server` dispatch) |
| `GET /tunnel` (WebSocket) | `tunnel` ticket | from `TunnelService.Forward` |
| `GET /hotspot` (WebSocket) | `hotspot` ticket | from `TunnelService.StartHotspot` |
+| `GET /spawn` (WebSocket) | `spawn` ticket | from `TunnelService.StartSpawn` (the host that runs the Space only) |
| `/media` | provider | 501 until a desktop provider serves it |
Services implemented here: System, Process, Filesystem, Driver, Teleport,
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/auth.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/auth.rs
index 8e3293eb9a..de62f5b788 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/auth.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/auth.rs
@@ -53,6 +53,8 @@ pub enum TicketScope {
Hotspot,
/// The Cua Volume mount's client socket (`/volume`).
Volume,
+ /// The host's end of the spawn channel (`/spawn`).
+ Spawn,
/// File transfer side channels.
Files,
/// The web viewer's scoped bearer (`SystemService.CreateViewerTicket`).
@@ -67,6 +69,7 @@ impl TicketScope {
Self::Tunnel => "tunnel",
Self::Hotspot => "hotspot",
Self::Volume => "volume",
+ Self::Spawn => "spawn",
Self::Files => "files",
Self::Viewer => "viewer",
}
@@ -78,6 +81,7 @@ impl TicketScope {
"tunnel" => Self::Tunnel,
"hotspot" => Self::Hotspot,
"volume" => Self::Volume,
+ "spawn" => Self::Spawn,
"files" => Self::Files,
"viewer" => Self::Viewer,
_ => return None,
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs
index 416cfa452d..c493c11620 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs
@@ -49,6 +49,9 @@ pub struct InitState {
/// Environment set by the hotspot (`set_system_proxy`), layered below
/// `env`.
pub proxy_env: BTreeMap<String, String>,
+ /// Environment the spawn channel adds to every new process
+ /// (`CUA_SPACE`, `CUA_SPAWN`, `CUA_SPAWN_TOKEN_FILE`); `Init` keeps it.
+ pub spawn_env: BTreeMap<String, String>,
}
struct Inner {
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/process/mod.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/process/mod.rs
index 151de7d7d2..ebacde6c56 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/process/mod.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/process/mod.rs
@@ -8,6 +8,7 @@
mod conpty;
pub mod ledger;
pub mod ring;
+pub mod services;
pub mod spawn;
use std::collections::{BTreeMap, HashMap};
@@ -101,6 +102,39 @@ pub struct ProcessEntry {
}
impl ProcessEntry {
+ /// The process id.
+ pub fn pid(&self) -> u32 {
+ self.pid
+ }
+
+ /// Its output ring.
+ pub fn output(&self) -> &Arc<Output> {
+ &self.output
+ }
+
+ /// Waits until it has ended, and how.
+ pub async fn ended(&self) -> ProcessEnd {
+ let mut progress = self.output.subscribe();
+ loop {
+ if let Some(end) = self.end_event() {
+ return end;
+ }
+ if progress.borrow().closed {
+ // The ring closes just before the end is recorded.
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ continue;
+ }
+ if progress.changed().await.is_err() {
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ }
+ }
+
+ /// Sends `signal` to the process group (see `SignalProcess`).
+ pub fn signal_group(&self, signal: Signal) -> Result<(), Status> {
+ self.send_signal(signal, true)
+ }
+
fn running(&self) -> bool {
self.end.lock().expect("end lock").is_none()
}
@@ -520,7 +554,12 @@ impl ProcessManager {
env.insert("LOGNAME".into(), user.name.clone());
env.insert("SHELL".into(), user.shell.clone());
}
- for (key, value) in init.proxy_env.iter().chain(init.env.iter()) {
+ for (key, value) in init
+ .proxy_env
+ .iter()
+ .chain(init.spawn_env.iter())
+ .chain(init.env.iter())
+ {
if value.is_empty() {
env.remove(key);
} else {
@@ -868,6 +907,17 @@ impl ProcessManager {
.map_err(|e| crate::error::internal(format!("exec ledger: {e}")))
}
+ /// Running processes whose tag is exactly `tag`.
+ pub fn running_with_tag(&self, tag: &str) -> Vec<Arc<ProcessEntry>> {
+ self.entries
+ .lock()
+ .expect("entries lock")
+ .iter()
+ .filter(|e| e.tag == tag && e.running())
+ .cloned()
+ .collect()
+ }
+
/// Lists processes, newest first.
pub fn list(&self, include_exited: bool, tag_prefix: &str) -> Vec<ProcessInfo> {
let entries = self.entries.lock().expect("registry lock");
@@ -1216,12 +1266,28 @@ async fn apply_input(
#[derive(Clone)]
pub struct ProcessServiceImpl {
manager: Arc<ProcessManager>,
+ services: Option<Arc<services::ServiceManager>>,
}
impl ProcessServiceImpl {
/// Creates the service over a manager.
pub fn new(manager: Arc<ProcessManager>) -> Self {
- Self { manager }
+ Self {
+ manager,
+ services: None,
+ }
+ }
+
+ /// Serves `PutService` and the other service calls from `services`.
+ pub fn with_services(mut self, services: Arc<services::ServiceManager>) -> Self {
+ self.services = Some(services);
+ self
+ }
+
+ fn services(&self) -> Result<&Arc<services::ServiceManager>, Status> {
+ self.services.as_ref().ok_or_else(|| {
+ crate::error::unsupported(services::FEATURE, "services are not kept by this server")
+ })
}
/// Tonic server with the driver's message limits.
@@ -1459,6 +1525,62 @@ impl ProcessService for ProcessServiceImpl {
killed,
}))
}
+
+ async fn put_service(
+ &self,
+ request: Request<cua_proto::env::v1::PutServiceRequest>,
+ ) -> Result<Response<cua_proto::env::v1::PutServiceResponse>, Status> {
+ let spec = request
+ .into_inner()
+ .spec
+ .ok_or_else(|| crate::error::invalid("spec is required"))?;
+ let service = self.services()?.put(spec).await?;
+ Ok(Response::new(cua_proto::env::v1::PutServiceResponse {
+ service: Some(service),
+ }))
+ }
+
+ async fn delete_service(
+ &self,
+ request: Request<cua_proto::env::v1::DeleteServiceRequest>,
+ ) -> Result<Response<cua_proto::env::v1::DeleteServiceResponse>, Status> {
+ self.services()?.delete(&request.into_inner().name).await?;
+ Ok(Response::new(cua_proto::env::v1::DeleteServiceResponse {}))
+ }
+
+ async fn list_services(
+ &self,
+ _request: Request<cua_proto::env::v1::ListServicesRequest>,
+ ) -> Result<Response<cua_proto::env::v1::ListServicesResponse>, Status> {
+ Ok(Response::new(cua_proto::env::v1::ListServicesResponse {
+ services: self.services()?.list(),
+ }))
+ }
+
+ async fn control_service(
+ &self,
+ request: Request<cua_proto::env::v1::ControlServiceRequest>,
+ ) -> Result<Response<cua_proto::env::v1::ControlServiceResponse>, Status> {
+ let r = request.into_inner();
+ let action = cua_proto::env::v1::ServiceAction::try_from(r.action)
+ .unwrap_or(cua_proto::env::v1::ServiceAction::Unspecified);
+ let service = self.services()?.control(&r.name, action).await?;
+ Ok(Response::new(cua_proto::env::v1::ControlServiceResponse {
+ service: Some(service),
+ }))
+ }
+
+ async fn get_service_logs(
+ &self,
+ request: Request<cua_proto::env::v1::GetServiceLogsRequest>,
+ ) -> Result<Response<cua_proto::env::v1::GetServiceLogsResponse>, Status> {
+ let r = request.into_inner();
+ let (data, truncated) = self.services()?.logs(&r.name, r.tail_bytes)?;
+ Ok(Response::new(cua_proto::env::v1::GetServiceLogsResponse {
+ data,
+ truncated,
+ }))
+ }
}
#[cfg(test)]
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/process/services.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/process/services.rs
new file mode 100644
index 0000000000..7efd9095e3
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/process/services.rs
@@ -0,0 +1,759 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Services: commands this guest keeps running (`ProcessService.PutService`).
+//!
+//! Each service is a managed process (tag `svc:<name>`) watched by a
+//! supervisor task: when it ends it is started again by its restart policy
+//! after a backoff that doubles on quick failures; a health probe that fails
+//! `failure_threshold` times in a row ends it, so the policy restarts it.
+//! Definitions are kept in `<data_dir>/services/<name>.json`, so cua-spacesd
+//! starts them again when it starts (after the guest boots) unless
+//! `start_on_boot` is false or a caller stopped them. Output goes to
+//! `<data_dir>/services/<name>.log`, rotated at `log_max_bytes` with one
+//! older file (`<name>.log.1`) kept.
+
+use std::collections::BTreeMap;
+use std::io::Write as _;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant, SystemTime};
+
+use cua_proto::env::v1::{
+ HealthProbe, ProcessConfig, ProcessEnd, RestartPolicy, ServiceAction, ServiceSpec,
+ ServiceState, ServiceStatus, Signal, StartProcessRequest,
+};
+use serde::{Deserialize, Serialize};
+use tokio::sync::Notify;
+use tokio_util::sync::CancellationToken;
+use tonic::Status;
+
+use super::{ProcessManager, Started};
+use crate::util::{duration, timestamp};
+
+/// Tag prefix of a service's processes.
+pub const TAG_PREFIX: &str = "svc:";
+/// Capability feature.
+pub const FEATURE: &str = "process.services";
+
+const DEFAULT_BACKOFF_MIN: Duration = Duration::from_secs(1);
+const DEFAULT_BACKOFF_MAX: Duration = Duration::from_secs(60);
+/// A run this long resets the backoff.
+const STABLE_AFTER: Duration = Duration::from_secs(60);
+const DEFAULT_PROBE_INTERVAL: Duration = Duration::from_secs(10);
+const DEFAULT_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
+const DEFAULT_PROBE_GRACE: Duration = Duration::from_secs(10);
+const DEFAULT_FAILURE_THRESHOLD: u32 = 3;
+const DEFAULT_LOG_MAX: u64 = 10 * 1024 * 1024;
+const DEFAULT_TAIL: u64 = 64 * 1024;
+const MAX_TAIL: u64 = 4 * 1024 * 1024;
+/// How long a stopped process gets after SIGTERM before SIGKILL.
+const STOP_GRACE: Duration = Duration::from_secs(10);
+/// Most services one guest keeps.
+pub const MAX_SERVICES: usize = 64;
+
+/// What is kept on disk for one service.
+#[derive(Serialize, Deserialize)]
+struct Record {
+ /// The spec, as protobuf JSON-free bytes (prost) in base64.
+ spec: String,
+ /// A caller stopped it: not started on boot until started again.
+ #[serde(default)]
+ stopped: bool,
+}
+
+/// Live state of one service.
+struct Unit {
+ spec: ServiceSpec,
+ state: Mutex<Live>,
+ stop: CancellationToken,
+ /// Woken when a run ends or the unit is told to stop.
+ changed: Notify,
+}
+
+#[derive(Clone)]
+struct Live {
+ state: ServiceState,
+ pid: u32,
+ restarts: u32,
+ started_at: Option<SystemTime>,
+ last_end: Option<ProcessEnd>,
+ probe_error: String,
+ next_start_at: Option<SystemTime>,
+}
+
+impl Default for Live {
+ fn default() -> Self {
+ Self {
+ state: ServiceState::Starting,
+ pid: 0,
+ restarts: 0,
+ started_at: None,
+ last_end: None,
+ probe_error: String::new(),
+ next_start_at: None,
+ }
+ }
+}
+
+/// The guest's services.
+pub struct ServiceManager {
+ processes: Arc<ProcessManager>,
+ dir: PathBuf,
+ units: Mutex<BTreeMap<String, Arc<Unit>>>,
+}
+
+/// Checks a service name.
+pub fn valid_name(name: &str) -> bool {
+ let b = name.as_bytes();
+ !b.is_empty()
+ && b.len() <= 63
+ && b[0].is_ascii_alphanumeric()
+ && b.iter().all(|c| {
+ c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, b'-' | b'_' | b'.')
+ })
+}
+
+fn b64(bytes: &[u8]) -> String {
+ use base64::Engine as _;
+ base64::engine::general_purpose::STANDARD.encode(bytes)
+}
+
+fn unb64(s: &str) -> Option<Vec<u8>> {
+ use base64::Engine as _;
+ base64::engine::general_purpose::STANDARD.decode(s).ok()
+}
+
+fn invalid(m: impl Into<String>) -> Status {
+ crate::error::invalid(m.into())
+}
+
+fn not_found(name: &str) -> Status {
+ crate::error::status(
+ tonic::Code::NotFound,
+ cua_proto::env::v1::ErrorReason::Unspecified,
+ format!("no service {name:?}"),
+ )
+}
+
+impl ServiceManager {
+ /// Opens `<data_dir>/services` and starts every service that starts on
+ /// boot and was not stopped.
+ pub fn start(processes: Arc<ProcessManager>, data_dir: &Path) -> Arc<Self> {
+ let dir = data_dir.join("services");
+ let manager = Arc::new(Self {
+ processes,
+ dir,
+ units: Mutex::new(BTreeMap::new()),
+ });
+ for (spec, stopped) in manager.load() {
+ let on_boot = spec.start_on_boot.unwrap_or(true);
+ let unit = manager.insert(spec);
+ if on_boot && !stopped {
+ manager.spawn_supervisor(unit);
+ } else {
+ unit.state.lock().expect("unit").state = ServiceState::Stopped;
+ }
+ }
+ manager
+ }
+
+ fn load(&self) -> Vec<(ServiceSpec, bool)> {
+ let Ok(read) = std::fs::read_dir(&self.dir) else {
+ return Vec::new();
+ };
+ let mut out = Vec::new();
+ for e in read.flatten() {
+ let p = e.path();
+ if p.extension().and_then(|x| x.to_str()) != Some("json") {
+ continue;
+ }
+ let Some(record) = std::fs::read(&p)
+ .ok()
+ .and_then(|b| serde_json::from_slice::<Record>(&b).ok())
+ else {
+ tracing::warn!(path = %p.display(), "unreadable service record");
+ continue;
+ };
+ let Some(spec) = unb64(&record.spec)
+ .and_then(|b| <ServiceSpec as prost::Message>::decode(b.as_slice()).ok())
+ else {
+ continue;
+ };
+ if valid_name(&spec.name) {
+ out.push((spec, record.stopped));
+ }
+ }
+ out
+ }
+
+ fn save(&self, spec: &ServiceSpec, stopped: bool) -> Result<(), Status> {
+ std::fs::create_dir_all(&self.dir)
+ .map_err(|e| crate::error::internal(format!("services dir: {e}")))?;
+ let record = Record {
+ spec: b64(&prost::Message::encode_to_vec(spec)),
+ stopped,
+ };
+ let path = self.dir.join(format!("{}.json", spec.name));
+ let tmp = path.with_extension("json.tmp");
+ std::fs::write(&tmp, serde_json::to_vec(&record).unwrap_or_default())
+ .and_then(|()| std::fs::rename(&tmp, &path))
+ .map_err(|e| crate::error::internal(format!("save service: {e}")))
+ }
+
+ fn log_path(&self, name: &str) -> PathBuf {
+ self.dir.join(format!("{name}.log"))
+ }
+
+ fn insert(&self, spec: ServiceSpec) -> Arc<Unit> {
+ let unit = Arc::new(Unit {
+ spec: spec.clone(),
+ state: Mutex::new(Live::default()),
+ stop: CancellationToken::new(),
+ changed: Notify::new(),
+ });
+ self.units
+ .lock()
+ .expect("units")
+ .insert(spec.name.clone(), unit.clone());
+ unit
+ }
+
+ fn unit(&self, name: &str) -> Result<Arc<Unit>, Status> {
+ self.units
+ .lock()
+ .expect("units")
+ .get(name)
+ .cloned()
+ .ok_or_else(|| not_found(name))
+ }
+
+ fn status_of(&self, unit: &Unit) -> ServiceStatus {
+ let live = unit.state.lock().expect("unit").clone();
+ ServiceStatus {
+ spec: Some(unit.spec.clone()),
+ state: live.state as i32,
+ pid: live.pid,
+ restarts: live.restarts,
+ started_at: live.started_at.map(timestamp),
+ last_end: live.last_end,
+ probe_error: live.probe_error,
+ next_start_at: live.next_start_at.map(timestamp),
+ log_path: self.log_path(&unit.spec.name).display().to_string(),
+ }
+ }
+
+ /// Checks a spec and fills its defaults.
+ fn check(spec: &ServiceSpec) -> Result<(), Status> {
+ if !valid_name(&spec.name) {
+ return Err(invalid(format!(
+ "service name {:?}: use 1 to 63 lowercase letters, digits, '-', '_' or '.', \
+ starting with a letter or digit",
+ spec.name
+ )));
+ }
+ spec.config
+ .as_ref()
+ .filter(|c| !c.command.trim().is_empty())
+ .ok_or_else(|| invalid("a service needs a command"))?;
+ if let Some(p) = &spec.probe {
+ let set = [p.exec.is_some(), !p.http.is_empty(), !p.tcp.is_empty()]
+ .iter()
+ .filter(|s| **s)
+ .count();
+ if set != 1 {
+ return Err(invalid(
+ "a health probe checks one thing: set exactly one of exec, http or tcp",
+ ));
+ }
+ if !p.http.is_empty()
+ && !p.http.starts_with("http://")
+ && !p.http.starts_with("https://")
+ {
+ return Err(invalid("probe http must be an http(s):// URL"));
+ }
+ }
+ Ok(())
+ }
+
+ /// `PutService`.
+ pub async fn put(self: &Arc<Self>, spec: ServiceSpec) -> Result<ServiceStatus, Status> {
+ Self::check(&spec)?;
+ let replaced = self.units.lock().expect("units").get(&spec.name).cloned();
+ if replaced.is_none() && self.units.lock().expect("units").len() >= MAX_SERVICES {
+ return Err(crate::error::status(
+ tonic::Code::ResourceExhausted,
+ cua_proto::env::v1::ErrorReason::Unspecified,
+ format!("at most {MAX_SERVICES} services"),
+ ));
+ }
+ if let Some(old) = replaced {
+ self.halt(&old).await;
+ }
+ self.save(&spec, false)?;
+ let unit = self.insert(spec);
+ self.spawn_supervisor(unit.clone());
+ Ok(self.status_of(&unit))
+ }
+
+ /// `DeleteService`.
+ pub async fn delete(&self, name: &str) -> Result<(), Status> {
+ let unit = self.unit(name)?;
+ self.halt(&unit).await;
+ self.units.lock().expect("units").remove(name);
+ let _ = std::fs::remove_file(self.dir.join(format!("{name}.json")));
+ let _ = std::fs::remove_file(self.log_path(name));
+ let _ = std::fs::remove_file(self.dir.join(format!("{name}.log.1")));
+ Ok(())
+ }
+
+ /// `ListServices`.
+ pub fn list(&self) -> Vec<ServiceStatus> {
+ let units: Vec<Arc<Unit>> = self
+ .units
+ .lock()
+ .expect("units")
+ .values()
+ .cloned()
+ .collect();
+ units.iter().map(|u| self.status_of(u)).collect()
+ }
+
+ /// `ControlService`.
+ pub async fn control(
+ self: &Arc<Self>,
+ name: &str,
+ action: ServiceAction,
+ ) -> Result<ServiceStatus, Status> {
+ let unit = self.unit(name)?;
+ match action {
+ ServiceAction::Unspecified => Err(invalid("action is required")),
+ ServiceAction::Stop => {
+ self.halt(&unit).await;
+ self.save(&unit.spec, true)?;
+ unit.state.lock().expect("unit").state = ServiceState::Stopped;
+ Ok(self.status_of(&unit))
+ }
+ ServiceAction::Start | ServiceAction::Restart => {
+ let running = matches!(
+ unit.state.lock().expect("unit").state,
+ ServiceState::Starting
+ | ServiceState::Running
+ | ServiceState::Unhealthy
+ | ServiceState::Backoff
+ ) && !unit.stop.is_cancelled();
+ if running && action == ServiceAction::Start {
+ return Ok(self.status_of(&unit));
+ }
+ self.halt(&unit).await;
+ self.save(&unit.spec, false)?;
+ let restarts = unit.state.lock().expect("unit").restarts;
+ let fresh = self.insert(unit.spec.clone());
+ fresh.state.lock().expect("unit").restarts = restarts;
+ self.spawn_supervisor(fresh.clone());
+ Ok(self.status_of(&fresh))
+ }
+ }
+ }
+
+ /// `GetServiceLogs`: the last `tail` bytes of the log (and of the older
+ /// file when the current one is shorter).
+ pub fn logs(&self, name: &str, tail: u64) -> Result<(Vec<u8>, bool), Status> {
+ self.unit(name)?;
+ let tail = match tail {
+ 0 => DEFAULT_TAIL,
+ n => n.min(MAX_TAIL),
+ };
+ let current = std::fs::read(self.log_path(name)).unwrap_or_default();
+ let mut data = Vec::new();
+ if (current.len() as u64) < tail {
+ let older = std::fs::read(self.dir.join(format!("{name}.log.1"))).unwrap_or_default();
+ let need = (tail - current.len() as u64) as usize;
+ let from = older.len().saturating_sub(need);
+ data.extend_from_slice(&older[from..]);
+ }
+ data.extend_from_slice(&current);
+ let truncated = data.len() as u64 > tail;
+ if truncated {
+ data.drain(..data.len() - tail as usize);
+ }
+ Ok((data, truncated))
+ }
+
+ /// Stops a unit's supervisor and its process (SIGTERM to its group,
+ /// then SIGKILL after the grace).
+ async fn halt(&self, unit: &Unit) {
+ unit.stop.cancel();
+ unit.changed.notify_waiters();
+ let tag = format!("{TAG_PREFIX}{}", unit.spec.name);
+ for p in self.processes.running_with_tag(&tag) {
+ let _ = p.signal_group(Signal::Term);
+ }
+ let deadline = Instant::now() + STOP_GRACE;
+ while Instant::now() < deadline && !self.processes.running_with_tag(&tag).is_empty() {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ for p in self.processes.running_with_tag(&tag) {
+ let _ = p.signal_group(Signal::Kill);
+ }
+ let deadline = Instant::now() + Duration::from_secs(5);
+ while Instant::now() < deadline && !self.processes.running_with_tag(&tag).is_empty() {
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ }
+
+ fn spawn_supervisor(self: &Arc<Self>, unit: Arc<Unit>) {
+ let manager = self.clone();
+ tokio::spawn(async move { manager.supervise(unit).await });
+ }
+
+ async fn supervise(self: Arc<Self>, unit: Arc<Unit>) {
+ let spec = unit.spec.clone();
+ let policy = RestartPolicy::try_from(spec.restart).unwrap_or(RestartPolicy::Always);
+ let min = duration(spec.backoff_min.as_ref())
+ .filter(|d| !d.is_zero())
+ .unwrap_or(DEFAULT_BACKOFF_MIN);
+ let max = duration(spec.backoff_max.as_ref())
+ .filter(|d| !d.is_zero())
+ .unwrap_or(DEFAULT_BACKOFF_MAX)
+ .max(min);
+ let mut backoff = min;
+ let mut first = true;
+ loop {
+ if unit.stop.is_cancelled() {
+ return;
+ }
+ if !first {
+ unit.state.lock().expect("unit").restarts += 1;
+ }
+ first = false;
+ let request = StartProcessRequest {
+ config: spec.config.clone().map(|mut c| {
+ c.timeout = None;
+ c
+ }),
+ tag: format!("{TAG_PREFIX}{}", spec.name),
+ ..Default::default()
+ };
+ let entry = match self.processes.start(&request) {
+ Ok(Started::New(e)) => e,
+ Ok(Started::Failed(end)) => {
+ {
+ let mut live = unit.state.lock().expect("unit");
+ live.state = ServiceState::Failed;
+ live.last_end = Some(end.clone());
+ }
+ self.append_log(
+ &spec,
+ format!("[cua] could not start: {}\n", end.error).as_bytes(),
+ );
+ if !self
+ .wait_backoff(&unit, policy, &end, &mut backoff, max, Duration::ZERO)
+ .await
+ {
+ return;
+ }
+ continue;
+ }
+ Ok(_) => return,
+ Err(status) => {
+ {
+ let mut live = unit.state.lock().expect("unit");
+ live.state = ServiceState::Failed;
+ live.probe_error = status.message().to_owned();
+ }
+ return;
+ }
+ };
+ let started = Instant::now();
+ {
+ let mut live = unit.state.lock().expect("unit");
+ live.state = if spec.probe.is_some() {
+ ServiceState::Starting
+ } else {
+ ServiceState::Running
+ };
+ live.pid = entry.pid();
+ live.started_at = Some(SystemTime::now());
+ live.next_start_at = None;
+ live.probe_error.clear();
+ }
+ let logs = {
+ let (manager, entry, spec) = (self.clone(), entry.clone(), spec.clone());
+ tokio::spawn(async move { manager.pump_logs(&spec, &entry).await })
+ };
+ let probe = spec.probe.clone().map(|p| {
+ let (unit, entry) = (unit.clone(), entry.clone());
+ tokio::spawn(async move { probe_loop(&unit, &entry, p).await })
+ });
+ let end = tokio::select! {
+ end = entry.ended() => Some(end),
+ _ = unit.stop.cancelled() => None,
+ };
+ if let Some(p) = probe {
+ p.abort();
+ }
+ let Some(end) = end else {
+ // Stopped by a caller: `halt` ends the process.
+ let _ = tokio::time::timeout(Duration::from_secs(20), entry.ended()).await;
+ let _ = logs.await;
+ return;
+ };
+ let _ = logs.await;
+ {
+ let mut live = unit.state.lock().expect("unit");
+ live.pid = 0;
+ live.last_end = Some(end.clone());
+ }
+ self.append_log(&spec, describe_end(&end).as_bytes());
+ if !self
+ .wait_backoff(&unit, policy, &end, &mut backoff, max, started.elapsed())
+ .await
+ {
+ return;
+ }
+ }
+ }
+
+ /// After a run: whether to start again (after the backoff wait).
+ async fn wait_backoff(
+ &self,
+ unit: &Unit,
+ policy: RestartPolicy,
+ end: &ProcessEnd,
+ backoff: &mut Duration,
+ max: Duration,
+ ran: Duration,
+ ) -> bool {
+ let failed = end.exit_code != Some(0) || end.signal != 0 || !end.error.is_empty();
+ let again = match policy {
+ RestartPolicy::Always | RestartPolicy::Unspecified => true,
+ RestartPolicy::OnFailure => failed,
+ RestartPolicy::Never => false,
+ };
+ if !again || unit.stop.is_cancelled() {
+ let mut live = unit.state.lock().expect("unit");
+ if live.state != ServiceState::Failed {
+ live.state = ServiceState::Exited;
+ }
+ return false;
+ }
+ if ran >= STABLE_AFTER {
+ *backoff = DEFAULT_BACKOFF_MIN.min(*backoff);
+ }
+ let wait = *backoff;
+ *backoff = (*backoff * 2).min(max);
+ {
+ let mut live = unit.state.lock().expect("unit");
+ live.state = ServiceState::Backoff;
+ live.next_start_at = Some(SystemTime::now() + wait);
+ }
+ tokio::select! {
+ _ = tokio::time::sleep(wait) => !unit.stop.is_cancelled(),
+ _ = unit.stop.cancelled() => false,
+ }
+ }
+
+ /// Copies a run's output into the log file as it arrives.
+ async fn pump_logs(&self, spec: &ServiceSpec, entry: &super::ProcessEntry) {
+ let output = entry.output().clone();
+ let mut progress = output.subscribe();
+ let mut next = output.bounds().0;
+ loop {
+ let batch = output.read_from(next, 256 * 1024);
+ if batch.next < next {
+ next = batch.next;
+ }
+ for c in &batch.chunks {
+ self.append_log(spec, &c.data);
+ }
+ let advanced = batch.next != next;
+ next = batch.next;
+ if advanced {
+ continue;
+ }
+ if progress.borrow().closed && next >= output.bounds().1 {
+ return;
+ }
+ if progress.changed().await.is_err() {
+ return;
+ }
+ }
+ }
+
+ fn append_log(&self, spec: &ServiceSpec, data: &[u8]) {
+ if data.is_empty() {
+ return;
+ }
+ let max = match spec.log_max_bytes {
+ 0 => DEFAULT_LOG_MAX,
+ n => n,
+ };
+ let path = self.log_path(&spec.name);
+ let _ = std::fs::create_dir_all(&self.dir);
+ if std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0) + data.len() as u64 > max {
+ let _ = std::fs::rename(&path, self.dir.join(format!("{}.log.1", spec.name)));
+ }
+ if let Ok(mut f) = std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(&path)
+ {
+ let _ = f.write_all(data);
+ }
+ }
+}
+
+fn describe_end(end: &ProcessEnd) -> String {
+ if !end.error.is_empty() {
+ format!("[cua] ended: {}\n", end.error)
+ } else if let Some(code) = end.exit_code {
+ format!("[cua] exited with code {code}\n")
+ } else {
+ format!("[cua] ended by signal {}\n", end.signal_number)
+ }
+}
+
+/// Checks a run's health until it ends; `threshold` failures in a row end
+/// the run (the policy then restarts it).
+async fn probe_loop(unit: &Unit, entry: &super::ProcessEntry, probe: HealthProbe) {
+ let interval = duration(probe.interval.as_ref())
+ .filter(|d| !d.is_zero())
+ .unwrap_or(DEFAULT_PROBE_INTERVAL);
+ let timeout = duration(probe.timeout.as_ref())
+ .filter(|d| !d.is_zero())
+ .unwrap_or(DEFAULT_PROBE_TIMEOUT);
+ let grace = duration(probe.start_period.as_ref()).unwrap_or(DEFAULT_PROBE_GRACE);
+ let threshold = match probe.failure_threshold {
+ 0 => DEFAULT_FAILURE_THRESHOLD,
+ n => n,
+ };
+ let started = Instant::now();
+ let mut failures = 0u32;
+ loop {
+ tokio::time::sleep(interval.min(Duration::from_secs(3600))).await;
+ let result = tokio::time::timeout(timeout, check(&probe))
+ .await
+ .unwrap_or_else(|_| Err(format!("no answer within {}s", timeout.as_secs_f32())));
+ let give_up = {
+ let mut live = unit.state.lock().expect("unit");
+ match result {
+ Ok(()) => {
+ failures = 0;
+ live.probe_error.clear();
+ live.state = ServiceState::Running;
+ false
+ }
+ Err(e) => {
+ live.probe_error = e;
+ if started.elapsed() >= grace {
+ failures += 1;
+ live.state = ServiceState::Unhealthy;
+ }
+ failures >= threshold
+ }
+ }
+ };
+ if give_up {
+ tracing::warn!(service = %unit.spec.name, "health check failed {threshold} times; restarting");
+ let _ = entry.signal_group(Signal::Term);
+ tokio::time::sleep(STOP_GRACE).await;
+ let _ = entry.signal_group(Signal::Kill);
+ return;
+ }
+ }
+}
+
+/// One health check.
+async fn check(probe: &HealthProbe) -> Result<(), String> {
+ if let Some(cmd) = &probe.exec {
+ return exec_probe(cmd).await;
+ }
+ if !probe.tcp.is_empty() {
+ return tokio::net::TcpStream::connect(probe.tcp.as_str())
+ .await
+ .map(|_| ())
+ .map_err(|e| format!("tcp {}: {e}", probe.tcp));
+ }
+ http_probe(&probe.http).await
+}
+
+async fn exec_probe(cmd: &ProcessConfig) -> Result<(), String> {
+ let mut c = tokio::process::Command::new(&cmd.command);
+ c.args(&cmd.args).envs(&cmd.env).kill_on_drop(true);
+ if !cmd.cwd.is_empty() {
+ c.current_dir(&cmd.cwd);
+ }
+ let out = c
+ .output()
+ .await
+ .map_err(|e| format!("{}: {e}", cmd.command))?;
+ if out.status.success() {
+ Ok(())
+ } else {
+ let tail = String::from_utf8_lossy(&out.stderr);
+ Err(format!(
+ "exited with {}{}",
+ out.status,
+ tail.lines()
+ .last()
+ .map(|l| format!(": {l}"))
+ .unwrap_or_default()
+ ))
+ }
+}
+
+async fn http_probe(url: &str) -> Result<(), String> {
+ use http_body_util::Empty;
+ use hyper_util::client::legacy::Client;
+ use hyper_util::rt::TokioExecutor;
+ let uri: http::Uri = url.parse().map_err(|e| format!("{url}: {e}"))?;
+ if uri.scheme_str() != Some("http") {
+ return Err("only http:// probes are checked here".into());
+ }
+ let client: Client<_, Empty<bytes::Bytes>> = Client::builder(TokioExecutor::new()).build_http();
+ let resp = client.get(uri).await.map_err(|e| format!("{url}: {e}"))?;
+ let code = resp.status();
+ if code.is_success() || code.is_redirection() {
+ Ok(())
+ } else {
+ Err(format!("{url}: {code}"))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn names_are_checked() {
+ for ok in ["web", "a", "api-2", "db_main", "x.y"] {
+ assert!(valid_name(ok), "{ok}");
+ }
+ for bad in ["", "-a", "Web", "a b", "a/b", &"a".repeat(64)] {
+ assert!(!valid_name(bad), "{bad}");
+ }
+ }
+
+ #[test]
+ fn a_probe_checks_one_thing() {
+ let mut spec = ServiceSpec {
+ name: "web".into(),
+ config: Some(ProcessConfig {
+ command: "true".into(),
+ ..Default::default()
+ }),
+ probe: Some(HealthProbe {
+ tcp: "127.0.0.1:1".into(),
+ http: "http://127.0.0.1:1/".into(),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ assert!(ServiceManager::check(&spec).is_err());
+ spec.probe.as_mut().unwrap().http.clear();
+ assert!(ServiceManager::check(&spec).is_ok());
+ spec.config = None;
+ assert!(ServiceManager::check(&spec).is_err());
+ }
+}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/server.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/server.rs
index 94c0b871e2..5f328b4241 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/server.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/server.rs
@@ -32,7 +32,7 @@ use crate::services::diagnose::{DiagnoseState, Diagnoser};
use crate::services::driver::{DriverServiceImpl, NO_REGISTRY};
use crate::services::system::SystemServiceImpl;
use crate::services::teleport::TeleportServiceImpl;
-use crate::services::tunnel::{hotspot_ws, tunnel_ws, TunnelServiceImpl, TunnelState};
+use crate::services::tunnel::{hotspot_ws, spawn_ws, tunnel_ws, TunnelServiceImpl, TunnelState};
use crate::services::volume::{volume_ws, VolumeServiceImpl, VolumeShared};
/// gRPC services implemented by this crate.
@@ -134,6 +134,12 @@ impl ServerBuilder {
// Core services.
let processes = ProcessManager::new(ctx.clone());
+ // Services this guest keeps running; the ones that start on boot
+ // start now.
+ let services = crate::process::services::ServiceManager::start(
+ processes.clone(),
+ &ctx.config().data_dir,
+ );
let fs = FsState::new(ctx.clone());
let tunnel = TunnelState::new(ctx.clone());
let volume = VolumeShared::new(ctx.clone());
@@ -189,6 +195,8 @@ impl ServerBuilder {
feature(crate::filesystem::runas::MULTIPART_FEATURE, true, ""),
feature("tunnel.forward", true, ""),
feature("hotspot", true, ""),
+ // `TunnelService.StartSpawn`: the guest end of child Spaces.
+ feature(crate::services::tunnel::SPAWN_FEATURE, true, ""),
match crate::services::volume::backend() {
Ok(backend) => {
let mut f = feature(crate::services::volume::FEATURE, true, "");
@@ -219,6 +227,8 @@ impl ServerBuilder {
// `StartProcessRequest.request_id` / `epoch`, `GetExecRecord` and
// `AdvanceEpoch`: idempotent, fenced execs for durable harnesses.
core_features.push(feature(crate::process::EXEC_LEDGER_FEATURE, true, ""));
+ // `ProcessService.PutService` and the rest: commands kept running.
+ core_features.push(feature(crate::process::services::FEATURE, true, ""));
let system = SystemServiceImpl::new(ctx.clone(), providers.clone(), core_features)
.with_diagnose(DiagnoseState::new(ctx.clone(), self.diagnoser));
@@ -232,7 +242,11 @@ impl ServerBuilder {
.expect("valid descriptor set");
let mut routes = tonic::service::Routes::new(system.into_server())
- .add_service(ProcessServiceImpl::new(processes).into_server())
+ .add_service(
+ ProcessServiceImpl::new(processes)
+ .with_services(services)
+ .into_server(),
+ )
.add_service(FilesystemServiceImpl::new(fs.clone()).into_server())
.add_service(DriverServiceImpl::new(tools.clone()).into_server())
.add_service(teleport.into_server())
@@ -350,6 +364,7 @@ impl ServerBuilder {
Router::new()
.route(cua_proto::metadata::TUNNEL_WS_PATH, get(tunnel_ws))
.route(cua_proto::metadata::HOTSPOT_WS_PATH, get(hotspot_ws))
+ .route(cua_proto::metadata::SPAWN_WS_PATH, get(spawn_ws))
.with_state(tunnel),
);
manifest
@@ -358,6 +373,9 @@ impl ServerBuilder {
manifest
.http_paths
.insert(cua_proto::metadata::HOTSPOT_WS_PATH.into());
+ manifest
+ .http_paths
+ .insert(cua_proto::metadata::SPAWN_WS_PATH.into());
http = http.merge(
Router::new()
.route(cua_proto::metadata::VOLUME_WS_PATH, get(volume_ws))
@@ -374,7 +392,12 @@ impl ServerBuilder {
ctx: ctx.clone(),
envelopes: crate::http::mcp_envelope::enabled()
.then(|| crate::http::mcp_envelope::Envelopes::new(tools.clone())),
- tools,
+ // Plus this Space's child-Space tools (answered
+ // through its spawn channel, for its children only).
+ tools: Arc::new(crate::services::spawn_tools::WithChildTools::new(
+ tools,
+ ctx.clone(),
+ )),
}),
);
manifest
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/services/mod.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/mod.rs
index 5d3e59020b..968de4fa5b 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/services/mod.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/mod.rs
@@ -6,6 +6,8 @@
pub mod diagnose;
pub mod driver;
+pub mod spawn;
+pub mod spawn_tools;
pub mod system;
pub mod teleport;
pub mod tunnel;
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/services/spawn.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/spawn.rs
new file mode 100644
index 0000000000..1ec58e53c0
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/spawn.rs
@@ -0,0 +1,182 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Files of the spawn channel (`TunnelService.StartSpawn`): where the guest
+//! keeps the Space's spawn capability and the listener's address for
+//! clients in the Space (the `cua` CLI, SDKs, the agent's tools).
+//!
+//! The files live in a directory only the user cua-spacesd runs as can
+//! read: `/run/cua` when it may write there (a root driver), else a private
+//! directory in the user's runtime dir or a RAM-backed temp dir. They are
+//! never the proof of who calls: the host knows the Space by the WebSocket
+//! it opened, and a capability copied into another Space (a snapshot, a
+//! fork) is refused there.
+
+use std::io::Write as _;
+use std::path::{Path, PathBuf};
+
+/// The capability's file name (`/run/cua/spawn-token` for a root driver).
+pub const TOKEN_FILE: &str = cua_proto::metadata::SPAWN_TOKEN_FILE;
+/// The listener address's file name (one line, `http://127.0.0.1:<port>`).
+pub const ADDRESS_FILE: &str = cua_proto::metadata::SPAWN_ADDRESS_FILE;
+
+/// Environment of new processes: the Space's id.
+pub const ENV_SPACE: &str = cua_proto::metadata::ENV_SPACE;
+/// Environment of new processes: the spawn listener's URL.
+pub const ENV_ADDRESS: &str = cua_proto::metadata::ENV_SPAWN;
+/// Environment of new processes: the capability's file.
+pub const ENV_TOKEN_FILE: &str = cua_proto::metadata::ENV_SPAWN_TOKEN_FILE;
+
+/// Directories tried in order; the first this process can own wins (the
+/// same list clients look in, [`cua_proto::metadata::spawn_dirs`]).
+pub fn candidate_dirs() -> Vec<PathBuf> {
+ #[cfg(unix)]
+ // SAFETY: getuid has no preconditions.
+ let uid = Some(unsafe { libc::getuid() });
+ #[cfg(not(unix))]
+ let uid = None;
+ let xdg = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from);
+ cua_proto::metadata::spawn_dirs(uid, xdg.as_deref(), &std::env::temp_dir())
+}
+
+/// The first usable directory of [`candidate_dirs`], created when missing.
+pub fn choose_dir() -> std::io::Result<PathBuf> {
+ let mut last = None;
+ for dir in candidate_dirs() {
+ match usable(&dir) {
+ Ok(()) => return Ok(dir),
+ Err(e) => last = Some(e),
+ }
+ }
+ Err(last.unwrap_or_else(|| std::io::Error::other("no directory for the spawn files")))
+}
+
+/// Creates `dir` (0700) or accepts an existing one this user owns that no
+/// one else may write, then proves a file can be made in it.
+fn usable(dir: &Path) -> std::io::Result<()> {
+ if !dir.exists() {
+ std::fs::create_dir_all(dir)?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
+ }
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt as _;
+ let meta = std::fs::symlink_metadata(dir)?;
+ if !meta.is_dir() {
+ return Err(std::io::Error::other(format!(
+ "{} is not a directory",
+ dir.display()
+ )));
+ }
+ // SAFETY: getuid has no preconditions.
+ let uid = unsafe { libc::getuid() };
+ // Another user's directory, or one others may write into, could
+ // swap the files under us.
+ if meta.uid() != uid || meta.mode() & 0o022 != 0 {
+ return Err(std::io::Error::other(format!(
+ "{} is not private to this user",
+ dir.display()
+ )));
+ }
+ }
+ let probe = dir.join(".spawn-probe");
+ std::fs::write(&probe, b"")?;
+ let _ = std::fs::remove_file(&probe);
+ Ok(())
+}
+
+/// Writes `contents` to `path` atomically with `mode` (Unix).
+pub fn write_private(path: &Path, contents: &[u8], mode: u32) -> std::io::Result<()> {
+ let tmp = path.with_extension(format!("tmp-{}", crate::util::random_id(6)));
+ {
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt as _;
+ options.mode(mode);
+ }
+ #[cfg(not(unix))]
+ let _ = mode;
+ let mut f = options.open(&tmp)?;
+ f.write_all(contents)?;
+ f.sync_all()?;
+ }
+ std::fs::rename(&tmp, path).inspect_err(|_| {
+ let _ = std::fs::remove_file(&tmp);
+ })
+}
+
+/// The written files of one channel.
+#[derive(Debug, Clone)]
+pub struct SpawnFiles {
+ /// The capability.
+ pub token: PathBuf,
+ /// The listener's address.
+ pub address: PathBuf,
+}
+
+impl SpawnFiles {
+ /// Writes the capability (0600) and the address (0600) into `dir`.
+ pub fn write(dir: &Path, capability: &str, address: &str) -> std::io::Result<Self> {
+ let files = Self {
+ token: dir.join(TOKEN_FILE),
+ address: dir.join(ADDRESS_FILE),
+ };
+ write_private(&files.token, capability.as_bytes(), 0o600)?;
+ write_private(&files.address, format!("{address}\n").as_bytes(), 0o600)?;
+ Ok(files)
+ }
+
+ /// Removes both files (missing is fine).
+ pub fn remove(&self) {
+ let _ = std::fs::remove_file(&self.token);
+ let _ = std::fs::remove_file(&self.address);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn files_are_private_and_removed() {
+ let dir = tempfile::tempdir().unwrap();
+ let files = SpawnFiles::write(dir.path(), "cap", "http://127.0.0.1:1").unwrap();
+ assert_eq!(std::fs::read_to_string(&files.token).unwrap(), "cap");
+ assert_eq!(
+ std::fs::read_to_string(&files.address).unwrap(),
+ "http://127.0.0.1:1\n"
+ );
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ let mode = std::fs::metadata(&files.token)
+ .unwrap()
+ .permissions()
+ .mode();
+ assert_eq!(mode & 0o777, 0o600);
+ }
+ files.remove();
+ assert!(!files.token.exists() && !files.address.exists());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_directory_others_may_write_is_refused() {
+ use std::os::unix::fs::PermissionsExt as _;
+ let dir = tempfile::tempdir().unwrap();
+ let shared = dir.path().join("shared");
+ std::fs::create_dir(&shared).unwrap();
+ std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o777)).unwrap();
+ assert!(usable(&shared).is_err());
+ let own = dir.path().join("own");
+ usable(&own).unwrap();
+ let mode = std::fs::metadata(&own).unwrap().permissions().mode();
+ assert_eq!(mode & 0o777, 0o700);
+ }
+}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/services/spawn_tools.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/spawn_tools.rs
new file mode 100644
index 0000000000..fd5c6190dd
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/spawn_tools.rs
@@ -0,0 +1,301 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Child-Space tools in the Space's own MCP server: `create_space`,
+//! `fork_space`, `list_spaces`, `delete_space`, `stop_space`,
+//! `start_space` and `space_bash`, for the Space's own children only.
+//!
+//! They call the Space's spawn channel (`TunnelService.StartSpawn`) with the
+//! Space's capability, so every harness that uses this MCP server gets them
+//! with no setup. The host answers them for this Space's subtree alone;
+//! this server adds no authority of its own.
+
+use std::sync::Arc;
+
+use cua_driver_core::server::ToolProvider;
+use cua_proto::daemon::v1 as dpb;
+use cua_proto::daemon::v1::space_service_client::SpaceServiceClient;
+use serde_json::{json, Value};
+
+use crate::context::ServerContext;
+
+/// Names this provider adds.
+pub const TOOLS: &[&str] = &[
+ "create_space",
+ "fork_space",
+ "list_spaces",
+ "delete_space",
+ "stop_space",
+ "start_space",
+ "space_bash",
+];
+
+const SCOPE: &str = "Children of this Space only: Spaces it made (and theirs). \
+Other Spaces, including its parent and siblings, are not reachable.";
+
+fn defs() -> Vec<Value> {
+ let space = json!({"type": "string", "description": "A child's name or id."});
+ vec![
+ json!({"name": "create_space", "description": format!("Creates a child Space of this Space, on the same computer, and waits until it is ready. It keeps this Space's network rules and ends no later than this Space. {SCOPE}"),
+ "inputSchema": {"type": "object", "properties": {
+ "name": {"type": "string", "description": "Name (default: <this Space>.c<n>)."},
+ "image": {"type": "string", "description": "Image (default: the Linux image)."},
+ "kind": {"type": "string", "description": "\"container\" or \"vm\" (default: decided from the image)."},
+ "cpus": {"type": "integer"},
+ "memory_mb": {"type": "integer"},
+ "headless": {"type": "boolean", "description": "No desktop: only commands and files."}
+ }}}),
+ json!({"name": "fork_space", "description": format!("Forks this Space (or one of its children) into a new child Space. {SCOPE}"),
+ "inputSchema": {"type": "object", "properties": {
+ "source": {"type": "string", "description": "A child to fork (default: this Space)."},
+ "name": {"type": "string"}
+ }}}),
+ json!({"name": "list_spaces", "description": format!("Lists this Space's children. {SCOPE}"),
+ "inputSchema": {"type": "object", "properties": {}}}),
+ json!({"name": "delete_space", "description": format!("Deletes a child Space and everything below it. {SCOPE}"),
+ "inputSchema": {"type": "object", "properties": {"space": space}, "required": ["space"]}}),
+ json!({"name": "stop_space", "description": format!("Turns a child Space off (its disk is kept). {SCOPE}"),
+ "inputSchema": {"type": "object", "properties": {"space": space}, "required": ["space"]}}),
+ json!({"name": "start_space", "description": format!("Turns a child Space on again. {SCOPE}"),
+ "inputSchema": {"type": "object", "properties": {"space": space}, "required": ["space"]}}),
+ json!({"name": "space_bash", "description": format!("Runs a bash command in a child Space and returns its output and exit code. {SCOPE}"),
+ "inputSchema": {"type": "object", "properties": {
+ "space": space,
+ "command": {"type": "string"},
+ "timeout": {"type": "integer", "description": "Seconds (default 60)."}
+ }, "required": ["space", "command"]}}),
+ ]
+}
+
+/// The driver's tools plus the child-Space tools.
+pub struct WithChildTools {
+ inner: Arc<dyn ToolProvider>,
+ ctx: ServerContext,
+}
+
+impl WithChildTools {
+ /// Wraps `inner`.
+ pub fn new(inner: Arc<dyn ToolProvider>, ctx: ServerContext) -> Self {
+ Self { inner, ctx }
+ }
+
+ /// The spawn channel's URL and capability, while it is started.
+ fn channel(&self) -> Result<(String, String), String> {
+ let env = self.ctx.init_state().spawn_env;
+ let url = env.get(super::spawn::ENV_ADDRESS).cloned();
+ let file = env.get(super::spawn::ENV_TOKEN_FILE).cloned();
+ let (Some(url), Some(file)) = (url, file) else {
+ return Err(
+ "this Space cannot make child Spaces: its owner has not turned \
+ children on for it"
+ .into(),
+ );
+ };
+ let token = std::fs::read_to_string(&file)
+ .map(|t| t.trim().to_owned())
+ .map_err(|e| format!("the spawn capability is unreadable: {e}"))?;
+ Ok((url, token))
+ }
+
+ async fn client(
+ &self,
+ ) -> Result<
+ SpaceServiceClient<
+ tonic::service::interceptor::InterceptedService<
+ tonic::transport::Channel,
+ impl tonic::service::Interceptor,
+ >,
+ >,
+ String,
+ > {
+ let (url, token) = self.channel()?;
+ let channel = tonic::transport::Endpoint::from_shared(url)
+ .map_err(|e| e.to_string())?
+ .connect()
+ .await
+ .map_err(|e| format!("the spawn channel is not reachable: {e}"))?;
+ let bearer: tonic::metadata::MetadataValue<_> = format!("Bearer {token}")
+ .parse()
+ .map_err(|_| "the spawn capability is not a valid header".to_string())?;
+ Ok(
+ SpaceServiceClient::with_interceptor(channel, move |mut req: tonic::Request<()>| {
+ req.metadata_mut().insert("authorization", bearer.clone());
+ Ok(req)
+ })
+ .max_decoding_message_size(64 << 20),
+ )
+ }
+
+ async fn call(&self, name: &str, a: Value) -> Result<Value, String> {
+ let mut c = self.client().await?;
+ let s = |k: &str| {
+ a.get(k)
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_owned()
+ };
+ let status = |e: tonic::Status| e.message().to_owned();
+ Ok(match name {
+ "create_space" => {
+ let r = c
+ .create_space(dpb::CreateSpaceRequest {
+ name: s("name"),
+ image: s("image"),
+ kind: s("kind"),
+ cpus: a.get("cpus").and_then(Value::as_u64).unwrap_or(0) as u32,
+ memory_mb: a.get("memory_mb").and_then(Value::as_u64).unwrap_or(0),
+ headless: a.get("headless").and_then(Value::as_bool).unwrap_or(false),
+ wait: Some(true),
+ ..Default::default()
+ })
+ .await
+ .map_err(status)?
+ .into_inner();
+ r.space.map(row).unwrap_or(Value::Null)
+ }
+ "fork_space" => c
+ .fork_space(dpb::ForkSpaceRequest {
+ source: s("source"),
+ name: s("name"),
+ })
+ .await
+ .map_err(status)?
+ .into_inner()
+ .space
+ .map(row)
+ .unwrap_or(Value::Null),
+ "list_spaces" => {
+ let r = c
+ .list_spaces(dpb::ListSpacesRequest::default())
+ .await
+ .map_err(status)?
+ .into_inner();
+ json!({"spaces": r.spaces.into_iter().map(row).collect::<Vec<_>>()})
+ }
+ "delete_space" => {
+ let r = c
+ .delete_space(dpb::DeleteSpaceRequest {
+ space: s("space"),
+ keep_children: false,
+ })
+ .await
+ .map_err(status)?
+ .into_inner();
+ json!({"deleted": s("space"), "message": r.message})
+ }
+ _ => {
+ // stop_space, start_space, space_bash: the host's tools,
+ // which the channel answers for children only.
+ let r = c
+ .call_space_tool(dpb::CallSpaceToolRequest {
+ name: name.to_owned(),
+ arguments_json: a.to_string(),
+ })
+ .await
+ .map_err(status)?
+ .into_inner();
+ let content: Value =
+ serde_json::from_str(&r.content_json).unwrap_or(Value::Array(vec![]));
+ return Ok(json!({"content": content, "isError": r.is_error}));
+ }
+ })
+ }
+}
+
+/// A child as the tools show it.
+fn row(s: dpb::Space) -> Value {
+ json!({
+ "id": s.id,
+ "name": if s.display_name.is_empty() { s.name } else { s.display_name },
+ "parent": if s.parent.is_empty() {
+ s.labels.get("cua.parent").cloned().unwrap_or_default()
+ } else {
+ s.parent.clone()
+ },
+ "power": s.power,
+ "image": s.image,
+ "os": s.os,
+ "expires_at_unix": s.expires_at_unix,
+ })
+}
+
+fn text_result(text: String, is_error: bool) -> Value {
+ json!({"content": [{"type": "text", "text": text}], "isError": is_error})
+}
+
+#[async_trait::async_trait]
+impl ToolProvider for WithChildTools {
+ fn tools_list(&self) -> Value {
+ let mut list = self.inner.tools_list();
+ let defs = defs();
+ match list.get_mut("tools").and_then(Value::as_array_mut) {
+ Some(tools) => {
+ tools.retain(|t| {
+ t.get("name")
+ .and_then(Value::as_str)
+ .is_none_or(|n| !TOOLS.contains(&n))
+ });
+ tools.extend(defs);
+ }
+ None => list = json!({"tools": defs}),
+ }
+ list
+ }
+
+ fn is_known_tool(&self, name: &str) -> bool {
+ TOOLS.contains(&name) || self.inner.is_known_tool(name)
+ }
+
+ async fn invoke_tool(&self, name: &str, arguments: Value) -> Result<Value, String> {
+ if !TOOLS.contains(&name) {
+ return self.inner.invoke_tool(name, arguments).await;
+ }
+ Ok(match self.call(name, arguments).await {
+ Ok(v) if v.get("content").is_some() => v,
+ Ok(v) => text_result(serde_json::to_string_pretty(&v).unwrap_or_default(), false),
+ Err(e) => text_result(e, true),
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ struct Driver;
+
+ #[async_trait::async_trait]
+ impl ToolProvider for Driver {
+ fn tools_list(&self) -> Value {
+ json!({"tools": [{"name": "click"}]})
+ }
+ async fn invoke_tool(&self, name: &str, _: Value) -> Result<Value, String> {
+ Ok(text_result(format!("driver {name}"), false))
+ }
+ }
+
+ #[tokio::test]
+ async fn child_tools_join_the_driver_and_say_when_children_are_off() {
+ let ctx = ServerContext::new(crate::config::ServerConfig::default(), Some("t".into()));
+ let p = WithChildTools::new(Arc::new(Driver), ctx);
+ let names: Vec<String> = p.tools_list()["tools"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|t| t["name"].as_str().unwrap().to_owned())
+ .collect();
+ assert!(names.contains(&"click".to_owned()));
+ for t in TOOLS {
+ assert!(names.contains(&t.to_string()), "{t}");
+ }
+ let out = p.invoke_tool("click", json!({})).await.unwrap();
+ assert_eq!(out["content"][0]["text"], "driver click");
+ // No channel: a plain refusal the agent can read.
+ let out = p.invoke_tool("list_spaces", json!({})).await.unwrap();
+ assert_eq!(out["isError"], true);
+ assert!(out["content"][0]["text"]
+ .as_str()
+ .unwrap()
+ .contains("not turned children on"));
+ }
+}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/services/tunnel.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/tunnel.rs
index 99e4959b16..44ff25e3e7 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/services/tunnel.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/tunnel.rs
@@ -32,6 +32,13 @@ use crate::util::{duration, timestamp};
pub const FORWARD_DEFAULT_TTL: Duration = Duration::from_secs(10 * 60);
/// Default hotspot ticket lifetime.
pub const HOTSPOT_DEFAULT_TTL: Duration = Duration::from_secs(60);
+/// The capability a guest with the spawn channel advertises.
+pub const SPAWN_FEATURE: &str = "spawn";
+/// Default spawn ticket lifetime.
+pub const SPAWN_DEFAULT_TTL: Duration = Duration::from_secs(60);
+/// The host end every spawn connection is opened to (the host serves its
+/// child-Space API there; the name is not dialed).
+pub const SPAWN_PEER_HOST: &str = "spawn";
struct Forward {
id: String,
@@ -53,12 +60,22 @@ struct Hotspot {
set_system_proxy: bool,
}
+/// The spawn channel: a listener on guest loopback relayed to the host.
+struct Spawn {
+ id: String,
+ address: String,
+ hub: Hub,
+ stop: CancellationToken,
+ files: super::spawn::SpawnFiles,
+}
+
/// State shared by the gRPC service and the WebSocket routes.
#[derive(Clone)]
pub struct TunnelState {
ctx: ServerContext,
forwards: Arc<Mutex<HashMap<String, Arc<Forward>>>>,
hotspot: Arc<Mutex<Option<Arc<Hotspot>>>>,
+ spawn: Arc<Mutex<Option<Arc<Spawn>>>>,
}
impl TunnelState {
@@ -68,6 +85,7 @@ impl TunnelState {
ctx,
forwards: Arc::default(),
hotspot: Arc::default(),
+ spawn: Arc::default(),
};
// Revoked sessions (token file rotated or emptied): stop every
// forward and the hotspot.
@@ -77,6 +95,7 @@ impl TunnelState {
let weak = (
Arc::downgrade(&state.forwards),
Arc::downgrade(&state.hotspot),
+ Arc::downgrade(&state.spawn),
);
let ctx = state.ctx.clone();
handle.spawn(async move {
@@ -85,7 +104,8 @@ impl TunnelState {
changed = revoked.changed() => if changed.is_err() { return },
_ = shutdown.cancelled() => return,
}
- let (Some(forwards), Some(hotspot)) = (weak.0.upgrade(), weak.1.upgrade())
+ let (Some(forwards), Some(hotspot), Some(spawn)) =
+ (weak.0.upgrade(), weak.1.upgrade(), weak.2.upgrade())
else {
return;
};
@@ -93,6 +113,7 @@ impl TunnelState {
ctx: ctx.clone(),
forwards,
hotspot,
+ spawn,
};
state.revoke_all();
}
@@ -101,8 +122,10 @@ impl TunnelState {
state
}
- /// Closes every forward and stops the hotspot.
+ /// Closes every forward, stops the hotspot and the spawn channel (a
+ /// new token is a new owner: the old Space's capability must not stay).
pub fn revoke_all(&self) {
+ self.stop_spawn(None);
let forwards: Vec<_> = self
.forwards
.lock()
@@ -126,6 +149,25 @@ impl TunnelState {
.retain(|_, f| f.expires_at > now || f.active.load(Ordering::SeqCst) > 0);
}
+ fn stop_spawn(&self, id: Option<&str>) -> bool {
+ let mut slot = self.spawn.lock().expect("spawn");
+ let matches = match (slot.as_ref(), id) {
+ (Some(s), Some(id)) => s.id == id,
+ (Some(_), None) => true,
+ (None, _) => false,
+ };
+ if !matches {
+ return false;
+ }
+ if let Some(spawn) = slot.take() {
+ spawn.stop.cancel();
+ spawn.files.remove();
+ self.ctx.update_init(|state| state.spawn_env.clear());
+ tracing::info!(spawn = %spawn.id, "spawn channel stopped");
+ }
+ true
+ }
+
fn stop_hotspot(&self, id: Option<&str>) -> bool {
let mut slot = self.hotspot.lock().expect("hotspot");
let matches = match (slot.as_ref(), id) {
@@ -495,6 +537,139 @@ impl TunnelService for TunnelServiceImpl {
bytes_in: stats.bytes_in.load(Ordering::Relaxed),
}))
}
+
+ async fn start_spawn(
+ &self,
+ request: Request<StartSpawnRequest>,
+ ) -> Result<GrpcResponse<StartSpawnResponse>, Status> {
+ let caller = caller(&request);
+ // Only the host that runs this Space: it holds the Space's own
+ // token. A relayed account, a viewer or a share never may (they
+ // would put themselves between the Space and its host).
+ if !caller.token_verified || caller.account.is_some() || caller.viewer.is_some() {
+ return Err(status(
+ Code::PermissionDenied,
+ ErrorReason::Unspecified,
+ "only the host that runs this Space may start its spawn channel",
+ ));
+ }
+ let body = request.into_inner();
+ if body.capability.trim().is_empty() {
+ return Err(crate::error::invalid("capability is required"));
+ }
+ self.state.stop_spawn(None);
+ let dir = super::spawn::choose_dir().map_err(|e| {
+ status(
+ Code::FailedPrecondition,
+ ErrorReason::Unspecified,
+ format!("no private directory for the spawn files: {e}"),
+ )
+ })?;
+ let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
+ .await
+ .map_err(|e| crate::error::internal(format!("spawn listener: {e}")))?;
+ let local = listener
+ .local_addr()
+ .map_err(|e| crate::error::internal(e.to_string()))?;
+ let address = format!("http://{local}");
+ let files = super::spawn::SpawnFiles::write(&dir, body.capability.trim(), &address)
+ .map_err(|e| crate::error::internal(format!("spawn files: {e}")))?;
+ let id = format!("sp-{}", crate::util::random_id(9));
+ let hub = Hub::new();
+ let stop = CancellationToken::new();
+ {
+ let (hub, stop) = (hub.clone(), stop.clone());
+ tokio::spawn(async move {
+ tokio::select! {
+ r = cua_spacesd_socks::serve_forward(listener, hub, SPAWN_PEER_HOST.into(), 0) => {
+ if let Err(error) = r {
+ tracing::warn!(%error, "spawn listener failed");
+ }
+ }
+ _ = stop.cancelled() => {}
+ }
+ });
+ }
+ let token_path = files.token.to_string_lossy().into_owned();
+ let address_path = files.address.to_string_lossy().into_owned();
+ self.state.ctx.update_init(|state| {
+ state.spawn_env.clear();
+ state
+ .spawn_env
+ .insert(super::spawn::ENV_ADDRESS.into(), address.clone());
+ state
+ .spawn_env
+ .insert(super::spawn::ENV_TOKEN_FILE.into(), token_path.clone());
+ if !body.space_id.is_empty() {
+ state
+ .spawn_env
+ .insert(super::spawn::ENV_SPACE.into(), body.space_id.clone());
+ }
+ });
+ let ttl = duration(body.ticket_ttl.as_ref())
+ .filter(|d| !d.is_zero())
+ .unwrap_or(SPAWN_DEFAULT_TTL);
+ let (ticket, _) = self.state.ctx.mint_ticket_issued(
+ TicketScope::Spawn,
+ &id,
+ caller.principal.as_ref(),
+ None,
+ ttl,
+ );
+ *self.state.spawn.lock().expect("spawn") = Some(Arc::new(Spawn {
+ id: id.clone(),
+ address: address.clone(),
+ hub,
+ stop,
+ files,
+ }));
+ tracing::info!(spawn = %id, %address, "spawn channel started");
+ Ok(GrpcResponse::new(StartSpawnResponse {
+ spawn_id: id,
+ ws_path: ticket_path(cua_proto::metadata::SPAWN_WS_PATH, &ticket),
+ ticket,
+ address,
+ token_path,
+ address_path,
+ }))
+ }
+
+ async fn stop_spawn(
+ &self,
+ request: Request<StopSpawnRequest>,
+ ) -> Result<GrpcResponse<StopSpawnResponse>, Status> {
+ let caller = caller(&request);
+ if !caller.token_verified || caller.account.is_some() || caller.viewer.is_some() {
+ return Err(status(
+ Code::PermissionDenied,
+ ErrorReason::Unspecified,
+ "only the host that runs this Space may stop its spawn channel",
+ ));
+ }
+ let id = request.into_inner().spawn_id;
+ let id = (!id.is_empty()).then_some(id);
+ if !self.state.stop_spawn(id.as_deref()) && id.is_some() {
+ return Err(session_not_found("spawn", id.as_deref().unwrap_or("")));
+ }
+ Ok(GrpcResponse::new(StopSpawnResponse {}))
+ }
+
+ async fn get_spawn_status(
+ &self,
+ _request: Request<GetSpawnStatusRequest>,
+ ) -> Result<GrpcResponse<GetSpawnStatusResponse>, Status> {
+ let spawn = self.state.spawn.lock().expect("spawn").clone();
+ let Some(spawn) = spawn else {
+ return Ok(GrpcResponse::new(GetSpawnStatusResponse::default()));
+ };
+ Ok(GrpcResponse::new(GetSpawnStatusResponse {
+ started: true,
+ attached: spawn.hub.is_connected(),
+ spawn_id: spawn.id.clone(),
+ address: spawn.address.clone(),
+ active_connections: spawn.hub.stats().active_connections.load(Ordering::Relaxed),
+ }))
+ }
}
pub(crate) fn refuse(error: crate::auth::TicketError) -> Response {
@@ -659,6 +834,51 @@ pub async fn hotspot_ws(
})
}
+/// `GET /spawn?ticket=…` (WebSocket): attaches the host as the peer of the
+/// spawn listener; the listener refuses connections while it is detached.
+/// A newer host socket replaces an older one (a host that restarted).
+pub async fn spawn_ws(
+ State(state): State<TunnelState>,
+ uri: Uri,
+ headers: HeaderMap,
+ upgrade: WebSocketUpgrade,
+) -> Response {
+ let (claims, subprotocol) =
+ match state
+ .ctx
+ .validate_request_ticket(&uri, &headers, TicketScope::Spawn)
+ {
+ Ok(v) => v,
+ Err(e) => return refuse(e),
+ };
+ let spawn = state.spawn.lock().expect("spawn").clone();
+ let Some(spawn) = spawn.filter(|s| s.id == claims.resource) else {
+ return (StatusCode::GONE, "spawn channel stopped").into_response();
+ };
+ with_protocol(upgrade, subprotocol)
+ .max_message_size(16 * 1024 * 1024)
+ .on_upgrade(move |socket| async move {
+ let (ws_tx, ws_rx) = socket.split();
+ let source = ws_rx
+ .take_while(|m| {
+ futures_util::future::ready(!matches!(m, Err(_) | Ok(Message::Close(_))))
+ })
+ .filter_map(|m| async move {
+ match m {
+ Ok(Message::Binary(data)) => Some(data.to_vec()),
+ _ => None,
+ }
+ });
+ let sink = ws_tx.with(|data: Vec<u8>| async move {
+ Ok::<_, axum::Error>(Message::Binary(data.into()))
+ });
+ tokio::select! {
+ _ = spawn.hub.run_peer(Box::pin(source), Box::pin(sink)) => {}
+ _ = spawn.stop.cancelled() => {}
+ }
+ })
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/tests/conformance.rs b/libs/cua-spacesd/crates/cua-spacesd-server/tests/conformance.rs
index 798074523f..c717499b31 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/tests/conformance.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/tests/conformance.rs
@@ -119,11 +119,13 @@ async fn capabilities_report_contract_and_limitations() {
"fs_watch",
"tunnel.forward",
"hotspot",
+ "spawn",
"driver",
"a11y",
"desktop_stream",
"audio.uplink",
"process.exec_ledger",
+ "process.services",
"fs.run_as",
"fs.xattr",
"files.multipart",
@@ -181,6 +183,7 @@ async fn route_spec_consistency() {
cua_proto::metadata::MEDIA_WS_PATH,
cua_proto::metadata::TUNNEL_WS_PATH,
cua_proto::metadata::HOTSPOT_WS_PATH,
+ cua_proto::metadata::SPAWN_WS_PATH,
cua_proto::metadata::VOLUME_WS_PATH,
cua_proto::metadata::FILES_PATH,
cua_proto::metadata::MCP_PATH,
@@ -1843,6 +1846,277 @@ async fn hotspot_egress_goes_through_the_peer() {
t.cleanup().await;
}
+#[tokio::test]
+async fn spawn_channel_reaches_the_host_and_tells_processes_where() {
+ let t = target().await;
+ let c = t.client(TransportPreference::Native).await;
+ let spawn = c
+ .tunnel()
+ .start_spawn(StartSpawnRequest {
+ capability: "cap-for-this-space".into(),
+ space_id: "space-under-test".into(),
+ ..Default::default()
+ })
+ .await
+ .unwrap()
+ .into_inner();
+ assert!(spawn.address.starts_with("http://127.0.0.1:"));
+ // A forged ticket is refused.
+ let bad = t.endpoint().ws_url("/spawn?ticket=v1.bad.sig");
+ assert!(ws_connect(&bad).await.is_err());
+ let (ws, _) = ws_connect(t.endpoint().ws_url(&spawn.ws_path))
+ .await
+ .unwrap();
+ let (sink, source) = ws.split();
+ let source = Box::pin(source.filter_map(|m| async move {
+ match m {
+ Ok(tokio_tungstenite::tungstenite::Message::Binary(b)) => Some(b),
+ _ => None,
+ }
+ }));
+ let sink = Box::pin(sink.with(|b: Vec<u8>| async move {
+ Ok::<_, tokio_tungstenite::tungstenite::Error>(
+ tokio_tungstenite::tungstenite::Message::Binary(b),
+ )
+ }));
+ // The host's end: every connection is a stream to its own API (here a
+ // fixed HTTP answer), never a dial into the network.
+ let opened = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let log = opened.clone();
+ tokio::spawn(cua_spacesd_socks::peer::serve_streams(
+ source,
+ sink,
+ move |host: String, port| {
+ log.lock().unwrap().push(format!("{host}:{port}"));
+ async move {
+ let (ours, theirs) = tokio::io::duplex(4096);
+ tokio::spawn(async move {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let mut s = theirs;
+ let mut buf = [0u8; 1024];
+ let _ = s.read(&mut buf).await;
+ let _ = s
+ .write_all(b"HTTP/1.0 200 OK\r\nContent-Length: 8\r\n\r\nspawn-ok")
+ .await;
+ });
+ Ok::<_, std::io::Error>(ours)
+ }
+ },
+ ));
+ // New processes are told the Space, the listener and the capability.
+ let (code, env) = run_sh(
+ &c,
+ "printf '%s|%s|' \"$CUA_SPACE\" \"$CUA_SPAWN\"; cat \"$CUA_SPAWN_TOKEN_FILE\"",
+ )
+ .await;
+ assert_eq!(code, Some(0));
+ assert_eq!(
+ String::from_utf8_lossy(&env),
+ format!("space-under-test|{}|cap-for-this-space", spawn.address)
+ );
+ let mut body = Vec::new();
+ for _ in 0..20 {
+ let (code, out) = run_sh(&c, &format!("curl -s --max-time 5 {}/", spawn.address)).await;
+ body = out;
+ if code == Some(0) && body == b"spawn-ok" {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ }
+ assert_eq!(body, b"spawn-ok");
+ assert_eq!(opened.lock().unwrap()[0], "spawn:0");
+ let status = c
+ .tunnel()
+ .get_spawn_status(GetSpawnStatusRequest {})
+ .await
+ .unwrap()
+ .into_inner();
+ assert!(status.started && status.attached);
+ c.tunnel()
+ .stop_spawn(StopSpawnRequest {
+ spawn_id: spawn.spawn_id,
+ })
+ .await
+ .unwrap();
+ // Stopped: the capability is gone from the guest and new processes are
+ // not told about a channel.
+ let (_, gone) = run_sh(
+ &c,
+ &format!(
+ "test -e '{}' && echo left; printf '%s' \"$CUA_SPAWN\"",
+ spawn.token_path
+ ),
+ )
+ .await;
+ assert_eq!(gone, b"");
+ let status = c
+ .tunnel()
+ .get_spawn_status(GetSpawnStatusRequest {})
+ .await
+ .unwrap()
+ .into_inner();
+ assert!(!status.started);
+ t.cleanup().await;
+}
+
+#[tokio::test]
+async fn a_service_is_kept_running_logged_checked_and_stopped() {
+ let t = target().await;
+ let c = t.client(TransportPreference::Native).await;
+ let name = format!("svc-{}", std::process::id());
+ let ms = |n: u64| {
+ Some(cua_proto::wkt::Duration {
+ seconds: (n / 1000) as i64,
+ nanos: ((n % 1000) * 1_000_000) as i32,
+ })
+ };
+ let put = c
+ .process()
+ .put_service(PutServiceRequest {
+ spec: Some(ServiceSpec {
+ name: name.clone(),
+ config: Some(ProcessConfig {
+ command: "sh".into(),
+ args: vec!["-c".into(), "echo started-once; exit 3".into()],
+ ..Default::default()
+ }),
+ restart: RestartPolicy::OnFailure as i32,
+ backoff_min: ms(100),
+ backoff_max: ms(200),
+ ..Default::default()
+ }),
+ })
+ .await
+ .unwrap()
+ .into_inner()
+ .service
+ .unwrap();
+ assert_eq!(put.spec.unwrap().name, name);
+ // It fails, so the policy starts it again, and again.
+ let deadline = Instant::now() + Duration::from_secs(20);
+ let status = loop {
+ let list = c
+ .process()
+ .list_services(ListServicesRequest {})
+ .await
+ .unwrap()
+ .into_inner();
+ let s = list
+ .services
+ .into_iter()
+ .find(|s| s.spec.as_ref().is_some_and(|p| p.name == name))
+ .unwrap();
+ if s.restarts >= 2 {
+ break s;
+ }
+ assert!(Instant::now() < deadline, "not restarted: {s:?}");
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ };
+ assert_eq!(status.last_end.unwrap().exit_code, Some(3));
+ let logs = c
+ .process()
+ .get_service_logs(GetServiceLogsRequest {
+ name: name.clone(),
+ tail_bytes: 0,
+ })
+ .await
+ .unwrap()
+ .into_inner();
+ let text = String::from_utf8_lossy(&logs.data);
+ assert!(text.matches("started-once").count() >= 2, "{text}");
+ assert!(text.contains("[cua] exited with code 3"), "{text}");
+ // Stopped by a caller: it stays stopped.
+ let stopped = c
+ .process()
+ .control_service(ControlServiceRequest {
+ name: name.clone(),
+ action: ServiceAction::Stop as i32,
+ })
+ .await
+ .unwrap()
+ .into_inner()
+ .service
+ .unwrap();
+ assert_eq!(stopped.state, ServiceState::Stopped as i32);
+ c.process()
+ .delete_service(DeleteServiceRequest { name: name.clone() })
+ .await
+ .unwrap();
+ let e = c
+ .process()
+ .get_service_logs(GetServiceLogsRequest {
+ name: name.clone(),
+ tail_bytes: 0,
+ })
+ .await
+ .unwrap_err();
+ assert_eq!(e.code(), Code::NotFound);
+ t.cleanup().await;
+}
+
+#[tokio::test]
+async fn a_failing_health_check_restarts_a_service() {
+ let t = target().await;
+ let c = t.client(TransportPreference::Native).await;
+ let name = format!("probe-{}", std::process::id());
+ let ms = |n: u64| {
+ Some(cua_proto::wkt::Duration {
+ seconds: (n / 1000) as i64,
+ nanos: ((n % 1000) * 1_000_000) as i32,
+ })
+ };
+ // Port 9 (discard) answers nothing on a guest's loopback.
+ c.process()
+ .put_service(PutServiceRequest {
+ spec: Some(ServiceSpec {
+ name: name.clone(),
+ config: Some(ProcessConfig {
+ command: "sleep".into(),
+ args: vec!["600".into()],
+ ..Default::default()
+ }),
+ backoff_min: ms(100),
+ probe: Some(HealthProbe {
+ tcp: "127.0.0.1:9".into(),
+ interval: ms(200),
+ timeout: ms(200),
+ failure_threshold: 2,
+ start_period: ms(0),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }),
+ })
+ .await
+ .unwrap();
+ let deadline = Instant::now() + Duration::from_secs(60);
+ loop {
+ let s = c
+ .process()
+ .list_services(ListServicesRequest {})
+ .await
+ .unwrap()
+ .into_inner()
+ .services
+ .into_iter()
+ .find(|s| s.spec.as_ref().is_some_and(|p| p.name == name))
+ .unwrap();
+ if s.restarts >= 1 {
+ // The failed check stopped it (the reason is cleared once the new
+ // run starts, so it is not asserted here).
+ assert!(s.last_end.is_some(), "{s:?}");
+ break;
+ }
+ assert!(Instant::now() < deadline, "not restarted: {s:?}");
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ c.process()
+ .delete_service(DeleteServiceRequest { name })
+ .await
+ .unwrap();
+ t.cleanup().await;
+}
+
// ---------------------------------------------------------------------------
// Teleport
// ---------------------------------------------------------------------------
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/tests/image_claims.rs b/libs/cua-spacesd/crates/cua-spacesd-server/tests/image_claims.rs
index 54869d173a..22d19972d4 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/tests/image_claims.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/tests/image_claims.rs
@@ -51,6 +51,8 @@ fn everywhere() -> Vec<&'static str> {
"fs_watch",
"tunnel.forward",
"hotspot",
+ services::tunnel::SPAWN_FEATURE,
+ process::services::FEATURE,
runas::MULTIPART_FEATURE,
process::EXEC_LEDGER_FEATURE,
server::RELAY_ATTACH_FEATURE,
diff --git a/libs/cua-spacesd/crates/cua-spacesd-socks/src/lib.rs b/libs/cua-spacesd/crates/cua-spacesd-socks/src/lib.rs
index d24f431182..8cc471af54 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-socks/src/lib.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-socks/src/lib.rs
@@ -278,15 +278,44 @@ async fn fulfill_via_tunnel(
relay(client, tunnel, stats, host, port, true).await
}
+/// [`serve_forward`] on a Unix socket: the guest's spawn socket
+/// (`/run/cua/spawn.sock`), whose every connection reaches the host's
+/// spawn API for this Space. A connection made while no peer is attached is
+/// closed.
+#[cfg(unix)]
+pub async fn serve_forward_unix(
+ listener: tokio::net::UnixListener,
+ hub: Hub,
+ host: String,
+ port: u16,
+) -> std::io::Result<()> {
+ loop {
+ let (client, _peer) = listener.accept().await?;
+ let Some(tunnel) = hub.tunnel() else {
+ drop(client);
+ continue;
+ };
+ let (stats, host) = (hub.stats.clone(), host.clone());
+ tokio::spawn(async move {
+ if let Err(error) = relay(client, tunnel, stats, host, port, false).await {
+ tracing::debug!(%error, "forwarded connection ended");
+ }
+ });
+ }
+}
+
/// One stream through the peer; `socks` writes the SOCKS replies.
-async fn relay(
- mut client: TcpStream,
+async fn relay<C>(
+ mut client: C,
tunnel: Arc<Tunnel>,
stats: Arc<Stats>,
host: String,
port: u16,
socks: bool,
-) -> std::io::Result<()> {
+) -> std::io::Result<()>
+where
+ C: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
+{
let (id, mut from_peer) = tunnel.register();
if tunnel
.to_peer
@@ -321,7 +350,7 @@ async fn relay(
}
}
stats.active_connections.fetch_add(1, Ordering::SeqCst);
- let (mut reader, mut writer) = client.into_split();
+ let (mut reader, mut writer) = tokio::io::split(client);
let mut buf = vec![0u8; READ_CHUNK];
loop {
tokio::select! {
@@ -352,7 +381,10 @@ async fn relay(
Ok(())
}
-async fn write_socks_reply(client: &mut TcpStream, rep: u8) -> std::io::Result<()> {
+async fn write_socks_reply<C>(client: &mut C, rep: u8) -> std::io::Result<()>
+where
+ C: tokio::io::AsyncWrite + Unpin,
+{
client
.write_all(&[0x05, rep, 0x00, 0x01, 0, 0, 0, 0, 0, 0])
.await
diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
index b9726e5d86..13bfe744ad 100644
--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
@@ -2249,6 +2249,7 @@ dependencies = [
"cua-spacesd-client",
"cua-vmm",
"futures-util",
+ "hmac 0.12.1",
"http",
"http-body-util",
"humantime",
diff --git a/libs/cua-spacesd/tests/spaces-e2e/tests/daemon_spaces.rs b/libs/cua-spacesd/tests/spaces-e2e/tests/daemon_spaces.rs
index a1629d10cf..d34c268c22 100644
--- a/libs/cua-spacesd/tests/spaces-e2e/tests/daemon_spaces.rs
+++ b/libs/cua-spacesd/tests/spaces-e2e/tests/daemon_spaces.rs
@@ -208,6 +208,7 @@ async fn space_service_delegates_to_cua_spaces_and_the_passthrough_carries_crede
let msg = svc
.delete_space(pb::DeleteSpaceRequest {
space: added.id.clone(),
+ keep_children: false,
})
.await
.unwrap()
diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lock
index 833a9e0bee..df2f3b9330 100644
--- a/libs/cua/Cargo.lock
+++ b/libs/cua/Cargo.lock
@@ -2674,6 +2674,7 @@ dependencies = [
"cua-vmm",
"flate2",
"futures-util",
+ "hmac 0.12.1",
"http",
"http-body-util",
"humantime",
@@ -3617,6 +3618,7 @@ dependencies = [
"libc",
"pbjson-types",
"png",
+ "proptest",
"reqwest 0.12.28",
"serde",
"serde_json",
diff --git a/libs/cua/crates/cua-byoc/src/aws.rs b/libs/cua/crates/cua-byoc/src/aws.rs
index a83ff04693..407aa1f609 100644
--- a/libs/cua/crates/cua-byoc/src/aws.rs
+++ b/libs/cua/crates/cua-byoc/src/aws.rs
@@ -27,9 +27,10 @@ use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use aws_sdk_ec2::error::ProvideErrorMetadata;
use aws_sdk_ec2::types::{
- BlockDeviceMapping, EbsBlockDevice, Filter, HttpTokensState, InstanceMetadataEndpointState,
- InstanceMetadataOptionsRequest, InstanceType, LocationType, ResourceType, ShutdownBehavior,
- Tag, TagSpecification, VolumeType,
+ BlockDeviceMapping, CpuOptionsRequest, EbsBlockDevice, Filter, HttpTokensState,
+ InstanceMetadataEndpointState, InstanceMetadataOptionsRequest, InstanceType, LocationType,
+ NestedVirtualizationSpecification, ResourceType, ShutdownBehavior, Tag, TagSpecification,
+ VolumeType,
};
use cua_sandbox_core::Error;
use cua_sandbox_core::byoc::{CloudCredentials, CloudKind};
@@ -793,6 +794,13 @@ impl Aws {
.tag_specifications(spec_for(ResourceType::Instance))
.tag_specifications(spec_for(ResourceType::Volume))
.user_data(base64::engine::general_purpose::STANDARD.encode(&spec.user_data));
+ if spec.nested_virtualization {
+ req = req.cpu_options(
+ CpuOptionsRequest::builder()
+ .nested_virtualization(NestedVirtualizationSpecification::Enabled)
+ .build(),
+ );
+ }
if let Some(g) = group {
req = req.security_group_ids(g);
}
diff --git a/libs/cua/crates/cua-byoc/src/hosts.rs b/libs/cua/crates/cua-byoc/src/hosts.rs
index 49a137230d..a6a20ac6f8 100644
--- a/libs/cua/crates/cua-byoc/src/hosts.rs
+++ b/libs/cua/crates/cua-byoc/src/hosts.rs
@@ -175,6 +175,8 @@ pub struct HostBoot<'a> {
/// The cloud it runs in (`hetzner`): its relay machine says so, so the
/// pool knows it whichever machine coordinates.
pub provider: &'a str,
+ /// Install a local QEMU runtime for nested Spaces on this host.
+ pub nested_virtualization: bool,
/// Extra environment (`CUA_ENV=staging`), as `K=V` words.
pub env: &'a [String],
/// Its cost per hour (shown in the pool).
@@ -190,6 +192,34 @@ pub struct HostBoot<'a> {
pub prepull: &'a [String],
}
+/// Whether this EC2 instance type documents nested virtualization, so a
+/// host of it can run QEMU with KVM. Lives here, not in `aws`, because the
+/// `aws` module is behind a feature and the host launch code is not.
+pub fn supports_nested_virtualization(instance_type: &str) -> bool {
+ let family = instance_type.split('.').next().unwrap_or_default();
+ matches!(
+ family,
+ "c7i"
+ | "c7i-flex"
+ | "c8i"
+ | "c8i-flex"
+ | "c8id"
+ | "m7i"
+ | "m7i-flex"
+ | "m8i"
+ | "m8i-flex"
+ | "m8id"
+ | "r7i"
+ | "r7iz"
+ | "r8i"
+ | "r8i-flex"
+ | "r8id"
+ | "x8i"
+ | "i7i"
+ | "i7ie"
+ )
+}
+
fn sh_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', r"'\''"))
}
@@ -218,13 +248,19 @@ pub fn user_data(b: &HostBoot<'_>) -> String {
.filter(|kv| kv.contains('=') && !kv.contains('\'') && !kv.contains('\n'))
.map(|kv| format!("export {kv}\n"))
.collect();
+ let qemu = if b.nested_virtualization {
+ " qemu-system-x86 qemu-utils ovmf"
+ } else {
+ ""
+ };
let idle = if b.idle_poweroff_secs > 0 {
format!(
"# Backstop: power off after {secs} s with no Spaces (the scaler removes it sooner).\n\
cat > /usr/local/bin/cua-idle-poweroff <<'IDLE'\n\
#!/bin/bash\n\
# Spaces are containers (Docker, runc or gVisor) or VMs (QEMU).\n\
- busy() {{ [ \"$(docker ps -q 2>/dev/null | wc -l)\" -gt 0 ] || pgrep -x qemu-system-x86_64 >/dev/null || pgrep -x qemu-system-aarch64 >/dev/null; }}\n\
+ # Linux truncates long /proc comm names, so match QEMU command lines.\n\
+ busy() {{ [ \"$(docker ps -q 2>/dev/null | wc -l)\" -gt 0 ] || pgrep -f '[q]emu-system-(x86_64|aarch64)([[:space:]]|$)' >/dev/null; }}\n\
idle=0\n\
while sleep 60; do\n\
if busy; then idle=0; else idle=$((idle+60)); fi\n\
@@ -277,7 +313,7 @@ pub fn user_data(b: &HostBoot<'_>) -> String {
export HOME=/root DEBIAN_FRONTEND=noninteractive PATH=/usr/local/bin:$PATH\n\
# cua-spacesd links the X11 client libraries, a cua built where libopus\n\
# is installed links it; Docker runs container Spaces.\n\
- pkgs='libx11-6 libxext6 libxi6 libopus0'\n\
+ pkgs='libx11-6 libxext6 libxi6 libopus0{qemu}'\n\
command -v docker >/dev/null || pkgs=\"$pkgs docker.io\"\n\
for i in 1 2 3 4 5; do apt-get update -qq && apt-get install -y -qq $pkgs && break; sleep 5; done\n\
systemctl enable --now docker\n\
@@ -305,6 +341,7 @@ pub fn user_data(b: &HostBoot<'_>) -> String {
{prepull}\
echo 'cua: host ready'\n",
runsc_args = RUNSC_ARGS,
+ qemu = qemu,
expires = b.expires,
usd = b.usd_per_hour,
code = sh_quote(b.code),
@@ -938,6 +975,8 @@ impl Hosts {
name: &name,
relay: &relay.url,
provider: &req.provider,
+ nested_virtualization: api.name() == "aws"
+ && supports_nested_virtualization(&t.name),
env: &opts.env,
usd_per_hour: t.usd_per_hour,
ttl_secs: ttl,
@@ -957,6 +996,7 @@ impl Hosts {
ttl_secs: ttl,
image_parameter: opts.image_parameter.clone(),
peer_ports: opts.peer_ports,
+ nested_virtualization: api.name() == "aws" && supports_nested_virtualization(&t.name),
role: ROLE_HOST.into(),
region: region.clone(),
..Default::default()
@@ -1272,6 +1312,7 @@ mod tests {
name: "hetzner-1",
relay: "https://relay.cua.ai",
provider: "hetzner",
+ nested_virtualization: false,
env,
usd_per_hour: 0.0684,
ttl_secs: 3600,
@@ -1300,6 +1341,10 @@ mod tests {
assert!(ud.contains("shutdown -h now 'cua: this host reached its TTL'"));
assert!(ud.contains("echo 1800000000 > /etc/cua/expires"));
assert!(ud.contains("cua-idle-poweroff"), "idle backstop");
+ assert!(
+ ud.contains("pgrep -f '[q]emu-system-(x86_64|aarch64)"),
+ "idle guard must match QEMU command lines"
+ );
assert!(ud.contains("[ \"$idle\" -ge 1200 ]"));
assert!(ud.contains("export CUA_ENV=staging"));
// The mesh is on before setup, so the service keeps it; a person's
diff --git a/libs/cua/crates/cua-byoc/src/model.rs b/libs/cua/crates/cua-byoc/src/model.rs
index a7f8ac5e98..978d192fa7 100644
--- a/libs/cua/crates/cua-byoc/src/model.rs
+++ b/libs/cua/crates/cua-byoc/src/model.rs
@@ -523,6 +523,8 @@ pub struct ProvisionSpec {
/// group, whose ingress rules name the group itself; nothing is opened
/// to any address. `None`: the outbound-only group.
pub peer_ports: Option<(u16, u16)>,
+ /// Expose hardware virtualization extensions when the host type supports it.
+ pub nested_virtualization: bool,
/// [`ROLE_HOST`] (an elastic pool host: exactly `machine_type` in
/// `region`, user data passed through) or [`ROLE_SANDBOX`] / empty.
pub role: String,
diff --git a/libs/cua/crates/cua-cli/src/experiments_cmd.rs b/libs/cua/crates/cua-cli/src/experiments_cmd.rs
new file mode 100644
index 0000000000..a7d964fba2
--- /dev/null
+++ b/libs/cua/crates/cua-cli/src/experiments_cmd.rs
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! `cua experiments`: features that are still being built, one switch each.
+//!
+//! The switches live in the cua home, where the daemon and the Spaces apps
+//! read them. `CUA_EXPERIMENTS`
+//! turns experiments on (`secure-spaces`) or off (`-secure-spaces`) for one
+//! process.
+
+use std::io::Write;
+
+use clap::Subcommand;
+use cua_sdk::CuaError;
+use cua_vmm::experiments::{self, Gate};
+
+use crate::util::line;
+
+/// `cua experiments`.
+#[derive(Subcommand, Debug, Clone)]
+pub enum ExperimentsCmd {
+ /// Every experiment and whether it is on .
+ #[command(after_help = "Examples:
+ cua experiments list
+ cua experiments list --json")]
+ List,
+ /// Turn an experiment on.
+ #[command(after_help = "Examples:
+ cua experiments enable secure-spaces")]
+ Enable {
+ /// The experiment's name, as `cua experiments` lists it.
+ name: String,
+ },
+ /// Turn an experiment off. Nothing it made is deleted.
+ #[command(after_help = "Examples:
+ cua experiments disable secure-spaces")]
+ Disable {
+ /// The experiment's name, as `cua experiments` lists it.
+ name: String,
+ },
+}
+
+fn gate(name: &str) -> Result<Gate, CuaError> {
+ Gate::parse(name).ok_or_else(|| {
+ let names: Vec<_> = Gate::ALL.iter().map(|g| g.name()).collect();
+ CuaError::InvalidArgument(format!(
+ "no experiment named {name:?}; they are: {}",
+ names.join(", ")
+ ))
+ })
+}
+
+/// Runs `cmd`.
+pub fn run(cmd: &ExperimentsCmd, json: bool, out: &mut dyn Write) -> Result<i32, CuaError> {
+ let home = cua_home::cua_home();
+ match cmd {
+ ExperimentsCmd::List => list(&home, json, out),
+ ExperimentsCmd::Enable { name } | ExperimentsCmd::Disable { name } => {
+ let on = matches!(cmd, ExperimentsCmd::Enable { .. });
+ let g = gate(name)?;
+ experiments::set_switch(&home, g, on)
+ .map_err(|e| CuaError::Internal(format!("keep the {} switch: {e}", g.name())))?;
+ if json {
+ return list(&home, true, out);
+ }
+ line(
+ out,
+ format!("{} is {}.", g.title(), if on { "on" } else { "off" }),
+ );
+ // The environment can still decide for this process.
+ let now = experiments::enabled_in(&home, g);
+ if now != on {
+ line(
+ out,
+ format!(
+ "It stays {} here: {} says so.",
+ if now { "on" } else { "off" },
+ experiments::EXPERIMENTS_ENV
+ ),
+ );
+ }
+ Ok(0)
+ }
+ }
+}
+
+fn list(home: &std::path::Path, json: bool, out: &mut dyn Write) -> Result<i32, CuaError> {
+ if json {
+ let rows: Vec<_> = Gate::ALL
+ .iter()
+ .map(|g| {
+ serde_json::json!({
+ "name": g.name(),
+ "title": g.title(),
+ "summary": g.summary(),
+ "on": experiments::enabled_in(home, *g),
+ })
+ })
+ .collect();
+ line(out, serde_json::Value::Array(rows).to_string());
+ return Ok(0);
+ }
+ for g in Gate::ALL {
+ let state = if experiments::enabled_in(home, *g) {
+ "on "
+ } else {
+ "off"
+ };
+ line(out, format!("{state} {:<16} {}", g.name(), g.summary()));
+ }
+ line(out, "");
+ line(
+ out,
+ "Turn one on with `cua experiments enable <name>`; they are also in the app, Settings, Advanced, Labs.",
+ );
+ Ok(0)
+}
diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rs
index 06298d7764..e90e2bd0a0 100644
--- a/libs/cua/crates/cua-cli/src/host.rs
+++ b/libs/cua/crates/cua-cli/src/host.rs
@@ -371,6 +371,10 @@ Examples:
/// (that walk can take a moment with many Spaces).
#[arg(long)]
no_size: bool,
+ /// List child Spaces under their parent, indented (otherwise the
+ /// parent's row counts them).
+ #[arg(long)]
+ tree: bool,
},
/// Register a Space after a capabilities handshake with its cua-spacesd
/// (or, for another URL, an MCP initialize). Re-adding an address
@@ -461,6 +465,12 @@ Examples:
/// for good.
#[arg(long)]
durable: bool,
+ /// Let it make child Spaces of its own: `cua`, the SDKs and the
+ /// agent's tools in it create, list and delete Spaces that belong to
+ /// it, on this computer, never wider than it (`cua spaces children`).
+ /// Agent runs turn this on by themselves.
+ #[arg(long)]
+ children: bool,
/// A fork source (a "bake" Space): a local QEMU VM's guest RAM is a
/// shared file, so `cua sb checkpoint` takes milliseconds and forks
/// of its checkpoints share its pages. Other kinds ignore it.
@@ -484,14 +494,40 @@ Examples:
/// with `--durable`.
#[arg(long, value_name = "KEY=VALUE")]
label: Vec<String>,
- /// Block this destination from the guest's first instruction (IP,
- /// CIDR or `all`; repeat for more). Enforced by the host, outside
- /// the guest. See `cua spaces egress`.
- #[arg(long, value_name = "ADDR|CIDR|all")]
+ /// Its network: `internet` (the default: the internet and its own
+ /// tree; this computer, your local network, cloud metadata and other
+ /// trees are blocked), `none`, `localhost:5432,3000` (also this
+ /// computer's localhost on those ports), `lan` (also your local
+ /// network), `custom` / `custom:none` (with --allow/--deny), or
+ /// `unprotected` (No protection). Enforced by the host, outside the
+ /// guest. See `cua network`.
+ #[arg(long, value_name = "PRESET")]
+ network: Option<String>,
+ /// Block this destination (IP, CIDR or `all`; repeat for more).
+ #[arg(
+ long = "deny",
+ visible_alias = "egress-deny",
+ value_name = "ADDR|CIDR|all"
+ )]
egress_deny: Vec<String>,
- /// Keep this destination reachable where --egress-deny blocks it.
- #[arg(long, value_name = "ADDR|CIDR|all")]
+ /// Allow this destination, also where a block covers it (IP or CIDR;
+ /// repeat for more).
+ #[arg(
+ long = "allow",
+ visible_alias = "egress-allow",
+ value_name = "ADDR|CIDR"
+ )]
egress_allow: Vec<String>,
+ /// Create it as a child of this Space: it joins the parent's tree
+ /// (they reach each other) and its network is no more open than the
+ /// parent's. With `--parent`, the children are deleted, stopped and
+ /// suspended with it.
+ #[arg(long, value_name = "SPACE")]
+ parent: Option<String>,
+ /// With --parent: let its network be more open than its parent's
+ /// (recorded on the Space).
+ #[arg(long, requires = "parent")]
+ widen: bool,
},
/// Keep Spaces of one image ready where the elastic pool puts them, so
/// the next creates of that shape start in a fraction of a second
@@ -574,6 +610,64 @@ Examples:
#[arg(long, conflicts_with_all = ["deny", "allow"])]
clear: bool,
},
+ /// Let a Space make child Spaces of its own, or stop it. While on,
+ /// `cua`, the SDKs and the agent's tools inside it create, list and
+ /// delete Spaces that belong to it: on this computer, with its egress
+ /// rules, ending no later than it, through a channel only it can reach.
+ /// Off ends its capability at once; children it made keep running
+ /// until deleted or their lifetime ends.
+ #[command(after_help = "Examples:
+ cua spaces children studio on
+ cua spaces children studio off")]
+ Children {
+ /// Space id or name.
+ space: String,
+ /// `on` or `off`.
+ #[arg(value_parser = ["on", "off"])]
+ state: String,
+ },
+ /// Show or set a tree's budget: how many child Spaces, vCPUs and memory
+ /// its children may hold at once, and what they may cost. A child that
+ /// does not fit is refused with what is left. Without flags it shows the
+ /// budget and what the children use.
+ #[command(after_help = "Examples:
+ cua spaces budget studio
+ cua spaces budget studio --spaces 32 --cpus 64 --memory 131072
+ cua spaces budget studio --usd-per-hour 5 --usd-total 50
+ cua spaces budget studio --clear")]
+ Budget {
+ /// Any Space of the tree (id or name).
+ space: String,
+ /// Child Spaces at once (default 16).
+ #[arg(long)]
+ spaces: Option<u32>,
+ /// vCPUs at once (default 16).
+ #[arg(long)]
+ cpus: Option<u32>,
+ /// Memory at once, in MiB (default 32768).
+ #[arg(long, value_name = "MIB")]
+ memory: Option<u64>,
+ /// Cost per hour in linked clouds, in dollars (default 2).
+ #[arg(long, value_name = "USD")]
+ usd_per_hour: Option<f64>,
+ /// Cost in total, in dollars (default: none).
+ #[arg(long, value_name = "USD")]
+ usd_total: Option<f64>,
+ /// Back to the defaults.
+ #[arg(long, conflicts_with_all = ["spaces", "cpus", "memory", "usd_per_hour", "usd_total"])]
+ clear: bool,
+ },
+ /// List child Spaces whose parent is gone or out of reach. The daemon
+ /// ends a child only on proof its parent is gone, after a grace period;
+ /// the others stay until you delete them or their lifetime ends.
+ #[command(after_help = "Examples:
+ cua spaces orphans")]
+ Orphans,
+ /// Keep a command running in a Space: started again when it exits or
+ /// fails its health check (with a backoff), started when the Space
+ /// boots, its output kept in a log file in the Space.
+ #[command(subcommand)]
+ Service(ServiceCmd),
/// Cancel a create that is still running (here, in the daemon, or in
/// another terminal): it stops and what it made is removed. Finished
/// image downloads stay cached. Ctrl-C during `cua spaces create` does
@@ -607,6 +701,10 @@ Examples:
/// Skip the confirmation (required without a terminal).
#[arg(long, short)]
force: bool,
+ /// Keep its child Spaces: they become top-level Spaces and keep
+ /// running (otherwise they are deleted first).
+ #[arg(long)]
+ keep_children: bool,
},
/// Turn a Space off: a local VM (QEMU or Lume) or a Space one of your
/// computers provides is stopped, keeping its disk and freeing its
@@ -1036,6 +1134,7 @@ pub async fn run_spaces_sdk(
) -> Result<i32, CuaError> {
let spaces = cua.spaces();
match cmd {
+ SpacesCmd::Service(cmd) => run_service(&spaces, cmd, json, out).await?,
SpacesCmd::Add {
url,
token,
@@ -1274,6 +1373,119 @@ pub async fn run_spaces_sdk(
}
}
}
+ SpacesCmd::Budget {
+ space,
+ spaces: max_spaces,
+ cpus,
+ memory,
+ usd_per_hour,
+ usd_total,
+ clear,
+ } => {
+ let setting = clear
+ || max_spaces.is_some()
+ || cpus.is_some()
+ || memory.is_some()
+ || usd_per_hour.is_some()
+ || usd_total.is_some();
+ let b = if setting {
+ let current = if clear {
+ cua_sdk::TreeBudgetLimits::default()
+ } else {
+ let now = spaces.tree_budget(space.clone()).await?.set;
+ cua_sdk::TreeBudgetLimits {
+ max_spaces: max_spaces.or(now.max_spaces),
+ max_vcpus: cpus.or(now.max_vcpus),
+ max_memory_mb: memory.or(now.max_memory_mb),
+ usd_per_hour: usd_per_hour.or(now.usd_per_hour),
+ usd_total: usd_total.or(now.usd_total),
+ }
+ };
+ spaces.set_tree_budget(space, current).await?
+ } else {
+ spaces.tree_budget(space).await?
+ };
+ if json {
+ line(
+ out,
+ serde_json::json!({
+ "root": b.root,
+ "limits": {"spaces": b.max_spaces, "cpus": b.max_vcpus,
+ "memory_mb": b.max_memory_mb,
+ "usd_per_hour": b.usd_per_hour, "usd_total": b.usd_total},
+ "used": {"spaces": b.spaces, "cpus": b.vcpus, "memory_mb": b.memory_mb,
+ "usd_per_hour": b.usd_per_hour_used, "usd_spent": b.usd_spent},
+ })
+ .to_string(),
+ );
+ } else {
+ line(out, format!("Tree of {}:", b.root));
+ line(
+ out,
+ format!(" Spaces {:>6} of {}", b.spaces, b.max_spaces),
+ );
+ line(out, format!(" vCPUs {:>6} of {}", b.vcpus, b.max_vcpus));
+ line(
+ out,
+ format!(" Memory {:>6} of {} MiB", b.memory_mb, b.max_memory_mb),
+ );
+ line(
+ out,
+ format!(
+ " Cost ${:.2}/h of ${:.2}/h",
+ b.usd_per_hour_used, b.usd_per_hour
+ ),
+ );
+ match b.usd_total {
+ Some(t) => line(out, format!(" Spent ${:.2} of ${t:.2}", b.usd_spent)),
+ None => line(out, format!(" Spent ${:.2}", b.usd_spent)),
+ }
+ }
+ }
+ SpacesCmd::Orphans => {
+ let list = spaces.orphans().await?;
+ if json {
+ let rows: Vec<serde_json::Value> = list
+ .iter()
+ .map(|o| {
+ serde_json::json!({"space": o.space, "parent": o.parent,
+ "state": o.state, "why": o.why, "ends_in_secs": o.ends_in_secs})
+ })
+ .collect();
+ line(out, serde_json::json!({ "orphans": rows }).to_string());
+ } else if list.is_empty() {
+ line(out, "No orphaned child Spaces.");
+ } else {
+ for o in &list {
+ let when = if o.state == "ending" {
+ format!("ends in {}s", o.ends_in_secs)
+ } else {
+ "kept".into()
+ };
+ line(out, format!("{:<32} {:<10} {}", o.space, when, o.why));
+ }
+ }
+ }
+ SpacesCmd::Children { space, state } => {
+ let on = state == "on";
+ spaces.set_children(space.clone(), on).await?;
+ if json {
+ line(
+ out,
+ serde_json::json!({"space": space, "children": on}).to_string(),
+ );
+ } else if on {
+ line(
+ out,
+ format!(
+ "{space} can make child Spaces of its own (inside it: `cua spaces \
+ create`, or the create_space tool)."
+ ),
+ );
+ } else {
+ line(out, format!("{space} can no longer make child Spaces."));
+ }
+ }
SpacesCmd::Egress {
space,
deny,
@@ -1378,22 +1590,33 @@ pub async fn run_spaces_sdk(
disk_gb,
gpu,
durable,
+ children,
forkable,
instance_type,
region,
volumes,
label,
+ network,
egress_deny,
egress_allow,
+ parent,
+ widen,
} => {
let volumes = parse_volumes(&volumes)?;
let labels = parse_labels(&label)?;
- let egress = (!egress_deny.is_empty() || !egress_allow.is_empty()).then(|| {
- cua_sdk::EgressPolicy {
- allow: egress_allow.clone(),
- deny: egress_deny.clone(),
- }
- });
+ // One shape for the network: a preset and the lists.
+ let network_settings =
+ (network.is_some() || !egress_deny.is_empty() || !egress_allow.is_empty())
+ .then(|| {
+ cua_spaces::network::parse_network(
+ network.as_deref().unwrap_or("internet"),
+ &egress_allow,
+ &egress_deny,
+ )
+ .map(cua_sdk::NetworkSettings::from)
+ .map_err(CuaError::from)
+ })
+ .transpose()?;
if !(1..=8).contains(&count) {
return Err(CuaError::InvalidArgument(format!(
"--count {count}: create 1 to 8 Spaces at a time"
@@ -1426,7 +1649,10 @@ pub async fn run_spaces_sdk(
region: region.clone(),
volumes: volumes.clone(),
labels: labels.clone(),
- egress: egress.clone(),
+ network_settings: network_settings.clone(),
+ parent: parent.clone(),
+ widen: widen.then_some(true),
+ children: children.then_some(true),
..Default::default()
};
// Durable Spaces are kept by the coordinator of your machines,
@@ -1561,7 +1787,11 @@ pub async fn run_spaces_sdk(
return Ok(first_failure);
}
}
- SpacesCmd::Delete { space, force } => {
+ SpacesCmd::Delete {
+ space,
+ force,
+ keep_children,
+ } => {
use crate::sandbox::{DeleteConfirmation, confirm_delete};
use std::io::IsTerminal as _;
match confirm_delete(force, std::io::stdin().is_terminal(), || {
@@ -1593,7 +1823,7 @@ pub async fn run_spaces_sdk(
.await?;
format!("Deleted the durable Space {name} (it is not created again).")
}
- _ => spaces.delete(space.clone()).await?,
+ _ => spaces.delete_tree(space.clone(), keep_children).await?,
};
if json {
line(
@@ -3307,7 +3537,7 @@ pub(crate) fn grouped_lines_for_tests(
list: &[cua_spaces::SpaceInfo],
columns: Option<&crate::resources_view::Columns<'_>>,
) -> Vec<String> {
- grouped_lines_with(list, columns, &Default::default())
+ grouped_lines_with(list, columns, &Default::default(), false)
}
#[cfg(test)]
@@ -3315,16 +3545,21 @@ fn grouped_lines(
list: &[cua_spaces::SpaceInfo],
load: &std::collections::HashMap<String, String>,
) -> Vec<String> {
- grouped_lines_with(list, None, load)
+ grouped_lines_with(list, None, load, false)
}
/// [`grouped_lines`] with the CPU, MEMORY and DISK ON THIS MAC columns (and
/// their header) when `columns` is given; their `own_machine` (this
/// install's relay machine id) is the row tagged "(this computer)".
+///
+/// Child Spaces ([`cua_spaces::tree`]) are not rows of their own: their
+/// parent's row counts them (`+2 children`). `tree` lists them instead,
+/// indented under their parent.
fn grouped_lines_with(
list: &[cua_spaces::SpaceInfo],
columns: Option<&crate::resources_view::Columns<'_>>,
load: &std::collections::HashMap<String, String>,
+ tree: bool,
) -> Vec<String> {
use crate::resources_view::{CPU_WIDTH, MEMORY_WIDTH};
let this_computer = columns.and_then(|c| c.own_machine.as_deref());
@@ -3389,12 +3624,33 @@ fn grouped_lines_with(
if columns.is_some() && !list.is_empty() {
out.push(crate::resources_view::header(48));
}
- for s in list.iter().filter(|s| s.host.is_empty()) {
+ let listed_child =
+ |s: &cua_spaces::SpaceInfo| parent_of(s).is_some_and(|p| list.iter().any(|o| o.id == p));
+ for s in list
+ .iter()
+ .filter(|s| s.host.is_empty() && !listed_child(s))
+ {
+ let below = space_subtree(list, &s.id);
+ let first = if tree || below.is_empty() {
+ row(s, "")
+ } else {
+ format!(
+ "{} (+{} child{})",
+ row(s, "").trim_end(),
+ below.len(),
+ if below.len() == 1 { "" } else { "ren" }
+ )
+ };
// A Space in your cloud names its cloud ("AWS · us-west-2").
if s.host_name.is_empty() {
- out.push(row(s, ""));
+ out.push(first);
} else {
- out.push(format!("{} (on {})", row(s, ""), s.host_name));
+ out.push(format!("{first} (on {})", s.host_name));
+ }
+ if tree {
+ for (c, depth) in &below {
+ out.push(row(c, &format!("{}└ ", " ".repeat(*depth - 1))));
+ }
}
// A relay host's Spaces name its machine id; a direct host's name
// its Space id.
@@ -3407,6 +3663,7 @@ fn grouped_lines_with(
}
for c in list.iter().filter(|c| {
!c.host.is_empty()
+ && !listed_child(c)
&& !list
.iter()
.any(|s| s.id == format!("relay:{}", c.host) || s.id == c.host)
@@ -3424,6 +3681,37 @@ fn grouped_lines_with(
out
}
+/// The parent a listed Space was created from, if any.
+fn parent_of(s: &cua_spaces::SpaceInfo) -> Option<&str> {
+ s.tree.as_ref().and_then(|t| t.parent.as_deref())
+}
+
+/// The listed Spaces below `id`, depth first, with their depth under it
+/// (1: a child). Safe against a cycle.
+fn space_subtree<'a>(
+ list: &'a [cua_spaces::SpaceInfo],
+ id: &str,
+) -> Vec<(&'a cua_spaces::SpaceInfo, usize)> {
+ fn walk<'a>(
+ list: &'a [cua_spaces::SpaceInfo],
+ id: &str,
+ depth: usize,
+ seen: &mut std::collections::BTreeSet<String>,
+ out: &mut Vec<(&'a cua_spaces::SpaceInfo, usize)>,
+ ) {
+ for c in list.iter().filter(|c| parent_of(c) == Some(id)) {
+ if seen.insert(c.id.clone()) {
+ out.push((c, depth));
+ walk(list, &c.id, depth + 1, seen, out);
+ }
+ }
+ }
+ let mut out = Vec::new();
+ let mut seen = std::collections::BTreeSet::from([id.to_string()]);
+ walk(list, id, 1, &mut seen, &mut out);
+ out
+}
+
/// `cua spaces add <addr> --host`: registers a machine that provides
/// Spaces over its direct address, in this cua home's registry (the one the
/// daemon and `cua mcp` use).
@@ -3539,6 +3827,7 @@ pub async fn run_spaces(
relay,
label,
no_size,
+ tree,
} = cmd
else {
return Err(CuaError::Internal(
@@ -3613,7 +3902,7 @@ pub async fn run_spaces(
if list.is_empty() {
line(out, "No Spaces.");
}
- for l in grouped_lines_with(&list, Some(&columns), &load) {
+ for l in grouped_lines_with(&list, Some(&columns), &load, tree) {
line(out, l);
}
for d in durable
@@ -3914,6 +4203,38 @@ mod tests {
}
other => panic!("{other:?}"),
}
+ // The network flags: a preset, the lists, a parent and --widen.
+ match parse(&[
+ "create",
+ "linux",
+ "--network",
+ "localhost:5432",
+ "--allow",
+ "10.0.5.0/24",
+ "--deny",
+ "8.8.8.8",
+ "--parent",
+ "studio",
+ "--widen",
+ ]) {
+ SpacesCmd::Create {
+ network,
+ egress_deny,
+ egress_allow,
+ parent,
+ widen,
+ ..
+ } => {
+ assert_eq!(network.as_deref(), Some("localhost:5432"));
+ assert_eq!(egress_allow, ["10.0.5.0/24"]);
+ assert_eq!(egress_deny, ["8.8.8.8"]);
+ assert_eq!(parent.as_deref(), Some("studio"));
+ assert!(widen);
+ }
+ other => panic!("{other:?}"),
+ }
+ // --widen only goes with --parent.
+ assert!(parse_spaces(&["create", "linux", "--widen"]).is_err());
}
#[test]
@@ -3966,6 +4287,8 @@ mod tests {
created_at_unix: 0,
egress: Default::default(),
egress_enforced: None,
+ network: None,
+ tree: None,
sharing: None,
};
let mut list = vec![
@@ -4028,6 +4351,8 @@ mod tests {
created_at_unix: 0,
egress: Default::default(),
egress_enforced: None,
+ network: None,
+ tree: None,
sharing: None,
stop_reason: String::new(),
};
@@ -4097,6 +4422,8 @@ mod tests {
created_at_unix: 0,
egress: Default::default(),
egress_enforced: None,
+ network: None,
+ tree: None,
sharing: None,
stop_reason: String::new(),
}
@@ -4159,6 +4486,34 @@ mod tests {
lines[0].ends_with("· 2 running · 40% CPU · 55% memory"),
"{lines:?}"
);
+ // Child Spaces: counted on their parent's row, or listed under it
+ // with `--tree`.
+ let child = |id: &str, parent: &str, depth: u32| {
+ let mut s = space(id, "");
+ s.provider = cua_spaces::Provider::Local;
+ s.tree = Some(cua_spaces::tree::TreeLink {
+ parent: Some(parent.into()),
+ root: Some("local:root".into()),
+ depth,
+ origin: "child".into(),
+ });
+ s
+ };
+ let list = [
+ space("local:root", ""),
+ child("local:kid", "local:root", 1),
+ child("local:grandkid", "local:kid", 2),
+ space("local:alone", ""),
+ ];
+ let lines = grouped_lines(&list, &none);
+ assert_eq!(lines.len(), 2, "{lines:?}");
+ assert!(lines[0].ends_with("(+2 children)"), "{lines:?}");
+ assert!(!lines[1].contains("child"), "{lines:?}");
+ let lines = grouped_lines_with(&list, None, &none, true);
+ assert_eq!(lines.len(), 4, "{lines:?}");
+ assert!(lines[1].starts_with("└ local:kid"), "{lines:?}");
+ assert!(lines[2].starts_with(" └ local:grandkid"), "{lines:?}");
+ assert!(lines[3].starts_with("local:alone"), "{lines:?}");
}
#[test]
@@ -4294,6 +4649,8 @@ mod tests {
created_at_unix: 0,
egress: Default::default(),
egress_enforced: None,
+ network: None,
+ tree: None,
sharing: None,
stop_reason: String::new(),
};
@@ -4591,6 +4948,7 @@ mod tests {
relay: None,
label: vec![],
no_size: false,
+ tree: false,
},
&home,
Some(Arc::new(StaticToken("acct".into()))),
@@ -4626,6 +4984,7 @@ mod tests {
relay: Some(relay.url.clone()),
label: vec![],
no_size: true,
+ tree: false,
},
&elsewhere.path().join(".cua"),
Some(Arc::new(StaticToken("acct".into()))),
@@ -4649,6 +5008,7 @@ mod tests {
relay: None,
no_size: true,
label: vec![],
+ tree: false,
},
&home,
Some(Arc::new(StaticToken("acct".into()))),
@@ -5982,3 +6342,293 @@ mod tests {
assert_eq!(seen(&home, &manager), ((true, true), (true, true), false));
}
}
+
+/// `cua spaces ls` inside a Space: the Space's own children (and theirs),
+/// as its spawn channel lists them.
+pub async fn run_children_ls(
+ cua: &Arc<cua_sdk::Cua>,
+ json: bool,
+ out: &mut dyn Write,
+) -> Result<i32, CuaError> {
+ let list = cua.spaces().list().await?;
+ let parent_of = |s: &cua_sdk::SpaceInfo| {
+ s.parent
+ .clone()
+ .or_else(|| s.labels.get("cua.parent").cloned())
+ .unwrap_or_default()
+ };
+ if json {
+ let rows: Vec<serde_json::Value> = list
+ .iter()
+ .map(|s| {
+ serde_json::json!({
+ "id": s.id,
+ "name": if s.display_name.is_empty() { &s.name } else { &s.display_name },
+ "parent": parent_of(s),
+ "power": s.power,
+ "image": s.image,
+ "expires_at_unix": s.expires_at_unix,
+ })
+ })
+ .collect();
+ line(out, serde_json::json!({ "spaces": rows }).to_string());
+ return Ok(0);
+ }
+ if list.is_empty() {
+ line(out, "No child Spaces.");
+ return Ok(0);
+ }
+ line(
+ out,
+ format!("{:<28} {:<36} {:<10} PARENT", "NAME", "ID", "STATE"),
+ );
+ for s in &list {
+ let name = if s.display_name.is_empty() {
+ &s.name
+ } else {
+ &s.display_name
+ };
+ let state = if s.power.is_empty() {
+ "-"
+ } else {
+ s.power.as_str()
+ };
+ line(
+ out,
+ format!("{name:<28} {:<36} {state:<10} {}", s.id, parent_of(s)),
+ );
+ }
+ Ok(0)
+}
+
+/// `cua spaces service`.
+#[derive(Debug, Clone, Subcommand)]
+pub enum ServiceCmd {
+ /// Keep a command running (replaces a service of that name).
+ #[command(after_help = "Examples:
+ cua spaces service add studio web -- python3 -m http.server 8080
+ cua spaces service add studio web --http http://127.0.0.1:8080/ -- python3 -m http.server 8080
+ cua spaces service add studio job --restart on-failure -- ./run.sh")]
+ Add {
+ /// Space id or name.
+ space: String,
+ /// Service name (lowercase letters, digits, `-`, `_`, `.`).
+ name: String,
+ /// When to start it again: always, on-failure or never.
+ #[arg(long, default_value = "always", value_parser = ["always", "on-failure", "never"])]
+ restart: String,
+ /// Health check: a URL that answers 2xx or 3xx.
+ #[arg(long, conflicts_with_all = ["tcp", "check"])]
+ http: Option<String>,
+ /// Health check: `host:port` that accepts a connection.
+ #[arg(long, conflicts_with_all = ["http", "check"])]
+ tcp: Option<String>,
+ /// Health check: a shell command that exits 0 when healthy.
+ #[arg(long, conflicts_with_all = ["http", "tcp"])]
+ check: Option<String>,
+ /// Do not start it when the Space boots.
+ #[arg(long)]
+ no_boot: bool,
+ /// `KEY=VALUE` for its environment (repeat for more).
+ #[arg(long = "env", value_name = "KEY=VALUE")]
+ env: Vec<String>,
+ /// Working directory in the Space.
+ #[arg(long)]
+ cwd: Option<String>,
+ /// The command (after `--`).
+ #[arg(last = true, required = true)]
+ command: Vec<String>,
+ },
+ /// List a Space's services.
+ #[command(after_help = "Examples:
+ cua spaces service ls studio")]
+ Ls {
+ /// Space id or name.
+ space: String,
+ },
+ /// Show the end of a service's log.
+ #[command(after_help = "Examples:
+ cua spaces service logs studio web")]
+ Logs {
+ /// Space id or name.
+ space: String,
+ /// Service name.
+ name: String,
+ /// Bytes from the end.
+ #[arg(long, default_value_t = 65536)]
+ tail: u64,
+ },
+ /// Start a stopped service.
+ #[command(after_help = "Examples:
+ cua spaces service start studio web")]
+ Start {
+ /// Space id or name.
+ space: String,
+ /// Service name.
+ name: String,
+ },
+ /// Stop a service and keep it stopped.
+ #[command(after_help = "Examples:
+ cua spaces service stop studio web")]
+ Stop {
+ /// Space id or name.
+ space: String,
+ /// Service name.
+ name: String,
+ },
+ /// Restart a service.
+ #[command(after_help = "Examples:
+ cua spaces service restart studio web")]
+ Restart {
+ /// Space id or name.
+ space: String,
+ /// Service name.
+ name: String,
+ },
+ /// Stop a service and forget it.
+ #[command(after_help = "Examples:
+ cua spaces service rm studio web")]
+ Rm {
+ /// Space id or name.
+ space: String,
+ /// Service name.
+ name: String,
+ },
+}
+
+fn service_line(s: &cua_sdk::SpaceServiceInfo) -> String {
+ let mut l = format!("{:<20} {:<10}", s.name, s.state);
+ if s.pid > 0 {
+ l.push_str(&format!(" pid {}", s.pid));
+ }
+ if s.restarts > 0 {
+ l.push_str(&format!(", {} restarts", s.restarts));
+ }
+ if !s.last_end.is_empty() {
+ l.push_str(&format!(", last {}", s.last_end));
+ }
+ if !s.probe_error.is_empty() {
+ l.push_str(&format!(", check: {}", s.probe_error));
+ }
+ l.push_str(&format!(" {}", s.command));
+ l
+}
+
+/// `cua spaces service ...`.
+pub async fn run_service(
+ spaces: &cua_sdk::Spaces,
+ cmd: ServiceCmd,
+ json: bool,
+ out: &mut dyn Write,
+) -> Result<(), CuaError> {
+ let one = |s: cua_sdk::SpaceServiceInfo, out: &mut dyn Write| {
+ if json {
+ line(out, serde_json::to_string(&s).unwrap_or_default());
+ } else {
+ line(out, service_line(&s));
+ }
+ };
+ match cmd {
+ ServiceCmd::Add {
+ space,
+ name,
+ restart,
+ http,
+ tcp,
+ check,
+ no_boot,
+ env,
+ cwd,
+ command,
+ } => {
+ let env = env
+ .iter()
+ .map(|kv| {
+ kv.split_once('=')
+ .map(|(k, v)| (k.to_owned(), v.to_owned()))
+ .ok_or_else(|| {
+ CuaError::InvalidArgument(format!("--env {kv:?}: use KEY=VALUE"))
+ })
+ })
+ .collect::<Result<_, _>>()?;
+ let probe = (http.is_some() || tcp.is_some() || check.is_some()).then(|| {
+ cua_sdk::SpaceServiceProbe {
+ http,
+ tcp,
+ command: check,
+ ..Default::default()
+ }
+ });
+ let def = cua_sdk::SpaceServiceDef {
+ name,
+ command: shell_words(&command),
+ env,
+ cwd,
+ restart: Some(restart),
+ probe,
+ start_on_boot: Some(!no_boot),
+ };
+ let s = spaces.space(space).await?;
+ one(s.put_service(def).await?, out);
+ }
+ ServiceCmd::Ls { space } => {
+ let list = spaces.space(space).await?.kept_services().await?;
+ if json {
+ line(out, serde_json::json!({ "services": list }).to_string());
+ } else if list.is_empty() {
+ line(out, "No services.");
+ } else {
+ for s in &list {
+ line(out, service_line(s));
+ }
+ }
+ }
+ ServiceCmd::Logs { space, name, tail } => {
+ let text = spaces
+ .space(space)
+ .await?
+ .service_logs(name, Some(tail))
+ .await?;
+ let _ = out.write_all(text.as_bytes());
+ }
+ ServiceCmd::Start { space, name } => {
+ one(spaces.space(space).await?.start_service(name).await?, out);
+ }
+ ServiceCmd::Stop { space, name } => {
+ one(spaces.space(space).await?.stop_service(name).await?, out);
+ }
+ ServiceCmd::Restart { space, name } => {
+ one(spaces.space(space).await?.restart_service(name).await?, out);
+ }
+ ServiceCmd::Rm { space, name } => {
+ spaces
+ .space(space)
+ .await?
+ .delete_service(name.clone())
+ .await?;
+ if json {
+ line(out, serde_json::json!({ "deleted": name }).to_string());
+ } else {
+ line(out, format!("Removed service {name}."));
+ }
+ }
+ }
+ Ok(())
+}
+
+/// Joins argv into one shell line, quoting words that need it.
+fn shell_words(argv: &[String]) -> String {
+ argv.iter()
+ .map(|w| {
+ if !w.is_empty()
+ && w.bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b"-_./:=@%+,".contains(&b))
+ {
+ w.clone()
+ } else {
+ format!("'{}'", w.replace('\'', "'\\''"))
+ }
+ })
+ .collect::<Vec<_>>()
+ .join(" ")
+}
diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rs
index 86bf0956f3..344aa0fcec 100644
--- a/libs/cua/crates/cua-cli/src/lib.rs
+++ b/libs/cua/crates/cua-cli/src/lib.rs
@@ -45,6 +45,7 @@ mod do_cmd;
mod doctor;
pub mod drive_cmd;
mod dump_docs;
+mod experiments_cmd;
pub mod extension;
mod host;
mod image_build;
@@ -53,6 +54,7 @@ mod jobs_cmd;
pub mod keyvault_cmd;
mod mcp;
mod member_cmd;
+mod network_cmd;
pub mod onboard;
mod persistent_cmd;
pub mod prewarm;
@@ -253,6 +255,14 @@ enum Command {
/// that Spaces fork from in under a second. Works in any directory;
/// layers already built are reused.
Build(build_cmd::BuildArgs),
+ /// What a Space can reach on the network, and changing it: `show`,
+ /// `set`, `log`. An experiment: see `cua experiments`.
+ #[command(subcommand)]
+ Network(network_cmd::NetworkCmd),
+ /// Features that are still being built, one switch each: `list`,
+ /// `enable`, `disable`.
+ #[command(subcommand)]
+ Experiments(experiments_cmd::ExperimentsCmd),
/// Images: local OCI pull/build/push.
#[command(subcommand, visible_alias = "img")]
Image(ImageCmd),
@@ -1224,6 +1234,14 @@ async fn open(cli: &Cli, with_session: bool) -> Result<Arc<Cua>, CuaError> {
let _ = TOPOLOGY.set("daemon");
return Cua::connect(cli.daemon.clone(), cli.daemon_token.clone());
}
+ // Inside a Space with children on: its spawn channel, where every
+ // Space made is a child of this one.
+ if let Some(cua_daemon::client::DaemonAddress::Url { url, token }) =
+ cua_daemon::client::spawn_channel()
+ {
+ let _ = TOPOLOGY.set("space");
+ return Cua::connect(Some(url), Some(token));
+ }
// A daemon that is starting is waited for (bounded), never raced with
// a runtime of this process's own (a `cua volume mount` would mount
// here, not in the daemon).
@@ -1328,8 +1346,16 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
cua_home::experimental::TEAMS_UNAVAILABLE.into(),
));
}
+ // An experiment that is off is refused before any sign-in, daemon or
+ // relay call.
+ if let Some(g) = uses_experiment(&cli.command)
+ && !cua_vmm::experiments::enabled(g)
+ {
+ return Err(CuaError::InvalidArgument(g.off_message()));
+ }
// Commands that need no SDK handle.
match &cli.command {
+ Command::Experiments(cmd) => return experiments_cmd::run(cmd, json, out),
Command::Images(cmd) => {
return match cmd {
ImagesCmd::Ls { all, os, browser } => catalog::print_list(
@@ -1732,6 +1758,7 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
relay: None,
label: vec![],
no_size: false,
+ tree: false,
}),
..cli
};
@@ -1794,6 +1821,10 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
| host::SpacesCmd::Resize { .. }
| host::SpacesCmd::Start { .. }
| host::SpacesCmd::Egress { .. }
+ | host::SpacesCmd::Children { .. }
+ | host::SpacesCmd::Budget { .. }
+ | host::SpacesCmd::Orphans
+ | host::SpacesCmd::Service(..)
| host::SpacesCmd::Prewarm { .. }
| host::SpacesCmd::Share { .. }
| host::SpacesCmd::Unshare { .. }
@@ -1824,6 +1855,7 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
relay: None,
label: vec![],
no_size: false,
+ tree: false,
}),
..cli
};
@@ -1855,12 +1887,26 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
let res = host::run_spaces_sdk(&cua, cmd, json, out).await;
res.map_err(host::explain_share_presence_failure)
}
+ Command::Network(cmd) => {
+ let rest = Cli {
+ command: Command::Spaces(host::SpacesCmd::Ls {
+ relay: None,
+ label: vec![],
+ no_size: false,
+ tree: false,
+ }),
+ ..cli
+ };
+ let cua = open(&rest, false).await?;
+ return network_cmd::run(&cua, cmd, json, out).await;
+ }
Command::Build(a) => {
let rest = Cli {
command: Command::Spaces(host::SpacesCmd::Ls {
relay: None,
label: vec![],
no_size: false,
+ tree: false,
}),
..cli
};
@@ -1879,6 +1925,7 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
relay: None,
label: vec![],
no_size: false,
+ tree: false,
}),
..cli
};
@@ -1894,6 +1941,7 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
relay: None,
label: vec![],
no_size: false,
+ tree: false,
}),
embedded: true,
..cli
@@ -1913,6 +1961,13 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
)
.await;
}
+ Command::Spaces(host::SpacesCmd::Ls { .. })
+ if cli.daemon.is_none() && cua_daemon::client::spawn_channel().is_some() =>
+ {
+ // Inside a Space: its own children, through its spawn channel.
+ let cua = open(&cli, false).await?;
+ return host::run_children_ls(&cua, json, out).await;
+ }
Command::Spaces(cmd) => {
// Relay machines only when signed in; the registry either way.
let tokens: Option<Arc<dyn cua_host::AccountTokens>> =
@@ -2271,6 +2326,7 @@ async fn run_sdk(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
| Command::Host(_)
| Command::Run(_)
| Command::Build(_)
+ | Command::Network(_)
| Command::Jobs(_)
| Command::Computers
| Command::Machines(_)
@@ -2290,6 +2346,7 @@ async fn run_sdk(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
| Command::Bench(_)
| Command::Keyvault(_)
| Command::Images(_)
+ | Command::Experiments(_)
| Command::DumpDocs { .. } => unreachable!("handled above"),
}
Ok(0)
@@ -2756,11 +2813,82 @@ fn uses_teams(cmd: &Command) -> bool {
}
}
+/// The experiment a command belongs to, if any: the commands and flags that
+/// are new with it. They are hidden from help, and refused with how to turn
+/// the experiment on, until it is on.
+fn uses_experiment(cmd: &Command) -> Option<cua_vmm::experiments::Gate> {
+ use cua_vmm::experiments::Gate;
+ match cmd {
+ Command::Network(_) => Some(Gate::SecureSpaces),
+ Command::Spaces(host::SpacesCmd::Create {
+ network,
+ parent,
+ widen,
+ children,
+ ..
+ }) => {
+ if network.is_some() {
+ Some(Gate::SecureSpaces)
+ } else if parent.is_some() || *widen || *children {
+ Some(Gate::ChildSpaces)
+ } else {
+ None
+ }
+ }
+ Command::Spaces(
+ host::SpacesCmd::Ls { tree: true, .. }
+ | host::SpacesCmd::Delete {
+ keep_children: true,
+ ..
+ }
+ | host::SpacesCmd::Children { .. }
+ | host::SpacesCmd::Budget { .. }
+ | host::SpacesCmd::Orphans
+ | host::SpacesCmd::Service(host::ServiceCmd::Add { .. }),
+ ) => Some(Gate::ChildSpaces),
+ _ => None,
+ }
+}
+
/// The clap command `cua` parses with. Teams are experimental: without
/// them, `cua team` and `cua host pair --team` stay out of help (they still
/// parse, and are refused with a short reason).
fn cli_command(teams: bool) -> clap::Command {
- let cmd = Cli::command();
+ cli_command_for(teams, |_| true)
+}
+
+/// [`cli_command`] with the experiments `on` says are on; the commands and
+/// flags of the others stay out of help (they still parse, and are refused
+/// with how to turn the experiment on).
+fn cli_command_for(teams: bool, on: impl Fn(cua_vmm::experiments::Gate) -> bool) -> clap::Command {
+ use cua_vmm::experiments::Gate;
+ let mut cmd = without_teams_if(Cli::command(), teams);
+ if !on(Gate::SecureSpaces) {
+ cmd = cmd
+ .mut_subcommand("network", |c| c.hide(true))
+ .mut_subcommand("spaces", |s| {
+ s.mut_subcommand("create", |c| c.mut_arg("network", |a| a.hide(true)))
+ });
+ }
+ if !on(Gate::ChildSpaces) {
+ cmd = cmd.mut_subcommand("spaces", |s| {
+ s.mut_subcommand("create", |c| {
+ c.mut_arg("parent", |a| a.hide(true))
+ .mut_arg("widen", |a| a.hide(true))
+ .mut_arg("children", |a| a.hide(true))
+ })
+ .mut_subcommand("ls", |c| c.mut_arg("tree", |a| a.hide(true)))
+ .mut_subcommand("delete", |c| c.mut_arg("keep_children", |a| a.hide(true)))
+ .mut_subcommand("children", |c| c.hide(true))
+ .mut_subcommand("budget", |c| c.hide(true))
+ .mut_subcommand("orphans", |c| c.hide(true))
+ .mut_subcommand("service", |c| c.hide(true))
+ });
+ }
+ cmd
+}
+
+fn without_teams_if(cmd: clap::Command, teams: bool) -> clap::Command {
if teams {
return cmd;
}
@@ -2940,7 +3068,10 @@ pub fn main() {
// process (the daemon) uses that channel's and environment's home.
unsafe { cua_home::env::pin_home() };
let matches = channel_command(
- cli_command(cua_home::experimental::teams_enabled()),
+ cli_command_for(
+ cua_home::experimental::teams_enabled(),
+ cua_vmm::experiments::enabled,
+ ),
channel,
)
.get_matches();
diff --git a/libs/cua/crates/cua-cli/src/network_cmd.rs b/libs/cua/crates/cua-cli/src/network_cmd.rs
new file mode 100644
index 0000000000..834735a0aa
--- /dev/null
+++ b/libs/cua/crates/cua-cli/src/network_cmd.rs
@@ -0,0 +1,259 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! `cua network`: what a Space can reach, and changing it.
+//!
+//! - `show`: its preset, what it opens beyond Internet only, where the
+//! rules are enforced (outside the guest) or why it has no network, and
+//! what is always blocked;
+//! - `set`: a new preset and lists (a child stays within its parent's
+//! unless `--widen`; `--tree` gives its children the same);
+//! - `log`: what it tried to reach and was blocked.
+
+use std::io::Write;
+use std::sync::Arc;
+
+use clap::Subcommand;
+use cua_sdk::{Cua, CuaError, SpaceNetworkInfo};
+
+use crate::util::line;
+
+/// `cua network`.
+#[derive(Subcommand, Debug, Clone)]
+pub enum NetworkCmd {
+ /// What a Space can reach: its preset, what it opens, where it is
+ /// enforced, and what is always blocked.
+ #[command(after_help = "Examples:
+ cua network show studio
+ cua network show local:studio --json")]
+ Show {
+ /// Space id or name.
+ space: String,
+ },
+ /// Change what a Space can reach. A child Space stays within its
+ /// parent's unless `--widen`.
+ #[command(after_help = "Examples:
+ # This computer's Postgres and dev server only
+ cua network set studio --network localhost:5432,3000
+ # Your local network too
+ cua network set studio --network lan
+ # Only these destinations
+ cua network set studio --network custom:none --allow 140.82.112.0/20
+ # Back to the default
+ cua network set studio --network internet")]
+ Set {
+ /// Space id or name.
+ space: String,
+ /// `internet`, `none`, `localhost:<ports>` (or `localhost:all`),
+ /// `lan`, `custom`, `custom:none` or `unprotected` (No protection).
+ #[arg(long, value_name = "PRESET")]
+ network: String,
+ /// Allow this destination (IP or CIDR; repeat for more).
+ #[arg(long, value_name = "ADDR|CIDR")]
+ allow: Vec<String>,
+ /// Block this destination (IP, CIDR or `all`; repeat for more).
+ #[arg(long, value_name = "ADDR|CIDR|all")]
+ deny: Vec<String>,
+ /// A child Space: let it reach more than its parent (recorded on
+ /// the Space).
+ #[arg(long)]
+ widen: bool,
+ /// Its child Spaces get the same settings (each within its parent's).
+ #[arg(long)]
+ tree: bool,
+ },
+ /// What a Space tried to reach and was blocked, most recent first.
+ #[command(after_help = "Examples:
+ cua network log studio")]
+ Log {
+ /// Space id or name.
+ space: String,
+ },
+}
+
+/// The one-time line about the new defaults, before a Space's first `show`
+/// after the update.
+const NOTICE: &str = "New: Spaces now reach the internet only. This Space can't reach this \
+ computer, your local network or other Spaces unless you allow it \
+ (cua network set <space> --network ...).";
+
+/// Runs `cmd` against `cua`'s Spaces.
+pub async fn run(
+ cua: &Arc<Cua>,
+ cmd: NetworkCmd,
+ json: bool,
+ out: &mut dyn Write,
+) -> Result<i32, CuaError> {
+ let spaces = cua.spaces();
+ match cmd {
+ NetworkCmd::Show { space } => {
+ let info = spaces.network(space.clone()).await?;
+ if json {
+ line(out, info_json(&info).to_string());
+ } else {
+ if info.notice_pending {
+ line(out, NOTICE);
+ }
+ for l in show_lines(&space, &info) {
+ line(out, l);
+ }
+ }
+ if info.notice_pending {
+ // Shown once (in JSON too: `notice_pending` said it).
+ spaces.ack_network_notice(space.clone()).await?;
+ }
+ }
+ NetworkCmd::Set {
+ space,
+ network,
+ allow,
+ deny,
+ widen,
+ tree,
+ } => {
+ let settings = cua_spaces::network::parse_network(&network, &allow, &deny)?;
+ let r = spaces
+ .set_network(space.clone(), settings.into(), widen, tree)
+ .await?;
+ if json {
+ line(
+ out,
+ serde_json::json!({
+ "applied": r.applied,
+ "network": info_json(&r.network),
+ })
+ .to_string(),
+ );
+ } else {
+ line(
+ out,
+ format!(
+ "{space}: {}. {}",
+ r.network.summary,
+ if r.applied == "now" {
+ "In effect now."
+ } else {
+ "Applies when it starts next (`cua spaces stop` then `start`)."
+ }
+ ),
+ );
+ for w in &r.network.widenings {
+ line(out, format!(" ⚠ {w}"));
+ }
+ if let Some(note) = &r.network.note {
+ line(out, format!(" {note}"));
+ }
+ }
+ }
+ NetworkCmd::Log { space } => {
+ let _ = space;
+ line(
+ out,
+ "Blocked connections are not reported yet. `cua network show` says what this \
+ Space can reach.",
+ );
+ }
+ }
+ Ok(0)
+}
+
+/// The JSON `show` prints.
+fn info_json(i: &SpaceNetworkInfo) -> serde_json::Value {
+ serde_json::json!({
+ "settings": {
+ "preset": i.settings.preset,
+ "localhost_ports": i.settings.localhost_ports,
+ "all_localhost_ports": i.settings.all_localhost_ports,
+ "allow": i.settings.allow,
+ "deny": i.settings.deny,
+ "custom_base": i.settings.custom_base,
+ "widened_by": i.settings.widened_by,
+ },
+ "summary": i.summary,
+ "widenings": i.widenings,
+ "enforcement": i.enforcement,
+ "point": i.point,
+ "note": i.note,
+ "parent": i.parent,
+ "root": i.root,
+ "always_blocked": i.always_blocked,
+ "notice_pending": i.notice_pending,
+ })
+}
+
+/// `show`'s lines, in plain words.
+fn show_lines(space: &str, i: &SpaceNetworkInfo) -> Vec<String> {
+ let mut out = vec![format!("{space}: {}", i.summary)];
+ if !i.settings.allow.is_empty() {
+ out.push(format!(" Allowed: {}", i.settings.allow.join(", ")));
+ }
+ if !i.settings.deny.is_empty() {
+ out.push(format!(" Blocked: {}", i.settings.deny.join(", ")));
+ }
+ for w in &i.widenings {
+ out.push(format!(" ⚠ {w}"));
+ }
+ if let Some(p) = &i.parent {
+ out.push(format!(" Within its parent {p}"));
+ }
+ if let Some(w) = &i.settings.widened_by {
+ out.push(format!(" Allowed more than its parent (by {w})"));
+ }
+ match i.enforcement.as_str() {
+ "enforced" => out.push(format!(
+ " Enforced by this computer, outside the Space: {}",
+ i.point
+ )),
+ "no_network" => out.push(" No network: this runtime can't protect it yet".into()),
+ "open" => out.push(" No protection: chosen by you".into()),
+ "refused" => out.push(format!(" Can't start like this: {}", i.point)),
+ _ if !i.point.is_empty() => out.push(format!(" {}", i.point)),
+ _ => {}
+ }
+ if let Some(n) = &i.note {
+ out.push(format!(" {n}"));
+ }
+ out.push(" Always blocked:".into());
+ for b in &i.always_blocked {
+ out.push(format!(" {b}"));
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn show_says_it_in_plain_words() {
+ let info = SpaceNetworkInfo {
+ settings: cua_sdk::NetworkSettings {
+ preset: "localhost".into(),
+ localhost_ports: vec![5432],
+ deny: vec!["8.8.8.8".into()],
+ ..Default::default()
+ },
+ summary: "Allow this computer's localhost (ports 5432)".into(),
+ widenings: vec!["Allows this computer's localhost (ports 5432)".into()],
+ enforcement: "enforced".into(),
+ point: "nftables".into(),
+ always_blocked: vec!["Cloud metadata".into()],
+ ..Default::default()
+ };
+ let l = show_lines("studio", &info).join("\n");
+ assert!(
+ l.starts_with("studio: Allow this computer's localhost"),
+ "{l}"
+ );
+ assert!(l.contains("Blocked: 8.8.8.8"), "{l}");
+ assert!(l.contains("⚠ Allows this computer's localhost"), "{l}");
+ assert!(
+ l.contains("Enforced by this computer, outside the Space"),
+ "{l}"
+ );
+ assert!(l.contains("Always blocked:\n Cloud metadata"), "{l}");
+ let j = info_json(&info);
+ assert_eq!(j["settings"]["localhost_ports"][0], 5432);
+ assert_eq!(j["enforcement"], "enforced");
+ }
+}
diff --git a/libs/cua/crates/cua-cli/src/resources_view.rs b/libs/cua/crates/cua-cli/src/resources_view.rs
index 418ab6a5d5..6233ddb92f 100644
--- a/libs/cua/crates/cua-cli/src/resources_view.rs
+++ b/libs/cua/crates/cua-cli/src/resources_view.rs
@@ -265,6 +265,8 @@ mod tests {
created_at_unix: 0,
egress: Default::default(),
egress_enforced: None,
+ network: None,
+ tree: None,
sharing: None,
volumes: Vec::new(),
}
diff --git a/libs/cua/crates/cua-cli/src/risky.rs b/libs/cua/crates/cua-cli/src/risky.rs
index f1cb7dc88a..4e3a6690f6 100644
--- a/libs/cua/crates/cua-cli/src/risky.rs
+++ b/libs/cua/crates/cua-cli/src/risky.rs
@@ -184,6 +184,13 @@ fn is_passwords_app(name: &str) -> bool {
pub fn tool_risk(tool: &str, arguments: &Value) -> Option<&'static str> {
match tool {
"space_bash" => command_risk(arguments["command"].as_str()?),
+ // A background job runs a command (or a condition's shell) like
+ // `space_bash` does; reading, cancelling and listing run nothing.
+ "space_job" if arguments["action"] == "start" => command_risk(
+ arguments["command"]
+ .as_str()
+ .or_else(|| arguments["until"]["command"].as_str())?,
+ ),
"call_tool" => {
let inner = arguments["tool"].as_str()?;
let args = &arguments["arguments"];
@@ -417,6 +424,21 @@ mod tests {
),
Some("uninstall an app")
);
+ // A background job is as risky as the command it runs.
+ assert_eq!(
+ tool_risk(
+ "space_job",
+ &json!({"space": "this-mac", "action": "start", "command": "brew zap slack"})
+ ),
+ Some("uninstall an app")
+ );
+ assert_eq!(
+ tool_risk(
+ "space_job",
+ &json!({"space": "this-mac", "action": "logs", "job": "j1"})
+ ),
+ None
+ );
assert_eq!(tool_risk("list_spaces", &json!({})), None);
}
diff --git a/libs/cua/crates/cua-cli/src/sandbox.rs b/libs/cua/crates/cua-cli/src/sandbox.rs
index d483b5b669..ea6dfbad6b 100644
--- a/libs/cua/crates/cua-cli/src/sandbox.rs
+++ b/libs/cua/crates/cua-cli/src/sandbox.rs
@@ -4260,7 +4260,10 @@ mod tests {
r("python:3.12", Some("slim")),
Err(CuaError::InvalidArgument(_))
));
- let published = |x: &str| cua_image::catalog::find(x).is_none_or(|e| e.published);
+ // Derived on the user's Mac (the developer tools image) counts as available.
+ let published = |x: &str| {
+ cua_image::catalog::find(x).is_none_or(|e| e.published || e.derived_from.is_some())
+ };
for (got, want, os) in [
(
r("linux", Some("slim")),
diff --git a/libs/cua/crates/cua-cli/tests/cache.rs b/libs/cua/crates/cua-cli/tests/cache.rs
index e2bfe2421d..dc488995d4 100644
--- a/libs/cua/crates/cua-cli/tests/cache.rs
+++ b/libs/cua/crates/cua-cli/tests/cache.rs
@@ -55,6 +55,7 @@ fn qemu_state(h: &Home, name: &str, disk: &Path, created_at: u64) {
ssh: None,
restrict_network: false,
egress: None,
+ network: None,
netns: false,
pasta_pid: None,
extra_args: vec![],
diff --git a/libs/cua/crates/cua-daemon/Cargo.toml b/libs/cua/crates/cua-daemon/Cargo.toml
index 15964ed3eb..48a2162911 100644
--- a/libs/cua/crates/cua-daemon/Cargo.toml
+++ b/libs/cua/crates/cua-daemon/Cargo.toml
@@ -72,6 +72,8 @@ tokio-tungstenite.workspace = true
futures-util.workspace = true
bytes.workspace = true
base64.workspace = true
+# The spawn capability's MAC (child Spaces).
+hmac = "0.12"
rand.workspace = true
sha2.workspace = true
thiserror.workspace = true
diff --git a/libs/cua/crates/cua-daemon/src/children/api.rs b/libs/cua/crates/cua-daemon/src/children/api.rs
new file mode 100644
index 0000000000..8aa042f96d
--- /dev/null
+++ b/libs/cua/crates/cua-daemon/src/children/api.rs
@@ -0,0 +1,1031 @@
+//! The API a Space reaches on its spawn channel: `SpaceService` and
+//! `DaemonService` of the cua daemon, so `cua`, the SDKs and the agent's
+//! tools work in a Space unchanged, but answered for this Space's own
+//! subtree and nothing else.
+//!
+//! - Every call names Spaces inside the caller's subtree. A sibling, an
+//! ancestor, another tree or a guessed id is "not found", word for word
+//! what a missing Space gets.
+//! - A create or fork makes a child of the caller: one level deeper (up to
+//! its tree's limit), on this computer, with the caller's egress rules,
+//! and a lifetime no longer than the caller's (4 hours by default).
+//! - Everything else (other computers, clouds, volumes, shares, the
+//! daemon's own token and settings) is refused.
+//!
+//! The caller is the Space whose channel the request came in on (the host
+//! opened it), and the capability it presents must be that Space's live
+//! one ([`super::capability`]).
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use cua_proto::daemon::v1::{
+ self as pb, daemon_service_server::DaemonService, space_service_server::SpaceService,
+};
+use serde_json::Value;
+use tonic::{Request, Response, Status};
+
+use super::capability::Claims;
+use super::tree;
+use crate::server::{Shared, Svc};
+use cua_sandbox_core::placement::On;
+
+type R<T> = std::result::Result<Response<T>, Status>;
+
+/// The label that mirrors a child's parent. The record's tree fields
+/// (`SpaceMeta.parent`, `root`, `depth`) are what counts on this computer.
+pub const LABEL_PARENT: &str = cua_spaces::tree::PARENT_LABEL;
+/// The root of the tree, for a child placed on another computer or a cloud
+/// (whose registry does not hold its parent).
+pub const LABEL_ROOT: &str = "cua.root";
+/// The depth, for a child placed elsewhere (0 for a Space a person made).
+pub const LABEL_DEPTH: &str = "cua.depth";
+
+/// A child's lifetime when its parent has none.
+pub const DEFAULT_CHILD_LIFETIME: Duration = Duration::from_secs(4 * 3600);
+
+/// The one answer for a Space outside the caller's subtree.
+pub fn not_found(query: &str) -> Status {
+ Status::not_found(format!("no Space {query:?} among this Space's children"))
+}
+
+fn refused(what: &str) -> Status {
+ Status::permission_denied(format!(
+ "a Space can only {what}; ask the owner to do this outside the Space"
+ ))
+}
+
+fn deny<T>() -> R<T> {
+ Err(refused("create, list and manage its own children"))
+}
+
+/// The scoped services of one Space's channel.
+#[derive(Clone)]
+pub struct Scoped {
+ pub(crate) shared: Arc<Shared>,
+ /// The Space the channel belongs to.
+ pub(crate) space: String,
+}
+
+/// The verified capability of a request (put there by the channel's auth).
+fn claims<T>(req: &Request<T>) -> Result<Claims, Status> {
+ req.extensions()
+ .get::<Claims>()
+ .cloned()
+ .ok_or_else(|| Status::unauthenticated(super::capability::Refusal::Malformed.message()))
+}
+
+impl Scoped {
+ fn owner(&self) -> Svc {
+ Svc(self.shared.clone())
+ }
+
+ fn spaces(&self) -> &cua_spaces::Spaces {
+ self.shared.runtime.spaces()
+ }
+
+ /// Parent links of every registered Space.
+ pub(crate) fn links(&self) -> tree::Links {
+ links_of(self.spaces())
+ }
+
+ /// The registered records below the caller.
+ fn subtree_records(&self) -> Result<Vec<pb::Space>, Status> {
+ let links = self.links();
+ let below: std::collections::BTreeSet<String> =
+ tree::subtree(&links, &self.space).into_iter().collect();
+ let mut records: Vec<pb::Space> = self
+ .spaces()
+ .registry()
+ .list()
+ .map_err(|e| Status::internal(e.to_string()))?
+ .into_iter()
+ .filter(|r| below.contains(&r.id))
+ .collect();
+ for r in &mut records {
+ (r.power, r.power_state) = self.spaces().power_of(&r.id);
+ r.stop_reason = self.spaces().stop_reason_of(&r.id);
+ }
+ self.spaces().fill_records(&mut records);
+ crate::spaces_svc::imp::mark_children(self.spaces(), &mut records);
+ Ok(records)
+ }
+
+ /// The Space `query` names among the caller's descendants: by id, then
+ /// by name. Nothing outside the subtree is ever matched.
+ pub(crate) fn resolve(&self, query: &str) -> Result<pb::Space, Status> {
+ let q = query.trim();
+ if q.is_empty() {
+ return Err(Status::invalid_argument("name a Space"));
+ }
+ let records = self.subtree_records()?;
+ if let Some(r) = records.iter().find(|r| r.id == q) {
+ return Ok(r.clone());
+ }
+ let named: Vec<&pb::Space> = records
+ .iter()
+ .filter(|r| r.name == q || (!r.display_name.is_empty() && r.display_name == q))
+ .collect();
+ match named.as_slice() {
+ [one] => Ok((*one).clone()),
+ [] => Err(not_found(q)),
+ many => Err(Status::failed_precondition(format!(
+ "{q:?} names {} children: use an id ({})",
+ many.len(),
+ many.iter()
+ .map(|r| r.id.as_str())
+ .collect::<Vec<_>>()
+ .join(", ")
+ ))),
+ }
+ }
+
+ /// The caller's own record (its egress, lifetime).
+ fn own_meta(&self) -> Option<cua_spaces::registry::SpaceMeta> {
+ self.spaces().registry().meta(&self.space)
+ }
+
+ /// The request a create of a child becomes: refused when it asks for
+ /// more than a child may have, otherwise placed under the caller.
+ pub(crate) fn child_request(
+ &self,
+ claims: &Claims,
+ mut r: pb::CreateSpaceRequest,
+ ) -> Result<pb::CreateSpaceRequest, Status> {
+ let depth = claims.depth.saturating_add(1);
+ if depth > claims.max_depth {
+ return Err(Status::resource_exhausted(format!(
+ "this Space is {} level(s) below its tree's root and the tree allows {}: \
+ it cannot make children",
+ claims.depth, claims.max_depth
+ )));
+ }
+ // Whether it may make children of its own is the tree's depth's
+ // call ([`Scoped::adopt`]), never the request's.
+ r.children = None;
+ // Its place in the tree is this Space's, and its network stays
+ // within this Space's: neither is the request's to say.
+ if r.widen {
+ return Err(refused(
+ "make children whose network is no more open than its own",
+ ));
+ }
+ if !r.parent.trim().is_empty() && r.parent != self.space {
+ return Err(Status::invalid_argument(
+ "a child's parent is the Space that makes it; leave parent empty",
+ ));
+ }
+ // Where: this computer (the default), the least-loaded of the
+ // owner's computers and linked clouds (`auto`), one of the owner's
+ // machines (`host:<m>`), or a linked cloud. This daemon creates it
+ // with the owner's own sign-in and cloud links; the Space asking
+ // never holds them.
+ let location = r.location.trim().to_owned();
+ let on = if location.is_empty() {
+ On::Local
+ } else {
+ On::parse_or_host(&location).map_err(|e| Status::invalid_argument(e.message))?
+ };
+ match &on {
+ On::Local | On::Auto | On::Host(_) | On::Provider(_) => {}
+ On::Cloud | On::Direct(_) | On::Relay(_) => {
+ return Err(Status::failed_precondition(format!(
+ "a child goes on this computer, `auto`, one of your computers \
+ (`host:<name>`) or a linked cloud; on={location:?} is not one"
+ )));
+ }
+ }
+ r.location = on.to_string();
+ let local = matches!(on, On::Local);
+ if r.reuse {
+ return Err(Status::invalid_argument(
+ "a child is always a new Space (reuse is not available here)",
+ ));
+ }
+ if r.durable {
+ return Err(Status::invalid_argument(
+ "a child lives as long as its parent allows (durable is not available here)",
+ ));
+ }
+ if !r.volumes.is_empty() {
+ return Err(refused(
+ "mount volumes in children that it was given itself",
+ ));
+ }
+ if local && (!r.instance_type.is_empty() || !r.region.is_empty()) {
+ return Err(Status::failed_precondition(
+ "a machine type or region needs on=auto or a linked cloud",
+ ));
+ }
+ if let Some(k) = r.labels.keys().find(|k| k.starts_with("cua.")) {
+ return Err(Status::invalid_argument(format!(
+ "label {k:?} is reserved (labels starting with \"cua.\" are set by Cua)"
+ )));
+ }
+ // Egress: the parent's rules, never wider.
+ let own = self.own_meta().map(|m| m.egress).unwrap_or_default();
+ let asked = r.egress.take().map(|e| cua_spaces::egress::EgressPolicy {
+ allow: e.allow,
+ deny: e.deny,
+ });
+ let egress = match asked {
+ None => own,
+ Some(a) if a.is_empty() => own,
+ Some(a) if own.is_empty() || a == own => a,
+ Some(_) => {
+ return Err(Status::permission_denied(
+ "a child keeps its parent's egress rules; leave egress empty",
+ ));
+ }
+ };
+ if !egress.is_empty() {
+ r.egress = Some(pb::EgressPolicy {
+ allow: egress.allow,
+ deny: egress.deny,
+ });
+ }
+ if r.name.trim().is_empty() {
+ r.name = self.next_child_name("c");
+ }
+ if local {
+ // This computer records it in the caller's tree: the record's
+ // parent, root and depth, its network no more open than the
+ // caller's, the tree's own network.
+ r.parent = self.space.clone();
+ self.allow_depth(claims);
+ } else {
+ // Another computer or a cloud does not hold the caller's record:
+ // the network goes with the request, cut down to the caller's,
+ // and labels carry the tree.
+ let asked = match r.network_settings.as_ref() {
+ Some(n) => cua_spaces::network::from_pb(n)
+ .map_err(|e| Status::invalid_argument(e.to_string()))?,
+ None => cua_spaces::network::NetworkSettings::internet(),
+ };
+ let own = self.own_network();
+ r.network_settings = Some(cua_spaces::network::to_pb(&asked.intersect(&own)));
+ r.labels.insert(LABEL_PARENT.into(), self.space.clone());
+ r.labels.insert(LABEL_ROOT.into(), claims.root.clone());
+ r.labels.insert(LABEL_DEPTH.into(), depth.to_string());
+ }
+ Ok(r)
+ }
+
+ /// The caller's network settings (or what it would move to).
+ fn own_network(&self) -> cua_spaces::network::NetworkSettings {
+ match self.own_meta() {
+ Some(m) => m
+ .network
+ .clone()
+ .unwrap_or_else(|| cua_spaces::network::migrate_meta(&m, false)),
+ None => cua_spaces::network::NetworkSettings::internet(),
+ }
+ }
+
+ /// The tree's depth limit is at least what the owner granted the
+ /// caller's capability, so the record's own limit does not refuse a
+ /// child the capability allows.
+ fn allow_depth(&self, claims: &Claims) {
+ let want = claims.max_depth.min(cua_spaces::tree::MAX_DEPTH);
+ let limit =
+ cua_spaces::tree::depth_limit(self.spaces().registry().meta(&claims.root).as_ref());
+ if limit < want {
+ let _ = self
+ .spaces()
+ .registry()
+ .update_meta(&claims.root, |m| m.depth_limit = Some(want));
+ }
+ }
+
+ /// `<parent name>.<prefix><n>`, the first one not taken.
+ fn next_child_name(&self, prefix: &str) -> String {
+ let base = self
+ .space
+ .split_once(':')
+ .map(|(_, n)| n)
+ .unwrap_or(&self.space)
+ .to_owned();
+ let taken: std::collections::BTreeSet<String> = self
+ .spaces()
+ .registry()
+ .list()
+ .unwrap_or_default()
+ .into_iter()
+ .map(|r| r.name)
+ .collect();
+ (1..)
+ .map(|n| format!("{base}.{prefix}{n}"))
+ .find(|n| !taken.contains(n))
+ .expect("an unused name")
+ }
+
+ /// After a child exists: its lifetime (no longer than the caller's) and,
+ /// when the tree allows another level, its own children turned on.
+ pub(crate) fn adopt(&self, claims: &Claims, child: &str) {
+ let spaces = self.spaces();
+ let remaining = spaces.lifetime(&self.space).map(|l| {
+ l.expires_at()
+ .duration_since(std::time::SystemTime::now())
+ .unwrap_or_default()
+ });
+ let life = remaining
+ .map(|r| r.min(DEFAULT_CHILD_LIFETIME))
+ .unwrap_or(DEFAULT_CHILD_LIFETIME)
+ .max(Duration::from_secs(60));
+ if let Err(e) =
+ spaces.set_lifetime(child, life, Some(cua_sandbox_core::LocalExpiry::Delete))
+ {
+ tracing::warn!(child, error = %e, "could not set a child's lifetime");
+ }
+ if claims.depth.saturating_add(1) < claims.max_depth
+ && let Err(e) = spaces.set_children(child, true)
+ {
+ tracing::warn!(child, error = %e, "could not turn on a child's own children");
+ }
+ }
+
+ /// Deletes `id` and everything below it, deepest first.
+ async fn delete_tree(&self, id: &str) -> Result<String, Status> {
+ let links = self.links();
+ let mut order = tree::subtree(&links, id);
+ order.push(id.to_owned());
+ let mut last = String::new();
+ for victim in order {
+ let r = self
+ .owner()
+ .delete_space(Request::new(pb::DeleteSpaceRequest {
+ space: victim.clone(),
+ keep_children: false,
+ }))
+ .await;
+ if let Some(a) = self.shared.spawn_authority() {
+ a.revoke(&victim);
+ }
+ let _ = self.spaces().set_children(&victim, false);
+ match r {
+ Ok(m) => last = m.into_inner().message,
+ Err(s) if s.code() == tonic::Code::NotFound => {}
+ Err(s) => return Err(s),
+ }
+ }
+ Ok(last)
+ }
+
+ /// The tools a Space may call on its children, and the argument that
+ /// names the child.
+ fn tool_target(name: &str) -> Option<&'static str> {
+ Some(match name {
+ "stop_space" | "start_space" | "space_bash" | "space_write" | "upload" | "download"
+ | "list_tools" | "call_tool" | "list_space_windows" => "space",
+ _ => return None,
+ })
+ }
+
+ /// Rewrites a tool call's Space argument to the child's id, refusing
+ /// tools that are not a child's and Spaces outside the subtree.
+ pub(crate) fn scoped_tool_args(&self, name: &str, args: &mut Value) -> Result<(), Status> {
+ let Some(key) = Self::tool_target(name) else {
+ return Err(refused("use its children's own tools"));
+ };
+ let q = args
+ .get(key)
+ .and_then(Value::as_str)
+ .ok_or_else(|| Status::invalid_argument(format!("{name} needs `{key}`")))?
+ .to_owned();
+ let child = self.resolve(&q)?;
+ args[key] = Value::String(child.id);
+ Ok(())
+ }
+}
+
+/// What a create of a child asks of its tree's budget (a child on this
+/// machine costs nothing per hour).
+fn ask_of(r: &pb::CreateSpaceRequest) -> super::budget::Ask {
+ super::budget::Ask {
+ vcpus: if r.cpus == 0 { 2 } else { r.cpus },
+ memory_mb: if r.memory_mb == 0 { 4096 } else { r.memory_mb },
+ usd_per_hour: 0.0,
+ }
+}
+
+/// What a child placed off this computer costs per hour: what the elastic
+/// pool would add to place it (0 when it fits on a machine already running).
+/// A child the pool can't place is refused with the pool's reason.
+async fn priced(
+ spaces: &cua_spaces::Spaces,
+ r: &pb::CreateSpaceRequest,
+ mut ask: super::budget::Ask,
+) -> Result<super::budget::Ask, Status> {
+ if r.location == "local" {
+ return Ok(ask);
+ }
+ let req = cua_spaces::elastic::ElasticRequest {
+ image: r.image.clone(),
+ kind: r.kind.clone(),
+ cpus: Some(ask.vcpus),
+ memory_mb: Some(ask.memory_mb),
+ count: 1,
+ ..Default::default()
+ };
+ match spaces.elastic_plan(&[req]).await {
+ Ok(p) => {
+ if let Some(u) = p.plan.unplaced.first() {
+ return Err(Status::resource_exhausted(format!(
+ "no machine can take this child: {}",
+ u.reason
+ )));
+ }
+ ask.usd_per_hour = p.plan.added_usd_per_hour.max(0.0);
+ Ok(ask)
+ }
+ // Without a pool view (no linked cloud), it goes on a machine of
+ // yours: free here; the create itself says if none can take it.
+ Err(_) => Ok(ask),
+ }
+}
+
+/// A tree's budget and use, as the API reports it.
+pub(crate) fn tree_budget(shared: &Shared, root: &str) -> pb::TreeBudget {
+ let Some(c) = shared.children.as_deref() else {
+ return pb::TreeBudget {
+ root: root.to_owned(),
+ ..Default::default()
+ };
+ };
+ let set = c.budget.budget(root);
+ let l = set.effective();
+ let used = super::tree_usage(shared, root);
+ let reserved = c.budget.reserved(root);
+ pb::TreeBudget {
+ root: root.to_owned(),
+ set: Some(pb::TreeBudgetLimits {
+ max_spaces: set.max_spaces,
+ max_vcpus: set.max_vcpus,
+ max_memory_mb: set.max_memory_mb,
+ usd_per_hour: set.usd_per_hour,
+ usd_total: set.usd_total,
+ }),
+ max_spaces: l.max_spaces,
+ max_vcpus: l.max_vcpus,
+ max_memory_mb: l.max_memory_mb,
+ usd_per_hour: l.usd_per_hour,
+ usd_total: l.usd_total,
+ spaces: used.spaces + reserved.spaces,
+ vcpus: used.vcpus + reserved.vcpus,
+ memory_mb: used.memory_mb + reserved.memory_mb,
+ usd_per_hour_used: used.usd_per_hour + reserved.usd_per_hour,
+ usd_spent: used.usd_spent,
+ }
+}
+
+/// Parent links from the registry's records.
+pub(crate) fn links_of(spaces: &cua_spaces::Spaces) -> tree::Links {
+ let meta = spaces.registry().all_meta();
+ let ids: Vec<String> = spaces
+ .registry()
+ .list()
+ .unwrap_or_default()
+ .into_iter()
+ .map(|r| r.id)
+ .collect();
+ tree::Links(
+ ids.into_iter()
+ .map(|id| {
+ let parent = meta.get(&id).and_then(parent_of);
+ (id, parent)
+ })
+ .collect(),
+ )
+}
+
+/// A record's parent: its tree field, else the label a child placed from
+/// another computer carries.
+pub(crate) fn parent_of(m: &cua_spaces::registry::SpaceMeta) -> Option<String> {
+ m.parent
+ .clone()
+ .or_else(|| m.labels.get(LABEL_PARENT).cloned())
+}
+
+/// The tree position of `id`: (root, depth). A Space a person made is its
+/// own root at depth 0.
+pub(crate) fn position(spaces: &cua_spaces::Spaces, id: &str) -> (String, u32) {
+ let meta = spaces.registry().meta(id);
+ if let Some(m) = meta.as_ref().filter(|m| m.parent.is_some()) {
+ let root = m
+ .root
+ .clone()
+ .or_else(|| m.parent.clone())
+ .unwrap_or_default();
+ return (root, m.depth);
+ }
+ let label = |k: &str| meta.as_ref().and_then(|m| m.labels.get(k).cloned());
+ match (
+ label(LABEL_ROOT),
+ label(LABEL_DEPTH).and_then(|d| d.parse().ok()),
+ ) {
+ (Some(root), Some(depth)) if label(LABEL_PARENT).is_some() => (root, depth),
+ _ => (id.to_owned(), 0),
+ }
+}
+
+#[tonic::async_trait]
+impl SpaceService for Scoped {
+ async fn add_space(&self, _: Request<pb::AddSpaceRequest>) -> R<pb::AddSpaceResponse> {
+ deny()
+ }
+
+ async fn list_spaces(&self, _: Request<pb::ListSpacesRequest>) -> R<pb::ListSpacesResponse> {
+ Ok(Response::new(pb::ListSpacesResponse {
+ spaces: self.subtree_records()?,
+ ..Default::default()
+ }))
+ }
+
+ async fn remove_space(&self, _: Request<pb::RemoveSpaceRequest>) -> R<pb::RemoveSpaceResponse> {
+ deny()
+ }
+
+ async fn list_volumes(&self, _: Request<pb::ListVolumesRequest>) -> R<pb::ListVolumesResponse> {
+ deny()
+ }
+
+ async fn create_volume(
+ &self,
+ _: Request<pb::CreateVolumeRequest>,
+ ) -> R<pb::CreateVolumeResponse> {
+ deny()
+ }
+
+ async fn delete_volume(
+ &self,
+ _: Request<pb::DeleteVolumeRequest>,
+ ) -> R<pb::DeleteVolumeResponse> {
+ deny()
+ }
+
+ async fn resolve_space(
+ &self,
+ req: Request<pb::ResolveSpaceRequest>,
+ ) -> R<pb::ResolveSpaceResponse> {
+ let space = self.resolve(&req.into_inner().space)?;
+ Ok(Response::new(pb::ResolveSpaceResponse {
+ space: Some(space),
+ }))
+ }
+
+ async fn provision_local_space(
+ &self,
+ _: Request<pb::ProvisionLocalSpaceRequest>,
+ ) -> R<pb::ProvisionLocalSpaceResponse> {
+ deny()
+ }
+
+ async fn release_space(
+ &self,
+ _: Request<pb::ReleaseSpaceRequest>,
+ ) -> R<pb::ReleaseSpaceResponse> {
+ deny()
+ }
+
+ async fn create_space(
+ &self,
+ req: Request<pb::CreateSpaceRequest>,
+ ) -> R<pb::CreateSpaceResponse> {
+ let claims = claims(&req)?;
+ let child = self.child_request(&claims, req.into_inner())?;
+ let ask = priced(self.spaces(), &child, ask_of(&child)).await?;
+ let _held = super::admit(&self.shared, &claims.root, ask)?;
+ let resp = self.owner().create_space(Request::new(child)).await?;
+ if let Some(s) = &resp.get_ref().space {
+ self.adopt(&claims, &s.id);
+ super::record_cost(&self.shared, &claims.root, &s.id, ask);
+ }
+ Ok(resp)
+ }
+
+ type CreateSpaceStreamStream = <Svc as SpaceService>::CreateSpaceStreamStream;
+
+ async fn create_space_stream(
+ &self,
+ req: Request<pb::CreateSpaceStreamRequest>,
+ ) -> R<Self::CreateSpaceStreamStream> {
+ use tokio_stream::StreamExt as _;
+ let claims = claims(&req)?;
+ let inner = req.into_inner();
+ let child = self.child_request(&claims, inner.create.unwrap_or_default())?;
+ let ask = priced(self.spaces(), &child, ask_of(&child)).await?;
+ let held = super::admit(&self.shared, &claims.root, ask)?;
+ let stream = self
+ .owner()
+ .create_space_stream(Request::new(pb::CreateSpaceStreamRequest {
+ create: Some(child),
+ }))
+ .await?
+ .into_inner();
+ let me = self.clone();
+ // The reservation lasts as long as the create's stream.
+ let adopted = stream.map(move |item| {
+ let _ = &held;
+ if let Ok(pb::CreateSpaceStreamResponse {
+ event: Some(pb::create_space_stream_response::Event::Result(r)),
+ }) = &item
+ && let Some(s) = &r.space
+ {
+ me.adopt(&claims, &s.id);
+ super::record_cost(&me.shared, &claims.root, &s.id, ask);
+ }
+ item
+ });
+ Ok(Response::new(Box::pin(adopted)))
+ }
+
+ async fn cancel_create_space(
+ &self,
+ req: Request<pb::CancelCreateSpaceRequest>,
+ ) -> R<pb::CancelCreateSpaceResponse> {
+ let space = self.resolve(&req.into_inner().space)?;
+ self.owner()
+ .cancel_create_space(Request::new(pb::CancelCreateSpaceRequest {
+ space: space.id,
+ }))
+ .await
+ }
+
+ async fn get_gpu_support(
+ &self,
+ _: Request<pb::GetGpuSupportRequest>,
+ ) -> R<pb::GetGpuSupportResponse> {
+ deny()
+ }
+
+ async fn delete_space(
+ &self,
+ req: Request<pb::DeleteSpaceRequest>,
+ ) -> R<pb::DeleteSpaceResponse> {
+ let space = self.resolve(&req.into_inner().space)?;
+ let message = self.delete_tree(&space.id).await?;
+ Ok(Response::new(pb::DeleteSpaceResponse { message }))
+ }
+
+ async fn delete_spaces(
+ &self,
+ req: Request<pb::DeleteSpacesRequest>,
+ ) -> R<pb::DeleteSpacesResponse> {
+ let mut results = Vec::new();
+ for q in req.into_inner().spaces {
+ let r = match self.resolve(&q) {
+ Ok(s) => self.delete_tree(&s.id).await,
+ Err(e) => Err(e),
+ };
+ results.push(match r {
+ Ok(message) => pb::SpaceBulkResult {
+ space: q,
+ ok: true,
+ message,
+ ..Default::default()
+ },
+ Err(e) => pb::SpaceBulkResult {
+ space: q,
+ ok: false,
+ error: e.message().to_owned(),
+ ..Default::default()
+ },
+ });
+ }
+ Ok(Response::new(pb::DeleteSpacesResponse { results }))
+ }
+
+ async fn leave_spaces(&self, _: Request<pb::LeaveSpacesRequest>) -> R<pb::LeaveSpacesResponse> {
+ deny()
+ }
+
+ async fn rename_space(
+ &self,
+ req: Request<pb::RenameSpaceRequest>,
+ ) -> R<pb::RenameSpaceResponse> {
+ let r = req.into_inner();
+ let space = self.resolve(&r.space)?;
+ self.owner()
+ .rename_space(Request::new(pb::RenameSpaceRequest {
+ space: space.id,
+ name: r.name,
+ }))
+ .await
+ }
+
+ async fn fork_space(&self, req: Request<pb::ForkSpaceRequest>) -> R<pb::ForkSpaceResponse> {
+ let claims = claims(&req)?;
+ let r = req.into_inner();
+ if claims.depth.saturating_add(1) > claims.max_depth {
+ return Err(Status::resource_exhausted(format!(
+ "this Space is {} level(s) below its tree's root and the tree allows {}: \
+ it cannot make children",
+ claims.depth, claims.max_depth
+ )));
+ }
+ // A Space may fork itself or any of its descendants.
+ let source = if r.source.trim().is_empty() || r.source == self.space {
+ self.space.clone()
+ } else {
+ self.resolve(&r.source)?.id
+ };
+ let name = if r.name.trim().is_empty() {
+ self.next_child_name("f")
+ } else {
+ r.name
+ };
+ let (vcpus, memory_mb) = super::local_size(&self.shared, &source);
+ let _held = super::admit(
+ &self.shared,
+ &claims.root,
+ super::budget::Ask {
+ vcpus,
+ memory_mb,
+ usd_per_hour: 0.0,
+ },
+ )?;
+ let resp = self
+ .owner()
+ .fork_space(Request::new(pb::ForkSpaceRequest { source, name }))
+ .await?;
+ if let Some(s) = &resp.get_ref().space {
+ // A fork starts with its source's labels: it is the caller's
+ // child whatever it was forked from.
+ let depth = claims.depth.saturating_add(1);
+ let _ = self.spaces().registry().update_meta(&s.id, |m| {
+ m.parent = Some(self.space.clone());
+ m.root = Some(claims.root.clone());
+ m.depth = depth;
+ m.origin = Some(cua_spaces::tree::ORIGIN_CHILD.into());
+ m.labels.insert(LABEL_PARENT.into(), self.space.clone());
+ m.labels.remove(LABEL_ROOT);
+ m.labels.remove(LABEL_DEPTH);
+ });
+ self.adopt(&claims, &s.id);
+ }
+ Ok(resp)
+ }
+
+ type BuildSpaceStream = <Svc as SpaceService>::BuildSpaceStream;
+
+ async fn build_space(&self, _: Request<pb::BuildSpaceRequest>) -> R<Self::BuildSpaceStream> {
+ deny()
+ }
+
+ async fn list_builds(&self, _: Request<pb::ListBuildsRequest>) -> R<pb::ListBuildsResponse> {
+ deny()
+ }
+
+ async fn delete_build(&self, _: Request<pb::DeleteBuildRequest>) -> R<pb::DeleteBuildResponse> {
+ deny()
+ }
+
+ async fn set_space_lifetime(
+ &self,
+ req: Request<pb::SetSpaceLifetimeRequest>,
+ ) -> R<pb::SetSpaceLifetimeResponse> {
+ let mut r = req.into_inner();
+ let space = self.resolve(&r.space)?;
+ // Never past the caller's own end.
+ if let (Some(own), Some(d)) = (self.spaces().lifetime(&self.space), r.duration.as_ref()) {
+ let left = own
+ .expires_at()
+ .duration_since(std::time::SystemTime::now())
+ .unwrap_or_default();
+ let asked = Duration::from_secs(u64::try_from(d.seconds).unwrap_or(0));
+ if asked > left {
+ return Err(Status::permission_denied(format!(
+ "a child cannot outlive its parent: this Space ends in {}s",
+ left.as_secs()
+ )));
+ }
+ }
+ r.space = space.id;
+ self.owner().set_space_lifetime(Request::new(r)).await
+ }
+
+ async fn set_space_egress(
+ &self,
+ _: Request<pb::SetSpaceEgressRequest>,
+ ) -> R<pb::SetSpaceEgressResponse> {
+ Err(refused(
+ "give children its own egress rules (set them on the parent)",
+ ))
+ }
+
+ async fn get_tree_budget(
+ &self,
+ req: Request<pb::GetTreeBudgetRequest>,
+ ) -> R<pb::GetTreeBudgetResponse> {
+ // Its own tree's budget, and nothing about another tree.
+ let claims = claims(&req)?;
+ Ok(Response::new(pb::GetTreeBudgetResponse {
+ budget: Some(tree_budget(&self.shared, &claims.root)),
+ }))
+ }
+
+ async fn set_tree_budget(
+ &self,
+ _: Request<pb::SetTreeBudgetRequest>,
+ ) -> R<pb::SetTreeBudgetResponse> {
+ Err(refused("spend within its tree's budget; the owner sets it"))
+ }
+
+ async fn list_orphans(&self, _: Request<pb::ListOrphansRequest>) -> R<pb::ListOrphansResponse> {
+ deny()
+ }
+
+ async fn get_space_network(
+ &self,
+ _: Request<pb::GetSpaceNetworkRequest>,
+ ) -> R<pb::GetSpaceNetworkResponse> {
+ // Network settings are the owner's, never an agent's.
+ deny()
+ }
+
+ async fn set_space_network(
+ &self,
+ _: Request<pb::SetSpaceNetworkRequest>,
+ ) -> R<pb::SetSpaceNetworkResponse> {
+ // Network settings are the owner's, never an agent's.
+ deny()
+ }
+
+ async fn set_space_children(
+ &self,
+ req: Request<pb::SetSpaceChildrenRequest>,
+ ) -> R<pb::SetSpaceChildrenResponse> {
+ // A Space may turn its children's own children off, never on: the
+ // tree's depth decides that.
+ let r = req.into_inner();
+ let mut space = self.resolve(&r.space)?;
+ if r.enabled {
+ return Err(refused(
+ "let its children make children as deep as its tree allows (that is automatic)",
+ ));
+ }
+ self.spaces()
+ .set_children(&space.id, false)
+ .map_err(|e| Status::internal(e.to_string()))?;
+ if let Some(a) = self.shared.spawn_authority() {
+ a.revoke(&space.id);
+ }
+ space.children = false;
+ Ok(Response::new(pb::SetSpaceChildrenResponse {
+ space: Some(space),
+ }))
+ }
+
+ async fn connect_space(
+ &self,
+ req: Request<pb::ConnectSpaceRequest>,
+ ) -> R<pb::ConnectSpaceResponse> {
+ // The child's commands go through this channel with the caller's
+ // own capability.
+ let bearer = req
+ .extensions()
+ .get::<super::Presented>()
+ .map(|p| p.0.clone())
+ .unwrap_or_default();
+ let origin = req
+ .extensions()
+ .get::<super::Origin>()
+ .map(|o| o.0.clone())
+ .unwrap_or_default();
+ let space = self.resolve(&req.into_inner().space)?;
+ let mut resp = self
+ .owner()
+ .connect_space(Request::new(pb::ConnectSpaceRequest {
+ space: space.id.clone(),
+ }))
+ .await?
+ .into_inner();
+ // Through this channel's own passthrough, never the daemon's
+ // loopback listener, its token or another computer's route.
+ let key = crate::passthrough::space_key(&space.id);
+ resp.env_url = if resp.env_url.is_empty() || origin.is_empty() {
+ String::new()
+ } else {
+ format!("http://{origin}/v1/spaces/{key}/env")
+ };
+ resp.token = bearer;
+ resp.services.clear();
+ resp.bulk = String::new();
+ Ok(Response::new(resp))
+ }
+
+ async fn list_space_tools(
+ &self,
+ _: Request<pb::ListSpaceToolsRequest>,
+ ) -> R<pb::ListSpaceToolsResponse> {
+ let all = self
+ .owner()
+ .list_space_tools(Request::new(pb::ListSpaceToolsRequest {}))
+ .await?
+ .into_inner();
+ let tools: Vec<Value> = serde_json::from_str(&all.tools_json).unwrap_or_default();
+ let kept: Vec<Value> = tools
+ .into_iter()
+ .filter(|t| {
+ t.get("name")
+ .and_then(Value::as_str)
+ .is_some_and(|n| Self::tool_target(n).is_some())
+ })
+ .collect();
+ Ok(Response::new(pb::ListSpaceToolsResponse {
+ tools_json: Value::Array(kept).to_string(),
+ }))
+ }
+
+ async fn call_space_tool(
+ &self,
+ req: Request<pb::CallSpaceToolRequest>,
+ ) -> R<pb::CallSpaceToolResponse> {
+ let r = req.into_inner();
+ let mut args: Value = if r.arguments_json.trim().is_empty() {
+ Value::Object(Default::default())
+ } else {
+ serde_json::from_str(&r.arguments_json)
+ .map_err(|e| Status::invalid_argument(format!("arguments_json: {e}")))?
+ };
+ self.scoped_tool_args(&r.name, &mut args)?;
+ self.owner()
+ .call_space_tool(Request::new(pb::CallSpaceToolRequest {
+ name: r.name,
+ arguments_json: args.to_string(),
+ }))
+ .await
+ }
+
+ async fn list_hosts(&self, _: Request<pb::ListHostsRequest>) -> R<pb::ListHostsResponse> {
+ deny()
+ }
+
+ async fn pool_request(&self, _: Request<pb::PoolRequestRequest>) -> R<pb::PoolRequestResponse> {
+ deny()
+ }
+
+ async fn get_space_thumbnail(
+ &self,
+ req: Request<pb::GetSpaceThumbnailRequest>,
+ ) -> R<pb::GetSpaceThumbnailResponse> {
+ let mut r = req.into_inner();
+ r.space = self.resolve(&r.space)?.id;
+ self.owner().get_space_thumbnail(Request::new(r)).await
+ }
+
+ async fn get_space_route(
+ &self,
+ req: Request<pb::GetSpaceRouteRequest>,
+ ) -> R<pb::GetSpaceRouteResponse> {
+ let mut r = req.into_inner();
+ r.space = self.resolve(&r.space)?.id;
+ self.owner().get_space_route(Request::new(r)).await
+ }
+
+ async fn get_resources(
+ &self,
+ _: Request<pb::GetResourcesRequest>,
+ ) -> R<pb::GetResourcesResponse> {
+ deny()
+ }
+
+ type WatchResourcesStream = <Svc as SpaceService>::WatchResourcesStream;
+
+ async fn watch_resources(
+ &self,
+ _: Request<pb::WatchResourcesRequest>,
+ ) -> R<Self::WatchResourcesStream> {
+ deny()
+ }
+
+ type WatchSpacesStream = <Svc as SpaceService>::WatchSpacesStream;
+
+ async fn watch_spaces(&self, _: Request<pb::WatchSpacesRequest>) -> R<Self::WatchSpacesStream> {
+ deny()
+ }
+}
+
+#[tonic::async_trait]
+impl DaemonService for Scoped {
+ async fn get_info(&self, _: Request<pb::GetInfoRequest>) -> R<pb::GetInfoResponse> {
+ // Who answers, and nothing of the daemon's own (no token, socket
+ // or loopback address).
+ Ok(Response::new(pb::GetInfoResponse {
+ version: crate::VERSION.into(),
+ features: vec!["spaces".into(), super::CHILDREN_FEATURE.into()],
+ ..Default::default()
+ }))
+ }
+
+ async fn open_media_bridge(
+ &self,
+ _: Request<pb::OpenMediaBridgeRequest>,
+ ) -> R<pb::OpenMediaBridgeResponse> {
+ deny()
+ }
+
+ async fn shutdown(&self, _: Request<pb::ShutdownRequest>) -> R<pb::ShutdownResponse> {
+ deny()
+ }
+}
diff --git a/libs/cua/crates/cua-daemon/src/children/bridge.rs b/libs/cua/crates/cua-daemon/src/children/bridge.rs
new file mode 100644
index 0000000000..d089cec77a
--- /dev/null
+++ b/libs/cua/crates/cua-daemon/src/children/bridge.rs
@@ -0,0 +1,265 @@
+//! Keeps the spawn channel of every running Space on this computer that has
+//! children on, and ends the capabilities of Spaces that are gone.
+//!
+//! For each such Space the host mints a capability, starts the guest's end
+//! (`TunnelService.StartSpawn`) and keeps the WebSocket open, serving each
+//! stream that arrives with [`super::channel_app`] for that Space. When the
+//! guest restarts, the socket closes and the host starts the channel again
+//! with a fresh capability (the old one, in a snapshot or a fork, is dead).
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::sync::Arc;
+use std::time::Duration;
+
+use tokio::sync::watch;
+use tokio::task::JoinHandle;
+
+use super::capability::{DEFAULT_MAX_DEPTH, DEFAULT_TTL_SECS, RENEW_AFTER_SECS};
+use crate::server::Shared;
+
+/// How often the loop looks again without being woken.
+const EVERY: Duration = Duration::from_secs(5);
+/// Wait before trying a Space that could not be reached again.
+const RETRY: Duration = Duration::from_secs(5);
+/// Wait before asking a guest without the spawn channel again (an older
+/// cua-spacesd).
+const NO_FEATURE_RETRY: Duration = Duration::from_secs(60);
+
+/// How often orphaned children are judged.
+const REAP_EVERY: Duration = Duration::from_secs(60);
+
+/// What the reaper sees of this computer's registry, or `None` when it can
+/// not be read (then nothing is decided).
+pub(crate) fn seen(shared: &Shared) -> Option<Vec<super::reaper::Seen>> {
+ let spaces = shared.runtime.spaces();
+ let records = spaces.registry().list().ok()?;
+ let meta = spaces.registry().all_meta();
+ Some(
+ records
+ .into_iter()
+ .map(|r| {
+ let m = meta.get(&r.id);
+ super::reaper::Seen {
+ parent: m.and_then(super::api::parent_of),
+ created_at: m.map(|m| m.created_at_unix).unwrap_or(0),
+ id: r.id,
+ }
+ })
+ .collect(),
+ )
+}
+
+/// Judges the children of this computer and ends the ones whose parent is
+/// provably gone for the grace period (each with everything below it).
+pub(crate) fn reap(shared: &Arc<Shared>) {
+ use super::reaper::{Memory, Verdict, judge};
+ let Some(seen) = seen(shared) else {
+ return;
+ };
+ let home = shared.runtime.spaces().home_dir().to_path_buf();
+ let mut memory = Memory::load(&home);
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ let verdicts = judge(&seen, &mut memory, now);
+ if let Err(e) = memory.save(&home) {
+ tracing::warn!(error = %e, "could not save the orphan records");
+ }
+ let links = super::api::links_of(shared.runtime.spaces());
+ for (id, verdict) in verdicts {
+ let Verdict::End { why } = verdict else {
+ continue;
+ };
+ let mut order = super::tree::subtree(&links, &id);
+ order.push(id.clone());
+ tracing::warn!(space = %id, below = order.len() - 1, %why, "ending an orphaned child Space");
+ let shared = shared.clone();
+ tokio::spawn(async move {
+ use cua_proto::daemon::v1::space_service_server::SpaceService as _;
+ for victim in order {
+ let owner = crate::server::Svc(shared.clone());
+ let r = owner
+ .delete_space(tonic::Request::new(
+ cua_proto::daemon::v1::DeleteSpaceRequest {
+ space: victim.clone(),
+ keep_children: false,
+ },
+ ))
+ .await;
+ if let Some(a) = shared.spawn_authority() {
+ a.revoke(&victim);
+ }
+ match r {
+ Ok(_) => tracing::info!(space = %victim, "orphaned child Space ended"),
+ Err(e) if e.code() == tonic::Code::NotFound => {}
+ Err(e) => {
+ tracing::warn!(space = %victim, error = %e, "could not end an orphaned child Space")
+ }
+ }
+ }
+ });
+ }
+}
+
+/// Only Spaces this computer runs itself hold a channel to it.
+fn runs_here(id: &str) -> bool {
+ id.starts_with("local:")
+}
+
+/// The loop; ends with the daemon.
+pub(crate) fn spawn(shared: Arc<Shared>, mut shutdown: watch::Receiver<bool>) -> JoinHandle<()> {
+ tokio::spawn(async move {
+ if shared.children.is_none() {
+ return;
+ }
+ let mut bridges: BTreeMap<String, JoinHandle<()>> = BTreeMap::new();
+ let mut last_reap = std::time::Instant::now() - REAP_EVERY;
+ loop {
+ reconcile(&shared, &mut bridges);
+ if last_reap.elapsed() >= REAP_EVERY {
+ last_reap = std::time::Instant::now();
+ reap(&shared);
+ }
+ tokio::select! {
+ _ = shutdown.changed() => break,
+ _ = cua_spaces::children::CHANGED.notified() => {}
+ _ = tokio::time::sleep(EVERY) => {}
+ }
+ }
+ for (_, t) in bridges {
+ t.abort();
+ }
+ })
+}
+
+/// One pass: channels for the Spaces that want one, none for the rest, and
+/// no capability or setting left for a Space that is gone.
+pub(crate) fn reconcile(shared: &Arc<Shared>, bridges: &mut BTreeMap<String, JoinHandle<()>>) {
+ let Some(children) = shared.children.as_deref() else {
+ return;
+ };
+ let spaces = shared.runtime.spaces();
+ let Ok(records) = spaces.registry().list() else {
+ return;
+ };
+ let registered: BTreeSet<String> = records.into_iter().map(|r| r.id).collect();
+ // Children that are gone stop costing; what they cost stays with their
+ // tree.
+ children.budget.close_gone(
+ &registered,
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0),
+ );
+ for id in children.authority.spaces() {
+ if !registered.contains(&id) {
+ children.authority.revoke(&id);
+ }
+ }
+ spaces.forget_children_of_gone(&registered);
+ let wanted: BTreeSet<String> = spaces
+ .children_enabled()
+ .into_iter()
+ .filter(|id| runs_here(id))
+ .collect();
+ bridges.retain(|id, task| {
+ let keep = wanted.contains(id) && !task.is_finished();
+ if !keep {
+ task.abort();
+ if !wanted.contains(id) {
+ children.authority.revoke(id);
+ }
+ }
+ keep
+ });
+ for id in wanted {
+ if !bridges.contains_key(&id) {
+ bridges.insert(id.clone(), tokio::spawn(run(shared.clone(), id)));
+ }
+ }
+}
+
+/// The depth limit of `root`'s tree: what its own capability carries, else
+/// the default.
+fn tree_limit(shared: &Shared, root: &str) -> u32 {
+ shared
+ .spawn_authority()
+ .and_then(|a| a.record(root))
+ .map(|r| r.max_depth)
+ .unwrap_or(DEFAULT_MAX_DEPTH)
+}
+
+/// Keeps one Space's channel until the task is aborted.
+async fn run(shared: Arc<Shared>, id: String) {
+ let mut warned = false;
+ loop {
+ let spaces = shared.runtime.spaces();
+ let space = match spaces.space(&id).await {
+ Ok(s) => s,
+ Err(e) => {
+ tracing::debug!(space = %id, error = %e, "spawn channel waits for the Space");
+ tokio::time::sleep(RETRY).await;
+ continue;
+ }
+ };
+ if !space
+ .feature(cua_spaces::spawn::SPAWN_FEATURE)
+ .is_some_and(|f| f.supported)
+ {
+ if !warned {
+ tracing::info!(
+ space = %id,
+ "this Space's cua-spacesd has no spawn channel; it cannot make children"
+ );
+ warned = true;
+ }
+ tokio::time::sleep(NO_FEATURE_RETRY).await;
+ continue;
+ }
+ let Some(authority) = shared.spawn_authority() else {
+ return;
+ };
+ // Child Spaces are an experiment: no capability while it is off
+ // (turning it off ends this channel at its next renewal; the API
+ // refuses the capability at once).
+ if !cua_vmm::experiments::enabled(cua_vmm::experiments::Gate::ChildSpaces) {
+ authority.revoke(&id);
+ tokio::time::sleep(NO_FEATURE_RETRY).await;
+ continue;
+ }
+ let (root, depth) = super::api::position(spaces, &id);
+ let limit = if root == id {
+ DEFAULT_MAX_DEPTH
+ } else {
+ tree_limit(&shared, &root)
+ };
+ let capability = authority.mint(&id, &root, depth, limit, DEFAULT_TTL_SECS);
+ let app = super::channel_app(shared.clone(), id.clone());
+ let dial = move |_host: String, _port: u16| {
+ let app = app.clone();
+ async move {
+ let (ours, theirs) = tokio::io::duplex(256 * 1024);
+ tokio::spawn(super::serve_stream(app, theirs));
+ Ok::<_, std::io::Error>(ours)
+ }
+ };
+ let mut channel = match space.start_spawn_with(&capability, dial).await {
+ Ok(c) => c,
+ Err(e) => {
+ tracing::warn!(space = %id, error = %e, "could not start the spawn channel");
+ authority.revoke(&id);
+ tokio::time::sleep(RETRY).await;
+ continue;
+ }
+ };
+ tracing::info!(space = %id, address = %channel.address(), "spawn channel up");
+ tokio::select! {
+ _ = channel.closed() => {
+ tracing::info!(space = %id, "spawn channel closed; starting it again");
+ }
+ _ = tokio::time::sleep(Duration::from_secs(RENEW_AFTER_SECS)) => {}
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-daemon/src/children/budget.rs b/libs/cua/crates/cua-daemon/src/children/budget.rs
new file mode 100644
index 0000000000..6b6b415ebf
--- /dev/null
+++ b/libs/cua/crates/cua-daemon/src/children/budget.rs
@@ -0,0 +1,543 @@
+//! A tree's budget: how many Spaces, vCPUs and memory its children may
+//! hold at once, and what they may cost (per hour and in total).
+//!
+//! The owner sets it on the tree's top-level Space (`<home>/spawn/
+//! budgets.json`); unset fields take the defaults below, sized so a runaway
+//! loop is cheap. A create or fork of a child reserves what it asks before
+//! it starts ([`Ledger::reserve`]), so concurrent creates can never pass the
+//! budget together: one that does not fit is refused with what is left. The
+//! reservation becomes the child's use when it exists, and is dropped when
+//! the create fails.
+//!
+//! Children on this computer cost nothing per hour; children in a linked
+//! cloud cost what the cloud bills, and the account's own cloud budget is
+//! checked as well (the stricter wins).
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+use serde::{Deserialize, Serialize};
+
+/// Live children of one tree, unless the owner says more.
+pub const DEFAULT_MAX_SPACES: u32 = 16;
+/// vCPUs its children hold together.
+pub const DEFAULT_MAX_VCPUS: u32 = 16;
+/// Memory its children hold together (MiB).
+pub const DEFAULT_MAX_MEMORY_MB: u64 = 32 * 1024;
+/// What its children may cost per hour in linked clouds.
+pub const DEFAULT_USD_PER_HOUR: f64 = 2.0;
+/// A reservation not settled in this long is dropped (a create that
+/// crashed).
+pub const RESERVATION_TTL: Duration = Duration::from_secs(30 * 60);
+
+/// The owner's limits for one tree (unset: the default).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct Budget {
+ /// Live children at once.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub max_spaces: Option<u32>,
+ /// vCPUs at once.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub max_vcpus: Option<u32>,
+ /// Memory at once (MiB).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub max_memory_mb: Option<u64>,
+ /// Cost per hour of everything running at once ($).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub usd_per_hour: Option<f64>,
+ /// Cost in total, over the tree's life ($). Unset: no total cap.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub usd_total: Option<f64>,
+}
+
+impl Budget {
+ /// With the defaults filled in.
+ pub fn effective(&self) -> Limits {
+ Limits {
+ max_spaces: self.max_spaces.unwrap_or(DEFAULT_MAX_SPACES),
+ max_vcpus: self.max_vcpus.unwrap_or(DEFAULT_MAX_VCPUS),
+ max_memory_mb: self.max_memory_mb.unwrap_or(DEFAULT_MAX_MEMORY_MB),
+ usd_per_hour: self.usd_per_hour.unwrap_or(DEFAULT_USD_PER_HOUR),
+ usd_total: self.usd_total,
+ }
+ }
+}
+
+/// A budget with every field decided.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Limits {
+ /// Live children at once.
+ pub max_spaces: u32,
+ /// vCPUs at once.
+ pub max_vcpus: u32,
+ /// Memory at once (MiB).
+ pub max_memory_mb: u64,
+ /// $ per hour at once.
+ pub usd_per_hour: f64,
+ /// $ in total.
+ pub usd_total: Option<f64>,
+}
+
+/// What one child holds, or asks for.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct Ask {
+ /// vCPUs.
+ pub vcpus: u32,
+ /// Memory (MiB).
+ pub memory_mb: u64,
+ /// $ per hour (0 on this computer).
+ pub usd_per_hour: f64,
+}
+
+/// What a tree's children hold now and have spent.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct Usage {
+ /// Live children.
+ pub spaces: u32,
+ /// vCPUs they hold.
+ pub vcpus: u32,
+ /// Memory they hold (MiB).
+ pub memory_mb: u64,
+ /// $ per hour they cost.
+ pub usd_per_hour: f64,
+ /// $ spent so far.
+ pub usd_spent: f64,
+}
+
+impl Usage {
+ fn plus(mut self, a: &Ask) -> Self {
+ self.spaces += 1;
+ self.vcpus += a.vcpus;
+ self.memory_mb += a.memory_mb;
+ self.usd_per_hour += a.usd_per_hour;
+ self
+ }
+}
+
+/// Why a child does not fit: the limit that stopped it, in words the
+/// agent can read and act on.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Refusal(pub String);
+
+/// Checks `ask` against `limits` given what is used and reserved.
+pub fn fits(limits: &Limits, used: &Usage, ask: &Ask) -> Result<(), Refusal> {
+ let after = used.plus(ask);
+ if after.spaces > limits.max_spaces {
+ return Err(Refusal(format!(
+ "this tree may hold {} child Spaces at once and holds {}; delete one, or ask the \
+ owner to raise it (`cua spaces budget <root> --spaces N`)",
+ limits.max_spaces, used.spaces
+ )));
+ }
+ if after.vcpus > limits.max_vcpus {
+ return Err(Refusal(format!(
+ "this child asks for {} vCPUs and the tree has {} of {} left; ask for fewer, or ask \
+ the owner to raise it (`--cpus N`)",
+ ask.vcpus,
+ limits.max_vcpus.saturating_sub(used.vcpus),
+ limits.max_vcpus
+ )));
+ }
+ if after.memory_mb > limits.max_memory_mb {
+ return Err(Refusal(format!(
+ "this child asks for {} MiB and the tree has {} of {} MiB left; ask for less, or ask \
+ the owner to raise it (`--memory MiB`)",
+ ask.memory_mb,
+ limits.max_memory_mb.saturating_sub(used.memory_mb),
+ limits.max_memory_mb
+ )));
+ }
+ if ask.usd_per_hour > 0.0 && after.usd_per_hour > limits.usd_per_hour + 1e-9 {
+ return Err(Refusal(format!(
+ "this child costs ${:.2}/h and the tree has ${:.2}/h of ${:.2}/h left; pick a \
+ cheaper machine, or ask the owner to raise it (`--usd-per-hour N`)",
+ ask.usd_per_hour,
+ (limits.usd_per_hour - used.usd_per_hour).max(0.0),
+ limits.usd_per_hour
+ )));
+ }
+ if let Some(total) = limits.usd_total
+ && ask.usd_per_hour > 0.0
+ && used.usd_spent + ask.usd_per_hour > total + 1e-9
+ {
+ return Err(Refusal(format!(
+ "this tree has spent ${:.2} of its ${total:.2}, and one hour of this child \
+ (${:.2}) would pass it; ask the owner to raise it (`--usd-total N`)",
+ used.usd_spent, ask.usd_per_hour
+ )));
+ }
+ Ok(())
+}
+
+struct Reservation {
+ id: u64,
+ root: String,
+ ask: Ask,
+ at: Instant,
+}
+
+/// What one child was made with, for its tree's use and spend.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Cost {
+ /// Its tree.
+ pub root: String,
+ /// vCPUs.
+ pub vcpus: u32,
+ /// Memory (MiB).
+ pub memory_mb: u64,
+ /// $ per hour while it lives.
+ pub usd_per_hour: f64,
+ /// Since when (unix seconds).
+ pub since: u64,
+}
+
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+struct Costs {
+ /// Live children.
+ #[serde(default)]
+ children: BTreeMap<String, Cost>,
+ /// $ spent by children that are gone, per tree.
+ #[serde(default)]
+ spent: BTreeMap<String, f64>,
+}
+
+/// The owner's budgets and the reservations of creates in flight.
+pub struct Ledger {
+ path: PathBuf,
+ budgets: Mutex<BTreeMap<String, Budget>>,
+ reservations: Mutex<(u64, Vec<Reservation>)>,
+ costs: Mutex<Costs>,
+}
+
+/// A reservation; [`Ledger::settle`] or [`Ledger::release`] it.
+#[derive(Debug)]
+#[must_use]
+pub struct Ticket(u64);
+
+impl Ledger {
+ /// Opens `<home>/spawn/budgets.json`.
+ pub fn open(home: &Path) -> Self {
+ let path = home.join("spawn").join("budgets.json");
+ let budgets = std::fs::read(&path)
+ .ok()
+ .and_then(|b| serde_json::from_slice(&b).ok())
+ .unwrap_or_default();
+ let costs = std::fs::read(path.with_file_name("costs.json"))
+ .ok()
+ .and_then(|b| serde_json::from_slice(&b).ok())
+ .unwrap_or_default();
+ Self {
+ path,
+ budgets: Mutex::new(budgets),
+ reservations: Mutex::new((1, Vec::new())),
+ costs: Mutex::new(costs),
+ }
+ }
+
+ fn save_costs(&self, costs: &Costs) {
+ let p = self.path.with_file_name("costs.json");
+ if let Some(d) = p.parent() {
+ let _ = std::fs::create_dir_all(d);
+ }
+ let tmp = p.with_extension("json.tmp");
+ if std::fs::write(&tmp, serde_json::to_vec_pretty(costs).unwrap_or_default()).is_ok() {
+ let _ = std::fs::rename(&tmp, &p);
+ }
+ }
+
+ /// Records a child made in `root`'s tree with `ask`, from `now`.
+ pub fn record(&self, root: &str, child: &str, ask: &Ask, now: u64) {
+ let mut c = self.costs.lock().unwrap();
+ c.children.insert(
+ child.to_owned(),
+ Cost {
+ root: root.to_owned(),
+ vcpus: ask.vcpus,
+ memory_mb: ask.memory_mb,
+ usd_per_hour: ask.usd_per_hour,
+ since: now,
+ },
+ );
+ self.save_costs(&c);
+ }
+
+ /// What `child` was made with, if recorded.
+ pub fn cost(&self, child: &str) -> Option<Cost> {
+ self.costs.lock().unwrap().children.get(child).cloned()
+ }
+
+ /// Closes the records of children not in `live`: what they cost goes to
+ /// their tree's spend.
+ pub fn close_gone(&self, live: &std::collections::BTreeSet<String>, now: u64) {
+ let mut c = self.costs.lock().unwrap();
+ let gone: Vec<String> = c
+ .children
+ .keys()
+ .filter(|k| !live.contains(*k))
+ .cloned()
+ .collect();
+ if gone.is_empty() {
+ return;
+ }
+ for id in gone {
+ if let Some(x) = c.children.remove(&id) {
+ *c.spent.entry(x.root.clone()).or_default() += cost_so_far(&x, now);
+ }
+ }
+ self.save_costs(&c);
+ }
+
+ /// `root`'s tree: $ per hour of its live children, and $ spent in all.
+ pub fn spend(&self, root: &str, now: u64) -> (f64, f64) {
+ let c = self.costs.lock().unwrap();
+ let live = c.children.values().filter(|x| x.root == root);
+ let per_hour = live.clone().map(|x| x.usd_per_hour).sum();
+ let spent = c.spent.get(root).copied().unwrap_or(0.0)
+ + live.map(|x| cost_so_far(x, now)).sum::<f64>();
+ (per_hour, spent)
+ }
+
+ /// The budget of `root`'s tree.
+ pub fn budget(&self, root: &str) -> Budget {
+ self.budgets
+ .lock()
+ .unwrap()
+ .get(root)
+ .cloned()
+ .unwrap_or_default()
+ }
+
+ /// Sets the budget of `root`'s tree (`Budget::default()` removes it).
+ pub fn set_budget(&self, root: &str, budget: Budget) -> std::io::Result<()> {
+ let mut all = self.budgets.lock().unwrap();
+ if budget == Budget::default() {
+ all.remove(root);
+ } else {
+ all.insert(root.to_owned(), budget);
+ }
+ if let Some(dir) = self.path.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
+ let tmp = self.path.with_extension("json.tmp");
+ std::fs::write(&tmp, serde_json::to_vec_pretty(&*all).unwrap_or_default())?;
+ std::fs::rename(&tmp, &self.path)
+ }
+
+ /// What creates in flight hold in `root`'s tree.
+ pub fn reserved(&self, root: &str) -> Usage {
+ let mut r = self.reservations.lock().unwrap();
+ r.1.retain(|x| x.at.elapsed() < RESERVATION_TTL);
+ r.1.iter()
+ .filter(|x| x.root == root)
+ .fold(Usage::default(), |u, x| u.plus(&x.ask))
+ }
+
+ /// Reserves `ask` in `root`'s tree when it fits what is `used` (the
+ /// live children) plus what is reserved, all under one lock so two
+ /// creates cannot both take the last room.
+ pub fn reserve(
+ &self,
+ root: &str,
+ limits: &Limits,
+ used: &Usage,
+ ask: Ask,
+ ) -> Result<Ticket, Refusal> {
+ let mut r = self.reservations.lock().unwrap();
+ r.1.retain(|x| x.at.elapsed() < RESERVATION_TTL);
+ let held =
+ r.1.iter()
+ .filter(|x| x.root == root)
+ .fold(*used, |u, x| u.plus(&x.ask));
+ fits(limits, &held, &ask)?;
+ let id = r.0;
+ r.0 += 1;
+ r.1.push(Reservation {
+ id,
+ root: root.to_owned(),
+ ask,
+ at: Instant::now(),
+ });
+ Ok(Ticket(id))
+ }
+
+ /// The create finished (its child now counts as used) or failed: the
+ /// reservation goes either way.
+ pub fn release(&self, ticket: Ticket) {
+ self.reservations
+ .lock()
+ .unwrap()
+ .1
+ .retain(|x| x.id != ticket.0);
+ }
+}
+
+fn cost_so_far(c: &Cost, now: u64) -> f64 {
+ c.usd_per_hour * now.saturating_sub(c.since) as f64 / 3600.0
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn ask(vcpus: u32, memory_mb: u64, usd: f64) -> Ask {
+ Ask {
+ vcpus,
+ memory_mb,
+ usd_per_hour: usd,
+ }
+ }
+
+ #[test]
+ fn defaults_and_plain_refusals() {
+ let l = Budget::default().effective();
+ assert_eq!(
+ (l.max_spaces, l.max_vcpus, l.max_memory_mb),
+ (16, 16, 32 * 1024)
+ );
+ let used = Usage {
+ spaces: 3,
+ vcpus: 14,
+ memory_mb: 4096,
+ ..Default::default()
+ };
+ let e = fits(&l, &used, &ask(4, 1024, 0.0)).unwrap_err();
+ assert!(e.0.contains("2 of 16 left"), "{}", e.0);
+ assert!(fits(&l, &used, &ask(2, 1024, 0.0)).is_ok());
+ let e = fits(&l, &used, &ask(1, 40 * 1024, 0.0)).unwrap_err();
+ assert!(e.0.contains("MiB"), "{}", e.0);
+ let full = Usage {
+ spaces: 16,
+ ..Default::default()
+ };
+ assert!(
+ fits(&l, &full, &ask(1, 1, 0.0))
+ .unwrap_err()
+ .0
+ .contains("16 child")
+ );
+ }
+
+ #[test]
+ fn dollars_per_hour_and_total() {
+ let l = Budget {
+ usd_per_hour: Some(1.0),
+ usd_total: Some(5.0),
+ ..Default::default()
+ }
+ .effective();
+ let used = Usage {
+ usd_per_hour: 0.6,
+ usd_spent: 4.5,
+ ..Default::default()
+ };
+ // Local children cost nothing: never refused on $.
+ assert!(fits(&l, &used, &ask(1, 1, 0.0)).is_ok());
+ assert!(
+ fits(&l, &used, &ask(1, 1, 0.5))
+ .unwrap_err()
+ .0
+ .contains("/h")
+ );
+ let used = Usage {
+ usd_spent: 4.8,
+ ..Default::default()
+ };
+ assert!(
+ fits(&l, &used, &ask(1, 1, 0.3))
+ .unwrap_err()
+ .0
+ .contains("spent")
+ );
+ }
+
+ #[test]
+ fn concurrent_reservations_never_pass_the_budget() {
+ let dir = tempfile::tempdir().unwrap();
+ let ledger = std::sync::Arc::new(Ledger::open(dir.path()));
+ let limits = Budget {
+ max_spaces: Some(5),
+ ..Default::default()
+ }
+ .effective();
+ let granted = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
+ let threads: Vec<_> = (0..32)
+ .map(|_| {
+ let (ledger, granted) = (ledger.clone(), granted.clone());
+ std::thread::spawn(move || {
+ if let Ok(t) = ledger.reserve("r", &limits, &Usage::default(), ask(1, 512, 0.0))
+ {
+ granted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ // The reservation stays: the test counts what was granted.
+ let _ticket = t;
+ }
+ })
+ })
+ .collect();
+ for t in threads {
+ t.join().unwrap();
+ }
+ assert_eq!(granted.load(std::sync::atomic::Ordering::SeqCst), 5);
+ assert_eq!(ledger.reserved("r").spaces, 5);
+ // Another tree has its own room.
+ assert!(
+ ledger
+ .reserve("other", &limits, &Usage::default(), ask(1, 1, 0.0))
+ .is_ok()
+ );
+ }
+
+ #[test]
+ fn a_released_reservation_frees_its_room_and_budgets_persist() {
+ let dir = tempfile::tempdir().unwrap();
+ let ledger = Ledger::open(dir.path());
+ let limits = Budget {
+ max_spaces: Some(1),
+ ..Default::default()
+ }
+ .effective();
+ let t = ledger
+ .reserve("r", &limits, &Usage::default(), ask(1, 1, 0.0))
+ .unwrap();
+ assert!(
+ ledger
+ .reserve("r", &limits, &Usage::default(), ask(1, 1, 0.0))
+ .is_err()
+ );
+ ledger.release(t);
+ let t = ledger
+ .reserve("r", &limits, &Usage::default(), ask(1, 1, 0.0))
+ .unwrap();
+ ledger.release(t);
+ let b = Budget {
+ max_vcpus: Some(64),
+ usd_total: Some(10.0),
+ ..Default::default()
+ };
+ ledger.set_budget("r", b.clone()).unwrap();
+ assert_eq!(Ledger::open(dir.path()).budget("r"), b);
+ ledger.set_budget("r", Budget::default()).unwrap();
+ assert_eq!(Ledger::open(dir.path()).budget("r"), Budget::default());
+ }
+
+ #[test]
+ fn spend_is_live_cost_plus_what_gone_children_cost() {
+ let dir = tempfile::tempdir().unwrap();
+ let l = Ledger::open(dir.path());
+ l.record("r", "c1", &ask(2, 1024, 0.5), 1000);
+ l.record("r", "c2", &ask(2, 1024, 1.0), 1000);
+ l.record("other", "o1", &ask(2, 1024, 9.0), 1000);
+ let (h, spent) = l.spend("r", 1000 + 3600);
+ assert!((h - 1.5).abs() < 1e-9 && (spent - 1.5).abs() < 1e-9);
+ // c2 is deleted: it stops costing per hour, and what it cost stays.
+ l.close_gone(&["c1".to_string(), "o1".to_string()].into(), 1000 + 3600);
+ let (h, spent) = l.spend("r", 1000 + 7200);
+ assert!((h - 0.5).abs() < 1e-9, "{h}");
+ assert!((spent - (1.0 + 1.0)).abs() < 1e-9, "{spent}");
+ // And it survives a restart.
+ let back = Ledger::open(dir.path());
+ assert!((back.spend("r", 1000 + 7200).1 - 2.0).abs() < 1e-9);
+ assert_eq!(back.cost("c1").unwrap().vcpus, 2);
+ }
+}
diff --git a/libs/cua/crates/cua-daemon/src/children/capability.rs b/libs/cua/crates/cua-daemon/src/children/capability.rs
new file mode 100644
index 0000000000..484d5bea80
--- /dev/null
+++ b/libs/cua/crates/cua-daemon/src/children/capability.rs
@@ -0,0 +1,407 @@
+//! The spawn capability: what a Space presents on its spawn channel to make
+//! and manage its own children.
+//!
+//! A capability is `cuaspawn1.<claims>.<mac>`: base64url JSON claims and an
+//! HMAC-SHA-256 over them with this host's spawn key (`<home>/spawn/key`,
+//! 0600, never leaves the host). It is checked three ways, all required:
+//!
+//! - the MAC: only this host made it;
+//! - the record (`<home>/spawn/capabilities.json`): one live capability
+//! per Space, by its `jti`. Minting again or revoking (the Space is
+//! deleted, its children are turned off) ends the old one at once;
+//! - the channel: the Space it names must be the Space whose channel it came
+//! in on. A capability copied out of a snapshot, a fork or another Space
+//! is refused, because the host knows each channel's Space by the
+//! connection it opened itself.
+//!
+//! It holds no account data, keys or cloud links: it only names a Space,
+//! its tree and how deep it sits.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use base64::Engine as _;
+use hmac::{Hmac, Mac};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+
+/// Prefix of every capability (and its version).
+pub const PREFIX: &str = "cuaspawn1";
+/// Domain separation for the MAC.
+const MAC_CONTEXT: &[u8] = b"cua-spawn-capability/v1\n";
+/// Default lifetime. The host mints a fresh one well before this while the
+/// Space runs (each time it attaches the channel, and every
+/// [`RENEW_AFTER_SECS`]).
+pub const DEFAULT_TTL_SECS: u64 = 24 * 3600;
+/// When the host replaces a live capability with a fresh one.
+pub const RENEW_AFTER_SECS: u64 = 12 * 3600;
+/// Default depth below a Space a person made: its children and their
+/// children.
+pub const DEFAULT_MAX_DEPTH: u32 = 2;
+/// The deepest a tree may go, whatever is asked.
+pub const HARD_MAX_DEPTH: u32 = 4;
+
+type HmacSha256 = Hmac<Sha256>;
+
+/// What a capability says.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Claims {
+ /// The Space it belongs to.
+ pub space: String,
+ /// The root of the Space's tree (itself for a Space a person made).
+ pub root: String,
+ /// How deep the Space is (0 for a Space a person made).
+ pub depth: u32,
+ /// The deepest any Space of the tree may be.
+ pub max_depth: u32,
+ /// Expiry, unix seconds.
+ pub exp: u64,
+ /// Issued at, unix seconds.
+ pub iat: u64,
+ /// Unique id; the record holds the live one.
+ pub jti: String,
+ /// Which host key made it (first 16 hex of SHA-256 of the key).
+ pub kid: String,
+}
+
+/// Why a capability is refused. Every refusal reads the same to the
+/// caller ([`Refusal::message`]); the kind is for logs and tests.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Refusal {
+ /// Not `cuaspawn1.<claims>.<mac>`.
+ Malformed,
+ /// The MAC does not match this host's key.
+ BadSignature,
+ /// Made by another host key.
+ OtherHost,
+ /// Past `exp`.
+ Expired,
+ /// Names another Space than the channel's.
+ WrongSpace,
+ /// Not the Space's live capability (replaced or revoked).
+ Revoked,
+}
+
+impl Refusal {
+ /// The one answer a caller gets.
+ pub fn message(self) -> &'static str {
+ "this Space's spawn capability is missing, expired or not valid here"
+ }
+}
+
+/// A live capability's record.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Record {
+ /// The live capability's id.
+ pub jti: String,
+ /// Its tree's root.
+ pub root: String,
+ /// Its depth.
+ pub depth: u32,
+ /// Its tree's depth limit.
+ pub max_depth: u32,
+ /// Issued at, unix seconds.
+ pub iat: u64,
+ /// Expiry, unix seconds.
+ pub exp: u64,
+}
+
+/// Mints, checks and revokes capabilities for one host home.
+pub struct Authority {
+ dir: PathBuf,
+ key: [u8; 32],
+ kid: String,
+ records: Mutex<BTreeMap<String, Record>>,
+}
+
+fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+}
+
+fn b64(bytes: &[u8]) -> String {
+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
+}
+
+fn unb64(s: &str) -> Option<Vec<u8>> {
+ base64::engine::general_purpose::URL_SAFE_NO_PAD
+ .decode(s.as_bytes())
+ .ok()
+}
+
+/// Writes `bytes` to `path` atomically, 0600 on Unix.
+fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
+ use std::io::Write as _;
+ let tmp = path.with_extension(format!("tmp-{:016x}", rand::random::<u64>()));
+ {
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt as _;
+ options.mode(0o600);
+ }
+ let mut f = options.open(&tmp)?;
+ f.write_all(bytes)?;
+ f.sync_all()?;
+ }
+ std::fs::rename(&tmp, path).inspect_err(|_| {
+ let _ = std::fs::remove_file(&tmp);
+ })
+}
+
+impl Authority {
+ /// Opens (or creates) the authority in `<home>/spawn`.
+ pub fn open(home: &Path) -> std::io::Result<Self> {
+ let dir = home.join("spawn");
+ std::fs::create_dir_all(&dir)?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700))?;
+ }
+ let key_path = dir.join("key");
+ let key = match std::fs::read(&key_path) {
+ Ok(k) if k.len() == 32 => {
+ let mut key = [0u8; 32];
+ key.copy_from_slice(&k);
+ key
+ }
+ Ok(_) => {
+ return Err(std::io::Error::other(format!(
+ "{} is not a spawn key",
+ key_path.display()
+ )));
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ let key: [u8; 32] = rand::random();
+ write_private(&key_path, &key)?;
+ key
+ }
+ Err(e) => return Err(e),
+ };
+ let kid = hex_prefix(&Sha256::digest(key));
+ let records = match std::fs::read(dir.join("capabilities.json")) {
+ Ok(b) => serde_json::from_slice(&b).unwrap_or_default(),
+ Err(_) => BTreeMap::new(),
+ };
+ Ok(Self {
+ dir,
+ key,
+ kid,
+ records: Mutex::new(records),
+ })
+ }
+
+ fn save(&self, records: &BTreeMap<String, Record>) {
+ let bytes = serde_json::to_vec_pretty(records).unwrap_or_default();
+ if let Err(e) = write_private(&self.dir.join("capabilities.json"), &bytes) {
+ tracing::warn!(error = %e, "could not save the spawn capability records");
+ }
+ }
+
+ fn mac(&self, payload: &str) -> Vec<u8> {
+ let mut mac = HmacSha256::new_from_slice(&self.key).expect("any key length");
+ mac.update(MAC_CONTEXT);
+ mac.update(payload.as_bytes());
+ mac.finalize().into_bytes().to_vec()
+ }
+
+ /// Mints a capability for `space`, replacing (and so revoking) the one
+ /// it had.
+ pub fn mint(
+ &self,
+ space: &str,
+ root: &str,
+ depth: u32,
+ max_depth: u32,
+ ttl_secs: u64,
+ ) -> String {
+ let iat = now();
+ let claims = Claims {
+ space: space.to_owned(),
+ root: root.to_owned(),
+ depth,
+ max_depth: max_depth.min(HARD_MAX_DEPTH),
+ exp: iat.saturating_add(ttl_secs),
+ iat,
+ jti: format!("{:032x}", rand::random::<u128>()),
+ kid: self.kid.clone(),
+ };
+ let payload = b64(&serde_json::to_vec(&claims).expect("claims serialize"));
+ let token = format!("{PREFIX}.{payload}.{}", b64(&self.mac(&payload)));
+ let mut records = self.records.lock().unwrap();
+ records.insert(
+ space.to_owned(),
+ Record {
+ jti: claims.jti,
+ root: claims.root,
+ depth: claims.depth,
+ max_depth: claims.max_depth,
+ iat: claims.iat,
+ exp: claims.exp,
+ },
+ );
+ self.save(&records);
+ token
+ }
+
+ /// Checks `token` as presented on the channel of `channel_space`.
+ pub fn verify(&self, token: &str, channel_space: &str) -> Result<Claims, Refusal> {
+ let mut parts = token.trim().split('.');
+ let (Some(prefix), Some(payload), Some(sig), None) =
+ (parts.next(), parts.next(), parts.next(), parts.next())
+ else {
+ return Err(Refusal::Malformed);
+ };
+ if prefix != PREFIX {
+ return Err(Refusal::Malformed);
+ }
+ let sig = unb64(sig).ok_or(Refusal::Malformed)?;
+ let mut mac = HmacSha256::new_from_slice(&self.key).expect("any key length");
+ mac.update(MAC_CONTEXT);
+ mac.update(payload.as_bytes());
+ mac.verify_slice(&sig).map_err(|_| Refusal::BadSignature)?;
+ let claims: Claims = unb64(payload)
+ .and_then(|b| serde_json::from_slice(&b).ok())
+ .ok_or(Refusal::Malformed)?;
+ if claims.kid != self.kid {
+ return Err(Refusal::OtherHost);
+ }
+ if claims.exp <= now() {
+ return Err(Refusal::Expired);
+ }
+ if claims.space != channel_space {
+ return Err(Refusal::WrongSpace);
+ }
+ let records = self.records.lock().unwrap();
+ match records.get(&claims.space) {
+ Some(r) if r.jti == claims.jti => Ok(claims),
+ _ => Err(Refusal::Revoked),
+ }
+ }
+
+ /// The live record of `space`.
+ pub fn record(&self, space: &str) -> Option<Record> {
+ self.records.lock().unwrap().get(space).cloned()
+ }
+
+ /// Ends `space`'s capability. True when it had one.
+ pub fn revoke(&self, space: &str) -> bool {
+ let mut records = self.records.lock().unwrap();
+ let had = records.remove(space).is_some();
+ if had {
+ self.save(&records);
+ }
+ had
+ }
+
+ /// Spaces holding a live record.
+ pub fn spaces(&self) -> Vec<String> {
+ self.records.lock().unwrap().keys().cloned().collect()
+ }
+}
+
+fn hex_prefix(bytes: &[u8]) -> String {
+ bytes.iter().take(8).map(|b| format!("{b:02x}")).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn authority() -> (tempfile::TempDir, Authority) {
+ let dir = tempfile::tempdir().unwrap();
+ let a = Authority::open(dir.path()).unwrap();
+ (dir, a)
+ }
+
+ #[test]
+ fn a_capability_works_only_on_its_own_spaces_channel() {
+ let (_d, a) = authority();
+ let cap = a.mint("parent", "parent", 0, 2, 60);
+ let claims = a.verify(&cap, "parent").unwrap();
+ assert_eq!(
+ (claims.space.as_str(), claims.root.as_str(), claims.depth),
+ ("parent", "parent", 0)
+ );
+ // Copied into a sibling, a child or another tree: refused.
+ assert_eq!(a.verify(&cap, "sibling"), Err(Refusal::WrongSpace));
+ assert_eq!(a.verify(&cap, "parent.c1"), Err(Refusal::WrongSpace));
+ }
+
+ #[test]
+ fn minting_again_or_revoking_ends_the_old_capability() {
+ let (_d, a) = authority();
+ let old = a.mint("s", "s", 0, 2, 60);
+ let new = a.mint("s", "s", 0, 2, 60);
+ assert_eq!(a.verify(&old, "s"), Err(Refusal::Revoked));
+ assert!(a.verify(&new, "s").is_ok());
+ assert!(a.revoke("s"));
+ assert_eq!(a.verify(&new, "s"), Err(Refusal::Revoked));
+ assert!(!a.revoke("s"));
+ }
+
+ #[test]
+ fn a_replayed_capability_from_a_snapshot_is_refused_after_a_fresh_mint() {
+ // A memory snapshot holds the capability the guest had; the fork
+ // restored from it gets its own, and the parent's replaced one.
+ let (_d, a) = authority();
+ let in_snapshot = a.mint("parent", "parent", 0, 2, 60);
+ let _fork = a.mint("fork", "fork", 0, 2, 60);
+ assert_eq!(a.verify(&in_snapshot, "fork"), Err(Refusal::WrongSpace));
+ let _renewed = a.mint("parent", "parent", 0, 2, 60);
+ assert_eq!(a.verify(&in_snapshot, "parent"), Err(Refusal::Revoked));
+ }
+
+ #[test]
+ fn tampering_expiry_and_other_hosts_are_refused() {
+ let (_d, a) = authority();
+ let cap = a.mint("s", "s", 0, 2, 60);
+ // Raise the depth limit in the claims, keep the MAC.
+ let parts: Vec<&str> = cap.split('.').collect();
+ let mut claims: Claims = serde_json::from_slice(&unb64(parts[1]).unwrap()).unwrap();
+ claims.max_depth = 4;
+ let forged = format!(
+ "{PREFIX}.{}.{}",
+ b64(&serde_json::to_vec(&claims).unwrap()),
+ parts[2]
+ );
+ assert_eq!(a.verify(&forged, "s"), Err(Refusal::BadSignature));
+ assert_eq!(a.verify("nonsense", "s"), Err(Refusal::Malformed));
+ assert_eq!(a.verify("cuaspawn1.a.b.c", "s"), Err(Refusal::Malformed));
+ let expired = a.mint("e", "e", 0, 2, 0);
+ assert_eq!(a.verify(&expired, "e"), Err(Refusal::Expired));
+ // Another host's key: its capabilities mean nothing here.
+ let (_d2, other) = authority();
+ let theirs = other.mint("s", "s", 0, 2, 60);
+ assert_eq!(a.verify(&theirs, "s"), Err(Refusal::BadSignature));
+ }
+
+ #[test]
+ fn the_key_and_records_survive_a_restart_and_the_depth_is_capped() {
+ let dir = tempfile::tempdir().unwrap();
+ let cap = {
+ let a = Authority::open(dir.path()).unwrap();
+ a.mint("s", "r", 1, 9, 60)
+ };
+ let a = Authority::open(dir.path()).unwrap();
+ let claims = a.verify(&cap, "s").unwrap();
+ assert_eq!(claims.max_depth, HARD_MAX_DEPTH);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ for f in ["key", "capabilities.json"] {
+ let mode = std::fs::metadata(dir.path().join("spawn").join(f))
+ .unwrap()
+ .permissions()
+ .mode();
+ assert_eq!(mode & 0o777, 0o600, "{f}");
+ }
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-daemon/src/children/mod.rs b/libs/cua/crates/cua-daemon/src/children/mod.rs
new file mode 100644
index 0000000000..5402f0bff7
--- /dev/null
+++ b/libs/cua/crates/cua-daemon/src/children/mod.rs
@@ -0,0 +1,379 @@
+//! Child Spaces: a Space makes, lists and deletes Spaces of its own, on a
+//! narrow channel only it can reach.
+//!
+//! - [`capability`]: the per-Space spawn capability this host mints.
+//! - [`tree`]: who is whose child; every answer stays inside the caller's
+//! subtree.
+//! - [`api`]: `SpaceService` and `DaemonService` answered for one Space's
+//! subtree (so `cua` and the SDKs work in a Space unchanged).
+//! - [`bridge`]: keeps the channel of each running Space with children on:
+//! the guest's cua-spacesd listens on its own loopback and relays each
+//! connection over a WebSocket this host opened (`TunnelService.
+//! StartSpawn`), so the channel's Space is known by the connection, never
+//! by what the guest says. It is never the daemon's socket or loopback
+//! listener, and a guest never holds the daemon's token.
+
+pub mod api;
+pub mod bridge;
+pub mod budget;
+pub mod capability;
+pub mod reaper;
+#[cfg(test)]
+mod tests;
+pub mod tree;
+
+use std::path::Path;
+use std::sync::Arc;
+
+use axum::body::Body as AxumBody;
+use axum::extract::{Path as AxPath, State};
+use axum::response::{IntoResponse, Response};
+use http::Request;
+
+use crate::server::Shared;
+
+/// The feature a daemon reached on a spawn channel reports.
+pub const CHILDREN_FEATURE: &str = "children";
+
+/// The capability a request presented (for the passthrough's bearer).
+#[derive(Clone, Debug)]
+pub struct Presented(pub String);
+
+/// The channel's address as the caller dialed it (`127.0.0.1:<port>` in
+/// the guest), for URLs handed back to it.
+#[derive(Clone, Debug)]
+pub struct Origin(pub String);
+
+fn origin<B>(req: &Request<B>) -> String {
+ req.uri()
+ .authority()
+ .map(|a| a.to_string())
+ .or_else(|| {
+ req.headers()
+ .get(http::header::HOST)
+ .and_then(|h| h.to_str().ok())
+ .map(str::to_owned)
+ })
+ .unwrap_or_default()
+}
+
+/// The daemon's child-Space state.
+pub struct Children {
+ /// Mints and checks capabilities.
+ pub authority: capability::Authority,
+ /// Trees' budgets and the reservations of creates in flight.
+ pub budget: budget::Ledger,
+}
+
+impl Children {
+ /// Opens the state in `home`.
+ pub fn open(home: &Path) -> std::io::Result<Self> {
+ Ok(Self {
+ authority: capability::Authority::open(home)?,
+ budget: budget::Ledger::open(home),
+ })
+ }
+}
+
+/// A reservation in a tree's budget, released when dropped (the create is
+/// over: its child now counts as used, or it failed).
+pub(crate) struct Held {
+ shared: Arc<Shared>,
+ ticket: Option<budget::Ticket>,
+}
+
+impl Drop for Held {
+ fn drop(&mut self) {
+ if let (Some(t), Some(c)) = (self.ticket.take(), self.shared.children.as_deref()) {
+ c.budget.release(t);
+ }
+ }
+}
+
+/// What the children of `root`'s tree hold now: each counts as a Space;
+/// the ones not stopped hold their vCPUs and memory.
+pub(crate) fn tree_usage(shared: &Shared, root: &str) -> budget::Usage {
+ let spaces = shared.runtime.spaces();
+ let links = api::links_of(spaces);
+ let mut u = budget::Usage::default();
+ let ledger = shared.children.as_deref().map(|c| &c.budget);
+ for id in tree::subtree(&links, root) {
+ u.spaces += 1;
+ let (power, _) = spaces.power_of(&id);
+ if power == "stopped" {
+ continue;
+ }
+ let (cpus, mem) = match ledger.and_then(|l| l.cost(&id)) {
+ Some(c) => (c.vcpus, c.memory_mb),
+ None => local_size(shared, &id),
+ };
+ u.vcpus += cpus;
+ u.memory_mb += mem;
+ }
+ if let Some(l) = ledger {
+ (u.usd_per_hour, u.usd_spent) = l.spend(root, unix_now());
+ }
+ u
+}
+
+fn unix_now() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+}
+
+/// Records what a new child of `root`'s tree was made with (its size and
+/// cost per hour), so its tree's use and spend count it.
+pub(crate) fn record_cost(shared: &Shared, root: &str, child: &str, ask: budget::Ask) {
+ if let Some(c) = shared.children.as_deref() {
+ c.budget.record(root, child, &ask, unix_now());
+ }
+}
+
+/// A local Space's vCPUs and memory (MiB) as recorded, else the create
+/// defaults (2, 4096).
+pub(crate) fn local_size(shared: &Shared, id: &str) -> (u32, u64) {
+ let recorded = id.strip_prefix("local:").and_then(|name| {
+ let cua_sandbox_core::SandboxState::Local(l) =
+ shared.runtime.sandboxes().state().load(name)?
+ else {
+ return None;
+ };
+ Some((l.cpu_count, l.memory_mb))
+ });
+ let (cpus, mem) = recorded.unwrap_or((None, None));
+ (cpus.unwrap_or(2), mem.unwrap_or(4096))
+}
+
+/// Reserves `ask` in `root`'s tree, or says plainly why it does not fit.
+pub(crate) fn admit(
+ shared: &Arc<Shared>,
+ root: &str,
+ ask: budget::Ask,
+) -> Result<Held, tonic::Status> {
+ let Some(c) = shared.children.as_deref() else {
+ return Ok(Held {
+ shared: shared.clone(),
+ ticket: None,
+ });
+ };
+ let limits = c.budget.budget(root).effective();
+ let used = tree_usage(shared, root);
+ let ticket = c
+ .budget
+ .reserve(root, &limits, &used, ask)
+ .map_err(|r| tonic::Status::resource_exhausted(r.0))?;
+ Ok(Held {
+ shared: shared.clone(),
+ ticket: Some(ticket),
+ })
+}
+
+/// The orphans of this computer as the reaper judges them now (without
+/// changing what it remembers).
+pub(crate) fn orphans(shared: &Shared) -> Vec<cua_proto::daemon::v1::Orphan> {
+ use reaper::Verdict;
+ let Some(seen) = bridge::seen(shared) else {
+ return Vec::new();
+ };
+ let mut memory = reaper::Memory::load(shared.runtime.spaces().home_dir());
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ let parents: std::collections::BTreeMap<String, String> = seen
+ .iter()
+ .filter_map(|s| Some((s.id.clone(), s.parent.clone()?)))
+ .collect();
+ reaper::judge(&seen, &mut memory, now)
+ .into_iter()
+ .filter_map(|(space, v)| {
+ let parent = parents.get(&space).cloned().unwrap_or_default();
+ let (state, why, ends_in_secs) = match v {
+ Verdict::Keep => return None,
+ Verdict::Waiting { left } => (
+ "ending",
+ format!("its parent {parent} is gone; it ends after the grace period"),
+ i64::try_from(left).unwrap_or(i64::MAX),
+ ),
+ Verdict::End { why } => ("ending", why, 0),
+ Verdict::Orphan { why } => ("listed", why, 0),
+ };
+ Some(cua_proto::daemon::v1::Orphan {
+ space,
+ parent,
+ state: state.into(),
+ why,
+ ends_in_secs,
+ })
+ })
+ .collect()
+}
+
+impl Shared {
+ /// The capability authority, when child Spaces are available.
+ pub(crate) fn spawn_authority(&self) -> Option<&capability::Authority> {
+ self.children.as_deref().map(|c| &c.authority)
+ }
+}
+
+/// The bearer of a request (`authorization: Bearer <capability>`).
+fn bearer<B>(req: &Request<B>) -> Option<String> {
+ req.headers()
+ .get(http::header::AUTHORIZATION)
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.strip_prefix("Bearer "))
+ .map(|v| v.trim().to_owned())
+}
+
+fn unauthenticated(grpc: bool, message: &str) -> Response {
+ if grpc {
+ let status = tonic::Status::unauthenticated(message);
+ return status.into_http::<AxumBody>();
+ }
+ (http::StatusCode::UNAUTHORIZED, message.to_owned()).into_response()
+}
+
+/// The app one Space's channel serves.
+pub(crate) fn channel_app(shared: Arc<Shared>, space: String) -> axum::Router {
+ use cua_proto::daemon::v1::{
+ daemon_service_server::DaemonServiceServer, space_service_server::SpaceServiceServer,
+ };
+ let scoped = api::Scoped {
+ shared: shared.clone(),
+ space: space.clone(),
+ };
+ let limit = cua_spacesd_client::MAX_MESSAGE_BYTES;
+ let grpc = tonic::service::Routes::new(
+ SpaceServiceServer::new(scoped.clone())
+ .max_decoding_message_size(limit)
+ .max_encoding_message_size(limit),
+ )
+ .add_service(DaemonServiceServer::new(scoped.clone()))
+ .into_axum_router();
+ let routes = axum::Router::new()
+ .route(
+ "/v1/spaces/{key}/env/{*rest}",
+ axum::routing::any(child_env_passthrough),
+ )
+ .with_state(scoped)
+ .merge(grpc);
+ let check = move |mut req: Request<AxumBody>, next: axum::middleware::Next| {
+ let shared = shared.clone();
+ let space = space.clone();
+ async move {
+ let grpc = crate::passthrough::is_grpc(&req);
+ // A caller header is never identity here: the channel is.
+ crate::server::strip_forwarded_caller(req.headers_mut());
+ let Some(authority) = shared.spawn_authority() else {
+ return unauthenticated(grpc, "child Spaces are off on this computer");
+ };
+ // An experiment: while it is off, no capability does anything.
+ if !cua_vmm::experiments::enabled(cua_vmm::experiments::Gate::ChildSpaces) {
+ return unauthenticated(
+ grpc,
+ &cua_vmm::experiments::Gate::ChildSpaces.off_message(),
+ );
+ }
+ let Some(token) = bearer(&req) else {
+ return unauthenticated(grpc, capability::Refusal::Malformed.message());
+ };
+ match authority.verify(&token, &space) {
+ Ok(claims) => {
+ let at = Origin(origin(&req));
+ req.extensions_mut().insert(claims);
+ req.extensions_mut().insert(Presented(token));
+ req.extensions_mut().insert(at);
+ next.run(req).await
+ }
+ Err(why) => {
+ tracing::warn!(space = %space, ?why, "spawn capability refused");
+ unauthenticated(grpc, why.message())
+ }
+ }
+ }
+ };
+ routes.layer(axum::middleware::from_fn(check))
+}
+
+/// gRPC methods of a child's cua-spacesd its parent may not call: the
+/// child's own spawn channel belongs to the host alone.
+const CHILD_ENV_DENIED: &[&str] = &[
+ "/cua.env.v1.TunnelService/StartSpawn",
+ "/cua.env.v1.TunnelService/StopSpawn",
+];
+
+/// `/v1/spaces/<key>/env/<rest>` on a channel: the daemon's env
+/// passthrough, for the caller's descendants only.
+async fn child_env_passthrough(
+ State(scoped): State<api::Scoped>,
+ AxPath((key, rest)): AxPath<(String, String)>,
+ req: Request<AxumBody>,
+) -> Response {
+ let (req, ws) = match crate::passthrough::split_upgrade(req).await {
+ Ok(v) => v,
+ Err(r) => return *r,
+ };
+ let grpc = ws.is_none() && crate::passthrough::is_grpc(&req);
+ let refuse = |status: tonic::Status| -> Response {
+ if grpc {
+ status.into_http::<AxumBody>()
+ } else {
+ (http::StatusCode::NOT_FOUND, status.message().to_owned()).into_response()
+ }
+ };
+ let id = match crate::passthrough::space_from_key(&key) {
+ Ok(id) => id,
+ Err(_) => return refuse(api::not_found(&key)),
+ };
+ let child = match scoped.resolve(&id) {
+ Ok(c) if c.id == id => c,
+ Ok(_) | Err(_) => return refuse(api::not_found(&id)),
+ };
+ let path = format!("/{}", rest.trim_start_matches('/'));
+ if CHILD_ENV_DENIED.contains(&path.as_str()) || path == cua_proto::metadata::SPAWN_WS_PATH {
+ return refuse(tonic::Status::permission_denied(
+ "a child's spawn channel belongs to its host",
+ ));
+ }
+ let space = match scoped.shared.runtime.spaces().space(&child.id).await {
+ Ok(s) => s,
+ Err(e) => return crate::passthrough::error_response(e.into(), grpc),
+ };
+ let headers = if ws.is_some() {
+ match space.websocket_headers().await {
+ Ok(h) => h,
+ Err(e) => return crate::passthrough::error_response(e.into(), false),
+ }
+ } else {
+ vec![]
+ };
+ let env = match space.spacesd() {
+ Ok(env) => env,
+ Err(e) => return crate::passthrough::error_response(e.into(), grpc),
+ };
+ crate::passthrough::forward(env, headers, &rest, req, ws).await
+}
+
+/// Serves `app` on one relayed stream (HTTP/1.1 or h2c).
+pub(crate) async fn serve_stream<T>(app: axum::Router, io: T)
+where
+ T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
+{
+ use hyper_util::{
+ rt::{TokioExecutor, TokioIo},
+ server::conn::auto::Builder,
+ service::TowerToHyperService,
+ };
+ let svc = TowerToHyperService::new(app);
+ let mut builder = Builder::new(TokioExecutor::new());
+ builder
+ .http2()
+ .initial_stream_window_size(cua_spacesd_client::transport::STREAM_WINDOW)
+ .initial_connection_window_size(cua_spacesd_client::transport::CONNECTION_WINDOW)
+ .max_frame_size(cua_spacesd_client::transport::MAX_FRAME);
+ let _ = builder
+ .serve_connection_with_upgrades(TokioIo::new(io), svc)
+ .await;
+}
diff --git a/libs/cua/crates/cua-daemon/src/children/reaper.rs b/libs/cua/crates/cua-daemon/src/children/reaper.rs
new file mode 100644
index 0000000000..22c9614bbf
--- /dev/null
+++ b/libs/cua/crates/cua-daemon/src/children/reaper.rs
@@ -0,0 +1,266 @@
+//! Orphaned children: which ones this host may end, and which it may only
+//! list (`cua spaces orphans`).
+//!
+//! A child is ended by automation only on positive proof that its parent is
+//! gone, from this host's own records:
+//!
+//! - its parent is a Space this host runs (`local:`), and
+//! - that parent is not in this host's registry, or it is a different Space
+//! now (deleted and made again under the same name: its creation time
+//! changed), and
+//! - that has been so for the whole grace period (15 minutes), across
+//! passes, measured by this host's clock.
+//!
+//! Anything else is never ended here: a parent on another computer that does
+//! not answer is a partition, not proof. Such a child stays and is listed
+//! as an orphan; its own lifetime (no longer than its parent's, set when it
+//! was made) is the backstop that works with every daemon down. A read of
+//! the registry that fails decides nothing.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+
+/// How long a parent must be provably gone before its children are ended.
+pub const GRACE_SECS: u64 = 15 * 60;
+
+/// One registered Space as the reaper sees it.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Seen {
+ /// Its id.
+ pub id: String,
+ /// Its parent's id, for a child.
+ pub parent: Option<String>,
+ /// When it was made (unix seconds; 0 unknown).
+ pub created_at: u64,
+}
+
+/// What to do with one child.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Verdict {
+ /// Its parent is here: nothing.
+ Keep,
+ /// Its parent is provably gone, but not for the whole grace yet.
+ Waiting {
+ /// Seconds left.
+ left: u64,
+ },
+ /// Its parent is provably gone for the grace: end it.
+ End {
+ /// Why, for the event and the log.
+ why: String,
+ },
+ /// Its parent is not this host's to judge: list it, never end it.
+ Orphan {
+ /// Why.
+ why: String,
+ },
+}
+
+/// What the reaper remembers between passes (`<home>/spawn/leases.json`).
+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
+pub struct Memory {
+ /// Child → the creation time of the parent it was made under.
+ #[serde(default)]
+ pub parent_born: BTreeMap<String, u64>,
+ /// Child → when this host first saw its parent gone.
+ #[serde(default)]
+ pub gone_since: BTreeMap<String, u64>,
+}
+
+impl Memory {
+ fn path(home: &Path) -> PathBuf {
+ home.join("spawn").join("leases.json")
+ }
+
+ /// Loads it (empty when missing or unreadable).
+ pub fn load(home: &Path) -> Self {
+ std::fs::read(Self::path(home))
+ .ok()
+ .and_then(|b| serde_json::from_slice(&b).ok())
+ .unwrap_or_default()
+ }
+
+ /// Saves it.
+ pub fn save(&self, home: &Path) -> std::io::Result<()> {
+ let p = Self::path(home);
+ if let Some(d) = p.parent() {
+ std::fs::create_dir_all(d)?;
+ }
+ let tmp = p.with_extension("json.tmp");
+ std::fs::write(&tmp, serde_json::to_vec_pretty(self).unwrap_or_default())?;
+ std::fs::rename(&tmp, &p)
+ }
+}
+
+/// Judges every child of `seen` at `now`, updating `memory`.
+pub fn judge(seen: &[Seen], memory: &mut Memory, now: u64) -> BTreeMap<String, Verdict> {
+ let by_id: BTreeMap<&str, &Seen> = seen.iter().map(|s| (s.id.as_str(), s)).collect();
+ let children: BTreeSet<&str> = seen
+ .iter()
+ .filter(|s| s.parent.is_some())
+ .map(|s| s.id.as_str())
+ .collect();
+ // Forget what is about Spaces that are gone.
+ memory
+ .parent_born
+ .retain(|c, _| children.contains(c.as_str()));
+ memory
+ .gone_since
+ .retain(|c, _| children.contains(c.as_str()));
+ let mut out = BTreeMap::new();
+ for s in seen {
+ let Some(parent) = &s.parent else { continue };
+ let verdict = if !parent.starts_with("local:") {
+ Verdict::Orphan {
+ why: format!(
+ "its parent {parent} runs on another computer; only that computer or its \
+ own lifetime ends it"
+ ),
+ }
+ .only_if_gone(by_id.contains_key(parent.as_str()))
+ } else {
+ let here = by_id.get(parent.as_str());
+ let born = here.map(|p| p.created_at);
+ let first = *memory
+ .parent_born
+ .entry(s.id.clone())
+ .or_insert_with(|| born.unwrap_or(0));
+ let same = match (born, first) {
+ (Some(b), f) => f == 0 || b == 0 || b == f,
+ (None, _) => false,
+ };
+ if here.is_some() && same {
+ memory.gone_since.remove(&s.id);
+ Verdict::Keep
+ } else {
+ let since = *memory.gone_since.entry(s.id.clone()).or_insert(now);
+ let gone_for = now.saturating_sub(since);
+ if gone_for >= GRACE_SECS {
+ Verdict::End {
+ why: if here.is_some() {
+ format!("its parent {parent} was deleted and made again")
+ } else {
+ format!("its parent {parent} was deleted")
+ },
+ }
+ } else {
+ Verdict::Waiting {
+ left: GRACE_SECS - gone_for,
+ }
+ }
+ }
+ };
+ out.insert(s.id.clone(), verdict);
+ }
+ out
+}
+
+impl Verdict {
+ /// An `Orphan` only while its parent is not registered here at all (a
+ /// remote parent this host also knows about is kept).
+ fn only_if_gone(self, parent_known_here: bool) -> Self {
+ if parent_known_here {
+ Verdict::Keep
+ } else {
+ self
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn s(id: &str, parent: Option<&str>, at: u64) -> Seen {
+ Seen {
+ id: id.into(),
+ parent: parent.map(str::to_owned),
+ created_at: at,
+ }
+ }
+
+ #[test]
+ fn a_child_ends_only_after_its_local_parent_is_gone_for_the_grace() {
+ let mut m = Memory::default();
+ let with = [s("local:p", None, 10), s("local:c", Some("local:p"), 20)];
+ assert_eq!(judge(&with, &mut m, 100)["local:c"], Verdict::Keep);
+ let without = [s("local:c", Some("local:p"), 20)];
+ assert_eq!(
+ judge(&without, &mut m, 1000)["local:c"],
+ Verdict::Waiting { left: GRACE_SECS }
+ );
+ assert!(matches!(
+ judge(&without, &mut m, 1000 + GRACE_SECS - 1)["local:c"],
+ Verdict::Waiting { left: 1 }
+ ));
+ assert!(matches!(
+ judge(&without, &mut m, 1000 + GRACE_SECS)["local:c"],
+ Verdict::End { .. }
+ ));
+ }
+
+ #[test]
+ fn a_parent_that_comes_back_resets_the_clock() {
+ let mut m = Memory::default();
+ let with = [s("local:p", None, 10), s("local:c", Some("local:p"), 20)];
+ let without = [s("local:c", Some("local:p"), 20)];
+ judge(&with, &mut m, 0);
+ judge(&without, &mut m, 100);
+ judge(&with, &mut m, 200);
+ assert!(matches!(
+ judge(&without, &mut m, 300 + GRACE_SECS - 10)["local:c"],
+ Verdict::Waiting { .. }
+ ));
+ }
+
+ #[test]
+ fn a_parent_made_again_under_the_same_name_is_not_the_parent() {
+ let mut m = Memory::default();
+ judge(
+ &[s("local:p", None, 10), s("local:c", Some("local:p"), 20)],
+ &mut m,
+ 0,
+ );
+ let again = [s("local:p", None, 99), s("local:c", Some("local:p"), 20)];
+ assert!(matches!(
+ judge(&again, &mut m, 50)["local:c"],
+ Verdict::Waiting { .. }
+ ));
+ assert!(matches!(
+ judge(&again, &mut m, 50 + GRACE_SECS)["local:c"],
+ Verdict::End { .. }
+ ));
+ }
+
+ #[test]
+ fn a_remote_parent_is_never_proof() {
+ let mut m = Memory::default();
+ let seen = [s("local:c", Some("relay:abcdefgh"), 20)];
+ for t in [0, GRACE_SECS * 10] {
+ assert!(matches!(
+ judge(&seen, &mut m, t)["local:c"],
+ Verdict::Orphan { .. }
+ ));
+ }
+ }
+
+ #[test]
+ fn memory_survives_a_restart() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut m = Memory::default();
+ judge(&[s("local:c", Some("local:p"), 20)], &mut m, 500);
+ m.save(dir.path()).unwrap();
+ let mut back = Memory::load(dir.path());
+ assert_eq!(back, m);
+ assert!(matches!(
+ judge(
+ &[s("local:c", Some("local:p"), 20)],
+ &mut back,
+ 500 + GRACE_SECS
+ )["local:c"],
+ Verdict::End { .. }
+ ));
+ }
+}
diff --git a/libs/cua/crates/cua-daemon/src/children/tests.rs b/libs/cua/crates/cua-daemon/src/children/tests.rs
new file mode 100644
index 0000000000..79a7e6cfbf
--- /dev/null
+++ b/libs/cua/crates/cua-daemon/src/children/tests.rs
@@ -0,0 +1,633 @@
+//! What a Space's spawn channel answers, attacked from inside the Space: a
+//! sibling, an ancestor, another tree, a guessed id, a name that collides
+//! with another Space, a replayed or copied capability, and owner calls.
+//! In-process: the channel's app on an in-memory stream, no VM.
+
+use std::sync::Arc;
+
+use cua_proto::daemon::v1::{
+ self as pb, daemon_service_client::DaemonServiceClient,
+ space_service_client::SpaceServiceClient,
+};
+use cua_spaces::registry::Credential;
+use tonic::{Code, Request};
+
+use super::api::LABEL_PARENT;
+use crate::server::Shared;
+use crate::{Runtime, RuntimeConfig};
+
+struct World {
+ _home: tempfile::TempDir,
+ shared: Arc<Shared>,
+}
+
+/// root ── a ── a1 ("dup")
+/// └─ b
+/// other ── o1
+/// owner-dup ("dup", a Space of the owner's own)
+fn world() -> World {
+ // Child Spaces are an experiment; these tests run with it on.
+ cua_vmm::experiments::set_enabled(cua_vmm::experiments::Gate::ChildSpaces, Some(true));
+ let home = tempfile::tempdir().unwrap();
+ let runtime = Runtime::new(RuntimeConfig {
+ state_dir: Some(home.path().join("sandboxes")),
+ spaces_home: Some(home.path().to_path_buf()),
+ ..Default::default()
+ })
+ .unwrap();
+ let shared = Shared::for_tests(runtime);
+ let spaces = shared.runtime.spaces();
+ let add = |id: &str, name: &str, parent: Option<(&str, &str, u32)>| {
+ spaces
+ .registry()
+ .upsert(
+ pb::Space {
+ id: id.into(),
+ name: name.into(),
+ ..Default::default()
+ },
+ Credential::default(),
+ )
+ .unwrap();
+ if let Some((parent, root, depth)) = parent {
+ spaces
+ .registry()
+ .update_meta(id, |m| {
+ m.parent = Some(parent.into());
+ m.root = Some(root.into());
+ m.depth = depth;
+ m.origin = Some("child".into());
+ m.labels.insert(LABEL_PARENT.into(), parent.into());
+ })
+ .unwrap();
+ }
+ };
+ add("local:root", "root", None);
+ add("local:a", "a", Some(("local:root", "local:root", 1)));
+ add("local:a1", "dup", Some(("local:a", "local:root", 2)));
+ add("local:b", "b", Some(("local:root", "local:root", 1)));
+ add("local:other", "other", None);
+ add("local:o1", "o1", Some(("local:other", "local:other", 1)));
+ add("local:owner-dup", "dup", None);
+ World {
+ _home: home,
+ shared,
+ }
+}
+
+type Chan = tonic::transport::Channel;
+
+/// A client of `space`'s channel (as the guest dials it).
+async fn channel(shared: &Arc<Shared>, space: &str) -> Chan {
+ let app = super::channel_app(shared.clone(), space.to_owned());
+ tonic::transport::Endpoint::from_static("http://127.0.0.1:41234")
+ .connect_with_connector(tower::service_fn(move |_: http::Uri| {
+ let app = app.clone();
+ async move {
+ let (ours, theirs) = tokio::io::duplex(1 << 20);
+ tokio::spawn(super::serve_stream(app, theirs));
+ Ok::<_, std::io::Error>(hyper_util::rt::TokioIo::new(ours))
+ }
+ }))
+ .await
+ .unwrap()
+}
+
+fn with<T>(token: &str, msg: T) -> Request<T> {
+ let mut r = Request::new(msg);
+ r.metadata_mut()
+ .insert("authorization", format!("Bearer {token}").parse().unwrap());
+ r
+}
+
+fn mint(shared: &Shared, space: &str, root: &str, depth: u32) -> String {
+ shared
+ .spawn_authority()
+ .unwrap()
+ .mint(space, root, depth, 2, 3600)
+}
+
+#[tokio::test]
+async fn a_space_sees_only_its_own_subtree() {
+ let w = world();
+ let cap = mint(&w.shared, "local:a", "local:root", 1);
+ let mut c = SpaceServiceClient::new(channel(&w.shared, "local:a").await);
+ let list = c
+ .list_spaces(with(&cap, pb::ListSpacesRequest::default()))
+ .await
+ .unwrap()
+ .into_inner();
+ let ids: Vec<_> = list.spaces.iter().map(|s| s.id.as_str()).collect();
+ assert_eq!(ids, ["local:a1"]);
+
+ // The root sees its whole tree, and nothing of the other tree or the
+ // owner's own Spaces.
+ let root_cap = mint(&w.shared, "local:root", "local:root", 0);
+ let mut r = SpaceServiceClient::new(channel(&w.shared, "local:root").await);
+ let mut ids: Vec<String> = r
+ .list_spaces(with(&root_cap, pb::ListSpacesRequest::default()))
+ .await
+ .unwrap()
+ .into_inner()
+ .spaces
+ .into_iter()
+ .map(|s| s.id)
+ .collect();
+ ids.sort();
+ assert_eq!(ids, ["local:a", "local:a1", "local:b"]);
+}
+
+#[tokio::test]
+async fn siblings_ancestors_other_trees_and_guesses_read_as_missing() {
+ let w = world();
+ let cap = mint(&w.shared, "local:a", "local:root", 1);
+ let mut c = SpaceServiceClient::new(channel(&w.shared, "local:a").await);
+ for target in [
+ "local:b",
+ "local:root",
+ "local:a",
+ "local:o1",
+ "local:other",
+ "local:owner-dup",
+ "local:does-not-exist",
+ "b",
+ "root",
+ ] {
+ let e = c
+ .resolve_space(with(
+ &cap,
+ pb::ResolveSpaceRequest {
+ space: target.into(),
+ },
+ ))
+ .await
+ .unwrap_err();
+ assert_eq!(e.code(), Code::NotFound, "{target}");
+ assert_eq!(
+ e.message(),
+ super::api::not_found(target).message(),
+ "{target}"
+ );
+ let e = c
+ .delete_space(with(
+ &cap,
+ pb::DeleteSpaceRequest {
+ space: target.into(),
+ keep_children: false,
+ },
+ ))
+ .await
+ .unwrap_err();
+ assert_eq!(e.code(), Code::NotFound, "delete {target}");
+ let e = c
+ .call_space_tool(with(
+ &cap,
+ pb::CallSpaceToolRequest {
+ name: "space_bash".into(),
+ arguments_json: serde_json::json!({"space": target, "command": "id"})
+ .to_string(),
+ },
+ ))
+ .await
+ .unwrap_err();
+ assert_eq!(e.code(), Code::NotFound, "space_bash {target}");
+ let e = c
+ .set_space_lifetime(with(
+ &cap,
+ pb::SetSpaceLifetimeRequest {
+ space: target.into(),
+ ..Default::default()
+ },
+ ))
+ .await
+ .unwrap_err();
+ assert_eq!(e.code(), Code::NotFound, "lifetime {target}");
+ }
+ // Nothing was deleted.
+ let left = w.shared.runtime.spaces().registry().list().unwrap().len();
+ assert_eq!(left, 7);
+}
+
+#[tokio::test]
+async fn a_name_shared_with_the_owners_space_means_the_child() {
+ let w = world();
+ let cap = mint(&w.shared, "local:a", "local:root", 1);
+ let mut c = SpaceServiceClient::new(channel(&w.shared, "local:a").await);
+ let s = c
+ .resolve_space(with(
+ &cap,
+ pb::ResolveSpaceRequest {
+ space: "dup".into(),
+ },
+ ))
+ .await
+ .unwrap()
+ .into_inner()
+ .space
+ .unwrap();
+ assert_eq!(s.id, "local:a1");
+}
+
+#[tokio::test]
+async fn only_this_spaces_live_capability_opens_its_channel() {
+ let w = world();
+ let mut c = SpaceServiceClient::new(channel(&w.shared, "local:a").await);
+ let list = |c: &mut SpaceServiceClient<Chan>, token: Option<String>| {
+ let mut c = c.clone();
+ async move {
+ let mut r = Request::new(pb::ListSpacesRequest::default());
+ if let Some(t) = token {
+ r.metadata_mut()
+ .insert("authorization", format!("Bearer {t}").parse().unwrap());
+ }
+ c.list_spaces(r).await.map(|_| ()).map_err(|e| e.code())
+ }
+ };
+ // None, garbage, the owner's daemon token.
+ assert_eq!(list(&mut c, None).await, Err(Code::Unauthenticated));
+ assert_eq!(
+ list(&mut c, Some("nope".into())).await,
+ Err(Code::Unauthenticated)
+ );
+ assert_eq!(
+ list(&mut c, Some(w.shared.token.clone())).await,
+ Err(Code::Unauthenticated)
+ );
+ // A sibling's, its parent's, its child's: live capabilities, but of
+ // other Spaces (copied out of a snapshot, a fork, a shared folder).
+ for (space, root, depth) in [
+ ("local:b", "local:root", 1),
+ ("local:root", "local:root", 0),
+ ("local:a1", "local:root", 2),
+ ] {
+ let other = mint(&w.shared, space, root, depth);
+ assert_eq!(
+ list(&mut c, Some(other)).await,
+ Err(Code::Unauthenticated),
+ "{space}'s capability"
+ );
+ }
+ // Its own, then replaced (renewed, or restored from a snapshot): the old
+ // one is dead.
+ let old = mint(&w.shared, "local:a", "local:root", 1);
+ assert_eq!(list(&mut c, Some(old.clone())).await, Ok(()));
+ let new = mint(&w.shared, "local:a", "local:root", 1);
+ assert_eq!(list(&mut c, Some(old)).await, Err(Code::Unauthenticated));
+ assert_eq!(list(&mut c, Some(new.clone())).await, Ok(()));
+ // Revoked (children turned off, the Space deleted).
+ w.shared.spawn_authority().unwrap().revoke("local:a");
+ assert_eq!(list(&mut c, Some(new)).await, Err(Code::Unauthenticated));
+}
+
+#[tokio::test]
+async fn owner_calls_are_refused_and_the_daemon_token_never_shows() {
+ let w = world();
+ let cap = mint(&w.shared, "local:a", "local:root", 1);
+ let chan = channel(&w.shared, "local:a").await;
+ let mut c = SpaceServiceClient::new(chan.clone());
+ let e = c
+ .list_hosts(with(&cap, pb::ListHostsRequest::default()))
+ .await
+ .unwrap_err();
+ assert_eq!(e.code(), Code::PermissionDenied);
+ let e = c
+ .add_space(with(&cap, pb::AddSpaceRequest::default()))
+ .await
+ .unwrap_err();
+ assert_eq!(e.code(), Code::PermissionDenied);
+ let e = c
+ .set_space_egress(with(&cap, pb::SetSpaceEgressRequest::default()))
+ .await
+ .unwrap_err();
+ assert_eq!(e.code(), Code::PermissionDenied);
+ // Owner tools through the tool call: refused by name.
+ for tool in [
+ "share_space",
+ "cloud_connect",
+ "create_space",
+ "agent_start",
+ ] {
+ let e = c
+ .call_space_tool(with(
+ &cap,
+ pb::CallSpaceToolRequest {
+ name: tool.into(),
+ arguments_json: serde_json::json!({"space": "local:a1"}).to_string(),
+ },
+ ))
+ .await
+ .unwrap_err();
+ assert_eq!(e.code(), Code::PermissionDenied, "{tool}");
+ }
+ let info = DaemonServiceClient::new(chan)
+ .get_info(with(&cap, pb::GetInfoRequest::default()))
+ .await
+ .unwrap()
+ .into_inner();
+ assert!(info.loopback_token.is_empty() && info.loopback_url.is_empty());
+ assert!(info.socket_path.is_empty());
+ assert!(info.features.contains(&super::CHILDREN_FEATURE.to_string()));
+}
+
+#[tokio::test]
+async fn a_create_becomes_a_child_or_a_plain_refusal() {
+ let w = world();
+ let scoped = super::api::Scoped {
+ shared: w.shared.clone(),
+ space: "local:a".into(),
+ };
+ let claims = |depth| super::capability::Claims {
+ space: "local:a".into(),
+ root: "local:root".into(),
+ depth,
+ max_depth: 2,
+ exp: u64::MAX,
+ iat: 0,
+ jti: String::new(),
+ kid: String::new(),
+ };
+ let r = scoped
+ .child_request(&claims(1), pb::CreateSpaceRequest::default())
+ .unwrap();
+ assert_eq!(r.location, "local");
+ assert_eq!(r.name, "a.c1");
+ // On this machine the record's tree fields place it, not labels.
+ assert_eq!(r.parent, "local:a");
+ assert!(r.labels.is_empty(), "{:?}", r.labels);
+
+ let refuse = |depth, req: pb::CreateSpaceRequest| {
+ scoped
+ .child_request(&claims(depth), req)
+ .unwrap_err()
+ .code()
+ };
+ // Deeper than the tree allows.
+ assert_eq!(refuse(2, Default::default()), Code::ResourceExhausted);
+ // Another machine or a linked cloud is allowed (inside the budget); an
+ // address is not; nor are reuse, durable and volumes.
+ assert!(
+ scoped
+ .child_request(
+ &claims(1),
+ pb::CreateSpaceRequest {
+ location: "aws".into(),
+ ..Default::default()
+ }
+ )
+ .is_ok()
+ );
+ assert_eq!(
+ refuse(
+ 1,
+ pb::CreateSpaceRequest {
+ location: "direct:10.0.0.9:7400".into(),
+ ..Default::default()
+ }
+ ),
+ Code::FailedPrecondition
+ );
+ assert_eq!(
+ refuse(
+ 1,
+ pb::CreateSpaceRequest {
+ reuse: true,
+ ..Default::default()
+ }
+ ),
+ Code::InvalidArgument
+ );
+ assert_eq!(
+ refuse(
+ 1,
+ pb::CreateSpaceRequest {
+ durable: true,
+ ..Default::default()
+ }
+ ),
+ Code::InvalidArgument
+ );
+ // A forged tree position.
+ assert_eq!(
+ refuse(
+ 1,
+ pb::CreateSpaceRequest {
+ labels: [(LABEL_PARENT.to_string(), "local:other".to_string())].into(),
+ ..Default::default()
+ }
+ ),
+ Code::InvalidArgument
+ );
+ assert_eq!(
+ refuse(
+ 1,
+ pb::CreateSpaceRequest {
+ parent: "local:other".into(),
+ ..Default::default()
+ }
+ ),
+ Code::InvalidArgument
+ );
+ // A network more open than the caller's.
+ assert_eq!(
+ refuse(
+ 1,
+ pb::CreateSpaceRequest {
+ widen: true,
+ ..Default::default()
+ }
+ ),
+ Code::PermissionDenied
+ );
+ // Egress: the parent's rules, never wider.
+ w.shared
+ .runtime
+ .spaces()
+ .registry()
+ .update_meta("local:a", |m| {
+ m.egress = cua_spaces::egress::EgressPolicy {
+ allow: vec![],
+ deny: vec!["0.0.0.0/0".into()],
+ }
+ })
+ .unwrap();
+ let r = scoped
+ .child_request(&claims(1), pb::CreateSpaceRequest::default())
+ .unwrap();
+ assert_eq!(r.egress.unwrap().deny, ["0.0.0.0/0"]);
+ assert_eq!(
+ refuse(
+ 1,
+ pb::CreateSpaceRequest {
+ egress: Some(pb::EgressPolicy {
+ allow: vec!["0.0.0.0/0".into()],
+ deny: vec![],
+ }),
+ ..Default::default()
+ }
+ ),
+ Code::PermissionDenied
+ );
+}
+
+#[tokio::test]
+async fn a_childs_env_is_reachable_only_below_and_never_its_spawn_channel() {
+ let w = world();
+ let cap = mint(&w.shared, "local:a", "local:root", 1);
+ let app = super::channel_app(w.shared.clone(), "local:a".into());
+ let get = |space: &str, rest: &str| {
+ let key = crate::passthrough::space_key(space);
+ http::Request::builder()
+ .method("POST")
+ .uri(format!("/v1/spaces/{key}/env/{rest}"))
+ .header("authorization", format!("Bearer {cap}"))
+ .header("content-type", "application/grpc")
+ .body(axum::body::Body::empty())
+ .unwrap()
+ };
+ use tower::ServiceExt as _;
+ let status = |r: http::Response<axum::body::Body>| {
+ r.headers()
+ .get("grpc-status")
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_owned)
+ };
+ // A sibling's and the owner's: not found.
+ for other in ["local:b", "local:owner-dup", "local:root"] {
+ let r = app
+ .clone()
+ .oneshot(get(other, "cua.env.v1.SystemService/GetCapabilities"))
+ .await
+ .unwrap();
+ assert_eq!(status(r).as_deref(), Some("5"), "{other}");
+ }
+ // Its own child's spawn channel belongs to the host.
+ let r = app
+ .clone()
+ .oneshot(get("local:a1", "cua.env.v1.TunnelService/StartSpawn"))
+ .await
+ .unwrap();
+ assert_eq!(status(r).as_deref(), Some("7"));
+}
+
+#[tokio::test]
+async fn a_child_past_the_trees_budget_gets_a_plain_refusal() {
+ let w = world();
+ // root's tree holds a, a1 and b.
+ w.shared
+ .children
+ .as_deref()
+ .unwrap()
+ .budget
+ .set_budget(
+ "local:root",
+ super::budget::Budget {
+ max_spaces: Some(3),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let cap = mint(&w.shared, "local:a", "local:root", 1);
+ let mut c = SpaceServiceClient::new(channel(&w.shared, "local:a").await);
+ let e = c
+ .create_space(with(&cap, pb::CreateSpaceRequest::default()))
+ .await
+ .unwrap_err();
+ assert_eq!(e.code(), Code::ResourceExhausted);
+ assert!(e.message().contains("3 child Spaces"), "{}", e.message());
+ // Nothing was created, and nothing stays reserved.
+ assert_eq!(
+ w.shared.runtime.spaces().registry().list().unwrap().len(),
+ 7
+ );
+
+ // The Space reads its own tree's budget and use; it can't change it.
+ let b = c
+ .get_tree_budget(with(&cap, pb::GetTreeBudgetRequest::default()))
+ .await
+ .unwrap()
+ .into_inner()
+ .budget
+ .unwrap();
+ assert_eq!(
+ (b.root.as_str(), b.max_spaces, b.spaces),
+ ("local:root", 3, 3)
+ );
+ assert_eq!(b.max_vcpus, super::budget::DEFAULT_MAX_VCPUS);
+ let e = c
+ .set_tree_budget(with(&cap, pb::SetTreeBudgetRequest::default()))
+ .await
+ .unwrap_err();
+ assert_eq!(e.code(), Code::PermissionDenied);
+ // Another tree's budget is not its to read: it only ever sees its own.
+ let other = mint(&w.shared, "local:o1", "local:other", 1);
+ let mut o = SpaceServiceClient::new(channel(&w.shared, "local:o1").await);
+ let b = o
+ .get_tree_budget(with(&other, pb::GetTreeBudgetRequest::default()))
+ .await
+ .unwrap()
+ .into_inner()
+ .budget
+ .unwrap();
+ assert_eq!(
+ (b.root.as_str(), b.spaces, b.max_spaces),
+ ("local:other", 1, 16)
+ );
+}
+
+#[test]
+fn a_trees_use_counts_its_children_and_their_size() {
+ let w = world();
+ let u = super::tree_usage(&w.shared, "local:root");
+ // a, a1 and b, with no recorded size: the create defaults.
+ assert_eq!((u.spaces, u.vcpus, u.memory_mb), (3, 6, 3 * 4096));
+ assert_eq!(super::tree_usage(&w.shared, "local:a").spaces, 1);
+ assert_eq!(super::tree_usage(&w.shared, "local:owner-dup").spaces, 0);
+}
+
+#[test]
+fn orphans_are_listed_and_only_provable_ones_will_end() {
+ let w = world();
+ let spaces = w.shared.runtime.spaces();
+ for (id, parent) in [
+ ("local:lost", "local:gone"),
+ ("local:far", "relay:abcdefgh"),
+ ] {
+ spaces
+ .registry()
+ .upsert(
+ pb::Space {
+ id: id.into(),
+ name: id.trim_start_matches("local:").into(),
+ ..Default::default()
+ },
+ Credential::default(),
+ )
+ .unwrap();
+ spaces
+ .registry()
+ .update_meta(id, |m| {
+ m.parent = Some(parent.into());
+ })
+ .unwrap();
+ }
+ let mut orphans = super::orphans(&w.shared);
+ orphans.sort_by(|a, b| a.space.cmp(&b.space));
+ let rows: Vec<(&str, &str, &str)> = orphans
+ .iter()
+ .map(|o| (o.space.as_str(), o.parent.as_str(), o.state.as_str()))
+ .collect();
+ assert_eq!(
+ rows,
+ [
+ ("local:far", "relay:abcdefgh", "listed"),
+ ("local:lost", "local:gone", "ending"),
+ ]
+ );
+ assert_eq!(
+ orphans[1].ends_in_secs,
+ super::reaper::GRACE_SECS as i64,
+ "the grace starts now"
+ );
+ // Children whose parents are here are not orphans.
+ assert!(orphans.iter().all(|o| !o.space.starts_with("local:a")));
+}
diff --git a/libs/cua/crates/cua-daemon/src/children/tree.rs b/libs/cua/crates/cua-daemon/src/children/tree.rs
new file mode 100644
index 0000000000..0992a6e48b
--- /dev/null
+++ b/libs/cua/crates/cua-daemon/src/children/tree.rs
@@ -0,0 +1,115 @@
+//! Who is whose child, as the spawn API needs it: every question a Space
+//! asks on its channel is answered inside its own subtree, so a sibling,
+//! an ancestor or another tree reads the same as a Space that does not
+//! exist.
+
+use std::collections::{BTreeMap, BTreeSet};
+
+/// The parent links of the Spaces this host knows.
+pub trait Tree: Send + Sync {
+ /// The parent of `id`, when it is a child.
+ fn parent(&self, id: &str) -> Option<String>;
+ /// Every Space id this host knows.
+ fn ids(&self) -> Vec<String>;
+}
+
+/// A snapshot of parent links (tests, and one listing's worth of records).
+#[derive(Debug, Default, Clone)]
+pub struct Links(pub BTreeMap<String, Option<String>>);
+
+impl Tree for Links {
+ fn parent(&self, id: &str) -> Option<String> {
+ self.0.get(id).cloned().flatten()
+ }
+ fn ids(&self) -> Vec<String> {
+ self.0.keys().cloned().collect()
+ }
+}
+
+/// Steps followed up the parent links before giving up (a cycle, or a
+/// tree deeper than any capability allows).
+const MAX_WALK: usize = 16;
+
+/// True when `id` is below `ancestor` (not `ancestor` itself).
+pub fn is_descendant(tree: &dyn Tree, ancestor: &str, id: &str) -> bool {
+ let mut cur = id.to_owned();
+ for _ in 0..MAX_WALK {
+ match tree.parent(&cur) {
+ Some(p) if p == ancestor => return true,
+ Some(p) => cur = p,
+ None => return false,
+ }
+ }
+ false
+}
+
+/// Every Space below `ancestor`, deepest first (the order to delete in).
+pub fn subtree(tree: &dyn Tree, ancestor: &str) -> Vec<String> {
+ let mut below: Vec<(usize, String)> = tree
+ .ids()
+ .into_iter()
+ .filter_map(|id| depth_below(tree, ancestor, &id).map(|d| (d, id)))
+ .collect();
+ below.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
+ below.into_iter().map(|(_, id)| id).collect()
+}
+
+/// How many steps `id` is below `ancestor`, when it is.
+fn depth_below(tree: &dyn Tree, ancestor: &str, id: &str) -> Option<usize> {
+ let mut cur = id.to_owned();
+ let mut seen = BTreeSet::new();
+ for step in 1..=MAX_WALK {
+ let p = tree.parent(&cur)?;
+ if !seen.insert(p.clone()) {
+ return None;
+ }
+ if p == ancestor {
+ return Some(step);
+ }
+ cur = p;
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn links(pairs: &[(&str, Option<&str>)]) -> Links {
+ Links(
+ pairs
+ .iter()
+ .map(|(c, p)| (c.to_string(), p.map(str::to_string)))
+ .collect(),
+ )
+ }
+
+ #[test]
+ fn only_descendants_are_in_a_subtree() {
+ let t = links(&[
+ ("root", None),
+ ("a", Some("root")),
+ ("a1", Some("a")),
+ ("b", Some("root")),
+ ("other", None),
+ ("o1", Some("other")),
+ ]);
+ assert!(is_descendant(&t, "root", "a1"));
+ assert!(is_descendant(&t, "a", "a1"));
+ // Not itself, not a sibling, not an ancestor, not another tree.
+ assert!(!is_descendant(&t, "a", "a"));
+ assert!(!is_descendant(&t, "a", "b"));
+ assert!(!is_descendant(&t, "a", "root"));
+ assert!(!is_descendant(&t, "a", "o1"));
+ assert_eq!(subtree(&t, "root"), vec!["a1", "a", "b"]);
+ assert_eq!(subtree(&t, "a"), vec!["a1"]);
+ assert!(subtree(&t, "a1").is_empty());
+ }
+
+ #[test]
+ fn a_cycle_is_no_ones_subtree() {
+ let t = links(&[("x", Some("y")), ("y", Some("x"))]);
+ assert!(subtree(&t, "z").is_empty());
+ assert!(!is_descendant(&t, "z", "x"));
+ }
+}
diff --git a/libs/cua/crates/cua-daemon/src/client.rs b/libs/cua/crates/cua-daemon/src/client.rs
index 5997491ff8..2ba9528cbf 100644
--- a/libs/cua/crates/cua-daemon/src/client.rs
+++ b/libs/cua/crates/cua-daemon/src/client.rs
@@ -1190,6 +1190,41 @@ fn refused(e: &tonic::Status) -> bool {
false
}
+/// The spawn channel of the Space this process runs in, when it has one:
+/// `CUA_SPAWN` and `CUA_SPAWN_TOKEN_FILE` (set for processes started after
+/// the channel), else the files cua-spacesd keeps
+/// ([`cua_proto::metadata::spawn_dirs`]). Through it, `cua` and the SDKs
+/// in a Space make and manage the Space's own children; nothing else.
+pub fn spawn_channel() -> Option<DaemonAddress> {
+ use cua_proto::metadata as m;
+ let read = |p: &std::path::Path| {
+ std::fs::read_to_string(p)
+ .ok()
+ .map(|s| s.trim().to_owned())
+ .filter(|s| !s.is_empty())
+ };
+ if let (Some(url), Some(file)) = (
+ std::env::var(m::ENV_SPAWN).ok().filter(|v| !v.is_empty()),
+ std::env::var_os(m::ENV_SPAWN_TOKEN_FILE),
+ ) && let Some(token) = read(std::path::Path::new(&file))
+ {
+ return Some(DaemonAddress::Url { url, token });
+ }
+ #[cfg(unix)]
+ // SAFETY: getuid has no preconditions.
+ let uid = Some(unsafe { libc::getuid() });
+ #[cfg(not(unix))]
+ let uid = None;
+ let xdg = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from);
+ m::spawn_dirs(uid, xdg.as_deref(), &std::env::temp_dir())
+ .into_iter()
+ .find_map(|dir| {
+ let url = read(&dir.join(m::SPAWN_ADDRESS_FILE))?;
+ let token = read(&dir.join(m::SPAWN_TOKEN_FILE))?;
+ Some(DaemonAddress::Url { url, token })
+ })
+}
+
/// The address of the daemon this machine runs when one accepts
/// connections: the discovery file (`~/.cua/daemon.json`), else the
/// default socket. A discovery file left by a daemon that exited is
diff --git a/libs/cua/crates/cua-daemon/src/lib.rs b/libs/cua/crates/cua-daemon/src/lib.rs
index 64e738b6e2..9f90ca4bf3 100644
--- a/libs/cua/crates/cua-daemon/src/lib.rs
+++ b/libs/cua/crates/cua-daemon/src/lib.rs
@@ -24,6 +24,9 @@ use cua_proto::daemon::v1::{DaemonErrorInfo, DaemonErrorReason};
use prost::Message;
use std::path::PathBuf;
+/// Child Spaces: a Space makes and manages Spaces of its own.
+#[cfg(all(feature = "server", feature = "spaces"))]
+pub mod children;
#[cfg(feature = "client")]
pub mod client;
#[cfg(feature = "byoc")]
diff --git a/libs/cua/crates/cua-daemon/src/local.rs b/libs/cua/crates/cua-daemon/src/local.rs
index 3f7b4f8b32..63fb0d45b3 100644
--- a/libs/cua/crates/cua-daemon/src/local.rs
+++ b/libs/cua/crates/cua-daemon/src/local.rs
@@ -1711,6 +1711,8 @@ impl VmmLocal {
s.restrict_network = spec.restrict_network;
s.forkable = spec.forkable;
s.egress = spec.egress.clone();
+ s.network = spec.network.clone();
+ s.tree = spec.tree.clone();
s.disk_size_gb = spec.disk_size_gb;
s.mounts = spec.mounts.clone();
if let Some(m) = self.repo_cache_mount(p.backend, &spec.os).await
@@ -2067,6 +2069,15 @@ impl LocalRuntime for VmmLocal {
rt.egress(name).await.map_err(rt_err)
}
+ async fn set_network(
+ &self,
+ name: &str,
+ settings: &cua_vmm::network::NetworkSettings,
+ ) -> RuntimeResult<cua_vmm::network::Applied> {
+ let (_, rt) = self.owner(name).await?;
+ rt.set_network(name, settings).await.map_err(rt_err)
+ }
+
async fn suspend(&self, name: &str) -> RuntimeResult<()> {
let (_, rt) = self.owner(name).await?;
rt.suspend(name).await.map_err(rt_err)
diff --git a/libs/cua/crates/cua-daemon/src/passthrough.rs b/libs/cua/crates/cua-daemon/src/passthrough.rs
index 67566f40d3..d53b019f5f 100644
--- a/libs/cua/crates/cua-daemon/src/passthrough.rs
+++ b/libs/cua/crates/cua-daemon/src/passthrough.rs
@@ -57,7 +57,7 @@ pub(crate) fn encode_segment(s: &str) -> String {
.replace("%3A", ":")
}
-fn error_response(e: Error, grpc: bool) -> Response {
+pub(crate) fn error_response(e: Error, grpc: bool) -> Response {
if grpc {
let mut r: Response<AxumBody> = e.to_status().into_http();
r.headers_mut().insert(
@@ -83,7 +83,7 @@ pub fn space_key(id: &str) -> String {
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(id.as_bytes())
}
-fn space_from_key(key: &str) -> Result<String, Error> {
+pub(crate) fn space_from_key(key: &str) -> Result<String, Error> {
use base64::Engine;
base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(key.as_bytes())
@@ -100,14 +100,14 @@ const WS_ROUTES: [&str; 4] = [
cua_proto::metadata::VOLUME_WS_PATH,
];
-fn is_grpc(req: &Request<AxumBody>) -> bool {
+pub(crate) fn is_grpc(req: &Request<AxumBody>) -> bool {
req.headers()
.get(http::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|c| c.starts_with("application/grpc"))
}
-async fn split_upgrade(
+pub(crate) async fn split_upgrade(
req: Request<AxumBody>,
) -> Result<(Request<AxumBody>, Option<WebSocketUpgrade>), Box<Response>> {
let is_upgrade = req
@@ -127,7 +127,7 @@ async fn split_upgrade(
}
/// Forwards one request (or WebSocket) to a spacesd connection.
-async fn forward(
+pub(crate) async fn forward(
client: &cua_spacesd_client::SpacesdClient,
ws_headers: Vec<(String, String)>,
rest: &str,
diff --git a/libs/cua/crates/cua-daemon/src/server.rs b/libs/cua/crates/cua-daemon/src/server.rs
index 1250b664e6..1bb6882a34 100644
--- a/libs/cua/crates/cua-daemon/src/server.rs
+++ b/libs/cua/crates/cua-daemon/src/server.rs
@@ -81,6 +81,10 @@ pub(crate) struct Shared {
/// cua-spacesd).
#[cfg(feature = "spaces")]
pub host_spaces: Arc<cua_spaces::host_spaces::HostSpacesServer>,
+ /// Child Spaces (the spawn capabilities this host mints); `None` when
+ /// the home has no room for them.
+ #[cfg(feature = "spaces")]
+ pub children: Option<Arc<crate::children::Children>>,
}
/// Counts a request as in flight until dropped.
@@ -566,9 +570,19 @@ pub async fn start(runtime: Runtime, config: ServerConfig) -> Result<DaemonHandl
let own = std::env::current_exe()
.ok()
.and_then(|e| crate::identity::of(&e));
+ #[cfg(feature = "spaces")]
+ let children = match crate::children::Children::open(runtime.spaces().home_dir()) {
+ Ok(c) => Some(Arc::new(c)),
+ Err(e) => {
+ tracing::warn!(error = %e, "child Spaces are unavailable in this daemon");
+ None
+ }
+ };
let shared = Arc::new(Shared {
#[cfg(feature = "spaces")]
host_spaces,
+ #[cfg(feature = "spaces")]
+ children,
runtime,
token: config.token.clone(),
info: Mutex::new(pb::GetInfoResponse {
@@ -698,6 +712,13 @@ pub async fn start(runtime: Runtime, config: ServerConfig) -> Result<DaemonHandl
)));
tasks.push(tokio::spawn(repo_cache_loop(shared.shutdown.subscribe())));
}
+ // Child Spaces: the spawn channel of each running Space with children
+ // on, and no capability left for a Space that is gone.
+ #[cfg(feature = "spaces")]
+ tasks.push(crate::children::bridge::spawn(
+ shared.clone(),
+ shared.shutdown.subscribe(),
+ ));
// The automatic cloud sweep (`CUA_CLOUD_SWEEP_SECS`, 0: off).
#[cfg(feature = "byoc")]
tasks.extend(crate::cloud_sweep::spawn(
@@ -1038,7 +1059,7 @@ fn unauthorized(req: &Request<AxumBody>) -> Response<AxumBody> {
// ------------------------------------------------------------------ services
#[derive(Clone)]
-pub(crate) struct Svc(pub(crate) Arc<Shared>);
+pub struct Svc(pub(crate) Arc<Shared>);
impl Svc {
pub(crate) fn rt(&self) -> &Runtime {
@@ -1846,3 +1867,28 @@ impl Shared {
.cloned()
}
}
+
+#[cfg(all(test, feature = "spaces"))]
+impl Shared {
+ /// A daemon's shared state without its listeners, for tests of what
+ /// its services answer.
+ pub(crate) fn for_tests(runtime: Runtime) -> Arc<Self> {
+ let host_spaces = cua_spaces::host_spaces::HostSpacesServer::new(runtime.spaces().clone());
+ let children = crate::children::Children::open(runtime.spaces().home_dir())
+ .ok()
+ .map(Arc::new);
+ let (tx, _) = watch::channel(false);
+ Arc::new(Shared {
+ host_spaces,
+ children,
+ runtime,
+ token: "owner-token".into(),
+ info: Mutex::new(pb::GetInfoResponse::default()),
+ bridges: Mutex::new(HashMap::new()),
+ bridge_ttl: Duration::from_secs(60),
+ shutdown: tx,
+ inflight: Default::default(),
+ last_activity: std::sync::atomic::AtomicU64::new(0),
+ })
+ }
+}
diff --git a/libs/cua/crates/cua-daemon/src/spaces_svc.rs b/libs/cua/crates/cua-daemon/src/spaces_svc.rs
index 450c84186f..0e588fa369 100644
--- a/libs/cua/crates/cua-daemon/src/spaces_svc.rs
+++ b/libs/cua/crates/cua-daemon/src/spaces_svc.rs
@@ -43,7 +43,7 @@ pub(crate) fn network_word(n: cua_sandbox_core::NetworkMode) -> &'static str {
}
#[cfg(feature = "spaces")]
-mod imp {
+pub(crate) mod imp {
use super::*;
use crate::convert::from_dur;
use crate::passthrough;
@@ -51,11 +51,63 @@ mod imp {
use cua_sandbox_core::placement::{Kind, On, Runtime};
use prost::Message;
+ /// The top-level Space of `space`'s tree.
+ fn tree_root(spaces: &cua_spaces::Spaces, space: &str) -> Result<String, tonic::Status> {
+ let id = spaces.resolve(space).map_err(|e| st(e.into()))?.to_string();
+ Ok(crate::children::api::position(spaces, &id).0)
+ }
+
+ /// Sets `Space.children` from the setting.
+ pub(crate) fn mark_children(spaces: &cua_spaces::Spaces, records: &mut [pb::Space]) {
+ let on: std::collections::BTreeSet<String> =
+ spaces.children_enabled().into_iter().collect();
+ for r in records {
+ r.children = on.contains(&r.id);
+ }
+ }
+
+ /// Refuses a create that asks for children while the experiment is off,
+ /// before anything is made.
+ fn children_allowed(children: bool) -> Result<(), tonic::Status> {
+ if children && !cua_vmm::experiments::enabled(cua_vmm::experiments::Gate::ChildSpaces) {
+ return Err(tonic::Status::failed_precondition(
+ cua_vmm::experiments::Gate::ChildSpaces.off_message(),
+ ));
+ }
+ Ok(())
+ }
+
+ /// Turns children on for `space`: only a Space this computer runs can
+ /// hold a channel to it.
+ fn turn_on_children(
+ spaces: &cua_spaces::Spaces,
+ space: &mut pb::Space,
+ ) -> Result<(), tonic::Status> {
+ // An experiment, off unless the owner turned it on.
+ if !cua_vmm::experiments::enabled(cua_vmm::experiments::Gate::ChildSpaces) {
+ return Err(tonic::Status::failed_precondition(
+ cua_vmm::experiments::Gate::ChildSpaces.off_message(),
+ ));
+ }
+ if !space.id.starts_with("local:") {
+ return Err(tonic::Status::failed_precondition(
+ "child Spaces are available for Spaces this computer runs; turn them on \
+ on the machine that runs this Space",
+ ));
+ }
+ spaces
+ .set_children(&space.id, true)
+ .map_err(|e| st(e.into()))?;
+ space.children = true;
+ Ok(())
+ }
+
async fn record(spaces: &cua_spaces::Spaces, id: &str) -> Result<pb::Space, Error> {
if let Some(r) = spaces.registry().get(id).map_err(Error::from)? {
let mut r = [r];
spaces.fill_records(&mut r);
- let [r] = r;
+ let [mut r] = r;
+ r.children = spaces.children_on(&r.id);
return Ok(r);
}
Ok(info_record(&spaces.find(id).await.map_err(Error::from)?))
@@ -102,6 +154,33 @@ mod imp {
.unwrap_or_default(),
volumes: info.volumes.iter().map(Into::into).collect(),
sharing: info.sharing.as_ref().map(Into::into),
+ network_settings: info
+ .network
+ .as_ref()
+ .map(|n| cua_spaces::network::to_pb(&n.settings)),
+ network_note: info
+ .network
+ .as_ref()
+ .and_then(|n| n.note.clone())
+ .unwrap_or_default(),
+ network_notice_pending: info.network.as_ref().is_some_and(|n| n.notice_pending),
+ parent: info
+ .tree
+ .as_ref()
+ .and_then(|t| t.parent.clone())
+ .unwrap_or_default(),
+ root: info
+ .tree
+ .as_ref()
+ .and_then(|t| t.root.clone())
+ .unwrap_or_default(),
+ depth: info.tree.as_ref().map_or(0, |t| t.depth),
+ origin: info
+ .tree
+ .as_ref()
+ .map(|t| t.origin.clone())
+ .unwrap_or_default(),
+ children: false,
}
}
@@ -170,6 +249,14 @@ mod imp {
deny: e.deny,
})
.unwrap_or_default(),
+ network_settings: r
+ .network_settings
+ .as_ref()
+ .map(cua_spaces::network::from_pb)
+ .transpose()
+ .map_err(|e| st(e.into()))?,
+ parent: opt(r.parent),
+ widen: r.widen,
})
}
@@ -349,6 +436,7 @@ mod imp {
s.stop_reason = self.spaces().stop_reason_of(&s.id);
}
self.spaces().fill_records(&mut spaces);
+ mark_children(self.spaces(), &mut spaces);
// Plus the signed-in account's relay machines: refreshed, or
// (`known_now`) as far as they answered, never holding up this
// machine's own Spaces.
@@ -631,14 +719,21 @@ mod imp {
&self,
req: tonic::Request<pb::CreateSpaceRequest>,
) -> R<pb::CreateSpaceResponse> {
- let create = create_args(req.into_inner())?;
+ let r = req.into_inner();
+ let children = r.children.unwrap_or(false);
+ children_allowed(children)?;
+ let create = create_args(r)?;
let network = create.network;
let created = self
.spaces()
.create(create)
.await
.map_err(|e| st(e.into()))?;
- ok(create_response(self.spaces(), created, network).await?)
+ let mut resp = create_response(self.spaces(), created, network).await?;
+ if children && let Some(s) = resp.space.as_mut() {
+ turn_on_children(self.spaces(), s)?;
+ }
+ ok(resp)
}
type CreateSpaceStreamStream = std::pin::Pin<
@@ -657,6 +752,8 @@ mod imp {
let mut r = req.into_inner().create.unwrap_or_default();
// The stream runs until the Space is ready.
r.wait = Some(true);
+ let children = r.children.unwrap_or(false);
+ children_allowed(children)?;
let mut create = create_args(r)?;
// Bounded: a slow reader drops progress, never the result (which
// goes out on the same channel after every report).
@@ -671,11 +768,18 @@ mod imp {
let network = create.network;
tokio::spawn(async move {
let result = match spaces.create(create).await {
- Ok(created) => create_response(&spaces, created, network).await.map(|r| {
- pb::CreateSpaceStreamResponse {
- event: Some(Event::Result(r)),
+ Ok(created) => match create_response(&spaces, created, network).await {
+ Ok(mut r) => {
+ let on = match r.space.as_mut() {
+ Some(s) if children => turn_on_children(&spaces, s),
+ _ => Ok(()),
+ };
+ on.map(|()| pb::CreateSpaceStreamResponse {
+ event: Some(Event::Result(r)),
+ })
}
- }),
+ Err(e) => Err(e),
+ },
Err(e) => Err(st(e.into())),
};
let _ = tx.send(result).await;
@@ -769,6 +873,131 @@ mod imp {
ok(pb::SetSpaceEgressResponse {})
}
+ async fn get_space_network(
+ &self,
+ req: tonic::Request<pb::GetSpaceNetworkRequest>,
+ ) -> R<pb::GetSpaceNetworkResponse> {
+ let r = req.into_inner();
+ let info = self
+ .spaces()
+ .network_info(&r.space)
+ .await
+ .map_err(|e| st(e.into()))?;
+ if r.ack_notice {
+ self.spaces()
+ .ack_network_notice(&r.space)
+ .map_err(|e| st(e.into()))?;
+ }
+ ok(pb::GetSpaceNetworkResponse {
+ network: Some(cua_spaces::network::info_to_pb(&info)),
+ })
+ }
+
+ async fn set_space_network(
+ &self,
+ req: tonic::Request<pb::SetSpaceNetworkRequest>,
+ ) -> R<pb::SetSpaceNetworkResponse> {
+ let r = req.into_inner();
+ let settings = cua_spaces::network::from_pb(&r.settings.unwrap_or_default())
+ .map_err(|e| st(e.into()))?;
+ let applied = self
+ .spaces()
+ .set_network(&r.space, &settings, r.widen, r.tree)
+ .await
+ .map_err(|e| st(e.into()))?;
+ let info = self
+ .spaces()
+ .network_info(&r.space)
+ .await
+ .map_err(|e| st(e.into()))?;
+ ok(pb::SetSpaceNetworkResponse {
+ applied: match applied {
+ cua_vmm::network::Applied::Now => "now",
+ cua_vmm::network::Applied::NextStart => "next_start",
+ }
+ .into(),
+ network: Some(cua_spaces::network::info_to_pb(&info)),
+ })
+ }
+
+ async fn get_tree_budget(
+ &self,
+ req: tonic::Request<pb::GetTreeBudgetRequest>,
+ ) -> R<pb::GetTreeBudgetResponse> {
+ let root = tree_root(self.spaces(), &req.into_inner().space)?;
+ ok(pb::GetTreeBudgetResponse {
+ budget: Some(crate::children::api::tree_budget(&self.0, &root)),
+ })
+ }
+
+ async fn set_tree_budget(
+ &self,
+ req: tonic::Request<pb::SetTreeBudgetRequest>,
+ ) -> R<pb::SetTreeBudgetResponse> {
+ let r = req.into_inner();
+ let root = tree_root(self.spaces(), &r.space)?;
+ let l = r.limits.unwrap_or_default();
+ for (what, v) in [("usd_per_hour", l.usd_per_hour), ("usd_total", l.usd_total)] {
+ if v.is_some_and(|v| !v.is_finite() || v < 0.0) {
+ return Err(tonic::Status::invalid_argument(format!(
+ "{what} must be a number of dollars, 0 or more"
+ )));
+ }
+ }
+ let budget = crate::children::budget::Budget {
+ max_spaces: l.max_spaces,
+ max_vcpus: l.max_vcpus,
+ max_memory_mb: l.max_memory_mb,
+ usd_per_hour: l.usd_per_hour,
+ usd_total: l.usd_total,
+ };
+ let Some(c) = self.0.children.as_deref() else {
+ return Err(tonic::Status::failed_precondition(
+ "child Spaces are unavailable in this daemon",
+ ));
+ };
+ c.budget
+ .set_budget(&root, budget)
+ .map_err(|e| tonic::Status::internal(format!("save the budget: {e}")))?;
+ ok(pb::SetTreeBudgetResponse {
+ budget: Some(crate::children::api::tree_budget(&self.0, &root)),
+ })
+ }
+
+ async fn list_orphans(
+ &self,
+ _: tonic::Request<pb::ListOrphansRequest>,
+ ) -> R<pb::ListOrphansResponse> {
+ ok(pb::ListOrphansResponse {
+ orphans: crate::children::orphans(&self.0),
+ })
+ }
+
+ async fn set_space_children(
+ &self,
+ req: tonic::Request<pb::SetSpaceChildrenRequest>,
+ ) -> R<pb::SetSpaceChildrenResponse> {
+ let r = req.into_inner();
+ let id = self
+ .spaces()
+ .resolve(&r.space)
+ .map_err(|e| st(e.into()))?
+ .to_string();
+ let mut space = record(self.spaces(), &id).await.map_err(st)?;
+ if r.enabled {
+ turn_on_children(self.spaces(), &mut space)?;
+ } else {
+ self.spaces()
+ .set_children(&id, false)
+ .map_err(|e| st(e.into()))?;
+ if let Some(a) = self.0.spawn_authority() {
+ a.revoke(&id);
+ }
+ space.children = false;
+ }
+ ok(pb::SetSpaceChildrenResponse { space: Some(space) })
+ }
+
async fn rename_space(
&self,
req: tonic::Request<pb::RenameSpaceRequest>,
@@ -787,15 +1016,31 @@ mod imp {
&self,
req: tonic::Request<pb::DeleteSpaceRequest>,
) -> R<pb::DeleteSpaceResponse> {
- let space = req.into_inner().space;
+ let req = req.into_inner();
+ let space = req.space;
+ // Its child Spaces go first, unless it keeps them.
+ let gone = if req.keep_children {
+ vec![]
+ } else {
+ self.spaces().descendants(&space).unwrap_or_default()
+ };
let message = self
.spaces()
- .delete(&space)
+ .delete_tree(&space, req.keep_children)
.await
.map_err(|e| st(e.into()))?;
+ for child in &gone {
+ self.rt().detach(child).await;
+ }
// Drop the connection an exec or a call cached for it: a new
// Space of the same name must not reach the deleted one.
self.rt().detach(&space).await;
+ // Its capability ends with it (the channel loop also notices).
+ if let Ok(id) = self.spaces().resolve(&space)
+ && let Some(a) = self.0.spawn_authority()
+ {
+ a.revoke(&id.to_string());
+ }
ok(pb::DeleteSpaceResponse { message })
}
@@ -1266,6 +1511,45 @@ mod imp {
) -> R<pb::SetSpaceEgressResponse> {
off()
}
+ async fn set_space_children(
+ &self,
+ _: tonic::Request<pb::SetSpaceChildrenRequest>,
+ ) -> R<pb::SetSpaceChildrenResponse> {
+ off()
+ }
+ async fn get_tree_budget(
+ &self,
+ _: tonic::Request<pb::GetTreeBudgetRequest>,
+ ) -> R<pb::GetTreeBudgetResponse> {
+ off()
+ }
+ async fn set_tree_budget(
+ &self,
+ _: tonic::Request<pb::SetTreeBudgetRequest>,
+ ) -> R<pb::SetTreeBudgetResponse> {
+ off()
+ }
+
+ async fn get_space_network(
+ &self,
+ _: tonic::Request<pb::GetSpaceNetworkRequest>,
+ ) -> R<pb::GetSpaceNetworkResponse> {
+ off()
+ }
+
+ async fn set_space_network(
+ &self,
+ _: tonic::Request<pb::SetSpaceNetworkRequest>,
+ ) -> R<pb::SetSpaceNetworkResponse> {
+ off()
+ }
+
+ async fn list_orphans(
+ &self,
+ _: tonic::Request<pb::ListOrphansRequest>,
+ ) -> R<pb::ListOrphansResponse> {
+ off()
+ }
async fn delete_space(
&self,
diff --git a/libs/cua/crates/cua-daemon/tests/linux_runtime_idle.rs b/libs/cua/crates/cua-daemon/tests/linux_runtime_idle.rs
index 3429512e87..8cf8ffda6e 100644
--- a/libs/cua/crates/cua-daemon/tests/linux_runtime_idle.rs
+++ b/libs/cua/crates/cua-daemon/tests/linux_runtime_idle.rs
@@ -49,6 +49,8 @@ fn spec(name: &str) -> LocalStartSpec {
forkable: false,
headless: false,
egress: Default::default(),
+ network: None,
+ tree: None,
// A bare alpine, as it is.
spacesd: Some(false),
}
diff --git a/libs/cua/crates/cua-daemon/tests/space_children_live.rs b/libs/cua/crates/cua-daemon/tests/space_children_live.rs
new file mode 100644
index 0000000000..7f2a2279b7
--- /dev/null
+++ b/libs/cua/crates/cua-daemon/tests/space_children_live.rs
@@ -0,0 +1,227 @@
+//! Opt-in: a Space makes, uses and deletes child Spaces through its own
+//! spawn channel, on a real runtime, and cannot reach past its subtree.
+//!
+//! The parent runs with children on. From inside it, the way an agent does
+//! (its own MCP server, `tools/call`), it creates a child, runs a command in
+//! it and lists it; it is refused another top-level Space, by id and by
+//! name, and the capability it holds does not open its child's channel.
+//! Deleting the parent through the owner ends its capability.
+//!
+//! ```text
+//! CUA_SPACESD_STATIC=/path/to/linux/cua-spacesd \
+//! cargo test -p cua-daemon --test space_children_live -- --ignored --nocapture
+//! ```
+//!
+//! Needs a local container runtime (Docker on Linux, or the built-in Linux
+//! runtime) and image `CUA_CHILDREN_TEST_IMAGE` (default
+//! `ghcr.io/trycua/linux:24.04-slim`; it needs curl). `CUA_SPACESD_STATIC`
+//! must be a cua-spacesd with the spawn channel (it is injected into the
+//! container). Everything lives under a temp home and is deleted on every
+//! path.
+
+use std::time::{Duration, Instant};
+
+use cua_daemon::server::{ServerConfig, start};
+use cua_daemon::{Runtime as DaemonRuntime, RuntimeConfig};
+use cua_proto::daemon::v1 as pb;
+use cua_proto::daemon::v1::space_service_client::SpaceServiceClient;
+use futures_util::FutureExt as _;
+use serde_json::{Value, json};
+
+type Client = SpaceServiceClient<
+ tonic::service::interceptor::InterceptedService<
+ tonic::transport::Channel,
+ Box<dyn FnMut(tonic::Request<()>) -> Result<tonic::Request<()>, tonic::Status> + Send>,
+ >,
+>;
+
+fn image() -> String {
+ std::env::var("CUA_CHILDREN_TEST_IMAGE")
+ .unwrap_or_else(|_| "ghcr.io/trycua/linux:24.04-slim".into())
+}
+
+async fn bash(c: &mut Client, space: &str, command: &str) -> String {
+ let r = c
+ .call_space_tool(pb::CallSpaceToolRequest {
+ name: "space_bash".into(),
+ arguments_json: json!({"space": space, "command": command, "timeout": 120}).to_string(),
+ })
+ .await
+ .expect("space_bash")
+ .into_inner();
+ let content: Value = serde_json::from_str(&r.content_json).unwrap();
+ content[0]["text"].as_str().unwrap_or_default().to_owned()
+}
+
+/// A `tools/call` on the Space's own MCP server, from inside it.
+fn mcp_call(tool: &str, args: Value) -> String {
+ let body = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": {"name": tool, "arguments": args}})
+ .to_string();
+ format!(
+ "T=$(cat /run/cua-env/env-token 2>/dev/null || cat /run/cua/env-token 2>/dev/null || \
+ printf %s \"$CUA_ENV_TOKEN\"); curl -s -m 600 -H \"authorization: Bearer $T\" \
+ -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' \
+ http://127.0.0.1:${{CUA_ENV_PORT:-3211}}/mcp -d '{body}'"
+ )
+}
+
+async fn create(c: &mut Client, name: &str, children: bool) -> String {
+ c.create_space(pb::CreateSpaceRequest {
+ image: image(),
+ location: "local".into(),
+ kind: "container".into(),
+ name: name.into(),
+ headless: true,
+ spacesd: Some(true),
+ children: Some(children),
+ ..Default::default()
+ })
+ .await
+ .expect("create")
+ .into_inner()
+ .space
+ .expect("space")
+ .id
+}
+
+#[tokio::test]
+#[ignore = "needs a local container runtime and a cua-spacesd with the spawn channel"]
+async fn a_space_makes_uses_and_cannot_escape_its_children() {
+ let home = tempfile::tempdir().unwrap();
+ // SAFETY: set before the runtime or any thread reads it.
+ unsafe { std::env::set_var("CUA_HOME", home.path()) };
+ // Child Spaces are an experiment, off unless turned on.
+ cua_vmm::experiments::set_enabled(cua_vmm::experiments::Gate::ChildSpaces, Some(true));
+ let runtime = DaemonRuntime::new(RuntimeConfig {
+ state_dir: Some(home.path().join("sandboxes")),
+ spaces_home: Some(home.path().to_path_buf()),
+ ..Default::default()
+ })
+ .unwrap();
+ let handle = start(
+ runtime,
+ ServerConfig {
+ socket_path: None,
+ loopback: Some(([127, 0, 0, 1], 0).into()),
+ token: "owner".into(),
+ discovery_path: None,
+ bridge_ticket_ttl: Duration::from_secs(60),
+ },
+ )
+ .await
+ .unwrap();
+ let channel = tonic::transport::Endpoint::from_shared(handle.loopback_url.clone().unwrap())
+ .unwrap()
+ .connect()
+ .await
+ .unwrap();
+ #[allow(clippy::type_complexity)]
+ let auth: Box<
+ dyn FnMut(tonic::Request<()>) -> Result<tonic::Request<()>, tonic::Status> + Send,
+ > = Box::new(|mut r: tonic::Request<()>| {
+ r.metadata_mut()
+ .insert("authorization", "Bearer owner".parse().unwrap());
+ Ok(r)
+ });
+ let mut c: Client = SpaceServiceClient::with_interceptor(channel, auth);
+
+ let mut made = Vec::new();
+ let result = std::panic::AssertUnwindSafe(async {
+ let parent = create(&mut c, "kid-parent", true).await;
+ made.push(parent.clone());
+ let outsider = create(&mut c, "kid-outsider", false).await;
+ made.push(outsider.clone());
+
+ // The host starts the parent's channel.
+ let deadline = Instant::now() + Duration::from_secs(90);
+ let address = loop {
+ let a = bash(&mut c, &parent, "printenv CUA_SPAWN || true").await;
+ if a.trim().starts_with("http://127.0.0.1:") {
+ break a.trim().to_owned();
+ }
+ assert!(Instant::now() < deadline, "no spawn channel: {a}");
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ };
+ eprintln!("parent channel at {address}");
+
+ // Create a child from inside, as an agent does.
+ let out = bash(&mut c, &parent, &mcp_call("create_space", json!({"headless": true, "kind": "container", "image": image()}))).await;
+ eprintln!("create_space: {out}");
+ let list = c
+ .list_spaces(pb::ListSpacesRequest::default())
+ .await
+ .unwrap()
+ .into_inner();
+ let child = list
+ .spaces
+ .iter()
+ .find(|s| s.parent == parent)
+ .expect("the child is registered under its parent")
+ .id
+ .clone();
+ made.push(child.clone());
+
+ // Use it, and see only it.
+ let out = bash(&mut c, &parent, &mcp_call("space_bash", json!({"space": child, "command": "echo hello-from-child"}))).await;
+ assert!(out.contains("hello-from-child"), "{out}");
+ let out = bash(&mut c, &parent, &mcp_call("list_spaces", json!({}))).await;
+ assert!(out.contains(&child) && !out.contains(&outsider), "{out}");
+
+ // Another top-level Space is not there, by id or by name.
+ for target in [outsider.as_str(), "kid-outsider", parent.as_str()] {
+ let out = bash(&mut c, &parent, &mcp_call("delete_space", json!({"space": target}))).await;
+ assert!(out.contains("isError\":true") && out.contains("no Space"), "{target}: {out}");
+ }
+ assert!(c
+ .resolve_space(pb::ResolveSpaceRequest { space: outsider.clone() })
+ .await
+ .is_ok());
+
+ // The parent's capability does not open the child's channel.
+ let deadline = Instant::now() + Duration::from_secs(90);
+ let child_address = loop {
+ let a = bash(&mut c, &child, "printenv CUA_SPAWN || true").await;
+ if a.trim().starts_with("http://127.0.0.1:") {
+ break a.trim().to_owned();
+ }
+ assert!(Instant::now() < deadline, "no channel in the child: {a}");
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ };
+ let parent_cap = bash(&mut c, &parent, "cat \"$CUA_SPAWN_TOKEN_FILE\"").await;
+ let probe = |cap: &str| {
+ format!(
+ "curl -s -o /dev/null -w '%{{http_code}}' -H 'authorization: Bearer {}' {child_address}/v1/spaces/x/env/y",
+ cap.trim()
+ )
+ };
+ let code = bash(&mut c, &child, &probe(&parent_cap)).await;
+ assert_eq!(code.trim(), "401", "the parent's capability on the child's channel");
+ let own = bash(&mut c, &child, "cat \"$CUA_SPAWN_TOKEN_FILE\"").await;
+ let code = bash(&mut c, &child, &probe(&own)).await;
+ assert_ne!(code.trim(), "401", "the child's own capability");
+
+ // Deleted from inside: gone.
+ let out = bash(&mut c, &parent, &mcp_call("delete_space", json!({"space": child}))).await;
+ assert!(!out.contains("isError\":true"), "{out}");
+ assert!(c
+ .resolve_space(pb::ResolveSpaceRequest { space: child.clone() })
+ .await
+ .is_err());
+ })
+ .catch_unwind()
+ .await;
+ for id in made.iter().rev() {
+ let _ = c
+ .delete_space(pb::DeleteSpaceRequest {
+ space: id.clone(),
+ keep_children: false,
+ })
+ .await;
+ }
+ handle.shutdown();
+ handle.wait().await;
+ if let Err(panic) = result {
+ std::panic::resume_unwind(panic);
+ }
+}
diff --git a/libs/cua/crates/cua-daemon/tests/space_egress.rs b/libs/cua/crates/cua-daemon/tests/space_egress.rs
index 42f6c9c06e..ee50bad691 100644
--- a/libs/cua/crates/cua-daemon/tests/space_egress.rs
+++ b/libs/cua/crates/cua-daemon/tests/space_egress.rs
@@ -451,8 +451,12 @@ mod qemu {
let dns = g
.sh("getent hosts one.one.one.one >/dev/null && echo resolved || echo no-dns")
.await;
- eprintln!(" DNS through the VM's resolver (10.0.2.3, not allowed): {dns}");
- assert_eq!(dns, "no-dns");
+ // Under the secure default the runtime's resolver stays open on
+ // 53 whatever the lists say; under the old default it follows
+ // them (10.0.2.3 is not allowed here).
+ let secure = cua_vmm::network::Mode::from_env() == cua_vmm::network::Mode::Secure;
+ eprintln!(" DNS through the VM's resolver (10.0.2.3): {dns}");
+ assert_eq!(dns, if secure { "resolved" } else { "no-dns" });
eprintln!("qemu: set_egress in the namespace (allow 10.0.2.3 and {DENIED})");
rt.set_egress(&name, &policy(&[ALLOWED, DENIED, "10.0.2.3"], &["all"]))
diff --git a/libs/cua/crates/cua-daemon/tests/space_secure_default.rs b/libs/cua/crates/cua-daemon/tests/space_secure_default.rs
new file mode 100644
index 0000000000..36f0b80688
--- /dev/null
+++ b/libs/cua/crates/cua-daemon/tests/space_secure_default.rs
@@ -0,0 +1,562 @@
+//! Opt-in: the secure default (`cua_vmm::network`) holds from inside the
+//! guest, on real runtimes. With no policy at all, a process that is root
+//! in the guest
+//!
+//! - reaches the internet (1.1.1.1:443) and resolves names;
+//! - reaches a Space of its own tree;
+//! - can't reach: the host's loopback through any alias (the bridge
+//! gateway, `host.docker.internal`, `10.0.2.2`, ...), the host's own
+//! addresses, the host's LAN gateway, the cloud metadata endpoint
+//! (`169.254.169.254`, the real one on an AWS host), a Space of another
+//! tree, the daemon's port (also under `localhost` with every port), or a
+//! name that resolves to any of those (DNS rebinding).
+//!
+//! "Can't reach" means the connection times out or is unreachable: a
+//! refused connection (RST) got through and fails the test.
+//!
+//! ```text
+//! CUA_HOME=$(mktemp -d) cargo test -p cua-daemon --test space_secure_default -- \
+//! --ignored --nocapture --test-threads=1
+//! ```
+//!
+//! Needs internet and, per test, what `space_egress.rs` says (a Docker
+//! engine on Linux with nftables; gVisor: `runsc`; QEMU: KVM, pasta and
+//! `CUA_EGRESS_TEST_DISK`; Firecracker: KVM, pasta and the microVM assets).
+//! VMs reach the members of their tree through cua-mesh, not yet through
+//! these tests' address probes. Image
+//! `CUA_EGRESS_TEST_IMAGE` (default `ghcr.io/trycua/linux:24.04-slim`; it
+//! needs python3). Everything is created under the test's `CUA_HOME` and
+//! deleted on every path, and the host listeners close with the test.
+
+use std::net::{IpAddr, Ipv4Addr};
+use std::time::Duration;
+
+use cua_vmm::exec::{ExecRequest, GuestExec};
+use cua_vmm::network::{NetworkPreset, NetworkSettings};
+use cua_vmm::{ImageSource, Runtime, StartSpec};
+
+/// `python3 probe.py <host:port>...` prints `<host:port>=open|refused|blocked`
+/// for a TCP connect to each (`blocked`: timed out or unreachable). A host
+/// name is resolved in the guest first (`name` stays in the output).
+const PROBE_PY: &str = r#"import socket, sys
+def tcp(target):
+ host, port = target.rsplit(":", 1)
+ try:
+ ip = socket.getaddrinfo(host, int(port), socket.AF_INET, socket.SOCK_STREAM)[0][4][0]
+ except Exception:
+ return "noname"
+ s = socket.socket(); s.settimeout(5)
+ try:
+ s.connect((ip, int(port))); return "open"
+ except ConnectionRefusedError:
+ return "refused"
+ except Exception:
+ return "blocked"
+print(" ".join(t + "=" + tcp(t) for t in sys.argv[1:]))
+"#;
+
+/// A guest to run shell commands in, as root.
+struct Guest {
+ exec: std::sync::Arc<dyn GuestExec>,
+ root: &'static str,
+}
+
+impl Guest {
+ async fn sh(&self, script: &str) -> String {
+ let req = ExecRequest::sh(format!("{} sh -c {}", self.root, quote(script)))
+ .timeout(Duration::from_secs(120));
+ match self.exec.exec(req).await {
+ Ok(o) => format!(
+ "{}{}",
+ String::from_utf8_lossy(&o.stdout),
+ String::from_utf8_lossy(&o.stderr)
+ )
+ .trim()
+ .to_string(),
+ Err(e) => format!("exec failed: {e}"),
+ }
+ }
+
+ async fn upload(&self) {
+ use base64::Engine as _;
+ let b64 = base64::engine::general_purpose::STANDARD.encode(PROBE_PY);
+ let out = self
+ .sh(&format!(
+ "echo {b64} | base64 -d > /tmp/sd-probe.py && echo ok"
+ ))
+ .await;
+ assert!(out.ends_with("ok"), "upload: {out}");
+ }
+
+ /// The probe's verdict per target (retried while the guest's network
+ /// comes up: the internet must answer first).
+ async fn probe(&self, targets: &[String]) -> Vec<(String, String)> {
+ let out = self
+ .sh(&format!("python3 /tmp/sd-probe.py {}", targets.join(" ")))
+ .await;
+ out.split_whitespace()
+ .filter_map(|kv| kv.rsplit_once('='))
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect()
+ }
+
+ async fn wait_internet(&self) {
+ for _ in 0..30 {
+ if self.probe(&["1.1.1.1:443".into()]).await == [("1.1.1.1:443".into(), "open".into())]
+ {
+ return;
+ }
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ }
+ panic!("the guest never reached the internet (1.1.1.1:443)");
+ }
+
+ /// Every target must be `want` (`blocked` for the negatives).
+ async fn expect_all(&self, what: &str, targets: &[String], want: &str) {
+ let got = self.probe(targets).await;
+ eprintln!(" {what}: {got:?}");
+ assert_eq!(got.len(), targets.len(), "{what}: {got:?}");
+ for (t, v) in &got {
+ assert_eq!(v, want, "{what}: {t} is {v}, wanted {want}");
+ }
+ }
+}
+
+fn quote(s: &str) -> String {
+ format!("'{}'", s.replace('\'', "'\\''"))
+}
+
+fn suffix() -> String {
+ format!(
+ "{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .subsec_nanos()
+ % 100000
+ )
+}
+
+/// Listeners on the host for the guest to (fail to) reach: one on every
+/// address, one on loopback only. Accept and hold, so `open` is real.
+struct HostListeners {
+ any: u16,
+ loopback: u16,
+ _tasks: Vec<tokio::task::JoinHandle<()>>,
+}
+
+async fn listen(addr: &str) -> (u16, tokio::task::JoinHandle<()>) {
+ let l = tokio::net::TcpListener::bind(addr).await.expect("bind");
+ let port = l.local_addr().unwrap().port();
+ let task = tokio::spawn(async move {
+ let mut held = Vec::new();
+ while let Ok((s, _)) = l.accept().await {
+ held.push(s);
+ }
+ });
+ (port, task)
+}
+
+impl HostListeners {
+ async fn start() -> HostListeners {
+ let (any, a) = listen("0.0.0.0:0").await;
+ let (loopback, b) = listen("127.0.0.1:0").await;
+ HostListeners {
+ any,
+ loopback,
+ _tasks: vec![a, b],
+ }
+ }
+}
+
+/// This host's own non-loopback IPv4 addresses and its default gateway.
+fn host_facts() -> (Vec<Ipv4Addr>, Option<Ipv4Addr>) {
+ let out = std::process::Command::new("ip")
+ .args(["-o", "-4", "addr", "show"])
+ .output()
+ .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
+ .unwrap_or_default();
+ let addrs = out
+ .lines()
+ .filter_map(|l| l.split_whitespace().nth(3))
+ .filter_map(|a| a.split('/').next()?.parse::<Ipv4Addr>().ok())
+ .filter(|a| !a.is_loopback())
+ .collect();
+ let route = std::process::Command::new("ip")
+ .args(["-4", "route", "show", "default"])
+ .output()
+ .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
+ .unwrap_or_default();
+ let gw = route
+ .split_whitespace()
+ .skip_while(|w| *w != "via")
+ .nth(1)
+ .and_then(|g| g.parse().ok());
+ (addrs, gw)
+}
+
+/// The names that resolve to `ip` (a public wildcard DNS service): DNS
+/// rebinding must not get the guest past the rules.
+fn rebinding(ip: IpAddr, port: u16) -> String {
+ format!("{ip}.nip.io:{port}")
+}
+
+// ---------------------------------------------------------------- container
+
+mod container {
+ use super::*;
+ use cua_vmm::container::{ContainerConfig, ContainerRuntime};
+
+ fn image() -> String {
+ std::env::var("CUA_EGRESS_TEST_IMAGE")
+ .unwrap_or_else(|_| "ghcr.io/trycua/linux:24.04-slim".into())
+ }
+
+ fn spec(name: &str, runtime: &str, tree: &str, network: NetworkSettings) -> StartSpec {
+ let mut s = StartSpec::new(name, ImageSource::oci(image()))
+ .cpus(1)
+ .memory_mb(512)
+ .command([
+ "python3",
+ "-c",
+ "import socket,time\ns=socket.socket();s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1);s.bind(('0.0.0.0',7777));s.listen(16)\nh=[]\nwhile True:\n c,_=s.accept();h.append(c)",
+ ])
+ .ready_timeout(Duration::from_secs(300));
+ s.container_runtime = Some(runtime.into());
+ s.network = Some(network);
+ s.tree = Some(tree.into());
+ s
+ }
+
+ async fn guest(rt: &ContainerRuntime, name: &str) -> Guest {
+ let g = Guest {
+ exec: rt.guest_exec(name).await.unwrap().unwrap(),
+ root: "",
+ };
+ g.upload().await;
+ g
+ }
+
+ async fn ip_of(name: &str) -> String {
+ let out = tokio::process::Command::new("docker")
+ .args([
+ "inspect",
+ "-f",
+ "{{range .NetworkSettings.Networks}}{{.IPAddress}} {{.Gateway}}{{end}}",
+ name,
+ ])
+ .output()
+ .await
+ .unwrap();
+ String::from_utf8_lossy(&out.stdout).trim().to_string()
+ }
+
+ async fn run(runtime: &str) {
+ let rt = ContainerRuntime::connect(ContainerConfig {
+ warm: false,
+ ..ContainerConfig::default()
+ })
+ .await
+ .expect("a Docker engine");
+ let host = HostListeners::start().await;
+ let (addrs, lan_gw) = host_facts();
+ let tag = suffix();
+ let a = format!("cua-sd-a-{runtime}-{tag}");
+ let child = format!("cua-sd-c-{runtime}-{tag}");
+ let other = format!("cua-sd-o-{runtime}-{tag}");
+ let open_host = format!("cua-sd-l-{runtime}-{tag}");
+ let names = [a.clone(), child.clone(), other.clone(), open_host.clone()];
+ let result = futures_util::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
+ let tree_a = format!("local:{a}");
+ rt.start(&spec(&a, runtime, &tree_a, NetworkSettings::internet()))
+ .await
+ .expect("start a");
+ rt.start(&spec(&child, runtime, &tree_a, NetworkSettings::internet()))
+ .await
+ .expect("start its child");
+ rt.start(&spec(
+ &other,
+ runtime,
+ &format!("local:{other}"),
+ NetworkSettings::internet(),
+ ))
+ .await
+ .expect("start another tree");
+ let g = guest(&rt, &a).await;
+ g.wait_internet().await;
+
+ let a_net = ip_of(&a).await;
+ let gateway = a_net.split_whitespace().nth(1).unwrap_or_default().to_string();
+ let child_ip = ip_of(&child).await.split_whitespace().next().unwrap_or_default().to_string();
+ let other_ip = ip_of(&other).await.split_whitespace().next().unwrap_or_default().to_string();
+ eprintln!("{runtime}: a {a_net}, child {child_ip}, other tree {other_ip}");
+
+ // Positives: the internet, names, its own child.
+ let dns = g.sh("getent hosts example.com >/dev/null && echo resolved").await;
+ assert_eq!(dns, "resolved", "DNS: {dns}");
+ g.expect_all(
+ "the internet and its own child",
+ &["1.1.1.1:443".into(), format!("{child_ip}:7777")],
+ "open",
+ )
+ .await;
+
+ // Negatives.
+ let mut no: Vec<String> = vec![
+ format!("{gateway}:{}", host.any),
+ format!("{gateway}:{}", host.loopback),
+ format!("host.docker.internal:{}", host.any),
+ format!("169.254.169.254:80"),
+ format!("{other_ip}:7777"),
+ rebinding("169.254.169.254".parse().unwrap(), 80),
+ ];
+ for addr in &addrs {
+ no.push(format!("{addr}:{}", host.any));
+ no.push(rebinding(IpAddr::V4(*addr), host.any));
+ }
+ if let Some(gw) = lan_gw {
+ no.push(format!("{gw}:53"));
+ no.push(format!("{gw}:80"));
+ }
+ // A missing alias name resolves to nothing: drop it rather than
+ // count `noname` as reached.
+ let got = g.probe(&no).await;
+ eprintln!(" {runtime}: host, LAN, metadata, other tree, rebinding: {got:?}");
+ for (t, v) in &got {
+ assert!(
+ v == "blocked" || (v == "noname" && t.starts_with("host.docker.internal")),
+ "{runtime}: reached {t} ({v})"
+ );
+ }
+ // Root in the guest has no raw sockets to forge with.
+ let raw = g
+ .sh("python3 -c 'import socket;socket.socket(socket.AF_PACKET,socket.SOCK_RAW)' 2>&1 && echo RAW_OK || echo RAW_DENIED")
+ .await;
+ assert!(raw.ends_with("RAW_DENIED"), "{runtime}: raw socket: {raw}");
+
+ // `localhost` with every port: the host's listener through the
+ // gateway, never the daemon's port.
+ eprintln!("{runtime}: localhost (all ports) reaches the host, not the daemon");
+ let daemon = std::env::var("CUA_HOME").map(std::path::PathBuf::from).unwrap();
+ std::fs::create_dir_all(&daemon).unwrap();
+ std::fs::write(
+ daemon.join("daemon.json"),
+ format!(
+ r#"{{"pid":1,"loopback_url":"http://127.0.0.1:{}","version":"test"}}"#,
+ host.loopback
+ ),
+ )
+ .unwrap();
+ let mut lh = NetworkSettings::preset(NetworkPreset::Localhost);
+ lh.all_localhost_ports = true;
+ rt.start(&spec(&open_host, runtime, &format!("local:{open_host}"), lh))
+ .await
+ .expect("start localhost");
+ let lg = guest(&rt, &open_host).await;
+ lg.wait_internet().await;
+ let lgw = ip_of(&open_host).await.split_whitespace().nth(1).unwrap_or_default().to_string();
+ // A listener on every address answers through the gateway.
+ lg.expect_all("the host via localhost", &[format!("{lgw}:{}", host.any)], "open")
+ .await;
+ let mut daemon_targets = vec![format!("{lgw}:{}", host.loopback)];
+ for addr in &addrs {
+ daemon_targets.push(format!("{addr}:{}", host.loopback));
+ }
+ lg.expect_all("the daemon's port", &daemon_targets, "blocked").await;
+ lg.expect_all("metadata", &["169.254.169.254:80".into()], "blocked")
+ .await;
+ let _ = std::fs::remove_file(daemon.join("daemon.json"));
+ }))
+ .await;
+ for n in names.iter().rev() {
+ let _ = rt.delete(n).await;
+ }
+ if let Err(p) = result {
+ std::panic::resume_unwind(p);
+ }
+ }
+
+ #[tokio::test]
+ #[ignore = "needs a Docker engine on Linux with nftables; run with --ignored"]
+ async fn container_runc_secure_default() {
+ run("runc").await;
+ }
+
+ #[tokio::test]
+ #[ignore = "needs a Docker engine on Linux with runsc and nftables; run with --ignored"]
+ async fn container_gvisor_secure_default() {
+ run("gvisor").await;
+ }
+}
+
+/// The negatives every VM kind shares: the host's own addresses, the
+/// host's loopback (`alias`, the guest's address for it), its LAN gateway,
+/// metadata, and rebinding names for them.
+fn vm_negatives(host: &HostListeners, alias: &str) -> Vec<String> {
+ let (addrs, lan_gw) = host_facts();
+ let mut no: Vec<String> = vec![
+ format!("{alias}:{}", host.any),
+ format!("{alias}:{}", host.loopback),
+ "169.254.169.254:80".into(),
+ rebinding("169.254.169.254".parse().unwrap(), 80),
+ ];
+ for addr in &addrs {
+ no.push(format!("{addr}:{}", host.any));
+ no.push(format!("{addr}:{}", host.loopback));
+ no.push(rebinding(IpAddr::V4(*addr), host.any));
+ }
+ if let Some(gw) = lan_gw {
+ no.push(format!("{gw}:53"));
+ no.push(format!("{gw}:80"));
+ }
+ no
+}
+
+async fn vm_checks(g: &Guest, what: &str, host: &HostListeners, alias: &str) {
+ g.wait_internet().await;
+ let dns = g
+ .sh("getent hosts example.com >/dev/null && echo resolved")
+ .await;
+ assert_eq!(dns, "resolved", "{what}: DNS: {dns}");
+ let got = g.probe(&vm_negatives(host, alias)).await;
+ eprintln!(" {what}: host, LAN, metadata, rebinding: {got:?}");
+ for (t, v) in &got {
+ assert_eq!(v, "blocked", "{what}: reached {t} ({v})");
+ }
+}
+
+// --------------------------------------------------------------------- QEMU
+
+mod qemu {
+ use super::*;
+ use cua_vmm::Probe;
+ use cua_vmm::exec::SshExec;
+ use cua_vmm::qemu::{QemuConfig, QemuRuntime};
+
+ async fn guest(rt: &QemuRuntime, name: &str) -> Guest {
+ let ep = rt.endpoints(name).await.unwrap();
+ assert!(ep.qmp.is_none(), "QMP must not be a TCP port: {:?}", ep.qmp);
+ let ssh = ep.ssh.expect("SSH endpoint");
+ let exec =
+ SshExec::new(&ssh.host, ssh.port, &ssh.user).key(ssh.private_key.expect("managed key"));
+ let g = Guest {
+ exec: std::sync::Arc::new(exec),
+ root: "sudo -n",
+ };
+ for _ in 0..60 {
+ if g.sh("id -u").await == "0" {
+ break;
+ }
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ }
+ g.upload().await;
+ g
+ }
+
+ #[tokio::test]
+ #[ignore = "boots a QEMU VM under KVM in a pasta namespace; run with --ignored"]
+ async fn qemu_secure_default() {
+ let disk = std::env::var("CUA_EGRESS_TEST_DISK").expect("CUA_EGRESS_TEST_DISK");
+ let root = tempfile::tempdir().unwrap();
+ let rt = QemuRuntime::new(QemuConfig {
+ root: root.path().to_path_buf(),
+ vnc: false,
+ warm: false,
+ graceful_stop: Duration::from_secs(5),
+ ..QemuConfig::default()
+ });
+ let host = HostListeners::start().await;
+ let name = format!("cua-sd-qemu-{}", suffix());
+ let mut spec = StartSpec::new(&name, ImageSource::Disk { path: disk.into() })
+ .cpus(2)
+ .memory_mb(2048)
+ .probe(Probe::Tcp { port: 22 })
+ .ready_timeout(Duration::from_secs(600));
+ spec.network = Some(NetworkSettings::internet());
+ let result = futures_util::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
+ rt.start(&spec).await.expect("start");
+ let g = guest(&rt, &name).await;
+ vm_checks(&g, "qemu", &host, "10.0.2.2").await;
+ // `localhost` with one port: that one answers through 10.0.2.2,
+ // nothing else of the host's does.
+ eprintln!("qemu: localhost (port {})", host.loopback);
+ rt.stop(&name).await.unwrap();
+ let mut lh = NetworkSettings::preset(NetworkPreset::Localhost);
+ lh.localhost_ports = vec![host.loopback];
+ // A kept setting wins; set it through the lists' owner.
+ let st = root.path().join(&name).join("state.json");
+ let mut v: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(&st).unwrap()).unwrap();
+ v["network"] = serde_json::to_value(&lh).unwrap();
+ std::fs::write(&st, serde_json::to_vec(&v).unwrap()).unwrap();
+ let mut again = spec.clone();
+ again.image = ImageSource::Existing;
+ rt.start(&again).await.expect("restart");
+ let g = guest(&rt, &name).await;
+ g.wait_internet().await;
+ g.expect_all(
+ "the listed localhost port",
+ &[format!("10.0.2.2:{}", host.loopback)],
+ "open",
+ )
+ .await;
+ g.expect_all(
+ "another host port",
+ &[format!("10.0.2.2:{}", host.any)],
+ "blocked",
+ )
+ .await;
+ }))
+ .await;
+ let _ = rt.delete(&name).await;
+ if let Err(p) = result {
+ std::panic::resume_unwind(p);
+ }
+ }
+}
+
+// -------------------------------------------------------------- Firecracker
+
+mod firecracker {
+ use super::*;
+ use cua_vmm::microvm::{MicroVmConfig, MicroVmRuntime};
+
+ #[tokio::test]
+ #[ignore = "boots a Firecracker microVM under KVM in a pasta namespace; run with --ignored"]
+ async fn firecracker_secure_default() {
+ let image = std::env::var("CUA_EGRESS_TEST_IMAGE")
+ .unwrap_or_else(|_| "ghcr.io/trycua/linux:24.04-slim".into());
+ if cua_vmm::microvm::assets::firecracker_bin().is_none() {
+ cua_vmm::microvm::assets::install_firecracker()
+ .await
+ .expect("install firecracker");
+ }
+ let rt = MicroVmRuntime::new(MicroVmConfig {
+ resolver: Some(cua_image::RootfsLayerResolver::shared()),
+ ..MicroVmConfig::default()
+ });
+ let host = HostListeners::start().await;
+ let name = format!("cua-sd-fc-{}", suffix());
+ let mut spec = StartSpec::new(&name, ImageSource::oci(image))
+ .cpus(1)
+ .memory_mb(1024)
+ .command(["sleep", "infinity"])
+ .ready_timeout(Duration::from_secs(300));
+ spec.network = Some(NetworkSettings::internet());
+ let result = futures_util::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
+ rt.start(&spec).await.expect("start");
+ let g = Guest {
+ exec: rt.guest_exec(&name).await.unwrap().unwrap(),
+ root: "",
+ };
+ g.upload().await;
+ vm_checks(&g, "firecracker", &host, "172.16.0.1").await;
+ }))
+ .await;
+ let _ = rt.delete(&name).await;
+ if let Err(p) = result {
+ std::panic::resume_unwind(p);
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-disk/tests/gc.rs b/libs/cua/crates/cua-disk/tests/gc.rs
index 9808a0fca6..26fe786c91 100644
--- a/libs/cua/crates/cua-disk/tests/gc.rs
+++ b/libs/cua/crates/cua-disk/tests/gc.rs
@@ -87,6 +87,7 @@ fn qemu_sandbox(l: &Layout, name: &str, backing: &Path) {
ssh: None,
restrict_network: false,
egress: None,
+ network: None,
netns: false,
pasta_pid: None,
extra_args: vec![],
diff --git a/libs/cua/crates/cua-hotspot/src/lib.rs b/libs/cua/crates/cua-hotspot/src/lib.rs
index feafa05b85..cdb1df907a 100644
--- a/libs/cua/crates/cua-hotspot/src/lib.rs
+++ b/libs/cua/crates/cua-hotspot/src/lib.rs
@@ -31,18 +31,31 @@ pub mod peer {
use futures_util::{Sink, SinkExt, Stream, StreamExt};
use std::collections::HashMap;
use std::sync::Arc;
- use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::sync::mpsc;
/// Serves the peer end of a hotspot channel: dials every `OPEN` with
/// `dial` and relays bytes, until `source` ends.
- pub async fn serve_egress<S, K, D, F>(mut source: S, mut sink: K, dial: D)
+ pub async fn serve_egress<S, K, D, F>(source: S, sink: K, dial: D)
where
S: Stream<Item = Vec<u8>> + Unpin + Send,
K: Sink<Vec<u8>> + Unpin + Send + 'static,
D: Fn(String, u16) -> F + Send + Sync + 'static,
F: std::future::Future<Output = std::io::Result<TcpStream>> + Send + 'static,
+ {
+ serve_streams(source, sink, dial).await
+ }
+
+ /// [`serve_egress`] for any byte stream, not only TCP: the host serves
+ /// a Space's spawn channel with in-memory streams to its own API.
+ pub async fn serve_streams<S, K, D, F, T>(mut source: S, mut sink: K, dial: D)
+ where
+ S: Stream<Item = Vec<u8>> + Unpin + Send,
+ K: Sink<Vec<u8>> + Unpin + Send + 'static,
+ D: Fn(String, u16) -> F + Send + Sync + 'static,
+ F: std::future::Future<Output = std::io::Result<T>> + Send + 'static,
+ T: AsyncRead + AsyncWrite + Send + 'static,
{
let (out_tx, mut out_rx) = mpsc::channel::<Frame>(CHANNEL_DEPTH);
let writer = tokio::spawn(async move {
@@ -78,7 +91,7 @@ pub mod peer {
}
};
let _ = out.send(Frame::OpenOk { stream }).await;
- let (mut r, mut w) = target.into_split();
+ let (mut r, mut w) = tokio::io::split(target);
let mut b = vec![0u8; READ_CHUNK];
loop {
tokio::select! {
diff --git a/libs/cua/crates/cua-image/src/canonical.rs b/libs/cua/crates/cua-image/src/canonical.rs
index 3ddc1b1042..1e1f13b0d0 100644
--- a/libs/cua/crates/cua-image/src/canonical.rs
+++ b/libs/cua/crates/cua-image/src/canonical.rs
@@ -13,11 +13,14 @@
//! Tiers (`<os-version>[-<tier>][-disk]`): no suffix is the full default
//! (dev tooling), `-slim` the minimum that passes `cua-spacesd doctor
//! --strict` with every feature (CI and benchmarks use it), on macOS
-//! `-xcode[-X.Y]` adds one pinned Xcode with its iOS simulator runtime, and
+//! `-xcode` (also `dev`) is the macOS Space with developer tools: Xcode, its iOS
+//! simulator runtime and Apple developer tools, built on the user's own Mac from
+//! the full image (Apple's terms: never published), and
//! on Linux `-docker` is slim plus the Docker engine (a VM: dockerd up at
//! boot, for Docker Compose stacks; the tier word resolves to
//! `-docker-disk`).
-//! [`tier_image`] builds them; entries the catalog marks unpublished fail
+//! [`tier_image`] builds them; entries the catalog marks unpublished (and not
+//! derived on the user's machine) fail
//! with [`ImageError::NotPublished`]. [`omarchy_image`] names the Omarchy
//! distribution image (`ghcr.io/trycua/omarchy:edge`, an amd64 VM).
//!
@@ -145,13 +148,14 @@ pub enum Tier {
}
impl Tier {
- /// Parses `slim`, `full` (or empty), `xcode`, `xcode-26.1`, `docker`.
+ /// Parses `slim`, `full` (or empty), `xcode` (or `dev`), `xcode-26.1`, `docker`.
pub fn parse(tier: &str) -> Result<Self> {
let t = tier.trim().to_ascii_lowercase();
match t.as_str() {
"" | "full" | "default" => Ok(Self::Full),
"slim" => Ok(Self::Slim),
- "xcode" => Ok(Self::Xcode(None)),
+ // `dev`: the macOS Space with developer tools, as an agent says it.
+ "xcode" | "dev" => Ok(Self::Xcode(None)),
"docker" => Ok(Self::Docker),
_ => match t.strip_prefix("xcode-") {
Some(v) if !v.is_empty() && v.bytes().all(|b| b.is_ascii_digit() || b == b'.') => {
@@ -575,6 +579,9 @@ mod tests {
assert_eq!(t(""), Tier::Full);
assert_eq!(t("SLIM"), Tier::Slim);
assert_eq!(t("xcode-26.1").suffix(), "-xcode-26.1");
+ // The macOS Space with developer tools, by the word an agent uses.
+ assert_eq!(t("dev"), Tier::Xcode(None));
+ assert_eq!(t("DEV").suffix(), "-xcode");
assert!(Tier::parse("xcode-beta").is_err());
assert!(Tier::parse("tiny").is_err());
let full = tier_for_with(CanonicalOs::Linux, None, &Tier::Full, &none).unwrap();
@@ -586,10 +593,10 @@ mod tests {
);
let slim = tier_for_with(CanonicalOs::Linux, None, &Tier::Slim, &over);
let xcode = tier_for_with(CanonicalOs::Macos, Some("tahoe"), &t("xcode"), &none);
- for (got, want) in [
- (slim, "ghcr.io/trycua/linux:24.04-slim"),
- (xcode, "ghcr.io/trycua/macos:26-xcode"), // <!-- cua-image-unverified --> not published yet
- ] {
+ // The macOS Space with developer tools is never published: it is
+ // derived on the user's Mac, so the tier resolves.
+ assert_eq!(xcode.unwrap(), "ghcr.io/trycua/macos:26-xcode"); // <!-- cua-image-unverified --> not published yet
+ for (got, want) in [(slim, "ghcr.io/trycua/linux:24.04-slim")] {
// Unpublished until CI publishes the tier; then the ref itself.
match crate::catalog::find(want) {
Some(e) if !e.published => assert!(
diff --git a/libs/cua/crates/cua-image/src/catalog.rs b/libs/cua/crates/cua-image/src/catalog.rs
index 5b1df82d6a..6dc1b1bb3b 100644
--- a/libs/cua/crates/cua-image/src/catalog.rs
+++ b/libs/cua/crates/cua-image/src/catalog.rs
@@ -52,6 +52,13 @@ pub struct CatalogEntry {
/// `Some(false)`: the guest cannot use GPU acceleration (absent: no claim).
#[serde(default)]
pub gpu: Option<bool>,
+ /// The published image this one is built from on the user's own machine
+ /// when it is not available to pull: the macOS Space with developer tools
+ /// is the full macOS image plus the Xcode the Mac already has. Such an
+ /// entry resolves even while `published` is false (to that build, which
+ /// the Lume runtime does on first use) and is pulled once it is published.
+ #[serde(default)]
+ pub derived_from: Option<String>,
}
/// The guest distribution a catalog entry names (`distro`).
@@ -119,14 +126,34 @@ pub fn find(reference: &str) -> Option<&'static CatalogEntry> {
}
/// `Ok(reference)` unless the catalog lists it as unpublished. References
-/// the catalog does not list pass through (other versions, local builds).
+/// the catalog does not list pass through (other versions, local builds), and
+/// so do the ones built on the user's machine ([`derived_from`]).
pub fn require_published(reference: String) -> Result<String> {
match find(&reference) {
- Some(e) if !e.published => Err(ImageError::NotPublished { reference }),
+ Some(e) if !e.published && e.derived_from.is_none() => {
+ Err(ImageError::NotPublished { reference })
+ }
_ => Ok(reference),
}
}
+/// The published image `reference` is built from on this computer, when the
+/// catalog lists it as derived ([`CatalogEntry::derived_from`]). A digest on
+/// `reference` is ignored: it names the parent's.
+pub fn derived_from(reference: &str) -> Option<&'static str> {
+ derived_from_in(reference, entries())
+}
+
+/// [`derived_from`] over explicit entries (tests).
+pub fn derived_from_in<'a>(reference: &str, entries: &'a [CatalogEntry]) -> Option<&'a str> {
+ let wanted = NormalizedRef::parse(reference.trim()).ok()?;
+ entries.iter().find_map(|e| {
+ let parent = e.derived_from.as_deref()?;
+ let n = NormalizedRef::parse(&e.reference).ok()?;
+ (n.repo() == wanted.repo() && n.tag == wanted.tag).then_some(parent)
+ })
+}
+
/// `(ref, os)` of every catalog entry, for [`catalog_os`].
fn os_pairs() -> &'static [(String, String)] {
static PAIRS: OnceLock<Vec<(String, String)>> = OnceLock::new();
@@ -236,6 +263,25 @@ mod tests {
}
}
+ #[test]
+ fn the_developer_tools_image_falls_back_to_a_local_build() {
+ let x = "ghcr.io/trycua/macos:26-xcode";
+ let e = find(x).expect("listed");
+ assert_eq!(e.derived_from.as_deref(), Some("ghcr.io/trycua/macos:26"));
+ assert_eq!(require_published(x.into()).as_deref().ok(), Some(x));
+ assert_eq!(derived_from(x), Some("ghcr.io/trycua/macos:26"));
+ let pinned = format!("{x}@sha256:{}", "a".repeat(64));
+ assert_eq!(derived_from(&pinned), Some("ghcr.io/trycua/macos:26"));
+ assert_eq!(derived_from("ghcr.io/trycua/macos:26"), None);
+ assert_eq!(derived_from("ghcr.io/trycua/macos:26-slim"), None);
+ // The parent is published, or the derive would have nothing to start from.
+ assert!(find("ghcr.io/trycua/macos:26").is_some_and(|p| p.published));
+ // Nothing else is derived.
+ for e in entries().iter().filter(|e| e.derived_from.is_some()) {
+ assert_eq!(e.reference, x);
+ }
+ }
+
#[test]
fn every_entry_names_its_distro() {
for e in entries() {
@@ -276,6 +322,7 @@ mod tests {
local: None,
sizes: None,
gpu: None,
+ derived_from: None,
distro: Some(Distro {
id: id.into(),
name: n.into(),
diff --git a/libs/cua/crates/cua-image/src/resolve.rs b/libs/cua/crates/cua-image/src/resolve.rs
index 4eb9800245..b79613edfc 100644
--- a/libs/cua/crates/cua-image/src/resolve.rs
+++ b/libs/cua/crates/cua-image/src/resolve.rs
@@ -529,6 +529,31 @@ pub async fn resolve_with(
reference: &str,
backend: Backend,
arch: &str,
+) -> Result<ResolvedImage> {
+ let found = resolve_listed(src, reference, backend, arch).await;
+ // The macOS Space with developer tools is published like the other macOS
+ // images; where it is not (yet, or at all) it is built on this computer
+ // from its parent, so it resolves as the parent's Lume build under its
+ // own name. The digest is then the parent's: a new parent is a new build.
+ let input = NormalizedRef::parse(reference)?;
+ if let Err(ImageError::NotFound(_)) = &found
+ && let Some(parent) = crate::catalog::derived_from(&input.full())
+ && backend.accepts().contains(&Variant::Lume)
+ {
+ let mut r = Box::pin(resolve_listed(src, parent, backend, arch)).await?;
+ r.reference = input.full();
+ r.variant_ref = input.full();
+ r.spacesd = Some(true);
+ return Ok(r);
+ }
+ found
+}
+
+async fn resolve_listed(
+ src: &dyn ManifestSource,
+ reference: &str,
+ backend: Backend,
+ arch: &str,
) -> Result<ResolvedImage> {
let input = NormalizedRef::parse(reference)?;
let accepts = backend.accepts();
diff --git a/libs/cua/crates/cua-image/src/resolve/tests.rs b/libs/cua/crates/cua-image/src/resolve/tests.rs
index adcc1335a2..f971c836a7 100644
--- a/libs/cua/crates/cua-image/src/resolve/tests.rs
+++ b/libs/cua/crates/cua-image/src/resolve/tests.rs
@@ -534,3 +534,38 @@ async fn live_canonical_images_resolve() {
}
eprintln!("{root:#?}\n{disk:#?}\n{win:#?}");
}
+
+/// The macOS Space with developer tools is published like the other macOS
+/// images; until it is (or where it is not), it resolves as its parent's Lume
+/// build, under its own name, and only for Lume.
+#[tokio::test]
+async fn the_developer_tools_image_resolves_as_its_parent() {
+ let mut r = FakeRegistry::default();
+ let lume = r.lume("ghcr.io/trycua/macos:26");
+ let x = format!("{}:26-xcode", crate::canonical::MACOS_REPO);
+ for b in [Backend::Auto, Backend::Local, Backend::Lume] {
+ let got = go(&r, &x, b, "arm64").await.unwrap();
+ assert_eq!(got.variant, Variant::Lume, "{b:?}");
+ assert_eq!(got.reference, x);
+ assert_eq!(got.variant_ref, x);
+ assert_eq!(got.digest, lume, "the parent's digest names the build");
+ assert_eq!(got.os, "macos");
+ assert_eq!(got.spacesd, Some(true));
+ }
+ // A container backend has no Lume and no tag to read: not found, as before.
+ assert!(go(&r, &x, Backend::Container, "arm64").await.is_err());
+ // An unlisted tier is still read from the registry (and is not there).
+ let other = format!("{}:26-xcode-beta", crate::canonical::MACOS_REPO);
+ assert!(go(&r, &other, Backend::Lume, "arm64").await.is_err());
+}
+
+#[tokio::test]
+async fn once_published_the_developer_tools_image_resolves_as_itself() {
+ // Only its own tag exists (no parent to fall back to).
+ let mut r = FakeRegistry::default();
+ let x = format!("{}:26-xcode", crate::canonical::MACOS_REPO);
+ let own = r.lume(&x);
+ let got = go(&r, &x, Backend::Local, "arm64").await.unwrap();
+ assert_eq!(got.digest, own);
+ assert_eq!(got.variant_ref, x);
+}
diff --git a/libs/cua/crates/cua-proto/src/lib.rs b/libs/cua/crates/cua-proto/src/lib.rs
index f70e1afdb8..9c7452b988 100644
--- a/libs/cua/crates/cua-proto/src/lib.rs
+++ b/libs/cua/crates/cua-proto/src/lib.rs
@@ -130,6 +130,45 @@ pub mod metadata {
pub const TUNNEL_WS_PATH: &str = "/tunnel";
/// Reverse-SOCKS hotspot WebSocket path (ticket-authenticated).
pub const HOTSPOT_WS_PATH: &str = "/hotspot";
+ /// Spawn channel WebSocket path (ticket-authenticated): the host that
+ /// runs the Space serves its child-Space API over it.
+ pub const SPAWN_WS_PATH: &str = "/spawn";
+ /// File (in a [`spawn_dirs`] directory) holding a Space's spawn
+ /// capability.
+ pub const SPAWN_TOKEN_FILE: &str = "spawn-token";
+ /// File (in a [`spawn_dirs`] directory) holding the spawn listener's URL.
+ pub const SPAWN_ADDRESS_FILE: &str = "spawn-address";
+ /// Environment of processes in a Space: its id.
+ pub const ENV_SPACE: &str = "CUA_SPACE";
+ /// Environment of processes in a Space: the spawn listener's URL.
+ pub const ENV_SPAWN: &str = "CUA_SPAWN";
+ /// Environment of processes in a Space: the capability's file.
+ pub const ENV_SPAWN_TOKEN_FILE: &str = "CUA_SPAWN_TOKEN_FILE";
+
+ /// Where a guest keeps its spawn files, in the order cua-spacesd tries
+ /// them (it takes the first it can own) and clients look: `/run/cua`,
+ /// `$XDG_RUNTIME_DIR/cua-spawn`, `/dev/shm/cua-spawn-<uid>`, then the
+ /// temp dir's `cua-spawn-<uid>` (`cua-spawn` without a uid).
+ pub fn spawn_dirs(
+ uid: Option<u32>,
+ xdg_runtime_dir: Option<&std::path::Path>,
+ temp_dir: &std::path::Path,
+ ) -> Vec<std::path::PathBuf> {
+ let mut dirs = Vec::new();
+ if let Some(uid) = uid {
+ dirs.push(std::path::PathBuf::from("/run/cua"));
+ if let Some(x) = xdg_runtime_dir.filter(|x| !x.as_os_str().is_empty()) {
+ dirs.push(x.join("cua-spawn"));
+ }
+ dirs.push(std::path::PathBuf::from(format!(
+ "/dev/shm/cua-spawn-{uid}"
+ )));
+ dirs.push(temp_dir.join(format!("cua-spawn-{uid}")));
+ } else {
+ dirs.push(temp_dir.join("cua-spawn"));
+ }
+ dirs
+ }
/// Cua Volume WebSocket path (ticket-authenticated): the client serves
/// the guest's volume mount over it.
pub const VOLUME_WS_PATH: &str = "/volume";
diff --git a/libs/cua/crates/cua-sandbox-core/src/external.rs b/libs/cua/crates/cua-sandbox-core/src/external.rs
index 75ef21b7ee..1014c3d2cc 100644
--- a/libs/cua/crates/cua-sandbox-core/src/external.rs
+++ b/libs/cua/crates/cua-sandbox-core/src/external.rs
@@ -1447,6 +1447,17 @@ impl LocalRuntime for WithExternal {
}
}
+ async fn set_network(
+ &self,
+ name: &str,
+ settings: &cua_vmm::network::NetworkSettings,
+ ) -> RuntimeResult<cua_vmm::network::Applied> {
+ match self.owner(name).await {
+ Some(rt) => rt.set_network(name, settings).await,
+ None => self.inner.set_network(name, settings).await,
+ }
+ }
+
async fn suspend(&self, name: &str) -> RuntimeResult<()> {
match self.owner(name).await {
Some(rt) => rt.suspend(name).await,
@@ -1821,6 +1832,8 @@ mod tests {
headless: false,
spacesd: None,
egress: Default::default(),
+ network: None,
+ tree: None,
gpu: None,
probes: vec![],
ephemeral: false,
diff --git a/libs/cua/crates/cua-sandbox-core/src/placement.rs b/libs/cua/crates/cua-sandbox-core/src/placement.rs
index 96ed180bc0..6e3346e59e 100644
--- a/libs/cua/crates/cua-sandbox-core/src/placement.rs
+++ b/libs/cua/crates/cua-sandbox-core/src/placement.rs
@@ -1007,10 +1007,26 @@ pub fn select(
);
Runtime::Vz
}
- (On::Local, Kind::MicroVm) if host.apple_containers => {
+ // Apple's Containerization can't protect a Space's network: it is
+ // never picked for you under the secure default, only chosen.
+ (On::Local, Kind::MicroVm)
+ if host.apple_containers
+ && cua_vmm::network::Mode::from_env() == cua_vmm::network::Mode::Legacy =>
+ {
why.push("microVMs on a Mac run on Apple's Containerization".into());
Runtime::Containerization
}
+ (On::Local, Kind::MicroVm) if host.apple_containers => {
+ return Err(PlacementError::new(
+ Axis::Runtime,
+ "auto",
+ "microVMs on this Mac need cua's own monitor (cua-vz), which is not set up. \
+ Apple's Containerization can't protect your network yet: choose it with \
+ --runtime containerization and No protection, or use a VM"
+ .into(),
+ vec!["vz".into(), "containerization".into()],
+ ));
+ }
_ => offered.first().cloned().unwrap_or(Runtime::Auto),
}
};
@@ -1561,11 +1577,18 @@ mod tests {
let s = select(&On::Local, Auto, &rt(w), &linux(), &MAC).unwrap();
assert_eq!((s.kind, s.runtime), (MicroVm, Runtime::Vz));
}
- // Without cua-vz (an older install) on macOS 26: Apple's
- // Containerization, as before.
- let s = select(&On::Local, MicroVm, &Runtime::Auto, &linux(), &MAC_26_NO_VZ).unwrap();
- assert_eq!((s.kind, s.runtime), (MicroVm, Runtime::Containerization));
- assert!(s.reason.contains("Containerization"), "{}", s.reason);
+ // Without cua-vz (an older install) on macOS 26: never Apple's
+ // Containerization for you under the secure default (it can't
+ // protect the network); as before under the old one.
+ let picked = select(&On::Local, MicroVm, &Runtime::Auto, &linux(), &MAC_26_NO_VZ);
+ if cua_vmm::network::Mode::from_env() == cua_vmm::network::Mode::Secure {
+ let e = picked.unwrap_err().to_string();
+ assert!(e.contains("can't protect your network"), "{e}");
+ } else {
+ let s = picked.unwrap();
+ assert_eq!((s.kind, s.runtime), (MicroVm, Runtime::Containerization));
+ assert!(s.reason.contains("Containerization"), "{}", s.reason);
+ }
// Containerization by name (or its short words) where it runs.
for w in ["containerization", "apple", "apple-container"] {
let s = select(&On::Local, Auto, &rt(w), &linux(), &MAC).unwrap();
diff --git a/libs/cua/crates/cua-sandbox-core/src/runtime.rs b/libs/cua/crates/cua-sandbox-core/src/runtime.rs
index 3e71215a3e..8c0784ad68 100644
--- a/libs/cua/crates/cua-sandbox-core/src/runtime.rs
+++ b/libs/cua/crates/cua-sandbox-core/src/runtime.rs
@@ -140,6 +140,15 @@ pub struct LocalStartSpec {
skip_serializing_if = "cua_vmm::egress::EgressPolicy::is_empty"
)]
pub egress: cua_vmm::egress::EgressPolicy,
+ /// The sandbox's network settings ([`cua_vmm::network`]), compiled by
+ /// the runtime. `None`: a caller from before network settings (the
+ /// runtime keeps to `restrict_network` and `egress`).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub network: Option<cua_vmm::network::NetworkSettings>,
+ /// The tree it belongs to ([`cua_vmm::StartSpec::tree`]); `None`: its
+ /// own.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tree: Option<String>,
/// A GPU option of the runtime (see [`crate::gpu`]); `None`: no GPU.
#[serde(default)]
pub gpu: Option<String>,
@@ -674,6 +683,20 @@ pub trait LocalRuntime: Send + Sync {
Ok(Default::default())
}
+ /// Replaces instance `name`'s network settings ([`cua_vmm::network`]),
+ /// kept with it; says whether they hold now or from its next start.
+ async fn set_network(
+ &self,
+ name: &str,
+ settings: &cua_vmm::network::NetworkSettings,
+ ) -> RuntimeResult<cua_vmm::network::Applied> {
+ let _ = (name, settings);
+ Err(RuntimeError::Unsupported {
+ backend: self.backend(),
+ op: "changing network settings (this runtime keeps none)".into(),
+ })
+ }
+
/// Builds `spec` (image layers on the container image `spec.from`)
/// into this machine's container engine and returns the reference to
/// run (`container:<ref>`). Cached by the same content hash as remote
diff --git a/libs/cua/crates/cua-sandbox-core/src/sandbox.rs b/libs/cua/crates/cua-sandbox-core/src/sandbox.rs
index 4097865d60..1982f5f312 100644
--- a/libs/cua/crates/cua-sandbox-core/src/sandbox.rs
+++ b/libs/cua/crates/cua-sandbox-core/src/sandbox.rs
@@ -287,6 +287,12 @@ pub struct CreateOptions {
/// the guest, from its first instruction (local runtimes that can;
/// everything else refuses a non-empty one).
pub egress: cua_vmm::egress::EgressPolicy,
+ /// Network settings ([`cua_vmm::network`]): a preset and the user's
+ /// lists. `None`: what `network` and `egress` say
+ /// ([`cua_vmm::network::NetworkSettings::from_legacy`]).
+ pub network_settings: Option<cua_vmm::network::NetworkSettings>,
+ /// The tree it belongs to (a top-level Space's id); `None`: its own.
+ pub network_tree: Option<String>,
/// The process that owns an ephemeral local sandbox (recorded in its
/// lease; the sandbox is reaped once that process is gone). `None`:
/// this process. A daemon passes its client's pid.
@@ -348,6 +354,8 @@ impl CreateOptions {
headless: false,
spacesd: None,
egress: Default::default(),
+ network_settings: None,
+ network_tree: None,
owner_pid: None,
contrib: None,
keep_on_failure: false,
@@ -358,6 +366,18 @@ impl CreateOptions {
}
}
+ /// The network settings this create asks for: `network_settings`, else
+ /// what `network` and `egress` say (`internet` when neither says
+ /// anything).
+ pub fn effective_network(&self) -> cua_vmm::network::NetworkSettings {
+ self.network_settings.clone().unwrap_or_else(|| {
+ cua_vmm::network::NetworkSettings::from_legacy(
+ &self.egress,
+ self.network == NetworkMode::None,
+ )
+ })
+ }
+
/// Adds a sidecar.
pub fn sidecar(mut self, sidecar: Sidecar) -> Self {
self.sidecars.push(sidecar);
@@ -1153,10 +1173,14 @@ impl Sandboxes {
container_runtime: o.container_runtime.clone(),
kind: (o.kind != Kind::Auto).then(|| o.kind.to_string()),
runtime: (o.runtime != Runtime::Auto).then(|| o.runtime.to_string()),
- restrict_network: o.network == NetworkMode::None,
+ // `none` settings cut the network the way every runtime knows.
+ restrict_network: o.network == NetworkMode::None
+ || o.effective_network().preset == cua_vmm::network::NetworkPreset::None,
headless: o.headless,
spacesd: o.spacesd,
egress: o.egress.clone(),
+ network: Some(o.effective_network()),
+ tree: o.network_tree.clone(),
gpu: o.gpu.clone().filter(|g| !g.trim().is_empty()),
probes: o
.wait_for
@@ -1971,6 +1995,25 @@ impl Sandboxes {
}
}
+ /// Replaces sandbox `name`'s network settings ([`cua_vmm::network`]) on
+ /// its local runtime; says whether they hold now or from its next start.
+ pub async fn set_network(
+ &self,
+ name: &str,
+ settings: &cua_vmm::network::NetworkSettings,
+ ) -> Result<cua_vmm::network::Applied> {
+ settings
+ .validate()
+ .map_err(|e| Error::InvalidArgument(e.0))?;
+ match self.kind_of(name)? {
+ (ProviderKind::Local, _) => Ok(self.local()?.set_network(name, settings).await?),
+ (kind, _) => Err(Error::Unsupported {
+ provider: kind,
+ op: "network settings (they are kept by the machine a sandbox runs on)".into(),
+ }),
+ }
+ }
+
/// The egress policy kept with sandbox `name` (empty: none, or a
/// sandbox that is not local).
pub async fn egress(&self, name: &str) -> Result<cua_vmm::egress::EgressPolicy> {
diff --git a/libs/cua/crates/cua-sandbox-core/src/sandbox/checkpoints.rs b/libs/cua/crates/cua-sandbox-core/src/sandbox/checkpoints.rs
index 7d5e7c1e3a..f2a4aa56a9 100644
--- a/libs/cua/crates/cua-sandbox-core/src/sandbox/checkpoints.rs
+++ b/libs/cua/crates/cua-sandbox-core/src/sandbox/checkpoints.rs
@@ -509,6 +509,8 @@ impl Sandboxes {
headless: false,
spacesd: None,
egress: Default::default(),
+ network: None,
+ tree: None,
gpu: None,
probes: probes
.iter()
diff --git a/libs/cua/crates/cua-sandbox-core/tests/external_runtime.rs b/libs/cua/crates/cua-sandbox-core/tests/external_runtime.rs
index ce20c51b91..86bb1950bd 100644
--- a/libs/cua/crates/cua-sandbox-core/tests/external_runtime.rs
+++ b/libs/cua/crates/cua-sandbox-core/tests/external_runtime.rs
@@ -124,6 +124,8 @@ fn spec(name: &str, runtime: Option<&str>) -> LocalStartSpec {
headless: false,
spacesd: None,
egress: Default::default(),
+ network: None,
+ tree: None,
gpu: None,
probes: vec![],
ephemeral: false,
diff --git a/libs/cua/crates/cua-sdk/src/json.rs b/libs/cua/crates/cua-sdk/src/json.rs
index 2f2ecbb9d7..09413738e9 100644
--- a/libs/cua/crates/cua-sdk/src/json.rs
+++ b/libs/cua/crates/cua-sdk/src/json.rs
@@ -165,6 +165,11 @@ pub const JSON_UNARY_METHODS: &[&str] = &[
"/cua.env.v1.ProcessService/ResizePty",
"/cua.env.v1.ProcessService/GetExecRecord",
"/cua.env.v1.ProcessService/AdvanceEpoch",
+ "/cua.env.v1.ProcessService/PutService",
+ "/cua.env.v1.ProcessService/DeleteService",
+ "/cua.env.v1.ProcessService/ListServices",
+ "/cua.env.v1.ProcessService/ControlService",
+ "/cua.env.v1.ProcessService/GetServiceLogs",
"/cua.env.v1.StreamService/ListTargets",
"/cua.env.v1.StreamService/OpenMedia",
"/cua.env.v1.StreamService/SetPreferences",
@@ -192,6 +197,9 @@ pub const JSON_UNARY_METHODS: &[&str] = &[
"/cua.env.v1.TunnelService/StartHotspot",
"/cua.env.v1.TunnelService/StopHotspot",
"/cua.env.v1.TunnelService/GetHotspotStatus",
+ "/cua.env.v1.TunnelService/StartSpawn",
+ "/cua.env.v1.TunnelService/StopSpawn",
+ "/cua.env.v1.TunnelService/GetSpawnStatus",
"/cua.env.v1.WindowsService/ListWindows",
"/cua.env.v1.WindowsService/GetWindow",
"/cua.env.v1.WindowsService/ActivateWindow",
@@ -754,6 +762,46 @@ pub(crate) async fn call_unary<C: Channel>(ch: C, path: &str, json: &str) -> Res
)
.await
}
+ "/cua.env.v1.ProcessService/PutService" => {
+ unary::<C, pb::PutServiceRequest, pb::PutServiceResponse>(
+ ch,
+ "/cua.env.v1.ProcessService/PutService",
+ json,
+ )
+ .await
+ }
+ "/cua.env.v1.ProcessService/DeleteService" => {
+ unary::<C, pb::DeleteServiceRequest, pb::DeleteServiceResponse>(
+ ch,
+ "/cua.env.v1.ProcessService/DeleteService",
+ json,
+ )
+ .await
+ }
+ "/cua.env.v1.ProcessService/ListServices" => {
+ unary::<C, pb::ListServicesRequest, pb::ListServicesResponse>(
+ ch,
+ "/cua.env.v1.ProcessService/ListServices",
+ json,
+ )
+ .await
+ }
+ "/cua.env.v1.ProcessService/ControlService" => {
+ unary::<C, pb::ControlServiceRequest, pb::ControlServiceResponse>(
+ ch,
+ "/cua.env.v1.ProcessService/ControlService",
+ json,
+ )
+ .await
+ }
+ "/cua.env.v1.ProcessService/GetServiceLogs" => {
+ unary::<C, pb::GetServiceLogsRequest, pb::GetServiceLogsResponse>(
+ ch,
+ "/cua.env.v1.ProcessService/GetServiceLogs",
+ json,
+ )
+ .await
+ }
"/cua.env.v1.StreamService/ListTargets" => {
unary::<C, pb::ListTargetsRequest, pb::ListTargetsResponse>(
ch,
@@ -970,6 +1018,30 @@ pub(crate) async fn call_unary<C: Channel>(ch: C, path: &str, json: &str) -> Res
)
.await
}
+ "/cua.env.v1.TunnelService/StartSpawn" => {
+ unary::<C, pb::StartSpawnRequest, pb::StartSpawnResponse>(
+ ch,
+ "/cua.env.v1.TunnelService/StartSpawn",
+ json,
+ )
+ .await
+ }
+ "/cua.env.v1.TunnelService/StopSpawn" => {
+ unary::<C, pb::StopSpawnRequest, pb::StopSpawnResponse>(
+ ch,
+ "/cua.env.v1.TunnelService/StopSpawn",
+ json,
+ )
+ .await
+ }
+ "/cua.env.v1.TunnelService/GetSpawnStatus" => {
+ unary::<C, pb::GetSpawnStatusRequest, pb::GetSpawnStatusResponse>(
+ ch,
+ "/cua.env.v1.TunnelService/GetSpawnStatus",
+ json,
+ )
+ .await
+ }
"/cua.env.v1.WindowsService/ListWindows" => {
unary::<C, pb::ListWindowsRequest, pb::ListWindowsResponse>(
ch,
diff --git a/libs/cua/crates/cua-sdk/src/native/cua.rs b/libs/cua/crates/cua-sdk/src/native/cua.rs
index 6f803d2609..28dd9629bb 100644
--- a/libs/cua/crates/cua-sdk/src/native/cua.rs
+++ b/libs/cua/crates/cua-sdk/src/native/cua.rs
@@ -194,6 +194,17 @@ impl Cua {
/// start` replaces it.
#[uniffi::constructor]
pub fn auto(config: CuaConfig) -> Result<Arc<Self>> {
+ // Inside a Space with children on: its spawn channel (every Space
+ // made through it is a child of that Space).
+ if let Some(addr) = cua_daemon::client::spawn_channel() {
+ let client = {
+ let _guard = runtime().enter();
+ DaemonClient::new(addr)?
+ };
+ return Ok(Arc::new(Self {
+ backend: Backend::Daemon(client),
+ }));
+ }
// A daemon that is starting is waited for (bounded), not raced with
// an embedded runtime.
match cua_daemon::client::wait_for_starting(std::time::Duration::from_secs(30))? {
diff --git a/libs/cua/crates/cua-sdk/src/native/image.rs b/libs/cua/crates/cua-sdk/src/native/image.rs
index 5dcacd0d46..97857c2a05 100644
--- a/libs/cua/crates/cua-sdk/src/native/image.rs
+++ b/libs/cua/crates/cua-sdk/src/native/image.rs
@@ -243,7 +243,10 @@ mod tests {
canonical_image_tier("windows".into(), None, Some("xcode".into())),
Err(CuaError::InvalidArgument(_))
));
- let published = |r: &str| cua_image::catalog::find(r).is_none_or(|e| e.published);
+ // Derived on the user's Mac (the developer tools image) counts as available.
+ let published = |r: &str| {
+ cua_image::catalog::find(r).is_none_or(|e| e.published || e.derived_from.is_some())
+ };
for (got, want) in [
(
canonical_image_tier("linux".into(), None, Some("slim".into())),
diff --git a/libs/cua/crates/cua-sdk/src/native/spaces.rs b/libs/cua/crates/cua-sdk/src/native/spaces.rs
index 8dd8c3bcce..4ceec83137 100644
--- a/libs/cua/crates/cua-sdk/src/native/spaces.rs
+++ b/libs/cua/crates/cua-sdk/src/native/spaces.rs
@@ -41,6 +41,7 @@ pub const SPACES_TOOL_METHODS: &[(&str, &str)] = &[
("start_space", "Spaces.start"),
("resize_space", "Spaces.resize"),
("space_bash", "Space.bash"),
+ ("space_job", "Spaces.call_tool_json"),
("space_write", "Space.write"),
("upload", "Space.upload"),
("send_file", "Space.send_file"),
@@ -127,6 +128,9 @@ pub const SPACES_TOOL_METHODS: &[(&str, &str)] = &[
("volume_cache_set", "Spaces.volume_cache_set"),
("volume_cache_clear", "Spaces.volume_cache_clear"),
("share_space", "Space.share"),
+ ("network_show", "Spaces.network"),
+ ("network_set", "Spaces.set_network"),
+ ("space_service", "Space.put_service"),
("unshare_space", "Space.unshare"),
("space_shares", "Space.shares"),
("relay_register_space", "Spaces.relay_register"),
@@ -273,6 +277,164 @@ impl EgressEnforcement {
}
}
+/// A Space's network settings: a preset and the user's own lists. The host
+/// the Space runs on compiles them to rules it enforces outside the guest.
+///
+/// - `internet` (the default): the public internet and the Space's own
+/// tree; this computer, your local network, cloud metadata, other trees
+/// and the cua daemon are blocked;
+/// - `none`: no network;
+/// - `localhost`: `internet`, plus this computer's localhost on
+/// `localhost_ports` (every port only with `all_localhost_ports`);
+/// - `lan`: `internet`, plus your local network (not this computer);
+/// - `custom`: `custom_base` (`internet` or `none`) plus `allow` and `deny`;
+/// - `unprotected`: everything but cloud metadata, other trees and the
+/// daemon.
+///
+/// A runtime that can't protect a Space yet starts it without network and
+/// says so (`SpaceInfo.network_note`); it never starts it open unless the
+/// preset is `unprotected`.
+#[derive(Debug, Clone, Default, PartialEq, Eq, uniffi::Record, Deserialize)]
+pub struct NetworkSettings {
+ /// `internet`, `none`, `localhost`, `lan`, `custom` or `unprotected`;
+ /// empty is `internet`.
+ #[uniffi(default)]
+ #[serde(default)]
+ pub preset: String,
+ /// `localhost`: the ports of this computer's localhost the Space may
+ /// reach.
+ #[uniffi(default)]
+ #[serde(default)]
+ pub localhost_ports: Vec<u16>,
+ /// `localhost`: every port (the daemon's stay blocked).
+ #[uniffi(default)]
+ #[serde(default)]
+ pub all_localhost_ports: bool,
+ /// Destinations that stay reachable (addresses or CIDRs).
+ #[uniffi(default)]
+ #[serde(default)]
+ pub allow: Vec<String>,
+ /// Destinations that are blocked (addresses, CIDRs or `all`).
+ #[uniffi(default)]
+ #[serde(default)]
+ pub deny: Vec<String>,
+ /// `custom`: what it starts from, `internet` (empty) or `none`.
+ #[uniffi(default)]
+ #[serde(default)]
+ pub custom_base: String,
+ /// Set when the Space was allowed more than its parent: who and when.
+ #[uniffi(default = None)]
+ #[serde(default)]
+ pub widened_by: Option<String>,
+}
+
+impl From<NetworkSettings> for dpb::NetworkSettings {
+ fn from(n: NetworkSettings) -> Self {
+ dpb::NetworkSettings {
+ preset: n.preset,
+ localhost_ports: n.localhost_ports.into_iter().map(u32::from).collect(),
+ all_localhost_ports: n.all_localhost_ports,
+ allow: n.allow,
+ deny: n.deny,
+ custom_base: n.custom_base,
+ widened_by: n.widened_by.unwrap_or_default(),
+ }
+ }
+}
+
+impl From<dpb::NetworkSettings> for NetworkSettings {
+ fn from(n: dpb::NetworkSettings) -> Self {
+ NetworkSettings {
+ preset: if n.preset.is_empty() {
+ "internet".into()
+ } else {
+ n.preset
+ },
+ localhost_ports: n
+ .localhost_ports
+ .into_iter()
+ .filter_map(|p| u16::try_from(p).ok())
+ .collect(),
+ all_localhost_ports: n.all_localhost_ports,
+ allow: n.allow,
+ deny: n.deny,
+ custom_base: if n.custom_base.is_empty() {
+ "internet".into()
+ } else {
+ n.custom_base
+ },
+ widened_by: (!n.widened_by.is_empty()).then_some(n.widened_by),
+ }
+ }
+}
+
+impl From<cua_spaces::network::NetworkSettings> for NetworkSettings {
+ fn from(n: cua_spaces::network::NetworkSettings) -> Self {
+ cua_spaces::network::to_pb(&n).into()
+ }
+}
+
+impl NetworkSettings {
+ /// The checked model of these settings.
+ fn checked(&self) -> Result<cua_spaces::network::NetworkSettings> {
+ cua_spaces::network::from_pb(&self.clone().into())
+ .map_err(|e| CuaError::InvalidArgument(e.to_string()))
+ }
+}
+
+/// A Space's network as `cua network show` says it ([`Spaces::network`]).
+#[derive(Debug, Clone, Default, PartialEq, Eq, uniffi::Record)]
+pub struct SpaceNetworkInfo {
+ /// Its settings.
+ pub settings: NetworkSettings,
+ /// One plain line ("Internet only").
+ pub summary: String,
+ /// What the settings open beyond `internet`, one plain line each.
+ pub widenings: Vec<String>,
+ /// `enforced` (rules on the host, outside the guest), `no_network`
+ /// (its runtime can't protect it yet), `open` (No protection) or
+ /// `refused`; empty when unknown (a Space another computer runs).
+ pub enforcement: String,
+ /// Where the rules are enforced, or why its network is cut.
+ pub point: String,
+ /// Why its network is not what was asked; `None` otherwise.
+ pub note: Option<String>,
+ /// Its parent and its tree's top-level Space; `None` for a top-level
+ /// Space.
+ pub parent: Option<String>,
+ pub root: Option<String>,
+ /// What no setting opens, in plain words.
+ pub always_blocked: Vec<String>,
+ /// An update changed its settings: say so once.
+ pub notice_pending: bool,
+}
+
+impl From<dpb::SpaceNetworkInfo> for SpaceNetworkInfo {
+ fn from(i: dpb::SpaceNetworkInfo) -> Self {
+ SpaceNetworkInfo {
+ settings: i.settings.unwrap_or_default().into(),
+ summary: i.summary,
+ widenings: i.widenings,
+ enforcement: i.enforcement,
+ point: i.point,
+ note: (!i.note.is_empty()).then_some(i.note),
+ parent: (!i.parent.is_empty()).then_some(i.parent),
+ root: (!i.root.is_empty()).then_some(i.root),
+ always_blocked: i.always_blocked,
+ notice_pending: i.notice_pending,
+ }
+ }
+}
+
+/// What [`Spaces::set_network`] did.
+#[derive(Debug, Clone, Default, PartialEq, Eq, uniffi::Record)]
+pub struct SetNetworkResult {
+ /// `now` (the running guest is under them) or `next_start`.
+ pub applied: String,
+ /// The Space's network after the change.
+ pub network: SpaceNetworkInfo,
+}
+
/// What carries a connected Space's calls ([`Space::transport`]), for a
/// badge: whether the relay can read them.
#[derive(Debug, Clone, Default, PartialEq, Eq, uniffi::Record)]
@@ -446,6 +608,30 @@ pub struct SpaceInfo {
/// Where `egress` is enforced; `None` without one.
#[serde(default)]
pub egress_enforced: Option<EgressEnforcement>,
+ /// Its network settings; `None` for a Space this computer keeps no
+ /// record of, or one created before they existed (it gets them on its
+ /// next start).
+ #[serde(default)]
+ pub network: Option<NetworkSettings>,
+ /// Why its network is not what was asked, in plain words (a runtime
+ /// that can't protect it yet started it without network); `None`
+ /// otherwise.
+ #[serde(default)]
+ pub network_note: Option<String>,
+ /// An update changed its network settings (an old Space moved to the
+ /// new defaults): say so once.
+ #[serde(default)]
+ pub network_notice_pending: bool,
+ /// The Space it was created from, by id; `None` for a top-level Space.
+ #[serde(default)]
+ pub parent: Option<String>,
+ /// The top-level Space of its tree, by id; `None` for a top-level
+ /// Space.
+ #[serde(default)]
+ pub root: Option<String>,
+ /// How far below its tree's top-level Space it is (0: top-level).
+ #[serde(default)]
+ pub depth: u32,
/// Named volumes mounted in the Space (see
/// [`SpaceCreateOptions::volumes`]).
#[serde(default)]
@@ -700,6 +886,12 @@ impl From<dpb::Space> for SpaceInfo {
})
.unwrap_or_default(),
egress_enforced: EgressEnforcement::from_word(&s.egress_enforced),
+ network: s.network_settings.map(Into::into),
+ network_note: (!s.network_note.is_empty()).then_some(s.network_note),
+ network_notice_pending: s.network_notice_pending,
+ parent: (!s.parent.is_empty()).then_some(s.parent),
+ root: (!s.root.is_empty()).then_some(s.root),
+ depth: s.depth,
sharing: s.sharing.map(Into::into),
}
}
@@ -739,6 +931,12 @@ impl From<cua_spaces::SpaceInfo> for SpaceInfo {
created_at_unix: i64::try_from(s.created_at_unix).unwrap_or(0),
egress: s.egress.into(),
egress_enforced: s.egress_enforced.map(Into::into),
+ network: s.network.as_ref().map(|n| n.settings.clone().into()),
+ network_note: s.network.as_ref().and_then(|n| n.note.clone()),
+ network_notice_pending: s.network.as_ref().is_some_and(|n| n.notice_pending),
+ parent: s.tree.as_ref().and_then(|t| t.parent.clone()),
+ root: s.tree.as_ref().and_then(|t| t.root.clone()),
+ depth: s.tree.as_ref().map_or(0, |t| t.depth),
sharing: s.sharing.map(Into::into),
}
}
@@ -900,6 +1098,19 @@ pub struct SpaceCreateOptions {
/// to enforce it makes the create fail.
#[uniffi(default = None)]
pub egress: Option<EgressPolicy>,
+ /// Network settings (see [`NetworkSettings`]). `None`: what `network`
+ /// and `egress` say (`internet` when neither says anything). A daemon
+ /// too old to keep them makes the create fail.
+ #[uniffi(default = None)]
+ pub network_settings: Option<NetworkSettings>,
+ /// Create it as a child of this Space (id or name): its network is no
+ /// more open than its parent's, and it joins the parent's tree.
+ #[uniffi(default = None)]
+ pub parent: Option<String>,
+ /// With `parent`: let its network be more open than its parent's
+ /// (recorded on the Space).
+ #[uniffi(default = None)]
+ pub widen: Option<bool>,
/// With `on` a linked cloud (`aws`, `hetzner`, ...): the machine type
/// its host must be (`c7g.xlarge`, `cax41`), a pin of the elastic
/// pool's solve. `None`: the pool picks the cheapest that fits.
@@ -908,6 +1119,10 @@ pub struct SpaceCreateOptions {
/// With `on` a linked cloud: the region its host must be in.
#[uniffi(default = None)]
pub region: Option<String>,
+ /// Lets the Space make child Spaces of its own ([`Spaces::set_children`]).
+ /// `None`: off. Only a Space the machine of the runtime runs itself.
+ #[uniffi(default = None)]
+ pub children: Option<bool>,
}
impl SpaceCreateOptions {
@@ -1219,6 +1434,206 @@ pub struct SpaceWriteReport {
pub sha256: String,
}
+/// What a tree's children may hold and cost ([`Spaces::set_tree_budget`]).
+/// `None`: the default.
+#[derive(Debug, Clone, Default, PartialEq, uniffi::Record)]
+pub struct TreeBudgetLimits {
+ /// Child Spaces at once (default 16).
+ #[uniffi(default = None)]
+ pub max_spaces: Option<u32>,
+ /// vCPUs at once (default 16).
+ #[uniffi(default = None)]
+ pub max_vcpus: Option<u32>,
+ /// Memory at once, MiB (default 32768).
+ #[uniffi(default = None)]
+ pub max_memory_mb: Option<u64>,
+ /// Cost per hour, in linked clouds (default 2.0).
+ #[uniffi(default = None)]
+ pub usd_per_hour: Option<f64>,
+ /// Cost in total (default: none).
+ #[uniffi(default = None)]
+ pub usd_total: Option<f64>,
+}
+
+/// A tree's budget and what its children use ([`Spaces::tree_budget`]).
+#[derive(Debug, Clone, PartialEq, uniffi::Record)]
+pub struct TreeBudget {
+ /// The tree's top-level Space.
+ pub root: String,
+ /// What the owner set.
+ pub set: TreeBudgetLimits,
+ /// Child Spaces it may hold at once.
+ pub max_spaces: u32,
+ /// vCPUs it may hold at once.
+ pub max_vcpus: u32,
+ /// Memory it may hold at once (MiB).
+ pub max_memory_mb: u64,
+ /// Cost per hour it may run at.
+ pub usd_per_hour: f64,
+ /// Cost in total it may reach, when capped.
+ pub usd_total: Option<f64>,
+ /// Child Spaces now.
+ pub spaces: u32,
+ /// vCPUs they hold.
+ pub vcpus: u32,
+ /// Memory they hold (MiB).
+ pub memory_mb: u64,
+ /// Cost per hour they run at.
+ pub usd_per_hour_used: f64,
+ /// What they have cost so far.
+ pub usd_spent: f64,
+}
+
+impl From<dpb::TreeBudget> for TreeBudget {
+ fn from(b: dpb::TreeBudget) -> Self {
+ let set = b.set.unwrap_or_default();
+ Self {
+ root: b.root,
+ set: TreeBudgetLimits {
+ max_spaces: set.max_spaces,
+ max_vcpus: set.max_vcpus,
+ max_memory_mb: set.max_memory_mb,
+ usd_per_hour: set.usd_per_hour,
+ usd_total: set.usd_total,
+ },
+ max_spaces: b.max_spaces,
+ max_vcpus: b.max_vcpus,
+ max_memory_mb: b.max_memory_mb,
+ usd_per_hour: b.usd_per_hour,
+ usd_total: b.usd_total,
+ spaces: b.spaces,
+ vcpus: b.vcpus,
+ memory_mb: b.memory_mb,
+ usd_per_hour_used: b.usd_per_hour_used,
+ usd_spent: b.usd_spent,
+ }
+ }
+}
+
+/// A child Space whose parent is gone or out of reach ([`Spaces::orphans`]).
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct SpaceOrphan {
+ /// The child.
+ pub space: String,
+ /// Its parent's id.
+ pub parent: String,
+ /// `ending` (its parent is provably gone: it ends after the grace) or
+ /// `listed` (not this computer's to judge: it stays until deleted or its
+ /// own lifetime ends).
+ pub state: String,
+ /// Why.
+ pub why: String,
+ /// Seconds until it ends (`ending` only).
+ pub ends_in_secs: i64,
+}
+
+/// A command a Space keeps running ([`Space::put_service`]).
+#[derive(Debug, Clone, Default, PartialEq, uniffi::Record, Serialize, Deserialize)]
+pub struct SpaceServiceDef {
+ /// Name: lowercase letters, digits, `-`, `_`, `.` (1 to 63).
+ pub name: String,
+ /// The shell command line it runs.
+ pub command: String,
+ /// Extra environment.
+ #[uniffi(default)]
+ #[serde(default)]
+ pub env: HashMap<String, String>,
+ /// Working directory.
+ #[uniffi(default = None)]
+ #[serde(default)]
+ pub cwd: Option<String>,
+ /// When it is started again: `always` (default), `on-failure` or
+ /// `never`.
+ #[uniffi(default = None)]
+ #[serde(default)]
+ pub restart: Option<String>,
+ /// A health check; failing it restarts the service.
+ #[uniffi(default = None)]
+ #[serde(default)]
+ pub probe: Option<SpaceServiceProbe>,
+ /// Start it when the Space boots. `None`: yes.
+ #[uniffi(default = None)]
+ #[serde(default)]
+ pub start_on_boot: Option<bool>,
+}
+
+/// A health check: exactly one of `http`, `tcp`, `command`.
+#[derive(Debug, Clone, Default, PartialEq, uniffi::Record, Serialize, Deserialize)]
+pub struct SpaceServiceProbe {
+ /// A URL that answers 2xx or 3xx.
+ #[uniffi(default = None)]
+ #[serde(default)]
+ pub http: Option<String>,
+ /// `host:port` that accepts a TCP connection.
+ #[uniffi(default = None)]
+ #[serde(default)]
+ pub tcp: Option<String>,
+ /// A shell command that exits 0 when healthy.
+ #[uniffi(default = None)]
+ #[serde(default)]
+ pub command: Option<String>,
+ /// Seconds between checks (default 10).
+ #[uniffi(default = None)]
+ #[serde(default)]
+ pub interval_secs: Option<u64>,
+ /// Failed checks in a row that restart it (default 3).
+ #[uniffi(default = None)]
+ #[serde(default)]
+ pub failures: Option<u32>,
+}
+
+/// A service and how it is doing ([`Space::services`]).
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record, Serialize, Deserialize)]
+pub struct SpaceServiceInfo {
+ /// Name.
+ pub name: String,
+ /// The command line.
+ pub command: String,
+ /// `starting`, `running`, `unhealthy`, `backoff`, `stopped`, `exited`
+ /// or `failed`.
+ pub state: String,
+ /// Its process, while it runs.
+ pub pid: u32,
+ /// Starts after the first.
+ pub restarts: u32,
+ /// How the last process ended, if one did.
+ pub last_end: String,
+ /// The last failed health check, if the last one failed.
+ pub probe_error: String,
+ /// `always`, `on-failure` or `never`.
+ pub restart: String,
+ /// Starts when the Space boots.
+ pub start_on_boot: bool,
+ /// Its log file in the Space.
+ pub log_path: String,
+}
+
+impl SpaceServiceDef {
+ fn core(self) -> Result<cua_spaces::keep::ServiceDef> {
+ let restart = match self.restart.as_deref() {
+ None => cua_spaces::keep::Restart::Always,
+ Some(r) => cua_spaces::keep::Restart::parse(r).ok_or_else(|| {
+ CuaError::InvalidArgument(format!("restart {r:?}: use always, on-failure or never"))
+ })?,
+ };
+ Ok(cua_spaces::keep::ServiceDef {
+ name: self.name,
+ command: self.command,
+ env: self.env.into_iter().collect(),
+ cwd: self.cwd,
+ restart,
+ probe: self.probe.map(|p| cua_spaces::keep::Probe {
+ http: p.http,
+ tcp: p.tcp,
+ command: p.command,
+ interval_secs: p.interval_secs,
+ failures: p.failures,
+ }),
+ start_on_boot: self.start_on_boot.unwrap_or(true),
+ })
+ }
+}
+
/// Result of [`Space::upload`] / [`Space::download`].
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record, Deserialize)]
pub struct SpaceTransferReport {
@@ -3487,10 +3902,41 @@ impl Spaces {
if let Some(on) = &on {
cua_sandbox_core::placement::validate(on, kind, &runtime).map_err(place)?;
}
+ // `network` takes a preset word too (`lan`, `localhost:5432`,
+ // `unprotected`): it becomes the settings when none are given.
+ let network_word = options
+ .network
+ .as_deref()
+ .map(str::trim)
+ .unwrap_or_default();
+ let legacy_word = matches!(
+ network_word.to_ascii_lowercase().as_str(),
+ "" | "default" | "none"
+ );
let network =
- cua_sandbox_core::NetworkMode::parse(options.network.as_deref().unwrap_or_default())
+ cua_sandbox_core::NetworkMode::parse(if legacy_word { network_word } else { "" })
.map_err(|e| CuaError::InvalidArgument(e.to_string()))?;
cua_spaces::registry::validate_labels(&options.labels).map_err(refused)?;
+ let network_settings = match &options.network_settings {
+ Some(n) => Some(n.checked()?),
+ None if !legacy_word => Some(
+ cua_spaces::network::parse_network(
+ network_word,
+ &options
+ .egress
+ .as_ref()
+ .map(|e| e.allow.clone())
+ .unwrap_or_default(),
+ &options
+ .egress
+ .as_ref()
+ .map(|e| e.deny.clone())
+ .unwrap_or_default(),
+ )
+ .map_err(|e| CuaError::InvalidArgument(e.to_string()))?,
+ ),
+ None => None,
+ };
if let Some(e) = &options.egress {
cua_spaces::egress::EgressPolicy::from(e.clone())
.parse()
@@ -3520,6 +3966,15 @@ impl Spaces {
run(async move {
match &host {
Host::Embedded(s) => {
+ if options.children == Some(true)
+ && !cua_spaces::experiments::enabled(
+ cua_spaces::experiments::Gate::ChildSpaces,
+ )
+ {
+ return Err(CuaError::Unsupported(
+ cua_spaces::experiments::Gate::ChildSpaces.off_message(),
+ ));
+ }
let created = s
.create(cua_spaces::SpaceCreate {
image: options.image,
@@ -3551,10 +4006,18 @@ impl Spaces {
network,
labels: options.labels.into_iter().collect(),
egress: options.egress.map(Into::into).unwrap_or_default(),
+ network_settings: network_settings.clone(),
+ parent: text(&options.parent),
+ widen: options.widen.unwrap_or(false),
instance_type: text(&options.instance_type),
region: text(&options.region),
})
.await?;
+ if options.children == Some(true)
+ && let cua_spaces::SpaceCreated::Ready { info, .. } = &created
+ {
+ s.set_children(&info.id, true)?;
+ }
Ok(match created {
cua_spaces::SpaceCreated::Ready { info, reused } => SpaceCreateResult {
space: Some(info.into()),
@@ -3601,8 +4064,12 @@ impl Spaces {
network: options.network.clone().unwrap_or_default(),
labels: options.labels,
egress: options.egress.map(Into::into),
+ network_settings: network_settings.as_ref().map(cua_spaces::network::to_pb),
+ parent: options.parent.clone().unwrap_or_default(),
+ widen: options.widen.unwrap_or(false),
instance_type: options.instance_type.clone().unwrap_or_default(),
region: options.region.clone().unwrap_or_default(),
+ children: options.children,
};
let r = match listener {
Some(l) => daemon_create_streaming(d, request, l).await?,
@@ -3613,7 +4080,16 @@ impl Spaces {
.map_err(daemon_err)?
.into_inner(),
};
- if let Err(what) = daemon_applied(network, asked_egress, &r) {
+ if let Err(what) = daemon_applied(network, asked_egress, &r).and_then(|()| {
+ // A daemon from before network settings never reads
+ // them: only its answer proves they hold.
+ match (&network_settings, r.space.as_ref()) {
+ (Some(_), Some(s)) if !r.reused && s.network_settings.is_none() => {
+ Err("network settings")
+ }
+ _ => Ok(()),
+ }
+ }) {
return Err(refuse_daemon_create(d, &r, what).await);
}
Ok(if r.phase == "starting" {
@@ -3636,6 +4112,18 @@ impl Spaces {
}
}
+/// A daemon that predates network settings: nothing was read or changed.
+fn too_old_for_network(e: tonic::Status) -> CuaError {
+ match e.code() {
+ tonic::Code::Unimplemented => CuaError::CapabilityMissing(
+ "network settings: the cua daemon is too old for them; update cua and restart its \
+ daemon"
+ .into(),
+ ),
+ _ => daemon_err(e),
+ }
+}
+
/// What a daemon's create left out of what was asked (`Err`): `network`
/// none it did not echo (`CreateSpaceResponse.network`), or an egress
/// policy the Space does not carry (`Space.egress`). A daemon that predates
@@ -3681,7 +4169,10 @@ async fn refuse_daemon_create(
}
let _ = d
.spaces()
- .delete_space(dpb::DeleteSpaceRequest { space: id.clone() })
+ .delete_space(dpb::DeleteSpaceRequest {
+ space: id.clone(),
+ keep_children: false,
+ })
.await;
format!(", so the Space it made ({id}) was deleted")
};
@@ -3936,6 +4427,104 @@ impl Spaces {
.await
}
+ /// A Space's network: its settings, what they open, where they are
+ /// enforced (or why its network is cut), and what is always blocked.
+ pub async fn network(&self, space: String) -> Result<SpaceNetworkInfo> {
+ let host = self.host.clone();
+ run(async move {
+ match &host {
+ Host::Embedded(s) => {
+ Ok(cua_spaces::network::info_to_pb(&s.network_info(&space).await?).into())
+ }
+ Host::Daemon(d) => Ok(d
+ .spaces()
+ .get_space_network(dpb::GetSpaceNetworkRequest {
+ space,
+ ack_notice: false,
+ })
+ .await
+ .map_err(too_old_for_network)?
+ .into_inner()
+ .network
+ .unwrap_or_default()
+ .into()),
+ }
+ })
+ .await
+ }
+
+ /// Marks the one-time notice about the new network defaults as shown
+ /// for `space` ([`SpaceNetworkInfo::notice_pending`]).
+ pub async fn ack_network_notice(&self, space: String) -> Result<()> {
+ let host = self.host.clone();
+ run(async move {
+ match &host {
+ Host::Embedded(s) => Ok(s.ack_network_notice(&space)?),
+ Host::Daemon(d) => {
+ d.spaces()
+ .get_space_network(dpb::GetSpaceNetworkRequest {
+ space,
+ ack_notice: true,
+ })
+ .await
+ .map_err(too_old_for_network)?;
+ Ok(())
+ }
+ }
+ })
+ .await
+ }
+
+ /// Replaces a Space's network settings (see [`NetworkSettings`]). A
+ /// child stays within its parent's unless `widen`; `tree` gives its
+ /// children the same settings. They hold at once where the runtime can
+ /// change a running guest's network, else from its next start
+ /// (`applied`). A Space another computer runs is `Unsupported`.
+ pub async fn set_network(
+ &self,
+ space: String,
+ settings: NetworkSettings,
+ widen: bool,
+ tree: bool,
+ ) -> Result<SetNetworkResult> {
+ let checked = settings.checked()?;
+ let host = self.host.clone();
+ run(async move {
+ match &host {
+ Host::Embedded(s) => {
+ let applied = s.set_network(&space, &checked, widen, tree).await?;
+ let info = s.network_info(&space).await?;
+ Ok(SetNetworkResult {
+ applied: match applied {
+ cua_spaces::network::Applied::Now => "now",
+ cua_spaces::network::Applied::NextStart => "next_start",
+ }
+ .into(),
+ network: cua_spaces::network::info_to_pb(&info).into(),
+ })
+ }
+ Host::Daemon(d) => {
+ let r = d
+ .spaces()
+ .set_space_network(dpb::SetSpaceNetworkRequest {
+ space,
+ settings: Some(cua_spaces::network::to_pb(&checked)),
+ widen,
+ tree,
+ })
+ .await
+ .map_err(too_old_for_network)?
+ .into_inner();
+ Ok(SetNetworkResult {
+ applied: r.applied,
+ network: r.network.unwrap_or_default().into(),
+ })
+ }
+ }
+ })
+ .await
+ }
+
/// Replaces a Space's egress policy; an empty one removes it (see
/// [`EgressPolicy`]). Its host enforces it at once. A bad entry is
/// `InvalidArgument`, a Space that cannot take one `Unsupported`.
@@ -3972,6 +4561,149 @@ impl Spaces {
.await
}
+ /// Lets a Space make child Spaces of its own, or stops it. While on,
+ /// `cua`, the SDKs and the agent's tools in that Space create, list and
+ /// delete Spaces that belong to it (on the same computer, never wider
+ /// than it, ending no later than it), through a channel only it can
+ /// reach. Off ends its capability at once; children it made keep running
+ /// until deleted or their lifetime ends. Only for a Space the machine of
+ /// this runtime runs itself.
+ pub async fn set_children(&self, space: String, enabled: bool) -> Result<()> {
+ let host = self.host.clone();
+ run(async move {
+ match &host {
+ Host::Embedded(s) => {
+ let id = s.resolve(&space)?.to_string();
+ if enabled
+ && !cua_spaces::experiments::enabled(
+ cua_spaces::experiments::Gate::ChildSpaces,
+ )
+ {
+ return Err(CuaError::Unsupported(
+ cua_spaces::experiments::Gate::ChildSpaces.off_message(),
+ ));
+ }
+ if enabled && !id.starts_with("local:") {
+ return Err(CuaError::Unsupported(
+ "child Spaces are available for Spaces this computer runs".into(),
+ ));
+ }
+ s.set_children(&id, enabled)?;
+ }
+ Host::Daemon(d) => {
+ d.spaces()
+ .set_space_children(dpb::SetSpaceChildrenRequest { space, enabled })
+ .await
+ .map_err(|e| match e.code() {
+ tonic::Code::Unimplemented => CuaError::CapabilityMissing(
+ "child Spaces: the cua daemon is too old; update cua and \
+ restart its daemon"
+ .into(),
+ ),
+ _ => daemon_err(e),
+ })?;
+ }
+ }
+ Ok(())
+ })
+ .await
+ }
+
+ /// The budget of `space`'s tree (any Space of it) and what its
+ /// children use now. Kept by the cua daemon.
+ pub async fn tree_budget(&self, space: String) -> Result<TreeBudget> {
+ let host = self.host.clone();
+ run(async move {
+ match &host {
+ Host::Embedded(_) => Err(CuaError::Unsupported(
+ "tree budgets are kept by the cua daemon; start it with `cua daemon start`"
+ .into(),
+ )),
+ Host::Daemon(d) => Ok(d
+ .spaces()
+ .get_tree_budget(dpb::GetTreeBudgetRequest { space })
+ .await
+ .map_err(daemon_err)?
+ .into_inner()
+ .budget
+ .unwrap_or_default()
+ .into()),
+ }
+ })
+ .await
+ }
+
+ /// Sets the budget of `space`'s tree: how many child Spaces, vCPUs and
+ /// memory its children may hold at once, and what they may cost. A child
+ /// that does not fit is refused with what is left. All `None` removes it.
+ pub async fn set_tree_budget(
+ &self,
+ space: String,
+ limits: TreeBudgetLimits,
+ ) -> Result<TreeBudget> {
+ let host = self.host.clone();
+ run(async move {
+ match &host {
+ Host::Embedded(_) => Err(CuaError::Unsupported(
+ "tree budgets are kept by the cua daemon; start it with `cua daemon start`"
+ .into(),
+ )),
+ Host::Daemon(d) => Ok(d
+ .spaces()
+ .set_tree_budget(dpb::SetTreeBudgetRequest {
+ space,
+ limits: Some(dpb::TreeBudgetLimits {
+ max_spaces: limits.max_spaces,
+ max_vcpus: limits.max_vcpus,
+ max_memory_mb: limits.max_memory_mb,
+ usd_per_hour: limits.usd_per_hour,
+ usd_total: limits.usd_total,
+ }),
+ })
+ .await
+ .map_err(daemon_err)?
+ .into_inner()
+ .budget
+ .unwrap_or_default()
+ .into()),
+ }
+ })
+ .await
+ }
+
+ /// Child Spaces whose parent is gone or out of reach. The cua daemon
+ /// ends a child only on proof its parent is gone (after a grace period);
+ /// the rest are listed here and never ended by it.
+ pub async fn orphans(&self) -> Result<Vec<SpaceOrphan>> {
+ let host = self.host.clone();
+ run(async move {
+ match &host {
+ Host::Embedded(_) => Err(CuaError::Unsupported(
+ "orphaned children are judged by the cua daemon; start it with `cua daemon \
+ start`"
+ .into(),
+ )),
+ Host::Daemon(d) => Ok(d
+ .spaces()
+ .list_orphans(dpb::ListOrphansRequest {})
+ .await
+ .map_err(daemon_err)?
+ .into_inner()
+ .orphans
+ .into_iter()
+ .map(|o| SpaceOrphan {
+ space: o.space,
+ parent: o.parent,
+ state: o.state,
+ why: o.why,
+ ends_in_secs: o.ends_in_secs,
+ })
+ .collect()),
+ }
+ })
+ .await
+ }
+
/// A machine's health as its own cua daemon checks it: Local Network
/// access (and which app macOS holds responsible), free disk,
/// virtualization, memory left by running Spaces, the permissions
@@ -3994,15 +4726,25 @@ impl Spaces {
}
/// Deletes a Space's sandbox and forgets it (a Space added by address
- /// is only forgotten). Returns what happened.
+ /// is only forgotten). Its child Spaces are deleted first. Returns what
+ /// happened.
pub async fn delete(&self, space: String) -> Result<String> {
+ self.delete_tree(space, false).await
+ }
+
+ /// [`Spaces::delete`], with `keep_children`: its child Spaces become
+ /// top-level Spaces and keep running instead of being deleted first.
+ pub async fn delete_tree(&self, space: String, keep_children: bool) -> Result<String> {
let host = self.host.clone();
run(async move {
match &host {
- Host::Embedded(s) => Ok(s.delete(&space).await?),
+ Host::Embedded(s) => Ok(s.delete_tree(&space, keep_children).await?),
Host::Daemon(d) => Ok(d
.spaces()
- .delete_space(dpb::DeleteSpaceRequest { space })
+ .delete_space(dpb::DeleteSpaceRequest {
+ space,
+ keep_children,
+ })
.await
.map_err(daemon_err)?
.into_inner()
@@ -4581,6 +5323,70 @@ impl Space {
run(async move { via_json(&s.write(&path, content).await?) }).await
}
+ // ---- keep running
+
+ /// Keeps a command running in this Space (replacing a service of that
+ /// name): restarted by its policy when it ends or fails its health
+ /// check, started when the Space boots, its output kept in a log file.
+ pub async fn put_service(&self, def: SpaceServiceDef) -> Result<SpaceServiceInfo> {
+ let s = self.inner.clone();
+ run(async move { via_json(&s.put_service(&def.core()?).await?) }).await
+ }
+
+ /// This Space's services.
+ pub async fn kept_services(&self) -> Result<Vec<SpaceServiceInfo>> {
+ let s = self.inner.clone();
+ run(async move { via_json(&s.kept_services().await?) }).await
+ }
+
+ /// Starts a stopped service.
+ pub async fn start_service(&self, name: String) -> Result<SpaceServiceInfo> {
+ let s = self.inner.clone();
+ run(async move {
+ via_json(
+ &s.control_service(&name, cua_spaces::keep::ServiceControl::Start)
+ .await?,
+ )
+ })
+ .await
+ }
+
+ /// Stops a service and keeps it stopped (also across a reboot).
+ pub async fn stop_service(&self, name: String) -> Result<SpaceServiceInfo> {
+ let s = self.inner.clone();
+ run(async move {
+ via_json(
+ &s.control_service(&name, cua_spaces::keep::ServiceControl::Stop)
+ .await?,
+ )
+ })
+ .await
+ }
+
+ /// Restarts a service.
+ pub async fn restart_service(&self, name: String) -> Result<SpaceServiceInfo> {
+ let s = self.inner.clone();
+ run(async move {
+ via_json(
+ &s.control_service(&name, cua_spaces::keep::ServiceControl::Restart)
+ .await?,
+ )
+ })
+ .await
+ }
+
+ /// Stops a service and forgets it (its logs go too).
+ pub async fn delete_service(&self, name: String) -> Result<()> {
+ let s = self.inner.clone();
+ run(async move { Ok(s.delete_service(&name).await?) }).await
+ }
+
+ /// The end of a service's log (`tail_bytes` `None`: 64 KiB).
+ pub async fn service_logs(&self, name: String, tail_bytes: Option<u64>) -> Result<String> {
+ let s = self.inner.clone();
+ run(async move { Ok(s.service_logs(&name, tail_bytes.unwrap_or(0)).await?) }).await
+ }
+
/// The Space user's home directory.
pub async fn home(&self) -> Result<String> {
let s = self.inner.clone();
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/experiments.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/experiments.json
index 6681fc7659..4a5ee59b97 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/experiments.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/experiments.json
@@ -95,7 +95,11 @@
"- experiment:your_cloud toggle: Your cloud {*On|Off}",
"- experiment:your_cloud-note note: Create Spaces in your own AWS, Google Cloud, Hetzner or Modal account.",
"- experiment:sharing toggle: Sharing {*On|Off}",
- "- experiment:sharing-note note: Share a Space with other Cua accounts."
+ "- experiment:sharing-note note: Share a Space with other Cua accounts.",
+ "- experiment:secure_spaces toggle: Secure Spaces {On|*Off}",
+ "- experiment:secure_spaces-note note: A Space reaches the internet and nothing else on your network unless you open it.",
+ "- experiment:child_spaces toggle: Child Spaces {On|*Off}",
+ "- experiment:child_spaces-note note: A Space can make Spaces of its own, inside a budget you set."
],
"volumePage": null,
"wizard": {
@@ -233,7 +237,11 @@
"- experiment:your_cloud toggle: Your cloud {*On|Off}",
"- experiment:your_cloud-note note: Create Spaces in your own AWS, Google Cloud, Hetzner or Modal account.",
"- experiment:sharing toggle: Sharing {*On|Off}",
- "- experiment:sharing-note note: Share a Space with other Cua accounts."
+ "- experiment:sharing-note note: Share a Space with other Cua accounts.",
+ "- experiment:secure_spaces toggle: Secure Spaces {On|*Off}",
+ "- experiment:secure_spaces-note note: A Space reaches the internet and nothing else on your network unless you open it.",
+ "- experiment:child_spaces toggle: Child Spaces {On|*Off}",
+ "- experiment:child_spaces-note note: A Space can make Spaces of its own, inside a budget you set."
],
"volumePage": "Volume",
"wizard": {
@@ -370,7 +378,11 @@
"- experiment:your_cloud toggle: Your cloud {On|*Off}",
"- experiment:your_cloud-note note: Create Spaces in your own AWS, Google Cloud, Hetzner or Modal account.",
"- experiment:sharing toggle: Sharing {*On|Off}",
- "- experiment:sharing-note note: Share a Space with other Cua accounts."
+ "- experiment:sharing-note note: Share a Space with other Cua accounts.",
+ "- experiment:secure_spaces toggle: Secure Spaces {On|*Off}",
+ "- experiment:secure_spaces-note note: A Space reaches the internet and nothing else on your network unless you open it.",
+ "- experiment:child_spaces toggle: Child Spaces {On|*Off}",
+ "- experiment:child_spaces-note note: A Space can make Spaces of its own, inside a budget you set."
],
"volumePage": "Volume",
"wizard": {
@@ -491,7 +503,11 @@
"- experiment:your_cloud toggle: Your cloud {On|*Off}",
"- experiment:your_cloud-note note: Create Spaces in your own AWS, Google Cloud, Hetzner or Modal account.",
"- experiment:sharing toggle: Sharing {*On|Off}",
- "- experiment:sharing-note note: Share a Space with other Cua accounts."
+ "- experiment:sharing-note note: Share a Space with other Cua accounts.",
+ "- experiment:secure_spaces toggle: Secure Spaces {On|*Off}",
+ "- experiment:secure_spaces-note note: A Space reaches the internet and nothing else on your network unless you open it.",
+ "- experiment:child_spaces toggle: Child Spaces {On|*Off}",
+ "- experiment:child_spaces-note note: A Space can make Spaces of its own, inside a budget you set."
],
"volumePage": "Volume",
"wizard": {
@@ -612,7 +628,11 @@
"- experiment:your_cloud toggle: Your cloud {On|*Off}",
"- experiment:your_cloud-note note: Create Spaces in your own AWS, Google Cloud, Hetzner or Modal account.",
"- experiment:sharing toggle: Sharing {*On|Off}",
- "- experiment:sharing-note note: Share a Space with other Cua accounts."
+ "- experiment:sharing-note note: Share a Space with other Cua accounts.",
+ "- experiment:secure_spaces toggle: Secure Spaces {On|*Off}",
+ "- experiment:secure_spaces-note note: A Space reaches the internet and nothing else on your network unless you open it.",
+ "- experiment:child_spaces toggle: Child Spaces {On|*Off}",
+ "- experiment:child_spaces-note note: A Space can make Spaces of its own, inside a budget you set."
],
"volumePage": "Volume",
"wizard": {
@@ -733,7 +753,11 @@
"- experiment:your_cloud toggle: Your cloud {On|*Off}",
"- experiment:your_cloud-note note: Create Spaces in your own AWS, Google Cloud, Hetzner or Modal account.",
"- experiment:sharing toggle: Sharing {*On|Off}",
- "- experiment:sharing-note note: Share a Space with other Cua accounts."
+ "- experiment:sharing-note note: Share a Space with other Cua accounts.",
+ "- experiment:secure_spaces toggle: Secure Spaces {On|*Off}",
+ "- experiment:secure_spaces-note note: A Space reaches the internet and nothing else on your network unless you open it.",
+ "- experiment:child_spaces toggle: Child Spaces {On|*Off}",
+ "- experiment:child_spaces-note note: A Space can make Spaces of its own, inside a budget you set."
],
"volumePage": "Volume",
"wizard": {
@@ -859,7 +883,11 @@
"- experiment:your_cloud toggle: Your cloud {On|*Off}",
"- experiment:your_cloud-note note: Create Spaces in your own AWS, Google Cloud, Hetzner or Modal account.",
"- experiment:sharing toggle: Sharing {*On|Off}",
- "- experiment:sharing-note note: Share a Space with other Cua accounts."
+ "- experiment:sharing-note note: Share a Space with other Cua accounts.",
+ "- experiment:secure_spaces toggle: Secure Spaces {On|*Off}",
+ "- experiment:secure_spaces-note note: A Space reaches the internet and nothing else on your network unless you open it.",
+ "- experiment:child_spaces toggle: Child Spaces {On|*Off}",
+ "- experiment:child_spaces-note note: A Space can make Spaces of its own, inside a budget you set."
],
"volumePage": null,
"wizard": {
@@ -986,7 +1014,11 @@
"- experiment:your_cloud toggle: Your cloud {*On|Off}",
"- experiment:your_cloud-note note: Create Spaces in your own AWS, Google Cloud, Hetzner or Modal account.",
"- experiment:sharing toggle: Sharing {*On|Off}",
- "- experiment:sharing-note note: Share a Space with other Cua accounts."
+ "- experiment:sharing-note note: Share a Space with other Cua accounts.",
+ "- experiment:secure_spaces toggle: Secure Spaces {On|*Off}",
+ "- experiment:secure_spaces-note note: A Space reaches the internet and nothing else on your network unless you open it.",
+ "- experiment:child_spaces toggle: Child Spaces {On|*Off}",
+ "- experiment:child_spaces-note note: A Space can make Spaces of its own, inside a budget you set."
],
"volumePage": null,
"wizard": {
@@ -1114,7 +1146,11 @@
"- experiment:your_cloud toggle: Your cloud {*On|Off}",
"- experiment:your_cloud-note note: Create Spaces in your own AWS, Google Cloud, Hetzner or Modal account.",
"- experiment:sharing toggle: Sharing {On|*Off}",
- "- experiment:sharing-note note: Share a Space with other Cua accounts."
+ "- experiment:sharing-note note: Share a Space with other Cua accounts.",
+ "- experiment:secure_spaces toggle: Secure Spaces {On|*Off}",
+ "- experiment:secure_spaces-note note: A Space reaches the internet and nothing else on your network unless you open it.",
+ "- experiment:child_spaces toggle: Child Spaces {On|*Off}",
+ "- experiment:child_spaces-note note: A Space can make Spaces of its own, inside a budget you set."
],
"volumePage": null,
"wizard": {
diff --git a/libs/cua/crates/cua-spaces-app-core/src/experiments.rs b/libs/cua/crates/cua-spaces-app-core/src/experiments.rs
index 54865beb86..4b71c18683 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/experiments.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/experiments.rs
@@ -14,6 +14,11 @@
//! - New UI ([`Experiment::WebUi`]): retired. The shared web UI is the only
//! UI of every shell, so it has no row; the key stays so the macOS shell
//! can report it ([`crate::settings::resolve_new_ui`]).
+//! - Secure Spaces ([`Experiment::SecureSpaces`]) and Child Spaces
+//! ([`Experiment::ChildSpaces`]): enforced, not only hidden. Their switches
+//! are also kept in the cua home, where the daemon and `cua experiments`
+//! read them; the shells load and save them through the app export
+//! (`app_settings_load` and `app_settings_save`).
//!
//! Off only hides the entry points. Nothing is undone: a mounted Volume
//! stays mounted (and keeps syncing), a connected cloud stays connected
@@ -44,6 +49,13 @@ pub struct Experiments {
/// The shared web UI is the main window. Always on in the macOS shell
/// ([`crate::settings::resolve_new_ui`]); kept for older files and builds.
pub web_ui: bool,
+ /// Secure Spaces: a Space reaches the internet and nothing else on the
+ /// network unless it is opened. Off unless turned on; the daemon enforces
+ /// it (the switch is kept in the cua home).
+ pub secure_spaces: bool,
+ /// Child Spaces: a Space may make Spaces of its own. Off unless turned
+ /// on; the daemon enforces it (the switch is kept in the cua home).
+ pub child_spaces: bool,
}
impl Default for Experiments {
@@ -53,6 +65,8 @@ impl Default for Experiments {
your_cloud: true,
sharing: true,
web_ui: false,
+ secure_spaces: false,
+ child_spaces: false,
}
}
}
@@ -69,14 +83,20 @@ pub enum Experiment {
Sharing,
/// New UI (preview).
WebUi,
+ /// Secure Spaces.
+ SecureSpaces,
+ /// Child Spaces.
+ ChildSpaces,
}
/// Every experiment, in the order Settings lists them.
-pub const ALL: [Experiment; 4] = [
+pub const ALL: [Experiment; 6] = [
Experiment::CuaVolume,
Experiment::YourCloud,
Experiment::Sharing,
Experiment::WebUi,
+ Experiment::SecureSpaces,
+ Experiment::ChildSpaces,
];
impl Experiment {
@@ -88,6 +108,8 @@ impl Experiment {
Experiment::YourCloud => "your_cloud",
Experiment::Sharing => "sharing",
Experiment::WebUi => "web_ui",
+ Experiment::SecureSpaces => "secure_spaces",
+ Experiment::ChildSpaces => "child_spaces",
}
}
@@ -103,6 +125,8 @@ impl Experiment {
Experiment::YourCloud => "Your cloud",
Experiment::Sharing => "Sharing",
Experiment::WebUi => "New UI",
+ Experiment::SecureSpaces => "Secure Spaces",
+ Experiment::ChildSpaces => "Child Spaces",
}
}
@@ -115,6 +139,12 @@ impl Experiment {
}
Experiment::Sharing => "Share a Space with other Cua accounts.",
Experiment::WebUi => "The Spaces window built on the shared web UI.",
+ Experiment::SecureSpaces => {
+ "A Space reaches the internet and nothing else on your network unless you open it."
+ }
+ Experiment::ChildSpaces => {
+ "A Space can make Spaces of its own, inside a budget you set."
+ }
}
}
}
@@ -127,6 +157,8 @@ impl Experiments {
Experiment::YourCloud => self.your_cloud,
Experiment::Sharing => self.sharing,
Experiment::WebUi => self.web_ui,
+ Experiment::SecureSpaces => self.secure_spaces,
+ Experiment::ChildSpaces => self.child_spaces,
}
}
@@ -137,6 +169,8 @@ impl Experiments {
Experiment::YourCloud => self.your_cloud = on,
Experiment::Sharing => self.sharing = on,
Experiment::WebUi => self.web_ui = on,
+ Experiment::SecureSpaces => self.secure_spaces = on,
+ Experiment::ChildSpaces => self.child_spaces = on,
}
self
}
@@ -246,6 +280,10 @@ mod tests {
"experiment:your_cloud-note",
"experiment:sharing",
"experiment:sharing-note",
+ "experiment:secure_spaces",
+ "experiment:secure_spaces-note",
+ "experiment:child_spaces",
+ "experiment:child_spaces-note",
]
);
for r in switches(&p) {
@@ -283,7 +321,14 @@ mod tests {
assert_eq!(choose(&x, "experiment:nope", "on"), x);
assert_eq!(
Experiments::all_on().on_ids(),
- ["cua_volume", "your_cloud", "sharing", "web_ui"]
+ [
+ "cua_volume",
+ "your_cloud",
+ "sharing",
+ "web_ui",
+ "secure_spaces",
+ "child_spaces"
+ ]
);
}
@@ -318,7 +363,7 @@ mod tests {
let back = serde_json::to_value(x).unwrap();
assert_eq!(
back,
- serde_json::json!({"cuaVolume": true, "yourCloud": true, "sharing": true, "webUi": false})
+ serde_json::json!({"cuaVolume": true, "yourCloud": true, "sharing": true, "webUi": false, "secureSpaces": false, "childSpaces": false})
);
// An explicit off is kept.
let off: Experiments = serde_json::from_str(r#"{"yourCloud":false}"#).unwrap();
diff --git a/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs b/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs
index 352f1518f5..90cc1a358f 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs
@@ -2116,7 +2116,9 @@ mod tests {
"cua_volume".into(),
"your_cloud".into(),
"sharing".into(),
- "web_ui".into()
+ "web_ui".into(),
+ "secure_spaces".into(),
+ "child_spaces".into()
]
}]
);
diff --git a/libs/cua/crates/cua-spaces-contract/src/inputs.rs b/libs/cua/crates/cua-spaces-contract/src/inputs.rs
index 9fc7f4fa8a..613b5ecfc9 100644
--- a/libs/cua/crates/cua-spaces-contract/src/inputs.rs
+++ b/libs/cua/crates/cua-spaces-contract/src/inputs.rs
@@ -213,11 +213,49 @@ pub struct CreateSpace {
/// values up to 256. Not with `durable` or `reuse`.
#[serde(default)]
pub labels: Option<std::collections::BTreeMap<String, String>>,
+ /// Its network: `internet` (default: the internet and its own tree;
+ /// this computer, the local network, cloud metadata and other trees are
+ /// blocked), `none`, or `custom` / `custom:none` with `allow` and
+ /// `deny`. Presets that open more (`localhost:<ports>`, `lan`,
+ /// `unprotected`) are the user's to choose: refused here.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub network: Option<String>,
+ /// Destinations to allow (addresses or CIDRs) on top of `network`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub allow: Option<Vec<String>>,
+ /// Destinations to block (addresses, CIDRs or `all`).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub deny: Option<Vec<String>>,
+ /// Create it as a child of this Space (id or name): it joins the
+ /// parent's tree, and its network is no more open than the parent's.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub parent: Option<String>,
/// Command, environment and services (see [`SpaceWorkload`]).
#[serde(flatten)]
pub workload: SpaceWorkload,
}
+/// `network_set`: change a Space's network.
+#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct NetworkSet {
+ /// Space id or name.
+ pub space: SpaceArg,
+ /// `internet`, `none`, or `custom` / `custom:none` with `allow` and
+ /// `deny`. Opening more than the Space has now is the user's to do
+ /// (`cua network set`, or the app): refused here.
+ pub network: String,
+ /// Destinations to allow (addresses or CIDRs).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub allow: Option<Vec<String>>,
+ /// Destinations to block (addresses, CIDRs or `all`).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub deny: Option<Vec<String>>,
+ /// Its child Spaces take the same settings (each within its parent's).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tree: Option<bool>,
+}
+
/// A tool whose only argument is the Space.
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct SpaceOnly {
@@ -266,6 +304,90 @@ pub struct SpaceBash {
pub timeout: Option<u64>,
}
+/// `space_job`: run a long command in the Space as a background job.
+#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
+pub struct SpaceJob {
+ /// Space id or name.
+ pub space: SpaceArg,
+ /// `start` (begin a job), `status` (state and the end of its log),
+ /// `logs` (read the log from a byte offset), `cancel` (stop it) or
+ /// `list` (this Space's jobs, newest first).
+ pub action: String,
+ /// `start`: the command line, run with `/bin/sh -c` in the background. It
+ /// keeps running when you or your connection go away. Give this or
+ /// `until`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub command: Option<String>,
+ /// `status`, `logs`, `cancel`: the job id `start` returned.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub job: Option<String>,
+ /// `start`: a short label for the job ("unit tests"), shown in listings
+ /// and in the message that wakes you.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ /// `start`: the directory to run in. Default: the Space user's home.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cwd: Option<String>,
+ /// `start`: environment variables for the command.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub env: Option<BTreeMap<String, String>>,
+ /// `start`: seconds before the job is stopped. Default: none.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub timeout: Option<u64>,
+ /// `start`: wait for a condition instead of running `command`. The job
+ /// ends when the condition holds (exit 0), or after `timeout`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub until: Option<JobUntil>,
+ /// `start`: wake me when the job ends. The Space's thread gets one
+ /// message with the job's result and the end of its log, addressed to
+ /// you when you are an agent member of the Space (so you can finish your
+ /// turn and sleep), and the person gets a notification. Default false.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub notify: Option<bool>,
+ /// `start` with `notify`: the agent member to wake instead of you.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub wake: Option<String>,
+ /// `logs`: the byte offset to read from (the `next_offset` of the
+ /// previous call). Without it: the last `limit` bytes.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub offset: Option<u64>,
+ /// `logs`: most bytes to return (default 16000, at most 262144).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub limit: Option<u64>,
+ /// `logs`: when there is nothing new after `offset` and the job is
+ /// running, wait up to this many milliseconds (at most 25000) for output
+ /// or for the job to end. Default 0.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub follow_ms: Option<u64>,
+}
+
+/// A condition a `space_job` waits for. Give exactly one of `file`, `port`,
+/// `command` or `pr_checks`.
+#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
+pub struct JobUntil {
+ /// Wait for this path to exist in the Space.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub file: Option<String>,
+ /// Wait for this TCP port to accept connections (on `host`, default
+ /// 127.0.0.1).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub port: Option<u16>,
+ /// With `port`: the host. Default 127.0.0.1.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub host: Option<String>,
+ /// Wait for this shell command to exit 0.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub command: Option<String>,
+ /// Wait for a GitHub pull request's required checks to finish with `gh`
+ /// (signed in inside the Space): a number, a URL or `owner/repo#123`.
+ /// The job exits 0 when they pass and 1 when one fails.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pr_checks: Option<String>,
+ /// Seconds between checks (1 to 300). Default 5 (30 for `pr_checks`).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub interval: Option<u64>,
+}
+
/// `space_write`: write literal text to a file in the Space.
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct SpaceWrite {
@@ -277,6 +399,42 @@ pub struct SpaceWrite {
pub content: String,
}
+/// `space_service`: keep a command running in a Space.
+#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
+pub struct SpaceService {
+ /// Space id or name.
+ pub space: SpaceArg,
+ /// `add` (or replace), `list`, `start`, `stop`, `restart`, `remove` or
+ /// `logs`.
+ pub action: String,
+ /// Service name (every action but `list`): lowercase letters, digits,
+ /// `-`, `_` and `.`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ /// `add`: the shell command line to keep running.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub command: Option<String>,
+ /// `add`: when to start it again: `always` (default), `on-failure` or
+ /// `never`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub restart: Option<String>,
+ /// `add`: health check, a URL that answers 2xx or 3xx.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub http: Option<String>,
+ /// `add`: health check, `host:port` that accepts a connection.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tcp: Option<String>,
+ /// `add`: health check, a shell command that exits 0 when healthy.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub check: Option<String>,
+ /// `add`: start it when the Space boots (default true).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub start_on_boot: Option<bool>,
+ /// `logs`: bytes from the end (default 64 KiB).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tail_bytes: Option<u64>,
+}
+
/// `upload`: copy a host file or folder into the Space.
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct Upload {
diff --git a/libs/cua/crates/cua-spaces-contract/src/lib.rs b/libs/cua/crates/cua-spaces-contract/src/lib.rs
index ae5fd1d148..5387c20f1a 100644
--- a/libs/cua/crates/cua-spaces-contract/src/lib.rs
+++ b/libs/cua/crates/cua-spaces-contract/src/lib.rs
@@ -679,6 +679,8 @@ impl Spec {
}
}
+const SPACE_JOB_INSTRUCTIONS: &str = "Use this instead of space_bash for anything that takes more than a minute (builds, test suites, installs, waiting on CI). `start` returns a job id at once and the command keeps running when you stop, disconnect, or the Space's daemon restarts. Read it with `logs` (pass the returned `next_offset` as `offset` to read on; `follow_ms` waits for output) or `status`; stop it with `cancel`; `list` shows the Space's jobs. Pass `notify: true` to be woken: the Space's thread gets one message `JOB <id> <state> exit=<n> ...` with the end of the log, and as an agent member you receive it as your next turn, so you can end your turn instead of polling. `until` makes a job that waits for a file, a port, a command or a pull request's required checks; its end is the condition. Output is stdout and stderr together. Linux and macOS guests.";
+
const SEND_FILE_INSTRUCTIONS: &str = "The same transfer the Cua Spaces pop-out's Teleport drop zone performs: files land in the Space user's ~/Downloads through the spacesd's TeleportService (chunked, resumable, every file verified by sha256 before it is published). A transfer that does not land, or lands corrupted, is an error and not a reported success.\n\nrespect_ignorefiles (default true) applies ONLY when `path` is a folder. It honors `.gitignore` and `.ignore` at the folder root and in every subdirectory (each scoped to its own subtree, so a nested ignore file overrides its parent), plus `.dockerignore` at the root only. All three use gitignore semantics: negation (`!`), directory-only patterns (`foo/`), anchoring, `*`/`?`/`[...]`, `**`, comments, last-matching-rule-wins. As in git, an excluded directory is pruned and `!` cannot re-include anything beneath it. `.git/` is always skipped and symlinks are never followed. For a single named file it has NO effect.";
const LIST_TOOLS_INSTRUCTIONS: &str = "Lists the tools of an MCP service INSIDE the Space. `service` is any service the Space declares (an MCP server the image runs, reached over streamable HTTP; no spacesd needed) or `driver`, the spacesd's own cua-driver registry (screenshot, click, type, launch apps, accessibility, ...). The default is `driver`, or the only declared service of a Space without spacesd. With no `name`, returns a scannable overview; pass name=<substring> for full input schemas. Then invoke them with call_tool. The reply names every service the Space exposes.";
@@ -696,6 +698,29 @@ macro_rules! join_next_steps {
};
}
+/// How an agent does work that takes a long time, in plain words. One text
+/// for the agent bridge, the join line and the bundled skill, so every way an
+/// agent learns about `space_job` teaches the same steps.
+macro_rules! long_work_steps {
+ () => {
+ "Long work (a build, a test suite, a wait on CI): never sit inside one call. Start it with space_job (action start, notify true, a name of a few words), post one line in the thread saying what you started, then end your turn. When it ends the thread gets `JOB <id> <state> exit=<n> ...` with the end of the log, and you receive it as your next task; read more with space_job logs (offset: the next_offset you were given). If you cannot be woken, poll with space_job logs and follow_ms instead of sleeping in space_bash."
+ };
+}
+
+/// [`long_work_steps!`] as a constant.
+pub const LONG_WORK_STEPS: &str = long_work_steps!();
+
+/// How agents that share work coordinate through a Space's thread, in plain
+/// words (the same text as [`LONG_WORK_STEPS`]: bridge, join line, skill).
+macro_rules! coordination_steps {
+ () => {
+ "Working with other agents (a parent Space and its child Spaces, or any agents in one Space): 1. Before you start, thread_read and note what others have claimed. 2. Post `CLAIM <what> | files: <paths or branch> | until: <when>` for what you will change. Do not edit files or branches another agent's live CLAIM covers: @mention the owner and wait for the reply. 3. A claim is live until its `until` passes or its owner posts DONE or RELEASE; once it has expired you may take it, and you say so in the thread. 4. Report with one structured line: `DONE <what> | <result> | next: <step>` or `BLOCKED <what> | needs: <thing> | from @who`. 5. Keep messages short, one @mention per request, and never your own name."
+ };
+}
+
+/// [`coordination_steps!`] as a constant.
+pub const COORDINATION_STEPS: &str = coordination_steps!();
+
/// [`join_next_steps!`] as a constant.
pub const JOIN_NEXT_STEPS: &str = join_next_steps!();
@@ -795,6 +820,30 @@ pub fn tools() -> Vec<Tool> {
)
}
.with::<i::CreateSpace>(),
+ Spec {
+ category: Category::Lifecycle,
+ result: "JSON: `settings` (preset, lists), `summary`, `widenings` (what it opens beyond internet), `enforcement` (`enforced`, `no_network`, `open`, `refused`), `point`, `note`, `parent`, `root`, `always_blocked`, `notice_pending`.",
+ errors: &["invalid_argument", "not_found"],
+ instructions: "Shows a Space's network: its preset (`internet` by default: the internet and its own tree, with this computer, the local network, cloud metadata and other trees blocked), what it opens beyond that, where the rules are enforced (outside the guest), or why it has no network (a runtime that can't protect it yet starts it without network), and what is always blocked. When a connection fails, check here before retrying: a blocked destination stays blocked.",
+ capabilities: &["space.network.read"],
+ annotations: Annotations::reading(),
+ sdk_symbol: "Spaces.network(space)",
+ rust_symbol: "Spaces::network_info",
+ ..Spec::new("network_show", "Show a Space's network: preset, what it opens, where it is enforced, what is always blocked.")
+ }
+ .with::<i::SpaceOnly>(),
+ Spec {
+ category: Category::Lifecycle,
+ result: "JSON: `applied` (`now` or `next_start`) and `network` (as network_show).",
+ errors: &["invalid_argument", "wrong_provider", "not_found", "sandbox"],
+ instructions: "Changes a Space's network to `internet`, `none`, or `custom` (from internet) / `custom:none` with `allow` and `deny` (addresses or CIDRs). It can only tighten: anything that opens more than the Space has now (this computer's localhost, the local network, No protection, an allow beyond its preset) is refused; the user does that with `cua network set` or the app. A child stays within its parent's. tree=true gives its children the same settings. Applies at once where the runtime can, else at the Space's next start (`applied`).",
+ capabilities: &["space.network.write"],
+ annotations: Annotations::mutating_idempotent(),
+ sdk_symbol: "Spaces.set_network(space, settings, widen, tree)",
+ rust_symbol: "Spaces::set_network",
+ ..Spec::new("network_set", "Tighten a Space's network: internet, none or custom lists. Opening more is the user's to do.")
+ }
+ .with::<i::NetworkSet>(),
Spec {
category: Category::Lifecycle,
result: "Text: what was deleted (`Deleted <id> (...)`), or `Removed <id> (...)` for a Space added by address.",
@@ -857,6 +906,19 @@ pub fn tools() -> Vec<Tool> {
..Spec::new("space_bash", "Run a shell command inside the Space.")
}
.with::<i::SpaceBash>(),
+ Spec {
+ category: Category::CommandsAndFiles,
+ result: "JSON. `start`: `job`, `state`, `log_command` and a `hint`. `status`, `logs`: `job`, `name`, `state` (`running`, `exited`, `cancelled`, `timed_out` or `lost`), `exit_code`, `signal`, `started_at` and `ended_at` (unix seconds), `elapsed_s`, `size` (log bytes), and for `logs` `offset`, `next_offset`, `text` and `more`. `cancel`: the final status. `list`: `jobs`.",
+ errors: &["not_found", "wrong_provider"],
+ instructions: SPACE_JOB_INSTRUCTIONS,
+ capabilities: &["space.exec", "space.exec.shell", "space.exec.jobs"],
+ annotations: Annotations::mutating(),
+ sdk_symbol: "Space.job(_:)",
+ rust_symbol: "Space::job",
+ notes: &["A job is a command that outlives the call, the connection and a restart of the Space's daemon; its state is files in the Space (`~/.cua/jobs/<id>`). Guests that are not Windows."],
+ ..Spec::new("space_job", "Run a long command in the Space as a background job: tail its log, cancel it, or get woken when it ends.")
+ }
+ .with::<i::SpaceJob>(),
Spec {
category: Category::CommandsAndFiles,
result: "Text: `wrote <path> (<n> bytes, sha256 <hex> verified in Space)`.",
@@ -1021,6 +1083,18 @@ pub fn tools() -> Vec<Tool> {
..Spec::new("call_tool", "Call a service tool inside the Space.")
}
.with::<i::CallTool>(),
+ Spec {
+ category: Category::Services,
+ result: "JSON: `add`, `start`, `stop` and `restart` give the service (`name`, `command`, `state`, `pid`, `restarts`, `last_end`, `probe_error`, `restart`, `start_on_boot`, `log_path`); `list` gives `services`; `logs` gives `logs` (text); `remove` gives `removed`.",
+ errors: &["capability_missing", "invalid_argument", "not_found"],
+ instructions: "Keeps a command running in the Space: cua-spacesd starts it at once, starts it again by its `restart` policy when it ends (waiting longer after each quick failure, up to a minute), restarts it when its health check (`http`, `tcp` or `check`, one of them) fails 3 times in a row, starts it when the Space boots unless start_on_boot is false, and keeps its output in a log file in the Space (`logs`). `stop` keeps it stopped, across a reboot too, until `start`. `add` with a name that exists replaces it.",
+ capabilities: &["space.services.keep"],
+ annotations: Annotations::mutating(),
+ sdk_symbol: "space.keepRunning.service(_:)",
+ rust_symbol: "Space::keep_service",
+ ..Spec::new("space_service", "Keep a command running in the Space: restarts, health checks, start on boot, logs.")
+ }
+ .with::<i::SpaceService>(),
// --- Agents ------------------------------------------------------------
Spec {
category: Category::Agents,
@@ -2264,7 +2338,55 @@ mod tests {
#[test]
fn advertises_every_tool() {
- assert_eq!(tools().len(), 114);
+ assert_eq!(tools().len(), 118);
+ }
+
+ #[test]
+ fn the_agent_texts_teach_the_structure_not_a_task() {
+ for word in [
+ "CLAIM",
+ "files:",
+ "until",
+ "DONE",
+ "BLOCKED",
+ "RELEASE",
+ "thread_read",
+ ] {
+ assert!(COORDINATION_STEPS.contains(word), "coordination: {word}");
+ }
+ for word in [
+ "space_job",
+ "notify true",
+ "JOB <id>",
+ "next_offset",
+ "end your turn",
+ ] {
+ assert!(LONG_WORK_STEPS.contains(word), "long work: {word}");
+ }
+ // The bundled skill carries the same words as the bridge and the join result.
+ let skill = include_str!("../../../skills/cua-spaces/SKILL.md");
+ assert!(
+ skill.contains(COORDINATION_STEPS),
+ "SKILL.md drifted from COORDINATION_STEPS"
+ );
+ assert!(
+ skill.contains(LONG_WORK_STEPS),
+ "SKILL.md drifted from LONG_WORK_STEPS"
+ );
+ // Examples are examples: no text names a tool chain or a project.
+ for text in [COORDINATION_STEPS, LONG_WORK_STEPS] {
+ for fixed in [
+ "cargo",
+ "npm",
+ "pytest",
+ "make ",
+ "gradle",
+ "pnpm",
+ "xcodebuild",
+ ] {
+ assert!(!text.contains(fixed), "{fixed} is a task, not the protocol");
+ }
+ }
}
#[test]
diff --git a/libs/cua/crates/cua-spaces-ext/src/lib.rs b/libs/cua/crates/cua-spaces-ext/src/lib.rs
index 954c5682fb..eace1a1ab0 100644
--- a/libs/cua/crates/cua-spaces-ext/src/lib.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/lib.rs
@@ -199,6 +199,7 @@ impl SpacesExtension for DriveExtension {
|| named_volumes::OPS.contains(&tool)
|| tool == "agent_start.home"
|| tool == cua_spaces::agents::WATCH_OP
+ || tool == cua_spaces::space_jobs::WATCH_OP
|| tool == cua_spaces::extension::MEMBER_AUTH_OP
}
@@ -251,6 +252,21 @@ impl SpacesExtension for DriveExtension {
)?;
return Ok(ToolOutcome::json(&json!({"watched": true})));
}
+ if tool == cua_spaces::space_jobs::WATCH_OP {
+ let field = |k: &str| {
+ args.get(k)
+ .and_then(Value::as_str)
+ .ok_or_else(|| Error::invalid(format!("{tool}: `{k}` is required")))
+ };
+ let out = spaces.persistent().watch_job(
+ &caller,
+ field("space")?,
+ field("job")?,
+ args.get("name").and_then(Value::as_str).unwrap_or_default(),
+ args.get("wake").and_then(Value::as_str),
+ )?;
+ return Ok(ToolOutcome::json(&out));
+ }
if named_volumes::OPS.contains(&tool) {
return named_volumes::call(spaces, tool, args).await;
}
diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/bridge.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/bridge.rs
index c5f958d7c9..043161dff4 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/bridge.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/bridge.rs
@@ -40,7 +40,21 @@ use cua_spaces::{Error, Result, Spaces};
const MAX_LINE: usize = 16 * 1024 * 1024;
/// Server instructions the agent sees.
-pub const INSTRUCTIONS: &str = "Cua: tools for a persistent agent. Your Space has a thread where people and other agents talk: thread_read reads it, thread_post posts (an @name of another agent gives it a task), thread_inbox lists the tasks addressed to you, thread_claim takes one and thread_reply answers it and marks it done. notify_user tells your user something in the Cua app (use it for results they asked for, or when you need them). The Cua Volume keeps files beyond this Space: your home is agents/<you>/ (your memory lives there too), public/ is shared reference (read only), spaces/<this space>/ is this Space's folder; anything else needs volume_request_access, which the user approves. computer_list shows the user's own computers you were allowed to use; computer_list_tools and computer_call use them. Never put secrets in the drive: the user's Keyvault holds them.";
+const BASE_INSTRUCTIONS: &str = "Cua: tools for a persistent agent. Your Space has a thread where people and other agents talk: thread_read reads it, thread_post posts (an @name of another agent gives it a task), thread_inbox lists the tasks addressed to you, thread_claim takes one and thread_reply answers it and marks it done. notify_user tells your user something in the Cua app (use it for results they asked for, or when you need them). The Cua Volume keeps files beyond this Space: your home is agents/<you>/ (your memory lives there too), public/ is shared reference (read only), spaces/<this space>/ is this Space's folder; anything else needs volume_request_access, which the user approves. computer_list shows the user's own computers you were allowed to use; computer_list_tools and computer_call use them. Never put secrets in the drive: the user's Keyvault holds them.";
+
+/// What the agent's MCP server tells it at `initialize`: its tools, then how
+/// to do long work and how to share a Space with other agents (the texts the
+/// join result and the bundled skill carry too).
+pub fn instructions() -> &'static str {
+ static TEXT: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
+ format!(
+ "{BASE_INSTRUCTIONS} {} {}",
+ cua_spaces_contract::LONG_WORK_STEPS,
+ cua_spaces_contract::COORDINATION_STEPS
+ )
+ });
+ TEXT.as_str()
+}
/// Per-run pipe state kept by the supervisor.
#[derive(Default)]
@@ -61,7 +75,7 @@ pub fn server(
McpServer::new(spaces.clone())
.with_filter(Arc::new(|_| false))
.with_name("cua-agent")
- .with_instructions(INSTRUCTIONS)
+ .with_instructions(instructions())
.with_extension(Arc::new(AgentTools {
persistent,
agent: rec.name.clone(),
@@ -220,6 +234,25 @@ fn tool(name: &str, description: &str, input: Value, read_only: bool) -> Value {
"idempotentHint": read_only, "openWorldHint": true}})
}
+/// `space_job` as this agent sees it: the contract's tool for its own Space
+/// (no `space` argument).
+fn space_job_tool() -> Value {
+ let contract = cua_spaces_contract::tool("space_job").expect("space_job is a contract tool");
+ let mut input = contract.input_schema.clone();
+ if let Some(p) = input.get_mut("properties").and_then(Value::as_object_mut) {
+ p.remove("space");
+ }
+ if let Some(r) = input.get_mut("required").and_then(Value::as_array_mut) {
+ r.retain(|x| x != "space");
+ }
+ tool(
+ "space_job",
+ &format!("{} {}", contract.description, contract.instructions),
+ input,
+ false,
+ )
+}
+
fn str_arg<'a>(a: &'a Value, k: &str) -> Result<&'a str> {
a.get(k)
.and_then(Value::as_str)
@@ -380,10 +413,40 @@ impl AgentTools {
"thread_read" | "thread_post" | "thread_inbox" | "thread_claim" | "thread_reply" => {
self.thread_tool(tool, a).await
}
+ "space_job" => self.space_job(a).await,
other => Err(Error::NotFound(format!("tool {other}"))),
}
}
+ /// `space_job` in this agent's own Space (whatever `space` says). With
+ /// `notify` the job's end is a task for this agent in the Space's thread.
+ async fn space_job(&self, mut a: Value) -> Result<ToolOutcome> {
+ if let Some(o) = a.as_object_mut() {
+ o.insert("space".into(), json!(self.space));
+ }
+ let args: cua_spaces_contract::inputs::SpaceJob = serde_json::from_value(a)
+ .map_err(|e| Error::invalid(format!("space_job: {e} (see the tool's inputSchema)")))?;
+ let space = self.persistent.spaces.space(&self.space).await?;
+ let mut out = space.job(&args).await?;
+ if args.action == "start" && args.notify.unwrap_or(false) {
+ let caller = Caller::Agent {
+ name: self.agent.clone(),
+ space: self.space.clone(),
+ };
+ out["notify"] = match self.persistent.watch_job(
+ &caller,
+ &self.space,
+ out["job"].as_str().unwrap_or_default(),
+ out["name"].as_str().unwrap_or_default(),
+ args.wake.as_deref(),
+ ) {
+ Ok(_) => json!({"registered": true}),
+ Err(e) => json!({"registered": false, "reason": e.to_string()}),
+ };
+ }
+ Ok(ToolOutcome::json(&out))
+ }
+
/// The thread tools, as this agent in its own Space (the author and
/// the Space are fixed here, whatever the arguments say).
async fn thread_tool(&self, tool: &str, a: Value) -> Result<ToolOutcome> {
@@ -487,6 +550,7 @@ const NAMES: &[&str] = &[
"thread_inbox",
"thread_claim",
"thread_reply",
+ "space_job",
];
#[async_trait::async_trait]
@@ -601,6 +665,7 @@ impl ToolExtension for AgentTools {
),
false,
),
+ space_job_tool(),
tool(
"thread_inbox",
"The open tasks addressed to you, oldest first.",
diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/jobs.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/jobs.rs
new file mode 100644
index 0000000000..4a4505cbc4
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/jobs.rs
@@ -0,0 +1,332 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Waking an agent when a `space_job` ends.
+//!
+//! `space_job start` with `notify` registers the job here
+//! (`watched-jobs.json`, the same shape as the watched runs). The supervisor
+//! ([`Persistent::tick`], run by `cua daemon`) asks each Space for its job's
+//! state. When a job has ended it:
+//!
+//! - gives the agent that started it (or the one named in `wake`) a task in
+//! the Space's thread, from the daemon, with the job's one-line result and
+//! the end of its log. The dispatcher delivers it as the agent's next
+//! turn, so the agent can end its turn and sleep while the job runs; and
+//! - tells the person (the notifications feed) when there is no agent to
+//! wake.
+//!
+//! The file survives a daemon restart, and a Space that is off or does not
+//! answer is asked again on the next pass, so a job is followed to its end
+//! for as long as [`WATCH_JOBS_FOR`].
+
+use std::path::PathBuf;
+use std::time::Duration;
+
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use super::{AGENT_TICK_BUDGET, Persistent, TickReport, locked_json, read_json};
+use crate::thread::policy::Right;
+use crate::thread::{Author, Draft, EntryKind, TaskTo};
+use cua_spaces::extension::Caller;
+use cua_spaces::space_jobs::{self, JobStatus};
+use cua_spaces::{Error, Result};
+
+/// How long a job is followed at most.
+pub const WATCH_JOBS_FOR: Duration = Duration::from_secs(7 * 24 * 3600);
+/// Jobs followed at most.
+const MAX_WATCHED_JOBS: usize = 200;
+/// Bytes of a job's log in the message that wakes the agent.
+pub const TAIL_BYTES: u64 = 2000;
+
+/// A job whose end is waited for.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct WatchedJob {
+ /// The Space id.
+ pub space: String,
+ /// The job id.
+ pub job: String,
+ /// Its label.
+ #[serde(default)]
+ pub name: String,
+ /// The agent member to give a task when it ends (none: tell the person).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub agent: Option<String>,
+ /// Unix ms the watch began.
+ pub added_ms: u64,
+ /// Consecutive passes that could not reach the Space.
+ #[serde(default)]
+ pub misses: u32,
+}
+
+impl Persistent {
+ fn watched_jobs_path(&self) -> PathBuf {
+ self.dir.join("watched-jobs.json")
+ }
+
+ /// The jobs being followed.
+ pub fn watched_jobs(&self) -> Result<Vec<WatchedJob>> {
+ read_json(&self.watched_jobs_path())
+ }
+
+ /// Follows `job` of `space` until it ends. The agent to wake is `wake`
+ /// (an agent member `caller` may task) or, without it, `caller` when it
+ /// is an agent member of that Space.
+ pub fn watch_job(
+ &self,
+ caller: &Caller,
+ space: &str,
+ job: &str,
+ name: &str,
+ wake: Option<&str>,
+ ) -> Result<Value> {
+ let agent = match wake.filter(|w| !w.is_empty()) {
+ Some(w) => {
+ let rec = self.get(w)?;
+ if rec.space != space {
+ return Err(Error::invalid(format!("{w} is not a member of this Space")));
+ }
+ if !self.allows(caller, &rec, Right::Task) {
+ return Err(Error::invalid(format!("you can't give {w} tasks")));
+ }
+ Some(w.to_string())
+ }
+ None => caller
+ .agent_member()
+ .filter(|(_, s)| *s == space)
+ .map(|(n, _)| n.to_string()),
+ };
+ let w = WatchedJob {
+ space: space.into(),
+ job: job.into(),
+ name: name.into(),
+ agent: agent.clone(),
+ added_ms: cua_volume::now_ms(),
+ misses: 0,
+ };
+ locked_json(&self.watched_jobs_path(), |all: &mut Vec<WatchedJob>| {
+ if !all.iter().any(|x| x.job == w.job && x.space == w.space) {
+ all.push(w);
+ }
+ let extra = all.len().saturating_sub(MAX_WATCHED_JOBS);
+ all.drain(..extra);
+ })?;
+ Ok(json!({"watching": true, "wake": agent}))
+ }
+
+ /// One pass over the watched jobs.
+ pub(super) async fn tick_watched_jobs(&self, report: &mut TickReport) {
+ let jobs = match self.watched_jobs() {
+ Ok(j) => j,
+ Err(e) => {
+ report.errors.push(format!("watched jobs: {e}"));
+ return;
+ }
+ };
+ if jobs.is_empty() {
+ return;
+ }
+ let off = self.spaces_off();
+ let mut next: Vec<(WatchedJob, Option<WatchedJob>)> = vec![];
+ for w in jobs {
+ let expired =
+ cua_volume::now_ms().saturating_sub(w.added_ms) > WATCH_JOBS_FOR.as_millis() as u64;
+ if expired {
+ next.push((w, None));
+ continue;
+ }
+ // A Space someone stopped is not woken to ask; its job is
+ // asked about when it runs again.
+ if off.contains(&w.space) {
+ next.push((w.clone(), Some(w)));
+ continue;
+ }
+ let after =
+ match tokio::time::timeout(AGENT_TICK_BUDGET, self.tick_watched_job(&w, report))
+ .await
+ {
+ Ok(Ok(done)) => (!done).then(|| WatchedJob {
+ misses: 0,
+ ..w.clone()
+ }),
+ Ok(Err(e)) => {
+ if matches!(e, Error::NotFound(_)) {
+ // The job's record is gone (pruned, or the Space
+ // was recreated): say so once and stop.
+ self.post_job_lost(&w, report);
+ None
+ } else {
+ self.forget_space(&w.space).await;
+ report.errors.push(format!("{}: {e}", w.job));
+ Some(WatchedJob {
+ misses: w.misses + 1,
+ ..w.clone()
+ })
+ }
+ }
+ Err(_) => {
+ report
+ .errors
+ .push(format!("{}: job check timed out", w.job));
+ Some(w.clone())
+ }
+ };
+ next.push((w, after));
+ }
+ let saved = locked_json(&self.watched_jobs_path(), |all: &mut Vec<WatchedJob>| {
+ all.retain_mut(|x| {
+ match next
+ .iter()
+ .find(|(w, _)| w.job == x.job && w.space == x.space)
+ {
+ Some((_, Some(w))) => {
+ *x = w.clone();
+ true
+ }
+ Some((_, None)) => false,
+ None => true,
+ }
+ });
+ });
+ if let Err(e) = saved {
+ report.errors.push(format!("watched jobs: {e}"));
+ }
+ }
+
+ /// Asks about one job; `true` once it ended and was reported.
+ async fn tick_watched_job(&self, w: &WatchedJob, report: &mut TickReport) -> Result<bool> {
+ let space = self.spaces.space(&w.space).await?;
+ let status = space.job_status(&w.job).await?;
+ if !status.finished() {
+ return Ok(false);
+ }
+ let tail = space
+ .job_logs(&w.job, None, TAIL_BYTES, Duration::ZERO)
+ .await
+ .ok();
+ self.post_job_end(
+ w,
+ &status,
+ tail.as_ref().map(|l| (l.text.as_str(), l.next_offset)),
+ )?;
+ report.notified += 1;
+ Ok(true)
+ }
+
+ /// The message that wakes the agent, or tells the person.
+ pub fn post_job_end(
+ &self,
+ w: &WatchedJob,
+ status: &JobStatus,
+ tail: Option<(&str, u64)>,
+ ) -> Result<()> {
+ let text = end_message(status, tail);
+ let store = self.thread_store(&w.space);
+ let woke = match &w.agent {
+ Some(agent) if self.get(agent).is_ok() => {
+ let mut d = Draft::new(Author::system("jobs"), EntryKind::Message, text.clone());
+ d.mentions = vec![agent.clone()];
+ d.task = Some(TaskTo {
+ to: agent.clone(),
+ session: None,
+ });
+ store.append(d)?;
+ true
+ }
+ _ => {
+ store.append(Draft::note("jobs", None, text.clone()))?;
+ false
+ }
+ };
+ if !woke {
+ let failed = status.state != "exited" || status.exit_code != Some(0);
+ let label = if status.name.is_empty() {
+ status.command.as_str()
+ } else {
+ status.name.as_str()
+ };
+ let title = format!(
+ "{} {}",
+ label.lines().next().unwrap_or("A job"),
+ if failed { "failed" } else { "finished" }
+ );
+ self.feed().post(
+ w.agent.as_deref(),
+ if failed { "error" } else { "message" },
+ &title,
+ &space_jobs::result_line(status),
+ None,
+ Some(&w.space),
+ )?;
+ }
+ Ok(())
+ }
+
+ fn post_job_lost(&self, w: &WatchedJob, report: &mut TickReport) {
+ let status = JobStatus {
+ job: w.job.clone(),
+ name: w.name.clone(),
+ state: "lost".into(),
+ exit_code: None,
+ signal: None,
+ started_at: None,
+ ended_at: None,
+ elapsed_s: 0,
+ size: 0,
+ command: String::new(),
+ };
+ match self.post_job_end(w, &status, None) {
+ Ok(()) => report.notified += 1,
+ Err(e) => report.errors.push(format!("{}: {e}", w.job)),
+ }
+ }
+}
+
+/// The text of the message: the structured result line, the end of the log,
+/// and what to do next.
+pub fn end_message(status: &JobStatus, tail: Option<(&str, u64)>) -> String {
+ let mut text = space_jobs::result_line(status);
+ if let Some((log, next)) = tail {
+ let log = log.trim_end();
+ if !log.is_empty() {
+ text += &format!("\n\nEnd of the log:\n{log}");
+ }
+ text += &format!(
+ "\n\nRead more with space_job {{action: \"logs\", job: \"{}\", offset: <byte>}} (the log is {next} bytes).",
+ status.job
+ );
+ } else {
+ text += "\n\nThe Space no longer has this job's record (it was removed, or the Space was recreated), so its result is unknown: run it again if you still need it.";
+ }
+ text
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn status(state: &str, code: Option<i32>) -> JobStatus {
+ JobStatus {
+ job: "j1".into(),
+ name: "unit tests".into(),
+ state: state.into(),
+ exit_code: code,
+ signal: None,
+ started_at: Some(1),
+ ended_at: Some(61),
+ elapsed_s: 60,
+ size: 11,
+ command: "cargo test".into(),
+ }
+ }
+
+ #[test]
+ fn the_message_starts_with_the_structured_line() {
+ let m = end_message(&status("exited", Some(0)), Some(("ok\n", 11)));
+ assert!(m.starts_with("JOB j1 exited exit=0 1m00s log=11B | unit tests\n"));
+ assert!(m.contains("End of the log:\nok"));
+ assert!(m.contains("offset: <byte>"));
+ let lost = end_message(&status("lost", None), None);
+ assert!(lost.contains("result is unknown"));
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/join.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/join.rs
index 591ee23d56..92b5e5b0bb 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/join.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/join.rs
@@ -678,7 +678,7 @@ impl Persistent {
// as the agent, not as the person who signed in).
"member_credential": {"member_id": member_id, "key": key},
"next_steps": format!(
- "You joined {} as @{}.{} {}",
+ "You joined {} as @{}.{} {} {} {}",
self.space_name(&code.space),
rec.name,
if ask {
@@ -686,7 +686,9 @@ impl Persistent {
} else {
""
},
- cua_spaces_contract::JOIN_NEXT_STEPS
+ cua_spaces_contract::JOIN_NEXT_STEPS,
+ cua_spaces_contract::LONG_WORK_STEPS,
+ cua_spaces_contract::COORDINATION_STEPS
),
}))
}
diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs
index ddda796da9..084c15ec56 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs
@@ -31,6 +31,7 @@ pub mod bridge;
pub mod durable;
pub mod home;
pub mod identity;
+pub mod jobs;
pub mod join;
pub mod members;
pub mod notify;
@@ -1764,6 +1765,7 @@ impl Persistent {
// ended above closed theirs).
self.dispatch(&mut report).await;
self.tick_watched(&mut report).await;
+ self.tick_watched_jobs(&mut report).await;
self.tick_mirror(&mut report).await;
report
}
diff --git a/libs/cua/crates/cua-spaces-ext/tests/e2e_space_job_wake.rs b/libs/cua/crates/cua-spaces-ext/tests/e2e_space_job_wake.rs
new file mode 100644
index 0000000000..60497a6235
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-ext/tests/e2e_space_job_wake.rs
@@ -0,0 +1,171 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! A finished `space_job` wakes the agent that started it, against a real
+//! Linux Space (`CUA_E2E_SPACE_JOBS=1`): cua-spacesd runs in an alpine
+//! container under a restart loop, the job starts with `notify` as an agent
+//! member, and the supervisor runs until the agent has the job's result as a
+//! task in the Space's thread.
+//!
+//! | env | meaning |
+//! |---|---|
+//! | `CUA_SPACESD_STATIC` | the static Linux cua-spacesd to run |
+//! | `DOCKER_HOST` | the engine (the `docker` command must be on `PATH`) |
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use cua_spaces::Spaces;
+use cua_spaces::extension::Caller;
+use cua_spaces::mcp::McpServer;
+use cua_spaces_ext::SpacesPersistent as _;
+use serde_json::{Value, json};
+
+fn docker(args: &[&str]) -> String {
+ let out = std::process::Command::new("docker")
+ .args(args)
+ .output()
+ .expect("the docker command");
+ assert!(
+ out.status.success(),
+ "docker {args:?}: {}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ String::from_utf8_lossy(&out.stdout).trim().to_string()
+}
+
+/// Removes the container however the test ends.
+struct Container(String);
+impl Drop for Container {
+ fn drop(&mut self) {
+ let _ = std::process::Command::new("docker")
+ .args(["rm", "-f", &self.0])
+ .output();
+ }
+}
+
+fn uniq() -> String {
+ format!(
+ "{:x}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_millis()
+ % 0xffffff
+ )
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_finished_job_wakes_the_agent() {
+ if std::env::var("CUA_E2E_SPACE_JOBS").as_deref() != Ok("1") {
+ eprintln!("skipping: set CUA_E2E_SPACE_JOBS=1 to run");
+ return;
+ }
+ let bin = std::path::PathBuf::from(
+ std::env::var("CUA_SPACESD_STATIC").expect("set CUA_SPACESD_STATIC"),
+ );
+ let name = format!("cua-e2e-jobs-wake-{}", uniq());
+ let _guard = Container(name.clone());
+ let token = format!("tok-{}", uniq());
+ docker(&[
+ "run",
+ "-d",
+ "--name",
+ &name,
+ "-p",
+ "127.0.0.1::3211",
+ "-e",
+ &format!("CUA_ENV_TOKEN={token}"),
+ "-v",
+ &format!("{}:/cua-spacesd:ro", bin.display()),
+ "alpine:3.20",
+ "sh",
+ "-c",
+ "while true; do /cua-spacesd; sleep 1; done",
+ ]);
+ let addr = docker(&["port", &name, "3211"]);
+ let addr = addr.lines().next().unwrap().to_string();
+
+ let home = tempfile::tempdir().unwrap();
+ let spaces = cua_spaces_ext::register(
+ Spaces::builder()
+ .home(home.path())
+ .download_dir(home.path().join("downloads"))
+ .operator_display(Arc::new(cua_spaces::operator::NoDisplay)),
+ cua_volume::Drive::open_local(home.path()),
+ None,
+ )
+ .build();
+ let info = spaces
+ .add(&format!("http://{addr}"), Some(token), Some("wake".into()))
+ .await
+ .expect("add the Space");
+ let up = Instant::now() + Duration::from_secs(60);
+ loop {
+ if let Ok(s) = spaces.space(&info.id).await
+ && s.bash("true", Duration::from_secs(10))
+ .await
+ .is_ok_and(|o| o.success())
+ {
+ break;
+ }
+ assert!(Instant::now() < up, "the Space did not answer");
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ }
+ let mcp = McpServer::new(spaces.clone());
+ let call = |caller: Caller, tool: &'static str, args: Value| {
+ let mcp = mcp.clone();
+ async move {
+ let out = caller.scope(Box::pin(mcp.call(tool, args))).await;
+ cua_spaces::extension::outcome_json(out).unwrap_or_else(|e| panic!("{tool}: {e}"))
+ }
+ };
+ call(
+ Caller::Owner,
+ "agent_add",
+ json!({"space": info.id, "name": "ada", "harness": "claude-code",
+ "env_from_host": ["ANTHROPIC_API_KEY"]}),
+ )
+ .await;
+
+ let started = call(
+ Caller::Agent {
+ name: "ada".into(),
+ space: info.id.clone(),
+ },
+ "space_job",
+ json!({"space": info.id, "action": "start", "name": "wake me",
+ "command": "sleep 8; echo hello from the job", "notify": true}),
+ )
+ .await;
+ assert_eq!(started["state"], "running", "{started}");
+ assert_eq!(started["notify"]["registered"], true, "{started}");
+
+ // The supervisor follows the job; the agent has the result as a task.
+ let p = spaces.persistent();
+ let until = Instant::now() + Duration::from_secs(90);
+ let task = loop {
+ p.tick().await;
+ let inbox = call(
+ Caller::Owner,
+ "thread_inbox",
+ json!({"space": info.id, "member": "ada"}),
+ )
+ .await;
+ if let Some(t) = inbox["tasks"].as_array().and_then(|t| t.first()) {
+ break t.clone();
+ }
+ assert!(Instant::now() < until, "ada was never woken");
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ };
+ let text = task["text"].as_str().unwrap();
+ eprintln!("{text}");
+ assert!(text.starts_with("JOB j"), "{text}");
+ assert!(text.contains(" exited exit=0 "), "{text}");
+ assert!(text.contains("| wake me"), "{text}");
+ assert!(text.contains("hello from the job"), "{text}");
+ assert!(
+ p.watched_jobs().unwrap().is_empty(),
+ "the job is no longer followed"
+ );
+}
diff --git a/libs/cua/crates/cua-spaces-ext/tests/space_job_notify.rs b/libs/cua/crates/cua-spaces-ext/tests/space_job_notify.rs
new file mode 100644
index 0000000000..77114fe111
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-ext/tests/space_job_notify.rs
@@ -0,0 +1,213 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The end of a `space_job` wakes the agent that started it: a task from the
+//! daemon in the Space's thread, addressed to the agent, with the structured
+//! result line; a person who started it gets a notification instead. Against
+//! the in-process spacesd mock and a temporary cua home. The job's own
+//! behavior (detached runner, logs, cancel) is tested where its scripts are,
+//! in `cua_spaces::space_jobs`, and on real Spaces by the e2e suite.
+
+use cua_spaces::Spaces;
+use cua_spaces::extension::Caller;
+use cua_spaces::mcp::McpServer;
+use cua_spaces::space_jobs::JobStatus;
+use cua_spaces_ext::SpacesPersistent as _;
+use cua_spaces_ext::persistent::jobs::WatchedJob;
+use cua_spacesd_client::testing::{MockAuth, MockServer};
+use serde_json::{Value, json};
+
+struct Fx {
+ _srv: MockServer,
+ _home: tempfile::TempDir,
+ spaces: Spaces,
+ space: String,
+ mcp: McpServer,
+}
+
+async fn setup() -> Fx {
+ let srv = MockServer::start(MockAuth::default()).await;
+ let home = tempfile::tempdir().unwrap();
+ let spaces = cua_spaces_ext::register(
+ Spaces::builder().home(home.path()),
+ cua_volume::Drive::open_local(home.path()),
+ None,
+ )
+ .build();
+ let info = spaces
+ .add(&format!("http://{}", srv.addr), None, Some("room".into()))
+ .await
+ .unwrap();
+ let mcp = McpServer::new(spaces.clone());
+ let fx = Fx {
+ _srv: srv,
+ _home: home,
+ spaces,
+ space: info.id,
+ mcp,
+ };
+ for name in ["ada", "bo"] {
+ call(
+ &fx,
+ &Caller::Owner,
+ "agent_add",
+ json!({"space": fx.space, "name": name, "harness": "claude-code",
+ "env_from_host": ["ANTHROPIC_API_KEY"]}),
+ )
+ .await
+ .unwrap();
+ }
+ fx
+}
+
+async fn call(fx: &Fx, caller: &Caller, tool: &str, args: Value) -> Result<Value, String> {
+ let out = caller
+ .clone()
+ .scope(Box::pin(fx.mcp.call(tool, args)))
+ .await;
+ cua_spaces::extension::outcome_json(out).map_err(|e| e.to_string())
+}
+
+fn ended(job: &str, state: &str, code: Option<i32>) -> JobStatus {
+ JobStatus {
+ job: job.into(),
+ name: "unit tests".into(),
+ state: state.into(),
+ exit_code: code,
+ signal: None,
+ started_at: Some(100),
+ ended_at: Some(875),
+ elapsed_s: 775,
+ size: 2048,
+ command: "run the tests".into(),
+ }
+}
+
+fn agent(name: &str, fx: &Fx) -> Caller {
+ Caller::Agent {
+ name: name.into(),
+ space: fx.space.clone(),
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn an_agent_that_started_a_job_gets_its_end_as_a_task() {
+ let fx = setup().await;
+ let p = fx.spaces.persistent();
+ let w = p
+ .watch_job(&agent("ada", &fx), &fx.space, "j1", "unit tests", None)
+ .unwrap();
+ assert_eq!(w["wake"], "ada");
+ // Watching twice follows the job once.
+ p.watch_job(&agent("ada", &fx), &fx.space, "j1", "unit tests", None)
+ .unwrap();
+ let watched: Vec<WatchedJob> = p.watched_jobs().unwrap();
+ assert_eq!(watched.len(), 1);
+ assert_eq!(watched[0].agent.as_deref(), Some("ada"));
+
+ p.post_job_end(
+ &watched[0],
+ &ended("j1", "exited", Some(0)),
+ Some(("all 412 passed\n", 2048)),
+ )
+ .unwrap();
+
+ let inbox = call(
+ &fx,
+ &Caller::Owner,
+ "thread_inbox",
+ json!({"space": fx.space, "member": "ada"}),
+ )
+ .await
+ .unwrap();
+ let tasks = inbox["tasks"].as_array().unwrap();
+ assert_eq!(tasks.len(), 1, "{inbox}");
+ let text = tasks[0]["text"].as_str().unwrap();
+ assert!(
+ text.starts_with("JOB j1 exited exit=0 12m55s log=2048B | unit tests"),
+ "{text}"
+ );
+ assert!(text.contains("all 412 passed"), "{text}");
+ assert_eq!(tasks[0]["to"], "ada");
+ // The other agent was not woken, and no person was notified: the agent
+ // decides whether the person needs to know.
+ let other = call(
+ &fx,
+ &Caller::Owner,
+ "thread_inbox",
+ json!({"space": fx.space, "member": "bo"}),
+ )
+ .await
+ .unwrap();
+ assert!(other["tasks"].as_array().unwrap().is_empty());
+ assert!(p.feed().list(false, None).unwrap().is_empty());
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_job_a_person_started_notifies_the_person() {
+ let fx = setup().await;
+ let p = fx.spaces.persistent();
+ let w = p
+ .watch_job(&Caller::Owner, &fx.space, "j2", "build", None)
+ .unwrap();
+ assert!(w["wake"].is_null());
+ let watched = p.watched_jobs().unwrap();
+ p.post_job_end(
+ &watched[0],
+ &ended("j2", "exited", Some(2)),
+ Some(("boom\n", 5)),
+ )
+ .unwrap();
+ let notes = p.feed().list(false, None).unwrap();
+ assert_eq!(notes.len(), 1);
+ assert_eq!(notes[0].kind, "error");
+ assert!(notes[0].title.ends_with("failed"), "{}", notes[0].title);
+ assert!(notes[0].body.starts_with("JOB j2 exited exit=2"));
+ // The thread has the note too, and nobody was given a task.
+ let thread = call(
+ &fx,
+ &Caller::Owner,
+ "thread_read",
+ json!({"space": fx.space}),
+ )
+ .await
+ .unwrap();
+ let last = thread["entries"]
+ .as_array()
+ .unwrap()
+ .last()
+ .unwrap()
+ .clone();
+ assert!(last["text"].as_str().unwrap().starts_with("JOB j2"));
+ assert!(last["task"].is_null());
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn waking_another_agent_is_checked_and_a_job_that_vanished_is_said() {
+ let fx = setup().await;
+ let p = fx.spaces.persistent();
+ // `wake` names an agent member of this Space.
+ let e = p
+ .watch_job(&Caller::Owner, &fx.space, "j3", "x", Some("nobody"))
+ .unwrap_err();
+ assert_eq!(e.tag(), "not_found", "{e}");
+ let w = p
+ .watch_job(&agent("ada", &fx), &fx.space, "j3", "x", Some("bo"))
+ .unwrap();
+ assert_eq!(w["wake"], "bo");
+ // A job whose record is gone ends as `lost`, in words.
+ let watched = p.watched_jobs().unwrap();
+ p.post_job_end(&watched[0], &ended("j3", "lost", None), None)
+ .unwrap();
+ let inbox = call(
+ &fx,
+ &Caller::Owner,
+ "thread_inbox",
+ json!({"space": fx.space, "member": "bo"}),
+ )
+ .await
+ .unwrap();
+ let text = inbox["tasks"][0]["text"].as_str().unwrap().to_string();
+ assert!(text.starts_with("JOB j3 lost"), "{text}");
+ assert!(text.contains("result is unknown"), "{text}");
+}
diff --git a/libs/cua/crates/cua-spaces-ext/tests/thread_join.rs b/libs/cua/crates/cua-spaces-ext/tests/thread_join.rs
index 683c55f66a..1ada8866fc 100644
--- a/libs/cua/crates/cua-spaces-ext/tests/thread_join.rs
+++ b/libs/cua/crates/cua-spaces-ext/tests/thread_join.rs
@@ -520,6 +520,10 @@ async fn redeeming_teaches_the_next_steps_and_posts_are_the_agents() {
"thread_post",
"never @mention yourself",
"scheduled poll",
+ // How to wait on long work and share a Space with other agents.
+ "space_job",
+ "CLAIM <what>",
+ "BLOCKED <what>",
] {
assert!(steps.contains(must), "{must}: {steps}");
}
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
index a684c62678..1fb194daad 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
@@ -2169,17 +2169,97 @@ pub fn app_resources_warning(warning: cua_sdk::DiskWarning) -> Option<AppWarning
core::resources::warning_view(&core_of(&warning))
}
-/// Reads the settings file (defaults when missing or damaged).
+/// Reads the settings file (defaults when missing or damaged). The
+/// experiments the daemon enforces (Secure Spaces, Child Spaces) are what
+/// the cua home keeps, so `cua experiments enable` shows in the app.
#[uniffi::export]
pub fn app_settings_load(path: String) -> AppSettings {
- core::settings::load(std::path::Path::new(&path))
+ let mut settings = core::settings::load(std::path::Path::new(&path));
+ settings.experiments = sync_experiments_from_home(settings.experiments, &cua_home::cua_home());
+ settings
}
-/// Writes the settings file.
+/// The experiments the daemon enforces ([`cua_spaces::experiments::Gate`])
+/// of `experiments`, with the switches `home` keeps laid over them: what
+/// `cua experiments enable` set wins over what the app's file remembers.
+fn sync_experiments_from_home(
+ mut experiments: AppExperiments,
+ home: &std::path::Path,
+) -> AppExperiments {
+ use cua_spaces::experiments::{Gate, switch};
+ if let Some(on) = switch(home, Gate::SecureSpaces) {
+ experiments.secure_spaces = on;
+ }
+ if let Some(on) = switch(home, Gate::ChildSpaces) {
+ experiments.child_spaces = on;
+ }
+ experiments
+}
+
+/// Keeps the daemon's experiments of `experiments` in `home` (only a change
+/// is written).
+fn sync_experiments_to_home(
+ experiments: &AppExperiments,
+ home: &std::path::Path,
+) -> std::io::Result<()> {
+ use cua_spaces::experiments::{Gate, set_switch};
+ set_switch(home, Gate::SecureSpaces, experiments.secure_spaces)?;
+ set_switch(home, Gate::ChildSpaces, experiments.child_spaces)
+}
+
+/// Writes the settings file, and keeps the experiments the daemon enforces
+/// where it reads them (the cua home).
#[uniffi::export]
pub fn app_settings_save(path: String, settings: AppSettings) -> Result<()> {
core::settings::save(std::path::Path::new(&path), &settings)
- .map_err(|e| CuaError::Internal(e.to_string()))
+ .map_err(|e| CuaError::Internal(e.to_string()))?;
+ sync_experiments_to_home(&settings.experiments, &cua_home::cua_home())
+ .map_err(|e| CuaError::Internal(format!("keep the experiment switches: {e}")))
+}
+
+#[cfg(test)]
+mod experiment_sync_tests {
+ use super::*;
+
+ #[test]
+ fn the_daemon_switches_follow_the_cua_home_both_ways() {
+ let home = tempfile::tempdir().unwrap();
+ // Nothing kept: the app's own file decides.
+ let mine = AppExperiments {
+ child_spaces: true,
+ ..Default::default()
+ };
+ assert_eq!(sync_experiments_from_home(mine, home.path()), mine);
+ // What `cua experiments enable` set wins.
+ cua_spaces::experiments::set_switch(
+ home.path(),
+ cua_spaces::experiments::Gate::SecureSpaces,
+ true,
+ )
+ .unwrap();
+ let seen = sync_experiments_from_home(mine, home.path());
+ assert!(seen.secure_spaces && seen.child_spaces);
+ // The app's switches land in the home for the daemon.
+ sync_experiments_to_home(&seen, home.path()).unwrap();
+ assert_eq!(
+ cua_spaces::experiments::switch(
+ home.path(),
+ cua_spaces::experiments::Gate::ChildSpaces
+ ),
+ Some(true)
+ );
+ // Only the daemon's two experiments are kept there.
+ let kept: Vec<_> = std::fs::read_dir(home.path().join("experiments"))
+ .unwrap()
+ .flatten()
+ .map(|e| e.file_name().to_string_lossy().into_owned())
+ .collect();
+ assert!(
+ kept.iter()
+ .all(|n| n == "secure-spaces" || n == "child-spaces"),
+ "{kept:?}"
+ );
+ }
}
/// The settings with the New UI as a launch of `version` shows it: the
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
index 83974ea33e..22b0a123fe 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
@@ -6968,6 +6968,13 @@ pub struct AppExperiments {
/// The shared web UI is the main window. Always on in the macOS shell
/// ([`crate::settings::resolve_new_ui`]); kept for older files and builds.
pub web_ui: bool,
+ /// Secure Spaces: a Space reaches the internet and nothing else on the
+ /// network unless it is opened. Off unless turned on; the daemon enforces
+ /// it (the switch is kept in the cua home).
+ pub secure_spaces: bool,
+ /// Child Spaces: a Space may make Spaces of its own. Off unless turned
+ /// on; the daemon enforces it (the switch is kept in the cua home).
+ pub child_spaces: bool,
}
/// A runtime the host found for one kind (the SDK's `RuntimeDetected`).
diff --git a/libs/cua/crates/cua-spaces/Cargo.toml b/libs/cua/crates/cua-spaces/Cargo.toml
index 4c541c0a9c..394aec5c60 100644
--- a/libs/cua/crates/cua-spaces/Cargo.toml
+++ b/libs/cua/crates/cua-spaces/Cargo.toml
@@ -15,6 +15,7 @@ default = [
"spaces-presence",
"spaces-hotspot",
"spaces-volume",
+ "spaces-spawn",
"spaces-agents",
"mcp",
"mcp-http",
@@ -32,6 +33,8 @@ spaces-presence = []
spaces-hotspot = ["dep:cua-hotspot", "dep:tokio-tungstenite"]
# Cua Volume mounted in a Space's guest, served from this host.
spaces-volume = ["dep:cua-hotspot", "dep:tokio-tungstenite"]
+# The host's end of a Space's spawn channel (child Spaces made from inside).
+spaces-spawn = ["dep:cua-hotspot", "dep:tokio-tungstenite"]
# Agent CLIs in a Space as detached, tagged spacesd processes.
spaces-agents = ["dep:cua-agents", "dep:cua-auth", "dep:reqwest"]
# The Spaces MCP server (stdio). Hosted by `cua daemon mcp`.
diff --git a/libs/cua/crates/cua-spaces/src/children.rs b/libs/cua/crates/cua-spaces/src/children.rs
new file mode 100644
index 0000000000..e7a4e274aa
--- /dev/null
+++ b/libs/cua/crates/cua-spaces/src/children.rs
@@ -0,0 +1,114 @@
+//! Which Spaces may make child Spaces of their own.
+//!
+//! The setting is the owner's (`SetSpaceChildren`, `cua spaces children`,
+//! `create --children`), and an agent run turns it on for its Space. The
+//! cua daemon of the machine that runs the Space keeps the Space's spawn
+//! channel while it is on. Kept in `<home>/spawn/enabled.json` with each
+//! Space's creation time, so a Space deleted and made again under the same
+//! name starts with it off.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+
+use crate::Spaces;
+
+/// The file, in the Spaces home.
+pub const ENABLED_FILE: &str = "spawn/enabled.json";
+
+static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+/// Woken when a Space's setting changes (the daemon's channel loop waits on
+/// it).
+pub static CHANGED: tokio::sync::Notify = tokio::sync::Notify::const_new();
+
+#[derive(Serialize, Deserialize, Default)]
+struct File {
+ #[serde(default)]
+ spaces: BTreeMap<String, u64>,
+}
+
+fn path(home: &Path) -> PathBuf {
+ home.join(ENABLED_FILE)
+}
+
+fn load(home: &Path) -> BTreeMap<String, u64> {
+ std::fs::read(path(home))
+ .ok()
+ .and_then(|b| serde_json::from_slice::<File>(&b).ok())
+ .unwrap_or_default()
+ .spaces
+}
+
+fn save(home: &Path, spaces: &BTreeMap<String, u64>) -> std::io::Result<()> {
+ let p = path(home);
+ if let Some(dir) = p.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
+ let tmp = p.with_extension(format!("tmp-{}", std::process::id()));
+ std::fs::write(
+ &tmp,
+ serde_json::to_vec_pretty(&File {
+ spaces: spaces.clone(),
+ })
+ .unwrap_or_default(),
+ )?;
+ std::fs::rename(&tmp, &p)
+}
+
+impl Spaces {
+ fn created_at(&self, id: &str) -> u64 {
+ self.registry()
+ .meta(id)
+ .map(|m| m.created_at_unix)
+ .unwrap_or(0)
+ }
+
+ /// Turns child Spaces on or off for registered Space `id`.
+ pub fn set_children(&self, id: &str, on: bool) -> crate::Result<()> {
+ let at = self.created_at(id);
+ {
+ let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ let mut all = load(self.home_dir());
+ let changed = if on {
+ all.insert(id.to_owned(), at) != Some(at)
+ } else {
+ all.remove(id).is_some()
+ };
+ if changed {
+ save(self.home_dir(), &all)?;
+ }
+ }
+ CHANGED.notify_waiters();
+ Ok(())
+ }
+
+ /// Whether `id` (this very Space, not an earlier one of the same name)
+ /// may make children.
+ pub fn children_on(&self, id: &str) -> bool {
+ load(self.home_dir())
+ .get(id)
+ .is_some_and(|at| *at == self.created_at(id))
+ }
+
+ /// Every Space with children on.
+ pub fn children_enabled(&self) -> Vec<String> {
+ load(self.home_dir())
+ .into_iter()
+ .filter(|(id, at)| *at == self.created_at(id))
+ .map(|(id, _)| id)
+ .collect()
+ }
+
+ /// Drops the settings of Spaces that are no longer registered.
+ pub fn forget_children_of_gone(&self, registered: &std::collections::BTreeSet<String>) {
+ let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ let mut all = load(self.home_dir());
+ let before = all.len();
+ all.retain(|id, _| registered.contains(id));
+ if all.len() != before {
+ let _ = save(self.home_dir(), &all);
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-spaces/src/client/control.rs b/libs/cua/crates/cua-spaces/src/client/control.rs
index 331772db6c..10a7c8b012 100644
--- a/libs/cua/crates/cua-spaces/src/client/control.rs
+++ b/libs/cua/crates/cua-spaces/src/client/control.rs
@@ -739,6 +739,12 @@ impl Space {
})
}
+ /// `space_job`: a background job in the Space (`arguments` as the tool
+ /// takes them: `action` and its fields).
+ pub fn job(&self, arguments: Value) -> Result<Map<String, Value>> {
+ self.call_object("space_job", self.arguments(arguments))
+ }
+
/// `space_write`. Literal text, no local file, no shell quoting.
pub fn write_text(&self, text: &str, path: &str) -> Result<RemoteFile> {
let target = self.guest_path(path);
@@ -753,6 +759,13 @@ impl Space {
})
}
+ /// `space_service`: keeps a command running in the Space (restarts,
+ /// health checks, start on boot, logs). `arguments` are the tool's own
+ /// (`action`, `name`, `command`, ...); the Space is filled in.
+ pub fn keep_service(&self, arguments: Value) -> Result<Value> {
+ self.call("space_service", self.arguments(arguments))
+ }
+
/// `upload`. Reports the path it actually wrote — `FRICTION.md` §13:
/// *"`upload` overwrites its destination silently … and no returned
/// path"*. The collision-safe placement keeps the user's filename intact
diff --git a/libs/cua/crates/cua-spaces/src/client/coverage.rs b/libs/cua/crates/cua-spaces/src/client/coverage.rs
index fb81f738f6..4a51dbdefd 100644
--- a/libs/cua/crates/cua-spaces/src/client/coverage.rs
+++ b/libs/cua/crates/cua-spaces/src/client/coverage.rs
@@ -23,7 +23,7 @@ pub struct ToolCoverage {
}
/// tool name → the typed Rust path that reaches it.
-const SYMBOLS: [(&str, &str); 113] = [
+const SYMBOLS: [(&str, &str); 117] = [
("add_space", "Connection::add_space"),
("remove_space", "Connection::remove_space"),
("list_spaces", "Connection::spaces"),
@@ -33,7 +33,9 @@ const SYMBOLS: [(&str, &str); 113] = [
("start_space", "Space::start"),
("resize_space", "Space::resize"),
("space_bash", "Space::bash"),
+ ("space_job", "Space::job"),
("space_write", "Space::write_text"),
+ ("space_service", "Space::keep_service"),
("upload", "Space::upload"),
("send_file", "Space::send_file"),
("download", "Space::download"),
@@ -106,6 +108,8 @@ const SYMBOLS: [(&str, &str); 113] = [
("thread_join_redeem", "Connection::thread_join_redeem"),
("thread_settings", "Connection::thread_settings"),
("thread_device_revoke", "Connection::thread_device_revoke"),
+ ("network_show", "Spaces::network_info"),
+ ("network_set", "Spaces::set_network"),
("teleport_manifest", "Space::teleport_manifest"),
("teleport_app", "Space::teleport_send"),
("request_site_login", "Space::request_site_login"),
diff --git a/libs/cua/crates/cua-spaces/src/egress.rs b/libs/cua/crates/cua-spaces/src/egress.rs
index 847782c665..5cbe8e97ee 100644
--- a/libs/cua/crates/cua-spaces/src/egress.rs
+++ b/libs/cua/crates/cua-spaces/src/egress.rs
@@ -121,6 +121,9 @@ impl Spaces {
}
self.inner.registry.update_meta(&id.to_string(), |m| {
m.egress = policy.clone();
+ // The lists are the network settings' own lists too.
+ m.network = Some(with_lists(m.network.take(), policy));
+ m.network_generation = m.network_generation.saturating_add(1);
})
}
@@ -141,10 +144,40 @@ impl Spaces {
}
}
+/// `settings` with `policy` as its lists: `internet` with lists becomes
+/// `custom` from `internet`, `none` with lists `custom` from `none`, and
+/// `custom` without lists goes back to its base.
+pub(crate) fn with_lists(
+ settings: Option<crate::network::NetworkSettings>,
+ policy: &EgressPolicy,
+) -> crate::network::NetworkSettings {
+ crate::network::NetworkSettings::with_lists(settings, policy)
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn set_egress_keeps_the_network_settings_in_step() {
+ use crate::network::{NetworkPreset as P, NetworkSettings};
+ let p = EgressPolicy {
+ allow: vec!["1.1.1.1".into()],
+ deny: vec!["all".into()],
+ };
+ let s = with_lists(None, &p);
+ assert_eq!((s.preset, s.custom_base), (P::Custom, P::Internet));
+ assert_eq!(s.custom, p);
+ let s = with_lists(Some(NetworkSettings::none()), &p);
+ assert_eq!((s.preset, s.custom_base), (P::Custom, P::None));
+ assert!(s.validate().is_ok());
+ let back = with_lists(Some(s), &EgressPolicy::default());
+ assert_eq!(back, NetworkSettings::none());
+ let lan = with_lists(Some(NetworkSettings::preset(P::Lan)), &p);
+ assert_eq!(lan.preset, P::Lan);
+ assert_eq!(lan.custom, p);
+ }
+
#[test]
fn the_policy_model_is_the_runtimes() {
// The same type: what Spaces keeps is what the runtime enforces.
diff --git a/libs/cua/crates/cua-spaces/src/host_spaces.rs b/libs/cua/crates/cua-spaces/src/host_spaces.rs
index 877b961c86..122e312ebc 100644
--- a/libs/cua/crates/cua-spaces/src/host_spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/host_spaces.rs
@@ -225,6 +225,10 @@ fn host_request(opts: &SpaceCreate, fork: Option<&str>) -> pb::CreateHostSpaceRe
gpu: opts.gpu.clone().unwrap_or_default(),
headless: opts.headless,
egress: egress_to_pb(&opts.egress),
+ network_settings: opts
+ .network_settings
+ .as_ref()
+ .map(crate::network::to_host_pb),
..Default::default()
}
}
@@ -1680,6 +1684,17 @@ impl HostSpacesServer {
Ok(n) => n,
Err(e) => return Err(self.refuse(caller, &label, Error::invalid(e.to_string()))),
};
+ // The caller's settings (already intersected with any parent on its
+ // side); a caller from before them sends `network` and `egress`.
+ let network_settings = match req
+ .network_settings
+ .as_ref()
+ .map(crate::network::from_host_pb)
+ .transpose()
+ {
+ Ok(s) => s,
+ Err(e) => return Err(self.refuse(caller, &label, e)),
+ };
let following = self.creating.follow(key, &caller.account);
let fork_source = req.fork_source.trim().to_string();
let created = if !fork_source.is_empty() {
@@ -1743,6 +1758,7 @@ impl HostSpacesServer {
headless: req.headless,
// Enforced by this host, from the guest's first instruction.
egress: egress_from_pb(req.egress.clone()),
+ network_settings: network_settings.clone(),
..Default::default()
};
match self.spaces.create(create.clone()).await {
@@ -3723,6 +3739,10 @@ impl Spaces {
direct: false,
network: network_word(opts.network).into(),
egress: egress_to_pb(&opts.egress),
+ network_settings: opts
+ .network_settings
+ .as_ref()
+ .map(crate::network::to_host_pb),
attach: Some(pb::AttachRelayRequest {
relay_url: relay.url.clone(),
machine_token: reg.machine_token.clone(),
diff --git a/libs/cua/crates/cua-spaces/src/keep.rs b/libs/cua/crates/cua-spaces/src/keep.rs
new file mode 100644
index 0000000000..2ef97ea14f
--- /dev/null
+++ b/libs/cua/crates/cua-spaces/src/keep.rs
@@ -0,0 +1,384 @@
+//! Keep running: commands a Space's cua-spacesd keeps up (services).
+//!
+//! A service is started at once, started again by its restart policy (with
+//! a backoff) when it exits or fails its health check, started when the
+//! Space boots, and its output is kept in log files in the Space
+//! (`ProcessService.PutService` and the rest). This module is the host's
+//! side: plain types for the CLI, the SDKs and the MCP tool.
+
+use std::collections::BTreeMap;
+use std::time::Duration;
+
+use cua_spacesd_client::pb;
+use serde::{Deserialize, Serialize};
+
+use crate::error::{Error, Result};
+use crate::space::Space;
+
+/// The guest feature.
+pub const SERVICES_FEATURE: &str = "process.services";
+
+/// When a service is started again.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum Restart {
+ /// Whenever it ends.
+ #[default]
+ Always,
+ /// When it fails (non-zero exit, a signal, a failed health check).
+ OnFailure,
+ /// Never: it runs once.
+ Never,
+}
+
+impl Restart {
+ /// Parses `always`, `on-failure` or `never`.
+ pub fn parse(s: &str) -> Option<Self> {
+ Some(match s.trim() {
+ "" | "always" => Self::Always,
+ "on-failure" | "on_failure" => Self::OnFailure,
+ "never" | "no" => Self::Never,
+ _ => return None,
+ })
+ }
+
+ fn pb(self) -> pb::RestartPolicy {
+ match self {
+ Self::Always => pb::RestartPolicy::Always,
+ Self::OnFailure => pb::RestartPolicy::OnFailure,
+ Self::Never => pb::RestartPolicy::Never,
+ }
+ }
+}
+
+/// A health check: exactly one of `http`, `tcp`, `command`.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct Probe {
+ /// A URL that answers 2xx or 3xx.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub http: Option<String>,
+ /// `host:port` that accepts a TCP connection.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tcp: Option<String>,
+ /// A shell command that exits 0 when healthy.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub command: Option<String>,
+ /// Seconds between checks (default 10).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub interval_secs: Option<u64>,
+ /// Failed checks in a row that restart it (default 3).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub failures: Option<u32>,
+}
+
+/// A service to keep running.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ServiceDef {
+ /// Name.
+ pub name: String,
+ /// The shell command line it runs.
+ pub command: String,
+ /// Extra environment.
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub env: BTreeMap<String, String>,
+ /// Working directory.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cwd: Option<String>,
+ /// When it is started again.
+ #[serde(default)]
+ pub restart: Restart,
+ /// Health check.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub probe: Option<Probe>,
+ /// Start it when the Space boots (default true).
+ #[serde(default = "yes")]
+ pub start_on_boot: bool,
+}
+
+fn yes() -> bool {
+ true
+}
+
+/// A service and how it is doing.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ServiceInfo {
+ /// Name.
+ pub name: String,
+ /// The command line.
+ pub command: String,
+ /// `starting`, `running`, `unhealthy`, `backoff`, `stopped`, `exited`
+ /// or `failed`.
+ pub state: String,
+ /// Its process, while it runs.
+ pub pid: u32,
+ /// Starts after the first.
+ pub restarts: u32,
+ /// How the last process ended (`exited 3`, `signal 9`, ...), if one did.
+ pub last_end: String,
+ /// The last failed health check, if the last one failed.
+ pub probe_error: String,
+ /// `always`, `on-failure` or `never`.
+ pub restart: String,
+ /// Starts when the Space boots.
+ pub start_on_boot: bool,
+ /// Its log file in the Space.
+ pub log_path: String,
+}
+
+fn secs(n: u64) -> Option<cua_proto::wkt::Duration> {
+ Some(cua_proto::wkt::Duration {
+ seconds: n as i64,
+ nanos: 0,
+ })
+}
+
+impl ServiceDef {
+ fn spec(&self, windows: bool) -> Result<pb::ServiceSpec> {
+ if self.command.trim().is_empty() {
+ return Err(Error::InvalidArgument("a service needs a command".into()));
+ }
+ let shell = |line: &str| {
+ if windows {
+ pb::ProcessConfig {
+ command: "cmd.exe".into(),
+ args: vec!["/C".into(), line.into()],
+ ..Default::default()
+ }
+ } else {
+ pb::ProcessConfig {
+ command: "/bin/sh".into(),
+ args: vec!["-c".into(), line.into()],
+ ..Default::default()
+ }
+ }
+ };
+ let mut config = shell(&self.command);
+ config.env = self.env.clone().into_iter().collect();
+ config.cwd = self.cwd.clone().unwrap_or_default();
+ let probe = match &self.probe {
+ None => None,
+ Some(p) => {
+ let set = [p.http.is_some(), p.tcp.is_some(), p.command.is_some()]
+ .iter()
+ .filter(|x| **x)
+ .count();
+ if set != 1 {
+ return Err(Error::InvalidArgument(
+ "a health check checks one thing: http, tcp or command".into(),
+ ));
+ }
+ Some(pb::HealthProbe {
+ exec: p.command.as_deref().map(shell),
+ http: p.http.clone().unwrap_or_default(),
+ tcp: p.tcp.clone().unwrap_or_default(),
+ interval: p.interval_secs.and_then(secs),
+ failure_threshold: p.failures.unwrap_or(0),
+ ..Default::default()
+ })
+ }
+ };
+ Ok(pb::ServiceSpec {
+ name: self.name.clone(),
+ config: Some(config),
+ restart: self.restart.pb() as i32,
+ probe,
+ start_on_boot: Some(self.start_on_boot),
+ ..Default::default()
+ })
+ }
+}
+
+fn line_of(spec: &pb::ServiceSpec) -> String {
+ spec.config
+ .as_ref()
+ .map(|c| match c.args.as_slice() {
+ [flag, line] if flag == "-c" || flag == "/C" => line.clone(),
+ args => std::iter::once(c.command.clone())
+ .chain(args.iter().cloned())
+ .collect::<Vec<_>>()
+ .join(" "),
+ })
+ .unwrap_or_default()
+}
+
+fn info(s: pb::ServiceStatus) -> ServiceInfo {
+ let spec = s.spec.unwrap_or_default();
+ let state = match pb::ServiceState::try_from(s.state).unwrap_or_default() {
+ pb::ServiceState::Starting => "starting",
+ pb::ServiceState::Running => "running",
+ pb::ServiceState::Unhealthy => "unhealthy",
+ pb::ServiceState::Backoff => "backoff",
+ pb::ServiceState::Stopped => "stopped",
+ pb::ServiceState::Exited => "exited",
+ pb::ServiceState::Failed => "failed",
+ pb::ServiceState::Unspecified => "unknown",
+ };
+ let last_end = s
+ .last_end
+ .map(|e| {
+ if !e.error.is_empty() {
+ e.error
+ } else if let Some(code) = e.exit_code {
+ format!("exited {code}")
+ } else {
+ format!("signal {}", e.signal_number)
+ }
+ })
+ .unwrap_or_default();
+ ServiceInfo {
+ command: line_of(&spec),
+ restart: match pb::RestartPolicy::try_from(spec.restart).unwrap_or_default() {
+ pb::RestartPolicy::OnFailure => "on-failure",
+ pb::RestartPolicy::Never => "never",
+ _ => "always",
+ }
+ .into(),
+ start_on_boot: spec.start_on_boot.unwrap_or(true),
+ name: spec.name,
+ state: state.into(),
+ pid: s.pid,
+ restarts: s.restarts,
+ last_end,
+ probe_error: s.probe_error,
+ log_path: s.log_path,
+ }
+}
+
+/// What [`Space::control_service`] does.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ServiceControl {
+ /// Start it.
+ Start,
+ /// Stop it and keep it stopped.
+ Stop,
+ /// Stop, then start.
+ Restart,
+}
+
+impl Space {
+ /// Keeps `def` running in this Space (replacing a service of that name).
+ pub async fn put_service(&self, def: &ServiceDef) -> Result<ServiceInfo> {
+ // Part of the Child Spaces experiment, off unless turned on.
+ // Listing, stopping and removing services stay available.
+ if !cua_vmm::experiments::enabled(cua_vmm::experiments::Gate::ChildSpaces) {
+ return Err(Error::invalid(format!(
+ "keeping a command running is part of the Child Spaces experiment. {}",
+ cua_vmm::experiments::Gate::ChildSpaces.off_message()
+ )));
+ }
+ self.require(SERVICES_FEATURE)?;
+ let r = self
+ .spacesd()?
+ .process()
+ .put_service(pb::PutServiceRequest {
+ spec: Some(def.spec(self.is_windows())?),
+ })
+ .await
+ .map_err(cua_spacesd_client::Error::from)?
+ .into_inner();
+ Ok(info(r.service.unwrap_or_default()))
+ }
+
+ /// This Space's services.
+ pub async fn kept_services(&self) -> Result<Vec<ServiceInfo>> {
+ self.require(SERVICES_FEATURE)?;
+ let r = self
+ .spacesd()?
+ .process()
+ .list_services(pb::ListServicesRequest {})
+ .await
+ .map_err(cua_spacesd_client::Error::from)?
+ .into_inner();
+ Ok(r.services.into_iter().map(info).collect())
+ }
+
+ /// Starts, stops or restarts a service.
+ pub async fn control_service(&self, name: &str, what: ServiceControl) -> Result<ServiceInfo> {
+ self.require(SERVICES_FEATURE)?;
+ let action = match what {
+ ServiceControl::Start => pb::ServiceAction::Start,
+ ServiceControl::Stop => pb::ServiceAction::Stop,
+ ServiceControl::Restart => pb::ServiceAction::Restart,
+ };
+ let r = self
+ .spacesd()?
+ .process()
+ .control_service(pb::ControlServiceRequest {
+ name: name.into(),
+ action: action as i32,
+ })
+ .await
+ .map_err(cua_spacesd_client::Error::from)?
+ .into_inner();
+ Ok(info(r.service.unwrap_or_default()))
+ }
+
+ /// Stops a service and forgets it.
+ pub async fn delete_service(&self, name: &str) -> Result<()> {
+ self.require(SERVICES_FEATURE)?;
+ self.spacesd()?
+ .process()
+ .delete_service(pb::DeleteServiceRequest { name: name.into() })
+ .await
+ .map_err(cua_spacesd_client::Error::from)?;
+ Ok(())
+ }
+
+ /// The end of a service's log (`tail_bytes` 0: 64 KiB).
+ pub async fn service_logs(&self, name: &str, tail_bytes: u64) -> Result<String> {
+ self.require(SERVICES_FEATURE)?;
+ let r = tokio::time::timeout(
+ Duration::from_secs(60),
+ self.spacesd()?
+ .process()
+ .get_service_logs(pb::GetServiceLogsRequest {
+ name: name.into(),
+ tail_bytes,
+ }),
+ )
+ .await
+ .map_err(|_| Error::Timeout("service logs".into()))?
+ .map_err(cua_spacesd_client::Error::from)?
+ .into_inner();
+ Ok(String::from_utf8_lossy(&r.data).into_owned())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_def_becomes_a_spec_and_back() {
+ let def = ServiceDef {
+ name: "web".into(),
+ command: "python3 -m http.server 8080".into(),
+ restart: Restart::OnFailure,
+ probe: Some(Probe {
+ http: Some("http://127.0.0.1:8080/".into()),
+ failures: Some(2),
+ ..Default::default()
+ }),
+ start_on_boot: true,
+ ..Default::default()
+ };
+ let spec = def.spec(false).unwrap();
+ assert_eq!(spec.config.as_ref().unwrap().command, "/bin/sh");
+ assert_eq!(spec.restart, pb::RestartPolicy::OnFailure as i32);
+ let back = info(pb::ServiceStatus {
+ spec: Some(spec),
+ state: pb::ServiceState::Running as i32,
+ ..Default::default()
+ });
+ assert_eq!(back.command, def.command);
+ assert_eq!(
+ (back.state.as_str(), back.restart.as_str()),
+ ("running", "on-failure")
+ );
+ let mut two = def.clone();
+ two.probe.as_mut().unwrap().tcp = Some("127.0.0.1:1".into());
+ assert!(two.spec(false).is_err());
+ assert_eq!(Restart::parse("never"), Some(Restart::Never));
+ assert_eq!(Restart::parse("sometimes"), None);
+ }
+}
diff --git a/libs/cua/crates/cua-spaces/src/lib.rs b/libs/cua/crates/cua-spaces/src/lib.rs
index ed0c4416ee..6ac041740f 100644
--- a/libs/cua/crates/cua-spaces/src/lib.rs
+++ b/libs/cua/crates/cua-spaces/src/lib.rs
@@ -61,6 +61,7 @@ pub mod app_icon;
/// A hash-chained audit log (the share audit).
pub mod audit;
pub mod build;
+pub mod children;
#[cfg(feature = "mcp-client")]
pub mod client;
/// Spaces in your own cloud account: a cloud sandbox (`cua_sandbox_core::byoc`)
@@ -79,12 +80,14 @@ pub mod groups;
pub mod host_jobs;
pub mod host_spaces;
pub mod id;
+pub mod keep;
pub mod lifetimes;
pub mod list_watch;
pub mod listing;
mod local_load;
pub mod mesh;
pub mod named_volumes;
+pub mod network;
pub mod operator;
pub mod pool_checkpoints;
pub mod prewarm;
@@ -98,8 +101,10 @@ pub mod routines;
pub mod services;
pub mod snapshots;
mod space;
+pub mod space_jobs;
mod spaces;
pub mod thumbnails;
+pub mod tree;
#[cfg(feature = "spaces-agents")]
pub mod agents;
@@ -129,6 +134,8 @@ pub mod sharing;
/// The Keyvault seam and the whole `request_site_login` tool: sign in to a
/// site in a Space with a saved password, approved by the user.
pub mod site_login;
+#[cfg(feature = "spaces-spawn")]
+pub mod spawn;
#[cfg(feature = "spaces-stream")]
pub mod stream;
/// The Keyvault broker seam the `teleport_app` MCP tool routes delivery
@@ -143,6 +150,7 @@ pub mod walk;
pub use app_icon::{AppIcon, IconRequest};
pub use creating::{CancelOutcome, CancelState};
+pub use cua_vmm::experiments;
pub use error::{Error, Result};
pub use id::{Provider, SpaceId};
pub use listing::{LIST_WAIT, ListProgress, SpaceListing};
diff --git a/libs/cua/crates/cua-spaces/src/mcp/mod.rs b/libs/cua/crates/cua-spaces/src/mcp/mod.rs
index 6b83211bac..cee6e3a8cd 100644
--- a/libs/cua/crates/cua-spaces/src/mcp/mod.rs
+++ b/libs/cua/crates/cua-spaces/src/mcp/mod.rs
@@ -487,6 +487,7 @@ pub async fn call_on(space: &Space, tool: &str, arguments: Value) -> ToolOutcome
pub const SPACE_SCOPED_TOOLS: &[&str] = &[
"space_bash",
"space_write",
+ "space_service",
"upload",
"download",
"send_file",
diff --git a/libs/cua/crates/cua-spaces/src/mcp/tools.rs b/libs/cua/crates/cua-spaces/src/mcp/tools.rs
index 229ca32c80..31af096dd4 100644
--- a/libs/cua/crates/cua-spaces/src/mcp/tools.rs
+++ b/libs/cua/crates/cua-spaces/src/mcp/tools.rs
@@ -254,7 +254,23 @@ async fn dispatch(
"count {count}: create 1 to {MAX_CREATE_COUNT} Spaces at a time"
)));
}
+ // The network: tightening only (anything opening more than
+ // Internet only is the user's to choose).
+ let network_settings = match (&a.network, &a.allow, &a.deny) {
+ (None, None, None) => None,
+ _ => {
+ let s = crate::network::parse_network(
+ a.network.as_deref().unwrap_or("internet"),
+ a.allow.as_deref().unwrap_or_default(),
+ a.deny.as_deref().unwrap_or_default(),
+ )?;
+ crate::network::refuse_widening_by_agent(&s, None)?;
+ Some(s)
+ }
+ };
let one = |name: Option<String>| SpaceCreate {
+ network_settings: network_settings.clone(),
+ parent: a.parent.clone(),
image: a.image.clone(),
on: on.clone(),
kind,
@@ -326,6 +342,29 @@ async fn dispatch(
let a: i::SpaceOnly = args(tool, a)?;
Ok(ToolOutcome::text(spaces.delete(&a.space).await?))
}
+ "network_show" => {
+ let a: i::SpaceOnly = args(tool, a)?;
+ Ok(ToolOutcome::json(&spaces.network_info(&a.space).await?))
+ }
+ "network_set" => {
+ let a: i::NetworkSet = args(tool, a)?;
+ let s = crate::network::parse_network(
+ &a.network,
+ a.allow.as_deref().unwrap_or_default(),
+ a.deny.as_deref().unwrap_or_default(),
+ )?;
+ let current = spaces.network_info(&a.space).await?.settings;
+ crate::network::refuse_widening_by_agent(&s, Some(&current))?;
+ let tree = a.tree.unwrap_or(false);
+ let applied = spaces.set_network(&a.space, &s, false, tree).await?;
+ Ok(ToolOutcome::json(&json!({
+ "applied": match applied {
+ crate::network::Applied::Now => "now",
+ crate::network::Applied::NextStart => "next_start",
+ },
+ "network": spaces.network_info(&a.space).await?,
+ })))
+ }
"stop_space" => {
let a: i::StopSpace = args(tool, a)?;
if a.suspend.unwrap_or(false) {
@@ -646,6 +685,20 @@ async fn dispatch(
let t = Duration::from_secs(a.timeout.unwrap_or(60).clamp(1, 24 * 3600));
Ok(ToolOutcome::text(s.bash(&a.command, t).await?.render()))
}
+ "space_service" => {
+ let a: i::SpaceService = args(tool, a)?;
+ let s = space_for(spaces, tool, &a.space).await?;
+ Ok(ToolOutcome::json(&space_service(&s, a).await?))
+ }
+ "space_job" => {
+ let a: i::SpaceJob = args(tool, a)?;
+ let s = space_for(spaces, tool, &a.space).await?;
+ let mut out = s.job(&a).await?;
+ if a.action == "start" && a.notify.unwrap_or(false) {
+ out["notify"] = crate::space_jobs::watch(spaces, &s, &out, &a).await;
+ }
+ Ok(json_of(&out))
+ }
"space_write" => {
let a: i::SpaceWrite = args(tool, a)?;
let s = space_for(spaces, tool, &a.space).await?;
@@ -1135,6 +1188,16 @@ async fn agents(spaces: &Spaces, tool: &str, a: Value) -> Result<ToolOutcome> {
// The caller's env, the env_from_host keys, and the keys saved
// in Cua Spaces that this harness reads.
let (opts, missing) = ag::start_options(&a)?;
+ // An agent run may make child Spaces of its own Space: this
+ // machine keeps the Space's spawn channel while that is on
+ // (only for a Space this computer runs).
+ let id = s.id().to_string();
+ if id.starts_with("local:")
+ && spaces.registry().get(&id).ok().flatten().is_some()
+ && let Err(e) = spaces.set_children(&id, true)
+ {
+ tracing::warn!(space = %id, error = %e, "could not turn on child Spaces");
+ }
let started = agents.start(&a.agent, &a.prompt, opts).await;
// The MCP `agent_start`, the SDKs' `Space.agent_start` and the
// Spaces app all arrive here.
@@ -1343,3 +1406,64 @@ async fn show(s: &crate::Space, run_dir: &str, run_id: &str) {
h.detach();
}
}
+
+/// `space_service`.
+async fn space_service(s: &crate::Space, a: i::SpaceService) -> Result<Value> {
+ use crate::keep::{Probe, Restart, ServiceControl, ServiceDef};
+ let name = || {
+ a.name
+ .clone()
+ .filter(|n| !n.trim().is_empty())
+ .ok_or_else(|| Error::InvalidArgument(format!("{} needs `name`", a.action)))
+ };
+ Ok(match a.action.as_str() {
+ "add" => {
+ let restart = match a.restart.as_deref() {
+ None => Restart::Always,
+ Some(r) => Restart::parse(r).ok_or_else(|| {
+ Error::InvalidArgument(format!(
+ "restart {r:?}: use always, on-failure or never"
+ ))
+ })?,
+ };
+ let probe = (a.http.is_some() || a.tcp.is_some() || a.check.is_some()).then(|| Probe {
+ http: a.http.clone(),
+ tcp: a.tcp.clone(),
+ command: a.check.clone(),
+ ..Default::default()
+ });
+ let def = ServiceDef {
+ name: name()?,
+ command: a
+ .command
+ .clone()
+ .ok_or_else(|| Error::InvalidArgument("add needs `command`".into()))?,
+ restart,
+ probe,
+ start_on_boot: a.start_on_boot.unwrap_or(true),
+ ..Default::default()
+ };
+ serde_json::to_value(s.put_service(&def).await?).unwrap_or(Value::Null)
+ }
+ "list" => json!({ "services": s.kept_services().await? }),
+ "start" => serde_json::to_value(s.control_service(&name()?, ServiceControl::Start).await?)
+ .unwrap_or(Value::Null),
+ "stop" => serde_json::to_value(s.control_service(&name()?, ServiceControl::Stop).await?)
+ .unwrap_or(Value::Null),
+ "restart" => {
+ serde_json::to_value(s.control_service(&name()?, ServiceControl::Restart).await?)
+ .unwrap_or(Value::Null)
+ }
+ "remove" => {
+ let n = name()?;
+ s.delete_service(&n).await?;
+ json!({ "removed": n })
+ }
+ "logs" => json!({ "logs": s.service_logs(&name()?, a.tail_bytes.unwrap_or(0)).await? }),
+ other => {
+ return Err(Error::InvalidArgument(format!(
+ "action {other:?}: use add, list, start, stop, restart, remove or logs"
+ )));
+ }
+ })
+}
diff --git a/libs/cua/crates/cua-spaces/src/network.rs b/libs/cua/crates/cua-spaces/src/network.rs
new file mode 100644
index 0000000000..c6bd1f8cf8
--- /dev/null
+++ b/libs/cua/crates/cua-spaces/src/network.rs
@@ -0,0 +1,956 @@
+//! Network settings of Spaces: kept with the Space ([`SpaceMeta::network`]),
+//! carried to the runtime that starts it, and compiled there to rules the
+//! host enforces outside the guest ([`cua_vmm::network`] has the model:
+//! presets, layers, the support table and the fail-closed plan).
+//!
+//! - A new Space gets what its create asks for: [`SpaceCreate::network_settings`],
+//! else what the old options say (`network=none` is `none`, an egress
+//! policy is `custom` from `internet`, nothing is `internet`).
+//! - A child Space (`parent`) gets the intersection of its own settings and
+//! its parent's: it can only tighten. `widen` skips that and records who
+//! widened it.
+//! - A Space from before network settings gets them, migrated the same
+//! way, on its next start ([`migrate_meta`]), and a one-time notice.
+//! - Forks keep their source's settings and tree
+//! ([`crate::registry::Registry::inherit_meta`]).
+//!
+//! [`SpaceMeta::network`]: crate::registry::SpaceMeta::network
+//! [`SpaceCreate::network_settings`]: crate::SpaceCreate::network_settings
+
+use crate::registry::SpaceMeta;
+use crate::{Error, Result, Spaces};
+use cua_proto::daemon::v1 as dpb;
+use cua_proto::env::v1 as epb;
+
+use cua_vmm::network::compile_mode;
+
+pub use cua_vmm::network::{
+ Applied, Mode, NO_NETWORK_NOTE, NetworkContext, NetworkPlan, NetworkPreset, NetworkSettings,
+ NetworkSupport, Placement, UNPROTECTED_NOTE, network_support,
+};
+
+/// The runtime of a local Space's backend word (`qemu`, `docker`,
+/// `gvisor`, `vz`, ...).
+pub fn backend_kind(word: &str) -> Option<cua_vmm::BackendKind> {
+ use cua_vmm::BackendKind as B;
+ Some(match word {
+ "qemu" => B::Qemu,
+ "qemu-docker" => B::QemuDocker,
+ "lume" => B::Lume,
+ "container" | "docker" | "podman" | "runc" | "runsc" | "gvisor" => B::Container,
+ "managed" => B::Managed,
+ "firecracker" => B::Firecracker,
+ "vz" => B::Vz,
+ "containerization" | "apple" => B::Containerization,
+ _ => return None,
+ })
+}
+
+/// The note a Space on this computer's `backend` gets for `settings`: why
+/// it has no network (its runtime can't protect it yet), or that the user
+/// chose No protection. `None` when its rules are enforced.
+pub fn note_for(backend: &str, settings: &NetworkSettings) -> Option<String> {
+ let kind = backend_kind(backend)?;
+ let support = network_support(kind, std::env::consts::OS, Placement::Local);
+ match cua_vmm::network::plan(
+ settings,
+ support,
+ &NetworkContext::default(),
+ Mode::from_env(),
+ ) {
+ Ok(NetworkPlan::NoNetwork { note: Some(n) }) | Ok(NetworkPlan::Open { note: Some(n) }) => {
+ Some(n.to_string())
+ }
+ _ => None,
+ }
+}
+
+/// While Secure Spaces is off (an experiment), a Space gets the network it
+/// always had: only the old allow and deny lists. Anything
+/// else is refused with how to turn the experiment on.
+pub fn require_secure_spaces(settings: Option<&NetworkSettings>) -> Result<()> {
+ if Mode::from_env() == Mode::Secure {
+ return Ok(());
+ }
+ // What the old calls (`network = none`, the egress lists) already
+ // asked for: Internet, None, and Custom from Internet.
+ let beyond_lists = settings.is_some_and(|s| {
+ !(matches!(s.preset, NetworkPreset::Internet | NetworkPreset::None)
+ || (s.preset == NetworkPreset::Custom && s.custom_base == NetworkPreset::Internet))
+ || !s.localhost_ports.is_empty()
+ || s.all_localhost_ports
+ || s.widened_by.is_some()
+ });
+ if beyond_lists {
+ return Err(Error::invalid(
+ cua_vmm::experiments::Gate::SecureSpaces.off_message(),
+ ));
+ }
+ Ok(())
+}
+
+/// Refuses network settings a Space in your own cloud account or a
+/// provider can't keep: anything but No protection (the provider has no
+/// point cua controls to enforce them).
+pub fn refuse_on_provider(settings: &NetworkSettings) -> Result<()> {
+ if Mode::from_env() == Mode::Legacy || settings.preset == NetworkPreset::Unprotected {
+ return Ok(());
+ }
+ match network_support(
+ cua_vmm::BackendKind::Container,
+ "linux",
+ Placement::Provider,
+ ) {
+ NetworkSupport::Refuse { why } => Err(Error::invalid(why)),
+ NetworkSupport::Enforced { .. } | NetworkSupport::NoNetworkOnly { .. } => Ok(()),
+ }
+}
+
+/// What no setting opens, in plain words (`cua network show`).
+pub const ALWAYS_BLOCKED: [&str; 4] = [
+ "Cloud metadata (169.254.169.254 and the other clouds' endpoints)",
+ "Spaces in other trees",
+ "The Cua daemon on this computer",
+ "This computer's own addresses (only \"localhost\" opens listed ports)",
+];
+
+/// A Space's network as `cua network show` says it.
+#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
+pub struct NetworkInfo {
+ /// Its settings.
+ pub settings: NetworkSettings,
+ /// One plain line.
+ pub summary: String,
+ /// What the settings open beyond "internet".
+ pub widenings: Vec<String>,
+ /// `enforced`, `no_network`, `open`, `refused`; empty when unknown.
+ pub enforcement: String,
+ /// Where it is enforced, or why its network is cut.
+ pub point: String,
+ /// Why its network is not what was asked.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub note: Option<String>,
+ /// Its parent and tree root.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub parent: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub root: Option<String>,
+ /// What no setting opens.
+ pub always_blocked: Vec<String>,
+ /// An update changed its settings; say so once.
+ pub notice_pending: bool,
+}
+
+/// [`NetworkInfo`] in the daemon's wire form.
+pub fn info_to_pb(i: &NetworkInfo) -> dpb::SpaceNetworkInfo {
+ dpb::SpaceNetworkInfo {
+ settings: Some(to_pb(&i.settings)),
+ summary: i.summary.clone(),
+ widenings: i.widenings.clone(),
+ enforcement: i.enforcement.clone(),
+ point: i.point.clone(),
+ note: i.note.clone().unwrap_or_default(),
+ parent: i.parent.clone().unwrap_or_default(),
+ root: i.root.clone().unwrap_or_default(),
+ always_blocked: i.always_blocked.clone(),
+ notice_pending: i.notice_pending,
+ }
+}
+
+/// How `settings` fare on `backend` here: (`enforcement`, `point`).
+pub fn enforcement_of(backend: &str, settings: &NetworkSettings) -> (String, String) {
+ let Some(kind) = backend_kind(backend) else {
+ return (String::new(), String::new());
+ };
+ let support = network_support(kind, std::env::consts::OS, Placement::Local);
+ let point = match support {
+ NetworkSupport::Enforced { point } => point,
+ NetworkSupport::NoNetworkOnly { why } | NetworkSupport::Refuse { why } => why,
+ };
+ let word = match cua_vmm::network::plan(
+ settings,
+ support,
+ &NetworkContext::default(),
+ Mode::from_env(),
+ ) {
+ Ok(NetworkPlan::Enforce(_)) => "enforced",
+ Ok(NetworkPlan::NoNetwork { .. }) => "no_network",
+ Ok(NetworkPlan::Open { .. }) => "open",
+ Ok(NetworkPlan::Refuse(_)) | Err(_) => "refused",
+ };
+ (word.into(), point.into())
+}
+
+/// What a Space's listing shows of its network.
+#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
+pub struct SpaceNetwork {
+ /// Its settings.
+ pub settings: NetworkSettings,
+ /// Why its network is not what was asked, in plain words.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub note: Option<String>,
+ /// Its settings were changed by an update; say so once.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub notice_pending: bool,
+}
+
+/// The one-time notice of a Space moved to the new defaults.
+pub const MIGRATION_NOTICE: &str = "This Space now uses Internet only. It can't reach this \
+ computer or your local network. Change it with `cua network set`.";
+
+/// The settings of a Space from before network settings
+/// ([`NetworkSettings::migrate`] of its egress policy), and whether they
+/// open anything its old policy's lists named (kept, and labelled by
+/// [`NetworkSettings::widenings`]). `restrict_network`: it was created with
+/// `network=none`.
+pub fn migrate_meta(meta: &SpaceMeta, restrict_network: bool) -> NetworkSettings {
+ NetworkSettings::migrate(&meta.egress, restrict_network)
+}
+
+/// `settings` in the daemon's wire form.
+pub fn to_pb(s: &NetworkSettings) -> dpb::NetworkSettings {
+ dpb::NetworkSettings {
+ preset: s.preset.as_str().into(),
+ localhost_ports: s.localhost_ports.iter().map(|p| u32::from(*p)).collect(),
+ all_localhost_ports: s.all_localhost_ports,
+ allow: s.custom.allow.clone(),
+ deny: s.custom.deny.clone(),
+ custom_base: match s.custom_base {
+ NetworkPreset::None => "none".into(),
+ _ => String::new(),
+ },
+ widened_by: s.widened_by.clone().unwrap_or_default(),
+ }
+}
+
+/// The daemon's wire form back, checked ([`NetworkSettings::validate`]).
+pub fn from_pb(p: &dpb::NetworkSettings) -> Result<NetworkSettings> {
+ settings_from_parts(
+ &p.preset,
+ &p.localhost_ports,
+ p.all_localhost_ports,
+ &p.allow,
+ &p.deny,
+ &p.custom_base,
+ &p.widened_by,
+ )
+}
+
+/// `settings` as a host's create carries them.
+pub fn to_host_pb(s: &NetworkSettings) -> epb::HostNetworkSettings {
+ let p = to_pb(s);
+ epb::HostNetworkSettings {
+ preset: p.preset,
+ localhost_ports: p.localhost_ports,
+ all_localhost_ports: p.all_localhost_ports,
+ allow: p.allow,
+ deny: p.deny,
+ custom_base: p.custom_base,
+ widened_by: p.widened_by,
+ }
+}
+
+/// A host's create's settings back, checked.
+pub fn from_host_pb(p: &epb::HostNetworkSettings) -> Result<NetworkSettings> {
+ settings_from_parts(
+ &p.preset,
+ &p.localhost_ports,
+ p.all_localhost_ports,
+ &p.allow,
+ &p.deny,
+ &p.custom_base,
+ &p.widened_by,
+ )
+}
+
+fn settings_from_parts(
+ preset: &str,
+ ports: &[u32],
+ all_ports: bool,
+ allow: &[String],
+ deny: &[String],
+ base: &str,
+ widened_by: &str,
+) -> Result<NetworkSettings> {
+ let word = |w: &str| -> Result<NetworkPreset> {
+ if w.trim().is_empty() {
+ return Ok(NetworkPreset::Internet);
+ }
+ NetworkPreset::parse(w).map_err(|e| Error::invalid(e.0))
+ };
+ let localhost_ports = ports
+ .iter()
+ .map(|p| {
+ u16::try_from(*p)
+ .ok()
+ .filter(|p| *p > 0)
+ .ok_or_else(|| Error::invalid(format!("localhost port {p} is not a port")))
+ })
+ .collect::<Result<Vec<u16>>>()?;
+ let s = NetworkSettings {
+ preset: word(preset)?,
+ localhost_ports,
+ all_localhost_ports: all_ports,
+ custom: crate::egress::EgressPolicy {
+ allow: allow.to_vec(),
+ deny: deny.to_vec(),
+ },
+ custom_base: word(base)?,
+ widened_by: (!widened_by.is_empty()).then(|| widened_by.to_string()),
+ };
+ s.validate().map_err(|e| Error::invalid(e.0))?;
+ Ok(s)
+}
+
+/// Who widened a child and when: `user@2026-10-26T12:00:00Z`.
+pub fn widened_stamp() -> String {
+ let who = std::env::var("USER")
+ .or_else(|_| std::env::var("USERNAME"))
+ .ok()
+ .filter(|u| !u.trim().is_empty())
+ .unwrap_or_else(|| "user".into());
+ format!(
+ "{who}@{}",
+ humantime::format_rfc3339_seconds(std::time::SystemTime::now())
+ )
+}
+
+/// The network a create resolved: the settings the Space gets and its
+/// place in a tree.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct CreateNetwork {
+ /// What the Space gets.
+ pub settings: NetworkSettings,
+ /// Its parent's canonical id.
+ pub parent: Option<String>,
+ /// Its tree's root's canonical id.
+ pub root: Option<String>,
+ /// Its depth below the root (0: top-level).
+ pub depth: u32,
+}
+
+/// Settings from one word as the CLI, SDK and MCP take it: `internet`
+/// (`default` and empty too), `none`, `lan`, `unprotected`, `custom` (from
+/// `internet`), `custom:none`, `localhost:5432,3000` or `localhost:all`,
+/// with `allow` and `deny` lists on top.
+pub fn parse_network(word: &str, allow: &[String], deny: &[String]) -> Result<NetworkSettings> {
+ let w = word.trim();
+ let (head, rest) = match w.split_once(':') {
+ Some((h, r)) => (h, Some(r)),
+ None => (w, None),
+ };
+ let preset = if head.is_empty() {
+ NetworkPreset::Internet
+ } else {
+ NetworkPreset::parse(head).map_err(|e| Error::invalid(e.0))?
+ };
+ let mut s = NetworkSettings::preset(preset);
+ match (preset, rest) {
+ (_, None) => {}
+ (NetworkPreset::Localhost, Some(r)) if r.trim().eq_ignore_ascii_case("all") => {
+ s.all_localhost_ports = true
+ }
+ (NetworkPreset::Localhost, Some(r)) => {
+ for p in r.split(',').map(str::trim).filter(|p| !p.is_empty()) {
+ let port =
+ p.parse::<u16>().ok().filter(|p| *p > 0).ok_or_else(|| {
+ Error::invalid(format!("localhost port {p:?} is not a port"))
+ })?;
+ if !s.localhost_ports.contains(&port) {
+ s.localhost_ports.push(port);
+ }
+ }
+ }
+ (NetworkPreset::Custom, Some(base)) => {
+ s.custom_base = NetworkPreset::parse(base).map_err(|e| Error::invalid(e.0))?;
+ }
+ (_, Some(_)) => {
+ return Err(Error::invalid(format!(
+ "network {w:?}: only localhost takes ports (localhost:5432,3000) and only \
+ custom a base (custom:none)"
+ )));
+ }
+ }
+ s.custom = crate::egress::EgressPolicy {
+ allow: allow.to_vec(),
+ deny: deny.to_vec(),
+ };
+ // Lists on internet or none make it custom from that base.
+ if !s.custom.is_empty() && matches!(preset, NetworkPreset::Internet | NetworkPreset::None) {
+ s.custom_base = preset;
+ s.preset = NetworkPreset::Custom;
+ }
+ s.validate().map_err(|e| Error::invalid(e.0))?;
+ Ok(s)
+}
+
+/// Refuses settings an agent (an MCP call) may not choose: anything that
+/// opens more than Internet only (`localhost`, `lan`, `unprotected`, an
+/// allow past the default blocks), or, with `current`, more than the Space
+/// has now. Opening more is the user's to do, in the app or the CLI.
+pub fn refuse_widening_by_agent(
+ settings: &NetworkSettings,
+ current: Option<&NetworkSettings>,
+) -> Result<()> {
+ let user_only = |what: &str| {
+ Err(Error::invalid(format!(
+ "{what} is the user's to choose: ask them to run `cua network set` (or use the app)"
+ )))
+ };
+ if !settings.widenings().is_empty() {
+ return user_only("Opening more than Internet only");
+ }
+ if let Some(current) = current {
+ // No more open than now: cutting it down to what the Space has now
+ // changes nothing.
+ let ctx = NetworkContext::default();
+ let want = compile_mode(settings, &ctx, Mode::Secure).map_err(|e| Error::invalid(e.0))?;
+ let within = compile_mode(&settings.intersect(current), &ctx, Mode::Secure)
+ .map_err(|e| Error::invalid(e.0))?;
+ if want != within {
+ return user_only("Opening more than the Space has now");
+ }
+ }
+ Ok(())
+}
+
+/// The settings a parent Space has: its own, or what it would migrate to.
+pub(crate) fn settings_of(meta: Option<&SpaceMeta>) -> NetworkSettings {
+ match meta {
+ Some(m) => m.network.clone().unwrap_or_else(|| migrate_meta(m, false)),
+ None => NetworkSettings::internet(),
+ }
+}
+
+/// [`CreateNetwork`] from what a create asks (`asked`), the parent's id
+/// and record (if any) and `widen`.
+pub(crate) fn resolve_create(
+ asked: NetworkSettings,
+ parent: Option<(String, Option<SpaceMeta>)>,
+ widen: bool,
+) -> Result<CreateNetwork> {
+ asked.validate().map_err(|e| Error::invalid(e.0))?;
+ let Some((parent_id, parent_meta)) = parent else {
+ if widen {
+ return Err(Error::invalid(
+ "widen goes with parent: only a child Space can be allowed more than its parent",
+ ));
+ }
+ return Ok(CreateNetwork {
+ settings: asked,
+ parent: None,
+ root: None,
+ depth: 0,
+ });
+ };
+ let root = parent_meta
+ .as_ref()
+ .and_then(|m| m.root.clone())
+ .unwrap_or_else(|| parent_id.clone());
+ let theirs = settings_of(parent_meta.as_ref());
+ let settings = if widen {
+ NetworkSettings {
+ widened_by: Some(widened_stamp()),
+ ..asked
+ }
+ } else {
+ asked.intersect(&theirs)
+ };
+ Ok(CreateNetwork {
+ settings,
+ depth: parent_meta.as_ref().map_or(0, |m| m.depth) + 1,
+ parent: Some(parent_id),
+ root: Some(root),
+ })
+}
+
+impl Spaces {
+ /// The network a create asks for, intersected with its parent's.
+ pub(crate) fn create_network(&self, opts: &crate::SpaceCreate) -> Result<CreateNetwork> {
+ let asked = opts.network_settings.clone().unwrap_or_else(|| {
+ NetworkSettings::from_legacy(
+ &opts.egress,
+ opts.network == cua_sandbox_core::NetworkMode::None,
+ )
+ });
+ let parent = match opts.parent.as_deref().map(str::trim) {
+ None | Some("") => None,
+ Some(p) => {
+ let id = self.resolve(p)?.to_string();
+ if self.inner.registry.get(&id)?.is_none()
+ && self.inner.registry.meta(&id).is_none()
+ {
+ return Err(Error::NotFound(format!("parent {p}")));
+ }
+ let meta = self.inner.registry.meta(&id);
+ // Not deeper than its tree allows.
+ let root_meta = match meta.as_ref().and_then(|m| m.root.clone()) {
+ Some(r) => self.inner.registry.meta(&r),
+ None => meta.clone(),
+ };
+ crate::tree::child_depth(
+ p,
+ meta.as_ref().map_or(0, |m| m.depth),
+ crate::tree::depth_limit(root_meta.as_ref()),
+ )?;
+ Some((id, meta))
+ }
+ };
+ resolve_create(asked, parent, opts.widen)
+ }
+
+ /// Records what a create resolved on the new Space.
+ pub(crate) fn record_network(&self, id: &str, net: &CreateNetwork) -> Result<()> {
+ self.inner.registry.update_meta(id, |m| {
+ m.network = Some(net.settings.clone());
+ m.network_generation = m.network_generation.saturating_add(1).max(1);
+ m.parent = net.parent.clone();
+ m.root = net.root.clone();
+ m.depth = net.depth;
+ if let Some(p) = &net.parent {
+ m.origin = Some(crate::tree::ORIGIN_CHILD.into());
+ m.labels.insert(crate::tree::PARENT_LABEL.into(), p.clone());
+ }
+ })
+ }
+
+ /// A Space's network: its settings, a note on why it differs from
+ /// them, and whether an update changed them. `None` for a Space with
+ /// no record here.
+ pub fn network(&self, space: &str) -> Result<Option<SpaceNetwork>> {
+ let id = self.resolve(space)?.to_string();
+ Ok(self.inner.registry.meta(&id).map(|m| SpaceNetwork {
+ settings: settings_of(Some(&m)),
+ note: m.network_note.clone(),
+ notice_pending: m.network_notice_pending || m.network.is_none(),
+ }))
+ }
+
+ /// Moves a Space from before network settings to them (at its next
+ /// start): its old egress policy becomes `custom`, nothing becomes
+ /// `internet`, and a one-time notice is left. A Space that has them is
+ /// left as it is. Returns its settings.
+ pub(crate) fn migrate_network(&self, id: &str) -> Result<NetworkSettings> {
+ let Some(meta) = self.inner.registry.meta(id) else {
+ // Nothing recorded: nothing it was created with but the
+ // default.
+ let s = NetworkSettings::internet();
+ self.inner.registry.update_meta(id, |m| {
+ m.network = Some(s.clone());
+ m.network_generation = 1;
+ m.network_notice_pending = true;
+ })?;
+ return Ok(s);
+ };
+ if let Some(s) = meta.network {
+ return Ok(s);
+ }
+ let s = migrate_meta(&meta, false);
+ self.inner.registry.update_meta(id, |m| {
+ m.network = Some(s.clone());
+ m.network_generation = m.network_generation.saturating_add(1);
+ m.network_notice_pending = true;
+ })?;
+ tracing::info!(space = %id, preset = %s.preset, "moved a Space to network settings");
+ Ok(s)
+ }
+
+ /// Replaces a Space's network settings. A child's are intersected with
+ /// its parent's (no more open) unless `widen`, which records who widened
+ /// it. With `tree`, its children get the new settings too (each
+ /// intersected with its own parent's). Says whether they hold now or
+ /// from its next start. A Space on this computer only: a Space another
+ /// machine runs keeps its settings there.
+ pub async fn set_network(
+ &self,
+ space: &str,
+ settings: &NetworkSettings,
+ widen: bool,
+ tree: bool,
+ ) -> Result<cua_vmm::network::Applied> {
+ settings.validate().map_err(|e| Error::invalid(e.0))?;
+ // Changing a Space's network is part of the experiment.
+ if Mode::from_env() == Mode::Legacy {
+ return Err(Error::invalid(
+ cua_vmm::experiments::Gate::SecureSpaces.off_message(),
+ ));
+ }
+ let id = self.resolve(space)?;
+ let crate::SpaceId::Local { name } = &id else {
+ return Err(Error::WrongProvider {
+ op: "Changing network settings".into(),
+ provider: format!(
+ "{} (only a Space on this computer; change it on the machine that runs it)",
+ id.provider()
+ ),
+ });
+ };
+ let key = id.to_string();
+ let meta = self.inner.registry.meta(&key).unwrap_or_default();
+ let parent = meta.parent.clone().map(|p| {
+ let m = self.inner.registry.meta(&p);
+ (p, m)
+ });
+ let resolved = resolve_create(settings.clone(), parent, widen && meta.parent.is_some())?;
+ if widen && meta.parent.is_none() {
+ return Err(Error::invalid(
+ "widen goes with a child Space: a top-level Space has no parent to stay within",
+ ));
+ }
+ let applied = self
+ .inner
+ .sandboxes
+ .set_network(name, &resolved.settings)
+ .await
+ .map_err(crate::egress::sandbox_error)?;
+ let backend = self
+ .inner
+ .sandboxes
+ .connect(name)
+ .await
+ .ok()
+ .map(|sb| sb.runtime_type().to_string());
+ let note = backend.and_then(|b| note_for(&b, &resolved.settings));
+ self.inner.registry.update_meta(&key, |m| {
+ m.network = Some(resolved.settings.clone());
+ m.network_generation = m.network_generation.saturating_add(1);
+ m.network_note = note;
+ m.network_notice_pending = false;
+ m.egress = resolved.settings.custom.clone();
+ })?;
+ // Its children stay within it: each keeps its own settings, intersected
+ // with the new ones (a child someone widened keeps that), or with
+ // `tree` takes the new ones.
+ for child in crate::tree::children_of(&self.inner.registry.all_meta(), &key) {
+ let current = self.inner.registry.meta(&child);
+ let widened = current
+ .as_ref()
+ .and_then(|m| m.network.as_ref())
+ .is_some_and(|n| n.widened_by.is_some());
+ if widened && !tree {
+ continue;
+ }
+ let child_settings = if tree {
+ settings.clone()
+ } else {
+ settings_of(current.as_ref())
+ };
+ Box::pin(self.set_network(&child, &child_settings, false, tree)).await?;
+ }
+ Ok(applied)
+ }
+
+ /// A Space's network as `cua network show` says it.
+ pub async fn network_info(&self, space: &str) -> Result<NetworkInfo> {
+ let id = self.resolve(space)?;
+ let key = id.to_string();
+ let meta = self.inner.registry.meta(&key);
+ let settings = settings_of(meta.as_ref());
+ let (enforcement, point) = match &id {
+ crate::SpaceId::Local { name } => match self.inner.sandboxes.connect(name).await {
+ Ok(sb) => enforcement_of(sb.runtime_type(), &settings),
+ Err(_) => (String::new(), String::new()),
+ },
+ _ => (
+ String::new(),
+ "kept by the machine that runs it".to_string(),
+ ),
+ };
+ Ok(NetworkInfo {
+ summary: settings.summary(),
+ widenings: settings.widenings(),
+ enforcement,
+ point,
+ note: meta.as_ref().and_then(|m| m.network_note.clone()),
+ parent: meta.as_ref().and_then(|m| m.parent.clone()),
+ root: meta.as_ref().and_then(|m| m.root.clone()),
+ always_blocked: ALWAYS_BLOCKED.iter().map(|s| s.to_string()).collect(),
+ notice_pending: meta
+ .as_ref()
+ .is_some_and(|m| m.network_notice_pending || m.network.is_none()),
+ settings,
+ })
+ }
+
+ /// Clears a Space's one-time notice (the CLI or app showed it).
+ pub fn ack_network_notice(&self, space: &str) -> Result<()> {
+ let id = self.resolve(space)?.to_string();
+ self.inner
+ .registry
+ .update_meta(&id, |m| m.network_notice_pending = false)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn one_word_networks() {
+ let p = |w: &str| parse_network(w, &[], &[]);
+ assert_eq!(p("").unwrap(), NetworkSettings::internet());
+ assert_eq!(p("default").unwrap(), NetworkSettings::internet());
+ assert_eq!(p("none").unwrap(), NetworkSettings::none());
+ let l = p("localhost:5432, 3000").unwrap();
+ assert_eq!(l.localhost_ports, [5432, 3000]);
+ assert!(p("localhost:all").unwrap().all_localhost_ports);
+ assert!(p("localhost").is_err(), "ports are needed");
+ assert!(p("localhost:0").is_err());
+ assert_eq!(p("custom:none").unwrap().custom_base, NetworkPreset::None);
+ assert!(p("lan:5432").is_err());
+ assert!(p("open").is_err());
+ let c = parse_network("internet", &["10.0.5.0/24".into()], &[]).unwrap();
+ assert_eq!(
+ (c.preset, c.custom_base),
+ (NetworkPreset::Custom, NetworkPreset::Internet)
+ );
+ let c = parse_network("none", &["1.1.1.1".into()], &[]).unwrap();
+ assert_eq!(
+ (c.preset, c.custom_base),
+ (NetworkPreset::Custom, NetworkPreset::None)
+ );
+ let e = parse_network("internet", &["pypi.org".into()], &[]).unwrap_err();
+ assert!(e.to_string().contains("by IP/CIDR"), "{e}");
+ }
+
+ #[test]
+ fn agents_only_tighten() {
+ let internet = NetworkSettings::internet();
+ assert!(refuse_widening_by_agent(&internet, None).is_ok());
+ assert!(refuse_widening_by_agent(&NetworkSettings::none(), Some(&internet)).is_ok());
+ let lan = NetworkSettings::preset(NetworkPreset::Lan);
+ let e = refuse_widening_by_agent(&lan, None).unwrap_err();
+ assert!(e.to_string().contains("cua network set"), "{e}");
+ assert!(
+ refuse_widening_by_agent(&NetworkSettings::preset(NetworkPreset::Unprotected), None)
+ .is_err()
+ );
+ let one = parse_network("custom", &["1.1.1.1".into()], &["all".into()]).unwrap();
+ assert!(
+ refuse_widening_by_agent(&one, Some(&internet)).is_ok(),
+ "tighter: {:?}",
+ refuse_widening_by_agent(&one, Some(&internet))
+ );
+ assert!(
+ refuse_widening_by_agent(&internet, Some(&one)).is_err(),
+ "wider than now"
+ );
+ let deny = parse_network("internet", &[], &["8.8.8.8".into()]).unwrap();
+ assert!(refuse_widening_by_agent(&deny, Some(&internet)).is_ok());
+ let private = parse_network("internet", &["10.0.5.0/24".into()], &[]).unwrap();
+ assert!(
+ refuse_widening_by_agent(&private, None).is_err(),
+ "a LAN allow"
+ );
+ }
+
+ #[test]
+ fn notes_and_provider_refusals_in_plain_words() {
+ if Mode::from_env() == Mode::Legacy {
+ return;
+ }
+ let internet = NetworkSettings::internet();
+ assert_eq!(note_for("docker", &internet), None);
+ assert_eq!(note_for("unknown", &internet), None);
+ if cfg!(target_os = "macos") {
+ assert_eq!(note_for("vz", &internet).as_deref(), Some(NO_NETWORK_NOTE));
+ }
+ let open = NetworkSettings::preset(NetworkPreset::Unprotected);
+ assert_eq!(
+ note_for("docker", &open),
+ None,
+ "enforced: its platform denies hold"
+ );
+ let e = refuse_on_provider(&internet).unwrap_err();
+ assert_eq!(e.tag(), "invalid_argument");
+ assert!(e.to_string().contains("No protection"), "{e}");
+ assert!(refuse_on_provider(&open).is_ok());
+ for w in [
+ "qemu",
+ "docker",
+ "gvisor",
+ "vz",
+ "lume",
+ "firecracker",
+ "containerization",
+ ] {
+ assert!(backend_kind(w).is_some(), "{w}");
+ }
+ }
+
+ fn meta(allow: &[&str], deny: &[&str]) -> SpaceMeta {
+ SpaceMeta {
+ egress: crate::egress::EgressPolicy {
+ allow: allow.iter().map(|s| s.to_string()).collect(),
+ deny: deny.iter().map(|s| s.to_string()).collect(),
+ },
+ ..Default::default()
+ }
+ }
+
+ /// Old `space-meta.json` entries become the expected settings.
+ #[test]
+ fn migration_fixtures() {
+ let old: std::collections::BTreeMap<String, SpaceMeta> = serde_json::from_str(
+ r#"{
+ "local:plain": {"labels": {"team": "a"}, "created_at_unix": 5},
+ "local:policy": {"egress": {"allow": ["192.168.1.0/24"], "deny": ["all"]}},
+ "local:allow-only": {"egress": {"allow": ["10.0.0.5"]}}
+ }"#,
+ )
+ .unwrap();
+ for m in old.values() {
+ assert!(m.network.is_none(), "from before network settings");
+ }
+ assert_eq!(
+ migrate_meta(&old["local:plain"], false),
+ NetworkSettings::internet()
+ );
+ assert_eq!(
+ migrate_meta(&old["local:plain"], true),
+ NetworkSettings::none()
+ );
+ let p = migrate_meta(&old["local:policy"], false);
+ assert_eq!(p.preset, NetworkPreset::Custom);
+ assert_eq!(p.custom.allow, ["192.168.1.0/24"]);
+ assert_eq!(p.custom.deny, ["all"]);
+ assert_eq!(
+ p.widenings(),
+ ["Allows your local network (192.168.1.0/24)"]
+ );
+ let a = migrate_meta(&old["local:allow-only"], false);
+ assert_eq!(a.widenings(), ["Allows your local network (10.0.0.5/32)"]);
+ // A new file round-trips with its settings.
+ let mut m = old["local:plain"].clone();
+ m.network = Some(NetworkSettings::none());
+ m.network_generation = 1;
+ let back: SpaceMeta = serde_json::from_str(&serde_json::to_string(&m).unwrap()).unwrap();
+ assert_eq!(back, m);
+ }
+
+ #[test]
+ fn wire_forms_round_trip_and_are_checked() {
+ let s = NetworkSettings {
+ preset: NetworkPreset::Localhost,
+ localhost_ports: vec![5432, 3000],
+ custom: crate::egress::EgressPolicy {
+ allow: vec!["1.1.1.1".into()],
+ deny: vec!["8.8.8.8".into()],
+ },
+ widened_by: Some("me@now".into()),
+ ..Default::default()
+ };
+ assert_eq!(from_pb(&to_pb(&s)).unwrap(), s);
+ assert_eq!(from_host_pb(&to_host_pb(&s)).unwrap(), s);
+ let none_base = NetworkSettings {
+ preset: NetworkPreset::Custom,
+ custom_base: NetworkPreset::None,
+ ..Default::default()
+ };
+ assert_eq!(to_pb(&none_base).custom_base, "none");
+ assert_eq!(from_pb(&to_pb(&none_base)).unwrap(), none_base);
+ // Empty is internet.
+ assert_eq!(
+ from_pb(&dpb::NetworkSettings::default()).unwrap(),
+ NetworkSettings::internet()
+ );
+ let bad = |p: dpb::NetworkSettings| from_pb(&p).unwrap_err().tag();
+ assert_eq!(
+ bad(dpb::NetworkSettings {
+ preset: "open".into(),
+ ..Default::default()
+ }),
+ "invalid_argument"
+ );
+ assert_eq!(
+ bad(dpb::NetworkSettings {
+ preset: "localhost".into(),
+ localhost_ports: vec![70000],
+ ..Default::default()
+ }),
+ "invalid_argument"
+ );
+ assert_eq!(
+ bad(dpb::NetworkSettings {
+ preset: "localhost".into(),
+ ..Default::default()
+ }),
+ "invalid_argument"
+ );
+ assert_eq!(
+ bad(dpb::NetworkSettings {
+ deny: vec!["example.com".into()],
+ ..Default::default()
+ }),
+ "invalid_argument"
+ );
+ }
+
+ #[test]
+ fn a_child_gets_the_intersection_unless_widened() {
+ let parent = SpaceMeta {
+ network: Some(NetworkSettings::none()),
+ ..Default::default()
+ };
+ let c = resolve_create(
+ NetworkSettings::preset(NetworkPreset::Lan),
+ Some(("local:p".into(), Some(parent.clone()))),
+ false,
+ )
+ .unwrap();
+ assert_eq!(c.settings, NetworkSettings::none());
+ assert_eq!(c.parent.as_deref(), Some("local:p"));
+ assert_eq!(c.root.as_deref(), Some("local:p"));
+ // A grandchild keeps the root.
+ let child = SpaceMeta {
+ network: Some(NetworkSettings::internet()),
+ parent: Some("local:p".into()),
+ root: Some("local:p".into()),
+ ..Default::default()
+ };
+ let g = resolve_create(
+ NetworkSettings::internet(),
+ Some(("local:c".into(), Some(child))),
+ false,
+ )
+ .unwrap();
+ assert_eq!(g.root.as_deref(), Some("local:p"));
+ assert_eq!(g.depth, 1, "the parent record says depth 0 here");
+ // Widened: what it asked, stamped.
+ let w = resolve_create(
+ NetworkSettings::preset(NetworkPreset::Lan),
+ Some(("local:p".into(), Some(parent))),
+ true,
+ )
+ .unwrap();
+ assert_eq!(w.settings.preset, NetworkPreset::Lan);
+ assert!(
+ w.settings
+ .widened_by
+ .as_deref()
+ .is_some_and(|s| s.contains('@'))
+ );
+ // A parent from before network settings counts as its migration.
+ let old = meta(&[], &["all"]);
+ let c = resolve_create(
+ NetworkSettings::internet(),
+ Some(("local:old".into(), Some(old))),
+ false,
+ )
+ .unwrap();
+ assert!(c.settings.custom.deny.contains(&"all".to_string()));
+ // No parent: as asked; widen alone is refused.
+ assert_eq!(
+ resolve_create(NetworkSettings::none(), None, false)
+ .unwrap()
+ .settings,
+ NetworkSettings::none()
+ );
+ assert_eq!(
+ resolve_create(NetworkSettings::none(), None, true)
+ .unwrap_err()
+ .tag(),
+ "invalid_argument"
+ );
+ }
+}
diff --git a/libs/cua/crates/cua-spaces/src/registry.rs b/libs/cua/crates/cua-spaces/src/registry.rs
index f8635546ea..726e45156d 100644
--- a/libs/cua/crates/cua-spaces/src/registry.rs
+++ b/libs/cua/crates/cua-spaces/src/registry.rs
@@ -63,6 +63,46 @@ pub struct SpaceMeta {
/// keeps the one it was created with. Its id never changes.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub display_name: String,
+ /// Its network settings ([`crate::network`]). `None`: a Space created
+ /// before they existed; it gets them, migrated from `egress`, on its
+ /// next start.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub network: Option<crate::network::NetworkSettings>,
+ /// How many times `network` was set (0: never).
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub network_generation: u64,
+ /// Why its network is not what was asked, in plain words (a runtime
+ /// that can't protect it yet started it without network).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub network_note: Option<String>,
+ /// Its settings were changed by an update (an old Space moved to the
+ /// new defaults): the CLI and apps say so once.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub network_notice_pending: bool,
+ /// The Space it was created from (a child), by canonical id.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub parent: Option<String>,
+ /// The top-level Space of its tree, by canonical id (`None` for a
+ /// top-level Space, which is its own root).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub root: Option<String>,
+ /// How far below its tree's top-level Space it is ([`crate::tree`]): 0
+ /// for a top-level Space, 1 for its children, ...
+ #[serde(default, skip_serializing_if = "is_zero_u32")]
+ pub depth: u32,
+ /// How it was made: `user`, `child` or `fork-batch:<id>`; `None` is
+ /// `user` for a top-level Space and `child` for one with a parent.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub origin: Option<String>,
+ /// On a top-level Space: how deep its tree may go
+ /// ([`crate::tree::DEFAULT_DEPTH_LIMIT`] when unset, never more than
+ /// [`crate::tree::MAX_DEPTH`]).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub depth_limit: Option<u32>,
+}
+
+fn is_zero_u32(n: &u32) -> bool {
+ *n == 0
}
fn is_zero(n: &u64) -> bool {
@@ -249,6 +289,21 @@ impl Registry {
self.write_meta(&all)
}
+ /// Changes what is kept about every Space at once (atomic; empty
+ /// records are dropped), returning what `change` returns.
+ pub fn update_all_meta<R>(
+ &self,
+ change: impl FnOnce(&mut BTreeMap<String, SpaceMeta>) -> R,
+ ) -> Result<R> {
+ let _g = self.lock.lock().expect("registry lock");
+ let _file = self.exclusive()?;
+ let mut all = self.read_meta();
+ let out = change(&mut all);
+ all.retain(|_, m| *m != SpaceMeta::default());
+ self.write_meta(&all)?;
+ Ok(out)
+ }
+
/// Gives Space `to` the labels and egress policy of Space `from` (a
/// fork starts as its source was; its creation time and lifetime are
/// its own). Returns whether `from` had any.
@@ -263,6 +318,17 @@ impl Registry {
let kept = all.entry(to).or_default();
kept.labels = source.labels;
kept.egress = source.egress;
+ // A fork has its source's network and stays in its source's tree.
+ if source.network.is_some() {
+ kept.network = source.network;
+ kept.network_generation = kept.network_generation.max(1);
+ }
+ kept.parent = source.parent;
+ kept.root = source.root;
+ kept.depth = source.depth;
+ if kept.parent.is_some() {
+ kept.origin = source.origin;
+ }
self.write_meta(&all)?;
Ok(true)
}
@@ -667,6 +733,11 @@ mod tests {
m.labels.insert("team".into(), "research".into());
m.created_at_unix = 100;
m.egress.deny.push("all".into());
+ m.network = Some(crate::network::NetworkSettings::none());
+ m.network_generation = 3;
+ m.parent = Some("local:p".into());
+ m.root = Some("local:p".into());
+ m.depth = 1;
})
.unwrap();
reg.update_meta("local:fork", |m| m.created_at_unix = 200)
@@ -675,6 +746,15 @@ mod tests {
let fork = reg.meta("local:fork").unwrap();
assert_eq!(fork.labels["team"], "research");
assert_eq!(fork.egress.deny, ["all"]);
+ assert_eq!(fork.network, Some(crate::network::NetworkSettings::none()));
+ assert_eq!(fork.network_generation, 1, "its own generation");
+ assert_eq!(
+ fork.parent.as_deref(),
+ Some("local:p"),
+ "it stays in the tree"
+ );
+ assert_eq!(fork.root.as_deref(), Some("local:p"));
+ assert_eq!(fork.depth, 1);
assert_eq!(fork.created_at_unix, 200, "its own creation time");
// The source is untouched, and a source with nothing gives nothing.
assert_eq!(reg.meta("local:src").unwrap().created_at_unix, 100);
diff --git a/libs/cua/crates/cua-spaces/src/space.rs b/libs/cua/crates/cua-spaces/src/space.rs
index 510aae59b9..ae244db4e7 100644
--- a/libs/cua/crates/cua-spaces/src/space.rs
+++ b/libs/cua/crates/cua-spaces/src/space.rs
@@ -708,6 +708,15 @@ pub struct SpaceInfo {
/// one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub egress_enforced: Option<crate::egress::Enforcement>,
+ /// Its network settings ([`crate::network`]), with a note when its
+ /// network is not what was asked. `None` when this computer keeps no
+ /// record of it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub network: Option<crate::network::SpaceNetwork>,
+ /// Its place in a tree of Spaces ([`crate::tree`]): `None` for a
+ /// top-level Space with nothing recorded about it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tree: Option<crate::tree::TreeLink>,
/// A Space that is a machine on the relay: who owns it and who else
/// has it, as this account sees it ([`crate::sharing`]). `None` for
/// other Spaces.
@@ -768,6 +777,25 @@ impl SpaceInfo {
on_expire: String::new(),
egress: Default::default(),
egress_enforced: None,
+ network: record
+ .network_settings
+ .as_ref()
+ .and_then(|p| crate::network::from_pb(p).ok())
+ .map(|settings| crate::network::SpaceNetwork {
+ settings,
+ note: (!record.network_note.is_empty()).then(|| record.network_note.clone()),
+ notice_pending: record.network_notice_pending,
+ }),
+ tree: (!record.parent.is_empty()).then(|| crate::tree::TreeLink {
+ parent: Some(record.parent.clone()),
+ root: (!record.root.is_empty()).then(|| record.root.clone()),
+ depth: record.depth,
+ origin: if record.origin.is_empty() {
+ crate::tree::ORIGIN_CHILD.into()
+ } else {
+ record.origin.clone()
+ },
+ }),
created_at_unix: record
.added_at
.as_ref()
diff --git a/libs/cua/crates/cua-spaces/src/space_jobs.rs b/libs/cua/crates/cua-spaces/src/space_jobs.rs
new file mode 100644
index 0000000000..8faf1d7130
--- /dev/null
+++ b/libs/cua/crates/cua-spaces/src/space_jobs.rs
@@ -0,0 +1,1197 @@
+//! Background jobs in a Space: a long command (a build, a test suite, a wait
+//! on CI) that outlives the call that started it, the connection and a restart
+//! of the Space's daemon.
+//!
+//! Every operation is one shell run through the Space's spacesd, so a job
+//! behaves the same on every runtime (container, gVisor, microVM, VM, cloud)
+//! and in images that shipped before jobs existed. Nothing here is specific to
+//! a runtime.
+//!
+//! A job is a directory in the Space, `$HOME/.cua/jobs/<id>`:
+//!
+//! | file | |
+//! | --- | --- |
+//! | `cmd.sh`, `cmdline`, `name` | what runs, as written, and its label |
+//! | `run.sh` | the runner: starts `cmd.sh` as a background child in its own process group, enforces `timeout`, records the end |
+//! | `runner.pid`, `child.pid`, `started` | liveness and timing (unix seconds) |
+//! | `log` | stdout and stderr together |
+//! | `exit` | `<code> <ended>`, written atomically when the command ends |
+//! | `cancelled`, `timedout` | markers that say why it ended |
+//!
+//! The runner is started detached (`setsid` where it exists), so it is not a
+//! child of the shell that started it or of cua-spacesd. The state is derived
+//! from the files: `running`, `exited`, `cancelled`, `timed_out`, or `lost`
+//! (the runner is gone and left no `exit`, for example after a reboot).
+//!
+//! The runner and the helper scripts are POSIX `sh`: Linux and macOS guests.
+//! A Windows guest is refused with `unsupported`.
+
+use std::collections::BTreeMap;
+use std::time::Duration;
+
+use cua_spaces_contract::inputs as i;
+use serde::Serialize;
+use serde_json::{Value, json};
+
+use crate::error::{Error, Result};
+use crate::space::Space;
+
+/// Most bytes one `logs` call returns.
+pub const MAX_LOG_BYTES: u64 = 256 * 1024;
+/// Bytes of log a `logs` call returns by default (and `status` shows).
+pub const DEFAULT_LOG_BYTES: u64 = 16_000;
+/// Longest `follow_ms` (the thread's bound).
+pub const MAX_FOLLOW_MS: u64 = 25_000;
+/// Jobs `list` shows.
+pub const MAX_LISTED: usize = 50;
+/// Longest label kept.
+const MAX_NAME: usize = 80;
+/// Jobs that ended this many days ago are removed when a job starts.
+pub const KEEP_DAYS: u32 = 7;
+/// Separates the header from the log bytes in a script's output.
+const LOG_MARK: &str = "\n---CUA-LOG---\n";
+/// Separates jobs in a listing.
+const ROW_MARK: &str = "---CUA-JOB---";
+
+/// The states of a job.
+pub const STATES: &[&str] = &["running", "exited", "cancelled", "timed_out", "lost"];
+
+/// What a job is doing, from its files.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
+pub struct JobStatus {
+ /// The job id.
+ pub job: String,
+ /// The label (empty when none).
+ pub name: String,
+ /// One of [`STATES`].
+ pub state: String,
+ /// The exit code, once it ended.
+ pub exit_code: Option<i32>,
+ /// The signal that ended it (`15` for TERM), when it was one.
+ pub signal: Option<i32>,
+ /// Unix seconds it started.
+ pub started_at: Option<u64>,
+ /// Unix seconds it ended.
+ pub ended_at: Option<u64>,
+ /// Seconds from start to end (or to now while it runs).
+ pub elapsed_s: u64,
+ /// Bytes in the log.
+ pub size: u64,
+ /// The command line, cut to one line.
+ pub command: String,
+}
+
+impl JobStatus {
+ /// Whether the job has ended (any state but `running`).
+ pub fn finished(&self) -> bool {
+ self.state != "running"
+ }
+
+ /// `1h02m03s`, `4m10s` or `9s`.
+ pub fn elapsed_text(&self) -> String {
+ elapsed_text(self.elapsed_s)
+ }
+}
+
+/// `1h02m03s`, `4m10s` or `9s`.
+pub fn elapsed_text(s: u64) -> String {
+ match (s / 3600, s / 60 % 60, s % 60) {
+ (0, 0, s) => format!("{s}s"),
+ (0, m, s) => format!("{m}m{s:02}s"),
+ (h, m, s) => format!("{h}h{m:02}m{s:02}s"),
+ }
+}
+
+/// A chunk of a job's log.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct JobLogs {
+ /// The job at the time of the read.
+ pub status: JobStatus,
+ /// Where `text` starts.
+ pub offset: u64,
+ /// Where to read on from.
+ pub next_offset: u64,
+ /// The bytes read (lossy UTF-8).
+ pub text: String,
+ /// More log exists after `next_offset`.
+ pub more: bool,
+}
+
+// --------------------------------------------------------------- scripts
+
+/// Shared shell functions: where jobs live and how a job's state reads from
+/// its files.
+const PRELUDE: &str = r#"
+J="${HOME:-/tmp}/.cua/jobs"
+now() { date +%s; }
+alive() {
+ kill -0 "$1" 2>/dev/null || return 1
+ if [ -r "/proc/$1/stat" ]; then
+ z=$(sed 's/.*) //' "/proc/$1/stat" 2>/dev/null | cut -c1)
+ case "$z" in Z|X) return 1 ;; esac
+ fi
+ return 0
+}
+show() {
+ D="$J/$1"
+ if [ ! -d "$D" ]; then printf 'job=%s\nstate=notfound\n' "$1"; return; fi
+ state=lost; code=; ended=
+ # The runner writes `exit` and then ends, so look at `exit` again after
+ # finding the runner gone: it may have finished between the two looks.
+ p=$(cat "$D/runner.pid" 2>/dev/null)
+ if [ ! -f "$D/exit" ] && [ -n "$p" ] && alive "$p"; then
+ state=running
+ elif [ -f "$D/exit" ]; then
+ read code ended < "$D/exit"
+ if [ -f "$D/cancelled" ]; then state=cancelled
+ elif [ -f "$D/timedout" ]; then state=timed_out
+ else state=exited; fi
+ fi
+ started=$(cat "$D/started" 2>/dev/null)
+ size=$(wc -c < "$D/log" 2>/dev/null | tr -d ' ')
+ printf 'job=%s\nstate=%s\ncode=%s\nstarted=%s\nended=%s\nsize=%s\nnow=%s\n' "$1" "$state" "$code" "$started" "$ended" "${size:-0}" "$(now)"
+ printf 'name=%s\n' "$(head -n 1 "$D/name" 2>/dev/null)"
+ printf 'command=%s\n' "$(head -n 1 "$D/cmdline" 2>/dev/null | cut -c1-160)"
+}
+"#;
+
+/// The runner. `run.sh DIR TIMEOUT_SECONDS`.
+const RUNNER: &str = r#"#!/bin/sh
+D=$1
+T=$2
+cd "$D" || exit 1
+echo $$ > runner.pid
+trap '' HUP
+set -m 2>/dev/null
+sh ./cmd.sh > log 2>&1 < /dev/null &
+child=$!
+echo "$child" > child.pid
+date +%s > started.tmp && mv started.tmp started
+wd=
+if [ -n "$T" ] && [ "$T" -gt 0 ] 2>/dev/null; then
+ (
+ sleep "$T"
+ : > timedout
+ kill -s TERM -- "-$child" 2>/dev/null || kill -s TERM "$child" 2>/dev/null
+ sleep 5
+ kill -s KILL -- "-$child" 2>/dev/null || kill -s KILL "$child" 2>/dev/null
+ ) &
+ wd=$!
+fi
+wait "$child"
+code=$?
+[ -n "$wd" ] && { kill -s KILL -- "-$wd" 2>/dev/null || kill -s KILL "$wd" 2>/dev/null; }
+printf '%s %s\n' "$code" "$(date +%s)" > exit.tmp && mv exit.tmp exit
+"#;
+
+/// Single-quotes `s` for a POSIX shell.
+pub fn sh_quote(s: &str) -> String {
+ format!("'{}'", s.replace('\'', r"'\''"))
+}
+
+fn one_line(s: &str, max: usize) -> String {
+ let flat: String = s
+ .chars()
+ .map(|c| if c.is_control() { ' ' } else { c })
+ .collect();
+ flat.trim().chars().take(max).collect()
+}
+
+fn valid_env_name(k: &str) -> bool {
+ let mut c = k.chars();
+ c.next()
+ .is_some_and(|f| f.is_ascii_alphabetic() || f == '_')
+ && c.all(|c| c.is_ascii_alphanumeric() || c == '_')
+}
+
+/// Splits `owner/repo#123` into `(Some("owner/repo"), "123")`.
+fn split_pr(pr: &str) -> (Option<String>, String) {
+ match pr.split_once('#') {
+ Some((repo, n)) if repo.contains('/') && !n.is_empty() => {
+ (Some(repo.to_string()), n.to_string())
+ }
+ _ => (None, pr.to_string()),
+ }
+}
+
+/// The shell for a condition (`until`): it ends with exit 0 when the
+/// condition holds (or the `gh` exit status for `pr_checks`).
+pub fn until_script(u: &i::JobUntil) -> Result<String> {
+ let given = [
+ u.file.is_some(),
+ u.port.is_some(),
+ u.command.is_some(),
+ u.pr_checks.is_some(),
+ ]
+ .iter()
+ .filter(|b| **b)
+ .count();
+ if given != 1 {
+ return Err(Error::invalid(
+ "until: give exactly one of file, port, command or pr_checks",
+ ));
+ }
+ let every = |default: u64| u.interval.unwrap_or(default).clamp(1, 300);
+ if let Some(f) = &u.file {
+ return Ok(format!(
+ "echo {wait}\nuntil [ -e {q} ]; do sleep {n}; done\necho {found}\n",
+ wait = sh_quote(&format!("waiting for file {}", one_line(f, 200))),
+ found = sh_quote(&format!("found {}", one_line(f, 200))),
+ q = sh_quote(f),
+ n = every(5)
+ ));
+ }
+ if let Some(port) = u.port {
+ let host = u.host.as_deref().unwrap_or("127.0.0.1");
+ if host.is_empty()
+ || !host
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '_'))
+ {
+ return Err(Error::invalid(
+ "until.host: letters, digits, '.', '-', ':' and '_' only",
+ ));
+ }
+ return Ok(format!(
+ r#"port_open() {{
+ if command -v nc >/dev/null 2>&1; then nc -z -w 2 "$1" "$2" >/dev/null 2>&1
+ elif command -v bash >/dev/null 2>&1; then bash -c "exec 3<>/dev/tcp/$1/$2" >/dev/null 2>&1
+ elif command -v python3 >/dev/null 2>&1; then python3 -c "import socket,sys; socket.create_connection((sys.argv[1], int(sys.argv[2])), 2).close()" "$1" "$2" >/dev/null 2>&1
+ else return 1; fi
+}}
+echo "waiting for {host}:{port}"
+until port_open {host} {port}; do sleep {n}; done
+echo "{host}:{port} is open"
+"#,
+ n = every(5)
+ ));
+ }
+ if let Some(c) = &u.command {
+ return Ok(format!(
+ "echo {msg}\nuntil ( {c}\n) >/dev/null 2>&1; do sleep {n}; done\necho \"condition met\"\n",
+ msg = sh_quote(&format!("waiting for: {}", one_line(c, 200))),
+ n = every(5)
+ ));
+ }
+ let pr = u.pr_checks.as_deref().unwrap_or_default().trim();
+ if pr.is_empty() {
+ return Err(Error::invalid("until.pr_checks is empty"));
+ }
+ let (repo, number) = split_pr(pr);
+ let repo_flag = repo
+ .map(|r| format!(" --repo {}", sh_quote(&r)))
+ .unwrap_or_default();
+ Ok(format!(
+ r#"command -v gh >/dev/null 2>&1 || {{ echo "gh is not installed in this Space" >&2; exit 127; }}
+echo {msg}
+gh pr checks {n}{repo_flag} --required --watch --interval {iv}
+rc=$?
+gh pr checks {n}{repo_flag} --required 2>&1
+exit $rc
+"#,
+ msg = sh_quote(&format!("waiting for the required checks of {pr}")),
+ n = sh_quote(&number),
+ iv = every(30)
+ ))
+}
+
+/// A fresh job id: `j` and twelve hex digits.
+pub fn new_job_id() -> String {
+ let n: u64 = rand::random::<u64>() & 0xffff_ffff_ffff;
+ format!("j{n:012x}")
+}
+
+fn valid_job_id(id: &str) -> Result<&str> {
+ if !id.is_empty()
+ && id.len() <= 40
+ && id
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
+ {
+ Ok(id)
+ } else {
+ Err(Error::invalid(format!("job: `{id}` is not a job id")))
+ }
+}
+
+/// The shell that creates job `id` and starts its runner, detached.
+pub fn start_script(id: &str, a: &i::SpaceJob) -> Result<String> {
+ valid_job_id(id)?;
+ let body = match (&a.command, &a.until) {
+ (Some(_), Some(_)) => {
+ return Err(Error::invalid("start: give `command` or `until`, not both"));
+ }
+ (Some(c), None) if !c.trim().is_empty() => c.clone(),
+ (None, Some(u)) => until_script(u)?,
+ _ => return Err(Error::invalid("start: `command` (or `until`) is required")),
+ };
+ let mut cmd = String::new();
+ if let Some(dir) = a.cwd.as_deref().filter(|d| !d.is_empty()) {
+ cmd += &format!("cd {} || exit 126\n", sh_quote(dir));
+ }
+ for (k, v) in a.env.iter().flatten() {
+ if !valid_env_name(k) {
+ return Err(Error::invalid(format!("env: `{k}` is not a variable name")));
+ }
+ cmd += &format!("export {k}={}\n", sh_quote(v));
+ }
+ cmd += &body;
+ let label = one_line(a.name.as_deref().unwrap_or_default(), MAX_NAME);
+ let cmdline = a.command.clone().unwrap_or_else(|| {
+ format!(
+ "until {}",
+ serde_json::to_string(&a.until).unwrap_or_default()
+ )
+ });
+ let (d_cmd, d_run) = (format!("CUA_JOB_{id}_CMD"), format!("CUA_JOB_{id}_RUN"));
+ let d_line = format!("CUA_JOB_{id}_LINE");
+ for (d, text) in [(&d_cmd, &cmd), (&d_line, &cmdline)] {
+ if text.lines().any(|l| l == d) {
+ return Err(Error::invalid("the command contains a reserved word"));
+ }
+ }
+ let timeout = a.timeout.filter(|t| *t > 0).unwrap_or(0);
+ Ok(format!(
+ r#"{PRELUDE}
+D="$J/{id}"
+mkdir -p "$D" || exit 1
+for e in $(find "$J" -maxdepth 2 -name exit -mtime +{KEEP_DAYS} 2>/dev/null); do rm -rf "$(dirname "$e")"; done
+cat > "$D/cmd.sh" <<'{d_cmd}'
+{cmd}
+{d_cmd}
+cat > "$D/run.sh" <<'{d_run}'
+{RUNNER}
+{d_run}
+cat > "$D/cmdline" <<'{d_line}'
+{cmdline}
+{d_line}
+printf '%s\n' {name} > "$D/name"
+if command -v setsid >/dev/null 2>&1; then
+ setsid sh "$D/run.sh" "$D" {timeout} </dev/null >/dev/null 2>&1 &
+else
+ nohup sh "$D/run.sh" "$D" {timeout} </dev/null >/dev/null 2>&1 &
+fi
+i=0
+while [ ! -f "$D/started" ] && [ "$i" -lt 100 ]; do sleep 0.1 2>/dev/null || sleep 1; i=$((i+1)); done
+[ -f "$D/started" ] || {{ echo "the job did not start" >&2; exit 1; }}
+show {id}
+"#,
+ name = sh_quote(&label),
+ ))
+}
+
+/// The shell that reads a job's state.
+pub fn status_script(id: &str) -> Result<String> {
+ let id = valid_job_id(id)?;
+ Ok(format!("{PRELUDE}\nshow {id}\n"))
+}
+
+/// The shell that reads a job's state and then its log: from `offset`, or the
+/// last `limit` bytes without one.
+pub fn logs_script(id: &str, offset: Option<u64>, limit: u64) -> Result<String> {
+ let id = valid_job_id(id)?;
+ let read = match offset {
+ Some(o) => format!(
+ "off={o}\necho \"offset=$off\"\necho '---CUA-LOG---'\ntail -c +$((off+1)) \"$J/{id}/log\" 2>/dev/null | head -c {limit}\n"
+ ),
+ None => format!(
+ "sz=$(wc -c < \"$J/{id}/log\" 2>/dev/null | tr -d ' ')\nsz=${{sz:-0}}\nif [ \"$sz\" -gt {limit} ]; then off=$((sz-{limit})); else off=0; fi\necho \"offset=$off\"\necho '---CUA-LOG---'\ntail -c +$((off+1)) \"$J/{id}/log\" 2>/dev/null | head -c {limit}\n"
+ ),
+ };
+ Ok(format!("{PRELUDE}\nshow {id}\n{read}"))
+}
+
+/// The shell that stops a job (TERM, then KILL after a grace period) and
+/// reads its state.
+pub fn cancel_script(id: &str) -> Result<String> {
+ let id = valid_job_id(id)?;
+ Ok(format!(
+ r#"{PRELUDE}
+D="$J/{id}"
+if [ -d "$D" ] && [ ! -f "$D/exit" ]; then
+ : > "$D/cancelled"
+ c=$(cat "$D/child.pid" 2>/dev/null)
+ if [ -n "$c" ]; then
+ kill -s TERM -- "-$c" 2>/dev/null || kill -s TERM "$c" 2>/dev/null
+ i=0
+ while [ ! -f "$D/exit" ] && [ "$i" -lt 50 ]; do sleep 0.1 2>/dev/null || sleep 1; i=$((i+1)); done
+ if [ ! -f "$D/exit" ]; then
+ kill -s KILL -- "-$c" 2>/dev/null || kill -s KILL "$c" 2>/dev/null
+ i=0
+ while [ ! -f "$D/exit" ] && [ "$i" -lt 50 ]; do sleep 0.1 2>/dev/null || sleep 1; i=$((i+1)); done
+ fi
+ fi
+fi
+show {id}
+"#
+ ))
+}
+
+/// The shell that lists the jobs, newest first.
+pub fn list_script() -> String {
+ format!(
+ r#"{PRELUDE}
+for d in "$J"/*/; do
+ [ -d "$d" ] || continue
+ show "$(basename "$d")"
+ echo '{ROW_MARK}'
+done
+"#
+ )
+}
+
+// --------------------------------------------------------------- parsing
+
+fn fields(header: &str) -> BTreeMap<String, String> {
+ header
+ .lines()
+ .filter_map(|l| l.split_once('='))
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect()
+}
+
+fn status_of(f: &BTreeMap<String, String>) -> Result<JobStatus> {
+ let get = |k: &str| f.get(k).map(String::as_str).unwrap_or_default();
+ let num = |k: &str| get(k).trim().parse::<u64>().ok();
+ let state = get("state");
+ if state == "notfound" {
+ return Err(Error::NotFound(format!("job {}", get("job"))));
+ }
+ if !STATES.contains(&state) {
+ return Err(Error::Agent(format!(
+ "job {}: unreadable state `{state}`",
+ get("job")
+ )));
+ }
+ let code = get("code").trim().parse::<i32>().ok();
+ let started = num("started");
+ let ended = num("ended");
+ let now = num("now").unwrap_or(0);
+ let elapsed_s = match (started, ended) {
+ (Some(s), Some(e)) => e.saturating_sub(s),
+ (Some(s), None) => now.saturating_sub(s),
+ _ => 0,
+ };
+ Ok(JobStatus {
+ job: get("job").to_string(),
+ name: get("name").to_string(),
+ state: state.to_string(),
+ exit_code: code.filter(|c| *c <= 128),
+ signal: code.filter(|c| *c > 128).map(|c| c - 128),
+ started_at: started,
+ ended_at: ended,
+ elapsed_s,
+ size: num("size").unwrap_or(0),
+ command: get("command").to_string(),
+ })
+}
+
+/// Reads the header a status script prints.
+pub fn parse_status(out: &str) -> Result<JobStatus> {
+ status_of(&fields(out))
+}
+
+/// Reads the output of [`list_script`].
+pub fn parse_list(out: &str) -> Vec<JobStatus> {
+ let mut jobs: Vec<JobStatus> = out
+ .split(ROW_MARK)
+ .filter(|b| !b.trim().is_empty())
+ .filter_map(|b| status_of(&fields(b)).ok())
+ .collect();
+ jobs.sort_by(|a, b| b.started_at.cmp(&a.started_at).then(b.job.cmp(&a.job)));
+ jobs.truncate(MAX_LISTED);
+ jobs
+}
+
+/// Reads the output of [`logs_script`]: the header, and the log bytes after
+/// the mark.
+pub fn parse_logs(out: &[u8], limit: u64) -> Result<JobLogs> {
+ let mark = LOG_MARK.as_bytes();
+ let at = out
+ .windows(mark.len())
+ .position(|w| w == mark)
+ .ok_or_else(|| Error::Agent("job logs: no log marker in the output".into()))?;
+ let header = String::from_utf8_lossy(&out[..at]);
+ let mut body = &out[at + mark.len()..];
+ let f = fields(&header);
+ let status = status_of(&f)?;
+ let offset = f
+ .get("offset")
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .unwrap_or(0);
+ if body.len() as u64 > limit {
+ body = &body[..limit as usize];
+ }
+ let next_offset = offset + body.len() as u64;
+ Ok(JobLogs {
+ more: status.size > next_offset,
+ status,
+ offset,
+ next_offset,
+ text: String::from_utf8_lossy(body).into_owned(),
+ })
+}
+
+// -------------------------------------------------------------- the Space
+
+impl Space {
+ async fn job_run(&self, script: &str, timeout: Duration) -> Result<Vec<u8>> {
+ if self.is_windows() {
+ return Err(Error::Unsupported(
+ "space_job runs in Linux and macOS guests; this Space is Windows".into(),
+ ));
+ }
+ let out = self
+ .spacesd()?
+ .run(self.shell_command(script).timeout(timeout))
+ .await?;
+ if out.status.code != Some(0) {
+ let err = out.stderr_str();
+ return Err(Error::Agent(format!(
+ "space_job: {}",
+ if err.trim().is_empty() {
+ out.stdout_str()
+ } else {
+ err
+ }
+ .trim()
+ )));
+ }
+ Ok(out.stdout)
+ }
+
+ /// Starts a job. The command keeps running when the caller goes away.
+ pub async fn job_start(&self, a: &i::SpaceJob) -> Result<JobStatus> {
+ let id = new_job_id();
+ let script = start_script(&id, a)?;
+ let out = self.job_run(&script, Duration::from_secs(60)).await?;
+ parse_status(&String::from_utf8_lossy(&out))
+ }
+
+ /// A job's state.
+ pub async fn job_status(&self, id: &str) -> Result<JobStatus> {
+ let out = self
+ .job_run(&status_script(id)?, Duration::from_secs(30))
+ .await?;
+ parse_status(&String::from_utf8_lossy(&out))
+ }
+
+ /// Reads a job's log from `offset` (the last `limit` bytes without one).
+ /// With `follow` and nothing new after `offset` while the job runs, waits
+ /// for output or the end.
+ pub async fn job_logs(
+ &self,
+ id: &str,
+ offset: Option<u64>,
+ limit: u64,
+ follow: Duration,
+ ) -> Result<JobLogs> {
+ let limit = limit.clamp(1, MAX_LOG_BYTES);
+ let deadline =
+ tokio::time::Instant::now() + follow.min(Duration::from_millis(MAX_FOLLOW_MS));
+ loop {
+ let out = self
+ .job_run(&logs_script(id, offset, limit)?, Duration::from_secs(30))
+ .await?;
+ let logs = parse_logs(&out, limit)?;
+ let quiet = logs.text.is_empty() && !logs.status.finished();
+ if !quiet || offset.is_none() || tokio::time::Instant::now() >= deadline {
+ return Ok(logs);
+ }
+ tokio::time::sleep(Duration::from_millis(1000)).await;
+ }
+ }
+
+ /// Stops a job and returns its state.
+ pub async fn job_cancel(&self, id: &str) -> Result<JobStatus> {
+ let out = self
+ .job_run(&cancel_script(id)?, Duration::from_secs(30))
+ .await?;
+ parse_status(&String::from_utf8_lossy(&out))
+ }
+
+ /// The Space's jobs, newest first.
+ pub async fn job_list(&self) -> Result<Vec<JobStatus>> {
+ let out = self
+ .job_run(&list_script(), Duration::from_secs(30))
+ .await?;
+ Ok(parse_list(&String::from_utf8_lossy(&out)))
+ }
+
+ /// The `space_job` tool: one call, as the contract describes it.
+ pub async fn job(&self, a: &i::SpaceJob) -> Result<Value> {
+ let job = || {
+ a.job
+ .as_deref()
+ .filter(|j| !j.is_empty())
+ .ok_or_else(|| Error::invalid(format!("{}: `job` is required", a.action)))
+ };
+ match a.action.as_str() {
+ "start" => {
+ let st = self.job_start(a).await?;
+ let mut v = status_json(&st);
+ v["log_command"] = json!(format!(
+ "space_job {{action: \"logs\", job: \"{}\"}}",
+ st.job
+ ));
+ v["hint"] = json!(if a.notify.unwrap_or(false) {
+ "Running. You will be woken in the Space thread when it ends: finish your turn instead of polling. Read progress any time with action logs (offset = next_offset)."
+ } else {
+ "Running. Read progress with action logs (offset = next_offset, follow_ms to wait), or restart with notify: true to be woken when it ends."
+ });
+ Ok(v)
+ }
+ "status" => {
+ let logs = self.job_logs(job()?, None, 4096, Duration::ZERO).await?;
+ Ok(logs_json(&logs))
+ }
+ "logs" => {
+ let logs = self
+ .job_logs(
+ job()?,
+ a.offset,
+ a.limit.unwrap_or(DEFAULT_LOG_BYTES),
+ Duration::from_millis(a.follow_ms.unwrap_or(0)),
+ )
+ .await?;
+ Ok(logs_json(&logs))
+ }
+ "cancel" => Ok(status_json(&self.job_cancel(job()?).await?)),
+ "list" => {
+ let jobs = self.job_list().await?;
+ Ok(json!({"jobs": jobs.iter().map(status_json).collect::<Vec<_>>()}))
+ }
+ other => Err(Error::invalid(format!(
+ "action: `{other}` is not one of start, status, logs, cancel, list"
+ ))),
+ }
+ }
+}
+
+/// A status as the tool returns it.
+pub fn status_json(s: &JobStatus) -> Value {
+ json!({
+ "job": s.job, "name": s.name, "state": s.state, "exit_code": s.exit_code,
+ "signal": s.signal, "started_at": s.started_at, "ended_at": s.ended_at,
+ "elapsed_s": s.elapsed_s, "elapsed": s.elapsed_text(), "size": s.size,
+ "command": s.command,
+ })
+}
+
+fn logs_json(l: &JobLogs) -> Value {
+ let mut v = status_json(&l.status);
+ v["offset"] = json!(l.offset);
+ v["next_offset"] = json!(l.next_offset);
+ v["more"] = json!(l.more);
+ v["text"] = json!(l.text);
+ v
+}
+
+/// The extension operation `space_job` calls when a job starts with `notify`
+/// (`{space, job, name, wake?}`): the daemon follows the job and, when it
+/// ends, posts to the Space's thread (waking the agent the call came from, or
+/// `wake`) and tells the person.
+pub const WATCH_OP: &str = "space_job.watch";
+
+/// Registers `notify` for the job `started` (the result of `start`). The
+/// answer goes in the tool result: `{registered: true, ...}`, or
+/// `{registered: false, reason}` where nothing can follow the job (the job
+/// still runs).
+pub async fn watch(
+ spaces: &crate::Spaces,
+ space: &Space,
+ started: &Value,
+ a: &i::SpaceJob,
+) -> Value {
+ let Some(ext) = spaces.extension_for(WATCH_OP) else {
+ return json!({"registered": false,
+ "reason": "this runtime has no Cua Spaces daemon to follow the job; read it with action logs"});
+ };
+ let call = crate::extension::ToolCall {
+ spaces,
+ tool: WATCH_OP,
+ args: json!({"space": space.id().to_string(), "job": started["job"],
+ "name": started["name"], "wake": a.wake}),
+ broker: None,
+ pinned: Some(space),
+ caller: crate::extension::Caller::current(),
+ };
+ match ext.call_tool(call).await {
+ Ok(_) => json!({"registered": true}),
+ Err(e) => json!({"registered": false, "reason": e.to_string()}),
+ }
+}
+
+/// The one line that says how a job ended, the same everywhere it is posted:
+/// `JOB <id> <state> exit=<n> <elapsed> log=<size>B [name]`.
+pub fn result_line(s: &JobStatus) -> String {
+ let mut line = format!("JOB {} {}", s.job, s.state);
+ match (s.exit_code, s.signal) {
+ (Some(c), _) => line += &format!(" exit={c}"),
+ (None, Some(sig)) => line += &format!(" signal={sig}"),
+ _ => {}
+ }
+ line += &format!(" {} log={}B", s.elapsed_text(), s.size);
+ if !s.name.is_empty() {
+ line += &format!(" | {}", s.name);
+ }
+ line
+}
+
+/// The checks every runtime's Spaces must pass: the same calls, the same
+/// answers, whatever the Space runs on (container, gVisor, microVM, VM,
+/// cloud). Nothing here knows the runtime; a backend's e2e suite calls
+/// [`conformance::run`] on a Space it made.
+pub mod conformance {
+ use super::*;
+
+ async fn until_ended(space: &Space, id: &str, within: Duration) -> Result<JobStatus> {
+ let deadline = tokio::time::Instant::now() + within;
+ loop {
+ let st = space.job_status(id).await?;
+ if st.finished() {
+ return Ok(st);
+ }
+ if tokio::time::Instant::now() >= deadline {
+ return Err(Error::Timeout(format!(
+ "job {id} did not end in {within:?}"
+ )));
+ }
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+ }
+
+ fn fail(what: &str, got: impl std::fmt::Debug) -> Error {
+ Error::Agent(format!("space_job conformance: {what}: {got:?}"))
+ }
+
+ fn start(command: &str) -> i::SpaceJob {
+ i::SpaceJob {
+ action: "start".into(),
+ command: Some(command.into()),
+ ..Default::default()
+ }
+ }
+
+ /// Runs the conformance checks on `space` (a Linux or macOS guest).
+ pub async fn run(space: &Space) -> Result<()> {
+ // 1. A job returns at once, ends with its exit status, and its log
+ // reads by offset without losing or repeating a byte.
+ let t0 = tokio::time::Instant::now();
+ let st = space
+ .job_start(&start(
+ "printf 'one\\n'; sleep 1; printf 'two\\n'; echo oops >&2; exit 3",
+ ))
+ .await?;
+ if t0.elapsed() > Duration::from_secs(20) || st.state != "running" {
+ return Err(fail("start returns at once, running", &st));
+ }
+ let done = until_ended(space, &st.job, Duration::from_secs(60)).await?;
+ if (done.state.as_str(), done.exit_code) != ("exited", Some(3)) {
+ return Err(fail("exit status", &done));
+ }
+ let first = space.job_logs(&st.job, Some(0), 5, Duration::ZERO).await?;
+ let rest = space
+ .job_logs(&st.job, Some(first.next_offset), 1000, Duration::ZERO)
+ .await?;
+ let all = format!("{}{}", first.text, rest.text);
+ if !first.more || rest.more || !all.starts_with("one\ntwo\n") || !all.contains("oops") {
+ return Err(fail("log offsets", (&first, &rest)));
+ }
+ if rest.next_offset != done.size {
+ return Err(fail("next_offset reaches the log size", (&rest, &done)));
+ }
+ let tail = space.job_logs(&st.job, None, 4, Duration::ZERO).await?;
+ if tail.text != all[all.len() - 4..] {
+ return Err(fail("the end of the log without an offset", &tail));
+ }
+
+ // 2. cwd and env reach the command.
+ let mut a = start("printf '%s %s' \"$CUA_JOB_CONFORMANCE\" \"$(pwd)\"");
+ a.cwd = Some("/".into());
+ a.env = Some(BTreeMap::from([(
+ "CUA_JOB_CONFORMANCE".to_string(),
+ "it's set".to_string(),
+ )]));
+ let st = space.job_start(&a).await?;
+ until_ended(space, &st.job, Duration::from_secs(60)).await?;
+ let l = space.job_logs(&st.job, None, 100, Duration::ZERO).await?;
+ if l.text != "it's set /" {
+ return Err(fail("cwd and env", &l));
+ }
+
+ // 3. follow waits for output; cancel stops the whole tree.
+ let st = space
+ .job_start(&start("sleep 300 & sleep 300; echo never"))
+ .await?;
+ let waited = tokio::time::Instant::now();
+ let quiet = space
+ .job_logs(&st.job, Some(0), 100, Duration::from_millis(2500))
+ .await?;
+ if quiet.status.state != "running" || waited.elapsed() < Duration::from_secs(2) {
+ return Err(fail("follow waits while the job is quiet", &quiet));
+ }
+ let c = space.job_cancel(&st.job).await?;
+ if c.state != "cancelled" || c.signal != Some(15) {
+ return Err(fail("cancel", &c));
+ }
+ let again = space.job_cancel(&st.job).await?;
+ if again.state != "cancelled" {
+ return Err(fail("cancel twice", &again));
+ }
+
+ // 4. A timeout stops the job and says so.
+ let mut a = start("sleep 300");
+ a.timeout = Some(2);
+ let st = space.job_start(&a).await?;
+ let done = until_ended(space, &st.job, Duration::from_secs(60)).await?;
+ if done.state != "timed_out" {
+ return Err(fail("timeout", &done));
+ }
+
+ // 5. A condition ends the job when it holds.
+ let flag = format!("/tmp/cua-job-conformance-{}", new_job_id());
+ let st = space
+ .job_start(&i::SpaceJob {
+ action: "start".into(),
+ until: Some(i::JobUntil {
+ file: Some(flag.clone()),
+ interval: Some(1),
+ ..Default::default()
+ }),
+ ..Default::default()
+ })
+ .await?;
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ if space.job_status(&st.job).await?.state != "running" {
+ return Err(fail("a condition waits", &st));
+ }
+ space
+ .bash(&format!("touch {flag}"), Duration::from_secs(30))
+ .await?;
+ let done = until_ended(space, &st.job, Duration::from_secs(60)).await?;
+ space
+ .bash(&format!("rm -f {flag}"), Duration::from_secs(30))
+ .await?;
+ if (done.state.as_str(), done.exit_code) != ("exited", Some(0)) {
+ return Err(fail("a condition ends the job", &done));
+ }
+
+ // 6. The Space's jobs list, and an unknown job is not found.
+ let jobs = space.job_list().await?;
+ if !jobs.iter().any(|j| j.job == st.job) {
+ return Err(fail("list includes the job", &jobs));
+ }
+ match space.job_status("jnosuchjob").await {
+ Err(Error::NotFound(_)) => {}
+ other => return Err(fail("an unknown job is not found", other)),
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::process::Command;
+
+ fn run_sh(home: &std::path::Path, script: &str) -> (bool, Vec<u8>, String) {
+ let out = Command::new("/bin/sh")
+ .arg("-c")
+ .arg(script)
+ .env("HOME", home)
+ .output()
+ .expect("sh runs");
+ (
+ out.status.success(),
+ out.stdout,
+ String::from_utf8_lossy(&out.stderr).into_owned(),
+ )
+ }
+
+ fn start(home: &std::path::Path, a: &i::SpaceJob) -> JobStatus {
+ let id = new_job_id();
+ let (ok, out, err) = run_sh(home, &start_script(&id, a).unwrap());
+ assert!(ok, "start failed: {err}");
+ parse_status(&String::from_utf8_lossy(&out)).unwrap()
+ }
+
+ fn status(home: &std::path::Path, id: &str) -> JobStatus {
+ let (ok, out, err) = run_sh(home, &status_script(id).unwrap());
+ assert!(ok, "{err}");
+ parse_status(&String::from_utf8_lossy(&out)).unwrap()
+ }
+
+ fn wait_done(home: &std::path::Path, id: &str) -> JobStatus {
+ for _ in 0..100 {
+ let s = status(home, id);
+ if s.finished() {
+ return s;
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+ panic!("job {id} did not end");
+ }
+
+ fn job(command: &str) -> i::SpaceJob {
+ i::SpaceJob {
+ action: "start".into(),
+ command: Some(command.into()),
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn ids_and_quoting_are_safe() {
+ assert_eq!(sh_quote("a'b"), r"'a'\''b'");
+ let id = new_job_id();
+ assert_eq!(id.len(), 13);
+ assert!(valid_job_id(&id).is_ok());
+ assert!(valid_job_id("../x").is_err());
+ assert!(valid_job_id("a b").is_err());
+ assert!(valid_job_id("").is_err());
+ }
+
+ #[test]
+ fn a_job_runs_detached_and_keeps_its_exit_status() {
+ let home = tempfile::tempdir().unwrap();
+ let st = start(home.path(), &job("echo hello; echo oops >&2; exit 3"));
+ let done = wait_done(home.path(), &st.job);
+ assert_eq!(done.state, "exited");
+ assert_eq!(done.exit_code, Some(3));
+ let (ok, out, _) = run_sh(home.path(), &logs_script(&st.job, None, 100).unwrap());
+ assert!(ok);
+ let logs = parse_logs(&out, 100).unwrap();
+ assert!(logs.text.contains("hello") && logs.text.contains("oops"));
+ assert_eq!(logs.offset, 0);
+ assert_eq!(logs.next_offset, logs.status.size);
+ assert!(!logs.more);
+ }
+
+ #[test]
+ fn logs_read_on_from_an_offset_without_losing_bytes() {
+ let home = tempfile::tempdir().unwrap();
+ let st = start(home.path(), &job("printf 'abcdefghij'"));
+ wait_done(home.path(), &st.job);
+ let (_, out, _) = run_sh(home.path(), &logs_script(&st.job, Some(0), 4).unwrap());
+ let a = parse_logs(&out, 4).unwrap();
+ assert_eq!((a.text.as_str(), a.next_offset, a.more), ("abcd", 4, true));
+ let (_, out, _) = run_sh(
+ home.path(),
+ &logs_script(&st.job, Some(a.next_offset), 100).unwrap(),
+ );
+ let b = parse_logs(&out, 100).unwrap();
+ assert_eq!(
+ (b.text.as_str(), b.next_offset, b.more),
+ ("efghij", 10, false)
+ );
+ // Without an offset: the end of the log.
+ let (_, out, _) = run_sh(home.path(), &logs_script(&st.job, None, 3).unwrap());
+ let c = parse_logs(&out, 3).unwrap();
+ assert_eq!((c.text.as_str(), c.offset), ("hij", 7));
+ }
+
+ #[test]
+ fn cwd_and_env_reach_the_command() {
+ let home = tempfile::tempdir().unwrap();
+ let work = tempfile::tempdir().unwrap();
+ let mut a = job("pwd; echo \"$GREETING\"");
+ a.cwd = Some(work.path().to_string_lossy().into_owned());
+ a.env = Some(BTreeMap::from([("GREETING".into(), "it's fine".into())]));
+ let st = start(home.path(), &a);
+ wait_done(home.path(), &st.job);
+ let (_, out, _) = run_sh(home.path(), &logs_script(&st.job, None, 1000).unwrap());
+ let text = parse_logs(&out, 1000).unwrap().text;
+ assert!(text.contains("it's fine"), "{text}");
+ let real = work.path().canonicalize().unwrap();
+ assert!(
+ text.contains(real.to_str().unwrap()) || text.contains(work.path().to_str().unwrap()),
+ "{text}"
+ );
+ a.env = Some(BTreeMap::from([("bad name".into(), "x".into())]));
+ assert!(start_script("j1", &a).is_err());
+ }
+
+ #[test]
+ fn cancel_stops_the_whole_process_tree() {
+ let home = tempfile::tempdir().unwrap();
+ let st = start(home.path(), &job("sleep 300 & sleep 300; echo never"));
+ assert_eq!(status(home.path(), &st.job).state, "running");
+ let (ok, out, err) = run_sh(home.path(), &cancel_script(&st.job).unwrap());
+ assert!(ok, "{err}");
+ let done = parse_status(&String::from_utf8_lossy(&out)).unwrap();
+ assert_eq!(done.state, "cancelled");
+ assert_eq!(done.signal, Some(15));
+ let (_, out, _) = run_sh(home.path(), &logs_script(&st.job, None, 100).unwrap());
+ assert!(!parse_logs(&out, 100).unwrap().text.contains("never"));
+ // Cancelling again changes nothing.
+ let (_, out, _) = run_sh(home.path(), &cancel_script(&st.job).unwrap());
+ assert_eq!(
+ parse_status(&String::from_utf8_lossy(&out)).unwrap().state,
+ "cancelled"
+ );
+ }
+
+ #[test]
+ fn a_timeout_stops_the_job_and_says_so() {
+ let home = tempfile::tempdir().unwrap();
+ let mut a = job("sleep 300");
+ a.timeout = Some(1);
+ let st = start(home.path(), &a);
+ let done = wait_done(home.path(), &st.job);
+ assert_eq!(done.state, "timed_out");
+ }
+
+ #[test]
+ fn a_runner_that_died_without_a_record_is_lost() {
+ let home = tempfile::tempdir().unwrap();
+ let st = start(home.path(), &job("sleep 300"));
+ let dir = home.path().join(".cua/jobs").join(&st.job);
+ let runner: i32 = std::fs::read_to_string(dir.join("runner.pid"))
+ .unwrap()
+ .trim()
+ .parse()
+ .unwrap();
+ let child: i32 = std::fs::read_to_string(dir.join("child.pid"))
+ .unwrap()
+ .trim()
+ .parse()
+ .unwrap();
+ let _ = Command::new("kill")
+ .args(["-9", &runner.to_string()])
+ .status();
+ let _ = Command::new("kill")
+ .args(["-9", "--", &format!("-{child}")])
+ .status();
+ std::thread::sleep(Duration::from_millis(300));
+ assert_eq!(status(home.path(), &st.job).state, "lost");
+ }
+
+ #[test]
+ fn listing_is_newest_first_and_unknown_jobs_are_not_found() {
+ let home = tempfile::tempdir().unwrap();
+ let mut a = job("true");
+ a.name = Some("first".into());
+ let one = start(home.path(), &a);
+ std::thread::sleep(Duration::from_millis(1100));
+ a.name = Some("second\nline".into());
+ let two = start(home.path(), &a);
+ wait_done(home.path(), &one.job);
+ wait_done(home.path(), &two.job);
+ let (_, out, _) = run_sh(home.path(), &list_script());
+ let jobs = parse_list(&String::from_utf8_lossy(&out));
+ assert_eq!(
+ jobs.iter().map(|j| j.name.as_str()).collect::<Vec<_>>(),
+ ["second line", "first"]
+ );
+ let (_, out, _) = run_sh(home.path(), &status_script("nope").unwrap());
+ assert!(matches!(
+ parse_status(&String::from_utf8_lossy(&out)),
+ Err(Error::NotFound(_))
+ ));
+ }
+
+ #[test]
+ fn a_file_condition_ends_when_the_file_appears() {
+ let home = tempfile::tempdir().unwrap();
+ let flag = home.path().join("ready.flag");
+ let a = i::SpaceJob {
+ action: "start".into(),
+ until: Some(i::JobUntil {
+ file: Some(flag.to_string_lossy().into_owned()),
+ interval: Some(1),
+ ..Default::default()
+ }),
+ name: Some("wait for flag".into()),
+ ..Default::default()
+ };
+ let st = start(home.path(), &a);
+ std::thread::sleep(Duration::from_millis(500));
+ assert_eq!(status(home.path(), &st.job).state, "running");
+ std::fs::write(&flag, "x").unwrap();
+ let done = wait_done(home.path(), &st.job);
+ assert_eq!((done.state.as_str(), done.exit_code), ("exited", Some(0)));
+ }
+
+ #[test]
+ fn a_command_condition_ends_when_it_passes() {
+ let home = tempfile::tempdir().unwrap();
+ let flag = home.path().join("go");
+ let a = i::SpaceJob {
+ action: "start".into(),
+ until: Some(i::JobUntil {
+ command: Some(format!("test -f {}", sh_quote(&flag.to_string_lossy()))),
+ interval: Some(1),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ let st = start(home.path(), &a);
+ std::fs::write(&flag, "x").unwrap();
+ assert_eq!(wait_done(home.path(), &st.job).exit_code, Some(0));
+ }
+
+ #[test]
+ fn conditions_are_checked() {
+ let none = i::JobUntil::default();
+ assert!(until_script(&none).is_err());
+ let two = i::JobUntil {
+ file: Some("/x".into()),
+ port: Some(1),
+ ..Default::default()
+ };
+ assert!(until_script(&two).is_err());
+ let bad_host = i::JobUntil {
+ port: Some(80),
+ host: Some("a;b".into()),
+ ..Default::default()
+ };
+ assert!(until_script(&bad_host).is_err());
+ let pr = until_script(&i::JobUntil {
+ pr_checks: Some("acme/widgets#42".into()),
+ ..Default::default()
+ })
+ .unwrap();
+ assert!(pr.contains("gh pr checks '42' --repo 'acme/widgets' --required --watch"));
+ assert!(start_script("j1", &i::SpaceJob::default()).is_err());
+ let both = i::SpaceJob {
+ command: Some("true".into()),
+ until: Some(i::JobUntil {
+ file: Some("/x".into()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ assert!(start_script("j1", &both).is_err());
+ }
+
+ #[test]
+ fn the_result_line_is_structured() {
+ let mut s = JobStatus {
+ job: "j1".into(),
+ name: "unit tests".into(),
+ state: "exited".into(),
+ exit_code: Some(0),
+ signal: None,
+ started_at: Some(10),
+ ended_at: Some(785),
+ elapsed_s: 775,
+ size: 2048,
+ command: "cargo test".into(),
+ };
+ assert_eq!(
+ result_line(&s),
+ "JOB j1 exited exit=0 12m55s log=2048B | unit tests"
+ );
+ s.state = "cancelled".into();
+ s.exit_code = None;
+ s.signal = Some(15);
+ s.name.clear();
+ assert_eq!(
+ result_line(&s),
+ "JOB j1 cancelled signal=15 12m55s log=2048B"
+ );
+ assert_eq!(elapsed_text(3723), "1h02m03s");
+ assert_eq!(elapsed_text(9), "9s");
+ }
+}
diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rs
index 5495efcbd3..c386981338 100644
--- a/libs/cua/crates/cua-spaces/src/spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/spaces.rs
@@ -113,6 +113,16 @@ pub struct SpaceCreate {
/// created (see [`crate::egress`]); not with `durable`, `reuse` or a
/// create that does not wait.
pub egress: crate::egress::EgressPolicy,
+ /// Network settings ([`crate::network`]): a preset and the user's
+ /// lists. `None`: what `network` and `egress` say (`internet` when
+ /// neither says anything).
+ pub network_settings: Option<crate::network::NetworkSettings>,
+ /// Create it as a child of this Space (id or name): its network is no
+ /// more open than its parent's, and it joins the parent's tree.
+ pub parent: Option<String>,
+ /// With `parent`: let its network be more open than its parent's
+ /// (recorded on the Space as who widened it and when).
+ pub widen: bool,
/// On a linked cloud (`on` `aws`, `hetzner`, ...): the machine type its
/// host must be (`c7g.xlarge`, `cax41`): a pin in the same elastic
/// solve. `None`: the solver picks.
@@ -228,6 +238,10 @@ pub(crate) struct LocalProvision {
pub network: cua_sandbox_core::NetworkMode,
/// Egress policy ([`SpaceCreate::egress`]).
pub egress: crate::egress::EgressPolicy,
+ /// Network settings ([`SpaceCreate::network_settings`]).
+ pub network_settings: Option<crate::network::NetworkSettings>,
+ /// The tree it joins (its root's id); `None`: its own.
+ pub network_tree: Option<String>,
}
/// A Space [`Spaces::create`] started with `wait = false`.
@@ -455,6 +469,8 @@ pub(crate) fn relay_info(m: &crate::relay::RelayMachine) -> SpaceInfo {
created_at_unix: 0,
egress: Default::default(),
egress_enforced: None,
+ network: None,
+ tree: None,
sharing: None,
}
}
@@ -1291,6 +1307,8 @@ impl Spaces {
created_at_unix: 0,
egress: Default::default(),
egress_enforced: None,
+ network: None,
+ tree: None,
sharing: None,
}))
}
@@ -1337,6 +1355,12 @@ impl Spaces {
info.egress = m.egress.clone();
info.egress_enforced =
(!m.egress.is_empty()).then_some(crate::egress::Enforcement::Host);
+ info.network = Some(crate::network::SpaceNetwork {
+ settings: crate::network::settings_of(Some(m)),
+ note: m.network_note.clone(),
+ notice_pending: m.network_notice_pending,
+ });
+ info.tree = Some(crate::tree::TreeLink::of(m));
}
if let Some(l) = self.lifetime_of(&info.id, &lifetimes) {
info.expires_at_unix = l.expires_at_unix;
@@ -1386,6 +1410,13 @@ impl Spaces {
} else {
crate::egress::Enforcement::Host.as_str().into()
};
+ r.network_settings = m.network.as_ref().map(crate::network::to_pb);
+ r.network_note = m.network_note.clone().unwrap_or_default();
+ r.network_notice_pending = m.network_notice_pending;
+ r.parent = m.parent.clone().unwrap_or_default();
+ r.root = m.root.clone().unwrap_or_default();
+ r.depth = m.depth;
+ r.origin = crate::tree::TreeLink::of(m).origin;
}
if let Some(l) = self.lifetime_of(&r.id, &lifetimes) {
r.expires_at_unix = i64::try_from(l.expires_at_unix).unwrap_or(0);
@@ -2221,8 +2252,21 @@ impl Spaces {
/// dropping the returned future (a closed request) does the same.
pub async fn create(&self, mut opts: SpaceCreate) -> Result<SpaceCreated> {
use cua_sandbox_core::progress::{Phase, Progress, report};
- refuse_windows_on_mac(opts.image.as_deref(), cfg!(target_os = "macos"))?;
crate::registry::validate_labels(&opts.labels)?;
+ // Secure Spaces and Child Spaces are experiments: until they are on, a
+ // create asks for no more than the old lists and no parent.
+ crate::network::require_secure_spaces(opts.network_settings.as_ref())?;
+ if opts.parent.is_some()
+ && !cua_vmm::experiments::enabled(cua_vmm::experiments::Gate::ChildSpaces)
+ {
+ return Err(Error::invalid(
+ cua_vmm::experiments::Gate::ChildSpaces.off_message(),
+ ));
+ }
+ // The network it gets: what it asks, no more open than its parent.
+ // Every path below carries the resolved settings.
+ let network = self.create_network(&opts)?;
+ opts.network_settings = Some(network.settings.clone());
let egress = opts.egress.clone();
if !egress.is_empty() {
// Checked before anything is created; the runtime refuses a
@@ -2295,6 +2339,12 @@ impl Spaces {
}
let sink = opts.progress.take().map(|p| p.0);
let (key, on) = self.create_key(&mut opts)?;
+ // A Mac cannot create a Windows VM locally yet. The selected host
+ // may be a Linux or Windows machine that can run it, so do not apply
+ // the coordinator's local runtime restriction to remote placement.
+ if on == On::Local {
+ refuse_windows_on_mac(opts.image.as_deref(), cfg!(target_os = "macos"))?;
+ }
// The record is written before the Space connects, and the volume
// attaches on connect: its mounts are known by then.
self.expect_volumes(&key.id, opts.volumes.clone());
@@ -2435,6 +2485,19 @@ impl Spaces {
let expect_env = expects_spacesd(opts.image.as_deref(), opts.spacesd);
let labels = opts.labels.clone();
let egress = opts.egress.clone();
+ let network = crate::network::CreateNetwork {
+ settings: opts
+ .network_settings
+ .clone()
+ .unwrap_or_else(crate::network::NetworkSettings::internet),
+ parent: opts
+ .parent
+ .as_deref()
+ .and_then(|p| self.resolve(p).ok())
+ .map(|i| i.to_string()),
+ root: None,
+ depth: 0,
+ };
let journal =
crate::creating::JournalHandle::start(self.home_dir(), &key, kind, expect_env);
// A create dropped before it returned (a closed request, a Ctrl-C
@@ -2560,6 +2623,27 @@ impl Spaces {
}),
_ => Ok(()),
};
+ let applied = applied.and_then(|()| {
+ // Its network settings and its place in a tree.
+ let root = network.parent.as_ref().map(|p| {
+ self.inner
+ .registry
+ .meta(p)
+ .and_then(|m| m.root)
+ .unwrap_or_else(|| p.clone())
+ });
+ let depth = network.parent.as_ref().map_or(0, |p| {
+ self.inner.registry.meta(p).map_or(0, |m| m.depth) + 1
+ });
+ self.record_network(
+ &id,
+ &crate::network::CreateNetwork {
+ root,
+ depth,
+ ..network.clone()
+ },
+ )
+ });
if let Some(e) = kept.err().or(applied.err()) {
let _ = Box::pin(self.delete(&id)).await;
result = Err(e);
@@ -2569,6 +2653,11 @@ impl Spaces {
info.egress = egress.clone();
info.egress_enforced =
(!egress.is_empty()).then_some(crate::egress::Enforcement::Host);
+ info.network = Some(crate::network::SpaceNetwork {
+ settings: network.settings.clone(),
+ note: None,
+ notice_pending: false,
+ });
}
}
flight.finish(match &result {
@@ -2689,6 +2778,13 @@ impl Spaces {
list_spaces"
)));
}
+ // Nothing there enforces network settings: only No protection.
+ crate::network::refuse_on_provider(
+ &opts
+ .network_settings
+ .clone()
+ .unwrap_or_else(crate::network::NetworkSettings::internet),
+ )?;
let info = self.create_in_cloud(word, opts).await?;
return Ok(SpaceCreated::Ready {
info,
@@ -2744,6 +2840,8 @@ impl Spaces {
forkable: opts.forkable,
network: opts.network,
egress: opts.egress,
+ network_tree: self.tree_root_of(opts.parent.as_deref()),
+ network_settings: opts.network_settings,
};
// `create` runs a `wait = false` create in the background
// itself, so here it always waits.
@@ -2828,6 +2926,13 @@ impl Spaces {
create.spacesd = opts.spacesd;
create.network = opts.network;
create.egress = opts.egress.clone();
+ create.network_settings = opts.network_settings.clone();
+ // Its tree: its parent's, or its own.
+ create.network_tree = Some(
+ opts.network_tree
+ .clone()
+ .unwrap_or_else(|| SpaceId::Local { name: name.clone() }.to_string()),
+ );
for (svc, port) in opts.services.iter().filter(|(s, _)| s.as_str() != "env") {
create = create
.service(svc.clone(), *port)
@@ -2846,6 +2951,23 @@ impl Spaces {
.create_cancellable(create, cua_sandbox_core::CancellationToken::new()),
)
.await;
+ // A runtime that can't protect it yet started it without network
+ // (or the user chose No protection): say so on the Space.
+ if let Ok(sb) = &created {
+ let settings = opts
+ .network_settings
+ .clone()
+ .unwrap_or_else(crate::network::NetworkSettings::internet);
+ let note = crate::network::note_for(sb.runtime_type(), &settings);
+ let id = SpaceId::Local { name: name.clone() }.to_string();
+ if let Err(e) = self
+ .inner
+ .registry
+ .update_meta(&id, |m| m.network_note = note)
+ {
+ tracing::warn!(space = %id, error = %e, "could not record the Space's network note");
+ }
+ }
if let Err(e) = created {
// A start that failed after the instance existed (a readiness
// probe that never passed) leaves a running VM no registry
@@ -3106,7 +3228,16 @@ impl Spaces {
/// the relay (`relay_register`, or a share) leaves the relay directory
/// with it, and deleting such a Space's `relay:<machine>` removes that
/// record (as its owner) even when the Space itself is already gone.
+ ///
+ /// Its child Spaces ([`crate::tree`]) go first: see
+ /// [`Spaces::delete_tree`], which can keep them instead.
pub async fn delete(&self, space: &str) -> Result<String> {
+ self.delete_tree(space, false).await
+ }
+
+ /// [`Spaces::delete`] of this Space alone (its children, if any, are
+ /// the caller's).
+ pub(crate) async fn delete_this(&self, space: &str) -> Result<String> {
// A durable Space goes for good (deleting only its current copy
// would have it created again).
if self.inner.pool.read().expect("pool").is_some() {
@@ -3126,7 +3257,16 @@ impl Spaces {
/// Space's copy: what the coordinator that keeps durable Spaces uses to
/// remove a copy it replaced or deleted.
pub async fn delete_copy(&self, space: &str) -> Result<String> {
- let id = self.resolve(space)?;
+ let id = match self.resolve(space) {
+ Ok(id) => id,
+ // A local sandbox no Space record names (a `cua sb fork`, a
+ // sandbox made with `cua sb create`): delete it by name too.
+ Err(Error::NotFound(m)) => match self.unregistered_local(space) {
+ Some(id) => id,
+ None => return Err(Error::NotFound(m)),
+ },
+ Err(e) => return Err(e),
+ };
let ended = self.delete_copy_of(id.clone()).await;
if ended.is_ok() {
// A Space made later under the same name starts without the
@@ -3136,6 +3276,24 @@ impl Spaces {
ended
}
+ /// `local:<name>` when `name` is a plain name (no `kind:` prefix) of a
+ /// sandbox Cua made on this computer (a recorded one) that no Space
+ /// record names. Only recorded sandboxes: a VM the runtime has that Cua
+ /// never made (another tool's Lume VM) is never deleted by name here.
+ fn unregistered_local(&self, name: &str) -> Option<SpaceId> {
+ if name.is_empty() || name.contains(':') || name.contains('/') {
+ return None;
+ }
+ self.inner
+ .sandboxes
+ .state()
+ .load(name)
+ .is_some()
+ .then(|| SpaceId::Local {
+ name: name.to_string(),
+ })
+ }
+
async fn delete_copy_of(&self, id: SpaceId) -> Result<String> {
self.learn_usage_before_delete(&id.to_string()).await;
if let SpaceId::Local { name } = &id {
@@ -3475,6 +3633,8 @@ impl Spaces {
/// and a legacy `cloud:` Space fails with
/// [`cua_sandbox_core::CLOUD_ENDED`].
pub async fn stop(&self, space: &str) -> Result<SpacePower> {
+ // Its child Spaces first ([`crate::tree`]).
+ self.power_off_children(space, false).await;
self.set_power(space, false).await
}
@@ -3484,8 +3644,17 @@ impl Spaces {
/// answers again (bounded).
pub async fn start(&self, space: &str) -> Result<SpacePower> {
// The runtime keeps an egress policy with the Space: it applies
- // again before the guest's first instruction.
- self.set_power(space, true).await
+ // again before the guest's first instruction. A Space from before
+ // network settings moves to them now ([`crate::network`]).
+ if let Ok(id) = self.resolve(space)
+ && let Err(e) = self.migrate_network(&id.to_string())
+ {
+ tracing::warn!(space, error = %e, "could not record the Space's network settings");
+ }
+ let power = self.set_power(space, true).await?;
+ // Its child Spaces after it ([`crate::tree`]).
+ self.power_on_children(space).await;
+ Ok(power)
}
/// Suspends a local Space, keeping its memory (it resumes where it
@@ -3493,6 +3662,13 @@ impl Spaces {
/// VM. [`Self::stop`] stops it instead and frees its memory. Other
/// Spaces are refused.
pub async fn suspend(&self, space: &str) -> Result<SpacePower> {
+ // Its child Spaces first ([`crate::tree`]).
+ self.power_off_children(space, true).await;
+ self.suspend_one(space).await
+ }
+
+ /// [`Spaces::suspend`] of this Space alone.
+ pub(crate) async fn suspend_one(&self, space: &str) -> Result<SpacePower> {
let id = self.resolve(space)?;
let SpaceId::Local { name } = &id else {
return Err(Error::WrongProvider {
@@ -3578,7 +3754,7 @@ impl Spaces {
})
}
- async fn set_power(&self, space: &str, on: bool) -> Result<SpacePower> {
+ pub(crate) async fn set_power(&self, space: &str, on: bool) -> Result<SpacePower> {
let id = self.resolve(space)?;
let cloud = self.cloud_sandbox_of(&id.to_string())?;
let refuse = |provider: &str| Error::WrongProvider {
@@ -3855,9 +4031,9 @@ async fn wait_serving(space: &Space, deadline: tokio::time::Instant) {
}
}
-/// Windows Spaces are not offered from a Mac yet: every create failed at the
-/// image pull. Refuses one up front, in words a person can act on. Windows
-/// and Linux hosts are not affected.
+/// A Mac cannot create a Windows VM locally yet. Refuses a local create up
+/// front, in words a person can act on. Remote host placement is checked by
+/// the selected host instead.
pub(crate) const WINDOWS_COMING_SOON: &str = "Windows Spaces are coming soon on Mac.";
fn refuse_windows_on_mac(image: Option<&str>, host_is_mac: bool) -> Result<()> {
diff --git a/libs/cua/crates/cua-spaces/src/spawn.rs b/libs/cua/crates/cua-spaces/src/spawn.rs
new file mode 100644
index 0000000000..817669071d
--- /dev/null
+++ b/libs/cua/crates/cua-spaces/src/spawn.rs
@@ -0,0 +1,156 @@
+//! The host's end of a Space's spawn channel (`TunnelService.StartSpawn`).
+//!
+//! The guest listens on its own loopback and relays each connection over a
+//! WebSocket this host opens to the Space's cua-spacesd. Every stream that
+//! arrives is handed to the caller's dialer, which serves this Space's
+//! child-Space API on it. The host knows the Space by the connection it
+//! opened, so nothing the guest sends can name another Space.
+
+use cua_spacesd_client::pb;
+use futures_util::{SinkExt, StreamExt};
+use tokio_tungstenite::tungstenite::{self, client::IntoClientRequest};
+
+use crate::error::{Error, Result};
+use crate::space::Space;
+
+/// The guest feature.
+pub const SPAWN_FEATURE: &str = "spawn";
+
+/// A started spawn channel. Dropping it leaves the guest's listener in
+/// place but closes the host's socket (new connections are refused);
+/// [`SpawnChannel::stop`] also removes the listener and the capability.
+pub struct SpawnChannel {
+ space: Space,
+ spawn_id: String,
+ address: String,
+ token_path: String,
+ task: Option<tokio::task::JoinHandle<()>>,
+}
+
+impl SpawnChannel {
+ /// The guest's listener URL (`http://127.0.0.1:<port>`).
+ pub fn address(&self) -> &str {
+ &self.address
+ }
+
+ /// Where the guest keeps the capability.
+ pub fn token_path(&self) -> &str {
+ &self.token_path
+ }
+
+ /// Waits until the host's socket closes (the guest stopped, restarted
+ /// or replaced the channel).
+ pub async fn closed(&mut self) {
+ if let Some(task) = self.task.as_mut() {
+ let _ = task.await;
+ }
+ self.task = None;
+ }
+
+ /// Stops the channel in the guest (listener and capability file).
+ pub async fn stop(mut self) -> Result<()> {
+ if let Some(task) = self.task.take() {
+ task.abort();
+ }
+ self.space
+ .spacesd()?
+ .tunnel()
+ .stop_spawn(pb::StopSpawnRequest {
+ spawn_id: self.spawn_id.clone(),
+ })
+ .await
+ .map_err(cua_spacesd_client::Error::from)?;
+ Ok(())
+ }
+}
+
+impl Drop for SpawnChannel {
+ fn drop(&mut self) {
+ if let Some(task) = self.task.take() {
+ task.abort();
+ }
+ }
+}
+
+impl Space {
+ /// Starts this Space's spawn channel with `capability`, serving every
+ /// stream the guest opens with `dial`.
+ pub async fn start_spawn_with<D, F, T>(&self, capability: &str, dial: D) -> Result<SpawnChannel>
+ where
+ D: Fn(String, u16) -> F + Send + Sync + 'static,
+ F: std::future::Future<Output = std::io::Result<T>> + Send + 'static,
+ T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static,
+ {
+ self.require(SPAWN_FEATURE)?;
+ let resp = self
+ .spacesd()?
+ .tunnel()
+ .start_spawn(pb::StartSpawnRequest {
+ capability: capability.to_owned(),
+ ticket_ttl: None,
+ space_id: self.id().to_string(),
+ })
+ .await
+ .map_err(cua_spacesd_client::Error::from)?
+ .into_inner();
+ let mut request = self
+ .websocket_url(&resp.ws_path)?
+ .into_client_request()
+ .map_err(|e| Error::Stream(e.to_string()))?;
+ for (k, v) in self.websocket_headers().await? {
+ if let (Ok(k), Ok(v)) = (
+ http::HeaderName::from_bytes(k.as_bytes()),
+ http::HeaderValue::from_str(&v),
+ ) {
+ request.headers_mut().insert(k, v);
+ }
+ }
+ cua_spacesd_client::transport::ensure_crypto_provider();
+ let config = tungstenite::protocol::WebSocketConfig::default()
+ .max_message_size(Some(16 << 20))
+ .max_frame_size(Some(16 << 20));
+ let ws =
+ match tokio_tungstenite::connect_async_with_config(request, Some(config), true).await {
+ Ok((ws, _)) => ws,
+ Err(e) => {
+ let _ = self
+ .spacesd()?
+ .tunnel()
+ .stop_spawn(pb::StopSpawnRequest {
+ spawn_id: resp.spawn_id.clone(),
+ })
+ .await;
+ return Err(Error::Stream(format!("spawn socket: {e}")));
+ }
+ };
+ let (sink, stream) = ws.split();
+ let sink = sink.with(|bytes: Vec<u8>| async move {
+ Ok::<_, tungstenite::Error>(tungstenite::Message::Binary(bytes.into()))
+ });
+ let source = stream
+ .take_while(|m| {
+ futures_util::future::ready(!matches!(
+ m,
+ Err(_) | Ok(tungstenite::Message::Close(_))
+ ))
+ })
+ .filter_map(|m| async move {
+ match m {
+ Ok(tungstenite::Message::Binary(b)) => Some(b.to_vec()),
+ _ => None,
+ }
+ });
+ let space_id = self.id().to_string();
+ let task = tokio::spawn(async move {
+ cua_hotspot::peer::serve_streams(Box::pin(source), Box::pin(sink), dial).await;
+ tracing::debug!(space = %space_id, "spawn socket closed");
+ });
+ Ok(SpawnChannel {
+ space: self.clone(),
+ spawn_id: resp.spawn_id,
+ address: resp.address,
+ token_path: resp.token_path,
+ task: Some(task),
+ })
+ }
+}
diff --git a/libs/cua/crates/cua-spaces/src/tree.rs b/libs/cua/crates/cua-spaces/src/tree.rs
new file mode 100644
index 0000000000..9b6ba79681
--- /dev/null
+++ b/libs/cua/crates/cua-spaces/src/tree.rs
@@ -0,0 +1,466 @@
+//! Trees of Spaces: a top-level Space and the Spaces created from it
+//! (children, their children, ...).
+//!
+//! **Record.** Each child keeps, in its [`SpaceMeta`]:
+//!
+//! - `parent`: its parent's canonical id;
+//! - `root`: the top-level Space of its tree (a top-level Space has none:
+//! it is its own root);
+//! - `depth`: 1 for a child of a top-level Space, 2 for a grandchild, ...;
+//! - `origin`: how it was made: `user` (top-level), `child`, or
+//! `fork-batch:<id>`.
+//!
+//! The record fields are what counts. A label `cua.parent=<id>` mirrors the
+//! parent so older clients, listings and cloud sweeps can see it. Links are
+//! by id, never by name: a parent re-created under the same name is not
+//! the old one.
+//!
+//! **Depth.** A child may be at most [`DEFAULT_DEPTH_LIMIT`] levels below a
+//! top-level Space unless its root's `depth_limit` says more, and never
+//! more than [`MAX_DEPTH`].
+//!
+//! **Cascade.** Deleting, stopping or suspending a Space does the same to
+//! its subtree, children first ([`Spaces::delete_tree`]); starting one
+//! starts its subtree after it. `keep_children` detaches the children
+//! instead: each becomes a top-level Space with its own subtree.
+//!
+//! **Network.** The tree is the network boundary ([`crate::network`]):
+//! a child's settings are no more open than its parent's, its members reach
+//! each other, and other trees are blocked.
+
+use std::collections::{BTreeMap, BTreeSet};
+
+use crate::registry::SpaceMeta;
+use crate::{Error, Result, Spaces};
+
+/// How deep a tree goes below its top-level Space unless its root says
+/// more (user → child → grandchild).
+pub const DEFAULT_DEPTH_LIMIT: u32 = 2;
+/// How deep a tree may ever go.
+pub const MAX_DEPTH: u32 = 4;
+/// The label that mirrors a child's parent.
+pub const PARENT_LABEL: &str = "cua.parent";
+/// `origin` of a top-level Space.
+pub const ORIGIN_USER: &str = "user";
+/// `origin` of a child Space.
+pub const ORIGIN_CHILD: &str = "child";
+
+/// A Space's place in its tree, as listings show it.
+#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)]
+pub struct TreeLink {
+ /// Its parent's id; `None` for a top-level Space.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub parent: Option<String>,
+ /// Its tree's top-level Space; `None` for a top-level Space.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub root: Option<String>,
+ /// 0 for a top-level Space, 1 for its children, ...
+ pub depth: u32,
+ /// `user`, `child` or `fork-batch:<id>`.
+ pub origin: String,
+}
+
+impl TreeLink {
+ /// The link a record keeps.
+ pub fn of(meta: &SpaceMeta) -> TreeLink {
+ TreeLink {
+ parent: meta.parent.clone(),
+ root: meta.root.clone(),
+ depth: meta.depth,
+ origin: meta.origin.clone().unwrap_or_else(|| {
+ if meta.parent.is_some() {
+ ORIGIN_CHILD
+ } else {
+ ORIGIN_USER
+ }
+ .into()
+ }),
+ }
+ }
+}
+
+/// The depth limit of a tree whose root keeps `root_meta`.
+pub fn depth_limit(root_meta: Option<&SpaceMeta>) -> u32 {
+ root_meta
+ .and_then(|m| m.depth_limit)
+ .unwrap_or(DEFAULT_DEPTH_LIMIT)
+ .min(MAX_DEPTH)
+}
+
+/// The depth a new child of a parent at `parent_depth` gets, or why it
+/// can't be made.
+pub fn child_depth(parent: &str, parent_depth: u32, limit: u32) -> Result<u32> {
+ let depth = parent_depth + 1;
+ if depth > limit {
+ return Err(Error::invalid(format!(
+ "{parent} can't have children: its tree is {limit} level{} deep already (the most \
+ is {MAX_DEPTH}; the tree's top-level Space sets it)",
+ if limit == 1 { "" } else { "s" }
+ )));
+ }
+ Ok(depth)
+}
+
+/// The direct children of `id` in `all`.
+pub fn children_of(all: &BTreeMap<String, SpaceMeta>, id: &str) -> Vec<String> {
+ all.iter()
+ .filter(|(_, m)| m.parent.as_deref() == Some(id))
+ .map(|(k, _)| k.clone())
+ .collect()
+}
+
+/// Every Space below `id`, deepest first (children before their parents),
+/// so a cascade never leaves a child without its parent. Safe against a
+/// cycle in a hand-edited record.
+pub fn descendants(all: &BTreeMap<String, SpaceMeta>, id: &str) -> Vec<String> {
+ let mut seen: BTreeSet<String> = BTreeSet::from([id.to_string()]);
+ let mut levels: Vec<Vec<String>> = Vec::new();
+ let mut frontier = vec![id.to_string()];
+ while !frontier.is_empty() {
+ let mut next = Vec::new();
+ for p in &frontier {
+ for c in children_of(all, p) {
+ if seen.insert(c.clone()) {
+ next.push(c);
+ }
+ }
+ }
+ if !next.is_empty() {
+ levels.push(next.clone());
+ }
+ frontier = next;
+ }
+ levels.into_iter().rev().flatten().collect()
+}
+
+/// [`descendants`] grouped by level, deepest level first: each level can
+/// go at once.
+pub fn levels(all: &BTreeMap<String, SpaceMeta>, id: &str) -> Vec<Vec<String>> {
+ let mut by_depth: BTreeMap<u32, Vec<String>> = BTreeMap::new();
+ let base = all.get(id).map_or(0, |m| m.depth);
+ for d in descendants(all, id) {
+ let depth = all.get(&d).map_or(base + 1, |m| m.depth.max(base + 1));
+ by_depth.entry(depth).or_default().push(d);
+ }
+ by_depth.into_values().rev().collect()
+}
+
+/// The members of the tree `id` belongs to: its root and everything below
+/// it.
+pub fn members(all: &BTreeMap<String, SpaceMeta>, id: &str) -> Vec<String> {
+ let root = all
+ .get(id)
+ .and_then(|m| m.root.clone())
+ .unwrap_or_else(|| id.to_string());
+ let mut out = vec![root.clone()];
+ out.extend(descendants(all, &root));
+ out
+}
+
+/// `all` with the children of `id` detached: each becomes a top-level
+/// Space, and the root and depth of everything below it follow.
+pub fn detach(all: &mut BTreeMap<String, SpaceMeta>, id: &str) -> Vec<String> {
+ let kids = children_of(all, id);
+ for kid in &kids {
+ let shift = all.get(kid).map_or(1, |m| m.depth.max(1));
+ let below = descendants(all, kid);
+ if let Some(m) = all.get_mut(kid) {
+ m.parent = None;
+ m.root = None;
+ m.depth = 0;
+ m.labels.remove(PARENT_LABEL);
+ }
+ for d in below {
+ if let Some(m) = all.get_mut(&d) {
+ m.root = Some(kid.clone());
+ m.depth = m.depth.saturating_sub(shift).max(1);
+ }
+ }
+ }
+ kids
+}
+
+impl Spaces {
+ /// The root of the tree a new child of `parent` joins (`None` without
+ /// a parent: it is its own).
+ pub(crate) fn tree_root_of(&self, parent: Option<&str>) -> Option<String> {
+ let parent = parent.map(str::trim).filter(|p| !p.is_empty())?;
+ let id = self.resolve(parent).ok()?.to_string();
+ Some(
+ self.inner
+ .registry
+ .meta(&id)
+ .and_then(|m| m.root)
+ .unwrap_or(id),
+ )
+ }
+
+ /// The direct children of a Space (canonical ids).
+ pub fn children(&self, space: &str) -> Result<Vec<String>> {
+ let id = self.resolve(space)?.to_string();
+ Ok(children_of(&self.inner.registry.all_meta(), &id))
+ }
+
+ /// Every Space below a Space, children before their parents.
+ pub fn descendants(&self, space: &str) -> Result<Vec<String>> {
+ let id = self.resolve(space)?.to_string();
+ Ok(descendants(&self.inner.registry.all_meta(), &id))
+ }
+
+ /// The members of a Space's tree: its root and everything below it.
+ pub fn tree_members(&self, space: &str) -> Result<Vec<String>> {
+ let id = self.resolve(space)?.to_string();
+ Ok(members(&self.inner.registry.all_meta(), &id))
+ }
+
+ /// A Space's place in its tree.
+ pub fn tree_link(&self, space: &str) -> Result<TreeLink> {
+ let id = self.resolve(space)?.to_string();
+ Ok(self
+ .inner
+ .registry
+ .meta(&id)
+ .map(|m| TreeLink::of(&m))
+ .unwrap_or_else(|| TreeLink {
+ origin: ORIGIN_USER.into(),
+ ..Default::default()
+ }))
+ }
+
+ /// Deletes a Space and its subtree, children first (each level at
+ /// once). `keep_children` detaches its children instead: they become
+ /// top-level Spaces and keep running. A child that can't be deleted
+ /// stops the cascade before its parent goes, so nothing is left without
+ /// a parent; deleting again continues it.
+ pub async fn delete_tree(&self, space: &str, keep_children: bool) -> Result<String> {
+ let id = match self.resolve(space) {
+ Ok(id) => id.to_string(),
+ // No record names it (a sandbox made by `cua sb fork` or
+ // `cua sb create`): it has no tree, and deleting it by name
+ // is [`Spaces::delete_copy`]'s.
+ Err(Error::NotFound(_)) => return Box::pin(self.delete_this(space)).await,
+ Err(e) => return Err(e),
+ };
+ if keep_children {
+ let kids = self
+ .inner
+ .registry
+ .update_all_meta(|all| detach(all, &id))?;
+ let message = Box::pin(self.delete_this(space)).await?;
+ return Ok(if kids.is_empty() {
+ message
+ } else {
+ format!(
+ "{message} Kept {} child Space{} as top-level: {}.",
+ kids.len(),
+ if kids.len() == 1 { "" } else { "s" },
+ kids.join(", ")
+ )
+ });
+ }
+ let all = self.inner.registry.all_meta();
+ let mut failed: Vec<String> = Vec::new();
+ let mut deleted = 0usize;
+ for level in levels(&all, &id) {
+ let mut results = Vec::with_capacity(level.len());
+ for c in &level {
+ results.push((c.clone(), Box::pin(self.delete_this(c)).await));
+ }
+ for (c, r) in results {
+ match r {
+ Ok(_) | Err(Error::NotFound(_)) => {
+ deleted += 1;
+ // A record with no Space behind it goes too.
+ let _ = self
+ .inner
+ .registry
+ .update_meta(&c, |m| *m = SpaceMeta::default());
+ }
+ Err(e) => failed.push(format!("{c} ({e})")),
+ }
+ }
+ if !failed.is_empty() {
+ return Err(Error::invalid(format!(
+ "{space} was not deleted: its child Space{} could not be deleted: {}. Delete \
+ again to continue.",
+ if failed.len() == 1 { "" } else { "s" },
+ failed.join("; ")
+ )));
+ }
+ }
+ let message = Box::pin(self.delete_this(space)).await?;
+ Ok(if deleted == 0 {
+ message
+ } else {
+ format!(
+ "{message} Deleted its {deleted} child Space{} too.",
+ if deleted == 1 { "" } else { "s" }
+ )
+ })
+ }
+
+ /// Turns a Space's subtree off before the Space itself (`suspend`:
+ /// keeping memory). A child that can't be turned off is logged and
+ /// left: it is not a reason to keep its parent on.
+ pub(crate) async fn power_off_children(&self, space: &str, suspend: bool) {
+ let Ok(id) = self.resolve(space).map(|i| i.to_string()) else {
+ return;
+ };
+ let all = self.inner.registry.all_meta();
+ for level in levels(&all, &id) {
+ let results = futures_util::future::join_all(level.iter().map(|c| async move {
+ let r = if suspend {
+ Box::pin(self.suspend_one(c)).await.map(|_| ())
+ } else {
+ Box::pin(self.set_power(c, false)).await.map(|_| ())
+ };
+ (c.clone(), r)
+ }))
+ .await;
+ for (c, r) in results {
+ if let Err(e) = r {
+ tracing::warn!(space = %c, parent = %id, error = %e, "a child Space was not turned off with its parent");
+ }
+ }
+ }
+ }
+
+ /// Turns a Space's subtree on after the Space itself, parents before
+ /// their children.
+ pub(crate) async fn power_on_children(&self, space: &str) {
+ let Ok(id) = self.resolve(space).map(|i| i.to_string()) else {
+ return;
+ };
+ let all = self.inner.registry.all_meta();
+ for level in levels(&all, &id).into_iter().rev() {
+ let results = futures_util::future::join_all(level.iter().map(|c| async move {
+ let _ = self.migrate_network(c);
+ (c.clone(), Box::pin(self.set_power(c, true)).await)
+ }))
+ .await;
+ for (c, r) in results {
+ if let Err(e) = r {
+ tracing::warn!(space = %c, parent = %id, error = %e, "a child Space was not turned on with its parent");
+ }
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn tree() -> BTreeMap<String, SpaceMeta> {
+ let node = |parent: Option<&str>, root: Option<&str>, depth: u32| SpaceMeta {
+ parent: parent.map(String::from),
+ root: root.map(String::from),
+ depth,
+ labels: parent
+ .map(|p| BTreeMap::from([(PARENT_LABEL.to_string(), p.to_string())]))
+ .unwrap_or_default(),
+ ..Default::default()
+ };
+ BTreeMap::from([
+ ("local:r".into(), node(None, None, 0)),
+ ("local:a".into(), node(Some("local:r"), Some("local:r"), 1)),
+ ("local:b".into(), node(Some("local:r"), Some("local:r"), 1)),
+ ("local:a1".into(), node(Some("local:a"), Some("local:r"), 2)),
+ (
+ "local:a11".into(),
+ node(Some("local:a1"), Some("local:r"), 3),
+ ),
+ ("local:other".into(), node(None, None, 0)),
+ ])
+ }
+
+ #[test]
+ fn descendants_come_children_first() {
+ let all = tree();
+ let d = descendants(&all, "local:r");
+ assert_eq!(d.len(), 4);
+ let pos = |s: &str| d.iter().position(|x| x == s).unwrap();
+ assert!(pos("local:a11") < pos("local:a1"));
+ assert!(pos("local:a1") < pos("local:a"));
+ assert_eq!(
+ levels(&all, "local:r"),
+ vec![
+ vec!["local:a11".to_string()],
+ vec!["local:a1".to_string()],
+ vec!["local:a".to_string(), "local:b".to_string()],
+ ]
+ );
+ assert!(descendants(&all, "local:other").is_empty());
+ let mut m = members(&all, "local:a1");
+ m.sort();
+ assert_eq!(
+ m,
+ ["local:a", "local:a1", "local:a11", "local:b", "local:r"]
+ );
+ assert_eq!(members(&all, "local:other"), ["local:other"]);
+ }
+
+ #[test]
+ fn a_cycle_does_not_loop() {
+ let mut all = tree();
+ all.get_mut("local:r").unwrap().parent = Some("local:a11".into());
+ let d = descendants(&all, "local:r");
+ assert_eq!(d.len(), 4, "{d:?}");
+ }
+
+ #[test]
+ fn detaching_makes_each_child_a_top_level_tree() {
+ let mut all = tree();
+ let kids = detach(&mut all, "local:r");
+ assert_eq!(kids, ["local:a", "local:b"]);
+ let a = &all["local:a"];
+ assert_eq!(
+ (a.parent.as_ref(), a.root.as_ref(), a.depth),
+ (None, None, 0)
+ );
+ assert!(!a.labels.contains_key(PARENT_LABEL));
+ let a1 = &all["local:a1"];
+ assert_eq!(
+ a1.parent.as_deref(),
+ Some("local:a"),
+ "its own parent stays"
+ );
+ assert_eq!((a1.root.as_deref(), a1.depth), (Some("local:a"), 1));
+ assert_eq!(
+ (all["local:a11"].root.as_deref(), all["local:a11"].depth),
+ (Some("local:a"), 2)
+ );
+ assert!(children_of(&all, "local:r").is_empty());
+ }
+
+ #[test]
+ fn depth_is_limited() {
+ assert_eq!(child_depth("local:r", 0, DEFAULT_DEPTH_LIMIT).unwrap(), 1);
+ assert_eq!(child_depth("local:a", 1, DEFAULT_DEPTH_LIMIT).unwrap(), 2);
+ let e = child_depth("local:a1", 2, DEFAULT_DEPTH_LIMIT).unwrap_err();
+ assert_eq!(e.tag(), "invalid_argument");
+ assert!(e.to_string().contains("2 levels deep"), "{e}");
+ let root = SpaceMeta {
+ depth_limit: Some(9),
+ ..Default::default()
+ };
+ assert_eq!(depth_limit(Some(&root)), MAX_DEPTH);
+ assert_eq!(depth_limit(None), DEFAULT_DEPTH_LIMIT);
+ assert!(child_depth("x", MAX_DEPTH, depth_limit(Some(&root))).is_err());
+ }
+
+ #[test]
+ fn links_say_where_a_space_is() {
+ let all = tree();
+ assert_eq!(
+ TreeLink::of(&all["local:a1"]),
+ TreeLink {
+ parent: Some("local:a".into()),
+ root: Some("local:r".into()),
+ depth: 2,
+ origin: ORIGIN_CHILD.into(),
+ }
+ );
+ assert_eq!(TreeLink::of(&all["local:r"]).origin, ORIGIN_USER);
+ }
+}
diff --git a/libs/cua/crates/cua-spaces/tests/delete_unregistered.rs b/libs/cua/crates/cua-spaces/tests/delete_unregistered.rs
new file mode 100644
index 0000000000..2ccddd44ad
--- /dev/null
+++ b/libs/cua/crates/cua-spaces/tests/delete_unregistered.rs
@@ -0,0 +1,100 @@
+//! `cua spaces delete <name>` deletes a sandbox Cua made on this machine
+//! that no Space record names (a `cua sb fork`, a `cua sb create`), and
+//! never a VM the local runtime has that Cua did not make.
+
+use async_trait::async_trait;
+use cua_sandbox_core::{
+ InstanceStatus, LocalEndpoints, LocalInstance, LocalRuntime, LocalStartSpec, LocalSummary,
+ RuntimeError,
+};
+use cua_spaces::Spaces;
+use std::collections::BTreeSet;
+use std::sync::{Arc, Mutex};
+
+#[derive(Default)]
+struct Runtime {
+ vms: Mutex<BTreeSet<String>>,
+ deleted: Mutex<Vec<String>>,
+}
+
+#[async_trait]
+impl LocalRuntime for Runtime {
+ fn backend(&self) -> String {
+ "fake".into()
+ }
+ async fn start(&self, spec: &LocalStartSpec) -> Result<LocalInstance, RuntimeError> {
+ Err(RuntimeError::NotFound(spec.name.clone()))
+ }
+ async fn stop(&self, _name: &str) -> Result<(), RuntimeError> {
+ Ok(())
+ }
+ async fn resume(&self, name: &str) -> Result<LocalInstance, RuntimeError> {
+ Err(RuntimeError::NotFound(name.into()))
+ }
+ async fn list(&self) -> Result<Vec<LocalSummary>, RuntimeError> {
+ Ok(vec![])
+ }
+ async fn status(&self, name: &str) -> Result<InstanceStatus, RuntimeError> {
+ if self.vms.lock().unwrap().contains(name) {
+ Ok(InstanceStatus::Running)
+ } else {
+ Err(RuntimeError::NotFound(name.into()))
+ }
+ }
+ async fn delete(&self, name: &str) -> Result<(), RuntimeError> {
+ self.deleted.lock().unwrap().push(name.into());
+ if self.vms.lock().unwrap().remove(name) {
+ Ok(())
+ } else {
+ Err(RuntimeError::NotFound(name.into()))
+ }
+ }
+ async fn endpoints(&self, _name: &str) -> Result<LocalEndpoints, RuntimeError> {
+ Ok(LocalEndpoints::default())
+ }
+}
+
+/// The state record a local sandbox create or fork leaves.
+fn record(dir: &std::path::Path, name: &str) {
+ std::fs::create_dir_all(dir).unwrap();
+ let state = serde_json::json!({
+ "name": name, "runtime_type": "fake", "image": {}, "host": "127.0.0.1",
+ "api_port": 9, "status": "running", "created_at": "2026-10-27T00:00:00+00:00",
+ });
+ std::fs::write(dir.join(format!("{name}.json")), state.to_string()).unwrap();
+}
+
+#[tokio::test]
+async fn a_forked_sandbox_deletes_by_name_but_a_foreign_vm_does_not() {
+ let home = tempfile::tempdir().unwrap();
+ let state = tempfile::tempdir().unwrap();
+ let rt = Arc::new(Runtime::default());
+ rt.vms
+ .lock()
+ .unwrap()
+ .extend(["forked".to_string(), "someone-elses-vm".to_string()]);
+ record(state.path(), "forked");
+ let spaces = Spaces::builder()
+ .home(home.path())
+ .sandboxes(
+ cua_sandbox_core::Sandboxes::builder()
+ .local(rt.clone())
+ .state_dir(state.path())
+ .build(),
+ )
+ .build();
+
+ let msg = spaces.delete("forked").await.unwrap();
+ assert!(msg.contains("local:forked"), "{msg}");
+ assert!(rt.deleted.lock().unwrap().contains(&"forked".to_string()));
+
+ let err = spaces.delete("someone-elses-vm").await.unwrap_err();
+ assert!(err.to_string().contains("not found"), "{err}");
+ assert!(
+ !rt.deleted
+ .lock()
+ .unwrap()
+ .contains(&"someone-elses-vm".to_string())
+ );
+ assert!(rt.vms.lock().unwrap().contains("someone-elses-vm"));
+}
diff --git a/libs/cua/crates/cua-spaces/tests/host_spaces.rs b/libs/cua/crates/cua-spaces/tests/host_spaces.rs
index ce5723f2c3..ecc13eac7b 100644
--- a/libs/cua/crates/cua-spaces/tests/host_spaces.rs
+++ b/libs/cua/crates/cua-spaces/tests/host_spaces.rs
@@ -2868,10 +2868,11 @@ async fn network_none_on_a_host_too_old_to_enforce_it_is_refused() {
msg.contains("too old") && msg.contains("update cua"),
"{msg}"
);
- // The host made it with outbound network, then deleted it on request.
+ // The host made it (this fixture's host runs current code, so what an old
+ // host would leave open is not simulated; the refusal is the client's),
+ // then deleted it on request.
let started = f.rt.started.lock().unwrap().clone();
assert_eq!(started.len(), 1, "{started:?}");
- assert!(!started[0].restrict_network, "the old host never cut it");
assert_eq!(
*f.rt.deleted.lock().unwrap(),
[started[0].name.clone()],
diff --git a/libs/cua/crates/cua-spacesd-client/src/testing.rs b/libs/cua/crates/cua-spacesd-client/src/testing.rs
index 75a7f9df1d..4d1794d7fd 100644
--- a/libs/cua/crates/cua-spacesd-client/src/testing.rs
+++ b/libs/cua/crates/cua-spacesd-client/src/testing.rs
@@ -1748,6 +1748,41 @@ impl ProcessService for Svc {
killed: 0,
}))
}
+
+ async fn put_service(
+ &self,
+ _: tonic::Request<pb::PutServiceRequest>,
+ ) -> Result<tonic::Response<pb::PutServiceResponse>, Status> {
+ Err(Status::unimplemented("mock: services"))
+ }
+
+ async fn delete_service(
+ &self,
+ _: tonic::Request<pb::DeleteServiceRequest>,
+ ) -> Result<tonic::Response<pb::DeleteServiceResponse>, Status> {
+ Err(Status::unimplemented("mock: services"))
+ }
+
+ async fn list_services(
+ &self,
+ _: tonic::Request<pb::ListServicesRequest>,
+ ) -> Result<tonic::Response<pb::ListServicesResponse>, Status> {
+ Err(Status::unimplemented("mock: services"))
+ }
+
+ async fn control_service(
+ &self,
+ _: tonic::Request<pb::ControlServiceRequest>,
+ ) -> Result<tonic::Response<pb::ControlServiceResponse>, Status> {
+ Err(Status::unimplemented("mock: services"))
+ }
+
+ async fn get_service_logs(
+ &self,
+ _: tonic::Request<pb::GetServiceLogsRequest>,
+ ) -> Result<tonic::Response<pb::GetServiceLogsResponse>, Status> {
+ Err(Status::unimplemented("mock: services"))
+ }
}
// --------------------------------------------------------------- filesystem
@@ -3162,6 +3197,27 @@ impl TunnelService for Svc {
) -> Result<tonic::Response<pb::GetHotspotStatusResponse>, Status> {
Err(Status::unimplemented("mock: hotspot"))
}
+
+ async fn start_spawn(
+ &self,
+ _: tonic::Request<pb::StartSpawnRequest>,
+ ) -> Result<tonic::Response<pb::StartSpawnResponse>, Status> {
+ Err(Status::unimplemented("mock: spawn"))
+ }
+
+ async fn stop_spawn(
+ &self,
+ _: tonic::Request<pb::StopSpawnRequest>,
+ ) -> Result<tonic::Response<pb::StopSpawnResponse>, Status> {
+ Err(Status::unimplemented("mock: spawn"))
+ }
+
+ async fn get_spawn_status(
+ &self,
+ _: tonic::Request<pb::GetSpawnStatusRequest>,
+ ) -> Result<tonic::Response<pb::GetSpawnStatusResponse>, Status> {
+ Err(Status::unimplemented("mock: spawn"))
+ }
}
/// Whether a fresh connection is a `GET …/tunnel` request (peeked, bounded).
diff --git a/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/host_egress_pb.ts b/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/host_egress_pb.ts
index 472600af5d..06348be8a4 100644
--- a/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/host_egress_pb.ts
+++ b/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/host_egress_pb.ts
@@ -14,7 +14,7 @@ import type { Message } from "@bufbuild/protobuf";
* Describes the file cua/env/v1/host_egress.proto.
*/
export const file_cua_env_v1_host_egress: GenFile = /*@__PURE__*/
- fileDesc("ChxjdWEvZW52L3YxL2hvc3RfZWdyZXNzLnByb3RvEgpjdWEuZW52LnYxIi8KEEhvc3RFZ3Jlc3NQb2xpY3kSDQoFYWxsb3cYASADKAkSDAoEZGVueRgCIAMoCSJYChlTZXRIb3N0U3BhY2VFZ3Jlc3NSZXF1ZXN0Eg0KBXNwYWNlGAEgASgJEiwKBmVncmVzcxgCIAEoCzIcLmN1YS5lbnYudjEuSG9zdEVncmVzc1BvbGljeSIuChpTZXRIb3N0U3BhY2VFZ3Jlc3NSZXNwb25zZRIQCghlbmZvcmNlZBgBIAEoCWIGcHJvdG8z");
+ fileDesc("ChxjdWEvZW52L3YxL2hvc3RfZWdyZXNzLnByb3RvEgpjdWEuZW52LnYxIi8KEEhvc3RFZ3Jlc3NQb2xpY3kSDQoFYWxsb3cYASADKAkSDAoEZGVueRgCIAMoCSJYChlTZXRIb3N0U3BhY2VFZ3Jlc3NSZXF1ZXN0Eg0KBXNwYWNlGAEgASgJEiwKBmVncmVzcxgCIAEoCzIcLmN1YS5lbnYudjEuSG9zdEVncmVzc1BvbGljeSIuChpTZXRIb3N0U3BhY2VFZ3Jlc3NSZXNwb25zZRIQCghlbmZvcmNlZBgBIAEoCSKhAQoTSG9zdE5ldHdvcmtTZXR0aW5ncxIOCgZwcmVzZXQYASABKAkSFwoPbG9jYWxob3N0X3BvcnRzGAIgAygNEhsKE2FsbF9sb2NhbGhvc3RfcG9ydHMYAyABKAgSDQoFYWxsb3cYBCADKAkSDAoEZGVueRgFIAMoCRITCgtjdXN0b21fYmFzZRgGIAEoCRISCgp3aWRlbmVkX2J5GAcgASgJYgZwcm90bzM");
/**
* Which destinations a Space may open connections to: every `deny` entry
@@ -96,3 +96,68 @@ export type SetHostSpaceEgressResponse = Message<"cua.env.v1.SetHostSpaceEgressR
export const SetHostSpaceEgressResponseSchema: GenMessage<SetHostSpaceEgressResponse> = /*@__PURE__*/
messageDesc(file_cua_env_v1_host_egress, 2);
+/**
+ * A Space's network settings (`cua.daemon.v1.NetworkSettings`), as
+ * `CreateHostSpaceRequest.network_settings` carries them to the host that
+ * creates the Space and enforces them.
+ *
+ * @generated from message cua.env.v1.HostNetworkSettings
+ */
+export type HostNetworkSettings = Message<"cua.env.v1.HostNetworkSettings"> & {
+ /**
+ * The preset word; empty is "internet".
+ *
+ * @generated from field: string preset = 1;
+ */
+ preset: string;
+
+ /**
+ * "localhost": the host loopback ports the Space may reach.
+ *
+ * @generated from field: repeated uint32 localhost_ports = 2;
+ */
+ localhostPorts: number[];
+
+ /**
+ * "localhost": every port.
+ *
+ * @generated from field: bool all_localhost_ports = 3;
+ */
+ allLocalhostPorts: boolean;
+
+ /**
+ * Destinations that stay reachable.
+ *
+ * @generated from field: repeated string allow = 4;
+ */
+ allow: string[];
+
+ /**
+ * Destinations that are blocked.
+ *
+ * @generated from field: repeated string deny = 5;
+ */
+ deny: string[];
+
+ /**
+ * "custom": "internet" (empty) or "none".
+ *
+ * @generated from field: string custom_base = 6;
+ */
+ customBase: string;
+
+ /**
+ * Set when the Space was allowed more than its parent.
+ *
+ * @generated from field: string widened_by = 7;
+ */
+ widenedBy: string;
+};
+
+/**
+ * Describes the message cua.env.v1.HostNetworkSettings.
+ * Use `create(HostNetworkSettingsSchema)` to create a new message.
+ */
+export const HostNetworkSettingsSchema: GenMessage<HostNetworkSettings> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_host_egress, 3);
+
diff --git a/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/host_pb.ts b/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/host_pb.ts
index 1d0c257f58..a8744b5785 100644
--- a/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/host_pb.ts
+++ b/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/host_pb.ts
@@ -8,7 +8,7 @@ import type { HostNodeStatus } from "./capacity_pb";
import { file_cua_env_v1_capacity } from "./capacity_pb";
import type { DiagnoseReport } from "./diagnose_pb";
import { file_cua_env_v1_diagnose } from "./diagnose_pb";
-import type { HostEgressPolicy, SetHostSpaceEgressRequestSchema, SetHostSpaceEgressResponseSchema } from "./host_egress_pb";
+import type { HostEgressPolicy, HostNetworkSettings, SetHostSpaceEgressRequestSchema, SetHostSpaceEgressResponseSchema } from "./host_egress_pb";
import { file_cua_env_v1_host_egress } from "./host_egress_pb";
import type { AttachRelayRequest } from "./system_pb";
import { file_cua_env_v1_system } from "./system_pb";
@@ -20,7 +20,7 @@ import type { Message } from "@bufbuild/protobuf";
* Describes the file cua/env/v1/host.proto.
*/
export const file_cua_env_v1_host: GenFile = /*@__PURE__*/
- fileDesc("ChVjdWEvZW52L3YxL2hvc3QucHJvdG8SCmN1YS5lbnYudjEiJgoTRGlhZ25vc2VIb3N0UmVxdWVzdBIPCgdtYWNoaW5lGAEgASgJImMKFERpYWdub3NlSG9zdFJlc3BvbnNlEioKBnJlcG9ydBgBIAEoCzIaLmN1YS5lbnYudjEuRGlhZ25vc2VSZXBvcnQSEwoLY3VhX3ZlcnNpb24YAiABKAkSCgoCb3MYAyABKAkiswEKEkhvc3RTcGFjZXNTZXR0aW5ncxIVCg1zaGFyZV9kZXNrdG9wGAEgASgIEhYKDnByb3ZpZGVfc3BhY2VzGAIgASgIEhIKCm1heF9zcGFjZXMYAyABKA0SFQoNbWF4X21hY29zX3ZtcxgEIAEoDRIVCg1tYXhfbWVtb3J5X2diGAUgASgNEhMKC21heF9kaXNrX2diGAYgASgNEhcKD21heF9ydW5fbWludXRlcxgHIAEoDSJTChJIb3N0U3BhY2VzQ2FwYWNpdHkSEAoIcmVzb3VyY2UYASABKAkSDAoEdXNlZBgCIAEoDRINCgVsaW1pdBgDIAEoDRIOCgZyZWFzb24YBCABKAkiqAIKCUhvc3RTcGFjZRIVCg1yZWxheV9tYWNoaW5lGAEgASgJEhMKC2xvY2FsX3NwYWNlGAIgASgJEgwKBG5hbWUYAyABKAkSDQoFaW1hZ2UYBCABKAkSCgoCb3MYBSABKAkSDAoEa2luZBgGIAEoCRIPCgdydW50aW1lGAcgASgJEhIKCmNyZWF0ZWRfYnkYCCABKAkSFQoNY3JlYXRlZF9hdF9tcxgJIAEoAxITCgtkaXJlY3RfcG9ydBgKIAEoDRIUCgxkaXJlY3RfdG9rZW4YCyABKAkSFwoPZWdyZXNzX2VuZm9yY2VkGBQgASgJEg8KB25ldHdvcmsYFSABKAkSJwoEZGlzaxgWIAEoCzIZLmN1YS5lbnYudjEuSG9zdFNwYWNlRGlzayJWCg1Ib3N0U3BhY2VEaXNrEhIKBWJ5dGVzGAEgASgESACIAQESEQoJYWxsb2NhdGVkGAIgASgEEhQKDHNoYXJlc19zcGFjZRgDIAEoCEIICgZfYnl0ZXMiJAoUR2V0SG9zdFNwYWNlc1JlcXVlc3QSDAoEZGlzaxgBIAEoCCLYAgoVR2V0SG9zdFNwYWNlc1Jlc3BvbnNlEgwKBG5hbWUYASABKAkSCgoCb3MYAiABKAkSMAoIc2V0dGluZ3MYAyABKAsyHi5jdWEuZW52LnYxLkhvc3RTcGFjZXNTZXR0aW5ncxIwCghjYXBhY2l0eRgEIAMoCzIeLmN1YS5lbnYudjEuSG9zdFNwYWNlc0NhcGFjaXR5EiUKBnNwYWNlcxgFIAMoCzIVLmN1YS5lbnYudjEuSG9zdFNwYWNlEi8KBWF1ZGl0GAYgAygLMiAuY3VhLmVudi52MS5Ib3N0U3BhY2VzQXVkaXRFdmVudBIOCgZpbWFnZXMYByADKAkSLwoIY3JlYXRpbmcYCCADKAsyHS5jdWEuZW52LnYxLkhvc3RTcGFjZUNyZWF0aW5nEigKBG5vZGUYCSABKAsyGi5jdWEuZW52LnYxLkhvc3ROb2RlU3RhdHVzIsMDChZDcmVhdGVIb3N0U3BhY2VSZXF1ZXN0Eg0KBWltYWdlGAEgASgJEgwKBGtpbmQYAiABKAkSDwoHcnVudGltZRgDIAEoCRIMCgRuYW1lGAQgASgJEgwKBGNwdXMYBSABKA0SEQoJbWVtb3J5X21iGAYgASgEEg8KB2Rpc2tfZ2IYByABKA0SLgoGYXR0YWNoGAggASgLMh4uY3VhLmVudi52MS5BdHRhY2hSZWxheVJlcXVlc3QSDgoGZGlyZWN0GAkgASgIEhIKCmNyZWF0ZV9rZXkYCiABKAkSDwoHbmV0d29yaxgMIAEoCRITCgtmb3JrX3NvdXJjZRgLIAEoCRIQCghoZWFkbGVzcxgOIAEoCBIsCgZlZ3Jlc3MYEyABKAsyHC5jdWEuZW52LnYxLkhvc3RFZ3Jlc3NQb2xpY3kSDgoGcm91dGVkGA0gASgIEjgKA2VudhgPIAMoCzIrLmN1YS5lbnYudjEuQ3JlYXRlSG9zdFNwYWNlUmVxdWVzdC5FbnZFbnRyeRILCgNncHUYECABKAkaKgoIRW52RW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASI/ChdDcmVhdGVIb3N0U3BhY2VSZXNwb25zZRIkCgVzcGFjZRgBIAEoCzIVLmN1YS5lbnYudjEuSG9zdFNwYWNlIicKFkRlbGV0ZUhvc3RTcGFjZVJlcXVlc3QSDQoFc3BhY2UYASABKAkiKgoXRGVsZXRlSG9zdFNwYWNlUmVzcG9uc2USDwoHbWVzc2FnZRgBIAEoCSIoChdEZWxldGVDbG91ZFNwYWNlUmVxdWVzdBINCgVzcGFjZRgBIAEoCSIrChhEZWxldGVDbG91ZFNwYWNlUmVzcG9uc2USDwoHbWVzc2FnZRgBIAEoCSInChZDYW5jZWxIb3N0U3BhY2VSZXF1ZXN0Eg0KBXNwYWNlGAEgASgJIioKF0NhbmNlbEhvc3RTcGFjZVJlc3BvbnNlEg8KB21lc3NhZ2UYASABKAkiNQoYU2V0SG9zdFNwYWNlUG93ZXJSZXF1ZXN0Eg0KBXNwYWNlGAEgASgJEgoKAm9uGAIgASgIIkoKGVNldEhvc3RTcGFjZVBvd2VyUmVzcG9uc2USDQoFc3RhdGUYASABKAkSDQoFcG93ZXIYAiABKAkSDwoHbWVzc2FnZRgDIAEoCSL3AgoLSG9zdEpvYlNwZWMSDgoGam9iX2lkGAEgASgJEg8KB2F0dGVtcHQYAiABKA0SDQoFaW1hZ2UYAyABKAkSDAoEa2luZBgEIAEoCRIPCgdydW50aW1lGAUgASgJEhEKCW1pbGxpY3B1cxgGIAEoDRIRCgltZW1vcnlfbWIYByABKAQSDAoEYXJndhgIIAMoCRItCgNlbnYYCSADKAsyIC5jdWEuZW52LnYxLkhvc3RKb2JTcGVjLkVudkVudHJ5EhQKDHRpbWVvdXRfc2VjcxgKIAEoDRITCgtyZXN1bHRfcGF0aBgLIAEoCRIYChBtYXhfb3V0cHV0X2J5dGVzGAwgASgNEg4KBmJ1bmRsZRgNIAEoDBIOCgZydW5faWQYDiABKAkSEwoLYWNjZWxlcmF0b3IYDyABKAkSEAoIc2VydmljZXMYECADKAkaKgoIRW52RW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASJOChJSdW5Ib3N0Sm9ic1JlcXVlc3QSJQoEam9icxgBIAMoCzIXLmN1YS5lbnYudjEuSG9zdEpvYlNwZWMSEQoJc2NoZWR1bGVyGAIgASgJInAKCkhvc3RKb2JBY2sSDgoGam9iX2lkGAEgASgJEg8KB2F0dGVtcHQYAiABKA0SDwoHb3V0Y29tZRgDIAEoCRIOCgZyZWFzb24YBCABKAkSIAoDam9iGAUgASgLMhMuY3VhLmVudi52MS5Ib3N0Sm9iImUKE1J1bkhvc3RKb2JzUmVzcG9uc2USJAoEYWNrcxgBIAMoCzIWLmN1YS5lbnYudjEuSG9zdEpvYkFjaxIoCgRub2RlGAIgASgLMhouY3VhLmVudi52MS5Ib3N0Tm9kZVN0YXR1cyLGAgoHSG9zdEpvYhIOCgZqb2JfaWQYASABKAkSDwoHYXR0ZW1wdBgCIAEoDRINCgVzdGF0ZRgDIAEoCRIWCglleGl0X2NvZGUYBCABKAVIAIgBARIRCgl0aW1lZF9vdXQYBSABKAgSDgoGc3Rkb3V0GAYgASgMEg4KBnN0ZGVychgHIAEoDBIOCgZyZXN1bHQYCCABKAwSDQoFZXJyb3IYCSABKAkSCwoDc2VxGAogASgEEg0KBXNwYWNlGAsgASgJEhYKDmFjY2VwdGVkX2F0X21zGAwgASgDEhYKDmZpbmlzaGVkX2F0X21zGA0gASgDEhEKCWNyZWF0ZV9tcxgOIAEoDRIOCgZydW5fbXMYDyABKA0SEQoJZGVsZXRlX21zGBAgASgNEhEKCXRydW5jYXRlZBgRIAEoCEIMCgpfZXhpdF9jb2RlIk0KEUdldEhvc3RKb2JSZXF1ZXN0Eg4KBmpvYl9pZBgBIAEoCRIYCgtvdXRwdXRfZnJvbRgCIAEoBEgAiAEBQg4KDF9vdXRwdXRfZnJvbSKLAQoSR2V0SG9zdEpvYlJlc3BvbnNlEiAKA2pvYhgBIAEoCzITLmN1YS5lbnYudjEuSG9zdEpvYhIoCgRub2RlGAIgASgLMhouY3VhLmVudi52MS5Ib3N0Tm9kZVN0YXR1cxIUCgxvdXRwdXRfY2h1bmsYAyABKAwSEwoLb3V0cHV0X3NpemUYBCABKAQiiQEKE0xpc3RIb3N0Sm9ic1JlcXVlc3QSEQoJYWZ0ZXJfc2VxGAEgASgEEg0KBWxpbWl0GAIgASgNEg8KB3dhaXRfbXMYAyABKA0SFgoOd2l0aG91dF9vdXRwdXQYBCABKAgSJwoHcmVsZWFzZRgFIAMoCzIWLmN1YS5lbnYudjEuSG9zdEpvYlJlZiItCgpIb3N0Sm9iUmVmEg4KBmpvYl9pZBgBIAEoCRIPCgdhdHRlbXB0GAIgASgNInsKD0hvc3RKb2JQcm9ncmVzcxIOCgZqb2JfaWQYASABKAkSDwoHYXR0ZW1wdBgCIAEoDRINCgVyZWFkeRgDIAEoCBIQCghyZWxlYXNlZBgEIAEoCBIYChBsYXN0X3Byb2dyZXNzX21zGAUgASgDEgwKBHN0ZXAYBiABKAMisgEKFExpc3RIb3N0Sm9ic1Jlc3BvbnNlEiEKBGpvYnMYASADKAsyEy5jdWEuZW52LnYxLkhvc3RKb2ISEAoIbmV4dF9zZXEYAiABKAQSDAoEbW9yZRgDIAEoCBIoCgRub2RlGAQgASgLMhouY3VhLmVudi52MS5Ib3N0Tm9kZVN0YXR1cxItCghwcm9ncmVzcxgFIAMoCzIbLmN1YS5lbnYudjEuSG9zdEpvYlByb2dyZXNzIkcKFENhbmNlbEhvc3RKb2JSZXF1ZXN0Eg4KBmpvYl9pZBgBIAEoCRIPCgdhdHRlbXB0GAIgASgNEg4KBnJlYXNvbhgDIAEoCSI5ChVDYW5jZWxIb3N0Sm9iUmVzcG9uc2USIAoDam9iGAEgASgLMhMuY3VhLmVudi52MS5Ib3N0Sm9iImEKFEhvc3RTcGFjZXNBdWRpdEV2ZW50Eg0KBXRzX21zGAEgASgDEg4KBmFjdGlvbhgCIAEoCRILCgN3aG8YAyABKAkSDQoFc3BhY2UYBCABKAkSDgoGZGV0YWlsGAUgASgJIukBChFIb3N0U3BhY2VDcmVhdGluZxILCgNrZXkYASABKAkSDQoFcGhhc2UYAiABKAkSFQoIZnJhY3Rpb24YAyABKAFIAIgBARIOCgZkZXRhaWwYBCABKAkSFwoKYnl0ZXNfZG9uZRgFIAEoBEgBiAEBEhgKC2J5dGVzX3RvdGFsGAYgASgESAKIAQESHQoQYnl0ZXNfcGVyX3NlY29uZBgHIAEoAUgDiAEBQgsKCV9mcmFjdGlvbkINCgtfYnl0ZXNfZG9uZUIOCgxfYnl0ZXNfdG90YWxCEwoRX2J5dGVzX3Blcl9zZWNvbmQiTAoVQ2FsbFRocmVhZFRvb2xSZXF1ZXN0Eg0KBXNwYWNlGAEgASgJEgwKBG5hbWUYAiABKAkSFgoOYXJndW1lbnRzX2pzb24YAyABKAkibAoWQ2FsbFRocmVhZFRvb2xSZXNwb25zZRIUCgxjb250ZW50X2pzb24YASABKAkSFwoPc3RydWN0dXJlZF9qc29uGAIgASgJEhAKCGlzX2Vycm9yGAMgASgIEhEKCW1ldGFfanNvbhgEIAEoCSJJCgpUaHJlYWRWaWV3EgwKBGtpbmQYASABKAkSCwoDYXBwGAIgASgJEg0KBXRpdGxlGAMgASgJEhEKCXdpbmRvd19pZBgEIAEoCTLGBgoRSG9zdFNwYWNlc1NlcnZpY2USVAoNR2V0SG9zdFNwYWNlcxIgLmN1YS5lbnYudjEuR2V0SG9zdFNwYWNlc1JlcXVlc3QaIS5jdWEuZW52LnYxLkdldEhvc3RTcGFjZXNSZXNwb25zZRJaCg9DcmVhdGVIb3N0U3BhY2USIi5jdWEuZW52LnYxLkNyZWF0ZUhvc3RTcGFjZVJlcXVlc3QaIy5jdWEuZW52LnYxLkNyZWF0ZUhvc3RTcGFjZVJlc3BvbnNlEloKD0RlbGV0ZUhvc3RTcGFjZRIiLmN1YS5lbnYudjEuRGVsZXRlSG9zdFNwYWNlUmVxdWVzdBojLmN1YS5lbnYudjEuRGVsZXRlSG9zdFNwYWNlUmVzcG9uc2USWgoPQ2FuY2VsSG9zdFNwYWNlEiIuY3VhLmVudi52MS5DYW5jZWxIb3N0U3BhY2VSZXF1ZXN0GiMuY3VhLmVudi52MS5DYW5jZWxIb3N0U3BhY2VSZXNwb25zZRJgChFTZXRIb3N0U3BhY2VQb3dlchIkLmN1YS5lbnYudjEuU2V0SG9zdFNwYWNlUG93ZXJSZXF1ZXN0GiUuY3VhLmVudi52MS5TZXRIb3N0U3BhY2VQb3dlclJlc3BvbnNlEk4KC1NldEhvc3RXYXJtEh4uY3VhLmVudi52MS5TZXRIb3N0V2FybVJlcXVlc3QaHy5jdWEuZW52LnYxLlNldEhvc3RXYXJtUmVzcG9uc2USXQoQRGVsZXRlQ2xvdWRTcGFjZRIjLmN1YS5lbnYudjEuRGVsZXRlQ2xvdWRTcGFjZVJlcXVlc3QaJC5jdWEuZW52LnYxLkRlbGV0ZUNsb3VkU3BhY2VSZXNwb25zZRJjChJTZXRIb3N0U3BhY2VFZ3Jlc3MSJS5jdWEuZW52LnYxLlNldEhvc3RTcGFjZUVncmVzc1JlcXVlc3QaJi5jdWEuZW52LnYxLlNldEhvc3RTcGFjZUVncmVzc1Jlc3BvbnNlElEKDERpYWdub3NlSG9zdBIfLmN1YS5lbnYudjEuRGlhZ25vc2VIb3N0UmVxdWVzdBogLmN1YS5lbnYudjEuRGlhZ25vc2VIb3N0UmVzcG9uc2Uy1wIKD0hvc3RKb2JzU2VydmljZRJOCgtSdW5Ib3N0Sm9icxIeLmN1YS5lbnYudjEuUnVuSG9zdEpvYnNSZXF1ZXN0Gh8uY3VhLmVudi52MS5SdW5Ib3N0Sm9ic1Jlc3BvbnNlEksKCkdldEhvc3RKb2ISHS5jdWEuZW52LnYxLkdldEhvc3RKb2JSZXF1ZXN0Gh4uY3VhLmVudi52MS5HZXRIb3N0Sm9iUmVzcG9uc2USUQoMTGlzdEhvc3RKb2JzEh8uY3VhLmVudi52MS5MaXN0SG9zdEpvYnNSZXF1ZXN0GiAuY3VhLmVudi52MS5MaXN0SG9zdEpvYnNSZXNwb25zZRJUCg1DYW5jZWxIb3N0Sm9iEiAuY3VhLmVudi52MS5DYW5jZWxIb3N0Sm9iUmVxdWVzdBohLmN1YS5lbnYudjEuQ2FuY2VsSG9zdEpvYlJlc3BvbnNlMmwKEUhvc3RUaHJlYWRTZXJ2aWNlElcKDkNhbGxUaHJlYWRUb29sEiEuY3VhLmVudi52MS5DYWxsVGhyZWFkVG9vbFJlcXVlc3QaIi5jdWEuZW52LnYxLkNhbGxUaHJlYWRUb29sUmVzcG9uc2ViBnByb3RvMw", [file_cua_env_v1_capacity, file_cua_env_v1_diagnose, file_cua_env_v1_host_egress, file_cua_env_v1_system, file_cua_env_v1_warm]);
+ fileDesc("ChVjdWEvZW52L3YxL2hvc3QucHJvdG8SCmN1YS5lbnYudjEiJgoTRGlhZ25vc2VIb3N0UmVxdWVzdBIPCgdtYWNoaW5lGAEgASgJImMKFERpYWdub3NlSG9zdFJlc3BvbnNlEioKBnJlcG9ydBgBIAEoCzIaLmN1YS5lbnYudjEuRGlhZ25vc2VSZXBvcnQSEwoLY3VhX3ZlcnNpb24YAiABKAkSCgoCb3MYAyABKAkiswEKEkhvc3RTcGFjZXNTZXR0aW5ncxIVCg1zaGFyZV9kZXNrdG9wGAEgASgIEhYKDnByb3ZpZGVfc3BhY2VzGAIgASgIEhIKCm1heF9zcGFjZXMYAyABKA0SFQoNbWF4X21hY29zX3ZtcxgEIAEoDRIVCg1tYXhfbWVtb3J5X2diGAUgASgNEhMKC21heF9kaXNrX2diGAYgASgNEhcKD21heF9ydW5fbWludXRlcxgHIAEoDSJTChJIb3N0U3BhY2VzQ2FwYWNpdHkSEAoIcmVzb3VyY2UYASABKAkSDAoEdXNlZBgCIAEoDRINCgVsaW1pdBgDIAEoDRIOCgZyZWFzb24YBCABKAkiqAIKCUhvc3RTcGFjZRIVCg1yZWxheV9tYWNoaW5lGAEgASgJEhMKC2xvY2FsX3NwYWNlGAIgASgJEgwKBG5hbWUYAyABKAkSDQoFaW1hZ2UYBCABKAkSCgoCb3MYBSABKAkSDAoEa2luZBgGIAEoCRIPCgdydW50aW1lGAcgASgJEhIKCmNyZWF0ZWRfYnkYCCABKAkSFQoNY3JlYXRlZF9hdF9tcxgJIAEoAxITCgtkaXJlY3RfcG9ydBgKIAEoDRIUCgxkaXJlY3RfdG9rZW4YCyABKAkSFwoPZWdyZXNzX2VuZm9yY2VkGBQgASgJEg8KB25ldHdvcmsYFSABKAkSJwoEZGlzaxgWIAEoCzIZLmN1YS5lbnYudjEuSG9zdFNwYWNlRGlzayJWCg1Ib3N0U3BhY2VEaXNrEhIKBWJ5dGVzGAEgASgESACIAQESEQoJYWxsb2NhdGVkGAIgASgEEhQKDHNoYXJlc19zcGFjZRgDIAEoCEIICgZfYnl0ZXMiJAoUR2V0SG9zdFNwYWNlc1JlcXVlc3QSDAoEZGlzaxgBIAEoCCLYAgoVR2V0SG9zdFNwYWNlc1Jlc3BvbnNlEgwKBG5hbWUYASABKAkSCgoCb3MYAiABKAkSMAoIc2V0dGluZ3MYAyABKAsyHi5jdWEuZW52LnYxLkhvc3RTcGFjZXNTZXR0aW5ncxIwCghjYXBhY2l0eRgEIAMoCzIeLmN1YS5lbnYudjEuSG9zdFNwYWNlc0NhcGFjaXR5EiUKBnNwYWNlcxgFIAMoCzIVLmN1YS5lbnYudjEuSG9zdFNwYWNlEi8KBWF1ZGl0GAYgAygLMiAuY3VhLmVudi52MS5Ib3N0U3BhY2VzQXVkaXRFdmVudBIOCgZpbWFnZXMYByADKAkSLwoIY3JlYXRpbmcYCCADKAsyHS5jdWEuZW52LnYxLkhvc3RTcGFjZUNyZWF0aW5nEigKBG5vZGUYCSABKAsyGi5jdWEuZW52LnYxLkhvc3ROb2RlU3RhdHVzIv4DChZDcmVhdGVIb3N0U3BhY2VSZXF1ZXN0Eg0KBWltYWdlGAEgASgJEgwKBGtpbmQYAiABKAkSDwoHcnVudGltZRgDIAEoCRIMCgRuYW1lGAQgASgJEgwKBGNwdXMYBSABKA0SEQoJbWVtb3J5X21iGAYgASgEEg8KB2Rpc2tfZ2IYByABKA0SLgoGYXR0YWNoGAggASgLMh4uY3VhLmVudi52MS5BdHRhY2hSZWxheVJlcXVlc3QSDgoGZGlyZWN0GAkgASgIEhIKCmNyZWF0ZV9rZXkYCiABKAkSDwoHbmV0d29yaxgMIAEoCRITCgtmb3JrX3NvdXJjZRgLIAEoCRIQCghoZWFkbGVzcxgOIAEoCBIsCgZlZ3Jlc3MYEyABKAsyHC5jdWEuZW52LnYxLkhvc3RFZ3Jlc3NQb2xpY3kSOQoQbmV0d29ya19zZXR0aW5ncxgUIAEoCzIfLmN1YS5lbnYudjEuSG9zdE5ldHdvcmtTZXR0aW5ncxIOCgZyb3V0ZWQYDSABKAgSOAoDZW52GA8gAygLMisuY3VhLmVudi52MS5DcmVhdGVIb3N0U3BhY2VSZXF1ZXN0LkVudkVudHJ5EgsKA2dwdRgQIAEoCRoqCghFbnZFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBIj8KF0NyZWF0ZUhvc3RTcGFjZVJlc3BvbnNlEiQKBXNwYWNlGAEgASgLMhUuY3VhLmVudi52MS5Ib3N0U3BhY2UiJwoWRGVsZXRlSG9zdFNwYWNlUmVxdWVzdBINCgVzcGFjZRgBIAEoCSIqChdEZWxldGVIb3N0U3BhY2VSZXNwb25zZRIPCgdtZXNzYWdlGAEgASgJIigKF0RlbGV0ZUNsb3VkU3BhY2VSZXF1ZXN0Eg0KBXNwYWNlGAEgASgJIisKGERlbGV0ZUNsb3VkU3BhY2VSZXNwb25zZRIPCgdtZXNzYWdlGAEgASgJIicKFkNhbmNlbEhvc3RTcGFjZVJlcXVlc3QSDQoFc3BhY2UYASABKAkiKgoXQ2FuY2VsSG9zdFNwYWNlUmVzcG9uc2USDwoHbWVzc2FnZRgBIAEoCSI1ChhTZXRIb3N0U3BhY2VQb3dlclJlcXVlc3QSDQoFc3BhY2UYASABKAkSCgoCb24YAiABKAgiSgoZU2V0SG9zdFNwYWNlUG93ZXJSZXNwb25zZRINCgVzdGF0ZRgBIAEoCRINCgVwb3dlchgCIAEoCRIPCgdtZXNzYWdlGAMgASgJIvcCCgtIb3N0Sm9iU3BlYxIOCgZqb2JfaWQYASABKAkSDwoHYXR0ZW1wdBgCIAEoDRINCgVpbWFnZRgDIAEoCRIMCgRraW5kGAQgASgJEg8KB3J1bnRpbWUYBSABKAkSEQoJbWlsbGljcHVzGAYgASgNEhEKCW1lbW9yeV9tYhgHIAEoBBIMCgRhcmd2GAggAygJEi0KA2VudhgJIAMoCzIgLmN1YS5lbnYudjEuSG9zdEpvYlNwZWMuRW52RW50cnkSFAoMdGltZW91dF9zZWNzGAogASgNEhMKC3Jlc3VsdF9wYXRoGAsgASgJEhgKEG1heF9vdXRwdXRfYnl0ZXMYDCABKA0SDgoGYnVuZGxlGA0gASgMEg4KBnJ1bl9pZBgOIAEoCRITCgthY2NlbGVyYXRvchgPIAEoCRIQCghzZXJ2aWNlcxgQIAMoCRoqCghFbnZFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBIk4KElJ1bkhvc3RKb2JzUmVxdWVzdBIlCgRqb2JzGAEgAygLMhcuY3VhLmVudi52MS5Ib3N0Sm9iU3BlYxIRCglzY2hlZHVsZXIYAiABKAkicAoKSG9zdEpvYkFjaxIOCgZqb2JfaWQYASABKAkSDwoHYXR0ZW1wdBgCIAEoDRIPCgdvdXRjb21lGAMgASgJEg4KBnJlYXNvbhgEIAEoCRIgCgNqb2IYBSABKAsyEy5jdWEuZW52LnYxLkhvc3RKb2IiZQoTUnVuSG9zdEpvYnNSZXNwb25zZRIkCgRhY2tzGAEgAygLMhYuY3VhLmVudi52MS5Ib3N0Sm9iQWNrEigKBG5vZGUYAiABKAsyGi5jdWEuZW52LnYxLkhvc3ROb2RlU3RhdHVzIsYCCgdIb3N0Sm9iEg4KBmpvYl9pZBgBIAEoCRIPCgdhdHRlbXB0GAIgASgNEg0KBXN0YXRlGAMgASgJEhYKCWV4aXRfY29kZRgEIAEoBUgAiAEBEhEKCXRpbWVkX291dBgFIAEoCBIOCgZzdGRvdXQYBiABKAwSDgoGc3RkZXJyGAcgASgMEg4KBnJlc3VsdBgIIAEoDBINCgVlcnJvchgJIAEoCRILCgNzZXEYCiABKAQSDQoFc3BhY2UYCyABKAkSFgoOYWNjZXB0ZWRfYXRfbXMYDCABKAMSFgoOZmluaXNoZWRfYXRfbXMYDSABKAMSEQoJY3JlYXRlX21zGA4gASgNEg4KBnJ1bl9tcxgPIAEoDRIRCglkZWxldGVfbXMYECABKA0SEQoJdHJ1bmNhdGVkGBEgASgIQgwKCl9leGl0X2NvZGUiTQoRR2V0SG9zdEpvYlJlcXVlc3QSDgoGam9iX2lkGAEgASgJEhgKC291dHB1dF9mcm9tGAIgASgESACIAQFCDgoMX291dHB1dF9mcm9tIosBChJHZXRIb3N0Sm9iUmVzcG9uc2USIAoDam9iGAEgASgLMhMuY3VhLmVudi52MS5Ib3N0Sm9iEigKBG5vZGUYAiABKAsyGi5jdWEuZW52LnYxLkhvc3ROb2RlU3RhdHVzEhQKDG91dHB1dF9jaHVuaxgDIAEoDBITCgtvdXRwdXRfc2l6ZRgEIAEoBCKJAQoTTGlzdEhvc3RKb2JzUmVxdWVzdBIRCglhZnRlcl9zZXEYASABKAQSDQoFbGltaXQYAiABKA0SDwoHd2FpdF9tcxgDIAEoDRIWCg53aXRob3V0X291dHB1dBgEIAEoCBInCgdyZWxlYXNlGAUgAygLMhYuY3VhLmVudi52MS5Ib3N0Sm9iUmVmIi0KCkhvc3RKb2JSZWYSDgoGam9iX2lkGAEgASgJEg8KB2F0dGVtcHQYAiABKA0iewoPSG9zdEpvYlByb2dyZXNzEg4KBmpvYl9pZBgBIAEoCRIPCgdhdHRlbXB0GAIgASgNEg0KBXJlYWR5GAMgASgIEhAKCHJlbGVhc2VkGAQgASgIEhgKEGxhc3RfcHJvZ3Jlc3NfbXMYBSABKAMSDAoEc3RlcBgGIAEoAyKyAQoUTGlzdEhvc3RKb2JzUmVzcG9uc2USIQoEam9icxgBIAMoCzITLmN1YS5lbnYudjEuSG9zdEpvYhIQCghuZXh0X3NlcRgCIAEoBBIMCgRtb3JlGAMgASgIEigKBG5vZGUYBCABKAsyGi5jdWEuZW52LnYxLkhvc3ROb2RlU3RhdHVzEi0KCHByb2dyZXNzGAUgAygLMhsuY3VhLmVudi52MS5Ib3N0Sm9iUHJvZ3Jlc3MiRwoUQ2FuY2VsSG9zdEpvYlJlcXVlc3QSDgoGam9iX2lkGAEgASgJEg8KB2F0dGVtcHQYAiABKA0SDgoGcmVhc29uGAMgASgJIjkKFUNhbmNlbEhvc3RKb2JSZXNwb25zZRIgCgNqb2IYASABKAsyEy5jdWEuZW52LnYxLkhvc3RKb2IiYQoUSG9zdFNwYWNlc0F1ZGl0RXZlbnQSDQoFdHNfbXMYASABKAMSDgoGYWN0aW9uGAIgASgJEgsKA3dobxgDIAEoCRINCgVzcGFjZRgEIAEoCRIOCgZkZXRhaWwYBSABKAki6QEKEUhvc3RTcGFjZUNyZWF0aW5nEgsKA2tleRgBIAEoCRINCgVwaGFzZRgCIAEoCRIVCghmcmFjdGlvbhgDIAEoAUgAiAEBEg4KBmRldGFpbBgEIAEoCRIXCgpieXRlc19kb25lGAUgASgESAGIAQESGAoLYnl0ZXNfdG90YWwYBiABKARIAogBARIdChBieXRlc19wZXJfc2Vjb25kGAcgASgBSAOIAQFCCwoJX2ZyYWN0aW9uQg0KC19ieXRlc19kb25lQg4KDF9ieXRlc190b3RhbEITChFfYnl0ZXNfcGVyX3NlY29uZCJMChVDYWxsVGhyZWFkVG9vbFJlcXVlc3QSDQoFc3BhY2UYASABKAkSDAoEbmFtZRgCIAEoCRIWCg5hcmd1bWVudHNfanNvbhgDIAEoCSJsChZDYWxsVGhyZWFkVG9vbFJlc3BvbnNlEhQKDGNvbnRlbnRfanNvbhgBIAEoCRIXCg9zdHJ1Y3R1cmVkX2pzb24YAiABKAkSEAoIaXNfZXJyb3IYAyABKAgSEQoJbWV0YV9qc29uGAQgASgJIkkKClRocmVhZFZpZXcSDAoEa2luZBgBIAEoCRILCgNhcHAYAiABKAkSDQoFdGl0bGUYAyABKAkSEQoJd2luZG93X2lkGAQgASgJMsYGChFIb3N0U3BhY2VzU2VydmljZRJUCg1HZXRIb3N0U3BhY2VzEiAuY3VhLmVudi52MS5HZXRIb3N0U3BhY2VzUmVxdWVzdBohLmN1YS5lbnYudjEuR2V0SG9zdFNwYWNlc1Jlc3BvbnNlEloKD0NyZWF0ZUhvc3RTcGFjZRIiLmN1YS5lbnYudjEuQ3JlYXRlSG9zdFNwYWNlUmVxdWVzdBojLmN1YS5lbnYudjEuQ3JlYXRlSG9zdFNwYWNlUmVzcG9uc2USWgoPRGVsZXRlSG9zdFNwYWNlEiIuY3VhLmVudi52MS5EZWxldGVIb3N0U3BhY2VSZXF1ZXN0GiMuY3VhLmVudi52MS5EZWxldGVIb3N0U3BhY2VSZXNwb25zZRJaCg9DYW5jZWxIb3N0U3BhY2USIi5jdWEuZW52LnYxLkNhbmNlbEhvc3RTcGFjZVJlcXVlc3QaIy5jdWEuZW52LnYxLkNhbmNlbEhvc3RTcGFjZVJlc3BvbnNlEmAKEVNldEhvc3RTcGFjZVBvd2VyEiQuY3VhLmVudi52MS5TZXRIb3N0U3BhY2VQb3dlclJlcXVlc3QaJS5jdWEuZW52LnYxLlNldEhvc3RTcGFjZVBvd2VyUmVzcG9uc2USTgoLU2V0SG9zdFdhcm0SHi5jdWEuZW52LnYxLlNldEhvc3RXYXJtUmVxdWVzdBofLmN1YS5lbnYudjEuU2V0SG9zdFdhcm1SZXNwb25zZRJdChBEZWxldGVDbG91ZFNwYWNlEiMuY3VhLmVudi52MS5EZWxldGVDbG91ZFNwYWNlUmVxdWVzdBokLmN1YS5lbnYudjEuRGVsZXRlQ2xvdWRTcGFjZVJlc3BvbnNlEmMKElNldEhvc3RTcGFjZUVncmVzcxIlLmN1YS5lbnYudjEuU2V0SG9zdFNwYWNlRWdyZXNzUmVxdWVzdBomLmN1YS5lbnYudjEuU2V0SG9zdFNwYWNlRWdyZXNzUmVzcG9uc2USUQoMRGlhZ25vc2VIb3N0Eh8uY3VhLmVudi52MS5EaWFnbm9zZUhvc3RSZXF1ZXN0GiAuY3VhLmVudi52MS5EaWFnbm9zZUhvc3RSZXNwb25zZTLXAgoPSG9zdEpvYnNTZXJ2aWNlEk4KC1J1bkhvc3RKb2JzEh4uY3VhLmVudi52MS5SdW5Ib3N0Sm9ic1JlcXVlc3QaHy5jdWEuZW52LnYxLlJ1bkhvc3RKb2JzUmVzcG9uc2USSwoKR2V0SG9zdEpvYhIdLmN1YS5lbnYudjEuR2V0SG9zdEpvYlJlcXVlc3QaHi5jdWEuZW52LnYxLkdldEhvc3RKb2JSZXNwb25zZRJRCgxMaXN0SG9zdEpvYnMSHy5jdWEuZW52LnYxLkxpc3RIb3N0Sm9ic1JlcXVlc3QaIC5jdWEuZW52LnYxLkxpc3RIb3N0Sm9ic1Jlc3BvbnNlElQKDUNhbmNlbEhvc3RKb2ISIC5jdWEuZW52LnYxLkNhbmNlbEhvc3RKb2JSZXF1ZXN0GiEuY3VhLmVudi52MS5DYW5jZWxIb3N0Sm9iUmVzcG9uc2UybAoRSG9zdFRocmVhZFNlcnZpY2USVwoOQ2FsbFRocmVhZFRvb2wSIS5jdWEuZW52LnYxLkNhbGxUaHJlYWRUb29sUmVxdWVzdBoiLmN1YS5lbnYudjEuQ2FsbFRocmVhZFRvb2xSZXNwb25zZWIGcHJvdG8z", [file_cua_env_v1_capacity, file_cua_env_v1_diagnose, file_cua_env_v1_host_egress, file_cua_env_v1_system, file_cua_env_v1_warm]);
/**
* Request for `HostSpacesService.DiagnoseHost`.
@@ -576,6 +576,14 @@ export type CreateHostSpaceRequest = Message<"cua.env.v1.CreateHostSpaceRequest"
*/
egress?: HostEgressPolicy | undefined;
+ /**
+ * Network settings, compiled and enforced by the host. Unset: what
+ * `network` and `egress` say.
+ *
+ * @generated from field: cua.env.v1.HostNetworkSettings network_settings = 20;
+ */
+ networkSettings?: HostNetworkSettings | undefined;
+
/**
* Reached through this host's channel (no relay machine of its own).
*
diff --git a/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/process_pb.ts b/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/process_pb.ts
index 956287048b..aa28b9d722 100644
--- a/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/process_pb.ts
+++ b/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/process_pb.ts
@@ -14,7 +14,7 @@ import type { Message } from "@bufbuild/protobuf";
* Describes the file cua/env/v1/process.proto.
*/
export const file_cua_env_v1_process: GenFile = /*@__PURE__*/
- fileDesc("ChhjdWEvZW52L3YxL3Byb2Nlc3MucHJvdG8SCmN1YS5lbnYudjEi0gEKDVByb2Nlc3NDb25maWcSDwoHY29tbWFuZBgBIAEoCRIMCgRhcmdzGAIgAygJEi8KA2VudhgDIAMoCzIiLmN1YS5lbnYudjEuUHJvY2Vzc0NvbmZpZy5FbnZFbnRyeRILCgNjd2QYBCABKAkSDAoEdXNlchgFIAEoCRIqCgd0aW1lb3V0GAYgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uGioKCEVudkVudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAEiPAoJUHR5Q29uZmlnEiEKBHNpemUYASABKAsyEy5jdWEuZW52LnYxLlB0eVNpemUSDAoEdGVybRgCIAEoCSJQCgdQdHlTaXplEgwKBGNvbHMYASABKA0SDAoEcm93cxgCIAEoDRITCgtwaXhlbF93aWR0aBgDIAEoDRIUCgxwaXhlbF9oZWlnaHQYBCABKA0iOwoPUHJvY2Vzc1NlbGVjdG9yEg0KA3BpZBgBIAEoDUgAEg0KA3RhZxgCIAEoCUgAQgoKCHNlbGVjdG9yIpACChNTdGFydFByb2Nlc3NSZXF1ZXN0EikKBmNvbmZpZxgBIAEoCzIZLmN1YS5lbnYudjEuUHJvY2Vzc0NvbmZpZxIiCgNwdHkYAiABKAsyFS5jdWEuZW52LnYxLlB0eUNvbmZpZxILCgN0YWcYAyABKAkSDQoFc3RkaW4YBCABKAgSNQoSa2VlcGFsaXZlX2ludGVydmFsGAUgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uEhgKEHNjcm9sbGJhY2tfYnl0ZXMYBiABKAQSGgoSa2lsbF9vbl9kaXNjb25uZWN0GAcgASgIEhIKCnJlcXVlc3RfaWQYCCABKAkSDQoFZXBvY2gYCSABKAQiPwoUU3RhcnRQcm9jZXNzUmVzcG9uc2USJwoFZXZlbnQYASABKAsyGC5jdWEuZW52LnYxLlByb2Nlc3NFdmVudCLKAQoVQ29ubmVjdFByb2Nlc3NSZXF1ZXN0EiwKB3Byb2Nlc3MYASABKAsyGy5jdWEuZW52LnYxLlByb2Nlc3NTZWxlY3RvchIUCgxyZXBsYXlfYnl0ZXMYAiABKAQSHwoScmVwbGF5X2Zyb21fb2Zmc2V0GAMgASgESACIAQESNQoSa2VlcGFsaXZlX2ludGVydmFsGAQgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uQhUKE19yZXBsYXlfZnJvbV9vZmZzZXQiQQoWQ29ubmVjdFByb2Nlc3NSZXNwb25zZRInCgVldmVudBgBIAEoCzIYLmN1YS5lbnYudjEuUHJvY2Vzc0V2ZW50Ir4BCgxQcm9jZXNzRXZlbnQSKQoFc3RhcnQYASABKAsyGC5jdWEuZW52LnYxLlByb2Nlc3NTdGFydEgAEicKBGRhdGEYAiABKAsyFy5jdWEuZW52LnYxLlByb2Nlc3NEYXRhSAASJQoDZW5kGAMgASgLMhYuY3VhLmVudi52MS5Qcm9jZXNzRW5kSAASKgoJa2VlcGFsaXZlGAQgASgLMhUuY3VhLmVudi52MS5LZWVwQWxpdmVIAEIHCgVldmVudCK+AQoMUHJvY2Vzc1N0YXJ0EgsKA3BpZBgBIAEoDRILCgN0YWcYAiABKAkSLgoKc3RhcnRlZF9hdBgDIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASHwoXc2Nyb2xsYmFja19zdGFydF9vZmZzZXQYBCABKAQSGQoRb3V0cHV0X2VuZF9vZmZzZXQYBSABKAQSFAoMZGVkdXBsaWNhdGVkGAYgASgIEhIKCnJlcXVlc3RfaWQYByABKAkiWgoLUHJvY2Vzc0RhdGESDgoGb2Zmc2V0GAEgASgEEhAKBnN0ZG91dBgCIAEoDEgAEhAKBnN0ZGVychgDIAEoDEgAEg0KA3B0eRgEIAEoDEgAQggKBm91dHB1dCLgAQoKUHJvY2Vzc0VuZBIWCglleGl0X2NvZGUYASABKAVIAIgBARIiCgZzaWduYWwYAiABKA4yEi5jdWEuZW52LnYxLlNpZ25hbBIRCgl0aW1lZF9vdXQYAyABKAgSDQoFZXJyb3IYBCABKAkSLAoIZW5kZWRfYXQYBSABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEgwKBGxvc3QYBiABKAgSFQoNc2lnbmFsX251bWJlchgHIAEoBRITCgtzaWduYWxfbmFtZRgIIAEoCUIMCgpfZXhpdF9jb2RlIkIKFExpc3RQcm9jZXNzZXNSZXF1ZXN0EhYKDmluY2x1ZGVfZXhpdGVkGAEgASgIEhIKCnRhZ19wcmVmaXgYAiABKAkiQwoVTGlzdFByb2Nlc3Nlc1Jlc3BvbnNlEioKCXByb2Nlc3NlcxgBIAMoCzIXLmN1YS5lbnYudjEuUHJvY2Vzc0luZm8iswIKC1Byb2Nlc3NJbmZvEgsKA3BpZBgBIAEoDRILCgN0YWcYAiABKAkSKQoGY29uZmlnGAMgASgLMhkuY3VhLmVudi52MS5Qcm9jZXNzQ29uZmlnEgsKA3B0eRgEIAEoCBInCgVzdGF0ZRgFIAEoDjIYLmN1YS5lbnYudjEuUHJvY2Vzc1N0YXRlEiMKA2VuZBgGIAEoCzIWLmN1YS5lbnYudjEuUHJvY2Vzc0VuZBIuCgpzdGFydGVkX2F0GAcgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIfChdzY3JvbGxiYWNrX3N0YXJ0X29mZnNldBgIIAEoBBIZChFvdXRwdXRfZW5kX29mZnNldBgJIAEoBBIYChBhdHRhY2hlZF9jbGllbnRzGAogASgNIjcKDFByb2Nlc3NJbnB1dBIPCgVzdGRpbhgBIAEoDEgAEg0KA3B0eRgCIAEoDEgAQgcKBWlucHV0Io4BChBTZW5kSW5wdXRSZXF1ZXN0EiwKB3Byb2Nlc3MYASABKAsyGy5jdWEuZW52LnYxLlByb2Nlc3NTZWxlY3RvchInCgVpbnB1dBgCIAEoCzIYLmN1YS5lbnYudjEuUHJvY2Vzc0lucHV0EhAKCHNlcXVlbmNlGAMgASgEEhEKCXdyaXRlcl9pZBgEIAEoCSJAChFTZW5kSW5wdXRSZXNwb25zZRIYChBhcHBsaWVkX3NlcXVlbmNlGAEgASgEEhEKCWR1cGxpY2F0ZRgCIAEoCCKmAQoSU3RyZWFtSW5wdXRSZXF1ZXN0Ei4KB3Byb2Nlc3MYASABKAsyGy5jdWEuZW52LnYxLlByb2Nlc3NTZWxlY3RvckgAEikKBWlucHV0GAIgASgLMhguY3VhLmVudi52MS5Qcm9jZXNzSW5wdXRIABIqCglrZWVwYWxpdmUYAyABKAsyFS5jdWEuZW52LnYxLktlZXBBbGl2ZUgAQgkKB21lc3NhZ2UiLAoTU3RyZWFtSW5wdXRSZXNwb25zZRIVCg1ieXRlc193cml0dGVuGAEgASgEIn8KFFNpZ25hbFByb2Nlc3NSZXF1ZXN0EiwKB3Byb2Nlc3MYASABKAsyGy5jdWEuZW52LnYxLlByb2Nlc3NTZWxlY3RvchIiCgZzaWduYWwYAiABKA4yEi5jdWEuZW52LnYxLlNpZ25hbBIVCg1wcm9jZXNzX2dyb3VwGAMgASgIIhcKFVNpZ25hbFByb2Nlc3NSZXNwb25zZSJBChFDbG9zZVN0ZGluUmVxdWVzdBIsCgdwcm9jZXNzGAEgASgLMhsuY3VhLmVudi52MS5Qcm9jZXNzU2VsZWN0b3IiFAoSQ2xvc2VTdGRpblJlc3BvbnNlImMKEFJlc2l6ZVB0eVJlcXVlc3QSLAoHcHJvY2VzcxgBIAEoCzIbLmN1YS5lbnYudjEuUHJvY2Vzc1NlbGVjdG9yEiEKBHNpemUYAiABKAsyEy5jdWEuZW52LnYxLlB0eVNpemUiEwoRUmVzaXplUHR5UmVzcG9uc2UiKgoUR2V0RXhlY1JlY29yZFJlcXVlc3QSEgoKcmVxdWVzdF9pZBgBIAEoCSJOChVHZXRFeGVjUmVjb3JkUmVzcG9uc2USJgoGcmVjb3JkGAEgASgLMhYuY3VhLmVudi52MS5FeGVjUmVjb3JkEg0KBWVwb2NoGAIgASgEIosCCgpFeGVjUmVjb3JkEhIKCnJlcXVlc3RfaWQYASABKAkSJAoFc3RhdGUYAiABKA4yFS5jdWEuZW52LnYxLkV4ZWNTdGF0ZRINCgVlcG9jaBgDIAEoBBILCgNwaWQYBCABKA0SLgoKc3RhcnRlZF9hdBgFIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASIwoDZW5kGAYgASgLMhYuY3VhLmVudi52MS5Qcm9jZXNzRW5kEhQKDG91dHB1dF9ieXRlcxgHIAEoBBIVCg1vdXRwdXRfc2hhMjU2GAggASgJEiUKBHRhaWwYCSADKAsyFy5jdWEuZW52LnYxLlByb2Nlc3NEYXRhIiQKE0FkdmFuY2VFcG9jaFJlcXVlc3QSDQoFZXBvY2gYASABKAQiNQoUQWR2YW5jZUVwb2NoUmVzcG9uc2USDQoFZXBvY2gYASABKAQSDgoGa2lsbGVkGAIgASgNKmIKDFByb2Nlc3NTdGF0ZRIdChlQUk9DRVNTX1NUQVRFX1VOU1BFQ0lGSUVEEAASGQoVUFJPQ0VTU19TVEFURV9SVU5OSU5HEAESGAoUUFJPQ0VTU19TVEFURV9FWElURUQQAiraAQoGU2lnbmFsEhYKElNJR05BTF9VTlNQRUNJRklFRBAAEg4KClNJR05BTF9IVVAQARIOCgpTSUdOQUxfSU5UEAISDwoLU0lHTkFMX1FVSVQQAxIPCgtTSUdOQUxfS0lMTBAJEg8KC1NJR05BTF9VU1IxEAoSDwoLU0lHTkFMX1VTUjIQDBIPCgtTSUdOQUxfVEVSTRAPEg8KC1NJR05BTF9DT05UEBISDwoLU0lHTkFMX1NUT1AQExIPCgtTSUdOQUxfVFNUUBAUEhAKDFNJR05BTF9XSU5DSBAcKmsKCUV4ZWNTdGF0ZRIaChZFWEVDX1NUQVRFX1VOU1BFQ0lGSUVEEAASFgoSRVhFQ19TVEFURV9SVU5OSU5HEAESFQoRRVhFQ19TVEFURV9FWElURUQQAhITCg9FWEVDX1NUQVRFX0xPU1QQAzLIBgoOUHJvY2Vzc1NlcnZpY2USUwoMU3RhcnRQcm9jZXNzEh8uY3VhLmVudi52MS5TdGFydFByb2Nlc3NSZXF1ZXN0GiAuY3VhLmVudi52MS5TdGFydFByb2Nlc3NSZXNwb25zZTABElkKDkNvbm5lY3RQcm9jZXNzEiEuY3VhLmVudi52MS5Db25uZWN0UHJvY2Vzc1JlcXVlc3QaIi5jdWEuZW52LnYxLkNvbm5lY3RQcm9jZXNzUmVzcG9uc2UwARJUCg1MaXN0UHJvY2Vzc2VzEiAuY3VhLmVudi52MS5MaXN0UHJvY2Vzc2VzUmVxdWVzdBohLmN1YS5lbnYudjEuTGlzdFByb2Nlc3Nlc1Jlc3BvbnNlEkgKCVNlbmRJbnB1dBIcLmN1YS5lbnYudjEuU2VuZElucHV0UmVxdWVzdBodLmN1YS5lbnYudjEuU2VuZElucHV0UmVzcG9uc2USUAoLU3RyZWFtSW5wdXQSHi5jdWEuZW52LnYxLlN0cmVhbUlucHV0UmVxdWVzdBofLmN1YS5lbnYudjEuU3RyZWFtSW5wdXRSZXNwb25zZSgBElQKDVNpZ25hbFByb2Nlc3MSIC5jdWEuZW52LnYxLlNpZ25hbFByb2Nlc3NSZXF1ZXN0GiEuY3VhLmVudi52MS5TaWduYWxQcm9jZXNzUmVzcG9uc2USSwoKQ2xvc2VTdGRpbhIdLmN1YS5lbnYudjEuQ2xvc2VTdGRpblJlcXVlc3QaHi5jdWEuZW52LnYxLkNsb3NlU3RkaW5SZXNwb25zZRJICglSZXNpemVQdHkSHC5jdWEuZW52LnYxLlJlc2l6ZVB0eVJlcXVlc3QaHS5jdWEuZW52LnYxLlJlc2l6ZVB0eVJlc3BvbnNlElQKDUdldEV4ZWNSZWNvcmQSIC5jdWEuZW52LnYxLkdldEV4ZWNSZWNvcmRSZXF1ZXN0GiEuY3VhLmVudi52MS5HZXRFeGVjUmVjb3JkUmVzcG9uc2USUQoMQWR2YW5jZUVwb2NoEh8uY3VhLmVudi52MS5BZHZhbmNlRXBvY2hSZXF1ZXN0GiAuY3VhLmVudi52MS5BZHZhbmNlRXBvY2hSZXNwb25zZWIGcHJvdG8z", [file_cua_env_v1_common, file_google_protobuf_duration, file_google_protobuf_timestamp]);
+ fileDesc("ChhjdWEvZW52L3YxL3Byb2Nlc3MucHJvdG8SCmN1YS5lbnYudjEi0gEKDVByb2Nlc3NDb25maWcSDwoHY29tbWFuZBgBIAEoCRIMCgRhcmdzGAIgAygJEi8KA2VudhgDIAMoCzIiLmN1YS5lbnYudjEuUHJvY2Vzc0NvbmZpZy5FbnZFbnRyeRILCgNjd2QYBCABKAkSDAoEdXNlchgFIAEoCRIqCgd0aW1lb3V0GAYgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uGioKCEVudkVudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAEiPAoJUHR5Q29uZmlnEiEKBHNpemUYASABKAsyEy5jdWEuZW52LnYxLlB0eVNpemUSDAoEdGVybRgCIAEoCSJQCgdQdHlTaXplEgwKBGNvbHMYASABKA0SDAoEcm93cxgCIAEoDRITCgtwaXhlbF93aWR0aBgDIAEoDRIUCgxwaXhlbF9oZWlnaHQYBCABKA0iOwoPUHJvY2Vzc1NlbGVjdG9yEg0KA3BpZBgBIAEoDUgAEg0KA3RhZxgCIAEoCUgAQgoKCHNlbGVjdG9yIpACChNTdGFydFByb2Nlc3NSZXF1ZXN0EikKBmNvbmZpZxgBIAEoCzIZLmN1YS5lbnYudjEuUHJvY2Vzc0NvbmZpZxIiCgNwdHkYAiABKAsyFS5jdWEuZW52LnYxLlB0eUNvbmZpZxILCgN0YWcYAyABKAkSDQoFc3RkaW4YBCABKAgSNQoSa2VlcGFsaXZlX2ludGVydmFsGAUgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uEhgKEHNjcm9sbGJhY2tfYnl0ZXMYBiABKAQSGgoSa2lsbF9vbl9kaXNjb25uZWN0GAcgASgIEhIKCnJlcXVlc3RfaWQYCCABKAkSDQoFZXBvY2gYCSABKAQiPwoUU3RhcnRQcm9jZXNzUmVzcG9uc2USJwoFZXZlbnQYASABKAsyGC5jdWEuZW52LnYxLlByb2Nlc3NFdmVudCLKAQoVQ29ubmVjdFByb2Nlc3NSZXF1ZXN0EiwKB3Byb2Nlc3MYASABKAsyGy5jdWEuZW52LnYxLlByb2Nlc3NTZWxlY3RvchIUCgxyZXBsYXlfYnl0ZXMYAiABKAQSHwoScmVwbGF5X2Zyb21fb2Zmc2V0GAMgASgESACIAQESNQoSa2VlcGFsaXZlX2ludGVydmFsGAQgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uQhUKE19yZXBsYXlfZnJvbV9vZmZzZXQiQQoWQ29ubmVjdFByb2Nlc3NSZXNwb25zZRInCgVldmVudBgBIAEoCzIYLmN1YS5lbnYudjEuUHJvY2Vzc0V2ZW50Ir4BCgxQcm9jZXNzRXZlbnQSKQoFc3RhcnQYASABKAsyGC5jdWEuZW52LnYxLlByb2Nlc3NTdGFydEgAEicKBGRhdGEYAiABKAsyFy5jdWEuZW52LnYxLlByb2Nlc3NEYXRhSAASJQoDZW5kGAMgASgLMhYuY3VhLmVudi52MS5Qcm9jZXNzRW5kSAASKgoJa2VlcGFsaXZlGAQgASgLMhUuY3VhLmVudi52MS5LZWVwQWxpdmVIAEIHCgVldmVudCK+AQoMUHJvY2Vzc1N0YXJ0EgsKA3BpZBgBIAEoDRILCgN0YWcYAiABKAkSLgoKc3RhcnRlZF9hdBgDIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASHwoXc2Nyb2xsYmFja19zdGFydF9vZmZzZXQYBCABKAQSGQoRb3V0cHV0X2VuZF9vZmZzZXQYBSABKAQSFAoMZGVkdXBsaWNhdGVkGAYgASgIEhIKCnJlcXVlc3RfaWQYByABKAkiWgoLUHJvY2Vzc0RhdGESDgoGb2Zmc2V0GAEgASgEEhAKBnN0ZG91dBgCIAEoDEgAEhAKBnN0ZGVychgDIAEoDEgAEg0KA3B0eRgEIAEoDEgAQggKBm91dHB1dCLgAQoKUHJvY2Vzc0VuZBIWCglleGl0X2NvZGUYASABKAVIAIgBARIiCgZzaWduYWwYAiABKA4yEi5jdWEuZW52LnYxLlNpZ25hbBIRCgl0aW1lZF9vdXQYAyABKAgSDQoFZXJyb3IYBCABKAkSLAoIZW5kZWRfYXQYBSABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEgwKBGxvc3QYBiABKAgSFQoNc2lnbmFsX251bWJlchgHIAEoBRITCgtzaWduYWxfbmFtZRgIIAEoCUIMCgpfZXhpdF9jb2RlIkIKFExpc3RQcm9jZXNzZXNSZXF1ZXN0EhYKDmluY2x1ZGVfZXhpdGVkGAEgASgIEhIKCnRhZ19wcmVmaXgYAiABKAkiQwoVTGlzdFByb2Nlc3Nlc1Jlc3BvbnNlEioKCXByb2Nlc3NlcxgBIAMoCzIXLmN1YS5lbnYudjEuUHJvY2Vzc0luZm8iswIKC1Byb2Nlc3NJbmZvEgsKA3BpZBgBIAEoDRILCgN0YWcYAiABKAkSKQoGY29uZmlnGAMgASgLMhkuY3VhLmVudi52MS5Qcm9jZXNzQ29uZmlnEgsKA3B0eRgEIAEoCBInCgVzdGF0ZRgFIAEoDjIYLmN1YS5lbnYudjEuUHJvY2Vzc1N0YXRlEiMKA2VuZBgGIAEoCzIWLmN1YS5lbnYudjEuUHJvY2Vzc0VuZBIuCgpzdGFydGVkX2F0GAcgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIfChdzY3JvbGxiYWNrX3N0YXJ0X29mZnNldBgIIAEoBBIZChFvdXRwdXRfZW5kX29mZnNldBgJIAEoBBIYChBhdHRhY2hlZF9jbGllbnRzGAogASgNIjcKDFByb2Nlc3NJbnB1dBIPCgVzdGRpbhgBIAEoDEgAEg0KA3B0eRgCIAEoDEgAQgcKBWlucHV0Io4BChBTZW5kSW5wdXRSZXF1ZXN0EiwKB3Byb2Nlc3MYASABKAsyGy5jdWEuZW52LnYxLlByb2Nlc3NTZWxlY3RvchInCgVpbnB1dBgCIAEoCzIYLmN1YS5lbnYudjEuUHJvY2Vzc0lucHV0EhAKCHNlcXVlbmNlGAMgASgEEhEKCXdyaXRlcl9pZBgEIAEoCSJAChFTZW5kSW5wdXRSZXNwb25zZRIYChBhcHBsaWVkX3NlcXVlbmNlGAEgASgEEhEKCWR1cGxpY2F0ZRgCIAEoCCKmAQoSU3RyZWFtSW5wdXRSZXF1ZXN0Ei4KB3Byb2Nlc3MYASABKAsyGy5jdWEuZW52LnYxLlByb2Nlc3NTZWxlY3RvckgAEikKBWlucHV0GAIgASgLMhguY3VhLmVudi52MS5Qcm9jZXNzSW5wdXRIABIqCglrZWVwYWxpdmUYAyABKAsyFS5jdWEuZW52LnYxLktlZXBBbGl2ZUgAQgkKB21lc3NhZ2UiLAoTU3RyZWFtSW5wdXRSZXNwb25zZRIVCg1ieXRlc193cml0dGVuGAEgASgEIn8KFFNpZ25hbFByb2Nlc3NSZXF1ZXN0EiwKB3Byb2Nlc3MYASABKAsyGy5jdWEuZW52LnYxLlByb2Nlc3NTZWxlY3RvchIiCgZzaWduYWwYAiABKA4yEi5jdWEuZW52LnYxLlNpZ25hbBIVCg1wcm9jZXNzX2dyb3VwGAMgASgIIhcKFVNpZ25hbFByb2Nlc3NSZXNwb25zZSJBChFDbG9zZVN0ZGluUmVxdWVzdBIsCgdwcm9jZXNzGAEgASgLMhsuY3VhLmVudi52MS5Qcm9jZXNzU2VsZWN0b3IiFAoSQ2xvc2VTdGRpblJlc3BvbnNlImMKEFJlc2l6ZVB0eVJlcXVlc3QSLAoHcHJvY2VzcxgBIAEoCzIbLmN1YS5lbnYudjEuUHJvY2Vzc1NlbGVjdG9yEiEKBHNpemUYAiABKAsyEy5jdWEuZW52LnYxLlB0eVNpemUiEwoRUmVzaXplUHR5UmVzcG9uc2UiKgoUR2V0RXhlY1JlY29yZFJlcXVlc3QSEgoKcmVxdWVzdF9pZBgBIAEoCSJOChVHZXRFeGVjUmVjb3JkUmVzcG9uc2USJgoGcmVjb3JkGAEgASgLMhYuY3VhLmVudi52MS5FeGVjUmVjb3JkEg0KBWVwb2NoGAIgASgEIosCCgpFeGVjUmVjb3JkEhIKCnJlcXVlc3RfaWQYASABKAkSJAoFc3RhdGUYAiABKA4yFS5jdWEuZW52LnYxLkV4ZWNTdGF0ZRINCgVlcG9jaBgDIAEoBBILCgNwaWQYBCABKA0SLgoKc3RhcnRlZF9hdBgFIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASIwoDZW5kGAYgASgLMhYuY3VhLmVudi52MS5Qcm9jZXNzRW5kEhQKDG91dHB1dF9ieXRlcxgHIAEoBBIVCg1vdXRwdXRfc2hhMjU2GAggASgJEiUKBHRhaWwYCSADKAsyFy5jdWEuZW52LnYxLlByb2Nlc3NEYXRhIiQKE0FkdmFuY2VFcG9jaFJlcXVlc3QSDQoFZXBvY2gYASABKAQiNQoUQWR2YW5jZUVwb2NoUmVzcG9uc2USDQoFZXBvY2gYASABKAQSDgoGa2lsbGVkGAIgASgNIvYBCgtIZWFsdGhQcm9iZRInCgRleGVjGAEgASgLMhkuY3VhLmVudi52MS5Qcm9jZXNzQ29uZmlnEgwKBGh0dHAYAiABKAkSCwoDdGNwGAMgASgJEisKCGludGVydmFsGAQgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uEioKB3RpbWVvdXQYBSABKAsyGS5nb29nbGUucHJvdG9idWYuRHVyYXRpb24SGQoRZmFpbHVyZV90aHJlc2hvbGQYBiABKA0SLwoMc3RhcnRfcGVyaW9kGAcgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uIr8CCgtTZXJ2aWNlU3BlYxIMCgRuYW1lGAEgASgJEikKBmNvbmZpZxgCIAEoCzIZLmN1YS5lbnYudjEuUHJvY2Vzc0NvbmZpZxIqCgdyZXN0YXJ0GAMgASgOMhkuY3VhLmVudi52MS5SZXN0YXJ0UG9saWN5Ei4KC2JhY2tvZmZfbWluGAQgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uEi4KC2JhY2tvZmZfbWF4GAUgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uEiYKBXByb2JlGAYgASgLMhcuY3VhLmVudi52MS5IZWFsdGhQcm9iZRIaCg1zdGFydF9vbl9ib290GAcgASgISACIAQESFQoNbG9nX21heF9ieXRlcxgIIAEoBEIQCg5fc3RhcnRfb25fYm9vdCKyAgoNU2VydmljZVN0YXR1cxIlCgRzcGVjGAEgASgLMhcuY3VhLmVudi52MS5TZXJ2aWNlU3BlYxInCgVzdGF0ZRgCIAEoDjIYLmN1YS5lbnYudjEuU2VydmljZVN0YXRlEgsKA3BpZBgDIAEoDRIQCghyZXN0YXJ0cxgEIAEoDRIuCgpzdGFydGVkX2F0GAUgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIoCghsYXN0X2VuZBgGIAEoCzIWLmN1YS5lbnYudjEuUHJvY2Vzc0VuZBITCgtwcm9iZV9lcnJvchgHIAEoCRIxCg1uZXh0X3N0YXJ0X2F0GAggASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIQCghsb2dfcGF0aBgJIAEoCSI6ChFQdXRTZXJ2aWNlUmVxdWVzdBIlCgRzcGVjGAEgASgLMhcuY3VhLmVudi52MS5TZXJ2aWNlU3BlYyJAChJQdXRTZXJ2aWNlUmVzcG9uc2USKgoHc2VydmljZRgBIAEoCzIZLmN1YS5lbnYudjEuU2VydmljZVN0YXR1cyIkChREZWxldGVTZXJ2aWNlUmVxdWVzdBIMCgRuYW1lGAEgASgJIhcKFURlbGV0ZVNlcnZpY2VSZXNwb25zZSIVChNMaXN0U2VydmljZXNSZXF1ZXN0IkMKFExpc3RTZXJ2aWNlc1Jlc3BvbnNlEisKCHNlcnZpY2VzGAEgAygLMhkuY3VhLmVudi52MS5TZXJ2aWNlU3RhdHVzIlAKFUNvbnRyb2xTZXJ2aWNlUmVxdWVzdBIMCgRuYW1lGAEgASgJEikKBmFjdGlvbhgCIAEoDjIZLmN1YS5lbnYudjEuU2VydmljZUFjdGlvbiJEChZDb250cm9sU2VydmljZVJlc3BvbnNlEioKB3NlcnZpY2UYASABKAsyGS5jdWEuZW52LnYxLlNlcnZpY2VTdGF0dXMiOQoVR2V0U2VydmljZUxvZ3NSZXF1ZXN0EgwKBG5hbWUYASABKAkSEgoKdGFpbF9ieXRlcxgCIAEoBCI5ChZHZXRTZXJ2aWNlTG9nc1Jlc3BvbnNlEgwKBGRhdGEYASABKAwSEQoJdHJ1bmNhdGVkGAIgASgIKmIKDFByb2Nlc3NTdGF0ZRIdChlQUk9DRVNTX1NUQVRFX1VOU1BFQ0lGSUVEEAASGQoVUFJPQ0VTU19TVEFURV9SVU5OSU5HEAESGAoUUFJPQ0VTU19TVEFURV9FWElURUQQAiraAQoGU2lnbmFsEhYKElNJR05BTF9VTlNQRUNJRklFRBAAEg4KClNJR05BTF9IVVAQARIOCgpTSUdOQUxfSU5UEAISDwoLU0lHTkFMX1FVSVQQAxIPCgtTSUdOQUxfS0lMTBAJEg8KC1NJR05BTF9VU1IxEAoSDwoLU0lHTkFMX1VTUjIQDBIPCgtTSUdOQUxfVEVSTRAPEg8KC1NJR05BTF9DT05UEBISDwoLU0lHTkFMX1NUT1AQExIPCgtTSUdOQUxfVFNUUBAUEhAKDFNJR05BTF9XSU5DSBAcKmsKCUV4ZWNTdGF0ZRIaChZFWEVDX1NUQVRFX1VOU1BFQ0lGSUVEEAASFgoSRVhFQ19TVEFURV9SVU5OSU5HEAESFQoRRVhFQ19TVEFURV9FWElURUQQAhITCg9FWEVDX1NUQVRFX0xPU1QQAyqDAQoNUmVzdGFydFBvbGljeRIeChpSRVNUQVJUX1BPTElDWV9VTlNQRUNJRklFRBAAEhkKFVJFU1RBUlRfUE9MSUNZX0FMV0FZUxABEh0KGVJFU1RBUlRfUE9MSUNZX09OX0ZBSUxVUkUQAhIYChRSRVNUQVJUX1BPTElDWV9ORVZFUhADKusBCgxTZXJ2aWNlU3RhdGUSHQoZU0VSVklDRV9TVEFURV9VTlNQRUNJRklFRBAAEhoKFlNFUlZJQ0VfU1RBVEVfU1RBUlRJTkcQARIZChVTRVJWSUNFX1NUQVRFX1JVTk5JTkcQAhIbChdTRVJWSUNFX1NUQVRFX1VOSEVBTFRIWRADEhkKFVNFUlZJQ0VfU1RBVEVfQkFDS09GRhAEEhkKFVNFUlZJQ0VfU1RBVEVfU1RPUFBFRBAFEhgKFFNFUlZJQ0VfU1RBVEVfRVhJVEVEEAYSGAoUU0VSVklDRV9TVEFURV9GQUlMRUQQByp+Cg1TZXJ2aWNlQWN0aW9uEh4KGlNFUlZJQ0VfQUNUSU9OX1VOU1BFQ0lGSUVEEAASGAoUU0VSVklDRV9BQ1RJT05fU1RBUlQQARIXChNTRVJWSUNFX0FDVElPTl9TVE9QEAISGgoWU0VSVklDRV9BQ1RJT05fUkVTVEFSVBADMvAJCg5Qcm9jZXNzU2VydmljZRJTCgxTdGFydFByb2Nlc3MSHy5jdWEuZW52LnYxLlN0YXJ0UHJvY2Vzc1JlcXVlc3QaIC5jdWEuZW52LnYxLlN0YXJ0UHJvY2Vzc1Jlc3BvbnNlMAESWQoOQ29ubmVjdFByb2Nlc3MSIS5jdWEuZW52LnYxLkNvbm5lY3RQcm9jZXNzUmVxdWVzdBoiLmN1YS5lbnYudjEuQ29ubmVjdFByb2Nlc3NSZXNwb25zZTABElQKDUxpc3RQcm9jZXNzZXMSIC5jdWEuZW52LnYxLkxpc3RQcm9jZXNzZXNSZXF1ZXN0GiEuY3VhLmVudi52MS5MaXN0UHJvY2Vzc2VzUmVzcG9uc2USSAoJU2VuZElucHV0EhwuY3VhLmVudi52MS5TZW5kSW5wdXRSZXF1ZXN0Gh0uY3VhLmVudi52MS5TZW5kSW5wdXRSZXNwb25zZRJQCgtTdHJlYW1JbnB1dBIeLmN1YS5lbnYudjEuU3RyZWFtSW5wdXRSZXF1ZXN0Gh8uY3VhLmVudi52MS5TdHJlYW1JbnB1dFJlc3BvbnNlKAESVAoNU2lnbmFsUHJvY2VzcxIgLmN1YS5lbnYudjEuU2lnbmFsUHJvY2Vzc1JlcXVlc3QaIS5jdWEuZW52LnYxLlNpZ25hbFByb2Nlc3NSZXNwb25zZRJLCgpDbG9zZVN0ZGluEh0uY3VhLmVudi52MS5DbG9zZVN0ZGluUmVxdWVzdBoeLmN1YS5lbnYudjEuQ2xvc2VTdGRpblJlc3BvbnNlEkgKCVJlc2l6ZVB0eRIcLmN1YS5lbnYudjEuUmVzaXplUHR5UmVxdWVzdBodLmN1YS5lbnYudjEuUmVzaXplUHR5UmVzcG9uc2USVAoNR2V0RXhlY1JlY29yZBIgLmN1YS5lbnYudjEuR2V0RXhlY1JlY29yZFJlcXVlc3QaIS5jdWEuZW52LnYxLkdldEV4ZWNSZWNvcmRSZXNwb25zZRJRCgxBZHZhbmNlRXBvY2gSHy5jdWEuZW52LnYxLkFkdmFuY2VFcG9jaFJlcXVlc3QaIC5jdWEuZW52LnYxLkFkdmFuY2VFcG9jaFJlc3BvbnNlEksKClB1dFNlcnZpY2USHS5jdWEuZW52LnYxLlB1dFNlcnZpY2VSZXF1ZXN0Gh4uY3VhLmVudi52MS5QdXRTZXJ2aWNlUmVzcG9uc2USVAoNRGVsZXRlU2VydmljZRIgLmN1YS5lbnYudjEuRGVsZXRlU2VydmljZVJlcXVlc3QaIS5jdWEuZW52LnYxLkRlbGV0ZVNlcnZpY2VSZXNwb25zZRJRCgxMaXN0U2VydmljZXMSHy5jdWEuZW52LnYxLkxpc3RTZXJ2aWNlc1JlcXVlc3QaIC5jdWEuZW52LnYxLkxpc3RTZXJ2aWNlc1Jlc3BvbnNlElcKDkNvbnRyb2xTZXJ2aWNlEiEuY3VhLmVudi52MS5Db250cm9sU2VydmljZVJlcXVlc3QaIi5jdWEuZW52LnYxLkNvbnRyb2xTZXJ2aWNlUmVzcG9uc2USVwoOR2V0U2VydmljZUxvZ3MSIS5jdWEuZW52LnYxLkdldFNlcnZpY2VMb2dzUmVxdWVzdBoiLmN1YS5lbnYudjEuR2V0U2VydmljZUxvZ3NSZXNwb25zZWIGcHJvdG8z", [file_cua_env_v1_common, file_google_protobuf_duration, file_google_protobuf_timestamp]);
/**
* What to run.
@@ -1243,6 +1243,439 @@ export type AdvanceEpochResponse = Message<"cua.env.v1.AdvanceEpochResponse"> &
export const AdvanceEpochResponseSchema: GenMessage<AdvanceEpochResponse> = /*@__PURE__*/
messageDesc(file_cua_env_v1_process, 30);
+/**
+ * How a service's health is checked. Set exactly one of `exec`, `http`,
+ * `tcp`.
+ *
+ * @generated from message cua.env.v1.HealthProbe
+ */
+export type HealthProbe = Message<"cua.env.v1.HealthProbe"> & {
+ /**
+ * A command that exits 0 when the service is healthy.
+ *
+ * @generated from field: cua.env.v1.ProcessConfig exec = 1;
+ */
+ exec?: ProcessConfig | undefined;
+
+ /**
+ * A URL that answers 2xx or 3xx (`http://127.0.0.1:8080/health`).
+ *
+ * @generated from field: string http = 2;
+ */
+ http: string;
+
+ /**
+ * A port that accepts a TCP connection (`127.0.0.1:5432`).
+ *
+ * @generated from field: string tcp = 3;
+ */
+ tcp: string;
+
+ /**
+ * Between checks. Unset: 10 seconds.
+ *
+ * @generated from field: google.protobuf.Duration interval = 4;
+ */
+ interval?: Duration | undefined;
+
+ /**
+ * For one check. Unset: 5 seconds.
+ *
+ * @generated from field: google.protobuf.Duration timeout = 5;
+ */
+ timeout?: Duration | undefined;
+
+ /**
+ * Failed checks in a row that mark it unhealthy and restart it. 0: 3.
+ *
+ * @generated from field: uint32 failure_threshold = 6;
+ */
+ failureThreshold: number;
+
+ /**
+ * Grace after a start before the first check counts. Unset: 10 seconds.
+ *
+ * @generated from field: google.protobuf.Duration start_period = 7;
+ */
+ startPeriod?: Duration | undefined;
+};
+
+/**
+ * Describes the message cua.env.v1.HealthProbe.
+ * Use `create(HealthProbeSchema)` to create a new message.
+ */
+export const HealthProbeSchema: GenMessage<HealthProbe> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 31);
+
+/**
+ * A service: a named command kept running.
+ *
+ * @generated from message cua.env.v1.ServiceSpec
+ */
+export type ServiceSpec = Message<"cua.env.v1.ServiceSpec"> & {
+ /**
+ * Name: lowercase letters, digits, `-`, `_` and `.`, 1 to 63 of them,
+ * starting with a letter or digit.
+ *
+ * @generated from field: string name = 1;
+ */
+ name: string;
+
+ /**
+ * What to run (`timeout` is ignored).
+ *
+ * @generated from field: cua.env.v1.ProcessConfig config = 2;
+ */
+ config?: ProcessConfig | undefined;
+
+ /**
+ * When it is started again. Unset: always.
+ *
+ * @generated from field: cua.env.v1.RestartPolicy restart = 3;
+ */
+ restart: RestartPolicy;
+
+ /**
+ * First wait before a restart; it doubles on each quick failure. Unset:
+ * 1 second.
+ *
+ * @generated from field: google.protobuf.Duration backoff_min = 4;
+ */
+ backoffMin?: Duration | undefined;
+
+ /**
+ * Longest wait before a restart. Unset: 60 seconds.
+ *
+ * @generated from field: google.protobuf.Duration backoff_max = 5;
+ */
+ backoffMax?: Duration | undefined;
+
+ /**
+ * Health check. Unset: the service is healthy while it runs.
+ *
+ * @generated from field: cua.env.v1.HealthProbe probe = 6;
+ */
+ probe?: HealthProbe | undefined;
+
+ /**
+ * Start it when cua-spacesd starts. Unset: true.
+ *
+ * @generated from field: optional bool start_on_boot = 7;
+ */
+ startOnBoot?: boolean | undefined;
+
+ /**
+ * Size at which the log file is rotated (one older file is kept). 0:
+ * 10 MiB.
+ *
+ * @generated from field: uint64 log_max_bytes = 8;
+ */
+ logMaxBytes: bigint;
+};
+
+/**
+ * Describes the message cua.env.v1.ServiceSpec.
+ * Use `create(ServiceSpecSchema)` to create a new message.
+ */
+export const ServiceSpecSchema: GenMessage<ServiceSpec> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 32);
+
+/**
+ * A service and how it is doing.
+ *
+ * @generated from message cua.env.v1.ServiceStatus
+ */
+export type ServiceStatus = Message<"cua.env.v1.ServiceStatus"> & {
+ /**
+ * What it runs.
+ *
+ * @generated from field: cua.env.v1.ServiceSpec spec = 1;
+ */
+ spec?: ServiceSpec | undefined;
+
+ /**
+ * Where it is.
+ *
+ * @generated from field: cua.env.v1.ServiceState state = 2;
+ */
+ state: ServiceState;
+
+ /**
+ * Its current process, while it runs.
+ *
+ * @generated from field: uint32 pid = 3;
+ */
+ pid: number;
+
+ /**
+ * Starts after the first one.
+ *
+ * @generated from field: uint32 restarts = 4;
+ */
+ restarts: number;
+
+ /**
+ * When the current (or last) process started.
+ *
+ * @generated from field: google.protobuf.Timestamp started_at = 5;
+ */
+ startedAt?: Timestamp | undefined;
+
+ /**
+ * How the last process ended.
+ *
+ * @generated from field: cua.env.v1.ProcessEnd last_end = 6;
+ */
+ lastEnd?: ProcessEnd | undefined;
+
+ /**
+ * The last failed health check, empty when the last one passed.
+ *
+ * @generated from field: string probe_error = 7;
+ */
+ probeError: string;
+
+ /**
+ * When it starts again (state `SERVICE_STATE_BACKOFF`).
+ *
+ * @generated from field: google.protobuf.Timestamp next_start_at = 8;
+ */
+ nextStartAt?: Timestamp | undefined;
+
+ /**
+ * Its log file in the guest.
+ *
+ * @generated from field: string log_path = 9;
+ */
+ logPath: string;
+};
+
+/**
+ * Describes the message cua.env.v1.ServiceStatus.
+ * Use `create(ServiceStatusSchema)` to create a new message.
+ */
+export const ServiceStatusSchema: GenMessage<ServiceStatus> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 33);
+
+/**
+ * Request for `ProcessService.PutService`.
+ *
+ * @generated from message cua.env.v1.PutServiceRequest
+ */
+export type PutServiceRequest = Message<"cua.env.v1.PutServiceRequest"> & {
+ /**
+ * The service.
+ *
+ * @generated from field: cua.env.v1.ServiceSpec spec = 1;
+ */
+ spec?: ServiceSpec | undefined;
+};
+
+/**
+ * Describes the message cua.env.v1.PutServiceRequest.
+ * Use `create(PutServiceRequestSchema)` to create a new message.
+ */
+export const PutServiceRequestSchema: GenMessage<PutServiceRequest> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 34);
+
+/**
+ * Response for `ProcessService.PutService`.
+ *
+ * @generated from message cua.env.v1.PutServiceResponse
+ */
+export type PutServiceResponse = Message<"cua.env.v1.PutServiceResponse"> & {
+ /**
+ * Its state right after it was put.
+ *
+ * @generated from field: cua.env.v1.ServiceStatus service = 1;
+ */
+ service?: ServiceStatus | undefined;
+};
+
+/**
+ * Describes the message cua.env.v1.PutServiceResponse.
+ * Use `create(PutServiceResponseSchema)` to create a new message.
+ */
+export const PutServiceResponseSchema: GenMessage<PutServiceResponse> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 35);
+
+/**
+ * Request for `ProcessService.DeleteService`.
+ *
+ * @generated from message cua.env.v1.DeleteServiceRequest
+ */
+export type DeleteServiceRequest = Message<"cua.env.v1.DeleteServiceRequest"> & {
+ /**
+ * Name.
+ *
+ * @generated from field: string name = 1;
+ */
+ name: string;
+};
+
+/**
+ * Describes the message cua.env.v1.DeleteServiceRequest.
+ * Use `create(DeleteServiceRequestSchema)` to create a new message.
+ */
+export const DeleteServiceRequestSchema: GenMessage<DeleteServiceRequest> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 36);
+
+/**
+ * Response for `ProcessService.DeleteService`.
+ *
+ * @generated from message cua.env.v1.DeleteServiceResponse
+ */
+export type DeleteServiceResponse = Message<"cua.env.v1.DeleteServiceResponse"> & {
+};
+
+/**
+ * Describes the message cua.env.v1.DeleteServiceResponse.
+ * Use `create(DeleteServiceResponseSchema)` to create a new message.
+ */
+export const DeleteServiceResponseSchema: GenMessage<DeleteServiceResponse> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 37);
+
+/**
+ * Request for `ProcessService.ListServices`.
+ *
+ * @generated from message cua.env.v1.ListServicesRequest
+ */
+export type ListServicesRequest = Message<"cua.env.v1.ListServicesRequest"> & {
+};
+
+/**
+ * Describes the message cua.env.v1.ListServicesRequest.
+ * Use `create(ListServicesRequestSchema)` to create a new message.
+ */
+export const ListServicesRequestSchema: GenMessage<ListServicesRequest> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 38);
+
+/**
+ * Response for `ProcessService.ListServices`.
+ *
+ * @generated from message cua.env.v1.ListServicesResponse
+ */
+export type ListServicesResponse = Message<"cua.env.v1.ListServicesResponse"> & {
+ /**
+ * By name.
+ *
+ * @generated from field: repeated cua.env.v1.ServiceStatus services = 1;
+ */
+ services: ServiceStatus[];
+};
+
+/**
+ * Describes the message cua.env.v1.ListServicesResponse.
+ * Use `create(ListServicesResponseSchema)` to create a new message.
+ */
+export const ListServicesResponseSchema: GenMessage<ListServicesResponse> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 39);
+
+/**
+ * Request for `ProcessService.ControlService`.
+ *
+ * @generated from message cua.env.v1.ControlServiceRequest
+ */
+export type ControlServiceRequest = Message<"cua.env.v1.ControlServiceRequest"> & {
+ /**
+ * Name.
+ *
+ * @generated from field: string name = 1;
+ */
+ name: string;
+
+ /**
+ * What to do.
+ *
+ * @generated from field: cua.env.v1.ServiceAction action = 2;
+ */
+ action: ServiceAction;
+};
+
+/**
+ * Describes the message cua.env.v1.ControlServiceRequest.
+ * Use `create(ControlServiceRequestSchema)` to create a new message.
+ */
+export const ControlServiceRequestSchema: GenMessage<ControlServiceRequest> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 40);
+
+/**
+ * Response for `ProcessService.ControlService`.
+ *
+ * @generated from message cua.env.v1.ControlServiceResponse
+ */
+export type ControlServiceResponse = Message<"cua.env.v1.ControlServiceResponse"> & {
+ /**
+ * Its state after the action.
+ *
+ * @generated from field: cua.env.v1.ServiceStatus service = 1;
+ */
+ service?: ServiceStatus | undefined;
+};
+
+/**
+ * Describes the message cua.env.v1.ControlServiceResponse.
+ * Use `create(ControlServiceResponseSchema)` to create a new message.
+ */
+export const ControlServiceResponseSchema: GenMessage<ControlServiceResponse> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 41);
+
+/**
+ * Request for `ProcessService.GetServiceLogs`.
+ *
+ * @generated from message cua.env.v1.GetServiceLogsRequest
+ */
+export type GetServiceLogsRequest = Message<"cua.env.v1.GetServiceLogsRequest"> & {
+ /**
+ * Name.
+ *
+ * @generated from field: string name = 1;
+ */
+ name: string;
+
+ /**
+ * How many bytes from the end. 0: 64 KiB; at most 4 MiB.
+ *
+ * @generated from field: uint64 tail_bytes = 2;
+ */
+ tailBytes: bigint;
+};
+
+/**
+ * Describes the message cua.env.v1.GetServiceLogsRequest.
+ * Use `create(GetServiceLogsRequestSchema)` to create a new message.
+ */
+export const GetServiceLogsRequestSchema: GenMessage<GetServiceLogsRequest> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 42);
+
+/**
+ * Response for `ProcessService.GetServiceLogs`.
+ *
+ * @generated from message cua.env.v1.GetServiceLogsResponse
+ */
+export type GetServiceLogsResponse = Message<"cua.env.v1.GetServiceLogsResponse"> & {
+ /**
+ * The end of its output (stdout and stderr interleaved as written).
+ *
+ * @generated from field: bytes data = 1;
+ */
+ data: Uint8Array;
+
+ /**
+ * True when older output was left out.
+ *
+ * @generated from field: bool truncated = 2;
+ */
+ truncated: boolean;
+};
+
+/**
+ * Describes the message cua.env.v1.GetServiceLogsResponse.
+ * Use `create(GetServiceLogsResponseSchema)` to create a new message.
+ */
+export const GetServiceLogsResponseSchema: GenMessage<GetServiceLogsResponse> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_process, 43);
+
/**
* Lifecycle state of a managed process.
*
@@ -1419,6 +1852,157 @@ export enum ExecState {
export const ExecStateSchema: GenEnum<ExecState> = /*@__PURE__*/
enumDesc(file_cua_env_v1_process, 2);
+/**
+ * When a service is started again.
+ *
+ * @generated from enum cua.env.v1.RestartPolicy
+ */
+export enum RestartPolicy {
+ /**
+ * Unset: `RESTART_POLICY_ALWAYS`.
+ *
+ * @generated from enum value: RESTART_POLICY_UNSPECIFIED = 0;
+ */
+ UNSPECIFIED = 0,
+
+ /**
+ * Whenever it ends, however it ends.
+ *
+ * @generated from enum value: RESTART_POLICY_ALWAYS = 1;
+ */
+ ALWAYS = 1,
+
+ /**
+ * When it ends with a non-zero code, a signal, or a failed health check.
+ *
+ * @generated from enum value: RESTART_POLICY_ON_FAILURE = 2;
+ */
+ ON_FAILURE = 2,
+
+ /**
+ * Never: it runs once.
+ *
+ * @generated from enum value: RESTART_POLICY_NEVER = 3;
+ */
+ NEVER = 3,
+}
+
+/**
+ * Describes the enum cua.env.v1.RestartPolicy.
+ */
+export const RestartPolicySchema: GenEnum<RestartPolicy> = /*@__PURE__*/
+ enumDesc(file_cua_env_v1_process, 3);
+
+/**
+ * Where a service is.
+ *
+ * @generated from enum cua.env.v1.ServiceState
+ */
+export enum ServiceState {
+ /**
+ * Not reported.
+ *
+ * @generated from enum value: SERVICE_STATE_UNSPECIFIED = 0;
+ */
+ UNSPECIFIED = 0,
+
+ /**
+ * Starting (or waiting for its first health check).
+ *
+ * @generated from enum value: SERVICE_STATE_STARTING = 1;
+ */
+ STARTING = 1,
+
+ /**
+ * Running, and healthy when it has a check.
+ *
+ * @generated from enum value: SERVICE_STATE_RUNNING = 2;
+ */
+ RUNNING = 2,
+
+ /**
+ * Running, but its last checks failed.
+ *
+ * @generated from enum value: SERVICE_STATE_UNHEALTHY = 3;
+ */
+ UNHEALTHY = 3,
+
+ /**
+ * Ended; waiting `next_start_at` to start again.
+ *
+ * @generated from enum value: SERVICE_STATE_BACKOFF = 4;
+ */
+ BACKOFF = 4,
+
+ /**
+ * Stopped by a caller.
+ *
+ * @generated from enum value: SERVICE_STATE_STOPPED = 5;
+ */
+ STOPPED = 5,
+
+ /**
+ * Ended and its policy does not start it again.
+ *
+ * @generated from enum value: SERVICE_STATE_EXITED = 6;
+ */
+ EXITED = 6,
+
+ /**
+ * Could not be started (the command does not exist, ...).
+ *
+ * @generated from enum value: SERVICE_STATE_FAILED = 7;
+ */
+ FAILED = 7,
+}
+
+/**
+ * Describes the enum cua.env.v1.ServiceState.
+ */
+export const ServiceStateSchema: GenEnum<ServiceState> = /*@__PURE__*/
+ enumDesc(file_cua_env_v1_process, 4);
+
+/**
+ * What `ControlService` does.
+ *
+ * @generated from enum cua.env.v1.ServiceAction
+ */
+export enum ServiceAction {
+ /**
+ * Not set (refused).
+ *
+ * @generated from enum value: SERVICE_ACTION_UNSPECIFIED = 0;
+ */
+ UNSPECIFIED = 0,
+
+ /**
+ * Start it (no-op when it runs).
+ *
+ * @generated from enum value: SERVICE_ACTION_START = 1;
+ */
+ START = 1,
+
+ /**
+ * Stop it and keep it stopped.
+ *
+ * @generated from enum value: SERVICE_ACTION_STOP = 2;
+ */
+ STOP = 2,
+
+ /**
+ * Stop it, then start it.
+ *
+ * @generated from enum value: SERVICE_ACTION_RESTART = 3;
+ */
+ RESTART = 3,
+}
+
+/**
+ * Describes the enum cua.env.v1.ServiceAction.
+ */
+export const ServiceActionSchema: GenEnum<ServiceAction> = /*@__PURE__*/
+ enumDesc(file_cua_env_v1_process, 5);
+
/**
* Runs and supervises guest processes.
*
@@ -1552,6 +2136,61 @@ export const ProcessService: GenService<{
input: typeof AdvanceEpochRequestSchema;
output: typeof AdvanceEpochResponseSchema;
},
+ /**
+ * Keeps a command running as a named service: started at once, started
+ * again by its restart policy when it exits or fails its health check,
+ * started when cua-spacesd starts (after the guest boots) unless
+ * `start_on_boot` is false, and its output kept in log files. Putting a
+ * name that exists replaces it (the old process is stopped first).
+ *
+ * @generated from rpc cua.env.v1.ProcessService.PutService
+ */
+ putService: {
+ methodKind: "unary";
+ input: typeof PutServiceRequestSchema;
+ output: typeof PutServiceResponseSchema;
+ },
+ /**
+ * Stops a service and forgets it (its log files go too).
+ *
+ * @generated from rpc cua.env.v1.ProcessService.DeleteService
+ */
+ deleteService: {
+ methodKind: "unary";
+ input: typeof DeleteServiceRequestSchema;
+ output: typeof DeleteServiceResponseSchema;
+ },
+ /**
+ * Lists services with their state.
+ *
+ * @generated from rpc cua.env.v1.ProcessService.ListServices
+ */
+ listServices: {
+ methodKind: "unary";
+ input: typeof ListServicesRequestSchema;
+ output: typeof ListServicesResponseSchema;
+ },
+ /**
+ * Starts, stops or restarts a service. A stopped service stays stopped
+ * until started (also across a restart of cua-spacesd).
+ *
+ * @generated from rpc cua.env.v1.ProcessService.ControlService
+ */
+ controlService: {
+ methodKind: "unary";
+ input: typeof ControlServiceRequestSchema;
+ output: typeof ControlServiceResponseSchema;
+ },
+ /**
+ * The end of a service's log.
+ *
+ * @generated from rpc cua.env.v1.ProcessService.GetServiceLogs
+ */
+ getServiceLogs: {
+ methodKind: "unary";
+ input: typeof GetServiceLogsRequestSchema;
+ output: typeof GetServiceLogsResponseSchema;
+ },
}> = /*@__PURE__*/
serviceDesc(file_cua_env_v1_process, 0);
diff --git a/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/tunnel_pb.ts b/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/tunnel_pb.ts
index caedf616ca..dbdb279a12 100644
--- a/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/tunnel_pb.ts
+++ b/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/tunnel_pb.ts
@@ -12,7 +12,7 @@ import type { Message } from "@bufbuild/protobuf";
* Describes the file cua/env/v1/tunnel.proto.
*/
export const file_cua_env_v1_tunnel: GenFile = /*@__PURE__*/
- fileDesc("ChdjdWEvZW52L3YxL3R1bm5lbC5wcm90bxIKY3VhLmVudi52MSJUCg5Gb3J3YXJkUmVxdWVzdBIMCgRwb3J0GAEgASgNEgwKBGhvc3QYAiABKAkSJgoDdHRsGAMgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uInYKD0ZvcndhcmRSZXNwb25zZRISCgpmb3J3YXJkX2lkGAEgASgJEg4KBnRpY2tldBgCIAEoCRIPCgd3c19wYXRoGAMgASgJEi4KCmV4cGlyZXNfYXQYBCABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wIq4BCgtGb3J3YXJkSW5mbxISCgpmb3J3YXJkX2lkGAEgASgJEgwKBGhvc3QYAiABKAkSDAoEcG9ydBgDIAEoDRIaChJhY3RpdmVfY29ubmVjdGlvbnMYBCABKA0SEAoIYnl0ZXNfaW4YBSABKAQSEQoJYnl0ZXNfb3V0GAYgASgEEi4KCmV4cGlyZXNfYXQYByABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wIhUKE0xpc3RGb3J3YXJkc1JlcXVlc3QiQQoUTGlzdEZvcndhcmRzUmVzcG9uc2USKQoIZm9yd2FyZHMYASADKAsyFy5jdWEuZW52LnYxLkZvcndhcmRJbmZvIikKE0Nsb3NlRm9yd2FyZFJlcXVlc3QSEgoKZm9yd2FyZF9pZBgBIAEoCSIWChRDbG9zZUZvcndhcmRSZXNwb25zZSKCAQoTU3RhcnRIb3RzcG90UmVxdWVzdBISCgpzb2Nrc19wb3J0GAEgASgNEhgKEHNldF9zeXN0ZW1fcHJveHkYAiABKAgSDgoGYnlwYXNzGAMgAygJEi0KCnRpY2tldF90dGwYBCABKAsyGS5nb29nbGUucHJvdG9idWYuRHVyYXRpb24iYgoUU3RhcnRIb3RzcG90UmVzcG9uc2USEgoKaG90c3BvdF9pZBgBIAEoCRIOCgZ0aWNrZXQYAiABKAkSDwoHd3NfcGF0aBgDIAEoCRIVCg1zb2Nrc19hZGRyZXNzGAQgASgJIigKElN0b3BIb3RzcG90UmVxdWVzdBISCgpob3RzcG90X2lkGAEgASgJIhUKE1N0b3BIb3RzcG90UmVzcG9uc2UiGQoXR2V0SG90c3BvdFN0YXR1c1JlcXVlc3QiygEKGEdldEhvdHNwb3RTdGF0dXNSZXNwb25zZRInCgVzdGF0ZRgBIAEoDjIYLmN1YS5lbnYudjEuSG90c3BvdFN0YXRlEhIKCmhvdHNwb3RfaWQYAiABKAkSGQoRcGVlcl9wcmluY2lwYWxfaWQYAyABKAkSFQoNc29ja3NfYWRkcmVzcxgEIAEoCRIaChJhY3RpdmVfY29ubmVjdGlvbnMYBSABKA0SEQoJYnl0ZXNfb3V0GAYgASgEEhAKCGJ5dGVzX2luGAcgASgEKoYBCgxIb3RzcG90U3RhdGUSHQoZSE9UU1BPVF9TVEFURV9VTlNQRUNJRklFRBAAEhkKFUhPVFNQT1RfU1RBVEVfU1RPUFBFRBABEiIKHkhPVFNQT1RfU1RBVEVfV0FJVElOR19GT1JfUEVFUhACEhgKFEhPVFNQT1RfU1RBVEVfQUNUSVZFEAMy+wMKDVR1bm5lbFNlcnZpY2USQgoHRm9yd2FyZBIaLmN1YS5lbnYudjEuRm9yd2FyZFJlcXVlc3QaGy5jdWEuZW52LnYxLkZvcndhcmRSZXNwb25zZRJRCgxMaXN0Rm9yd2FyZHMSHy5jdWEuZW52LnYxLkxpc3RGb3J3YXJkc1JlcXVlc3QaIC5jdWEuZW52LnYxLkxpc3RGb3J3YXJkc1Jlc3BvbnNlElEKDENsb3NlRm9yd2FyZBIfLmN1YS5lbnYudjEuQ2xvc2VGb3J3YXJkUmVxdWVzdBogLmN1YS5lbnYudjEuQ2xvc2VGb3J3YXJkUmVzcG9uc2USUQoMU3RhcnRIb3RzcG90Eh8uY3VhLmVudi52MS5TdGFydEhvdHNwb3RSZXF1ZXN0GiAuY3VhLmVudi52MS5TdGFydEhvdHNwb3RSZXNwb25zZRJOCgtTdG9wSG90c3BvdBIeLmN1YS5lbnYudjEuU3RvcEhvdHNwb3RSZXF1ZXN0Gh8uY3VhLmVudi52MS5TdG9wSG90c3BvdFJlc3BvbnNlEl0KEEdldEhvdHNwb3RTdGF0dXMSIy5jdWEuZW52LnYxLkdldEhvdHNwb3RTdGF0dXNSZXF1ZXN0GiQuY3VhLmVudi52MS5HZXRIb3RzcG90U3RhdHVzUmVzcG9uc2ViBnByb3RvMw", [file_google_protobuf_duration, file_google_protobuf_timestamp]);
+ fileDesc("ChdjdWEvZW52L3YxL3R1bm5lbC5wcm90bxIKY3VhLmVudi52MSJUCg5Gb3J3YXJkUmVxdWVzdBIMCgRwb3J0GAEgASgNEgwKBGhvc3QYAiABKAkSJgoDdHRsGAMgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uInYKD0ZvcndhcmRSZXNwb25zZRISCgpmb3J3YXJkX2lkGAEgASgJEg4KBnRpY2tldBgCIAEoCRIPCgd3c19wYXRoGAMgASgJEi4KCmV4cGlyZXNfYXQYBCABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wIq4BCgtGb3J3YXJkSW5mbxISCgpmb3J3YXJkX2lkGAEgASgJEgwKBGhvc3QYAiABKAkSDAoEcG9ydBgDIAEoDRIaChJhY3RpdmVfY29ubmVjdGlvbnMYBCABKA0SEAoIYnl0ZXNfaW4YBSABKAQSEQoJYnl0ZXNfb3V0GAYgASgEEi4KCmV4cGlyZXNfYXQYByABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wIhUKE0xpc3RGb3J3YXJkc1JlcXVlc3QiQQoUTGlzdEZvcndhcmRzUmVzcG9uc2USKQoIZm9yd2FyZHMYASADKAsyFy5jdWEuZW52LnYxLkZvcndhcmRJbmZvIikKE0Nsb3NlRm9yd2FyZFJlcXVlc3QSEgoKZm9yd2FyZF9pZBgBIAEoCSIWChRDbG9zZUZvcndhcmRSZXNwb25zZSKCAQoTU3RhcnRIb3RzcG90UmVxdWVzdBISCgpzb2Nrc19wb3J0GAEgASgNEhgKEHNldF9zeXN0ZW1fcHJveHkYAiABKAgSDgoGYnlwYXNzGAMgAygJEi0KCnRpY2tldF90dGwYBCABKAsyGS5nb29nbGUucHJvdG9idWYuRHVyYXRpb24iYgoUU3RhcnRIb3RzcG90UmVzcG9uc2USEgoKaG90c3BvdF9pZBgBIAEoCRIOCgZ0aWNrZXQYAiABKAkSDwoHd3NfcGF0aBgDIAEoCRIVCg1zb2Nrc19hZGRyZXNzGAQgASgJIigKElN0b3BIb3RzcG90UmVxdWVzdBISCgpob3RzcG90X2lkGAEgASgJIhUKE1N0b3BIb3RzcG90UmVzcG9uc2UiGQoXR2V0SG90c3BvdFN0YXR1c1JlcXVlc3QiygEKGEdldEhvdHNwb3RTdGF0dXNSZXNwb25zZRInCgVzdGF0ZRgBIAEoDjIYLmN1YS5lbnYudjEuSG90c3BvdFN0YXRlEhIKCmhvdHNwb3RfaWQYAiABKAkSGQoRcGVlcl9wcmluY2lwYWxfaWQYAyABKAkSFQoNc29ja3NfYWRkcmVzcxgEIAEoCRIaChJhY3RpdmVfY29ubmVjdGlvbnMYBSABKA0SEQoJYnl0ZXNfb3V0GAYgASgEEhAKCGJ5dGVzX2luGAcgASgEImgKEVN0YXJ0U3Bhd25SZXF1ZXN0EhIKCmNhcGFiaWxpdHkYASABKAkSLQoKdGlja2V0X3R0bBgCIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlvbhIQCghzcGFjZV9pZBgDIAEoCSKCAQoSU3RhcnRTcGF3blJlc3BvbnNlEhAKCHNwYXduX2lkGAEgASgJEg4KBnRpY2tldBgCIAEoCRIPCgd3c19wYXRoGAMgASgJEg8KB2FkZHJlc3MYBCABKAkSEgoKdG9rZW5fcGF0aBgFIAEoCRIUCgxhZGRyZXNzX3BhdGgYBiABKAkiJAoQU3RvcFNwYXduUmVxdWVzdBIQCghzcGF3bl9pZBgBIAEoCSITChFTdG9wU3Bhd25SZXNwb25zZSIXChVHZXRTcGF3blN0YXR1c1JlcXVlc3QiegoWR2V0U3Bhd25TdGF0dXNSZXNwb25zZRIPCgdzdGFydGVkGAEgASgIEhAKCGF0dGFjaGVkGAIgASgIEhAKCHNwYXduX2lkGAMgASgJEg8KB2FkZHJlc3MYBCABKAkSGgoSYWN0aXZlX2Nvbm5lY3Rpb25zGAUgASgNKoYBCgxIb3RzcG90U3RhdGUSHQoZSE9UU1BPVF9TVEFURV9VTlNQRUNJRklFRBAAEhkKFUhPVFNQT1RfU1RBVEVfU1RPUFBFRBABEiIKHkhPVFNQT1RfU1RBVEVfV0FJVElOR19GT1JfUEVFUhACEhgKFEhPVFNQT1RfU1RBVEVfQUNUSVZFEAMy6wUKDVR1bm5lbFNlcnZpY2USQgoHRm9yd2FyZBIaLmN1YS5lbnYudjEuRm9yd2FyZFJlcXVlc3QaGy5jdWEuZW52LnYxLkZvcndhcmRSZXNwb25zZRJRCgxMaXN0Rm9yd2FyZHMSHy5jdWEuZW52LnYxLkxpc3RGb3J3YXJkc1JlcXVlc3QaIC5jdWEuZW52LnYxLkxpc3RGb3J3YXJkc1Jlc3BvbnNlElEKDENsb3NlRm9yd2FyZBIfLmN1YS5lbnYudjEuQ2xvc2VGb3J3YXJkUmVxdWVzdBogLmN1YS5lbnYudjEuQ2xvc2VGb3J3YXJkUmVzcG9uc2USUQoMU3RhcnRIb3RzcG90Eh8uY3VhLmVudi52MS5TdGFydEhvdHNwb3RSZXF1ZXN0GiAuY3VhLmVudi52MS5TdGFydEhvdHNwb3RSZXNwb25zZRJOCgtTdG9wSG90c3BvdBIeLmN1YS5lbnYudjEuU3RvcEhvdHNwb3RSZXF1ZXN0Gh8uY3VhLmVudi52MS5TdG9wSG90c3BvdFJlc3BvbnNlEl0KEEdldEhvdHNwb3RTdGF0dXMSIy5jdWEuZW52LnYxLkdldEhvdHNwb3RTdGF0dXNSZXF1ZXN0GiQuY3VhLmVudi52MS5HZXRIb3RzcG90U3RhdHVzUmVzcG9uc2USSwoKU3RhcnRTcGF3bhIdLmN1YS5lbnYudjEuU3RhcnRTcGF3blJlcXVlc3QaHi5jdWEuZW52LnYxLlN0YXJ0U3Bhd25SZXNwb25zZRJICglTdG9wU3Bhd24SHC5jdWEuZW52LnYxLlN0b3BTcGF3blJlcXVlc3QaHS5jdWEuZW52LnYxLlN0b3BTcGF3blJlc3BvbnNlElcKDkdldFNwYXduU3RhdHVzEiEuY3VhLmVudi52MS5HZXRTcGF3blN0YXR1c1JlcXVlc3QaIi5jdWEuZW52LnYxLkdldFNwYXduU3RhdHVzUmVzcG9uc2ViBnByb3RvMw", [file_google_protobuf_duration, file_google_protobuf_timestamp]);
/**
* Request for `TunnelService.Forward`.
@@ -433,6 +433,203 @@ export type GetHotspotStatusResponse = Message<"cua.env.v1.GetHotspotStatusRespo
export const GetHotspotStatusResponseSchema: GenMessage<GetHotspotStatusResponse> = /*@__PURE__*/
messageDesc(file_cua_env_v1_tunnel, 12);
+/**
+ * Request for `TunnelService.StartSpawn`.
+ *
+ * @generated from message cua.env.v1.StartSpawnRequest
+ */
+export type StartSpawnRequest = Message<"cua.env.v1.StartSpawnRequest"> & {
+ /**
+ * The Space's spawn capability, minted by its host. The guest writes it
+ * to the token file (0600, owner: the user cua-spacesd runs as) for
+ * clients in the Space to present on the spawn listener.
+ *
+ * @generated from field: string capability = 1;
+ */
+ capability: string;
+
+ /**
+ * How long the ticket accepts the host's WebSocket. Unset means 60
+ * seconds.
+ *
+ * @generated from field: google.protobuf.Duration ticket_ttl = 2;
+ */
+ ticketTtl?: Duration | undefined;
+
+ /**
+ * The Space's id, for the environment of new processes (`CUA_SPACE`).
+ *
+ * @generated from field: string space_id = 3;
+ */
+ spaceId: string;
+};
+
+/**
+ * Describes the message cua.env.v1.StartSpawnRequest.
+ * Use `create(StartSpawnRequestSchema)` to create a new message.
+ */
+export const StartSpawnRequestSchema: GenMessage<StartSpawnRequest> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_tunnel, 13);
+
+/**
+ * Response for `TunnelService.StartSpawn`.
+ *
+ * @generated from message cua.env.v1.StartSpawnResponse
+ */
+export type StartSpawnResponse = Message<"cua.env.v1.StartSpawnResponse"> & {
+ /**
+ * Spawn channel id.
+ *
+ * @generated from field: string spawn_id = 1;
+ */
+ spawnId: string;
+
+ /**
+ * Ticket for the spawn WebSocket.
+ *
+ * @generated from field: string ticket = 2;
+ */
+ ticket: string;
+
+ /**
+ * WebSocket path relative to the spacesd base URL, including the ticket,
+ * for example "/spawn?ticket=…". The host keeps this socket open; the
+ * listener refuses connections while it is closed.
+ *
+ * @generated from field: string ws_path = 3;
+ */
+ wsPath: string;
+
+ /**
+ * Guest-side listener, as a URL clients in the Space use as their cua
+ * daemon, for example "http://127.0.0.1:41234".
+ *
+ * @generated from field: string address = 4;
+ */
+ address: string;
+
+ /**
+ * Where the guest wrote the capability.
+ *
+ * @generated from field: string token_path = 5;
+ */
+ tokenPath: string;
+
+ /**
+ * Where the guest wrote the listener's address (one line).
+ *
+ * @generated from field: string address_path = 6;
+ */
+ addressPath: string;
+};
+
+/**
+ * Describes the message cua.env.v1.StartSpawnResponse.
+ * Use `create(StartSpawnResponseSchema)` to create a new message.
+ */
+export const StartSpawnResponseSchema: GenMessage<StartSpawnResponse> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_tunnel, 14);
+
+/**
+ * Request for `TunnelService.StopSpawn`.
+ *
+ * @generated from message cua.env.v1.StopSpawnRequest
+ */
+export type StopSpawnRequest = Message<"cua.env.v1.StopSpawnRequest"> & {
+ /**
+ * Which channel. Empty stops the current one.
+ *
+ * @generated from field: string spawn_id = 1;
+ */
+ spawnId: string;
+};
+
+/**
+ * Describes the message cua.env.v1.StopSpawnRequest.
+ * Use `create(StopSpawnRequestSchema)` to create a new message.
+ */
+export const StopSpawnRequestSchema: GenMessage<StopSpawnRequest> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_tunnel, 15);
+
+/**
+ * Response for `TunnelService.StopSpawn`.
+ *
+ * @generated from message cua.env.v1.StopSpawnResponse
+ */
+export type StopSpawnResponse = Message<"cua.env.v1.StopSpawnResponse"> & {
+};
+
+/**
+ * Describes the message cua.env.v1.StopSpawnResponse.
+ * Use `create(StopSpawnResponseSchema)` to create a new message.
+ */
+export const StopSpawnResponseSchema: GenMessage<StopSpawnResponse> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_tunnel, 16);
+
+/**
+ * Request for `TunnelService.GetSpawnStatus`.
+ *
+ * @generated from message cua.env.v1.GetSpawnStatusRequest
+ */
+export type GetSpawnStatusRequest = Message<"cua.env.v1.GetSpawnStatusRequest"> & {
+};
+
+/**
+ * Describes the message cua.env.v1.GetSpawnStatusRequest.
+ * Use `create(GetSpawnStatusRequestSchema)` to create a new message.
+ */
+export const GetSpawnStatusRequestSchema: GenMessage<GetSpawnStatusRequest> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_tunnel, 17);
+
+/**
+ * Response for `TunnelService.GetSpawnStatus`.
+ *
+ * @generated from message cua.env.v1.GetSpawnStatusResponse
+ */
+export type GetSpawnStatusResponse = Message<"cua.env.v1.GetSpawnStatusResponse"> & {
+ /**
+ * A channel is started.
+ *
+ * @generated from field: bool started = 1;
+ */
+ started: boolean;
+
+ /**
+ * The host's WebSocket is attached.
+ *
+ * @generated from field: bool attached = 2;
+ */
+ attached: boolean;
+
+ /**
+ * Channel id, when started.
+ *
+ * @generated from field: string spawn_id = 3;
+ */
+ spawnId: string;
+
+ /**
+ * Guest-side listener URL, when started.
+ *
+ * @generated from field: string address = 4;
+ */
+ address: string;
+
+ /**
+ * Open relayed connections.
+ *
+ * @generated from field: uint32 active_connections = 5;
+ */
+ activeConnections: number;
+};
+
+/**
+ * Describes the message cua.env.v1.GetSpawnStatusResponse.
+ * Use `create(GetSpawnStatusResponseSchema)` to create a new message.
+ */
+export const GetSpawnStatusResponseSchema: GenMessage<GetSpawnStatusResponse> = /*@__PURE__*/
+ messageDesc(file_cua_env_v1_tunnel, 18);
+
/**
* Hotspot state.
*
@@ -486,6 +683,11 @@ export const HotspotStateSchema: GenEnum<HotspotState> = /*@__PURE__*/
* guest loopback relays each outbound connection over the client's
* WebSocket, and the client dials it from its own network. Replaces the
* unauthenticated rcdp-socks.
+ * - Spawn: the guest-to-host channel of child Spaces. A listener on guest
+ * loopback relays each connection over the WebSocket of the host that runs
+ * the Space, which serves this Space's own children (create, list, delete)
+ * and nothing else. The host knows which Space a connection comes from by
+ * the WebSocket it opened, never by anything the guest says.
*
* @generated from service cua.env.v1.TunnelService
*/
@@ -551,6 +753,38 @@ export const TunnelService: GenService<{
input: typeof GetHotspotStatusRequestSchema;
output: typeof GetHotspotStatusResponseSchema;
},
+ /**
+ * Starts the spawn channel and installs the Space's spawn capability.
+ * Only a caller holding the Space's own token (the host that runs it) may
+ * call it; starting it again replaces the channel and the capability.
+ *
+ * @generated from rpc cua.env.v1.TunnelService.StartSpawn
+ */
+ startSpawn: {
+ methodKind: "unary";
+ input: typeof StartSpawnRequestSchema;
+ output: typeof StartSpawnResponseSchema;
+ },
+ /**
+ * Stops the spawn channel and removes the capability from the guest.
+ *
+ * @generated from rpc cua.env.v1.TunnelService.StopSpawn
+ */
+ stopSpawn: {
+ methodKind: "unary";
+ input: typeof StopSpawnRequestSchema;
+ output: typeof StopSpawnResponseSchema;
+ },
+ /**
+ * Reports the spawn channel's state.
+ *
+ * @generated from rpc cua.env.v1.TunnelService.GetSpawnStatus
+ */
+ getSpawnStatus: {
+ methodKind: "unary";
+ input: typeof GetSpawnStatusRequestSchema;
+ output: typeof GetSpawnStatusResponseSchema;
+ },
}> = /*@__PURE__*/
serviceDesc(file_cua_env_v1_tunnel, 0);
diff --git a/libs/cua/crates/cua-telemetry/src/cli_commands.in b/libs/cua/crates/cua-telemetry/src/cli_commands.in
index 692ab253e6..b0f1b30a45 100644
--- a/libs/cua/crates/cua-telemetry/src/cli_commands.in
+++ b/libs/cua/crates/cua-telemetry/src/cli_commands.in
@@ -116,6 +116,9 @@
"doctor",
"doctor.parity",
"dump-docs",
+ "experiments.disable",
+ "experiments.enable",
+ "experiments.list",
"fleet",
"host.cache",
"host.config",
@@ -158,6 +161,9 @@
"keyvault.unlock",
"machines.rm",
"mcp",
+ "network.log",
+ "network.set",
+ "network.show",
"pools",
"run",
"runtime.doctor",
@@ -204,18 +210,22 @@
"skills.record",
"skills.replay",
"spaces.add",
+ "spaces.budget",
"spaces.cancel",
+ "spaces.children",
"spaces.create",
"spaces.delete",
"spaces.egress",
"spaces.gpus",
"spaces.ls",
+ "spaces.orphans",
"spaces.prewarm",
"spaces.relay-register",
"spaces.relay-unregister",
"spaces.rename",
"spaces.resize",
"spaces.rm",
+ "spaces.service",
"spaces.share",
"spaces.shares",
"spaces.start",
diff --git a/libs/cua/crates/cua-telemetry/src/schema.rs b/libs/cua/crates/cua-telemetry/src/schema.rs
index e2cbdce78f..c2a8dc3470 100644
--- a/libs/cua/crates/cua-telemetry/src/schema.rs
+++ b/libs/cua/crates/cua-telemetry/src/schema.rs
@@ -654,7 +654,13 @@ pub const LIMIT_KINDS: &[&str] = &["sessions", "hours", "machines", "seats", "ot
pub const PLANS: &[&str] = &["free", "pro", "teams", "unknown"];
/// The Spaces app's experiments (Settings, Experiments;
/// `cua-spaces-app-core` `experiments::Experiment::id`).
-pub const EXPERIMENTS: &[&str] = &["cua_volume", "your_cloud", "sharing"];
+pub const EXPERIMENTS: &[&str] = &[
+ "cua_volume",
+ "your_cloud",
+ "sharing",
+ "secure_spaces",
+ "child_spaces",
+];
/// The Spaces app's interface language, as a fixed set: the languages it
/// ships or plans to; any other language reads `other`. No region, no text.
pub const UI_LOCALES: &[&str] = &["en", "zh-Hans", "ko", "pt-BR", "ja", "es", "other"];
@@ -1747,7 +1753,7 @@ pub const EVENTS: &[EventSpec] = &[
p(
"experiments_on",
Kind::Set(EXPERIMENTS),
- "The Spaces app's experiments turned on in Settings, Experiments on this install (cua_volume, your_cloud, sharing, joined with +), or none.",
+ "The Spaces app's experiments turned on in Settings, Experiments on this install (cua_volume, your_cloud, sharing, secure_spaces, child_spaces, joined with +), or none.",
),
p(
"ui_locale",
@@ -2177,7 +2183,7 @@ pub const EVENTS: &[EventSpec] = &[
p(
"experiment",
Kind::Enum(EXPERIMENTS),
- "Which experiment: cua_volume, your_cloud or sharing.",
+ "Which experiment: cua_volume, your_cloud, sharing, secure_spaces or child_spaces.",
),
],
purpose: "Which experiments people try, and which they turn off again.",
diff --git a/libs/cua/crates/cua-vmm/Cargo.toml b/libs/cua/crates/cua-vmm/Cargo.toml
index a8e3d9c1fa..da7698a361 100644
--- a/libs/cua/crates/cua-vmm/Cargo.toml
+++ b/libs/cua/crates/cua-vmm/Cargo.toml
@@ -82,3 +82,5 @@ tempfile = "3"
tokio = { version = "1", features = ["full"] }
# Reads Local's `config.yaml` back with a real YAML parser (same version as cua-agent-setup).
serde_yaml_ng = "0.10"
+# Property tests of the network model (fail closed, tree intersection).
+proptest = "1"
diff --git a/libs/cua/crates/cua-vmm/build.rs b/libs/cua/crates/cua-vmm/build.rs
new file mode 100644
index 0000000000..befaf0dce3
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/build.rs
@@ -0,0 +1,62 @@
+//! Files this crate embeds from elsewhere in the repository (the macOS image
+//! recipe that builds the developer tools image on the user's own Mac).
+//!
+//! The crate reads committed copies under `recipe/`, so everything it compiles
+//! lives inside libs/cua (the Rust build cache key hashes that tree). The
+//! source of truth stays in libs/images/macos; a test in scripts/images/tests
+//! fails when a copy falls behind (refresh with
+//! `scripts/images/sync-cua-vmm-recipe.sh`). The crate published to crates.io
+//! also carries copies under `vendor/` (copied by
+//! libs/cua/scripts/publish-crates.sh). Either way they land in OUT_DIR and
+//! the code embeds them from there.
+
+use std::{
+ env, fs, io,
+ path::{Path, PathBuf},
+};
+
+/// (committed copy relative to this crate, name in OUT_DIR and vendor/):
+/// a file or a directory.
+const FILES: &[(&str, &str)] = &[
+ ("recipe/macos-derive-local.sh", "macos-derive-local.sh"),
+ ("recipe/macos-versions.env", "macos-versions.env"),
+ ("recipe/macos-tier-xcode.sh", "macos-tier-xcode.sh"),
+ ("recipe/macos-fetch.sh", "macos-fetch.sh"),
+ ("recipe/macos-xcode-source.sh", "macos-xcode-source.sh"),
+];
+
+fn copy(from: &Path, to: &Path) -> io::Result<()> {
+ if from.is_dir() {
+ fs::create_dir_all(to)?;
+ for entry in fs::read_dir(from)? {
+ let entry = entry?;
+ copy(&entry.path(), &to.join(entry.file_name()))?;
+ }
+ Ok(())
+ } else {
+ fs::copy(from, to).map(|_| ())
+ }
+}
+
+fn main() {
+ let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
+ let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
+ println!("cargo:rerun-if-changed=build.rs");
+ for (repo_path, name) in FILES {
+ let committed = manifest_dir.join(repo_path);
+ let source = if committed.exists() {
+ committed
+ } else {
+ manifest_dir.join("vendor").join(name)
+ };
+ println!("cargo:rerun-if-changed={}", source.display());
+ let target = out_dir.join(name);
+ let _ = fs::remove_dir_all(&target);
+ copy(&source, &target).unwrap_or_else(|e| {
+ panic!(
+ "{}: {e} (libs/cua/scripts/publish-crates.sh vendors it)",
+ source.display()
+ )
+ });
+ }
+}
diff --git a/libs/cua/crates/cua-vmm/recipe/macos-derive-local.sh b/libs/cua/crates/cua-vmm/recipe/macos-derive-local.sh
new file mode 100755
index 0000000000..3d815d2cb8
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/recipe/macos-derive-local.sh
@@ -0,0 +1,173 @@
+#!/usr/bin/env bash
+# Derive the macOS Space with developer tools (the xcode tier) on THIS Mac,
+# from the published full tier and an Xcode that is already here. The default
+# way to get the tier is to pull the published ghcr.io/trycua/macos:26-xcode;
+# this is the fallback for when that image is not available, or for a Mac that
+# already has the Xcode it wants and the user prefers to use it. Xcode and the
+# iOS Simulator runtimes are Apple software under Apple's license, for use on
+# Apple-branded hardware: this refuses to run anywhere else.
+#
+# libs/images/macos/derive-local.sh --base-vm NAME [--name VM] [--xcode PATH]
+# [--out DIR] [--memory 8GB] [--keep-going-low-disk] [--json]
+#
+# --base-vm NAME the local Lume VM of the full tier to clone (the SDK keeps
+# it as cua-base-<sha12>); it is never modified
+# --name VM the derived VM (default cua-dev-macos-<pid>)
+# --xcode PATH an Xcode.app or Xcode .xip to use; default: the Mac's own
+# (xcode-select, then /Applications/Xcode*.app, newest first,
+# then an .xip in $CUA_XCODE_CACHE, ~/XcodesCache or
+# ~/Downloads)
+# --out DIR staging and logs (default ~/.cache/cua-images/macos-dev)
+# --memory memory for the build boot (default 8GB; the VM keeps the
+# base's own value afterwards)
+# --json print one JSON line of results (sizes and timings) at the end
+#
+# Exit codes: 0 done; 2 usage; 3 no Xcode on this Mac (Apple needs a sign-in to
+# download one: install it from the App Store or download the .xip from
+# developer.apple.com, then run again); 4 not enough free disk; 5 the guest's
+# macOS is older than the Xcode needs.
+#
+# CUA_LUME_BIN is the lume binary (default: lume on PATH).
+# CUA_LUME_STORAGE is a Lume storage directory to use instead of the default
+# one (every lume call gets --storage with it): the base VM must be there, and
+# so is the derived VM.
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+BASE_VM="" VM="cua-dev-macos-$$" XCODE="" MEMORY=8GB JSON=0
+OUT="${CUA_IMAGES_OUT:-$HOME/.cache/cua-images}/macos-dev"
+# The volume must keep this much free after the derive (the build stops there).
+FLOOR_GB="${CUA_DEV_IMAGE_FLOOR_GB:-10}"
+# Growth the derive needs beyond Xcode itself: iOS runtime, Metal toolchain,
+# tools, Simulator data and caches while building.
+EXTRA_GB="${CUA_DEV_IMAGE_EXTRA_GB:-18}"
+# shellcheck disable=SC2034 # XCODE is read by find_xcode (files/xcode-source.sh)
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --base-vm) BASE_VM="$2"; shift 2 ;;
+ --name) VM="$2"; shift 2 ;;
+ --xcode) XCODE="$2"; shift 2 ;;
+ --out) OUT="$2"; shift 2 ;;
+ --memory) MEMORY="$2"; shift 2 ;;
+ --json) JSON=1; shift ;;
+ -h|--help) sed -n '2,29p' "$0"; exit 0 ;;
+ *) echo "unknown option $1" >&2; exit 2 ;;
+ esac
+done
+[ -n "$BASE_VM" ] || { echo "--base-vm is required (the local VM of the full tier)" >&2; exit 2; }
+# shellcheck source=versions.env
+. "$HERE/versions.env"
+log() { echo "[macos-dev $(date +%T)] $*" >&2; }
+ST="${CUA_LUME_STORAGE:-}"
+LUME_BIN="${CUA_LUME_BIN:-$(type -P lume || echo lume)}"
+# lume SUBCOMMAND ARGS...: with CUA_LUME_STORAGE set, on that storage.
+lume() {
+ local sub="$1"; shift
+ case "$sub" in
+ clone) if [ -n "$ST" ]; then "$LUME_BIN" clone --source-storage "$ST" --dest-storage "$ST" "$@"; else "$LUME_BIN" clone "$@"; fi ;;
+ run|ssh|get|set|stop|delete) if [ -n "$ST" ]; then "$LUME_BIN" "$sub" --storage "$ST" "$@"; else "$LUME_BIN" "$sub" "$@"; fi ;;
+ *) "$LUME_BIN" "$sub" "$@" ;;
+ esac
+}
+guest() { lume ssh -t "${2:-120}" "$VM" "$1" </dev/null; }
+# shellcheck source=files/xcode-source.sh
+. "$HERE/files/xcode-source.sh"
+if ! SRC="$(find_xcode)"; then
+ cat >&2 <<'MSG'
+No Xcode on this Mac. Apple requires a signed-in download, so Cua cannot fetch one for you.
+Install Xcode from the App Store, or download the Xcode .xip from developer.apple.com/download
+and put it in ~/XcodesCache, then create the macOS Space with developer tools again.
+MSG
+ exit 3
+fi
+[ -e "$SRC" ] || { echo "$SRC does not exist" >&2; exit 2; }
+log "Xcode source: $SRC"
+case "$SRC" in
+ *.app) XVER="$(plist "$SRC" CFBundleShortVersionString)"; XMIN="$(plist "$SRC" LSMinimumSystemVersion || true)"
+ SRC_KB="$(( $(du -sk "$SRC" | cut -f1) * 2 ))" ;; # the archive and the copy
+ *.xip) XVER="$(basename "$SRC" | sed -n 's/^Xcode[_ -]\{0,1\}\([0-9][0-9.]*\).*/\1/p')"; XMIN=""
+ SRC_KB="$(( $(stat -f %z "$SRC") * 3 / 1024 ))" ;; # an .xip expands to about 3x
+ *) echo "--xcode takes an Xcode.app or an .xip" >&2; exit 2 ;;
+esac
+
+# --- disk ---------------------------------------------------------------------------
+LUME_DIR="${CUA_LUME_STORAGE:-$HOME/.lume}"
+mkdir -p "$LUME_DIR" "$OUT"
+free_gb() { df -k "$1" | awk 'NR==2 {print int($4/1024/1024)}'; }
+need_gb=$(( SRC_KB / 1024 / 1024 + 1 + EXTRA_GB ))
+have_gb="$(free_gb "$LUME_DIR")"
+if [ "$have_gb" -lt $(( need_gb + FLOOR_GB )) ]; then
+ cat >&2 <<MSG
+Not enough free disk to build the macOS Space with developer tools: it needs about ${need_gb} GB
+and the Mac should keep ${FLOOR_GB} GB free, but only ${have_gb} GB is free.
+Make room: remove Spaces and images you no longer use, empty the Trash, or delete old Xcode caches
+(~/Library/Developer/Xcode/DerivedData, ~/Library/Developer/CoreSimulator).
+MSG
+ exit 4
+fi
+
+[ "$(uname -s)" = Darwin ] && [ "$(uname -m)" = arm64 ] ||
+ { echo "The macOS Space with developer tools runs only on Apple-branded hardware with Apple silicon." >&2; exit 2; }
+command -v "$LUME_BIN" >/dev/null || { echo "lume is required" >&2; exit 2; }
+
+# --- stage: scripts, pins, tools ----------------------------------------------------------
+CACHE="${CUA_MACOS_CACHE:-$HOME/.cache/cua-images/macos-cache}"
+SETUP="$OUT/setup"
+rm -rf "$SETUP"; mkdir -p "$SETUP/cache" "$SETUP/xcode" "$CACHE"; chmod 700 "$SETUP"
+cp "$HERE/files/tier-xcode.sh" "$HERE/versions.env" "$SETUP/"
+# shellcheck source=files/fetch.sh
+. "$HERE/files/fetch.sh"
+fetch_xcode_tools
+log "packing $(basename "$SRC") for the guest"
+stage_xcode "$SRC" "$SETUP/xcode"
+
+cleanup() {
+ lume stop "$VM" >/dev/null 2>&1 || true
+ for pid in $(pgrep -f "lume run .*$VM" || true); do kill "$pid" 2>/dev/null || true; done
+ rm -rf "$SETUP"
+ [ "${KEEP:-1}" = 1 ] || lume delete --force "$VM" >/dev/null 2>&1 || true
+}
+KEEP=0
+trap cleanup EXIT
+
+t0=$(date +%s)
+log "cloning $BASE_VM -> $VM"
+lume clone "$BASE_VM" "$VM"
+base_memory="$(lume get --format json "$VM" | python3 -c 'import json,sys;d=json.load(sys.stdin);d=d[0] if isinstance(d,list) else d;print(d["memorySize"])')"
+lume set --memory "$MEMORY" "$VM"
+log "booting $VM"
+lume run --display none --detach --shared-dir "$SETUP:ro" --log-file "$OUT/vm.log" "$VM" >/dev/null
+up=0
+for _ in $(seq 1 60); do guest 'echo up' 2>/dev/null | grep -q up && { up=1; break; }; sleep 5; done
+[ "$up" = 1 ] || { echo "$VM never answered over ssh (see $OUT/vm.log)" >&2; exit 1; }
+for _ in $(seq 1 36); do guest 'pgrep -qx Dock && pgrep -qx Finder' 2>/dev/null && break; sleep 5; done
+t_boot=$(date +%s)
+os="$(guest 'sw_vers -productVersion')"
+if [ -n "${XMIN:-}" ] && [ "$(printf '%s\n%s\n' "$XMIN" "$os" | sort -V | head -1)" != "$XMIN" ]; then
+ echo "Xcode $XVER needs macOS $XMIN; this Space's macOS is $os. Use an older Xcode (or a newer macOS image)." >&2
+ exit 5
+fi
+
+S="/Volumes/My Shared Files/setup"
+log "installing the developer tools (Xcode ${XVER:-?}, iOS runtime, tools)"
+guest "bash '$S/tier-xcode.sh' '$S'" 5400 2>&1 | tee "$OUT/tier-xcode.log" | sed 's/^/ /' >&2
+t_tier=$(date +%s)
+
+log "shutting down"
+guest "printf '%s\n' lume | sudo -S -p '' shutdown -h now" 30 >/dev/null 2>&1 || true
+for _ in $(seq 1 60); do
+ st="$(lume get --format json "$VM" 2>/dev/null | python3 -c 'import json,sys;d=json.load(sys.stdin);d=d[0] if isinstance(d,list) else d;print(d["status"])' 2>/dev/null || true)"
+ [ "$st" = stopped ] && break; sleep 5
+done
+[ "$st" = stopped ] || lume stop "$VM" >/dev/null
+lume set --memory "$((base_memory / 1024 / 1024))MB" "$VM"
+KEEP=1
+t_end=$(date +%s)
+sizes="$(lume get --format json "$VM" | python3 -c 'import json,sys;d=json.load(sys.stdin);d=d[0] if isinstance(d,list) else d;print(json.dumps({"vm":d["name"],"disk_used_bytes":d["diskSize"]["allocated"],"disk_total_bytes":d["diskSize"]["total"]}))')"
+log "derived $VM in $((t_end - t0)) s ($sizes)"
+if [ "$JSON" = 1 ]; then
+ python3 - "$sizes" "$XVER" "$((t_boot - t0))" "$((t_tier - t_boot))" "$((t_end - t0))" <<'PY'
+import json, sys
+d = json.loads(sys.argv[1]); d.update(xcode=sys.argv[2], clone_boot_seconds=int(sys.argv[3]), tier_seconds=int(sys.argv[4]), total_seconds=int(sys.argv[5]))
+print(json.dumps(d))
+PY
+fi
diff --git a/libs/cua/crates/cua-vmm/recipe/macos-fetch.sh b/libs/cua/crates/cua-vmm/recipe/macos-fetch.sh
new file mode 100644
index 0000000000..db34f7cd87
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/recipe/macos-fetch.sh
@@ -0,0 +1,23 @@
+# shellcheck shell=bash
+# Sourced by build.sh and derive-local.sh: the checksummed download cache.
+# CACHE the host cache directory
+# SETUP the share the guest reads (cache/ inside it)
+# log a logging function
+# fetch URL SHA256 downloads once into $CACHE, checks the hash and links the
+# file into $SETUP/cache.
+fetch() {
+ local f; f="$CACHE/$(basename "$1")"
+ if [ ! -f "$f" ] || [ "$(shasum -a 256 "$f" | cut -d' ' -f1)" != "$2" ]; then
+ log "fetching $1"
+ curl -fsSL --retry 3 -o "$f.part" "$1"
+ [ "$(shasum -a 256 "$f.part" | cut -d' ' -f1)" = "$2" ] ||
+ { rm -f "$f.part"; echo "checksum mismatch: $1" >&2; exit 1; }
+ mv "$f.part" "$f"
+ fi
+ ln -f "$f" "$SETUP/cache/" 2>/dev/null || cp "$f" "$SETUP/cache/"
+}
+# The downloads of the xcode tier's tools (everything but Xcode itself).
+fetch_xcode_tools() {
+ fetch "$SCCACHE_URL" "$SCCACHE_SHA256"
+ fetch "$XCODEGEN_URL" "$XCODEGEN_SHA256"
+}
diff --git a/libs/cua/crates/cua-vmm/recipe/macos-tier-xcode.sh b/libs/cua/crates/cua-vmm/recipe/macos-tier-xcode.sh
new file mode 100755
index 0000000000..ccd038a2de
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/recipe/macos-tier-xcode.sh
@@ -0,0 +1,185 @@
+#!/bin/bash
+# The xcode tier (the macOS Space with developer tools): full plus Xcode, its
+# iOS simulator runtime, the Metal toolchain and the Apple developer tools
+# below. Runs IN the guest as the desktop user, on a clone of the full VM
+# that already passed the doctor.
+#
+# tier-xcode.sh STAGE_DIR
+#
+# The Xcode comes from the first of:
+# STAGE/cache/$XCODE_XIP the pinned archive of CI's runner (build.sh); its
+# SHA-1 is checked here and the build must be
+# $XCODE_BUILD
+# STAGE/xcode/*.zip|*.app an Xcode already installed on the host Mac (a ditto
+# zip); with STAGE/xcode/pinned (build.sh, the pinned
+# build) the pin checks apply, else any Xcode is taken
+# STAGE/xcode/*.xip an archive the user downloaded (derive-local.sh);
+# xip checks Apple's signature while it expands
+# and lands at /Applications/Xcode_<version>.app, selected, licensed and
+# first-launched. No sign-in is involved: the Xcode is one that is already on
+# the Mac (or runner) building the image.
+#
+# Installs, all pinned in versions.env:
+# Xcode, Metal toolchain, iOS simulator runtime Apple (no sign-in)
+# Rust targets $RUST_IOS_TARGETS rustup
+# sccache, XcodeGen /usr/local/bin (release archives)
+# CocoaPods Homebrew bottle (checked)
+# developer mode, SwiftPM macro/plugin prompts off, one warmed Simulator device
+set -euo pipefail
+STAGE="${1:?staging directory}"
+# shellcheck source=/dev/null # STAGE/versions.env, a copy of ../versions.env
+. "$STAGE/versions.env"
+C="$STAGE/cache"
+# The password on a here-string, not a pipe: with sudo's credential cache
+# warm, sudo never reads it, and a printf pipe then dies of SIGPIPE, which
+# pipefail turns into a failed step.
+sudo_run() { sudo -S -p '' "$@" <<<"${CUA_SUDO_PW:-lume}"; }
+say() { echo "==> $*"; }
+verified() { # URL SHA256 -> the cached file, checked
+ local f; f="$C/$(basename "$1")"
+ [ "$(shasum -a 256 "$f" | cut -d' ' -f1)" = "$2" ] || { echo "checksum mismatch: $f" >&2; exit 1; }
+ echo "$f"
+}
+W="$(mktemp -d /tmp/cua-build-xcode.XXXXXX)"
+trap 'rm -rf "$W"' EXIT
+export PATH="$HOME/.cargo/bin:/usr/local/bin:$PATH"
+
+# --- Xcode -------------------------------------------------------------------
+src="" pinned=0
+if [ -f "$C/$XCODE_XIP" ]; then
+ say "checking $XCODE_XIP"
+ [ "$(shasum -a 1 "$C/$XCODE_XIP" | cut -d' ' -f1)" = "$XCODE_XIP_SHA1" ] ||
+ { echo "checksum mismatch: $C/$XCODE_XIP" >&2; exit 1; }
+ src="$C/$XCODE_XIP" pinned=1
+else
+ # An Xcode build.sh staged from the runner's own installed Xcode (the same
+ # pinned build): the pin checks apply to it too.
+ [ ! -e "$STAGE/xcode/pinned" ] || pinned=1
+ for f in "$STAGE"/xcode/*.zip "$STAGE"/xcode/*.app "$STAGE"/xcode/*.xip; do
+ [ -e "$f" ] && { src="$f"; break; }
+ done
+fi
+[ -n "$src" ] || { echo "no Xcode to install: expected $C/$XCODE_XIP or an Xcode.app or .xip in $STAGE/xcode" >&2; exit 1; }
+
+case "$src" in
+ *.xip)
+ say "expanding $(basename "$src") (xip checks Apple's signature)"
+ (cd "$W" && xip --expand "$src" >/dev/null)
+ app="$(ls -d "$W"/Xcode*.app | head -1)"
+ version="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$app/Contents/Info.plist")"
+ APP="/Applications/Xcode_${version}.app"
+ sudo_run rm -rf "$APP"
+ sudo_run mv "$app" "$APP" ;;
+ *.zip)
+ # The host's own Xcode, archived by ditto (links, signature, xattrs kept).
+ say "extracting $(basename "$src")"
+ sudo_run ditto -x -k "$src" "$W"
+ app="$(ls -d "$W"/Xcode*.app | head -1)"
+ version="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$app/Contents/Info.plist")"
+ APP="/Applications/Xcode_${version}.app"
+ sudo_run rm -rf "$APP"
+ sudo_run mv "$app" "$APP" ;;
+ *)
+ # A bundle copy straight into place: ditto keeps the code signature,
+ # links and xattrs, and the source is only read.
+ version="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$src/Contents/Info.plist")"
+ APP="/Applications/Xcode_${version}.app"
+ say "copying $(basename "$src") to $APP"
+ sudo_run rm -rf "$APP"
+ sudo_run ditto "$src" "$APP" ;;
+esac
+say "Xcode $version at $APP"
+codesign --verify --deep --strict "$APP" 2>&1 | head -3 || true
+sudo_run xcode-select --switch "$APP/Contents/Developer"
+sudo_run xcodebuild -license accept
+sudo_run xcodebuild -runFirstLaunch
+build="$(xcodebuild -version | sed -n 's/^Build version //p')"
+if [ "$pinned" = 1 ] && [ "$build" != "$XCODE_BUILD" ]; then
+ echo "Xcode build is $build, not $XCODE_BUILD" >&2; exit 1
+fi
+echo " Xcode $version ($build)"
+
+# --- simulator runtime and Metal toolchain --------------------------------------
+# Disk first: the runtime is several GB and the build volume is the guest's.
+free_gb="$(df -g / | awk 'NR==2 {print $4}')"
+[ "${free_gb:-0}" -ge 20 ] || { echo "the guest has ${free_gb} GB free; the iOS runtime needs about 20" >&2; exit 1; }
+if [ "$pinned" = 1 ]; then
+ say "iOS $XCODE_IOS_RUNTIME simulator runtime and Metal toolchain"
+ xcodebuild -downloadPlatform iOS -buildVersion "$XCODE_IOS_RUNTIME"
+else
+ say "iOS simulator runtime of Xcode $version and Metal toolchain"
+ xcodebuild -downloadPlatform iOS
+fi
+xcodebuild -downloadComponent MetalToolchain
+# The first boot of a new runtime builds its dyld shared cache; do it now so
+# the first `simctl boot` in a Space is not minutes long.
+xcrun simctl runtime dyld_shared_cache update --all >/dev/null 2>&1 || true
+xcrun simctl delete unavailable || true
+
+# --- developer tools ---------------------------------------------------------------
+say "Rust targets: $RUST_IOS_TARGETS"
+# shellcheck disable=SC2086 # a list
+"$HOME/.cargo/bin/rustup" target add $RUST_IOS_TARGETS
+rm -rf "$HOME/.rustup/downloads" "$HOME/.rustup/tmp"
+
+say "sccache $SCCACHE_VERSION, XcodeGen $XCODEGEN_VERSION"
+f="$(verified "$SCCACHE_URL" "$SCCACHE_SHA256")"; tar -xzf "$f" -C "$W"
+sudo_run install -m 0755 "$W"/sccache-*/sccache /usr/local/bin/sccache
+f="$(verified "$XCODEGEN_URL" "$XCODEGEN_SHA256")"; ditto -x -k "$f" "$W/xcodegen"
+sudo_run rm -rf /usr/local/lib/xcodegen
+sudo_run mkdir -p /usr/local/lib/xcodegen
+sudo_run ditto "$W/xcodegen/xcodegen" /usr/local/lib/xcodegen
+# A wrapper, not a link: XcodeGen finds its setting presets (share/) relative to
+# the path it was started by, and a link in /usr/local/bin has none.
+printf '#!/bin/sh\nexec /usr/local/lib/xcodegen/bin/xcodegen "$@"\n' >"$W/xcodegen-wrapper"
+sudo_run install -m 0755 "$W/xcodegen-wrapper" /usr/local/bin/xcodegen
+
+say "CocoaPods $COCOAPODS_VERSION"
+HOMEBREW_NO_AUTO_UPDATE=1 HOMEBREW_NO_ANALYTICS=1 HOMEBREW_NO_ENV_HINTS=1 /opt/homebrew/bin/brew install cocoapods
+got="$(LANG=en_US.UTF-8 /opt/homebrew/bin/pod --version)"
+[ "$got" = "$COCOAPODS_VERSION" ] || { echo "CocoaPods is $got, not $COCOAPODS_VERSION: Homebrew's formula moved; update versions.env" >&2; exit 1; }
+sudo_run ln -sfn /opt/homebrew/bin/pod /usr/local/bin/pod
+# CocoaPods insists on a UTF-8 locale.
+grep -q 'LANG=en_US.UTF-8' "$HOME/.zprofile" 2>/dev/null || printf 'export LANG=en_US.UTF-8\n' >>"$HOME/.zprofile"
+/opt/homebrew/bin/brew cleanup -s >/dev/null 2>&1 || true
+rm -rf "$HOME/Library/Caches/Homebrew"
+
+say "developer mode"
+# No debugger or Instruments authorization prompts for the agent's account,
+# and no SwiftPM macro or build-plugin trust dialogs (the agent cannot click
+# through a trust prompt in a headless build).
+sudo_run DevToolsSecurity -enable
+sudo_run dseditgroup -o edit -a "$(id -un)" -t user _developer
+defaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YES
+defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES
+defaults write com.apple.dt.Xcode IDEPackageSupportDisableManifestSandbox -bool YES
+
+say "Simulator device"
+runtime="$(xcrun simctl list runtimes -j | python3 -c '
+import json, sys
+rs = [r for r in json.load(sys.stdin)["runtimes"] if r.get("isAvailable") and r["identifier"].split(".")[-1].startswith("iOS")]
+print(rs[-1]["identifier"] if rs else "")')"
+[ -n "$runtime" ] || { echo "no iOS simulator runtime is available" >&2; exit 1; }
+devtype="$(xcrun simctl list devicetypes -j | python3 -c '
+import json, sys
+t = [d["identifier"] for d in json.load(sys.stdin)["devicetypes"] if "iPhone" in d["name"] and "Pro" in d["name"] and "Max" not in d["name"]]
+print(t[-1] if t else "")')"
+[ -n "$devtype" ] || devtype="$(xcrun simctl list devicetypes | sed -n 's/.*(\(com.apple.CoreSimulator.SimDeviceType.iPhone[^)]*\)).*/\1/p' | tail -1)"
+xcrun simctl delete "$SIMULATOR_DEVICE_NAME" >/dev/null 2>&1 || true
+udid="$(xcrun simctl create "$SIMULATOR_DEVICE_NAME" "$devtype" "$runtime")"
+echo " $SIMULATOR_DEVICE_NAME $udid ($runtime)"
+# Boot it once and shut it down: the first boot builds the runtime's caches.
+xcrun simctl boot "$udid" || true
+xcrun simctl bootstatus "$udid" -b || true
+xcrun simctl shutdown "$udid" || true
+
+say "runtimes"
+xcrun simctl list runtimes
+rm -rf "$HOME/Library/Caches/com.apple.dt.Xcode" "$HOME/Library/Developer/Xcode/DerivedData" "$HOME/Library/Caches/CocoaPods"
+rm -rf "$HOME/Library/Developer/CoreSimulator/Caches" 2>/dev/null || true
+
+say "versions"
+xcodebuild -version | head -2
+"$HOME/.cargo/bin/rustup" target list --installed
+/usr/local/bin/sccache --version; /usr/local/bin/xcodegen --version; pod --version 2>/dev/null || /usr/local/bin/pod --version
+echo "xcode tier installed"
diff --git a/libs/cua/crates/cua-vmm/recipe/macos-versions.env b/libs/cua/crates/cua-vmm/recipe/macos-versions.env
new file mode 100644
index 0000000000..1e119f2730
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/recipe/macos-versions.env
@@ -0,0 +1,92 @@
+# Pinned inputs of the macOS tiers (build.sh --tier, tiers.sh). One place:
+# a monthly rebuild changes nothing unless this file changes. Every download
+# is checked against its sha256 on the host before it is shared into the
+# guest, and again in the guest before it is installed. image.json's tier
+# claims (`expect`) must name the same versions (build.sh checks).
+# Sourced by bash; KEY=value only.
+
+# --- slim ---------------------------------------------------------------------
+# The Lume base the slim tier starts from: a digest-stable pin (the first
+# cua-spacesd macOS 26 image, macOS 26.5.2 25F84, SIP off, autologin lume).
+# Never a floating tag: `26` becomes the full tier.
+# (Repository and tag apart: the pin is not a catalog entry.)
+MACOS_BASE_REPO=ghcr.io/trycua/macos
+MACOS_BASE_TAG=26-20260925-3262e04
+MACOS_BASE_DIGEST=sha256:b03ff1154dc80a7dadef5397eaca395c1e6cb64093a29bd53ca5916127816a8e
+# Google Chrome (Omaha "release2" URL: a versioned, immutable download).
+CHROME_VERSION=154.0.8037.58
+CHROME_URL=https://dl.google.com/release2/chrome/esexjcwror2yyct27xsikjz3bq_154.0.8037.58/GoogleChrome-154.0.8037.58.dmg
+CHROME_SHA256=2df467b9bbf5fa93e2a3b59b79906a8ebd9e3677d1b61857f6c9d99e62eacb43
+
+# --- full ---------------------------------------------------------------------
+# Xcode Command Line Tools: installed through softwareupdate when the guest's
+# CLTools_Executables is not already this version.
+CLT_VERSION=26.6
+CLT_LABEL="Command Line Tools for Xcode 26.6-26.6"
+# Homebrew: git clone of this tag, checked out at exactly this commit.
+HOMEBREW_TAG=7.0.6
+HOMEBREW_COMMIT=570982948a8a194f0f42f43f4a5bce2d1c9f64cb
+GH_VERSION=2.101.0
+GH_URL=https://github.com/cli/cli/releases/download/v2.101.0/gh_2.101.0_macOS_arm64.zip
+GH_SHA256=e4303e39d8f07141c4bad4b99b01079f05029c59b27076e8fbc825c985ecdd8b
+JQ_VERSION=1.8.2
+JQ_URL=https://github.com/jqlang/jq/releases/download/jq-1.8.2/jq-macos-arm64
+JQ_SHA256=2d75340ba57a4b4b4c8708a21c2dc8e958a48aaa8bba13b27f77f6e4c0eca07e
+RG_VERSION=15.2.0
+RG_URL=https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-aarch64-apple-darwin.tar.gz
+RG_SHA256=3750b2e93f37e0c692657da574d7019a101c0084da05a790c83fd335bad973e4
+# Node LTS (Krypton) and pnpm (npm tarball, installed from the verified file).
+NODE_VERSION=24.21.0
+NODE_URL=https://nodejs.org/dist/v24.21.0/node-v24.21.0-darwin-arm64.tar.gz
+NODE_SHA256=bed7eea5325e1108f32ce5228ddd6a5f0f08a499ee42aa7442aea583702f6057
+PNPM_VERSION=12.6.0
+PNPM_URL=https://registry.npmjs.org/pnpm/-/pnpm-12.6.0.tgz
+PNPM_SHA256=05b7b921fbb31564505c967eabf825895a1cc18f50935c00be98815272cc9d56
+UV_VERSION=0.12.19
+UV_URL=https://github.com/astral-sh/uv/releases/download/0.12.19/uv-aarch64-apple-darwin.tar.gz
+UV_SHA256=a9a8df1eedeb192f2e47e40e2faabfb387db4b850209118786d42f89dde3e0ba
+# rustup-init, then this exact stable toolchain (minimal profile).
+RUSTUP_VERSION=1.29.1
+RUSTUP_URL=https://static.rust-lang.org/rustup/archive/1.29.1/aarch64-apple-darwin/rustup-init
+RUSTUP_SHA256=ec1b9233e7f72990ecd8e62063fa7f6c3dfc2bec8e97f88bff165f9100ac696a
+RUST_VERSION=1.98.1
+GO_VERSION=1.27.1
+GO_URL=https://go.dev/dl/go1.27.1.darwin-arm64.tar.gz
+GO_SHA256=ee215d57e0ec269c60cc9ceca68e6bda321ba9ee5afe24f4b0988703c2d87d12
+
+# --- xcode --------------------------------------------------------------------
+# The macOS Space with developer tools. Xcode and the Simulator runtimes are
+# Apple software under Apple's license, for use on Apple-branded hardware (the
+# image carries a notice, annotate.sh). CI needs no sign-in: it uses the pinned
+# Xcode already on the runner, the pinned .xip in CUA_XCODE_CACHE (default
+# ~/XcodesCache) when there is one, or the Xcode.app installed there. Apple and
+# xcodereleases.com publish SHA-1 for the archive; xip also checks Apple's
+# signature on expand.
+# XCODE_* below is the version CI builds, gates and publishes the tier with
+# (build.sh --tier xcode needs exactly that Xcode on the runner). Users pull
+# the published tier; a Mac that builds it locally instead (derive-local.sh) may
+# use any Xcode its guest macOS supports.
+XCODE_VERSION=26.6
+XCODE_BUILD=17F113
+XCODE_XIP=Xcode_26.6_Apple_silicon.xip
+XCODE_XIP_SHA1=02ce6fccf6c46c12cbef005fbd48f9eaf7489912
+# The iOS simulator runtime of that Xcode (xcodebuild -downloadPlatform iOS,
+# from Apple's CDN, no sign-in), the only runtime the tier claims
+# (image.json simulator_runtimes).
+XCODE_IOS_RUNTIME=26.5
+# Rust targets for iOS (rustup, on the full tier's pinned toolchain).
+RUST_IOS_TARGETS="aarch64-apple-ios aarch64-apple-ios-sim"
+SCCACHE_VERSION=0.19.0
+SCCACHE_URL=https://github.com/mozilla/sccache/releases/download/v0.19.0/sccache-v0.19.0-aarch64-apple-darwin.tar.gz
+SCCACHE_SHA256=a35a0b7d622618774bc1bb8102d72562dfb21e619f88b153b370d7f89bc286af
+XCODEGEN_VERSION=2.46.0
+XCODEGEN_URL=https://github.com/yonaskolb/XcodeGen/releases/download/2.46.0/xcodegen.zip
+XCODEGEN_SHA256=4d9e34b62172d645eed6457cac13fc222569974098ef4ee9c3368bedf0196806
+# CocoaPods from Homebrew's bottle (the system Ruby is 2.6, which CocoaPods
+# 1.17 and its gems cannot install on: measured in a real guest). Brew checks
+# the bottle's checksum; the tier fails unless `pod --version` is this exact
+# version, so a moved formula is a visible change, not a silent one.
+COCOAPODS_VERSION=1.17.0
+# The Simulator device the tier creates and warms (first boot of a runtime
+# builds its caches). Looked up by name in the runtime's device types.
+SIMULATOR_DEVICE_NAME="Cua iPhone"
diff --git a/libs/cua/crates/cua-vmm/recipe/macos-xcode-source.sh b/libs/cua/crates/cua-vmm/recipe/macos-xcode-source.sh
new file mode 100644
index 0000000000..ee6a20c7e8
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/recipe/macos-xcode-source.sh
@@ -0,0 +1,38 @@
+# shellcheck shell=bash
+# Sourced by build.sh and derive-local.sh: find an Xcode on this Mac and stage
+# it for the guest. Needs no Apple credentials: it only uses an Xcode that is
+# already here (installed, or an .xip somebody downloaded).
+# XCODE an explicit Xcode.app or .xip (optional)
+plist() { /usr/libexec/PlistBuddy -c "Print :$2" "$1/Contents/Info.plist" 2>/dev/null; }
+
+# find_xcode prints the Xcode to use: $XCODE, $CUA_XCODE_APP, the one xcode-select
+# names, else the newest /Applications/Xcode*.app, else an Xcode*.xip in
+# $CUA_XCODE_CACHE (default ~/XcodesCache) or ~/Downloads. Fails when none.
+find_xcode() {
+ local c best="" bestv="" v sel
+ if [ -n "${XCODE:-}" ]; then echo "$XCODE"; return 0; fi
+ if [ -n "${CUA_XCODE_APP:-}" ]; then echo "$CUA_XCODE_APP"; return 0; fi
+ sel="$(xcode-select -p 2>/dev/null || true)"
+ case "$sel" in */Xcode*.app/Contents/Developer) c="${sel%/Contents/Developer}"; [ -d "$c" ] && { echo "$c"; return 0; } ;; esac
+ for c in /Applications/Xcode*.app; do
+ [ -d "$c" ] || continue
+ v="$(plist "$c" CFBundleShortVersionString || true)"; [ -n "$v" ] || continue
+ if [ -z "$best" ] || [ "$(printf '%s\n%s\n' "$bestv" "$v" | sort -V | tail -1)" = "$v" ]; then best="$c" bestv="$v"; fi
+ done
+ [ -z "$best" ] || { echo "$best"; return 0; }
+ for c in "${CUA_XCODE_CACHE:-$HOME/XcodesCache}"/Xcode*.xip "$HOME"/Downloads/Xcode*.xip; do
+ [ -f "$c" ] && { echo "$c"; return 0; }
+ done
+ return 1
+}
+
+# stage_xcode SRC DIR puts the Xcode into DIR as one file the guest can read
+# over the share. The guest's virtiofs cannot follow an app bundle's framework
+# links, but a zip keeps them, the signatures and the extended attributes; an
+# .xip goes in as it is.
+stage_xcode() {
+ case "$1" in
+ *.app) ditto -c -k --sequesterRsrc --keepParent "$1" "$2/$(basename "$1").zip" ;;
+ *) cp -c "$1" "$2/" 2>/dev/null || cp "$1" "$2/" ;;
+ esac
+}
diff --git a/libs/cua/crates/cua-vmm/src/conformance.rs b/libs/cua/crates/cua-vmm/src/conformance.rs
new file mode 100644
index 0000000000..530f40d16d
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/src/conformance.rs
@@ -0,0 +1,666 @@
+//! Runtime conformance: what every runtime owes a Space, written once.
+//!
+//! A Space behaves the same on every runtime and kind (gVisor and runc in
+//! the built-in Linux runtime or on a Linux engine, Apple's Containerization
+//! and Cua's own microVM monitor on a Mac, Firecracker, QEMU, Lume, and the
+//! machines of a pool): the same network policy, DNS and egress, registry
+//! credentials, child Spaces from a home, downloads from the guest, and
+//! readiness. This module is the registry of those promises:
+//!
+//! * [`Case`] lists them. The same list runs against every [`Entry`]: the
+//! hermetic tests run it on the backends that have a fake (Apple's
+//! `container` has one), and `libs/cua/scripts/conformance/run.py` runs
+//! it live on the runtimes this computer has (opt in; it cleans up what it
+//! makes), writing the matrix.
+//! * [`capabilities`] is what a backend says about itself, and nothing
+//! else: the guests and architectures it runs, whether it can pause,
+//! checkpoint and fork, whether it needs KVM or nested virtualization,
+//! and what it does with the secure default network. What a backend does
+//! not offer it refuses at once with a plain reason ([`Expect::Refused`]),
+//! never late. The network answer is derived from
+//! [`crate::network::network_support`], so the two cannot disagree.
+//! * [`entries`] is the roster of runtimes under test. A drift guard
+//! (`every_backend_has_a_conformance_entry`) fails the build when a
+//! backend is added without one, and [`entries_json`] is what the live
+//! driver reads (a test keeps the committed file in step).
+//!
+//! The shared layers that make the cases pass the same way everywhere are
+//! not here: the secure-default policy compiler and its enforcement points
+//! ([`crate::network`], the container engine's nftables),
+//! the registry credential chain and layer cache (`cua-image`, reached
+//! through [`crate::RootfsResolver`]), the child-Space channel the host
+//! opens into the guest's `cua-spacesd` (`cua-daemon`'s children bridge: it
+//! dials the guest, so it needs nothing from a runtime but an address), and
+//! the readiness probes ([`crate::probe`]). A runtime supplies only how the
+//! guest is reached.
+
+use serde_json::{Value, json};
+
+use crate::network::{self, NetworkSupport, Placement};
+use crate::types::BackendKind;
+
+/// A promise every runtime keeps, or refuses up front.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Case {
+ /// The secure default network holds: the internet answers; the host,
+ /// the local network, cloud metadata and other trees' Spaces do not.
+ Policy,
+ /// Names resolve in the guest, for both address families.
+ Dns,
+ /// The guest downloads a large package from the internet (the coding
+ /// app's package).
+ Download,
+ /// A private image is pulled with the registry credential the daemon
+ /// holds, and no credential is written outside the Cua home.
+ Registry,
+ /// A home creates, lists, uses and deletes a child Space through the
+ /// daemon's authenticated channel, within its budget, and it is
+ /// audited.
+ Children,
+ /// A coding agent session starts in the guest (the app installs, the
+ /// scripted model answers).
+ Agent,
+ /// Time from the create call to a Space that answers is measured.
+ Ready,
+ /// Stop, resume, and what the backend declares (pause, checkpoint,
+ /// fork) work; what it does not declare is refused in plain words.
+ Lifecycle,
+ /// Deleting leaves nothing: no Space, no process, no container, no
+ /// network.
+ Teardown,
+}
+
+impl Case {
+ /// Every case, in the order the live run takes them.
+ pub const ALL: [Case; 9] = [
+ Case::Ready,
+ Case::Policy,
+ Case::Dns,
+ Case::Download,
+ Case::Registry,
+ Case::Children,
+ Case::Agent,
+ Case::Lifecycle,
+ Case::Teardown,
+ ];
+
+ /// The word the matrix and the driver use.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Case::Policy => "policy",
+ Case::Dns => "dns",
+ Case::Download => "download",
+ Case::Registry => "registry",
+ Case::Children => "children",
+ Case::Agent => "agent",
+ Case::Ready => "ready",
+ Case::Lifecycle => "lifecycle",
+ Case::Teardown => "teardown",
+ }
+ }
+
+ /// What it checks, in a sentence.
+ pub fn what(self) -> &'static str {
+ match self {
+ Case::Policy => {
+ "the default network holds: internet yes; host, LAN, cloud metadata, other trees no"
+ }
+ Case::Dns => "names resolve in the guest, IPv4 and IPv6",
+ Case::Download => "the guest downloads the coding app's package",
+ Case::Registry => "a private image is pulled with the host-held registry credential",
+ Case::Children => "a home creates, lists, uses and deletes a child Space, audited",
+ Case::Agent => "a coding agent session starts and answers",
+ Case::Ready => "time from create to a Space that answers",
+ Case::Lifecycle => "stop and resume, and the declared pause, checkpoint and fork",
+ Case::Teardown => "delete leaves no Space, process, container or network",
+ }
+ }
+}
+
+/// What a runtime does with a [`Case`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Expect {
+ /// It passes.
+ Pass,
+ /// It is refused at once, saying this (plain words, what to do
+ /// instead). A refusal that comes late, or says something else, fails
+ /// the case.
+ Refused(&'static str),
+}
+
+impl Expect {
+ /// `pass` or `refused`.
+ pub fn word(self) -> &'static str {
+ match self {
+ Expect::Pass => "pass",
+ Expect::Refused(_) => "refused",
+ }
+ }
+}
+
+/// What a backend declares about itself.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Capabilities {
+ /// Guest operating systems it runs.
+ pub guests: &'static [&'static str],
+ /// Guest architectures it runs natively on an Apple silicon or
+ /// arm64 host, and (after a slash) on an x86-64 host's own.
+ pub archs: &'static [&'static str],
+ /// A running guest can be paused in memory.
+ pub pause: bool,
+ /// A running guest can be checkpointed (memory and disk).
+ pub checkpoint: bool,
+ /// A checkpoint can be forked into new Spaces.
+ pub fork: bool,
+ /// It needs a usable `/dev/kvm`.
+ pub kvm: bool,
+ /// It runs where the host is itself a VM (nested virtualization
+ /// needed): only a backend that boots a guest kernel and cannot fall
+ /// back says `true`.
+ pub nested_virt: bool,
+ /// Guests the host cannot reach by address need the runtime's own
+ /// forward (`true`), else the guest is dialed at its own address.
+ pub forwarded: bool,
+}
+
+/// What `backend` declares. No wildcard: a new backend does not build
+/// until it says.
+pub fn capabilities(backend: BackendKind) -> Capabilities {
+ match backend {
+ // gVisor or runc in a container engine: pause with the engine,
+ // checkpoint and fork as gVisor and the engine allow.
+ BackendKind::Container | BackendKind::Managed => Capabilities {
+ guests: &["linux"],
+ archs: &["aarch64", "x86_64"],
+ pause: true,
+ checkpoint: true,
+ fork: true,
+ kvm: false,
+ nested_virt: false,
+ forwarded: true,
+ },
+ BackendKind::Qemu => Capabilities {
+ guests: &["linux", "windows", "android", "macos"],
+ archs: &["aarch64", "x86_64"],
+ pause: true,
+ checkpoint: true,
+ fork: true,
+ kvm: false,
+ nested_virt: false,
+ forwarded: true,
+ },
+ BackendKind::QemuDocker => Capabilities {
+ guests: &[],
+ archs: &[],
+ pause: false,
+ checkpoint: false,
+ fork: false,
+ kvm: false,
+ nested_virt: false,
+ forwarded: true,
+ },
+ BackendKind::Lume => Capabilities {
+ guests: &["macos"],
+ archs: &["aarch64"],
+ pause: false,
+ checkpoint: false,
+ fork: true,
+ kvm: false,
+ nested_virt: false,
+ forwarded: false,
+ },
+ BackendKind::Firecracker => Capabilities {
+ guests: &["linux"],
+ archs: &["aarch64", "x86_64"],
+ pause: true,
+ checkpoint: true,
+ fork: true,
+ kvm: true,
+ nested_virt: true,
+ forwarded: false,
+ },
+ // Apple's runtime helper owns the VM: no pause, no snapshots.
+ BackendKind::Containerization => Capabilities {
+ guests: &["linux"],
+ archs: &["aarch64", "x86_64"],
+ pause: false,
+ checkpoint: false,
+ fork: false,
+ kvm: false,
+ nested_virt: false,
+ forwarded: false,
+ },
+ BackendKind::Vz => Capabilities {
+ guests: &["linux"],
+ archs: &["aarch64"],
+ pause: true,
+ checkpoint: true,
+ fork: true,
+ kvm: false,
+ nested_virt: false,
+ forwarded: false,
+ },
+ }
+}
+
+/// One runtime under test: the words that select it (`--kind`,
+/// `--runtime`), the backend that runs it, the hosts it runs on, and what a
+/// live run needs.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Entry {
+ /// The row of the matrix.
+ pub id: &'static str,
+ /// The backend that runs it.
+ pub backend: BackendKind,
+ /// `--kind` (`container`, `vm`, `microvm`).
+ pub kind: &'static str,
+ /// `--runtime` (`gvisor`, `runc`, `vz`, `containerization`, ...).
+ pub runtime: &'static str,
+ /// Host operating systems it runs on (`linux`, `macos`, `windows`).
+ pub hosts: &'static [&'static str],
+ /// The guest the cases run in.
+ pub guest: &'static str,
+ /// What must be installed for a live run, in a sentence.
+ pub needs: &'static str,
+ /// The cases a live run takes (a macOS guest has no coding agent).
+ pub cases: &'static [Case],
+ /// Why a live run is impossible, when it is (no runtime of this build
+ /// starts it): the entry is kept so a new backend cannot hide.
+ pub not_runnable: Option<&'static str>,
+}
+
+const LINUX_CASES: &[Case] = &Case::ALL;
+const VM_CASES: &[Case] = &[
+ Case::Ready,
+ Case::Policy,
+ Case::Dns,
+ Case::Download,
+ Case::Lifecycle,
+ Case::Teardown,
+];
+
+/// The roster: every backend at least once.
+pub fn entries() -> &'static [Entry] {
+ const E: &[Entry] = &[
+ Entry {
+ id: "builtin-gvisor",
+ backend: BackendKind::Managed,
+ kind: "container",
+ runtime: "gvisor",
+ hosts: &["macos", "windows"],
+ guest: "linux",
+ needs: "the built-in Linux runtime (downloaded on first use)",
+ cases: LINUX_CASES,
+ not_runnable: None,
+ },
+ Entry {
+ id: "builtin-runc",
+ backend: BackendKind::Managed,
+ kind: "container",
+ runtime: "runc",
+ hosts: &["macos", "windows"],
+ guest: "linux",
+ needs: "the built-in Linux runtime (downloaded on first use)",
+ cases: LINUX_CASES,
+ not_runnable: None,
+ },
+ Entry {
+ id: "engine-gvisor",
+ backend: BackendKind::Container,
+ kind: "container",
+ runtime: "gvisor",
+ hosts: &["linux"],
+ guest: "linux",
+ needs: "Docker or containerd with gVisor (runsc) and nftables",
+ cases: LINUX_CASES,
+ not_runnable: None,
+ },
+ Entry {
+ id: "engine-runc",
+ backend: BackendKind::Container,
+ kind: "container",
+ runtime: "runc",
+ hosts: &["linux"],
+ guest: "linux",
+ needs: "Docker or containerd and nftables",
+ cases: LINUX_CASES,
+ not_runnable: None,
+ },
+ Entry {
+ id: "firecracker-microvm",
+ backend: BackendKind::Firecracker,
+ kind: "microvm",
+ runtime: "firecracker",
+ hosts: &["linux"],
+ guest: "linux",
+ needs: "Linux with /dev/kvm and Firecracker",
+ cases: LINUX_CASES,
+ not_runnable: None,
+ },
+ Entry {
+ id: "vz-microvm",
+ backend: BackendKind::Vz,
+ kind: "microvm",
+ runtime: "vz",
+ hosts: &["macos"],
+ guest: "linux",
+ needs: "an Apple silicon Mac with cua-vz and cua-microvm-init next to `cua`",
+ cases: LINUX_CASES,
+ not_runnable: None,
+ },
+ Entry {
+ id: "containerization-microvm",
+ backend: BackendKind::Containerization,
+ kind: "microvm",
+ runtime: "containerization",
+ hosts: &["macos"],
+ guest: "linux",
+ needs: "macOS 26 on Apple silicon (Cua installs Apple's container itself)",
+ cases: LINUX_CASES,
+ not_runnable: None,
+ },
+ Entry {
+ id: "qemu-vm",
+ backend: BackendKind::Qemu,
+ kind: "vm",
+ runtime: "qemu",
+ hosts: &["linux", "macos", "windows"],
+ guest: "linux",
+ needs: "qemu-system and a Linux VM image (a containerDisk)",
+ cases: VM_CASES,
+ not_runnable: None,
+ },
+ Entry {
+ id: "lume-macos-vm",
+ backend: BackendKind::Lume,
+ kind: "vm",
+ runtime: "lume",
+ hosts: &["macos"],
+ guest: "macos",
+ needs: "an Apple silicon Mac with Lume and a macOS image",
+ cases: VM_CASES,
+ not_runnable: None,
+ },
+ Entry {
+ id: "qemu-docker",
+ backend: BackendKind::QemuDocker,
+ kind: "vm",
+ runtime: "",
+ hosts: &[],
+ guest: "linux",
+ needs: "nothing: no runtime of this build starts QEMU inside a container",
+ cases: &[],
+ not_runnable: Some("no runtime of this build starts QEMU inside a container"),
+ },
+ ];
+ E
+}
+
+/// The entry with this id.
+pub fn entry(id: &str) -> Option<&'static Entry> {
+ entries().iter().find(|e| e.id == id)
+}
+
+/// What the secure default network does with `backend` on host `os`, as a
+/// [`Case::Policy`] expectation: [`Expect::Pass`] when the host enforces the
+/// rules, else the reason it is refused (or runs without network).
+pub fn policy_expectation(backend: BackendKind, os: &str) -> Expect {
+ match network::network_support(backend, os, Placement::Local) {
+ NetworkSupport::Enforced { .. } => Expect::Pass,
+ NetworkSupport::NoNetworkOnly { why } | NetworkSupport::Refuse { why } => {
+ Expect::Refused(why)
+ }
+ }
+}
+
+/// What `entry` is expected to do with `case` on host `os`.
+pub fn expect(entry: &Entry, case: Case, os: &str) -> Expect {
+ if !entry.cases.contains(&case) {
+ return Expect::Refused("not applicable to this guest");
+ }
+ match case {
+ Case::Policy => policy_expectation(entry.backend, os),
+ _ => Expect::Pass,
+ }
+}
+
+/// The roster as JSON for the live driver (`scripts/conformance/run.py`),
+/// with what each entry expects on each host OS. A test keeps
+/// `scripts/conformance/entries.json` equal to this.
+pub fn entries_json() -> Value {
+ let rows: Vec<Value> = entries()
+ .iter()
+ .map(|e| {
+ let c = capabilities(e.backend);
+ let hosts: Vec<Value> = e
+ .hosts
+ .iter()
+ .map(|os| {
+ let cases: Vec<Value> = Case::ALL
+ .iter()
+ .map(|case| {
+ let x = expect(e, *case, os);
+ json!({
+ "case": case.as_str(),
+ "expect": x.word(),
+ "why": match x {
+ Expect::Refused(w) => Value::from(w),
+ Expect::Pass => Value::Null,
+ },
+ })
+ })
+ .collect();
+ json!({ "os": os, "cases": cases })
+ })
+ .collect();
+ json!({
+ "id": e.id,
+ "backend": e.backend.as_str(),
+ "kind": e.kind,
+ "runtime": e.runtime,
+ "guest": e.guest,
+ "needs": e.needs,
+ "not_runnable": e.not_runnable,
+ "capabilities": {
+ "guests": c.guests,
+ "archs": c.archs,
+ "pause": c.pause,
+ "checkpoint": c.checkpoint,
+ "fork": c.fork,
+ "kvm": c.kvm,
+ "nested_virt": c.nested_virt,
+ },
+ "hosts": hosts,
+ })
+ })
+ .collect();
+ json!({ "cases": Case::ALL.iter().map(|c| json!({"case": c.as_str(), "what": c.what()})).collect::<Vec<_>>(), "entries": rows })
+}
+
+/// The matrix of what each runtime promises, as a Markdown table (for the
+/// docs; a test keeps them in step).
+pub fn promises_table_markdown() -> String {
+ let mut out = String::from(
+ "| Runtime | Guest | Default network | Pause | Checkpoint and fork | KVM |\n|---|---|---|---|---|---|\n",
+ );
+ for e in entries().iter().filter(|e| e.not_runnable.is_none()) {
+ let c = capabilities(e.backend);
+ let net: Vec<String> = e
+ .hosts
+ .iter()
+ .map(|os| {
+ let x = match policy_expectation(e.backend, os) {
+ Expect::Pass => "enforced".to_string(),
+ Expect::Refused(_) => "refused".to_string(),
+ };
+ format!("{x} on {os}")
+ })
+ .collect();
+ let yes = |b: bool| if b { "yes" } else { "no" };
+ out.push_str(&format!(
+ "| `{}` | {} | {} | {} | {} | {} |\n",
+ e.id,
+ e.guest,
+ net.join(", "),
+ yes(c.pause),
+ yes(c.checkpoint && c.fork),
+ yes(c.kvm),
+ ));
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::egress::BACKENDS;
+ use std::collections::HashSet;
+
+ /// Adding a backend or a kind means registering it here: a runtime with
+ /// no conformance entry would be a runtime nobody checks.
+ #[test]
+ fn every_backend_has_a_conformance_entry() {
+ for b in BACKENDS {
+ assert!(
+ entries().iter().any(|e| e.backend == b),
+ "backend {b} has no conformance entry: add one to cua_vmm::conformance::entries()"
+ );
+ }
+ // And the other way: an entry names a backend the build knows.
+ for e in entries() {
+ assert!(
+ BACKENDS.contains(&e.backend),
+ "{}: backend {} is not in egress::BACKENDS",
+ e.id,
+ e.backend
+ );
+ }
+ }
+
+ #[test]
+ fn every_placement_word_is_covered() {
+ // Each `--kind` word a Space can be created with has an entry, and
+ // each runtime word of those kinds does too.
+ let kinds: HashSet<&str> = entries().iter().map(|e| e.kind).collect();
+ for k in ["container", "vm", "microvm"] {
+ assert!(kinds.contains(k), "--kind {k} has no conformance entry");
+ }
+ let runtimes: HashSet<&str> = entries().iter().map(|e| e.runtime).collect();
+ for r in [
+ "gvisor",
+ "runc",
+ "qemu",
+ "lume",
+ "firecracker",
+ "vz",
+ "containerization",
+ ] {
+ assert!(
+ runtimes.contains(r),
+ "--runtime {r} has no conformance entry"
+ );
+ }
+ }
+
+ #[test]
+ fn ids_are_unique_and_entries_are_well_formed() {
+ let mut seen = HashSet::new();
+ for e in entries() {
+ assert!(seen.insert(e.id), "duplicate id {}", e.id);
+ assert!(!e.needs.is_empty(), "{}: say what a live run needs", e.id);
+ let c = capabilities(e.backend);
+ if e.not_runnable.is_none() {
+ assert!(!e.hosts.is_empty(), "{}: no host", e.id);
+ assert!(
+ c.guests.contains(&e.guest),
+ "{}: its backend does not declare a {} guest",
+ e.id,
+ e.guest
+ );
+ assert!(!e.cases.is_empty(), "{}: no cases", e.id);
+ }
+ for case in e.cases {
+ assert!(Case::ALL.contains(case));
+ }
+ }
+ }
+
+ /// The declared capabilities cannot promise what the support table
+ /// refuses, and a refusal always says why in plain words.
+ #[test]
+ fn declared_policy_matches_the_support_table() {
+ for e in entries() {
+ for os in e.hosts {
+ let x = expect(e, Case::Policy, os);
+ let table = network::network_support(e.backend, os, Placement::Local);
+ match (x, table) {
+ (Expect::Pass, NetworkSupport::Enforced { .. }) => {}
+ (
+ Expect::Refused(w),
+ NetworkSupport::Refuse { why } | NetworkSupport::NoNetworkOnly { why },
+ ) => {
+ assert_eq!(w, why);
+ assert!(w.len() > 20, "{}: say why: {w:?}", e.id);
+ }
+ (Expect::Refused(w), _) if !e.cases.contains(&Case::Policy) => {
+ assert!(!w.is_empty())
+ }
+ other => panic!("{} on {os}: {other:?}", e.id),
+ }
+ }
+ }
+ }
+
+ /// A backend that cannot snapshot says so: pause, checkpoint and fork
+ /// are consistent (a fork needs a checkpoint to fork from).
+ #[test]
+ fn capabilities_are_consistent() {
+ for b in BACKENDS {
+ let c = capabilities(b);
+ if c.fork && !c.checkpoint {
+ // Lume forks by cloning its disk, with no checkpoint.
+ assert_eq!(b, BackendKind::Lume, "{b}: a fork needs a checkpoint");
+ }
+ if c.kvm {
+ assert!(
+ c.guests.contains(&"linux"),
+ "{b}: KVM is for Linux guests here"
+ );
+ }
+ }
+ // Apple's Containerization: the runtime helper owns the VM.
+ let a = capabilities(BackendKind::Containerization);
+ assert!(!a.pause && !a.checkpoint && !a.fork);
+ }
+
+ /// The roster the live driver reads is the one committed next to it.
+ #[test]
+ fn the_driver_reads_the_registry() {
+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../../scripts/conformance/entries.json");
+ let want = serde_json::to_string_pretty(&entries_json()).unwrap() + "\n";
+ if std::env::var_os("CUA_REGEN_CONFORMANCE").is_some() {
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(&path, &want).unwrap();
+ }
+ let have = std::fs::read_to_string(&path).unwrap_or_default();
+ assert_eq!(
+ have, want,
+ "scripts/conformance/entries.json is stale: run `CUA_REGEN_CONFORMANCE=1 cargo test -p cua-vmm conformance`"
+ );
+ }
+
+ /// The docs table is the generated one.
+ #[test]
+ fn the_docs_table_is_generated() {
+ let doc = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../../../../docs/content/docs/spaces/concepts/runtime-conformance.mdx");
+ let text = std::fs::read_to_string(&doc).unwrap_or_default();
+ let table = promises_table_markdown();
+ assert!(
+ text.contains(&table),
+ "{} is missing the generated table:\n{table}",
+ doc.display()
+ );
+ }
+}
diff --git a/libs/cua/crates/cua-vmm/src/container/egress.rs b/libs/cua/crates/cua-vmm/src/container/egress.rs
index 35f5875fdc..3f6a8c2727 100644
--- a/libs/cua/crates/cua-vmm/src/container/egress.rs
+++ b/libs/cua/crates/cua-vmm/src/container/egress.rs
@@ -21,6 +21,20 @@
//! The policy is kept per container under `~/.cua/docker/egress/<name>.json`:
//! every start applies it again (an engine or host restart drops the
//! rules), and forks inherit it.
+//!
+//! **Secure default** ([`crate::network`]). Unless `CUA_SECURE_DEFAULT=0`,
+//! every container is policed, policy or not: its network settings
+//! (`internet` when none were given; an old egress policy becomes `custom`)
+//! are compiled with what the engine host says (its resolvers, its own
+//! addresses, its host aliases, the tree's subnet and other trees'), and the
+//! rules always include the platform denies, `fib daddr type local` for
+//! the engine host's own addresses and the default denies. Every container
+//! runs without `CAP_NET_RAW`, with its own MAC and the anti-spoof rules,
+//! on a Docker network of its own tree (`cua-t-<12 hex>`, inter-container
+//! traffic on inside the tree): Spaces of other trees are on other bridges
+//! and blocked. DNS keeps working: Docker's embedded resolver on a
+//! user-defined network forwards to the engine host's resolvers, and those
+//! are allowed on port 53.
use std::net::Ipv4Addr;
use std::path::PathBuf;
@@ -29,9 +43,12 @@ use std::time::Duration;
use serde::{Deserialize, Serialize};
use super::{ContainerRuntime, engine_err};
-use crate::egress::{self, BridgePort, EgressPolicy, EngineTarget};
+use crate::egress::{self, BridgePort, EgressPolicy, EngineTarget, Net};
use crate::error::{Result, VmmError};
use crate::host;
+use crate::network::{Mode, NetworkContext, NetworkSettings};
+use sha2::{Digest, Sha256};
+use std::net::IpAddr;
/// On a container: the MAC address it was created with.
pub const LABEL_MAC: &str = "ai.cua.mac";
@@ -39,6 +56,18 @@ pub const LABEL_MAC: &str = "ai.cua.mac";
/// The Docker network a container joins when it names none.
const DEFAULT_NETWORK: &str = "bridge";
+/// On a tree's Docker network: the tree it is for.
+pub const LABEL_TREE: &str = "ai.cua.tree";
+
+/// The name prefix of a tree's Docker network.
+pub const TREE_NETWORK_PREFIX: &str = "cua-t-";
+
+/// Host aliases of Docker Desktop's VM (`host.docker.internal`, the
+/// gateway), blocked when the engine host is on its network.
+const DESKTOP_ALIASES: [&str; 3] = ["192.168.65.254", "192.168.65.1", "192.168.65.2"];
+/// The host alias of a Lima VM (Colima: `host.lima.internal`).
+const LIMA_ALIASES: [&str; 1] = ["192.168.5.2"];
+
/// How long one engine-host command may take.
const HELPER_TIMEOUT: Duration = Duration::from_secs(30);
@@ -51,6 +80,13 @@ pub(crate) struct Kept {
/// recreate) does not leave the old one behind.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub table: Option<String>,
+ /// Its network settings ([`crate::network`]); `None`: kept from
+ /// before them (migrated from `policy` at its next start).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub network: Option<NetworkSettings>,
+ /// The tree it belongs to; `None`: its own.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tree: Option<String>,
}
fn dir() -> PathBuf {
@@ -81,7 +117,9 @@ pub(crate) fn forget(name: &str) {
let _ = std::fs::remove_file(path(name));
}
-/// Gives container `to` the policy of `from` (a fork, a rename).
+/// Gives container `to` the policy, network settings and tree of `from`
+/// (a fork, a rename, a checkpoint). A fork of a child stays in its tree;
+/// a fork of a top-level sandbox is a tree of its own, as its Space is.
pub(crate) fn copy(from: &str, to: &str) -> Result<()> {
match kept(from) {
Some(k) => keep(
@@ -89,15 +127,128 @@ pub(crate) fn copy(from: &str, to: &str) -> Result<()> {
&Kept {
policy: k.policy,
table: None,
+ network: k.network,
+ tree: k.tree,
},
),
None => Ok(()),
}
}
-/// Whether the policy kept for `name` blocks anything.
+/// Whether the secure default applies ([`Mode::from_env`]).
+pub(crate) fn secure() -> bool {
+ Mode::from_env() == Mode::Secure
+}
+
+/// The network settings in force for `name` under the secure default
+/// (`None` under the old open default): its own, or its old policy
+/// migrated.
+pub(crate) fn settings(name: &str) -> Option<NetworkSettings> {
+ if !secure() {
+ return None;
+ }
+ let k = kept(name).unwrap_or_default();
+ Some(
+ k.network
+ .unwrap_or_else(|| NetworkSettings::migrate(&k.policy, false)),
+ )
+}
+
+/// The tree `name` belongs to.
+pub(crate) fn tree_of(name: &str) -> String {
+ kept(name)
+ .and_then(|k| k.tree)
+ .unwrap_or_else(|| name.to_string())
+}
+
+/// The Docker network of tree `tree` for the cua home tagged `home_tag`:
+/// `cua-t-<12 hex>`.
+pub fn tree_network(home_tag: &str, tree: &str) -> String {
+ let d = Sha256::digest(format!("{home_tag}:{tree}").as_bytes());
+ let hex: String = d.iter().map(|b| format!("{b:02x}")).collect();
+ format!("{TREE_NETWORK_PREFIX}{}", &hex[..12])
+}
+
+/// Whether container `name` is policed: always under the secure default,
+/// else when its policy blocks anything.
pub(crate) fn blocks(name: &str) -> bool {
- kept(name).is_some_and(|k| policy_blocks(&k.policy))
+ secure() || kept(name).is_some_and(|k| policy_blocks(&k.policy))
+}
+
+/// What a stopped container must have before it may start policed: the
+/// network it must be on, its MAC labelled and configured alike, and no
+/// `CAP_NET_RAW`. `true`: it must be recreated.
+pub(crate) fn must_recreate(
+ expected_network: Option<&str>,
+ networks: &[String],
+ labelled_mac: Option<&str>,
+ configured_mac: Option<&str>,
+ raw_dropped: bool,
+) -> bool {
+ let wrong_network = expected_network.is_some_and(|n| networks != [n.to_string()]);
+ labelled_mac.is_none() || labelled_mac != configured_mac || !raw_dropped || wrong_network
+}
+
+/// The engine host's facts from [`PROBE`]'s output (`dns=`, `addr=`,
+/// `alias=` lines) and the networks' own: the tree's subnets (allowed), the
+/// gateway (a host alias), other trees' subnets (blocked) and the daemon's
+/// ports.
+pub(crate) fn context_from(
+ probe: &str,
+ gateways: &[IpAddr],
+ tree: &[Net],
+ other_trees: &[Net],
+ daemon_ports: &[u16],
+) -> NetworkContext {
+ let ips = |key: &str| -> Vec<IpAddr> {
+ let mut out: Vec<IpAddr> = Vec::new();
+ for ip in probe.lines().filter_map(|l| {
+ l.strip_prefix(&format!("{key}="))
+ .and_then(|v| v.split('/').next())
+ .and_then(|v| v.trim().parse::<IpAddr>().ok())
+ }) {
+ if !out.contains(&ip) {
+ out.push(ip);
+ }
+ }
+ out
+ };
+ let addrs = ips("addr");
+ let mut aliases: Vec<IpAddr> = gateways.to_vec();
+ aliases.extend(ips("alias"));
+ let on = |net: &str| {
+ let n = Net::parse(net).expect("a valid network");
+ addrs.iter().any(|a| n.contains(*a))
+ };
+ if on("192.168.65.0/24") {
+ aliases.extend(
+ DESKTOP_ALIASES
+ .iter()
+ .filter_map(|a| a.parse::<IpAddr>().ok()),
+ );
+ }
+ if on("192.168.5.0/24") {
+ aliases.extend(LIMA_ALIASES.iter().filter_map(|a| a.parse::<IpAddr>().ok()));
+ }
+ let mut host_aliases: Vec<IpAddr> = Vec::new();
+ for a in aliases {
+ if !a.is_loopback() && !host_aliases.contains(&a) {
+ host_aliases.push(a);
+ }
+ }
+ NetworkContext {
+ // Docker's embedded resolver (127.0.0.11) answers inside the
+ // container; it forwards to these.
+ resolvers: ips("dns")
+ .into_iter()
+ .filter(|i| !i.is_loopback())
+ .collect(),
+ host_aliases,
+ host_addrs: addrs.into_iter().filter(|i| !i.is_loopback()).collect(),
+ tree: tree.to_vec(),
+ other_trees: other_trees.to_vec(),
+ daemon_ports: daemon_ports.to_vec(),
+ }
}
/// Whether `policy` blocks any destination (an allow list alone does not).
@@ -120,6 +271,13 @@ if [ "$pid" != 0 ]; then
[ -n "$idx" ] && ip -o link | sed -n "s/^$idx: \([^:@]*\)[@:].*/veth=\1/p"
fi
command -v nft >/dev/null 2>&1 || echo nft=missing
+for f in /etc/resolv.conf /run/systemd/resolve/resolv.conf; do
+ [ -r "$f" ] && sed -n 's/^nameserver[[:space:]]*\([0-9a-fA-F:.]*\).*/dns=\1/p' "$f"
+done
+ip -o addr show 2>/dev/null | awk '{print "addr=" $4}'
+for h in host.docker.internal gateway.docker.internal host.lima.internal; do
+ getent hosts "$h" 2>/dev/null | awk '{print "alias=" $1}'
+done
"#;
/// The engine-host script that feeds `$1` to `nft -f -`.
@@ -168,36 +326,140 @@ impl ContainerRuntime {
Ok(dev)
}
+ /// The Docker network of `name`'s tree, created when missing (a
+ /// bridge with inter-container traffic on: the tree's members reach
+ /// each other directly).
+ pub(crate) async fn ensure_tree_network(&self, name: &str) -> Result<String> {
+ let tree = tree_of(name);
+ let net = tree_network(&super::home_tag(), &tree);
+ if self.docker.inspect_network(&net, None).await.is_ok() {
+ return Ok(net);
+ }
+ let req = bollard::models::NetworkCreateRequest {
+ name: net.clone(),
+ driver: Some("bridge".into()),
+ enable_ipv6: Some(false),
+ options: Some(
+ [(
+ "com.docker.network.bridge.enable_icc".to_string(),
+ "true".to_string(),
+ )]
+ .into_iter()
+ .collect(),
+ ),
+ labels: Some(
+ [
+ (LABEL_TREE.to_string(), tree),
+ ("ai.cua.home".to_string(), super::home_tag()),
+ ]
+ .into_iter()
+ .collect(),
+ ),
+ ..Default::default()
+ };
+ match self.docker.create_network(req).await {
+ Ok(_) => Ok(net),
+ // Another start made it first.
+ Err(e) => match self.docker.inspect_network(&net, None).await {
+ Ok(_) => Ok(net),
+ Err(_) => Err(VmmError::Engine(format!(
+ "could not create the network of {name}'s tree ({net}): {e}"
+ ))),
+ },
+ }
+ }
+
+ /// Removes the Docker network of tree `tree` once no container is on
+ /// it (its last member was deleted).
+ pub(crate) async fn drop_tree_network_if_empty(&self, tree: &str) {
+ let net = tree_network(&super::home_tag(), tree);
+ let Ok(n) = self.docker.inspect_network(&net, None).await else {
+ return;
+ };
+ if n.containers.as_ref().is_none_or(|c| c.is_empty())
+ && let Err(e) = self.docker.remove_network(&net).await
+ {
+ tracing::debug!(network = %net, error = %e, "could not remove an empty tree network");
+ }
+ }
+
/// The `NetworkingConfig` that gives a new container `name` its own MAC
- /// on the engine's default bridge, with the MAC (`None` when the engine
- /// has no such network: such an engine refuses policies).
+ /// on the network it belongs on, with the MAC: its tree's network under
+ /// the secure default (an error when it can't be made: never an open
+ /// container), else the engine's default bridge (`None` when the engine
+ /// has none: such an engine refuses policies).
pub(crate) async fn mac_config(
&self,
name: &str,
- ) -> Option<(bollard::models::NetworkingConfig, String)> {
- let n = self
- .docker
- .inspect_network(DEFAULT_NETWORK, None)
- .await
- .ok()?;
- if n.driver.as_deref() != Some("bridge") {
- return None;
- }
+ ) -> Result<Option<(bollard::models::NetworkingConfig, String)>> {
+ let net = if secure() {
+ self.ensure_tree_network(name).await?
+ } else {
+ let Ok(n) = self.docker.inspect_network(DEFAULT_NETWORK, None).await else {
+ return Ok(None);
+ };
+ if n.driver.as_deref() != Some("bridge") {
+ return Ok(None);
+ }
+ DEFAULT_NETWORK.to_string()
+ };
let mac = mac_for(name);
let endpoint = bollard::models::EndpointSettings {
mac_address: Some(mac.clone()),
..Default::default()
};
- Some((
+ Ok(Some((
bollard::models::NetworkingConfig {
- endpoints_config: Some(
- [(DEFAULT_NETWORK.to_string(), endpoint)]
- .into_iter()
- .collect(),
- ),
+ endpoints_config: Some([(net, endpoint)].into_iter().collect()),
},
mac,
- ))
+ )))
+ }
+
+ /// The subnets and gateways of Docker network `net`.
+ async fn subnets(&self, net: &str) -> (Vec<Net>, Vec<IpAddr>) {
+ let Ok(n) = self.docker.inspect_network(net, None).await else {
+ return (vec![], vec![]);
+ };
+ let configs = n.ipam.and_then(|i| i.config).unwrap_or_default();
+ let nets = configs
+ .iter()
+ .filter_map(|c| c.subnet.as_deref())
+ .filter_map(|s| Net::parse(s).ok())
+ .collect();
+ let gws = configs
+ .iter()
+ .filter_map(|c| c.gateway.as_deref())
+ .filter_map(|g| g.parse().ok())
+ .collect();
+ (nets, gws)
+ }
+
+ /// The subnets of every other tree's network on this engine, and of its
+ /// default bridge: Spaces there are blocked.
+ async fn other_tree_subnets(&self, own: &str) -> Vec<Net> {
+ let filters = [("label".to_string(), vec![LABEL_TREE.to_string()])]
+ .into_iter()
+ .collect();
+ let mut names: Vec<String> = self
+ .docker
+ .list_networks(Some(bollard::query_parameters::ListNetworksOptions {
+ filters: Some(filters),
+ }))
+ .await
+ .unwrap_or_default()
+ .into_iter()
+ .filter_map(|n| n.name)
+ .filter(|n| n != own)
+ .collect();
+ if own != DEFAULT_NETWORK {
+ names.push(DEFAULT_NETWORK.to_string());
+ }
+ let mut out = Vec::new();
+ for n in names {
+ out.extend(self.subnets(&n).await.0);
+ }
+ out
}
/// Where container `i`'s rules go: its network, MAC and address, its
@@ -206,7 +468,7 @@ impl ContainerRuntime {
&self,
i: &bollard::models::ContainerInspectResponse,
running: bool,
- ) -> Result<EngineTarget> {
+ ) -> Result<(EngineTarget, NetworkContext)> {
let name = i
.name
.as_deref()
@@ -298,13 +560,32 @@ impl ContainerRuntime {
} else {
None
};
- Ok(EngineTarget {
- table: egress::engine_table(&mac),
- bridge,
- gateway_mac,
- mac,
- port,
- })
+ let tree_net = net.starts_with(TREE_NETWORK_PREFIX);
+ let ctx = if secure() {
+ let (subnets, gateways) = self.subnets(&net).await;
+ context_from(
+ &out.stdout,
+ &gateways,
+ // The tree's own bridge: its members. The default bridge is
+ // shared, so it has none.
+ if tree_net { &subnets } else { &[] },
+ &self.other_tree_subnets(&net).await,
+ &crate::network::daemon_ports(),
+ )
+ } else {
+ NetworkContext::default()
+ };
+ Ok((
+ EngineTarget {
+ table: egress::engine_table(&mac),
+ bridge,
+ gateway_mac,
+ mac,
+ port,
+ isolate_l2: !tree_net,
+ },
+ ctx,
+ ))
}
/// Writes `text` with nft on the engine host.
@@ -322,13 +603,15 @@ impl ContainerRuntime {
/// Writes `policy` for container `name` on the engine host (keyed by
/// its MAC; bound to its bridge port as well when it runs) and keeps it.
pub(crate) async fn police(&self, name: &str, policy: &EgressPolicy) -> Result<()> {
- let rules = egress::check(crate::BackendKind::Container, policy)?;
+ let legacy = egress::check(crate::BackendKind::Container, policy)?;
let i = self
.inspect(name)
.await?
.ok_or_else(|| VmmError::NotFound(name.into()))?;
- let previous = kept(name).and_then(|k| k.table);
- if !rules.blocks_anything() {
+ let previous_kept = kept(name);
+ let previous = previous_kept.as_ref().and_then(|k| k.table.clone());
+ let network = settings(name);
+ if network.is_none() && !legacy.blocks_anything() {
// Nothing to filter: remove what was there.
if let Some(t) = &previous {
self.engine_apply(&egress::engine_remove(t)).await?;
@@ -338,6 +621,7 @@ impl ContainerRuntime {
&Kept {
policy: policy.clone(),
table: None,
+ ..previous_kept.unwrap_or_default()
},
);
}
@@ -345,7 +629,11 @@ impl ContainerRuntime {
Self::status_from(&i),
crate::Status::Running | crate::Status::Paused
);
- let target = self.engine_target(&i, running).await?;
+ let (target, ctx) = self.engine_target(&i, running).await?;
+ let rules = match &network {
+ Some(s) => crate::network::compile_mode(s, &ctx, Mode::Secure)?,
+ None => legacy,
+ };
let mut text = String::new();
if let Some(t) = previous.as_ref().filter(|t| **t != target.table) {
text.push_str(&egress::engine_remove(t));
@@ -357,6 +645,8 @@ impl ContainerRuntime {
&Kept {
policy: policy.clone(),
table: Some(target.table),
+ network: network.or(previous_kept.as_ref().and_then(|k| k.network.clone())),
+ tree: previous_kept.and_then(|k| k.tree),
},
)
}
@@ -369,7 +659,10 @@ impl ContainerRuntime {
{
tracing::warn!(container = name, error = %e, "could not remove a deleted container's egress rules");
}
+ let tree = tree_of(name);
forget(name);
+ // Its tree's network goes with the tree's last member.
+ self.drop_tree_network_if_empty(&tree).await;
}
/// Whether stopped container `i` must be recreated before it may start
@@ -401,7 +694,21 @@ impl ContainerRuntime {
.as_ref()
.and_then(|h| h.cap_drop.as_ref())
.is_some_and(|c| c.iter().any(|x| x.trim_start_matches("CAP_") == "NET_RAW"));
- labelled.is_none() || labelled != configured || !raw_dropped
+ let networks: Vec<String> = i
+ .network_settings
+ .as_ref()
+ .and_then(|n| n.networks.as_ref())
+ .map(|n| n.keys().cloned().collect())
+ .unwrap_or_default();
+ // Under the secure default it must be on its tree's network.
+ let expected = secure().then(|| tree_network(&super::home_tag(), &tree_of(name)));
+ must_recreate(
+ expected.as_deref(),
+ &networks,
+ labelled.as_deref(),
+ configured.as_deref(),
+ raw_dropped,
+ )
}
/// Starts container `name` under the policy kept for it: the rules are
@@ -409,7 +716,11 @@ impl ContainerRuntime {
/// port once it runs. A container whose rules cannot be written does
/// not start, and one whose port cannot be bound is killed.
pub(crate) async fn start_policed(&self, name: &str) -> Result<()> {
- let policy = kept(name).map(|k| k.policy).filter(policy_blocks);
+ // Under the secure default every container is policed.
+ let policy = kept(name)
+ .map(|k| k.policy)
+ .filter(|p| secure() || policy_blocks(p))
+ .or_else(|| secure().then(EgressPolicy::default));
if let Some(p) = &policy {
self.police(name, p).await?;
}
@@ -445,6 +756,112 @@ mod tests {
assert!(APPLY.contains(r#""$1""#));
}
+ #[test]
+ fn one_network_per_tree() {
+ let a = tree_network("home1", "local:root");
+ assert_eq!(a, tree_network("home1", "local:root"));
+ assert!(a.starts_with(TREE_NETWORK_PREFIX));
+ assert_eq!(a.len(), TREE_NETWORK_PREFIX.len() + 12);
+ assert_ne!(a, tree_network("home1", "local:other"));
+ assert_ne!(a, tree_network("home2", "local:root"), "per cua home");
+ }
+
+ #[test]
+ fn a_container_off_its_tree_network_is_recreated() {
+ let net = "cua-t-0123456789ab".to_string();
+ let mac = Some("02:aa:bb:cc:dd:ee");
+ // Right network, MAC and capabilities: kept.
+ assert!(!must_recreate(
+ Some(&net),
+ std::slice::from_ref(&net),
+ mac,
+ mac,
+ true
+ ));
+ // On the default bridge (made before the secure default): recreated.
+ assert!(must_recreate(
+ Some(&net),
+ &["bridge".into()],
+ mac,
+ mac,
+ true
+ ));
+ // Still has NET_RAW, or its MAC differs, or has none: recreated.
+ assert!(must_recreate(
+ Some(&net),
+ std::slice::from_ref(&net),
+ mac,
+ mac,
+ false
+ ));
+ assert!(must_recreate(
+ Some(&net),
+ std::slice::from_ref(&net),
+ mac,
+ Some("02:00:00:00:00:01"),
+ true
+ ));
+ assert!(must_recreate(None, &["bridge".into()], None, None, true));
+ // The old default: any network will do.
+ assert!(!must_recreate(None, &["bridge".into()], mac, mac, true));
+ }
+
+ #[test]
+ fn the_engine_hosts_facts_become_the_context() {
+ let probe = "gw=0a:de:71:61:ef:e1\nveth=veth1\n\
+ dns=127.0.0.53\ndns=10.0.0.2\ndns=10.0.0.2\n\
+ addr=127.0.0.1/8\naddr=10.0.1.5/24\naddr=172.18.0.1/16\naddr=fe80::1/64\n\
+ alias=172.17.0.1\n";
+ let ip = |s: &str| s.parse::<IpAddr>().unwrap();
+ let tree = [Net::parse("172.18.0.0/16").unwrap()];
+ let others = [Net::parse("172.17.0.0/16").unwrap()];
+ let c = context_from(probe, &[ip("172.18.0.1")], &tree, &others, &[4100]);
+ assert_eq!(
+ c.resolvers,
+ [ip("10.0.0.2")],
+ "loopback resolvers are the engine's own"
+ );
+ assert_eq!(c.host_aliases, [ip("172.18.0.1"), ip("172.17.0.1")]);
+ assert_eq!(
+ c.host_addrs,
+ [ip("10.0.1.5"), ip("172.18.0.1"), ip("fe80::1")]
+ );
+ assert_eq!(c.tree, tree);
+ assert_eq!(c.other_trees, others);
+ assert_eq!(c.daemon_ports, [4100]);
+ // Docker Desktop's and Lima's host aliases, when the engine is there.
+ let c = context_from("addr=192.168.65.3/24\n", &[], &[], &[], &[]);
+ assert!(c.host_aliases.contains(&ip("192.168.65.254")));
+ let c = context_from("addr=192.168.5.15/24\n", &[], &[], &[], &[]);
+ assert!(c.host_aliases.contains(&ip("192.168.5.2")));
+ let c = context_from("addr=10.0.1.5/24\n", &[], &[], &[], &[]);
+ assert!(c.host_aliases.is_empty());
+ // Compiled: the gateway and the engine's addresses are closed, the
+ // tree is open, other trees and the resolver as they should be.
+ let c = context_from(probe, &[ip("172.18.0.1")], &tree, &others, &[4100]);
+ let r = crate::network::compile_mode(
+ &NetworkSettings::internet(),
+ &c,
+ crate::network::Mode::Secure,
+ )
+ .unwrap();
+ assert!(!r.allows(ip("172.18.0.1")));
+ assert!(!r.allows(ip("10.0.1.5")));
+ assert!(r.allows(ip("172.18.0.7")));
+ assert!(!r.allows(ip("172.17.0.4")));
+ assert!(r.allows_port(ip("10.0.0.2"), crate::egress::Proto::Udp, 53));
+ assert!(!r.allows_port(ip("10.0.0.2"), crate::egress::Proto::Tcp, 22));
+ assert!(r.rules.iter().any(|r| r.host_local && !r.accept));
+ }
+
+ #[test]
+ fn the_probe_reads_resolvers_addresses_and_aliases() {
+ assert!(PROBE.contains("dns=\\1"), "{PROBE}");
+ assert!(PROBE.contains("/run/systemd/resolve/resolv.conf"));
+ assert!(PROBE.contains("print \"addr=\" $4"));
+ assert!(PROBE.contains("host.docker.internal"));
+ }
+
#[test]
fn a_mac_per_container_name() {
assert_eq!(mac_for("web"), mac_for("web"));
diff --git a/libs/cua/crates/cua-vmm/src/container/mod.rs b/libs/cua/crates/cua-vmm/src/container/mod.rs
index d459cb6b88..06be3f4b8e 100644
--- a/libs/cua/crates/cua-vmm/src/container/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/container/mod.rs
@@ -845,13 +845,13 @@ impl ContainerRuntime {
let mut body = create_body(name, image, spec, base_labels, engine_runtime);
// Its own MAC, so egress rules can be keyed by it before it starts
// ([`egress`]); no raw sockets under a policy that blocks anything.
- if let Some((net, mac)) = self.mac_config(name).await {
+ if let Some((net, mac)) = self.mac_config(name).await? {
body.networking_config = Some(net);
body.labels
.get_or_insert_with(Default::default)
.insert(egress::LABEL_MAC.into(), mac);
}
- if (egress::policy_blocks(&spec.egress) || egress::blocks(name))
+ if (egress::secure() || egress::policy_blocks(&spec.egress) || egress::blocks(name))
&& let Some(hc) = body.host_config.as_mut()
{
hc.cap_drop = Some(vec!["NET_RAW".into()]);
@@ -1225,17 +1225,34 @@ impl Runtime for ContainerRuntime {
// pulled or created.
self.group_runtime(spec).await?;
let existing = self.inspect(&spec.name).await?;
- // The policy: the start spec's for a new container (or one that has
- // none kept); a kept one wins (`set_egress` changed it since).
+ // The policy and network settings: the start spec's for a new
+ // container (or one that has none kept); kept ones win (`set_egress`
+ // changed them since). A container kept from before network
+ // settings takes the spec's.
match (&existing, egress::kept(&spec.name)) {
- (Some(_), Some(_)) => {}
- (Some(_), None) if spec.egress.is_empty() => {}
- _ if spec.egress.is_empty() => egress::forget(&spec.name),
+ (Some(_), Some(k)) => {
+ if k.network.is_none() && spec.network.is_some() {
+ egress::keep(
+ &spec.name,
+ &egress::Kept {
+ network: spec.network.clone(),
+ tree: k.tree.clone().or_else(|| spec.tree.clone()),
+ ..k
+ },
+ )?;
+ }
+ }
+ (Some(_), None) if spec.egress.is_empty() && spec.network.is_none() => {}
+ _ if spec.egress.is_empty() && spec.network.is_none() && spec.tree.is_none() => {
+ egress::forget(&spec.name)
+ }
_ => egress::keep(
&spec.name,
&egress::Kept {
policy: spec.egress.clone(),
table: None,
+ network: spec.network.clone(),
+ tree: spec.tree.clone(),
},
)?,
}
@@ -1530,9 +1547,13 @@ impl Runtime for ContainerRuntime {
.ok_or_else(|| VmmError::NotFound(name.into()))?;
if Self::status_from(&before) == Status::Stopped {
if self.needs_recreate(name, &before) {
+ // Recreating it would drop its writable layer: never done for you.
return Err(VmmError::invalid(format!(
- "{name} must be recreated for its egress policy before it runs again: \
- start it (not resume)"
+ "{name} was made before its network settings, so it can start only on the \
+ network it had. Joining the secure network means recreating it, and its \
+ files would be lost: turn Secure Spaces off (`cua experiments disable \
+ secure-spaces`) to keep using it as it is, or copy what you need out \
+ (`cua sandbox cp`) and delete it"
)));
}
self.start_policed(name).await?;
@@ -1564,7 +1585,8 @@ impl Runtime for ContainerRuntime {
}
let mut labels = HashMap::new();
labels.insert("cua.vmm.source".to_string(), source.to_string());
- // A fork inherits its source's egress policy (applied at its start).
+ // A fork inherits its source's egress policy and network settings
+ // (applied at its start), and stays in its tree.
egress::copy(source, new_name)?;
// Memory: a running gVisor Space (checkpointed now) or a memory
// checkpoint; the fork restores it when it starts.
@@ -1781,6 +1803,12 @@ impl Runtime for ContainerRuntime {
&egress::Kept {
policy: policy.clone(),
table: previous.as_ref().and_then(|k| k.table.clone()),
+ // The lists are its network settings' own lists too.
+ network: Some(crate::network::NetworkSettings::with_lists(
+ previous.as_ref().and_then(|k| k.network.clone()),
+ policy,
+ )),
+ tree: previous.as_ref().and_then(|k| k.tree.clone()),
},
)?;
if !running && self.needs_recreate(name, &i) {
@@ -1802,6 +1830,40 @@ impl Runtime for ContainerRuntime {
Ok(egress::kept(name).map(|k| k.policy).unwrap_or_default())
}
+ /// Kept with the container; on the engine host at once while it runs
+ /// (a container not yet on its tree's network gets them at its next
+ /// start, recreated first).
+ async fn set_network(
+ &self,
+ name: &str,
+ settings: &crate::network::NetworkSettings,
+ ) -> Result<crate::network::Applied> {
+ settings.validate()?;
+ let i = self
+ .inspect(name)
+ .await?
+ .ok_or_else(|| VmmError::NotFound(name.into()))?;
+ let previous = egress::kept(name);
+ let k = egress::Kept {
+ policy: settings.custom.clone(),
+ network: Some(settings.clone()),
+ ..previous.clone().unwrap_or_default()
+ };
+ egress::keep(name, &k)?;
+ let running = matches!(Self::status_from(&i), Status::Running | Status::Paused);
+ if !running || self.needs_recreate(name, &i) {
+ return Ok(crate::network::Applied::NextStart);
+ }
+ if let Err(e) = self.police(name, &k.policy).await {
+ match previous {
+ Some(p) => egress::keep(name, &p)?,
+ None => egress::forget(name),
+ }
+ return Err(e);
+ }
+ Ok(crate::network::Applied::Now)
+ }
+
async fn delete(&self, name: &str) -> Result<()> {
let opts = RemoveContainerOptions {
force: true,
@@ -2299,7 +2361,7 @@ impl ContainerRuntime {
}
hc.port_bindings = Some(bindings);
let mut labels = cfg.labels;
- let networking_config = match self.mac_config(name).await {
+ let networking_config = match self.mac_config(name).await? {
Some((net, mac)) => {
labels
.get_or_insert_with(Default::default)
diff --git a/libs/cua/crates/cua-vmm/src/containerization/mod.rs b/libs/cua/crates/cua-vmm/src/containerization/mod.rs
index 298f99f817..b17a68717a 100644
--- a/libs/cua/crates/cua-vmm/src/containerization/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/containerization/mod.rs
@@ -828,8 +828,27 @@ impl Runtime for ContainerizationRuntime {
async fn start(&self, spec: &StartSpec) -> Result<Instance> {
reject_sidecars(BackendKind::Containerization, spec)?;
crate::types::reject_mounts(BackendKind::Containerization, spec)?;
- reject_restricted_network(BackendKind::Containerization, spec)?;
- crate::egress::check(BackendKind::Containerization, &spec.egress)?;
+ // Apple's Containerization can't protect a Space's network: under the
+ // secure default only No protection starts it (anything else is
+ // refused in plain words); as before under the old one.
+ match crate::network::gate(
+ BackendKind::Containerization,
+ &spec.name,
+ &crate::network::spec_settings(spec),
+ )? {
+ Some(crate::network::NetworkPlan::Open { .. }) => {}
+ Some(_) => {
+ return Err(VmmError::Other(
+ "Apple's Containerization can't protect your network yet. Use the standard \
+ microVM (the default) or choose No protection."
+ .into(),
+ ));
+ }
+ None => {
+ reject_restricted_network(BackendKind::Containerization, spec)?;
+ crate::egress::check(BackendKind::Containerization, &spec.egress)?;
+ }
+ }
reject_gpu(BackendKind::Containerization, spec, &[])?;
if spec.os != GuestOs::Linux {
return Err(VmmError::Unsupported {
diff --git a/libs/cua/crates/cua-vmm/src/egress.rs b/libs/cua/crates/cua-vmm/src/egress.rs
index e3a0e5df3f..dd9a3be5cf 100644
--- a/libs/cua/crates/cua-vmm/src/egress.rs
+++ b/libs/cua/crates/cua-vmm/src/egress.rs
@@ -70,15 +70,23 @@ impl EgressPolicy {
/// Checks the entries: addresses, CIDRs and `all` only (a hostname is
/// refused).
pub fn parse(&self) -> Result<Rules, PolicyError> {
+ let allow = parse_list(&self.allow)?;
+ let deny = parse_list(&self.deny)?;
Ok(Rules {
- allow: parse_list(&self.allow)?,
- deny: parse_list(&self.deny)?,
+ rules: allow
+ .into_iter()
+ .map(|n| Rule::net(n, true, Reason::UserAllow))
+ .chain(
+ deny.into_iter()
+ .map(|n| Rule::net(n, false, Reason::UserDeny)),
+ )
+ .collect(),
})
}
}
/// One destination: a network of one address family.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Net {
/// IPv4 network address and prefix length.
V4(Ipv4Addr, u8),
@@ -105,6 +113,49 @@ impl Net {
}
}
+ /// The network's first address.
+ pub fn addr(&self) -> IpAddr {
+ match self {
+ Net::V4(a, _) => IpAddr::V4(*a),
+ Net::V6(a, _) => IpAddr::V6(*a),
+ }
+ }
+
+ /// The prefix length.
+ pub fn prefix(&self) -> u8 {
+ match self {
+ Net::V4(_, p) | Net::V6(_, p) => *p,
+ }
+ }
+
+ /// Whether every address of `other` is in this network.
+ pub fn covers(&self, other: &Net) -> bool {
+ self.is_v6() == other.is_v6()
+ && self.prefix() <= other.prefix()
+ && self.contains(other.addr())
+ }
+
+ /// Whether this network and `other` share an address.
+ pub fn overlaps(&self, other: &Net) -> bool {
+ self.covers(other) || other.covers(self)
+ }
+
+ /// The network of one address (`/32`, `/128`).
+ pub fn host(ip: IpAddr) -> Net {
+ match ip {
+ IpAddr::V4(a) => Net::V4(a, 32),
+ IpAddr::V6(a) => Net::V6(a, 128),
+ }
+ }
+
+ /// Parses `address/prefix` (host bits cleared) or one address.
+ pub fn parse(text: &str) -> Result<Net, PolicyError> {
+ match parse_entry(text)?.as_slice() {
+ [net] => Ok(*net),
+ _ => Err(PolicyError(format!("{text:?}: one network, not \"all\""))),
+ }
+ }
+
/// Whether `ip` is in this network.
pub fn contains(&self, ip: IpAddr) -> bool {
match (self, ip) {
@@ -129,14 +180,275 @@ impl Net {
}
}
-/// A checked policy: entries parsed, host bits cleared, duplicates dropped
-/// (first spelling wins, order kept).
+/// The transport a [`Rule`] is limited to.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Proto {
+ /// TCP.
+ Tcp,
+ /// UDP.
+ Udp,
+}
+
+impl Proto {
+ /// `tcp` or `udp`.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Proto::Tcp => "tcp",
+ Proto::Udp => "udp",
+ }
+ }
+}
+
+/// Why a [`Rule`] is there: the id a blocked-connection report carries
+/// (`platform:metadata`, `default:lan`, ...). The layers are
+/// [`crate::network`]'s.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum Reason {
+ /// A cloud metadata endpoint (always blocked).
+ #[serde(rename = "platform:metadata")]
+ PlatformMetadata,
+ /// The cua daemon's ports on the host (always blocked).
+ #[serde(rename = "platform:daemon")]
+ PlatformDaemon,
+ /// A Space of another tree (always blocked).
+ #[serde(rename = "platform:other-tree")]
+ PlatformOtherTree,
+ /// The runtime's own DNS resolver, on port 53.
+ #[serde(rename = "allow:resolver")]
+ Resolver,
+ /// A Space of the same tree.
+ #[serde(rename = "allow:tree")]
+ Tree,
+ /// The user's allow list.
+ #[serde(rename = "user:allow")]
+ UserAllow,
+ /// The user's deny list.
+ #[serde(rename = "user:deny")]
+ UserDeny,
+ /// The host's loopback on the ports the `localhost` preset lists.
+ #[serde(rename = "preset:localhost")]
+ PresetLocalhost,
+ /// The host's loopback through one of the runtime's host aliases.
+ #[serde(rename = "default:host-loopback")]
+ DefaultHostLoopback,
+ /// One of the host's own addresses.
+ #[serde(rename = "default:host")]
+ DefaultHost,
+ /// A private or link-local network (lifted by the `lan` preset).
+ #[serde(rename = "default:lan")]
+ DefaultLan,
+ /// Loopback, CGNAT, multicast and other reserved ranges.
+ #[serde(rename = "default:reserved")]
+ DefaultReserved,
+ /// Everything else, under a preset without network (`none`).
+ #[serde(rename = "default:none")]
+ DefaultNone,
+}
+
+impl Reason {
+ /// Every reason, for drift guards.
+ pub const ALL: [Reason; 13] = [
+ Reason::PlatformMetadata,
+ Reason::PlatformDaemon,
+ Reason::PlatformOtherTree,
+ Reason::Resolver,
+ Reason::Tree,
+ Reason::UserAllow,
+ Reason::UserDeny,
+ Reason::PresetLocalhost,
+ Reason::DefaultHostLoopback,
+ Reason::DefaultHost,
+ Reason::DefaultLan,
+ Reason::DefaultReserved,
+ Reason::DefaultNone,
+ ];
+
+ /// The id (`platform:metadata`).
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Reason::PlatformMetadata => "platform:metadata",
+ Reason::PlatformDaemon => "platform:daemon",
+ Reason::PlatformOtherTree => "platform:other-tree",
+ Reason::Resolver => "allow:resolver",
+ Reason::Tree => "allow:tree",
+ Reason::UserAllow => "user:allow",
+ Reason::UserDeny => "user:deny",
+ Reason::PresetLocalhost => "preset:localhost",
+ Reason::DefaultHostLoopback => "default:host-loopback",
+ Reason::DefaultHost => "default:host",
+ Reason::DefaultLan => "default:lan",
+ Reason::DefaultReserved => "default:reserved",
+ Reason::DefaultNone => "default:none",
+ }
+ }
+
+ /// The id as a small number, for a log prefix or an nft log group's
+ /// payload (stable: never renumbered).
+ pub fn code(self) -> u8 {
+ match self {
+ Reason::PlatformMetadata => 1,
+ Reason::PlatformDaemon => 2,
+ Reason::PlatformOtherTree => 3,
+ Reason::Resolver => 4,
+ Reason::Tree => 5,
+ Reason::UserAllow => 6,
+ Reason::UserDeny => 7,
+ Reason::PresetLocalhost => 8,
+ Reason::DefaultHostLoopback => 9,
+ Reason::DefaultHost => 10,
+ Reason::DefaultLan => 11,
+ Reason::DefaultReserved => 12,
+ Reason::DefaultNone => 13,
+ }
+ }
+
+ /// The reason with [`Reason::code`] `code`.
+ pub fn from_code(code: u8) -> Option<Reason> {
+ Reason::ALL.into_iter().find(|r| r.code() == code)
+ }
+}
+
+/// One rule: connections to `net` (on `ports` over `proto`, when set) are
+/// accepted or dropped.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Rule {
+ /// The destination network.
+ pub net: Net,
+ /// Only these destination ports; `None`: every port (and protocols
+ /// without ports, such as ICMP).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ports: Option<Vec<u16>>,
+ /// Only this transport; `None`: TCP and UDP when `ports` is set, every
+ /// protocol otherwise.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub proto: Option<Proto>,
+ /// Accept (`true`) or drop.
+ pub accept: bool,
+ /// Why the rule is there.
+ pub reason: Reason,
+ /// The destination is every address local to the host that enforces
+ /// the rules (its own interfaces, whatever they are), not `net`: nft
+ /// `fib daddr type local`, iptables `-m addrtype --dst-type LOCAL`.
+ /// `net` is `0.0.0.0/0` then and both families are meant. The address
+ /// model ([`Rules::allows`]) cannot know them, so it never matches
+ /// such a rule; the listed host addresses stand for them there.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub host_local: bool,
+}
+
+impl Rule {
+ /// A rule for every port and protocol of `net`.
+ pub fn net(net: Net, accept: bool, reason: Reason) -> Rule {
+ Rule {
+ net,
+ ports: None,
+ proto: None,
+ accept,
+ reason,
+ host_local: false,
+ }
+ }
+
+ /// A rule for every address local to the enforcing host
+ /// ([`Rule::host_local`]).
+ pub fn host_local(accept: bool, reason: Reason) -> Rule {
+ Rule {
+ host_local: true,
+ ..Rule::net(Net::V4(Ipv4Addr::UNSPECIFIED, 0), accept, reason)
+ }
+ }
+
+ /// Whether this rule decides a connection to `ip` over `proto` on
+ /// `port` (`None` for both: a packet the rule judges by address only,
+ /// so a rule limited to ports or a transport does not match it).
+ pub fn matches(&self, ip: IpAddr, proto: Option<Proto>, port: Option<u16>) -> bool {
+ if self.host_local || !self.net.contains(ip) {
+ return false;
+ }
+ if let Some(p) = self.proto
+ && proto != Some(p)
+ {
+ return false;
+ }
+ match (&self.ports, port) {
+ (None, _) => true,
+ (Some(list), Some(port)) => proto.is_some() && list.contains(&port),
+ (Some(_), None) => false,
+ }
+ }
+}
+
+/// An ordered rule list: the first rule that matches a connection decides
+/// it; a connection no rule matches is accepted. Built by
+/// [`EgressPolicy::parse`] (the legacy allow/deny lists) or by
+/// [`crate::network::compile`] (a Space's network settings).
+///
+/// The JSON form is stable (`{"version":1,"rules":[{"net":"10.0.0.0/8",
+/// "accept":false,"reason":"default:lan"}]}`, with `ports` and `proto` when
+/// set): other enforcement points, such as a network gateway, read it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Rules {
- /// Allowed destinations.
- pub allow: Vec<Net>,
- /// Blocked destinations.
- pub deny: Vec<Net>,
+ /// The rules, in the order they are evaluated.
+ pub rules: Vec<Rule>,
+}
+
+/// The version of [`Rules`]' JSON form.
+pub const RULES_VERSION: u32 = 1;
+
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RulesWire {
+ version: u32,
+ rules: Vec<Rule>,
+}
+
+impl Serialize for Rules {
+ fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
+ RulesWire {
+ version: RULES_VERSION,
+ rules: self.rules.clone(),
+ }
+ .serialize(s)
+ }
+}
+
+impl<'de> Deserialize<'de> for Rules {
+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let w = RulesWire::deserialize(d)?;
+ if w.version != RULES_VERSION {
+ return Err(serde::de::Error::custom(format!(
+ "network rules version {}: this build reads version {RULES_VERSION}",
+ w.version
+ )));
+ }
+ Ok(Rules { rules: w.rules })
+ }
+}
+
+impl Serialize for Net {
+ fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
+ s.serialize_str(&self.cidr())
+ }
+}
+
+impl<'de> Deserialize<'de> for Net {
+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let text = String::deserialize(d)?;
+ if !text.contains('/') {
+ return Err(serde::de::Error::custom(format!(
+ "network {text:?}: write it as address/prefix"
+ )));
+ }
+ let nets = parse_entry(&text).map_err(|e| serde::de::Error::custom(e.0))?;
+ match nets.as_slice() {
+ [net] if net.cidr() == text.trim() => Ok(*net),
+ _ => Err(serde::de::Error::custom(format!(
+ "network {text:?}: write it as address/prefix with no host bits"
+ ))),
+ }
+ }
}
/// Most entries in one list.
@@ -221,31 +533,71 @@ fn parse_list(list: &[String]) -> Result<Vec<Net>, PolicyError> {
}
impl Rules {
- /// Whether nothing is filtered (no entries).
+ /// Whether nothing is filtered (no rules).
pub fn is_empty(&self) -> bool {
- self.allow.is_empty() && self.deny.is_empty()
- }
-
- /// The rules in the order they are evaluated, as (net, accept): every
- /// `allow` entry first (an exception wins), then every `deny` entry.
- pub fn ordered(&self) -> impl Iterator<Item = (&Net, bool)> {
- self.allow
- .iter()
- .map(|n| (n, true))
- .chain(self.deny.iter().map(|n| (n, false)))
+ self.rules.is_empty()
}
/// Whether any destination is blocked (an allow list alone blocks
/// nothing).
pub fn blocks_anything(&self) -> bool {
- !self.deny.is_empty()
+ self.rules.iter().any(|r| !r.accept)
}
- /// Whether the guest may reach `ip` under these rules.
+ /// The rule that decides a connection to `ip` (an IPv4-mapped IPv6
+ /// address is judged as its IPv4 address), or `None` when no rule
+ /// matches (accepted).
+ pub fn decide(&self, ip: IpAddr, proto: Option<Proto>, port: Option<u16>) -> Option<&Rule> {
+ let ip = canonical_ip(ip);
+ self.rules.iter().find(|r| r.matches(ip, proto, port))
+ }
+
+ /// Whether the guest may reach `ip` on a port no rule names (the
+ /// verdict by address alone).
pub fn allows(&self, ip: IpAddr) -> bool {
- self.ordered()
- .find(|(n, _)| n.contains(ip))
- .is_none_or(|(_, accept)| accept)
+ self.decide(ip, None, None).is_none_or(|r| r.accept)
+ }
+
+ /// Whether the guest may open a `proto` connection to `ip` on `port`.
+ pub fn allows_port(&self, ip: IpAddr, proto: Proto, port: u16) -> bool {
+ self.decide(ip, Some(proto), Some(port))
+ .is_none_or(|r| r.accept)
+ }
+
+ /// Whether every address of `net` is reachable on a port no rule names:
+ /// no rule that drops part of it comes before one that accepts all of
+ /// it. Conservative: an accept that covers only part of `net` does not
+ /// count. A rule for the host's own addresses (`host_local`) is not one
+ /// that drops `net`: it matches only what is local to the host.
+ pub fn allows_net(&self, net: &Net) -> bool {
+ for r in self
+ .rules
+ .iter()
+ .filter(|r| r.ports.is_none() && r.proto.is_none() && !r.host_local)
+ {
+ if !r.net.overlaps(net) {
+ continue;
+ }
+ if r.net.covers(net) {
+ return r.accept;
+ }
+ if !r.accept {
+ return false;
+ }
+ }
+ true
+ }
+}
+
+/// `ip`, with an IPv4-mapped IPv6 address (`::ffff:a.b.c.d`) as its IPv4
+/// address.
+pub fn canonical_ip(ip: IpAddr) -> IpAddr {
+ match ip {
+ IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
+ Some(v4) => IpAddr::V4(v4),
+ None => ip,
+ },
+ v4 => v4,
}
}
@@ -433,6 +785,11 @@ pub struct EngineTarget {
pub mac: String,
/// Its bridge port, once it runs (`None` before its first start).
pub port: Option<BridgePort>,
+ /// Frames from it may only go to the gateway (and broadcast, IPv6
+ /// multicast), so every packet enters the host's IP stack: on a bridge
+ /// shared with other sandboxes (the engine's default). A bridge of its
+ /// own tree leaves it off: the tree's members may talk directly.
+ pub isolate_l2: bool,
}
/// The nft input that removes one sandbox's tables in one transaction
@@ -475,12 +832,14 @@ pub fn engine_ruleset(t: &EngineTarget, rules: &Rules) -> String {
));
}
}
+ if t.isolate_l2 {
+ pre.push_str(&format!(" ether saddr {mac} jump l2\n"));
+ }
out.push_str(&format!(
"table bridge {table} {{\n\
\x20 chain pre {{\n\
\x20 type filter hook prerouting priority -200; policy accept;\n\
{pre}\
- \x20 ether saddr {mac} jump l2\n\
\x20 }}\n\
\x20 chain l2 {{\n\
\x20 ether daddr {{ {gw}, ff:ff:ff:ff:ff:ff }} return\n\
@@ -501,21 +860,40 @@ pub fn engine_ruleset(t: &EngineTarget, rules: &Rules) -> String {
\x20 icmpv6 type {{ nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert }} accept\n",
bridge = t.bridge,
));
- for (net, accept) in rules.ordered() {
- out.push_str(&nft_rule(net, accept));
+ for rule in &rules.rules {
+ out.push_str(&nft_rule(rule));
}
out.push_str(" }\n}\n");
out
}
-fn nft_rule(net: &Net, accept: bool) -> String {
- let verdict = if accept { "accept" } else { "drop" };
- match (net.is_all(), net.is_v6()) {
- (true, false) => format!(" meta nfproto ipv4 {verdict}\n"),
- (true, true) => format!(" meta nfproto ipv6 {verdict}\n"),
- (false, false) => format!(" ip daddr {} {verdict}\n", net.cidr()),
- (false, true) => format!(" ip6 daddr {} {verdict}\n", net.cidr()),
- }
+/// One [`Rule`] as an nft statement (in an `inet` chain).
+pub fn nft_rule(rule: &Rule) -> String {
+ let verdict = if rule.accept { "accept" } else { "drop" };
+ let net = &rule.net;
+ let dest = match (net.is_all(), net.is_v6()) {
+ _ if rule.host_local => "fib daddr type local".to_string(),
+ (true, false) => "meta nfproto ipv4".to_string(),
+ (true, true) => "meta nfproto ipv6".to_string(),
+ (false, false) => format!("ip daddr {}", net.cidr()),
+ (false, true) => format!("ip6 daddr {}", net.cidr()),
+ };
+ let ports = |list: &[u16]| {
+ list.iter()
+ .map(u16::to_string)
+ .collect::<Vec<_>>()
+ .join(", ")
+ };
+ let l4 = match (rule.proto, &rule.ports) {
+ (None, None) => String::new(),
+ (Some(p), None) => format!(" meta l4proto {}", p.as_str()),
+ (Some(p), Some(list)) => format!(" {} dport {{ {} }}", p.as_str(), ports(list)),
+ (None, Some(list)) => format!(
+ " meta l4proto {{ tcp, udp }} th dport {{ {} }}",
+ ports(list)
+ ),
+ };
+ format!(" {dest}{l4} {verdict}\n")
}
// ------------------------------------------------------ VMM namespaces
@@ -562,7 +940,7 @@ pub fn ns_rules(rules: &Rules, v6: bool, resolver: Option<Resolver>) -> String {
));
}
} else if let Some(r) = resolver {
- let verdict = if rules.allows(IpAddr::V4(r.guest)) {
+ let verdict = if rules.allows_port(IpAddr::V4(r.guest), Proto::Udp, 53) {
"ACCEPT"
} else {
"DROP"
@@ -574,12 +952,52 @@ pub fn ns_rules(rules: &Rules, v6: bool, resolver: Option<Resolver>) -> String {
));
}
}
- for (net, accept) in rules.ordered().filter(|(n, _)| n.is_v6() == v6) {
- out.push_str(&format!(
- "-A {NS_CHAIN} -m conntrack --ctorigdst {} -j {}\n",
- net.cidr(),
- if accept { "ACCEPT" } else { "DROP" }
- ));
+ for rule in rules
+ .rules
+ .iter()
+ .filter(|r| r.host_local || r.net.is_v6() == v6)
+ {
+ out.push_str(&ipt_rule(rule));
+ }
+ }
+ out
+}
+
+/// One [`Rule`] as `-A` lines of [`NS_CHAIN`]: matched on the
+/// connection's original destination (and port), one line per transport
+/// and port.
+pub fn ipt_rule(rule: &Rule) -> String {
+ let verdict = if rule.accept { "ACCEPT" } else { "DROP" };
+ // `--ctorigdstport` is the last match's (conntrack) option.
+ let dest = match (rule.host_local, rule.ports.is_some()) {
+ (true, true) => "-m addrtype --dst-type LOCAL -m conntrack".to_string(),
+ (true, false) => "-m addrtype --dst-type LOCAL".to_string(),
+ (false, _) => format!("-m conntrack --ctorigdst {}", rule.net.cidr()),
+ };
+ let protos: Vec<Proto> = match rule.proto {
+ Some(p) => vec![p],
+ None if rule.ports.is_some() => vec![Proto::Tcp, Proto::Udp],
+ None => vec![],
+ };
+ let mut out = String::new();
+ if protos.is_empty() {
+ out.push_str(&format!("-A {NS_CHAIN} {dest} -j {verdict}\n"));
+ return out;
+ }
+ for p in protos {
+ match &rule.ports {
+ None => out.push_str(&format!(
+ "-A {NS_CHAIN} -p {} {dest} -j {verdict}\n",
+ p.as_str()
+ )),
+ Some(list) => {
+ for port in list {
+ out.push_str(&format!(
+ "-A {NS_CHAIN} -p {} {dest} --ctorigdstport {port} -j {verdict}\n",
+ p.as_str()
+ ));
+ }
+ }
}
}
out
@@ -689,8 +1107,14 @@ mod tests {
&[],
&["10.1.2.3/8", "10.0.0.0/8", "ALL", "all", "::1", "0.0.0.0/0"],
);
+ let deny: Vec<Net> = r
+ .rules
+ .iter()
+ .filter(|r| !r.accept)
+ .map(|r| r.net)
+ .collect();
assert_eq!(
- r.deny,
+ deny,
[
Net::V4(Ipv4Addr::new(10, 0, 0, 0), 8),
Net::V4(Ipv4Addr::UNSPECIFIED, 0),
@@ -699,12 +1123,12 @@ mod tests {
]
);
assert_eq!(
- rules(&[], &["2001:db8::1/32"]).deny,
- [Net::V6("2001:db8::".parse().unwrap(), 32)]
+ rules(&[], &["2001:db8::1/32"]).rules[0].net,
+ Net::V6("2001:db8::".parse().unwrap(), 32)
);
assert_eq!(
- rules(&[], &["1.2.3.4/0"]).deny,
- [Net::V4(Ipv4Addr::UNSPECIFIED, 0)]
+ rules(&[], &["1.2.3.4/0"]).rules[0].net,
+ Net::V4(Ipv4Addr::UNSPECIFIED, 0)
);
}
@@ -768,6 +1192,7 @@ mod tests {
veth: "veth1a2b3c4".into(),
ipv4: Some(Ipv4Addr::new(172, 17, 0, 2)),
}),
+ isolate_l2: true,
}
}
@@ -845,6 +1270,63 @@ mod tests {
engine_ruleset(&t, &rules(&["1.1.1.1"], &[])),
engine_remove(table)
);
+ // On its own tree's bridge: members talk directly, spoofing is
+ // still dropped, and the policy still applies.
+ let tree = EngineTarget {
+ isolate_l2: false,
+ ..target(true)
+ };
+ let text = engine_ruleset(&tree, &r);
+ assert!(!text.contains("jump l2"), "{text}");
+ assert!(
+ text.contains(&format!("ether saddr != {mac} drop")),
+ "{text}"
+ );
+ assert!(text.contains("jump verdict"), "{text}");
+ }
+
+ #[test]
+ fn host_local_and_port_rules_render() {
+ let local = Rule {
+ ports: Some(vec![3200]),
+ proto: Some(Proto::Tcp),
+ ..Rule::host_local(false, Reason::PlatformDaemon)
+ };
+ assert_eq!(
+ nft_rule(&local),
+ " fib daddr type local tcp dport { 3200 } drop\n"
+ );
+ assert_eq!(
+ ipt_rule(&local),
+ "-A CUA_EGRESS -p tcp -m addrtype --dst-type LOCAL -m conntrack --ctorigdstport 3200 -j DROP\n"
+ );
+ let all_local = Rule::host_local(false, Reason::DefaultHost);
+ assert_eq!(nft_rule(&all_local), " fib daddr type local drop\n");
+ assert_eq!(
+ ipt_rule(&all_local),
+ "-A CUA_EGRESS -m addrtype --dst-type LOCAL -j DROP\n"
+ );
+ // Never matched by the address model.
+ assert!(!all_local.matches("10.0.0.1".parse().unwrap(), None, None));
+ let dns = Rule {
+ ports: Some(vec![53]),
+ ..Rule::net(Net::parse("10.0.2.3").unwrap(), true, Reason::Resolver)
+ };
+ assert_eq!(
+ nft_rule(&dns),
+ " ip daddr 10.0.2.3/32 meta l4proto { tcp, udp } th dport { 53 } accept\n"
+ );
+ assert_eq!(
+ ipt_rule(&dns),
+ "-A CUA_EGRESS -p tcp -m conntrack --ctorigdst 10.0.2.3/32 --ctorigdstport 53 -j ACCEPT\n\
+ -A CUA_EGRESS -p udp -m conntrack --ctorigdst 10.0.2.3/32 --ctorigdstport 53 -j ACCEPT\n"
+ );
+ // Both families get a host-local rule.
+ let rules = Rules {
+ rules: vec![all_local.clone()],
+ };
+ assert!(ns_rules(&rules, false, None).contains("addrtype"));
+ assert!(ns_rules(&rules, true, None).contains("addrtype"));
}
#[test]
diff --git a/libs/cua/crates/cua-vmm/src/experiments.rs b/libs/cua/crates/cua-vmm/src/experiments.rs
new file mode 100644
index 0000000000..b441ef297b
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/src/experiments.rs
@@ -0,0 +1,211 @@
+//! Experiments: new behavior that is off until it is turned on.
+//!
+//! One switch per experiment, one source of truth in the cua home
+//! (`<home>/experiments/<name>`, `on` or `off`). The CLI (`cua experiments`),
+//! the Spaces apps and the daemon all read and write that file.
+//! `CUA_EXPERIMENTS` turns experiments on (`a,b`) or off (`-a`) for one
+//! process over the file.
+
+use std::sync::atomic::{AtomicU8, Ordering};
+
+/// Environment variable that turns experiments on or off for one process:
+/// a comma or space separated list of names, `-name` for off.
+pub const EXPERIMENTS_ENV: &str = "CUA_EXPERIMENTS";
+
+/// The folder, in the cua home, that holds the switches.
+pub const EXPERIMENTS_DIR: &str = "experiments";
+
+/// An experiment: a feature that is still being built and is off by default.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Gate {
+ /// Secure Spaces: a Space reaches the internet only by default, with a
+ /// network preset per Space (`cua network`).
+ SecureSpaces,
+ /// Child Spaces: a Space makes Spaces of its own through a channel only
+ /// it can reach, inside a budget for its tree (`cua spaces children`).
+ ChildSpaces,
+}
+
+impl Gate {
+ /// Every experiment, in the order they are listed.
+ pub const ALL: &'static [Gate] = &[Gate::SecureSpaces, Gate::ChildSpaces];
+
+ /// The stable name (`secure-spaces`): the file name, the CLI word.
+ pub fn name(self) -> &'static str {
+ match self {
+ Gate::SecureSpaces => "secure-spaces",
+ Gate::ChildSpaces => "child-spaces",
+ }
+ }
+
+ /// The same name with underscores (`secure_spaces`): the app's id.
+ pub fn id(self) -> &'static str {
+ match self {
+ Gate::SecureSpaces => "secure_spaces",
+ Gate::ChildSpaces => "child_spaces",
+ }
+ }
+
+ /// The experiment named `text` (dashes or underscores, any case).
+ pub fn parse(text: &str) -> Option<Gate> {
+ let t = text.trim().to_ascii_lowercase().replace('_', "-");
+ Gate::ALL.iter().copied().find(|g| g.name() == t)
+ }
+
+ /// The label people see.
+ pub fn title(self) -> &'static str {
+ match self {
+ Gate::SecureSpaces => "Secure Spaces",
+ Gate::ChildSpaces => "Child Spaces",
+ }
+ }
+
+ /// One line on what it does.
+ pub fn summary(self) -> &'static str {
+ match self {
+ Gate::SecureSpaces => {
+ "A Space reaches the internet and nothing else on your network unless you open it, with a network setting for each Space."
+ }
+ Gate::ChildSpaces => {
+ "A Space can make Spaces of its own, inside a budget, and keep a command running."
+ }
+ }
+ }
+
+ /// What a call says while the experiment is off.
+ pub fn off_message(self) -> String {
+ format!(
+ "{} is an experiment that is off. Turn it on with `cua experiments enable {}` (or in the app: Settings, Advanced, Labs).",
+ self.title(),
+ self.name()
+ )
+ }
+
+ fn slot(self) -> usize {
+ Gate::ALL.iter().position(|g| *g == self).unwrap_or(0)
+ }
+}
+
+/// Process-wide overrides, one per gate: 0 follows the environment and the
+/// file, 1 off, 2 on.
+static GATE_OVERRIDES: [AtomicU8; 8] = [
+ AtomicU8::new(0),
+ AtomicU8::new(0),
+ AtomicU8::new(0),
+ AtomicU8::new(0),
+ AtomicU8::new(0),
+ AtomicU8::new(0),
+ AtomicU8::new(0),
+ AtomicU8::new(0),
+];
+
+/// Turns `gate` on or off for this whole process (`None` follows the
+/// environment and the file again). For tests and embedders.
+pub fn set_enabled(gate: Gate, on: Option<bool>) {
+ let v = match on {
+ None => 0,
+ Some(false) => 1,
+ Some(true) => 2,
+ };
+ GATE_OVERRIDES[gate.slot()].store(v, Ordering::Relaxed);
+}
+
+/// What [`EXPERIMENTS_ENV`] says about `gate`: `Some(true)` when listed,
+/// `Some(false)` as `-name`, `None` when it does not mention it.
+pub fn env_says(value: Option<&str>, gate: Gate) -> Option<bool> {
+ let mut said = None;
+ for word in value?.split(|c: char| c == ',' || c.is_whitespace()) {
+ let word = word.trim();
+ if let Some(off) = word.strip_prefix('-') {
+ if Gate::parse(off) == Some(gate) {
+ said = Some(false);
+ }
+ } else if Gate::parse(word) == Some(gate) {
+ said = Some(true);
+ }
+ }
+ said
+}
+
+/// Whether `gate` is on in this process: the override, else
+/// [`EXPERIMENTS_ENV`], else the switch in `home`, else off.
+pub fn enabled_in(home: &std::path::Path, gate: Gate) -> bool {
+ match GATE_OVERRIDES[gate.slot()].load(Ordering::Relaxed) {
+ 1 => return false,
+ 2 => return true,
+ _ => {}
+ }
+ if let Some(v) = env_says(std::env::var(EXPERIMENTS_ENV).ok().as_deref(), gate) {
+ return v;
+ }
+ switch(home, gate).unwrap_or(false)
+}
+
+/// [`enabled_in`] with the switches in [`crate::cua_home`].
+pub fn enabled(gate: Gate) -> bool {
+ enabled_in(&cua_home::cua_home(), gate)
+}
+
+fn switch_path(home: &std::path::Path, gate: Gate) -> std::path::PathBuf {
+ home.join(EXPERIMENTS_DIR).join(gate.name())
+}
+
+/// The switch `home` keeps for `gate`; `None` when it was never set.
+pub fn switch(home: &std::path::Path, gate: Gate) -> Option<bool> {
+ let text = std::fs::read_to_string(switch_path(home, gate)).ok()?;
+ Some(text.trim() == "on")
+}
+
+/// Keeps the switch for `gate` in `home`. Writes only a change: a switch
+/// that was never set and stays off writes nothing.
+pub fn set_switch(home: &std::path::Path, gate: Gate, on: bool) -> std::io::Result<()> {
+ let now = switch(home, gate);
+ if now == Some(on) || (now.is_none() && !on) {
+ return Ok(());
+ }
+ let path = switch_path(home, gate);
+ // A test never writes the user's real cua home.
+ cua_home::guard_write(&path)?;
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
+ let tmp = path.with_extension("tmp");
+ std::fs::write(&tmp, if on { "on\n" } else { "off\n" })?;
+ std::fs::rename(&tmp, &path)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_gate_is_off_until_set_and_follows_the_file() {
+ let home = tempfile::tempdir().unwrap();
+ let g = Gate::SecureSpaces;
+ assert_eq!(super::switch(home.path(), g), None);
+ // Off and never set: nothing is written.
+ super::set_switch(home.path(), g, false).unwrap();
+ assert!(!home.path().join("experiments/secure-spaces").exists());
+ assert_eq!(super::switch(home.path(), g), None);
+ super::set_switch(home.path(), g, true).unwrap();
+ assert_eq!(super::switch(home.path(), g), Some(true));
+ super::set_switch(home.path(), g, false).unwrap();
+ assert_eq!(super::switch(home.path(), g), Some(false));
+ }
+
+ #[test]
+ fn the_environment_list_names_experiments_on_or_off() {
+ let g = Gate::SecureSpaces;
+ assert_eq!(super::env_says(None, g), None);
+ assert_eq!(super::env_says(Some("child-spaces"), g), None);
+ assert_eq!(super::env_says(Some("secure-spaces"), g), Some(true));
+ assert_eq!(super::env_says(Some("a, Secure_Spaces"), g), Some(true));
+ assert_eq!(
+ super::env_says(Some("secure-spaces -secure-spaces"), g),
+ Some(false)
+ );
+ assert_eq!(super::env_says(Some("-secure_spaces"), g), Some(false));
+ assert_eq!(Gate::parse("SECURE_SPACES"), Some(g));
+ assert_eq!(Gate::parse("nope"), None);
+ }
+}
diff --git a/libs/cua/crates/cua-vmm/src/lib.rs b/libs/cua/crates/cua-vmm/src/lib.rs
index 43087aa630..f736f55819 100644
--- a/libs/cua/crates/cua-vmm/src/lib.rs
+++ b/libs/cua/crates/cua-vmm/src/lib.rs
@@ -26,6 +26,7 @@ pub mod auto;
pub mod bulk;
pub mod cleanup;
pub mod cloudinit;
+pub mod conformance;
#[cfg(feature = "container")]
pub mod container;
#[cfg(feature = "containerization")]
@@ -36,6 +37,7 @@ pub mod egress;
pub mod elf;
pub mod error;
pub mod exec;
+pub mod experiments;
pub mod filetable;
pub mod gpu;
pub mod host;
@@ -49,6 +51,7 @@ pub mod lume;
pub mod managed;
#[cfg(feature = "microvm")]
pub mod microvm;
+pub mod network;
pub mod preflight;
pub mod probe;
pub mod progress;
diff --git a/libs/cua/crates/cua-vmm/src/lume/derive.rs b/libs/cua/crates/cua-vmm/src/lume/derive.rs
new file mode 100644
index 0000000000..d062f8a116
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/src/lume/derive.rs
@@ -0,0 +1,487 @@
+//! The macOS Space with developer tools: Xcode, its iOS Simulator runtime and
+//! the Apple developer tools on top of the full macOS image.
+//!
+//! Xcode and the iOS Simulator runtimes are Apple software under Apple's
+//! license, for use on Apple-branded hardware. The image is published like the
+//! other macOS tiers and pulled by default; when it is not available, or the
+//! user prefers the Xcode already on this Mac (`CUA_DEV_IMAGE=local`), it is
+//! built here as a clone of the full image's base VM plus that Xcode
+//! (`libs/images/macos/derive-local.sh`, which this module embeds and runs).
+//! The catalog lists the image's fallback parent (`derived_from`);
+//! [`dev_parent`] recognises its reference.
+//!
+//! Selection is automatic: a Space created from `ghcr.io/trycua/macos:26-xcode`
+//! (the `xcode` tier, or `dev`) pulls or builds the base with progress and a
+//! disk check, and every later Space is a clone of it.
+
+use std::path::{Path, PathBuf};
+use std::process::Stdio;
+use std::time::Duration;
+
+use tokio::io::{AsyncBufReadExt, BufReader};
+
+use crate::error::{Result, VmmError};
+use crate::progress::{Phase, Progress};
+
+use super::builtin::LumeCmd;
+
+/// The canonical macOS repository.
+pub const MACOS_REPO: &str = "ghcr.io/trycua/macos";
+
+/// What the build is assumed to write on top of the full image's base: Xcode
+/// and its archive, the iOS runtime, the Metal toolchain, tools and caches.
+pub const DEV_IMAGE_ESTIMATE: u64 = 35 * (1 << 30);
+
+/// The most a build may take: the Xcode copy, the runtime download and the
+/// tools, on a slow connection.
+pub const DERIVE_TIMEOUT: Duration = Duration::from_secs(3 * 60 * 60);
+
+/// The recipe files, as built into this crate (libs/images/macos).
+const DERIVE_LOCAL: &str = include_str!(concat!(env!("OUT_DIR"), "/macos-derive-local.sh"));
+const VERSIONS_ENV: &str = include_str!(concat!(env!("OUT_DIR"), "/macos-versions.env"));
+const TIER_XCODE: &str = include_str!(concat!(env!("OUT_DIR"), "/macos-tier-xcode.sh"));
+const FETCH: &str = include_str!(concat!(env!("OUT_DIR"), "/macos-fetch.sh"));
+const XCODE_SOURCE: &str = include_str!(concat!(env!("OUT_DIR"), "/macos-xcode-source.sh"));
+
+/// The full macOS image `reference` is derived from when it is the developer
+/// tools image (`ghcr.io/trycua/macos:<ver>-xcode`, with or without a
+/// `@sha256:` digest, which is the published image's own and is dropped), else
+/// `None`.
+pub fn dev_parent(reference: &str) -> Option<String> {
+ let tag_ref = reference.split('@').next().unwrap_or(reference);
+ let tag = tag_ref.strip_prefix(MACOS_REPO)?.strip_prefix(':')?;
+ let version = tag.strip_suffix("-xcode")?;
+ if version.is_empty() || !version.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
+ return None;
+ }
+ Some(format!("{MACOS_REPO}:{version}"))
+}
+
+/// Whether the user asked to build from the Xcode on this Mac instead of
+/// pulling the published image (`CUA_DEV_IMAGE=local`).
+pub fn prefer_local() -> bool {
+ std::env::var("CUA_DEV_IMAGE").is_ok_and(|v| v.trim().eq_ignore_ascii_case("local"))
+}
+
+/// Errors unless this host is Apple-branded hardware with Apple silicon, the
+/// only place the image may run.
+pub fn require_apple_hardware() -> Result<()> {
+ if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
+ return Ok(());
+ }
+ Err(VmmError::UnsupportedImage {
+ image: format!("{MACOS_REPO}:26-xcode"),
+ reason: "Xcode and the iOS Simulator runtimes are Apple software under Apple's license, \
+ for use on Apple-branded hardware: the macOS Space with developer tools runs \
+ only on a Mac with Apple silicon."
+ .into(),
+ })
+}
+
+/// Whether the SDK's recorded source `reference` of a base VM is a full
+/// macOS image of `version` (`26`): `macos:26` or its dated pin
+/// `macos:26-20261021-fca2193`, with or without a digest. Not a slim, xcode
+/// or other version.
+pub fn is_full_macos_base(reference: &str, version: &str) -> bool {
+ let tag_ref = reference.split('@').next().unwrap_or(reference);
+ let Some(tag) = tag_ref
+ .strip_prefix(MACOS_REPO)
+ .and_then(|t| t.strip_prefix(':'))
+ else {
+ return false;
+ };
+ if tag == version {
+ return true;
+ }
+ let Some(pin) = tag.strip_prefix(version).and_then(|t| t.strip_prefix('-')) else {
+ return false;
+ };
+ // <yyyymmdd>-<sha7>
+ let mut parts = pin.split('-');
+ let (Some(date), Some(sha), None) = (parts.next(), parts.next(), parts.next()) else {
+ return false;
+ };
+ date.len() == 8
+ && date.bytes().all(|b| b.is_ascii_digit())
+ && sha.len() == 7
+ && sha
+ .bytes()
+ .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
+}
+
+/// Writes the recipe under `root` (`<root>/<content hash>/`, laid out as in
+/// the repository) and returns the script. Idempotent: the same recipe is
+/// written once.
+pub fn write_recipe(root: &Path) -> std::io::Result<PathBuf> {
+ use sha2::{Digest, Sha256};
+ let mut h = Sha256::new();
+ for f in [DERIVE_LOCAL, VERSIONS_ENV, TIER_XCODE, FETCH, XCODE_SOURCE] {
+ h.update((f.len() as u64).to_le_bytes());
+ h.update(f.as_bytes());
+ }
+ let id: String = h
+ .finalize()
+ .iter()
+ .take(6)
+ .map(|b| format!("{b:02x}"))
+ .collect();
+ let dir = root.join(id);
+ let script = dir.join("derive-local.sh");
+ if script.exists() {
+ return Ok(script);
+ }
+ let tmp = root.join(format!(".tmp-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ std::fs::create_dir_all(tmp.join("files"))?;
+ for (name, text) in [
+ ("derive-local.sh", DERIVE_LOCAL),
+ ("versions.env", VERSIONS_ENV),
+ ("files/tier-xcode.sh", TIER_XCODE),
+ ("files/fetch.sh", FETCH),
+ ("files/xcode-source.sh", XCODE_SOURCE),
+ ] {
+ std::fs::write(tmp.join(name), text)?;
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ for name in ["derive-local.sh", "files/tier-xcode.sh"] {
+ std::fs::set_permissions(tmp.join(name), std::fs::Permissions::from_mode(0o755))?;
+ }
+ }
+ match std::fs::rename(&tmp, &dir) {
+ Ok(()) => Ok(script),
+ // Another process wrote it first.
+ Err(_) if script.exists() => {
+ let _ = std::fs::remove_dir_all(&tmp);
+ Ok(script)
+ }
+ Err(e) => Err(e),
+ }
+}
+
+/// The progress a `[macos-dev HH:MM:SS] message` line of the script says, or
+/// `None` for any other line.
+pub fn progress_of(line: &str) -> Option<Progress> {
+ let msg = line.strip_prefix("[macos-dev ")?.split_once("] ")?.1.trim();
+ let detail = match msg {
+ m if m.starts_with("Xcode source:") => "Finding Xcode on this Mac",
+ m if m.starts_with("archiving") => "Packing Xcode for the Space",
+ m if m.starts_with("cloning") => "Cloning the macOS image",
+ m if m.starts_with("booting") => "Starting the build",
+ m if m.starts_with("installing the developer tools") => {
+ "Installing Xcode, the iOS Simulator and the developer tools"
+ }
+ m if m.starts_with("shutting down") => "Finishing",
+ m if m.starts_with("fetching") => "Downloading the developer tools",
+ _ => return None,
+ };
+ Some(Progress::phase(Phase::Creating).detail(detail))
+}
+
+/// The error for the script's exit `code` and the tail of its output.
+pub fn exit_error(code: Option<i32>, tail: &str) -> VmmError {
+ match code {
+ Some(3) => VmmError::Missing {
+ what: "Xcode".into(),
+ hint: "Apple requires a signed-in download, so Cua cannot get one for you. \
+ Install Xcode from the App Store, or download the Xcode .xip from \
+ developer.apple.com/download and put it in ~/XcodesCache, then create \
+ the macOS Space with developer tools again."
+ .into(),
+ },
+ Some(4) => VmmError::HostCapacity(message_of(tail, "Not enough free disk")),
+ Some(5) => VmmError::UnsupportedImage {
+ image: format!("{MACOS_REPO}:26-xcode"),
+ reason: message_of(tail, "The Xcode on this Mac needs a newer macOS"),
+ },
+ _ => VmmError::Command {
+ cmd: "derive-local.sh".into(),
+ code,
+ stderr: crate::exec::tail(tail, 2000),
+ },
+ }
+}
+
+/// The paragraph of `tail` that starts at the line beginning `marker`, to the
+/// end of the output (the script prints its refusal last).
+fn message_of(tail: &str, marker: &str) -> String {
+ match tail.find(marker) {
+ Some(i) => tail[i..].trim().to_string(),
+ None => tail.trim().to_string(),
+ }
+}
+
+/// One run of the build.
+pub struct Derive<'a> {
+ /// The Lume that runs the VMs.
+ pub lume: &'a LumeCmd,
+ /// Lume's VM storage directory (the base VM is there, and the result).
+ pub storage: &'a Path,
+ /// The full image's base VM to clone.
+ pub base_vm: &'a str,
+ /// The derived base VM to make.
+ pub name: &'a str,
+ /// Scratch space for staging and logs.
+ pub work: &'a Path,
+}
+
+impl Derive<'_> {
+ /// Runs the embedded recipe. Progress is reported as it goes; the script
+ /// removes a half-built VM itself.
+ pub async fn run(&self) -> Result<()> {
+ let script = write_recipe(&self.work.join("recipe"))?;
+ self.run_script(&script).await
+ }
+
+ /// [`Self::run`] with `script` as the build (tests).
+ pub async fn run_script(&self, script: &Path) -> Result<()> {
+ std::fs::create_dir_all(self.work)?;
+ let mut cmd = tokio::process::Command::new("/bin/bash");
+ cmd.arg(script)
+ .args(["--base-vm", self.base_vm, "--name", self.name, "--out"])
+ .arg(self.work.join("out"))
+ .envs(self.lume.env().iter().map(|(k, v)| (k, v)))
+ .env("CUA_LUME_BIN", self.lume.bin())
+ .env("CUA_LUME_STORAGE", self.storage)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true);
+ tracing::info!(
+ base = self.base_vm,
+ name = self.name,
+ "building the macOS Space with developer tools"
+ );
+ let mut child = cmd.spawn().map_err(|e| VmmError::Command {
+ cmd: "bash derive-local.sh".into(),
+ code: None,
+ stderr: e.to_string(),
+ })?;
+ let stderr = child.stderr.take().expect("stderr is piped");
+ let mut lines = BufReader::new(stderr).lines();
+ let mut tail: std::collections::VecDeque<String> = Default::default();
+ let read = async {
+ while let Some(line) = lines.next_line().await? {
+ if let Some(p) = progress_of(&line) {
+ crate::progress::report(p);
+ }
+ tracing::debug!(target: "cua_vmm::derive", "{line}");
+ if tail.len() == 60 {
+ tail.pop_front();
+ }
+ tail.push_back(line);
+ }
+ child.wait().await
+ };
+ let status = tokio::time::timeout(DERIVE_TIMEOUT, read)
+ .await
+ .map_err(|_| VmmError::Timeout {
+ name: self.name.to_string(),
+ secs: DERIVE_TIMEOUT.as_secs(),
+ detail: "building the macOS Space with developer tools".into(),
+ })??;
+ if status.success() {
+ return Ok(());
+ }
+ let tail: Vec<String> = tail.into_iter().collect();
+ Err(exit_error(status.code(), &tail.join("\n")))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A ref in the macOS repository, built so the image-ref gate (which wants
+ /// catalog refs) does not read these synthetic tags as image references.
+ fn m(tag: &str) -> String {
+ format!("{MACOS_REPO}:{tag}")
+ }
+
+ const D: &str = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
+
+ #[test]
+ fn the_developer_tools_image_names_its_parent() {
+ assert_eq!(dev_parent(&m("26-xcode")), Some(m("26")));
+ // The digest is the published image's own: the parent is by tag.
+ assert_eq!(dev_parent(&format!("{}@{D}", m("26-xcode"))), Some(m("26")));
+ let other_org = format!("ghcr.io/{}/macos:26-xcode", "other");
+ let other_os = format!("ghcr.io/trycua/{}:24.04-xcode", "linux");
+ for not in [
+ m("26"),
+ m("26-slim"),
+ m("-xcode"),
+ m("26-xcode-26.6"),
+ m("26-xcode-disk"),
+ other_org,
+ other_os,
+ ] {
+ assert_eq!(dev_parent(&not), None, "{not}");
+ }
+ }
+
+ #[test]
+ fn only_a_full_image_of_the_version_is_a_parent() {
+ for ok in [
+ m("26"),
+ m("26-20261021-fca2193"),
+ format!("{}@{D}", m("26-20261021-fca2193")),
+ ] {
+ assert!(is_full_macos_base(&ok, "26"), "{ok}");
+ }
+ let other_os = format!("ghcr.io/trycua/{}:26", "linux");
+ for no in [
+ m("26-slim"),
+ m("26-slim-20261021-fca2193"),
+ m("26-xcode"),
+ m("15"),
+ m("26-2026102-fca2193"),
+ m("26-20261021-FCA2193"),
+ other_os,
+ ] {
+ assert!(!is_full_macos_base(&no, "26"), "{no}");
+ }
+ }
+
+ #[test]
+ fn the_script_says_where_the_build_is() {
+ let d = |l: &str| progress_of(l).map(|p| p.detail);
+ assert_eq!(
+ d("[macos-dev 20:01:36] Xcode source: /Applications/Xcode.app").as_deref(),
+ Some("Finding Xcode on this Mac")
+ );
+ assert!(progress_of("[macos-dev 20:02:00] booting cua-dev-1").is_some());
+ assert!(
+ progress_of("[macos-dev 20:02:19] installing the developer tools (Xcode 26.6)")
+ .is_some()
+ );
+ assert!(progress_of(" ==> Rust targets").is_none());
+ assert!(progress_of("[macos-dev 20:02:00] something else").is_none());
+ }
+
+ #[test]
+ fn exits_become_messages_a_person_can_act_on() {
+ let e = exit_error(Some(3), "").to_string();
+ assert!(e.contains("Xcode is not available"), "{e}");
+ assert!(
+ e.contains("App Store") && e.contains("developer.apple.com"),
+ "{e}"
+ );
+ let tail = "[macos-dev 1] Xcode source: x\nNot enough free disk to build the macOS Space with developer tools: it needs about 30 GB.\nMake room: remove Spaces and images you no longer use.";
+ let e = exit_error(Some(4), tail).to_string();
+ assert!(e.starts_with("Not enough free disk"), "{e}");
+ assert!(e.contains("Make room"), "{e}");
+ assert!(!e.contains("Xcode source"), "{e}");
+ let e = exit_error(
+ Some(5),
+ "Xcode 27 needs macOS 27.0; this Space's macOS is 26.5.",
+ )
+ .to_string();
+ assert!(e.contains("needs macOS 27.0"), "{e}");
+ let e = exit_error(Some(1), "boom").to_string();
+ assert!(e.contains("exit Some(1)") && e.contains("boom"), "{e}");
+ }
+
+ #[test]
+ fn the_image_runs_only_on_apple_silicon_macs() {
+ let r = require_apple_hardware();
+ if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
+ assert!(r.is_ok());
+ } else {
+ let e = r.unwrap_err().to_string();
+ assert!(
+ e.contains("Apple-branded hardware") && e.contains("Apple silicon"),
+ "{e}"
+ );
+ }
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn the_embedded_recipe_is_complete_and_parses() {
+ let d = tempfile::tempdir().unwrap();
+ let script = write_recipe(d.path()).unwrap();
+ // Again: the same directory, nothing rewritten.
+ assert_eq!(write_recipe(d.path()).unwrap(), script);
+ let dir = script.parent().unwrap();
+ for f in [
+ "derive-local.sh",
+ "versions.env",
+ "files/tier-xcode.sh",
+ "files/fetch.sh",
+ ] {
+ assert!(dir.join(f).is_file(), "{f}");
+ }
+ // The layout derive-local.sh expects of the repository.
+ assert!(DERIVE_LOCAL.contains(r#"$HERE/files/fetch.sh"#));
+ assert!(DERIVE_LOCAL.contains(r#"$HERE/files/tier-xcode.sh"#));
+ for f in [
+ "derive-local.sh",
+ "files/tier-xcode.sh",
+ "files/fetch.sh",
+ "files/xcode-source.sh",
+ ] {
+ let ok = std::process::Command::new("/bin/bash")
+ .arg("-n")
+ .arg(dir.join(f))
+ .status()
+ .unwrap();
+ assert!(ok.success(), "{f} does not parse");
+ }
+ }
+
+ #[cfg(unix)]
+ async fn run_stub(body: &str) -> Result<()> {
+ let d = tempfile::tempdir().unwrap();
+ let script = d.path().join("stub.sh");
+ std::fs::write(&script, format!("#!/bin/bash\n{body}\n")).unwrap();
+ let lume = LumeCmd::plain("/usr/bin/true");
+ Derive {
+ lume: &lume,
+ storage: d.path(),
+ base_vm: "cua-base-x",
+ name: "cua-base-y",
+ work: &d.path().join("work"),
+ }
+ .run_script(&script)
+ .await
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_run_reports_progress_and_maps_the_exit() {
+ use std::sync::{Arc, Mutex};
+ let seen: Arc<Mutex<Vec<String>>> = Arc::default();
+ let sink = {
+ let seen = seen.clone();
+ move |p: &Progress| seen.lock().unwrap().push(p.detail.clone())
+ };
+ let ok = crate::progress::scope(Arc::new(sink), run_stub(
+ "echo '[macos-dev 10:00:00] cloning a -> b' >&2\necho '[macos-dev 10:00:01] installing the developer tools (Xcode 26.6)' >&2\necho \"$CUA_LUME_STORAGE|$CUA_LUME_BIN\" >&2",
+ ))
+ .await;
+ ok.unwrap();
+ let seen = seen.lock().unwrap().join("\n");
+ assert!(seen.contains("Cloning the macOS image"), "{seen}");
+ assert!(seen.contains("Installing Xcode"), "{seen}");
+
+ let e = run_stub("echo 'No Xcode' >&2\nexit 3").await.unwrap_err();
+ assert!(
+ matches!(e, VmmError::Missing { ref what, .. } if what == "Xcode"),
+ "{e:?}"
+ );
+ let e = run_stub("echo 'Not enough free disk to build: Make room' >&2\nexit 4")
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(e, VmmError::HostCapacity(ref m) if m.contains("Make room")),
+ "{e:?}"
+ );
+ let e = run_stub("exit 9").await.unwrap_err();
+ assert!(
+ matches!(e, VmmError::Command { code: Some(9), .. }),
+ "{e:?}"
+ );
+ }
+}
diff --git a/libs/cua/crates/cua-vmm/src/lume/mod.rs b/libs/cua/crates/cua-vmm/src/lume/mod.rs
index ac9095f38a..f6e187197f 100644
--- a/libs/cua/crates/cua-vmm/src/lume/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/lume/mod.rs
@@ -16,6 +16,7 @@
pub mod builtin;
pub mod client;
+pub mod derive;
pub mod gpu;
pub mod lease;
pub mod owned;
@@ -1048,6 +1049,30 @@ impl LumeRuntime {
pull_bytes: Option<u64>,
) -> Result<CheckpointInfo> {
self.ensure_serving().await?;
+ let ImageSource::Oci { reference } = image else {
+ return Err(VmmError::invalid(
+ "lume bases are pulled from OCI references",
+ ));
+ };
+ // The macOS Space with developer tools: the published image is pulled
+ // like any other; building it here is the fallback.
+ if let Some(parent) = derive::dev_parent(reference) {
+ return self
+ .ensure_dev_base(reference, base_name, &parent, creds, pull_bytes)
+ .await;
+ }
+ self.pull_base(image, base_name, creds, pull_bytes).await
+ }
+
+ /// Pulls `image` into the stopped base VM `base_name` (the pull half of
+ /// [`Self::ensure_base_sized`]).
+ async fn pull_base(
+ &self,
+ image: &ImageSource,
+ base_name: &str,
+ creds: Option<&RegistryCredentials>,
+ pull_bytes: Option<u64>,
+ ) -> Result<CheckpointInfo> {
let ImageSource::Oci { reference } = image else {
return Err(VmmError::invalid(
"lume bases are pulled from OCI references",
@@ -1117,6 +1142,139 @@ impl LumeRuntime {
))
}
+ /// The base VM of the macOS Space with developer tools `reference`
+ /// (`ghcr.io/trycua/macos:26-xcode`, [`derive`]). The default is to pull
+ /// the published image, with the usual progress and disk check. When it
+ /// is not available (not published yet, no network to it), or the user
+ /// prefers the Xcode already on this Mac (`CUA_DEV_IMAGE=local`), it is
+ /// built here as a clone of the full image's base plus that Xcode. Either
+ /// way every Space is a clone of the one base.
+ async fn ensure_dev_base(
+ &self,
+ reference: &str,
+ base_name: &str,
+ parent: &str,
+ creds: Option<&RegistryCredentials>,
+ pull_bytes: Option<u64>,
+ ) -> Result<CheckpointInfo> {
+ derive::require_apple_hardware()?;
+ // One at a time in this process: two Spaces asked for together wait
+ // for the first, then both clone it.
+ static BUILD: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+ let _one_at_a_time = BUILD.lock().await;
+ let info =
+ || CheckpointInfo::now(base_name, BackendKind::Lume, Some(reference.to_string()));
+ if let Some(vm) = self.client.get(base_name).await? {
+ if vm.status == "running" {
+ return Err(VmmError::invalid(format!(
+ "base VM '{base_name}' is running; stop it before using it as a clone source"
+ )));
+ }
+ if vm.status != "pulling" {
+ OwnedVms::default().touch(base_name);
+ return Ok(info());
+ }
+ }
+ if !derive::prefer_local() {
+ let image = ImageSource::Oci {
+ reference: reference.to_string(),
+ };
+ match self.pull_base(&image, base_name, creds, pull_bytes).await {
+ Ok(done) => return Ok(done),
+ // Not enough disk is the same for a build: say so.
+ Err(e @ VmmError::InsufficientDisk(_)) => return Err(e),
+ Err(e) => {
+ tracing::warn!(error = %e, "the published macOS Space with developer tools is not available; building it on this Mac");
+ crate::progress::report(
+ crate::progress::Progress::phase(crate::progress::Phase::Creating).detail(
+ "The published image is not available; building it on this Mac",
+ ),
+ );
+ }
+ }
+ }
+ // The full image the build starts from: a base the SDK already holds
+ // for this macOS version (no second download), else the image itself.
+ let version = parent
+ .split('@')
+ .next()
+ .and_then(|t| t.rsplit_once(':'))
+ .map(|(_, v)| v)
+ .unwrap_or("26");
+ let owned = OwnedVms::default();
+ let mut held = owned
+ .list()
+ .into_iter()
+ .filter(|o| {
+ o.kind == OwnedKind::Base
+ && o.source
+ .as_deref()
+ .is_some_and(|s| derive::is_full_macos_base(s, version))
+ })
+ .collect::<Vec<_>>();
+ held.sort_by_key(|o| std::cmp::Reverse(o.last_used));
+ let mut parent_base = None;
+ for o in &held {
+ if matches!(self.client.get(&o.name).await?, Some(vm) if vm.status == "stopped") {
+ parent_base = Some(o.name.clone());
+ break;
+ }
+ }
+ let parent_base = match parent_base {
+ Some(b) => b,
+ None => {
+ let b = base_vm_name(parent);
+ Box::pin(self.ensure_base_sized(
+ &ImageSource::Oci {
+ reference: parent.to_string(),
+ },
+ &b,
+ creds,
+ pull_bytes,
+ ))
+ .await?;
+ b
+ }
+ };
+ crate::disk::ensure_space(
+ &self.vm_dir(),
+ derive::DEV_IMAGE_ESTIMATE,
+ "build the macOS Space with developer tools",
+ )?;
+ let lume = self.lume()?.ok_or_else(|| {
+ VmmError::missing(
+ "lume",
+ "binary needed to build the macOS Space with developer tools",
+ )
+ })?;
+ crate::progress::report(
+ crate::progress::Progress::phase(crate::progress::Phase::Creating)
+ .detail("Building the macOS Space with developer tools (first time only)"),
+ );
+ // Recorded before the build, as for a pull: a build cut off still
+ // leaves a VM the cache GC may remove; a failed one's record goes.
+ owned.mark(base_name, OwnedKind::Base, Some(reference));
+ let work = host::cua_home().join("vmm").join("lume").join("derive");
+ let built = derive::Derive {
+ lume: &lume,
+ storage: &self.vm_dir(),
+ base_vm: &parent_base,
+ name: base_name,
+ work: &work,
+ }
+ .run()
+ .await;
+ if let Err(e) = built {
+ if !matches!(self.client.get(base_name).await, Ok(Some(_))) {
+ owned.forget(base_name);
+ }
+ return Err(e);
+ }
+ owned.mark(base_name, OwnedKind::Base, Some(reference));
+ owned.touch(&parent_base);
+ Ok(info())
+ }
+
/// Installs the start spec's workload environment in a booted macOS
/// guest ([`apply_macos_env`]), or clears one an earlier start installed.
/// Nothing happens (no SSH round trip) when neither applies. `exec` is
@@ -1598,9 +1756,22 @@ impl LumeRuntime {
{
return Err(VmmError::invalid(why));
}
- crate::types::reject_restricted_network(BackendKind::Lume, spec)?;
+ // Under the secure default a macOS VM can't be protected yet (it
+ // shares Apple's NAT), and cua reaches it over that network, so a
+ // VM without one could never answer: only No protection starts it.
+ match crate::network::gate(
+ BackendKind::Lume,
+ &spec.name,
+ &crate::network::spec_settings(spec),
+ )? {
+ Some(crate::network::NetworkPlan::Open { .. }) => {}
+ Some(_) => return Err(VmmError::Other(crate::network::WHY_LUME.into())),
+ None => {
+ crate::types::reject_restricted_network(BackendKind::Lume, spec)?;
+ crate::egress::check(BackendKind::Lume, &spec.egress)?;
+ }
+ }
crate::types::reject_injection(BackendKind::Lume, spec)?;
- crate::egress::check(BackendKind::Lume, &spec.egress)?;
if macos_guest(spec) {
macos_mount_shares(&spec.mounts)?;
} else {
diff --git a/libs/cua/crates/cua-vmm/src/managed.rs b/libs/cua/crates/cua-vmm/src/managed.rs
index 4ea44adfc4..b87bf9d1d3 100644
--- a/libs/cua/crates/cua-vmm/src/managed.rs
+++ b/libs/cua/crates/cua-vmm/src/managed.rs
@@ -1733,6 +1733,15 @@ mod engine_impl {
self.engine().await?.set_egress(name, policy).await
}
+ async fn set_network(
+ &self,
+ name: &str,
+ settings: &crate::network::NetworkSettings,
+ ) -> Result<crate::network::Applied> {
+ let _busy = self.busy();
+ self.engine().await?.set_network(name, settings).await
+ }
+
async fn egress(&self, name: &str) -> Result<crate::egress::EgressPolicy> {
Ok(crate::container::egress::kept(name)
.map(|k| k.policy)
diff --git a/libs/cua/crates/cua-vmm/src/microvm/mod.rs b/libs/cua/crates/cua-vmm/src/microvm/mod.rs
index 03b91edd38..de3f09c3b6 100644
--- a/libs/cua/crates/cua-vmm/src/microvm/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/microvm/mod.rs
@@ -280,6 +280,10 @@ pub struct VmState {
/// the VM's network namespace from its first instruction.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub egress: Option<crate::egress::EgressPolicy>,
+ /// Its network settings ([`crate::network`]); `None`: kept from before
+ /// them (its policy is migrated at boot).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub network: Option<crate::network::NetworkSettings>,
/// The network's process: `pasta` (Linux) or gvproxy (macOS).
#[serde(default)]
pub pasta_pid: Option<u32>,
@@ -373,6 +377,9 @@ pub struct SnapshotMeta {
/// The source's egress policy: forks inherit it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub egress: Option<crate::egress::EgressPolicy>,
+ /// The source's network settings: forks inherit them.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub network: Option<crate::network::NetworkSettings>,
/// Memory and device state were saved (else only the disk: a fork
/// boots it cold).
pub memory: bool,
@@ -500,6 +507,56 @@ fn boot_args() -> String {
)
}
+/// Whether a Vz microVM boots with no network: always under the secure
+/// default (a Mac has no point to enforce rules yet) unless the user chose
+/// No protection; else only when asked (`network=none`).
+fn vz_no_network(st: &VmState) -> Result<bool> {
+ let settings = st.network.clone().unwrap_or_else(|| {
+ crate::network::NetworkSettings::migrate(
+ &st.egress.clone().unwrap_or_default(),
+ st.restrict_network,
+ )
+ });
+ Ok(
+ match crate::network::gate(BackendKind::Vz, &st.name, &settings)? {
+ Some(crate::network::NetworkPlan::Open { .. }) => false,
+ Some(_) => true,
+ None => st.restrict_network,
+ },
+ )
+}
+
+/// The rules a Firecracker VM's namespace enforces: under the secure
+/// default ([`crate::network`]) its settings compiled with
+/// [`fc_context`], else its old policy alone.
+fn fc_rules(st: &VmState) -> Result<crate::egress::Rules> {
+ crate::network::vm_rules(
+ st.network.as_ref(),
+ st.egress.as_ref(),
+ st.restrict_network,
+ &fc_context(),
+ )
+ .map_err(VmmError::from)
+}
+
+/// What a Firecracker VM's namespace knows: the guest's resolver is its
+/// gateway on 53 (the namespace sends it on to pasta's DNS forward; rules
+/// judge the address the guest sent), which is otherwise closed like the
+/// host's own addresses (pasta would reach them) and the daemon's ports.
+/// The host's loopback is not mapped (`--no-map-gw`).
+fn fc_context() -> crate::network::NetworkContext {
+ use cua_microvm_init::GATEWAY_IP;
+ let gw: std::net::IpAddr = GATEWAY_IP.parse().expect("a valid gateway");
+ crate::network::NetworkContext {
+ resolvers: vec![gw],
+ host_aliases: vec![gw],
+ host_addrs: crate::network::host_addresses(),
+ tree: vec![],
+ other_trees: vec![],
+ daemon_ports: crate::network::daemon_ports(),
+ }
+}
+
/// The script run inside the VM's namespace (by `pasta`): the tap device,
/// NAT, port forwards and DNS, then `exec firecracker`.
fn net_script(
@@ -507,6 +564,7 @@ fn net_script(
restrict: bool,
config: bool,
egress: &crate::egress::Rules,
+ localhost: &[u16],
) -> String {
use cua_microvm_init::{GATEWAY_IP, GUEST_IP, PREFIX_LEN};
let mut nat = String::from("*nat\n");
@@ -515,6 +573,13 @@ fn net_script(
"-A OUTPUT -d 127.0.0.1/32 -p tcp --dport {p} -j DNAT --to-destination {GUEST_IP}:{p}\n"
));
}
+ // The `localhost` preset's ports: the guest's gateway on them is the
+ // namespace's loopback, which pasta forwards to the host's (`-T`).
+ for p in localhost {
+ nat.push_str(&format!(
+ "-A PREROUTING -d {GATEWAY_IP}/32 -p tcp --dport {p} -j DNAT --to-destination 127.0.0.1:{p}\n"
+ ));
+ }
nat.push_str(&format!(
"-A POSTROUTING -d {GUEST_IP}/32 -j MASQUERADE\n\
-A PREROUTING -d {GATEWAY_IP}/32 -p udp --dport 53 -j DNAT --to-destination {DNS_FWD}:53\n\
@@ -1118,17 +1183,16 @@ impl MicroVmRuntime {
if let Some(c) = &config {
std::fs::write(dir.join("vm.json"), serde_json::to_vec_pretty(c)?)?;
}
+ let localhost =
+ crate::network::vm_localhost_ports(st.network.as_ref()).map_err(VmmError::from)?;
std::fs::write(
dir.join("net.sh"),
net_script(
&st.ports,
st.restrict_network,
config.is_some(),
- &st.egress
- .as_ref()
- .map(|p| p.parse())
- .transpose()?
- .unwrap_or_default(),
+ &fc_rules(st)?,
+ &localhost,
),
)?;
let host_ports = self.pick_ports(st.ports.len())?;
@@ -1140,7 +1204,7 @@ impl MicroVmRuntime {
"-u".into(),
"none".into(),
"-T".into(),
- "none".into(),
+ crate::network::pasta_out_spec(&localhost),
"-U".into(),
"none".into(),
"--dns-forward".into(),
@@ -1261,6 +1325,8 @@ impl MicroVmRuntime {
it in ~/.cua/bin (libs/cua/vz/build.sh builds it)",
)
})?;
+ // No network when asked, and on a Mac under the secure default
+ // unless the user chose No protection (`boot` decided).
let gvproxy = if st.restrict_network {
None
} else {
@@ -1522,6 +1588,20 @@ impl MicroVmRuntime {
/// snapshot of the same configuration (a fresh VM only), else a cold
/// boot (which records the golden snapshot when warm starts are on).
async fn boot(&self, st: &mut VmState, fresh: bool, timeout: Duration) -> Result<()> {
+ if self.cfg.vmm == Vmm::Vz {
+ // Decided before anything keys on it (golden snapshots, the
+ // monitor's config): a Mac has no point to enforce rules yet, so
+ // no network unless the user chose No protection.
+ if st.network.is_none()
+ && crate::network::Mode::from_env() == crate::network::Mode::Secure
+ {
+ st.network = Some(crate::network::NetworkSettings::migrate(
+ &st.egress.clone().unwrap_or_default(),
+ st.restrict_network,
+ ));
+ }
+ st.restrict_network = vz_no_network(st)?;
+ }
if let Some(snap) = st.restore_from.clone() {
self.restore(st, &snap, timeout, "restore").await?;
st.restore_from = None;
@@ -1935,6 +2015,7 @@ impl MicroVmRuntime {
probes: st.probes.clone(),
restrict_network: st.restrict_network,
egress: st.egress.clone(),
+ network: st.network.clone(),
memory: true,
created_at: host::now_secs(),
pinned: false,
@@ -2132,6 +2213,7 @@ impl MicroVmRuntime {
probes: meta.probes.clone(),
restrict_network: meta.restrict_network,
egress: meta.egress.clone(),
+ network: meta.network.clone(),
pasta_pid: None,
fc_pid: None,
sock_id: None,
@@ -2161,6 +2243,7 @@ impl MicroVmRuntime {
probes: st.probes.clone(),
restrict_network: st.restrict_network,
egress: st.egress.clone(),
+ network: st.network.clone(),
memory,
created_at: host::now_secs(),
pinned: false,
@@ -2270,6 +2353,7 @@ impl Runtime for MicroVmRuntime {
probes: vec![],
restrict_network: false,
egress: None,
+ network: None,
memory: false,
created_at: host::now_secs(),
pinned: false,
@@ -2293,7 +2377,17 @@ impl Runtime for MicroVmRuntime {
}
reject_sidecars(self.cfg.vmm.backend(), spec)?;
crate::types::reject_mounts(self.cfg.vmm.backend(), spec)?;
- crate::egress::check(self.cfg.vmm.backend(), &spec.egress)?;
+ // Under the secure default a Vz microVM starts without network
+ // instead of refusing its lists (`vz_no_network`).
+ if crate::network::gate(
+ self.cfg.vmm.backend(),
+ &spec.name,
+ &crate::network::spec_settings(spec),
+ )?
+ .is_none()
+ {
+ crate::egress::check(self.cfg.vmm.backend(), &spec.egress)?;
+ }
reject_gpu(self.cfg.vmm.backend(), spec, &[])?;
if spec.arch.is_some_and(|a| a != Arch::host()) {
return Err(VmmError::invalid(format!(
@@ -2335,6 +2429,10 @@ impl Runtime for MicroVmRuntime {
if st.egress.is_none() && !spec.egress.is_empty() {
st.egress = Some(spec.egress.clone());
}
+ // Network settings too (one from before them takes the spec's).
+ if st.network.is_none() {
+ st.network = spec.network.clone();
+ }
self.kill(&mut st);
let _vcpus = self.reserve_vcpus(st.cpus)?;
if let Err(e) = self.boot(&mut st, false, spec.ready_timeout).await {
@@ -2378,6 +2476,7 @@ impl Runtime for MicroVmRuntime {
probes: spec.probes.clone(),
restrict_network: spec.restrict_network,
egress: (!spec.egress.is_empty()).then(|| spec.egress.clone()),
+ network: spec.network.clone(),
pasta_pid: None,
fc_pid: None,
sock_id: None,
@@ -2628,13 +2727,21 @@ impl Runtime for MicroVmRuntime {
name: &str,
policy: &crate::egress::EgressPolicy,
) -> Result<crate::egress::Enforcement> {
- let rules = crate::egress::check(self.cfg.vmm.backend(), policy)?;
+ crate::egress::check(self.cfg.vmm.backend(), policy)?;
let lock = self.lock_for(name);
let _g = lock.lock().await;
let mut st = self.load(name)?;
if st.kind != EntryKind::Instance {
return Err(VmmError::invalid(format!("{name} is not a VM")));
}
+ // The lists are its network settings' own lists too.
+ let network = crate::network::NetworkSettings::with_lists(st.network.clone(), policy);
+ let candidate = VmState {
+ egress: Some(policy.clone()),
+ network: Some(network.clone()),
+ ..st.clone()
+ };
+ let rules = fc_rules(&candidate)?;
if self.running(&st) {
let pid = st
.fc_pid
@@ -2646,6 +2753,7 @@ impl Runtime for MicroVmRuntime {
.await?;
}
st.egress = Some(policy.clone());
+ st.network = Some(network);
self.save(&st)?;
Ok(crate::egress::Enforcement::Host)
}
@@ -2654,6 +2762,46 @@ impl Runtime for MicroVmRuntime {
Ok(self.load(name)?.egress.unwrap_or_default())
}
+ /// Kept with the VM. A running Firecracker VM's namespace rules are
+ /// refilled at once (its localhost ports change at its next start); a
+ /// Vz microVM gets them at its next start.
+ async fn set_network(
+ &self,
+ name: &str,
+ settings: &crate::network::NetworkSettings,
+ ) -> Result<crate::network::Applied> {
+ settings.validate()?;
+ let lock = self.lock_for(name);
+ let _g = lock.lock().await;
+ let mut st = self.load(name)?;
+ if st.kind != EntryKind::Instance {
+ return Err(VmmError::invalid(format!("{name} is not a VM")));
+ }
+ let ports_change = crate::network::vm_localhost_ports(st.network.as_ref()).ok()
+ != crate::network::vm_localhost_ports(Some(settings)).ok();
+ st.network = Some(settings.clone());
+ st.egress = Some(settings.custom.clone());
+ let applied = if self.cfg.vmm == Vmm::Firecracker && self.running(&st) {
+ let pid = st
+ .fc_pid
+ .ok_or_else(|| VmmError::other(format!("{name}: no firecracker process")))?;
+ crate::egress::ns_apply(
+ pid,
+ &crate::egress::ns_script(&fc_rules(&st)?, crate::egress::NsHook::Tap(TAP), None),
+ )
+ .await?;
+ if ports_change {
+ crate::network::Applied::NextStart
+ } else {
+ crate::network::Applied::Now
+ }
+ } else {
+ crate::network::Applied::NextStart
+ };
+ self.save(&st)?;
+ Ok(applied)
+ }
+
async fn checkpoint(&self, name: &str, checkpoint: &str) -> Result<CheckpointInfo> {
validate_name(checkpoint)?;
let target = self.checkpoint_dir(checkpoint);
@@ -2889,7 +3037,7 @@ mod tests {
#[test]
fn the_namespace_script_forwards_ports_and_nats_egress() {
let none = crate::egress::Rules::default();
- let s = net_script(&[3211, 8080], false, true, &none);
+ let s = net_script(&[3211, 8080], false, true, &none, &[]);
assert!(s.contains("--dport 3211 -j DNAT --to-destination 172.16.0.2:3211"));
assert!(s.contains("--dport 8080 -j DNAT"));
assert!(s.contains("-s 172.16.0.2/32 ! -d 172.16.0.1/30 -j MASQUERADE"));
@@ -2902,7 +3050,7 @@ mod tests {
assert!(s.contains(":CUA_EGRESS - [0:0]\n"), "{s}");
assert!(s.contains("-A FORWARD -i tap0 -j CUA_EGRESS\n-A INPUT -i tap0 -j CUA_EGRESS\n"));
assert!(!s.contains("-A CUA_EGRESS"), "{s}");
- let r = net_script(&[], true, false, &none);
+ let r = net_script(&[], true, false, &none, &[]);
assert!(!r.contains("-s 172.16.0.2/32 ! -d"), "no egress NAT");
assert!(r.contains("-A FORWARD -s 172.16.0.2/32 -j DROP"));
// network=none drops before the egress chain could accept.
@@ -2916,7 +3064,7 @@ mod tests {
allow: vec!["1.1.1.1".into()],
deny: vec!["all".into()],
};
- let e = net_script(&[3211], false, true, &p.parse().unwrap());
+ let e = net_script(&[3211], false, true, &p.parse().unwrap(), &[]);
assert!(
e.contains("-A CUA_EGRESS -m conntrack --ctdir REPLY -j ACCEPT"),
"{e}"
@@ -2934,6 +3082,41 @@ mod tests {
assert!(r.contains("exec \"$CUA_FIRECRACKER_BIN\" --api-sock api.sock\n"));
}
+ #[test]
+ fn the_secure_default_closes_the_host_and_keeps_dns_through_the_gateway() {
+ let mut ctx = fc_context();
+ ctx.host_addrs = vec!["10.0.1.5".parse().unwrap()];
+ ctx.daemon_ports = vec![4100];
+ let mut lh =
+ crate::network::NetworkSettings::preset(crate::network::NetworkPreset::Localhost);
+ lh.localhost_ports = vec![5432];
+ let rules = crate::network::compile_mode(&lh, &ctx, crate::network::Mode::Secure).unwrap();
+ let s = net_script(&[3211], false, true, &rules, &[5432]);
+ // DNS to the gateway is open; the gateway otherwise is closed, but
+ // for the localhost port, which goes to the host's loopback.
+ assert!(
+ s.contains(
+ "-p udp -m conntrack --ctorigdst 172.16.0.1/32 --ctorigdstport 53 -j ACCEPT"
+ ),
+ "{s}"
+ );
+ assert!(
+ s.contains(
+ "-p tcp -m conntrack --ctorigdst 172.16.0.1/32 --ctorigdstport 5432 -j ACCEPT"
+ ),
+ "{s}"
+ );
+ assert!(s.contains("--ctorigdst 172.16.0.1/32 -j DROP"), "{s}");
+ assert!(
+ s.contains("-A PREROUTING -d 172.16.0.1/32 -p tcp --dport 5432 -j DNAT --to-destination 127.0.0.1:5432"),
+ "{s}"
+ );
+ // The host's own address and every namespace-local one are closed.
+ assert!(s.contains("--ctorigdst 10.0.1.5/32 -j DROP"), "{s}");
+ assert!(s.contains("-m addrtype --dst-type LOCAL -j DROP"), "{s}");
+ assert!(s.contains("--ctorigdst 169.254.169.254/32 -j DROP"), "{s}");
+ }
+
#[test]
fn busy_time_comes_from_proc_stat() {
let s = "cpu 100 5 50 1000 20 3 2 0 0 0\ncpu0 1 2 3 4\n";
@@ -3075,6 +3258,7 @@ mod tests {
probes: vec![Probe::tcp(3211)],
restrict_network: false,
egress: None,
+ network: None,
memory: false,
created_at: 0,
pinned: false,
@@ -3124,6 +3308,7 @@ mod tests {
probes: vec![],
restrict_network: false,
egress: None,
+ network: None,
memory: false,
created_at: 0,
pinned: false,
@@ -3176,6 +3361,7 @@ mod tests {
probes: vec![],
restrict_network: false,
egress: None,
+ network: None,
memory: false,
created_at: 0,
pinned: false,
diff --git a/libs/cua/crates/cua-vmm/src/network.rs b/libs/cua/crates/cua-vmm/src/network.rs
new file mode 100644
index 0000000000..e09500dd8a
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/src/network.rs
@@ -0,0 +1,1163 @@
+//! Network settings of a Space: a preset, the user's own lists, and what
+//! the host compiles them to ([`compile`] → [`Rules`]).
+//!
+//! **Presets.** [`NetworkPreset::Internet`] is the default: the public
+//! internet and the Space's own tree. [`NetworkPreset::None`] reaches
+//! nothing. [`NetworkPreset::Localhost`] and [`NetworkPreset::Lan`] add the
+//! host's loopback (on listed ports) or the local network.
+//! [`NetworkPreset::Custom`] starts from `internet` or `none` and adds the
+//! user's allow and deny lists. [`NetworkPreset::Unprotected`] opens
+//! everything but the platform denies.
+//!
+//! **Layers**, first match wins ([`compile`]):
+//!
+//! 1. Platform denies, always (also for `unprotected`): cloud metadata
+//! endpoints, other trees' Spaces, the daemon's ports on the host.
+//! 2. The runtime's resolver on port 53.
+//! 3. The host itself: its loopback through the runtime's aliases, its own
+//! addresses, and every address local to the enforcing point (a
+//! [`Rule::host_local`] rule: nft `fib daddr type local`, iptables
+//! `addrtype LOCAL`). Only the `localhost` preset opens the aliases, and
+//! only on the ports it lists. A custom allow does not lift these, so a
+//! child can never reach the host past its parent through a numeric
+//! allow. Then the Space's own tree is allowed.
+//! 4. The user's allow list, then deny list (an allow is an exception to a
+//! deny, as before). User rules never beat layers 1 to 3.
+//! 5. Default denies: private, link-local, CGNAT, loopback, multicast and
+//! other reserved ranges (`lan` lifts the private and link-local ones).
+//! 6. Default action: accept, or drop for `none` and `custom` from `none`.
+//!
+//! **Trees.** A child Space's settings are the intersection of its own and
+//! its parent's ([`NetworkSettings::intersect`]): it can only tighten.
+//!
+//! **Fail closed.** [`network_support`] answers, for every runtime, host OS
+//! and placement, whether the runtime enforces the rules, can only run the
+//! Space without network, or refuses it. [`plan`] turns settings and that
+//! answer into what a start does; nothing but `unprotected` ever starts
+//! less strict than asked.
+//!
+//! **Experiment.** All of this is the Secure Spaces experiment, off until
+//! it is turned on (`cua experiments enable secure-spaces`). Off, Spaces
+//! keep the old open default ([`Mode::Legacy`]). `CUA_SECURE_DEFAULT=1` or
+//! `=0` forces one or the other for a process.
+
+use std::net::IpAddr;
+
+use serde::{Deserialize, Serialize};
+
+use crate::egress::{EgressPolicy, Net, PolicyError, Proto, Reason, Rule, Rules};
+use crate::types::BackendKind;
+
+/// A Space's network preset.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum NetworkPreset {
+ /// The public internet and the Space's own tree (the default).
+ #[default]
+ Internet,
+ /// No network.
+ None,
+ /// `internet`, plus the host's loopback on listed ports.
+ Localhost,
+ /// `internet`, plus the local network.
+ Lan,
+ /// `internet` or `none`, plus the user's allow and deny lists.
+ Custom,
+ /// Everything but the platform denies.
+ Unprotected,
+}
+
+impl NetworkPreset {
+ /// Every preset.
+ pub const ALL: [NetworkPreset; 6] = [
+ NetworkPreset::Internet,
+ NetworkPreset::None,
+ NetworkPreset::Localhost,
+ NetworkPreset::Lan,
+ NetworkPreset::Custom,
+ NetworkPreset::Unprotected,
+ ];
+
+ /// The word the CLI, SDK and JSON use (`internet`).
+ pub fn as_str(self) -> &'static str {
+ match self {
+ NetworkPreset::Internet => "internet",
+ NetworkPreset::None => "none",
+ NetworkPreset::Localhost => "localhost",
+ NetworkPreset::Lan => "lan",
+ NetworkPreset::Custom => "custom",
+ NetworkPreset::Unprotected => "unprotected",
+ }
+ }
+
+ /// The name people see ("Internet only").
+ pub fn label(self) -> &'static str {
+ match self {
+ NetworkPreset::Internet => "Internet only",
+ NetworkPreset::None => "No network",
+ NetworkPreset::Localhost => "Allow this computer's localhost",
+ NetworkPreset::Lan => "Allow my local network",
+ NetworkPreset::Custom => "Custom",
+ NetworkPreset::Unprotected => "No protection",
+ }
+ }
+
+ /// Parses a preset word (case-insensitive). `default` is `internet`,
+ /// as the old `network="default"` was.
+ pub fn parse(text: &str) -> Result<NetworkPreset, PolicyError> {
+ let t = text.trim().to_ascii_lowercase();
+ if t == "default" {
+ return Ok(NetworkPreset::Internet);
+ }
+ NetworkPreset::ALL
+ .into_iter()
+ .find(|p| p.as_str() == t)
+ .ok_or_else(|| {
+ PolicyError(format!(
+ "network {text:?}: expected internet, none, localhost, lan, custom or \
+ unprotected"
+ ))
+ })
+ }
+}
+
+impl std::fmt::Display for NetworkPreset {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(self.as_str())
+ }
+}
+
+/// Most ports the `localhost` preset lists.
+pub const MAX_LOCALHOST_PORTS: usize = 64;
+
+/// A Space's network settings: stored with the Space, carried to its
+/// runtime in the start spec, and compiled to [`Rules`] by [`compile`].
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct NetworkSettings {
+ /// The preset.
+ #[serde(default)]
+ pub preset: NetworkPreset,
+ /// `localhost`: the host loopback ports the Space may reach. Empty is
+ /// refused unless `all_localhost_ports`.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub localhost_ports: Vec<u16>,
+ /// `localhost`: every port of the host's loopback (the daemon's stay
+ /// blocked).
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub all_localhost_ports: bool,
+ /// The user's allow and deny lists: what `custom` adds to its base, and
+ /// what any other preset adds on top.
+ #[serde(default, skip_serializing_if = "EgressPolicy::is_empty")]
+ pub custom: EgressPolicy,
+ /// What `custom` starts from: `internet` or `none`.
+ #[serde(default)]
+ pub custom_base: NetworkPreset,
+ /// Set when the Space was allowed more than its parent (`--widen`):
+ /// who and when (`user@2026-10-26T12:00:00Z`).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub widened_by: Option<String>,
+}
+
+impl NetworkSettings {
+ /// Settings with `preset` and nothing else.
+ pub fn preset(preset: NetworkPreset) -> NetworkSettings {
+ NetworkSettings {
+ preset,
+ ..Default::default()
+ }
+ }
+
+ /// The default: `internet`.
+ pub fn internet() -> NetworkSettings {
+ NetworkSettings::preset(NetworkPreset::Internet)
+ }
+
+ /// `none`.
+ pub fn none() -> NetworkSettings {
+ NetworkSettings::preset(NetworkPreset::None)
+ }
+
+ /// Checks the settings: the lists parse, `custom_base` is `internet` or
+ /// `none`, and `localhost` names its ports (or says all).
+ pub fn validate(&self) -> Result<(), PolicyError> {
+ self.custom.parse()?;
+ if !matches!(
+ self.custom_base,
+ NetworkPreset::Internet | NetworkPreset::None
+ ) {
+ return Err(PolicyError(format!(
+ "custom starts from internet or none, not {}",
+ self.custom_base
+ )));
+ }
+ if self.preset == NetworkPreset::None && !self.custom.is_empty() {
+ return Err(PolicyError(
+ "no network takes no allow or deny list; use custom from none to allow a few \
+ destinations"
+ .into(),
+ ));
+ }
+ let localhost = self.preset == NetworkPreset::Localhost;
+ if !localhost && (!self.localhost_ports.is_empty() || self.all_localhost_ports) {
+ return Err(PolicyError(
+ "localhost ports go with the localhost preset".into(),
+ ));
+ }
+ if localhost && self.localhost_ports.is_empty() && !self.all_localhost_ports {
+ return Err(PolicyError(
+ "the localhost preset needs the ports to open (localhost:5432,3000), or all \
+ ports said explicitly"
+ .into(),
+ ));
+ }
+ if self.localhost_ports.contains(&0) {
+ return Err(PolicyError("localhost port 0 is not a port".into()));
+ }
+ if self.localhost_ports.len() > MAX_LOCALHOST_PORTS {
+ return Err(PolicyError(format!(
+ "{} localhost ports: at most {MAX_LOCALHOST_PORTS}",
+ self.localhost_ports.len()
+ )));
+ }
+ Ok(())
+ }
+
+ /// What the preset starts from, `custom` resolved: `none` for `none`
+ /// and `custom` from `none`, the preset itself otherwise.
+ pub fn base(&self) -> NetworkPreset {
+ match self.preset {
+ NetworkPreset::Custom => self.custom_base,
+ p => p,
+ }
+ }
+
+ /// Whether a connection no rule names is dropped.
+ pub fn default_drops(&self) -> bool {
+ self.base() == NetworkPreset::None
+ }
+
+ /// The settings an existing Space gets from what it was created with
+ /// before network settings existed (migration): `network=none` is
+ /// `none`, an egress policy is `custom` from `internet` with its lists
+ /// kept, nothing is `internet`.
+ pub fn migrate(egress: &EgressPolicy, restrict_network: bool) -> NetworkSettings {
+ if restrict_network {
+ // The old `none` cut everything, whatever the lists said.
+ return NetworkSettings::none();
+ }
+ if egress.is_empty() {
+ return NetworkSettings::internet();
+ }
+ NetworkSettings {
+ preset: NetworkPreset::Custom,
+ custom: egress.clone(),
+ custom_base: NetworkPreset::Internet,
+ ..Default::default()
+ }
+ }
+
+ /// The settings the old create options ask for: `network=none` and an
+ /// egress policy (the same mapping as [`NetworkSettings::migrate`]).
+ pub fn from_legacy(egress: &EgressPolicy, restrict_network: bool) -> NetworkSettings {
+ NetworkSettings::migrate(egress, restrict_network)
+ }
+
+ /// These settings with `policy` as their lists (a legacy
+ /// `set_egress`): `internet` with lists becomes `custom` from
+ /// `internet`, `none` with lists `custom` from `none`, and `custom`
+ /// without lists goes back to its base.
+ pub fn with_lists(settings: Option<NetworkSettings>, policy: &EgressPolicy) -> NetworkSettings {
+ use NetworkPreset as P;
+ let mut s = settings.unwrap_or_else(NetworkSettings::internet);
+ s.custom = policy.clone();
+ match s.preset {
+ P::Internet | P::None if !policy.is_empty() => {
+ s.custom_base = s.preset;
+ s.preset = P::Custom;
+ }
+ P::Custom if policy.is_empty() => {
+ s.preset = s.custom_base;
+ s.custom_base = P::Internet;
+ }
+ _ => {}
+ }
+ s
+ }
+
+ /// What these settings open beyond `internet`, one plain line each
+ /// ("Allows your local network (192.168.1.0/24)"). Empty for `internet`
+ /// and anything stricter.
+ pub fn widenings(&self) -> Vec<String> {
+ let mut out = Vec::new();
+ match self.preset {
+ NetworkPreset::Lan => out.push("Allows your local network".to_string()),
+ NetworkPreset::Localhost if self.all_localhost_ports => {
+ out.push("Allows this computer's localhost (all ports)".to_string())
+ }
+ NetworkPreset::Localhost => out.push(format!(
+ "Allows this computer's localhost (ports {})",
+ join_ports(&self.localhost_ports)
+ )),
+ NetworkPreset::Unprotected => {
+ out.push("No protection: allows everything but cloud metadata".to_string())
+ }
+ NetworkPreset::Internet | NetworkPreset::None | NetworkPreset::Custom => {}
+ }
+ if let Ok(rules) = self.custom.parse() {
+ for r in rules.rules.iter().filter(|r| r.accept) {
+ let lan = default_lan().iter().any(|n| n.overlaps(&r.net));
+ let reserved = default_reserved().iter().any(|n| n.overlaps(&r.net));
+ if lan {
+ out.push(format!("Allows your local network ({})", r.net.cidr()));
+ } else if reserved {
+ out.push(format!("Allows a reserved range ({})", r.net.cidr()));
+ }
+ }
+ }
+ out
+ }
+
+ /// One plain line for people ("Internet only", "Allow this computer's
+ /// localhost (ports 5432, 3000)").
+ pub fn summary(&self) -> String {
+ match self.preset {
+ NetworkPreset::Localhost if self.all_localhost_ports => {
+ format!("{} (all ports)", self.preset.label())
+ }
+ NetworkPreset::Localhost => format!(
+ "{} (ports {})",
+ self.preset.label(),
+ join_ports(&self.localhost_ports)
+ ),
+ NetworkPreset::Custom => format!(
+ "Custom, from {}",
+ match self.custom_base {
+ NetworkPreset::None => "no network",
+ _ => "internet only",
+ }
+ ),
+ p => p.label().to_string(),
+ }
+ }
+
+ /// The settings of a child Space under a parent with `parent`: no more
+ /// open than either (the stricter preset, the localhost ports both
+ /// list, every deny of both, and only the allows the other side also
+ /// allows). `widened_by` is dropped: a widened child skips this.
+ pub fn intersect(&self, parent: &NetworkSettings) -> NetworkSettings {
+ use NetworkPreset as P;
+ let (preset, base) = meet(self, parent);
+ let mut out = NetworkSettings {
+ preset,
+ custom_base: if preset == P::Custom {
+ base
+ } else {
+ P::Internet
+ },
+ ..Default::default()
+ };
+ if preset == P::Localhost {
+ let both_all = self.all_localhost_ports && parent.all_localhost_ports;
+ out.all_localhost_ports = both_all;
+ if !both_all {
+ let mine: Vec<u16> = ports_of(self);
+ let theirs: Vec<u16> = ports_of(parent);
+ out.localhost_ports = match (self.all_localhost_ports, parent.all_localhost_ports) {
+ (true, _) => theirs,
+ (_, true) => mine,
+ _ => mine.into_iter().filter(|p| theirs.contains(p)).collect(),
+ };
+ if out.localhost_ports.is_empty() {
+ out.preset = P::Internet;
+ }
+ }
+ }
+ let ctx = NetworkContext::default();
+ let mine = compile_mode(self, &ctx, Mode::Secure).unwrap_or_else(|_| drop_all());
+ let theirs = compile_mode(parent, &ctx, Mode::Secure).unwrap_or_else(|_| drop_all());
+ let keep = |list: &[String], other: &Rules| -> Vec<String> {
+ list.iter()
+ .filter(|e| match Net::parse(e) {
+ Ok(net) => other.allows_net(&net),
+ // `all` (both families): kept only if the other side
+ // allows both.
+ Err(_) => ["0.0.0.0/0", "::/0"]
+ .iter()
+ .all(|a| other.allows_net(&Net::parse(a).expect("valid"))),
+ })
+ .cloned()
+ .collect()
+ };
+ let mut allow = keep(&self.custom.allow, &theirs);
+ for e in keep(&parent.custom.allow, &mine) {
+ if !allow.contains(&e) {
+ allow.push(e);
+ }
+ }
+ let mut deny = self.custom.deny.clone();
+ for e in &parent.custom.deny {
+ if !deny.contains(e) {
+ deny.push(e.clone());
+ }
+ }
+ if out.preset != P::None {
+ out.custom = EgressPolicy { allow, deny };
+ }
+ out
+ }
+}
+
+fn ports_of(s: &NetworkSettings) -> Vec<u16> {
+ if s.preset == NetworkPreset::Localhost {
+ s.localhost_ports.clone()
+ } else {
+ Vec::new()
+ }
+}
+
+/// The stricter of two settings' presets, as (preset, custom base).
+fn meet(a: &NetworkSettings, b: &NetworkSettings) -> (NetworkPreset, NetworkPreset) {
+ use NetworkPreset as P;
+ let (pa, pb) = (a.preset, b.preset);
+ if pa == P::None || pb == P::None {
+ return (P::None, P::Internet);
+ }
+ if a.default_drops() || b.default_drops() {
+ // Either reaches nothing it does not list.
+ return (P::Custom, P::None);
+ }
+ match (pa, pb) {
+ (P::Unprotected, other) | (other, P::Unprotected) => (other, P::Internet),
+ (P::Custom, _) | (_, P::Custom) => (P::Custom, P::Internet),
+ (P::Lan, P::Lan) => (P::Lan, P::Internet),
+ (P::Localhost, P::Localhost) => (P::Localhost, P::Internet),
+ (P::Internet | P::Lan | P::Localhost, _) => (P::Internet, P::Internet),
+ (P::None, _) => (P::None, P::Internet),
+ }
+}
+
+fn join_ports(ports: &[u16]) -> String {
+ ports
+ .iter()
+ .map(u16::to_string)
+ .collect::<Vec<_>>()
+ .join(", ")
+}
+
+fn drop_all() -> Rules {
+ Rules {
+ rules: all_nets()
+ .into_iter()
+ .map(|n| Rule::net(n, false, Reason::DefaultNone))
+ .collect(),
+ }
+}
+
+fn all_nets() -> [Net; 2] {
+ [
+ Net::parse("0.0.0.0/0").expect("valid"),
+ Net::parse("::/0").expect("valid"),
+ ]
+}
+
+/// Cloud metadata endpoints: AWS (IPv4 and IPv6), ECS, Azure's wireserver
+/// and Alibaba's. Always blocked.
+pub const METADATA: [&str; 5] = [
+ "169.254.169.254/32",
+ "169.254.170.2/32",
+ "fd00:ec2::254/128",
+ "168.63.129.16/32",
+ "100.100.100.200/32",
+];
+
+/// Private and link-local networks: blocked unless `lan`.
+pub const DEFAULT_DENY_LAN: [&str; 6] = [
+ "10.0.0.0/8",
+ "172.16.0.0/12",
+ "192.168.0.0/16",
+ "169.254.0.0/16",
+ "fc00::/7",
+ "fe80::/10",
+];
+
+/// Loopback, CGNAT (Tailscale's range too), multicast and other reserved
+/// ranges: always blocked by default (no preset lifts them).
+pub const DEFAULT_DENY_RESERVED: [&str; 11] = [
+ "0.0.0.0/8",
+ "100.64.0.0/10",
+ "127.0.0.0/8",
+ "192.0.0.0/24",
+ "198.18.0.0/15",
+ "224.0.0.0/4",
+ "240.0.0.0/4",
+ "::1/128",
+ "::ffff:0:0/96",
+ "64:ff9b::/96",
+ "ff00::/8",
+];
+
+fn nets(list: &[&str]) -> Vec<Net> {
+ list.iter()
+ .map(|s| Net::parse(s).expect("a valid built-in network"))
+ .collect()
+}
+
+fn default_lan() -> Vec<Net> {
+ nets(&DEFAULT_DENY_LAN)
+}
+
+fn default_reserved() -> Vec<Net> {
+ nets(&DEFAULT_DENY_RESERVED)
+}
+
+/// What only the runtime knows, for [`compile`].
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct NetworkContext {
+ /// The runtime's own resolvers: allowed on port 53.
+ pub resolvers: Vec<IpAddr>,
+ /// The addresses through which the guest reaches the host's loopback
+ /// (`10.0.2.2`, the bridge gateway, `192.168.64.1`).
+ pub host_aliases: Vec<IpAddr>,
+ /// The host's own interface addresses.
+ pub host_addrs: Vec<IpAddr>,
+ /// The other Spaces of this Space's tree: allowed.
+ pub tree: Vec<Net>,
+ /// Spaces of other trees: always blocked.
+ pub other_trees: Vec<Net>,
+ /// The daemon's ports on the host: always blocked on every host
+ /// address and alias.
+ pub daemon_ports: Vec<u16>,
+}
+
+/// The TCP port the cua daemon listens on, from its discovery file under
+/// the cua home (`None` when no daemon has written one). Guests are never
+/// let through to it ([`Reason::PlatformDaemon`]).
+pub fn daemon_ports() -> Vec<u16> {
+ #[derive(Deserialize)]
+ struct Discovery {
+ #[serde(default)]
+ loopback_url: Option<String>,
+ }
+ let path = crate::host::cua_home().join("daemon.json");
+ let Some(url) = std::fs::read(path)
+ .ok()
+ .and_then(|b| serde_json::from_slice::<Discovery>(&b).ok())
+ .and_then(|d| d.loopback_url)
+ else {
+ return Vec::new();
+ };
+ url.rsplit(':')
+ .next()
+ .and_then(|p| p.trim_end_matches('/').parse::<u16>().ok())
+ .into_iter()
+ .collect()
+}
+
+/// This host's own interface addresses (loopback left out): what a guest
+/// must not reach through a runtime that maps them to the host (pasta).
+/// Enumerated at each start.
+pub fn host_addresses() -> Vec<IpAddr> {
+ #[cfg(unix)]
+ {
+ let mut out: Vec<IpAddr> = Vec::new();
+ // SAFETY: getifaddrs fills a list we only read and then free.
+ unsafe {
+ let mut head: *mut libc::ifaddrs = std::ptr::null_mut();
+ if libc::getifaddrs(&mut head) != 0 {
+ return out;
+ }
+ let mut cur = head;
+ while !cur.is_null() {
+ let a = (*cur).ifa_addr;
+ if !a.is_null() {
+ let ip = match i32::from((*a).sa_family) {
+ libc::AF_INET => {
+ let v4 = &*(a as *const libc::sockaddr_in);
+ Some(IpAddr::V4(std::net::Ipv4Addr::from(u32::from_be(
+ v4.sin_addr.s_addr,
+ ))))
+ }
+ libc::AF_INET6 => {
+ let v6 = &*(a as *const libc::sockaddr_in6);
+ Some(IpAddr::V6(std::net::Ipv6Addr::from(v6.sin6_addr.s6_addr)))
+ }
+ _ => None,
+ };
+ if let Some(ip) = ip.filter(|i| !i.is_loopback())
+ && !out.contains(&ip)
+ {
+ out.push(ip);
+ }
+ }
+ cur = (*cur).ifa_next;
+ }
+ libc::freeifaddrs(head);
+ }
+ out
+ }
+ #[cfg(not(unix))]
+ {
+ Vec::new()
+ }
+}
+
+/// The rules a VM runtime enforces: its network settings compiled with
+/// `ctx` under the secure default (an old egress policy migrated when it
+/// has none), or the old policy alone under `CUA_SECURE_DEFAULT=0`.
+pub fn vm_rules(
+ settings: Option<&NetworkSettings>,
+ legacy: Option<&EgressPolicy>,
+ restrict_network: bool,
+ ctx: &NetworkContext,
+) -> Result<Rules, PolicyError> {
+ match Mode::from_env() {
+ Mode::Secure => {
+ let s = match settings {
+ Some(s) => s.clone(),
+ None => {
+ NetworkSettings::migrate(&legacy.cloned().unwrap_or_default(), restrict_network)
+ }
+ };
+ compile_mode(&s, ctx, Mode::Secure)
+ }
+ Mode::Legacy => match legacy {
+ Some(p) => p.parse(),
+ None => Ok(Rules::default()),
+ },
+ }
+}
+
+/// The host loopback ports a VM's network namespace forwards to the host
+/// (pasta `-T`) for the `localhost` preset: its listed ports, never the
+/// daemon's. Every port is refused for VMs: a namespace forwards listed
+/// ports only. Empty for any other preset or under the old default.
+pub fn vm_localhost_ports(settings: Option<&NetworkSettings>) -> Result<Vec<u16>, PolicyError> {
+ let Some(s) = settings.filter(|s| s.preset == NetworkPreset::Localhost) else {
+ return Ok(Vec::new());
+ };
+ if Mode::from_env() == Mode::Legacy {
+ return Ok(Vec::new());
+ }
+ if s.all_localhost_ports {
+ return Err(PolicyError(
+ "a VM opens the localhost ports you list, not all of them: list them \
+ (localhost:5432,3000)"
+ .into(),
+ ));
+ }
+ let daemon = daemon_ports();
+ let mut out: Vec<u16> = s
+ .localhost_ports
+ .iter()
+ .copied()
+ .filter(|p| !daemon.contains(p))
+ .collect();
+ out.sort_unstable();
+ out.dedup();
+ Ok(out)
+}
+
+/// pasta's `-T` argument for `ports` (`none` without any).
+pub fn pasta_out_spec(ports: &[u16]) -> String {
+ if ports.is_empty() {
+ "none".into()
+ } else {
+ ports
+ .iter()
+ .map(u16::to_string)
+ .collect::<Vec<_>>()
+ .join(",")
+ }
+}
+
+/// Whether the secure default applies, or the old open one. The secure
+/// default is the Secure Spaces experiment ([`crate::experiments::Gate`]):
+/// off, Spaces keep the open network they always had.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Mode {
+ /// Secure Spaces on: presets, platform and default denies.
+ Secure,
+ /// The old open default: only the user's own lists, and `none`.
+ Legacy,
+}
+
+/// The environment variable that forces the mode over the experiment:
+/// `0` (or `false`, `off`, `no`) the old open default, `1` (or `true`, `on`,
+/// `yes`) the secure one.
+pub const SECURE_DEFAULT_ENV: &str = "CUA_SECURE_DEFAULT";
+
+impl Mode {
+ /// The mode of this process: [`SECURE_DEFAULT_ENV`] when it is set,
+ /// else [`crate::experiments::Gate::SecureSpaces`] (off unless
+ /// turned on).
+ pub fn from_env() -> Mode {
+ Mode::from_value(
+ std::env::var(SECURE_DEFAULT_ENV).ok().as_deref(),
+ crate::experiments::enabled(crate::experiments::Gate::SecureSpaces),
+ )
+ }
+
+ /// [`Mode::from_env`] for a value of the variable and the experiment's
+ /// state.
+ pub fn from_value(v: Option<&str>, experiment_on: bool) -> Mode {
+ match v.map(|v| v.trim().to_ascii_lowercase()).as_deref() {
+ Some("0" | "false" | "off" | "no") => Mode::Legacy,
+ Some("1" | "true" | "on" | "yes") => Mode::Secure,
+ _ if experiment_on => Mode::Secure,
+ _ => Mode::Legacy,
+ }
+ }
+}
+
+/// Compiles `settings` for a runtime whose facts are `ctx`, under the mode
+/// the environment says ([`Mode::from_env`]).
+pub fn compile(settings: &NetworkSettings, ctx: &NetworkContext) -> Result<Rules, PolicyError> {
+ compile_mode(settings, ctx, Mode::from_env())
+}
+
+/// [`compile`] under `mode` (see the module docs for the layers).
+pub fn compile_mode(
+ settings: &NetworkSettings,
+ ctx: &NetworkContext,
+ mode: Mode,
+) -> Result<Rules, PolicyError> {
+ settings.validate()?;
+ let user = settings.custom.parse()?;
+ if mode == Mode::Legacy {
+ let mut rules = user;
+ if settings.default_drops() {
+ rules.rules.extend(drop_all().rules);
+ }
+ return Ok(rules);
+ }
+ let mut r: Vec<Rule> = Vec::new();
+ // 1. Platform denies.
+ for n in nets(&METADATA) {
+ r.push(Rule::net(n, false, Reason::PlatformMetadata));
+ }
+ for n in &ctx.other_trees {
+ r.push(Rule::net(*n, false, Reason::PlatformOtherTree));
+ }
+ let host: Vec<IpAddr> = dedup(ctx.host_aliases.iter().chain(&ctx.host_addrs).copied());
+ if !ctx.daemon_ports.is_empty() {
+ for ip in &host {
+ r.push(Rule {
+ ports: Some(ctx.daemon_ports.clone()),
+ proto: Some(Proto::Tcp),
+ ..Rule::net(Net::host(*ip), false, Reason::PlatformDaemon)
+ });
+ }
+ r.push(Rule {
+ ports: Some(ctx.daemon_ports.clone()),
+ proto: Some(Proto::Tcp),
+ ..Rule::host_local(false, Reason::PlatformDaemon)
+ });
+ }
+ let none = settings.preset == NetworkPreset::None;
+ let unprotected = settings.preset == NetworkPreset::Unprotected;
+ // 2. The runtime's resolver, on 53 (it may be a host address, as a
+ // microVM's gateway is).
+ if !none {
+ for ip in dedup(ctx.resolvers.iter().copied()) {
+ r.push(Rule {
+ ports: Some(vec![53]),
+ ..Rule::net(Net::host(ip), true, Reason::Resolver)
+ });
+ }
+ }
+ // 3. The host: only `localhost` opens its aliases, on its ports.
+ if !unprotected {
+ if settings.preset == NetworkPreset::Localhost {
+ for ip in dedup(ctx.host_aliases.iter().copied()) {
+ r.push(Rule {
+ ports: (!settings.all_localhost_ports)
+ .then(|| settings.localhost_ports.clone()),
+ ..Rule::net(Net::host(ip), true, Reason::PresetLocalhost)
+ });
+ }
+ }
+ for ip in dedup(ctx.host_aliases.iter().copied()) {
+ r.push(Rule::net(Net::host(ip), false, Reason::DefaultHostLoopback));
+ }
+ for ip in dedup(ctx.host_addrs.iter().copied()) {
+ if !ctx.host_aliases.contains(&ip) {
+ r.push(Rule::net(Net::host(ip), false, Reason::DefaultHost));
+ }
+ }
+ // Every address of the enforcing host, whatever it is.
+ r.push(Rule::host_local(false, Reason::DefaultHost));
+ }
+ // The Space's own tree.
+ if !none {
+ for n in &ctx.tree {
+ r.push(Rule::net(*n, true, Reason::Tree));
+ }
+ }
+ // 4. The user's lists.
+ r.extend(user.rules);
+ // 5. Default denies.
+ if !unprotected {
+ for n in default_reserved() {
+ r.push(Rule::net(n, false, Reason::DefaultReserved));
+ }
+ if settings.preset != NetworkPreset::Lan {
+ for n in default_lan() {
+ r.push(Rule::net(n, false, Reason::DefaultLan));
+ }
+ }
+ }
+ // 6. The default action.
+ if settings.default_drops() {
+ r.extend(drop_all().rules);
+ }
+ Ok(Rules { rules: r })
+}
+
+fn dedup(it: impl Iterator<Item = IpAddr>) -> Vec<IpAddr> {
+ let mut out: Vec<IpAddr> = Vec::new();
+ for ip in it {
+ if !out.contains(&ip) {
+ out.push(ip);
+ }
+ }
+ out
+}
+
+// ------------------------------------------------------------- support
+
+/// Where a Space runs, as [`network_support`] sees it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Placement {
+ /// On this computer.
+ Local,
+ /// On one of your computers (a pool host): its own runtime enforces.
+ PoolHost,
+ /// In your own cloud account or a Spaces provider (`on=<provider>`).
+ Provider,
+ /// On a provider because this computer was full (`on=auto` overflow).
+ Overflow,
+}
+
+impl Placement {
+ /// Every placement.
+ pub const ALL: [Placement; 4] = [
+ Placement::Local,
+ Placement::PoolHost,
+ Placement::Provider,
+ Placement::Overflow,
+ ];
+
+ /// `local`, `pool_host`, `provider`, `overflow`.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Placement::Local => "local",
+ Placement::PoolHost => "pool_host",
+ Placement::Provider => "provider",
+ Placement::Overflow => "overflow",
+ }
+ }
+}
+
+/// What a runtime does with network settings ([`network_support`]).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum NetworkSupport {
+ /// The host enforces the rules, outside the guest, at `point`.
+ Enforced {
+ /// Where, for people.
+ point: &'static str,
+ },
+ /// It can't enforce rules yet, but can run the Space with no network.
+ NoNetworkOnly {
+ /// Why, in plain words.
+ why: &'static str,
+ },
+ /// It can't run a protected Space at all.
+ Refuse {
+ /// Why, in plain words, and what to do instead.
+ why: &'static str,
+ },
+}
+
+/// The engine-host point of the container backends.
+pub const ENGINE_POINT: &str = "nftables in the container engine's own network namespace, on the \
+ Space's bridge port (outside the container, runc and gVisor alike)";
+/// The namespace point of the Linux VMs.
+pub const NS_POINT: &str = "iptables in the network namespace pasta creates around the VM process";
+
+const WHY_VZ: &str = "Apple's microVM network can't be filtered per Space yet";
+const WHY_QEMU: &str = "QEMU on this system can't filter one VM's connections yet";
+/// Why a macOS VM (Lume) is refused under the secure default.
+pub const WHY_LUME: &str = "macOS VMs can't protect your network yet, and Cua reaches a macOS \
+ VM over its network, so it can't start without one. Choose No protection to start it.";
+const WHY_CONTAINERIZATION: &str = "Apple's Containerization can't protect your network yet. \
+ Use the standard microVM (the default) or choose No protection.";
+const WHY_QEMU_DOCKER: &str = "QEMU in a container isn't supported by this build";
+const WHY_FIRECRACKER_OS: &str = "Firecracker microVMs run on Linux only";
+const WHY_VZ_OS: &str = "Apple microVMs run on a Mac only";
+const WHY_MAC_OS: &str = "this runtime runs on a Mac only";
+const WHY_PROVIDER: &str = "Spaces in your cloud account can't protect your network yet. \
+ Create it on this computer or one of yours, or choose No protection.";
+
+/// What `kind` does with network settings on host OS `os` (`linux`,
+/// `macos`, `windows`) at `placement`. Every combination has an answer:
+/// the matches have no wildcard, so a new runtime or placement does not
+/// build until it says.
+pub fn network_support(kind: BackendKind, os: &str, placement: Placement) -> NetworkSupport {
+ use NetworkSupport::{Enforced, NoNetworkOnly, Refuse};
+ match placement {
+ // A pool host answers for its own runtime, on its own OS (and checks
+ // that it enforces before it reports the Space).
+ Placement::Local | Placement::PoolHost => {}
+ Placement::Provider | Placement::Overflow => {
+ return match kind {
+ BackendKind::Lume
+ | BackendKind::Qemu
+ | BackendKind::QemuDocker
+ | BackendKind::Container
+ | BackendKind::Managed
+ | BackendKind::Firecracker
+ | BackendKind::Containerization
+ | BackendKind::Vz => Refuse { why: WHY_PROVIDER },
+ };
+ }
+ }
+ let linux = os == "linux";
+ let mac = os == "macos";
+ match kind {
+ BackendKind::Container | BackendKind::Managed => Enforced {
+ point: ENGINE_POINT,
+ },
+ BackendKind::Firecracker if linux => Enforced { point: NS_POINT },
+ BackendKind::Firecracker => Refuse {
+ why: WHY_FIRECRACKER_OS,
+ },
+ BackendKind::Qemu if linux => Enforced { point: NS_POINT },
+ BackendKind::Qemu => NoNetworkOnly { why: WHY_QEMU },
+ BackendKind::Vz if mac => NoNetworkOnly { why: WHY_VZ },
+ BackendKind::Vz => Refuse { why: WHY_VZ_OS },
+ // Not "no network only": Cua reaches a macOS VM over its network.
+ BackendKind::Lume if mac => Refuse { why: WHY_LUME },
+ BackendKind::Lume => Refuse { why: WHY_MAC_OS },
+ BackendKind::Containerization => Refuse {
+ why: WHY_CONTAINERIZATION,
+ },
+ BackendKind::QemuDocker => Refuse {
+ why: WHY_QEMU_DOCKER,
+ },
+ }
+}
+
+/// The note a Space gets when it started without network because its
+/// runtime can't protect it yet.
+pub const NO_NETWORK_NOTE: &str = "This runtime can't protect your network yet, so this Space \
+ started without network. Choose No protection to open it.";
+
+/// The note a Space gets when the user chose `unprotected`.
+pub const UNPROTECTED_NOTE: &str =
+ "You chose No protection: this Space can reach this computer and your local network.";
+
+/// What a start does with a Space's network ([`plan`]).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum NetworkPlan {
+ /// Start with these rules enforced by the host.
+ Enforce(Rules),
+ /// Start with no network at all; `note` says why when it was not
+ /// asked for.
+ NoNetwork {
+ /// For people.
+ note: Option<&'static str>,
+ },
+ /// Start open: only the rules the runtime can apply (none where it
+ /// enforces nothing). Only for `unprotected`, or the revert switch.
+ Open {
+ /// For people.
+ note: Option<&'static str>,
+ },
+ /// Don't start: why, in plain words.
+ Refuse(&'static str),
+}
+
+/// What a start does with `settings` on a runtime that answers `support`
+/// (see the module docs). Nothing but `unprotected` (or the revert switch)
+/// is ever less strict than asked.
+pub fn plan(
+ settings: &NetworkSettings,
+ support: NetworkSupport,
+ ctx: &NetworkContext,
+ mode: Mode,
+) -> Result<NetworkPlan, PolicyError> {
+ let rules = compile_mode(settings, ctx, mode)?;
+ let none = settings.preset == NetworkPreset::None;
+ Ok(match (mode, support) {
+ (_, NetworkSupport::Enforced { .. }) => NetworkPlan::Enforce(rules),
+ // The old default: an open Space where nothing was asked.
+ (Mode::Legacy, _) if rules.is_empty() => NetworkPlan::Open { note: None },
+ (Mode::Legacy, NetworkSupport::NoNetworkOnly { .. }) if none => {
+ NetworkPlan::NoNetwork { note: None }
+ }
+ (Mode::Legacy, NetworkSupport::NoNetworkOnly { why } | NetworkSupport::Refuse { why }) => {
+ NetworkPlan::Refuse(why)
+ }
+ (Mode::Secure, _) if settings.preset == NetworkPreset::Unprotected => NetworkPlan::Open {
+ note: Some(UNPROTECTED_NOTE),
+ },
+ (Mode::Secure, NetworkSupport::NoNetworkOnly { .. }) if none => {
+ NetworkPlan::NoNetwork { note: None }
+ }
+ (Mode::Secure, NetworkSupport::NoNetworkOnly { .. }) => NetworkPlan::NoNetwork {
+ note: Some(NO_NETWORK_NOTE),
+ },
+ (Mode::Secure, NetworkSupport::Refuse { why }) => NetworkPlan::Refuse(why),
+ })
+}
+
+/// What a start of `kind` on this computer does with `spec`'s network, for
+/// a runtime that has no point to enforce rules (Lume, Vz, QEMU on macOS
+/// or Windows, Apple Containerization): [`NetworkPlan::NoNetwork`] (start
+/// it with no network), [`NetworkPlan::Open`] (`unprotected`, or the old
+/// default) or an error in plain words. Never more open than asked.
+pub fn local_plan(kind: BackendKind, spec: &crate::StartSpec) -> crate::Result<NetworkPlan> {
+ local_plan_for(kind, &spec.name, &spec_settings(spec))
+}
+
+/// The settings a start spec asks for: its own, else what its old options
+/// say.
+pub fn spec_settings(spec: &crate::StartSpec) -> NetworkSettings {
+ spec.network
+ .clone()
+ .unwrap_or_else(|| NetworkSettings::migrate(&spec.egress, spec.restrict_network))
+}
+
+/// Under the secure default, for a runtime that does not enforce rules on
+/// this host: [`local_plan_for`] (`Some`). `None` for a runtime that
+/// enforces them, and under the old default (the caller keeps its old
+/// checks).
+pub fn gate(
+ kind: BackendKind,
+ name: &str,
+ settings: &NetworkSettings,
+) -> crate::Result<Option<NetworkPlan>> {
+ if Mode::from_env() == Mode::Legacy {
+ return Ok(None);
+ }
+ match network_support(kind, std::env::consts::OS, Placement::Local) {
+ NetworkSupport::Enforced { .. } => Ok(None),
+ NetworkSupport::NoNetworkOnly { .. } | NetworkSupport::Refuse { .. } => {
+ local_plan_for(kind, name, settings).map(Some)
+ }
+ }
+}
+
+/// [`local_plan`] for `settings` of sandbox `name`.
+pub fn local_plan_for(
+ kind: BackendKind,
+ name: &str,
+ settings: &NetworkSettings,
+) -> crate::Result<NetworkPlan> {
+ let support = network_support(kind, std::env::consts::OS, Placement::Local);
+ let p = plan(
+ settings,
+ support,
+ &NetworkContext::default(),
+ Mode::from_env(),
+ )?;
+ match p {
+ NetworkPlan::Refuse(why) => Err(crate::VmmError::Other(why.to_string())),
+ NetworkPlan::Enforce(_) => Err(crate::VmmError::other(format!(
+ "{kind} enforces network rules itself; it does not start through local_plan"
+ ))),
+ other => {
+ if let NetworkPlan::NoNetwork { note: Some(n) } = &other {
+ tracing::info!(sandbox = %name, runtime = %kind, "{n}");
+ }
+ Ok(other)
+ }
+ }
+}
+
+/// When a runtime applies new network settings ([`crate::Runtime::set_network`]).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Applied {
+ /// At once: the running guest is under them now.
+ Now,
+ /// At its next start (it is stopped, or its runtime can't change a
+ /// running guest's network).
+ NextStart,
+}
+
+/// The support table as a Markdown table (for the docs; a test keeps them
+/// in step).
+pub fn support_table_markdown() -> String {
+ let mut out =
+ String::from("| Runtime | Host | Linux | macOS | Windows |\n|---|---|---|---|---|\n");
+ for kind in crate::egress::BACKENDS {
+ for placement in [Placement::Local, Placement::Provider] {
+ let cell = |os: &str| match network_support(kind, os, placement) {
+ NetworkSupport::Enforced { .. } => "Enforced".to_string(),
+ NetworkSupport::NoNetworkOnly { .. } => "No network only".to_string(),
+ NetworkSupport::Refuse { .. } => "Refused".to_string(),
+ };
+ out.push_str(&format!(
+ "| {} | {} | {} | {} | {} |\n",
+ kind.as_str(),
+ match placement {
+ Placement::Local | Placement::PoolHost => "this computer or one of yours",
+ Placement::Provider | Placement::Overflow => "your cloud account",
+ },
+ cell("linux"),
+ cell("macos"),
+ cell("windows"),
+ ));
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests;
+
+#[cfg(test)]
+mod host_tests {
+ use super::*;
+
+ #[test]
+ fn a_runtime_without_rules_starts_without_network_or_refuses() {
+ if Mode::from_env() == Mode::Legacy {
+ return;
+ }
+ let spec = crate::StartSpec::new("x", crate::ImageSource::Existing);
+ let os = std::env::consts::OS;
+ for kind in crate::egress::BACKENDS {
+ let support = network_support(kind, os, Placement::Local);
+ match (support, local_plan(kind, &spec)) {
+ (NetworkSupport::Enforced { .. }, r) => assert!(r.is_err(), "{kind}"),
+ (NetworkSupport::NoNetworkOnly { .. }, r) => assert_eq!(
+ r.unwrap(),
+ NetworkPlan::NoNetwork {
+ note: Some(NO_NETWORK_NOTE)
+ }
+ ),
+ (NetworkSupport::Refuse { why }, r) => {
+ assert_eq!(r.unwrap_err().to_string(), why, "{kind}")
+ }
+ }
+ }
+ // No protection opens it, and says so.
+ let mut open = spec.clone();
+ open.network = Some(NetworkSettings::preset(NetworkPreset::Unprotected));
+ assert_eq!(
+ local_plan(BackendKind::Containerization, &open).unwrap(),
+ NetworkPlan::Open {
+ note: Some(UNPROTECTED_NOTE)
+ }
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn host_addresses_leave_out_loopback() {
+ let a = super::host_addresses();
+ assert!(a.iter().all(|i| !i.is_loopback()), "{a:?}");
+ }
+}
diff --git a/libs/cua/crates/cua-vmm/src/network/tests.rs b/libs/cua/crates/cua-vmm/src/network/tests.rs
new file mode 100644
index 0000000000..8190255e4e
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/src/network/tests.rs
@@ -0,0 +1,804 @@
+use super::*;
+use crate::egress::BACKENDS;
+use proptest::prelude::*;
+use std::net::{Ipv4Addr, Ipv6Addr};
+
+fn ip(s: &str) -> IpAddr {
+ s.parse().unwrap()
+}
+
+fn net(s: &str) -> Net {
+ Net::parse(s).unwrap()
+}
+
+/// A runtime's facts: QEMU-like aliases, a LAN host address, one sibling in
+/// the tree and one Space of another tree.
+fn ctx() -> NetworkContext {
+ NetworkContext {
+ resolvers: vec![ip("10.0.2.3")],
+ host_aliases: vec![ip("10.0.2.2"), ip("192.168.64.1")],
+ host_addrs: vec![ip("192.168.1.20"), ip("203.0.113.7")],
+ tree: vec![net("172.30.0.3/32")],
+ other_trees: vec![net("172.30.1.0/24")],
+ daemon_ports: vec![3200, 8443],
+ }
+}
+
+fn secure(s: &NetworkSettings) -> Rules {
+ compile_mode(s, &ctx(), Mode::Secure).unwrap()
+}
+
+fn localhost(ports: &[u16]) -> NetworkSettings {
+ NetworkSettings {
+ preset: NetworkPreset::Localhost,
+ localhost_ports: ports.to_vec(),
+ ..Default::default()
+ }
+}
+
+fn custom(base: NetworkPreset, allow: &[&str], deny: &[&str]) -> NetworkSettings {
+ NetworkSettings {
+ preset: NetworkPreset::Custom,
+ custom_base: base,
+ custom: EgressPolicy {
+ allow: allow.iter().map(|s| s.to_string()).collect(),
+ deny: deny.iter().map(|s| s.to_string()).collect(),
+ },
+ ..Default::default()
+ }
+}
+
+#[test]
+fn internet_reaches_the_internet_and_its_tree_only() {
+ let r = secure(&NetworkSettings::internet());
+ for ok in ["1.1.1.1", "8.8.8.8", "2606:4700::1111", "172.30.0.3"] {
+ assert!(r.allows(ip(ok)), "{ok}");
+ }
+ for blocked in [
+ "169.254.169.254",
+ "169.254.170.2",
+ "fd00:ec2::254",
+ "168.63.129.16",
+ "100.100.100.200",
+ "10.0.2.2",
+ "192.168.64.1",
+ "192.168.1.20",
+ "203.0.113.7",
+ "127.0.0.1",
+ "10.1.2.3",
+ "172.16.5.5",
+ "192.168.0.1",
+ "100.64.0.1",
+ "100.101.102.103",
+ "169.254.1.1",
+ "224.0.0.251",
+ "255.255.255.255",
+ "0.0.0.0",
+ "::1",
+ "fe80::1",
+ "fd12::1",
+ "ff02::1",
+ "64:ff9b::a00:1",
+ "172.30.1.9",
+ // IPv4-mapped forms are judged as IPv4.
+ "::ffff:127.0.0.1",
+ "::ffff:10.0.0.1",
+ "::ffff:169.254.169.254",
+ ] {
+ assert!(!r.allows(ip(blocked)), "{blocked}");
+ }
+ assert!(r.allows(ip("::ffff:1.1.1.1")));
+ // The resolver on 53 only.
+ assert!(r.allows_port(ip("10.0.2.3"), Proto::Udp, 53));
+ assert!(r.allows_port(ip("10.0.2.3"), Proto::Tcp, 53));
+ assert!(!r.allows_port(ip("10.0.2.3"), Proto::Tcp, 80));
+ assert!(!r.allows(ip("10.0.2.3")));
+ // The reason ids.
+ let why = |s: &str| r.decide(ip(s), None, None).map(|r| r.reason);
+ assert_eq!(why("169.254.169.254"), Some(Reason::PlatformMetadata));
+ assert_eq!(why("10.0.2.2"), Some(Reason::DefaultHostLoopback));
+ assert_eq!(why("203.0.113.7"), Some(Reason::DefaultHost));
+ assert_eq!(why("192.168.0.1"), Some(Reason::DefaultLan));
+ assert_eq!(why("127.0.0.1"), Some(Reason::DefaultReserved));
+ assert_eq!(why("172.30.1.9"), Some(Reason::PlatformOtherTree));
+ assert_eq!(why("172.30.0.3"), Some(Reason::Tree));
+ assert_eq!(why("1.1.1.1"), None);
+ assert_eq!(
+ r.decide(ip("10.0.2.2"), Some(Proto::Tcp), Some(3200))
+ .map(|r| r.reason),
+ Some(Reason::PlatformDaemon)
+ );
+}
+
+#[test]
+fn platform_denies_beat_every_preset_and_user_rule() {
+ let wide = custom(
+ NetworkPreset::Internet,
+ &["169.254.169.254", "172.30.1.0/24", "all", "10.0.2.2"],
+ &[],
+ );
+ for s in [
+ wide,
+ NetworkSettings::preset(NetworkPreset::Lan),
+ NetworkSettings::preset(NetworkPreset::Unprotected),
+ NetworkSettings {
+ preset: NetworkPreset::Localhost,
+ all_localhost_ports: true,
+ ..Default::default()
+ },
+ ] {
+ let r = secure(&s);
+ for blocked in [
+ "169.254.169.254",
+ "fd00:ec2::254",
+ "168.63.129.16",
+ "172.30.1.4",
+ ] {
+ assert!(!r.allows(ip(blocked)), "{s:?} {blocked}");
+ }
+ for host in ["10.0.2.2", "192.168.64.1", "192.168.1.20"] {
+ assert!(
+ !r.allows_port(ip(host), Proto::Tcp, 3200),
+ "the daemon: {s:?} {host}"
+ );
+ }
+ }
+}
+
+#[test]
+fn localhost_opens_the_host_aliases_on_its_ports_only() {
+ let r = secure(&localhost(&[5432, 3000]));
+ assert!(r.allows_port(ip("10.0.2.2"), Proto::Tcp, 5432));
+ assert!(r.allows_port(ip("192.168.64.1"), Proto::Tcp, 3000));
+ assert!(!r.allows_port(ip("10.0.2.2"), Proto::Tcp, 22));
+ assert!(!r.allows(ip("10.0.2.2")));
+ // Not the host's other addresses, not the LAN.
+ assert!(!r.allows_port(ip("192.168.1.20"), Proto::Tcp, 5432));
+ assert!(!r.allows(ip("192.168.0.9")));
+ // All ports, said explicitly: still not the daemon's.
+ let all = secure(&NetworkSettings {
+ preset: NetworkPreset::Localhost,
+ all_localhost_ports: true,
+ ..Default::default()
+ });
+ assert!(all.allows_port(ip("10.0.2.2"), Proto::Tcp, 22));
+ assert!(!all.allows_port(ip("10.0.2.2"), Proto::Tcp, 8443));
+ // Empty ports are refused unless all.
+ let e = compile_mode(&localhost(&[]), &ctx(), Mode::Secure).unwrap_err();
+ assert!(e.0.contains("needs the ports"), "{e}");
+ let e = compile_mode(&localhost(&[0]), &ctx(), Mode::Secure).unwrap_err();
+ assert!(e.0.contains("port 0"), "{e}");
+}
+
+#[test]
+fn lan_opens_private_networks_but_not_the_host() {
+ let r = secure(&NetworkSettings::preset(NetworkPreset::Lan));
+ for ok in [
+ "192.168.1.30",
+ "10.9.9.9",
+ "172.16.0.1",
+ "169.254.10.10",
+ "fd00::5",
+ "fe80::9",
+ ] {
+ assert!(r.allows(ip(ok)), "{ok}");
+ }
+ for blocked in [
+ "10.0.2.2",
+ "192.168.64.1",
+ "192.168.1.20",
+ "127.0.0.1",
+ "100.64.1.1",
+ "169.254.169.254",
+ ] {
+ assert!(!r.allows(ip(blocked)), "{blocked}");
+ }
+}
+
+#[test]
+fn none_reaches_nothing_and_custom_from_none_only_its_list() {
+ let r = secure(&NetworkSettings::none());
+ for blocked in ["1.1.1.1", "2606:4700::1111", "172.30.0.3"] {
+ assert!(!r.allows(ip(blocked)), "{blocked}");
+ }
+ assert!(
+ !r.allows_port(ip("10.0.2.3"), Proto::Udp, 53),
+ "no DNS either"
+ );
+ let r = secure(&custom(NetworkPreset::None, &["1.1.1.1"], &[]));
+ assert!(r.allows(ip("1.1.1.1")));
+ assert!(!r.allows(ip("8.8.8.8")));
+ assert!(r.allows_port(ip("10.0.2.3"), Proto::Udp, 53), "DNS works");
+ assert_eq!(
+ r.decide(ip("8.8.8.8"), None, None).map(|r| r.reason),
+ Some(Reason::DefaultNone)
+ );
+ // `none` takes no lists.
+ let mut s = NetworkSettings::none();
+ s.custom.allow.push("1.1.1.1".into());
+ assert!(s.validate().is_err());
+}
+
+#[test]
+fn a_custom_allow_lifts_lan_but_never_the_host() {
+ let r = secure(&custom(
+ NetworkPreset::Internet,
+ &["192.168.1.0/24", "10.0.2.0/24"],
+ &["8.8.8.8"],
+ ));
+ assert!(r.allows(ip("192.168.1.30")));
+ assert!(r.allows(ip("10.0.2.50")));
+ assert!(!r.allows(ip("8.8.8.8")));
+ assert!(r.allows(ip("8.8.4.4")));
+ // The host stays closed: its alias and its own address on that LAN.
+ assert!(!r.allows(ip("10.0.2.2")));
+ assert!(!r.allows(ip("192.168.1.20")));
+ // An allow is an exception to a deny, as before.
+ let r = secure(&custom(NetworkPreset::Internet, &["1.1.1.1"], &["all"]));
+ assert!(r.allows(ip("1.1.1.1")) && !r.allows(ip("1.0.0.1")));
+}
+
+#[test]
+fn unprotected_keeps_only_the_platform_denies() {
+ let r = secure(&NetworkSettings::preset(NetworkPreset::Unprotected));
+ for ok in [
+ "10.0.2.2",
+ "192.168.1.20",
+ "127.0.0.1",
+ "192.168.0.1",
+ "1.1.1.1",
+ ] {
+ assert!(r.allows(ip(ok)), "{ok}");
+ }
+ assert!(!r.allows(ip("169.254.169.254")));
+ assert!(!r.allows(ip("172.30.1.1")));
+ // The host stays open, but never the daemon on it.
+ let local: Vec<&Rule> = r.rules.iter().filter(|r| r.host_local).collect();
+ assert_eq!(local.len(), 1, "{local:?}");
+ assert_eq!(local[0].reason, Reason::PlatformDaemon);
+}
+
+#[test]
+fn every_host_address_is_closed_after_the_resolver_and_localhost() {
+ let r = secure(&localhost(&[5432]));
+ let pos = |f: &dyn Fn(&Rule) -> bool| r.rules.iter().position(f).unwrap();
+ let local_drop = pos(&|r| r.host_local && r.reason == Reason::DefaultHost);
+ assert!(pos(&|r| r.reason == Reason::Resolver) < local_drop);
+ assert!(pos(&|r| r.reason == Reason::PresetLocalhost) < local_drop);
+ assert!(local_drop < pos(&|r| r.reason == Reason::Tree));
+ assert!(local_drop < pos(&|r| r.reason == Reason::DefaultReserved));
+ let daemon = pos(&|r| r.host_local && r.reason == Reason::PlatformDaemon);
+ assert!(daemon < pos(&|r| r.reason == Reason::PresetLocalhost));
+}
+
+#[test]
+fn the_old_open_default_is_what_you_get_until_secure_spaces_is_on() {
+ // Off (the experiment is off): the old open default.
+ assert_eq!(Mode::from_value(None, false), Mode::Legacy);
+ assert_eq!(Mode::from_value(Some(""), false), Mode::Legacy);
+ // On: the secure default.
+ assert_eq!(Mode::from_value(None, true), Mode::Secure);
+ // The variable wins over the experiment, either way.
+ assert_eq!(Mode::from_value(Some("1"), false), Mode::Secure);
+ for on in ["true", "ON", " yes "] {
+ assert_eq!(Mode::from_value(Some(on), false), Mode::Secure, "{on}");
+ }
+ for off in ["0", "false", "OFF", " no "] {
+ assert_eq!(Mode::from_value(Some(off), true), Mode::Legacy, "{off}");
+ }
+ let r = compile_mode(&NetworkSettings::internet(), &ctx(), Mode::Legacy).unwrap();
+ assert!(r.is_empty());
+ let r = compile_mode(&NetworkSettings::none(), &ctx(), Mode::Legacy).unwrap();
+ assert!(!r.allows(ip("1.1.1.1")));
+ let p = plan(
+ &NetworkSettings::internet(),
+ network_support(BackendKind::Vz, "macos", Placement::Local),
+ &ctx(),
+ Mode::Legacy,
+ )
+ .unwrap();
+ assert_eq!(p, NetworkPlan::Open { note: None });
+}
+
+#[test]
+fn migration_maps_old_spaces() {
+ let empty = EgressPolicy::default();
+ assert_eq!(
+ NetworkSettings::migrate(&empty, false),
+ NetworkSettings::internet()
+ );
+ assert_eq!(
+ NetworkSettings::migrate(&empty, true),
+ NetworkSettings::none()
+ );
+ let old = EgressPolicy {
+ allow: vec!["192.168.1.0/24".into(), "1.1.1.1".into()],
+ deny: vec!["all".into()],
+ };
+ let m = NetworkSettings::migrate(&old, false);
+ assert_eq!(m.preset, NetworkPreset::Custom);
+ assert_eq!(m.custom_base, NetworkPreset::Internet);
+ assert_eq!(m.custom, old);
+ // The allow that lifted a default deny is labelled.
+ assert_eq!(
+ m.widenings(),
+ ["Allows your local network (192.168.1.0/24)"]
+ );
+ let r = secure(&m);
+ assert!(r.allows(ip("192.168.1.9")) && r.allows(ip("1.1.1.1")));
+ assert!(!r.allows(ip("8.8.8.8")));
+ // A stored meta file from before: no `network` key means migrate.
+ let json = r#"{"preset":"custom","custom":{"allow":["1.1.1.1"],"deny":["all"]}}"#;
+ let back: NetworkSettings = serde_json::from_str(json).unwrap();
+ assert_eq!(back.custom_base, NetworkPreset::Internet);
+ assert_eq!(back.preset, NetworkPreset::Custom);
+}
+
+#[test]
+fn settings_json_is_small_and_stable() {
+ assert_eq!(
+ serde_json::to_string(&NetworkSettings::internet()).unwrap(),
+ r#"{"preset":"internet","custom_base":"internet"}"#
+ );
+ assert_eq!(
+ serde_json::to_string(&localhost(&[5432])).unwrap(),
+ r#"{"preset":"localhost","localhost_ports":[5432],"custom_base":"internet"}"#
+ );
+ let back: NetworkSettings = serde_json::from_str("{}").unwrap();
+ assert_eq!(back, NetworkSettings::internet());
+ for p in NetworkPreset::ALL {
+ assert_eq!(NetworkPreset::parse(p.as_str()).unwrap(), p);
+ assert_eq!(
+ serde_json::to_string(&p).unwrap(),
+ format!("\"{}\"", p.as_str())
+ );
+ assert!(!p.label().is_empty());
+ }
+ assert_eq!(
+ NetworkPreset::parse("Default").unwrap(),
+ NetworkPreset::Internet
+ );
+ assert!(NetworkPreset::parse("open").is_err());
+}
+
+#[test]
+fn rules_json_is_the_stable_contract() {
+ let s = localhost(&[5432]);
+ let r = compile_mode(
+ &s,
+ &NetworkContext {
+ resolvers: vec![ip("10.0.2.3")],
+ host_aliases: vec![ip("10.0.2.2")],
+ ..Default::default()
+ },
+ Mode::Secure,
+ )
+ .unwrap();
+ let json = serde_json::to_value(&r).unwrap();
+ assert_eq!(json["version"], 1);
+ assert_eq!(
+ json["rules"][0],
+ serde_json::json!({"net": "169.254.169.254/32", "accept": false, "reason": "platform:metadata"})
+ );
+ assert_eq!(
+ json["rules"][5],
+ serde_json::json!({"net": "10.0.2.3/32", "ports": [53], "accept": true, "reason": "allow:resolver"})
+ );
+ assert_eq!(
+ json["rules"][6],
+ serde_json::json!({"net": "10.0.2.2/32", "ports": [5432], "accept": true, "reason": "preset:localhost"})
+ );
+ let back: Rules = serde_json::from_value(json.clone()).unwrap();
+ assert_eq!(back, r);
+ // Strict: unknown fields, other versions and host bits are refused.
+ let mut bad = json.clone();
+ bad["extra"] = serde_json::json!(1);
+ assert!(serde_json::from_value::<Rules>(bad).is_err());
+ let mut bad = json.clone();
+ bad["version"] = serde_json::json!(2);
+ assert!(serde_json::from_value::<Rules>(bad).is_err());
+ let mut bad = json.clone();
+ bad["rules"][0]["why"] = serde_json::json!("x");
+ assert!(serde_json::from_value::<Rules>(bad).is_err());
+ for bad_net in ["10.0.0.1/8", "10.0.0.1", "all", "example.com/32"] {
+ let mut bad = json.clone();
+ bad["rules"][0]["net"] = serde_json::json!(bad_net);
+ assert!(serde_json::from_value::<Rules>(bad).is_err(), "{bad_net}");
+ }
+ let mut tcp = json;
+ tcp["rules"][0]["proto"] = serde_json::json!("tcp");
+ assert_eq!(
+ serde_json::from_value::<Rules>(tcp).unwrap().rules[0].proto,
+ Some(Proto::Tcp)
+ );
+}
+
+#[test]
+fn reason_ids_are_unique_and_round_trip() {
+ let mut ids: Vec<&str> = Reason::ALL.iter().map(|r| r.as_str()).collect();
+ ids.sort();
+ ids.dedup();
+ assert_eq!(ids.len(), Reason::ALL.len());
+ for r in Reason::ALL {
+ assert_eq!(Reason::from_code(r.code()), Some(r));
+ assert_eq!(
+ serde_json::to_string(&r).unwrap(),
+ format!("\"{}\"", r.as_str())
+ );
+ }
+ assert_eq!(Reason::from_code(0), None);
+ // Exhaustive: a new reason fails to build until it is in ALL.
+ let listed = |r: Reason| match r {
+ Reason::PlatformMetadata
+ | Reason::PlatformDaemon
+ | Reason::PlatformOtherTree
+ | Reason::Resolver
+ | Reason::Tree
+ | Reason::UserAllow
+ | Reason::UserDeny
+ | Reason::PresetLocalhost
+ | Reason::DefaultHostLoopback
+ | Reason::DefaultHost
+ | Reason::DefaultLan
+ | Reason::DefaultReserved
+ | Reason::DefaultNone => Reason::ALL.contains(&r),
+ };
+ assert!(Reason::ALL.into_iter().all(listed));
+}
+
+/// The support table, cell by cell: every runtime × host OS × placement.
+/// A new runtime or placement does not build until [`network_support`]
+/// answers for it, and fails here until this table says what it should be.
+#[test]
+fn golden_support_table() {
+ use NetworkSupport as S;
+ let short = |s: S| match s {
+ S::Enforced { .. } => "E",
+ S::NoNetworkOnly { .. } => "N",
+ S::Refuse { .. } => "R",
+ };
+ // (kind, linux, macos, windows) on this computer or a pool host.
+ let local = [
+ (BackendKind::Lume, "R", "R", "R"),
+ (BackendKind::Qemu, "E", "N", "N"),
+ (BackendKind::QemuDocker, "R", "R", "R"),
+ (BackendKind::Container, "E", "E", "E"),
+ (BackendKind::Managed, "E", "E", "E"),
+ (BackendKind::Firecracker, "E", "R", "R"),
+ (BackendKind::Containerization, "R", "R", "R"),
+ (BackendKind::Vz, "R", "N", "R"),
+ ];
+ assert_eq!(local.len(), BACKENDS.len());
+ for (kind, l, m, w) in local {
+ for placement in Placement::ALL {
+ let want = match placement {
+ Placement::Local | Placement::PoolHost => [l, m, w],
+ Placement::Provider | Placement::Overflow => ["R", "R", "R"],
+ };
+ for (os, want) in ["linux", "macos", "windows"].into_iter().zip(want) {
+ let got = network_support(kind, os, placement);
+ assert_eq!(short(got), want, "{kind} on {os} at {}", placement.as_str());
+ match got {
+ S::Enforced { point } => assert!(point.len() > 20),
+ S::NoNetworkOnly { why } | S::Refuse { why } => {
+ assert!(why.len() > 20, "{kind} {os}: say why");
+ assert!(!why.contains("TODO"), "{kind} {os}: finished wording");
+ }
+ }
+ }
+ }
+ }
+ let md = support_table_markdown();
+ assert!(
+ md.contains(
+ "| container | this computer or one of yours | Enforced | Enforced | Enforced |"
+ ),
+ "{md}"
+ );
+ assert!(
+ md.contains("| vz | this computer or one of yours | Refused | No network only | Refused |"),
+ "{md}"
+ );
+}
+
+#[test]
+fn plan_fails_closed() {
+ let c = ctx();
+ let local = |k, os| network_support(k, os, Placement::Local);
+ let internet = NetworkSettings::internet();
+ // Enforced: the compiled rules.
+ assert_eq!(
+ plan(
+ &internet,
+ local(BackendKind::Container, "linux"),
+ &c,
+ Mode::Secure
+ )
+ .unwrap(),
+ NetworkPlan::Enforce(secure(&internet))
+ );
+ // Can't enforce: no network, with the note.
+ assert_eq!(
+ plan(&internet, local(BackendKind::Vz, "macos"), &c, Mode::Secure).unwrap(),
+ NetworkPlan::NoNetwork {
+ note: Some(NO_NETWORK_NOTE)
+ }
+ );
+ // Asked for none: no note.
+ assert_eq!(
+ plan(
+ &NetworkSettings::none(),
+ local(BackendKind::Lume, "macos"),
+ &c,
+ Mode::Secure
+ )
+ .unwrap(),
+ // Cua reaches a macOS VM over its network, so even none is refused.
+ NetworkPlan::Refuse(
+ "macOS VMs can't protect your network yet, and Cua reaches a macOS VM over its network, so it can't start without one. Choose No protection to start it."
+ )
+ );
+ // Refused, in plain words.
+ match plan(
+ &internet,
+ local(BackendKind::Containerization, "macos"),
+ &c,
+ Mode::Secure,
+ )
+ .unwrap()
+ {
+ NetworkPlan::Refuse(why) => assert!(why.contains("No protection"), "{why}"),
+ other => panic!("{other:?}"),
+ }
+ match plan(
+ &internet,
+ network_support(BackendKind::Container, "linux", Placement::Overflow),
+ &c,
+ Mode::Secure,
+ )
+ .unwrap()
+ {
+ NetworkPlan::Refuse(why) => assert!(why.contains("cloud account"), "{why}"),
+ other => panic!("{other:?}"),
+ }
+ // Unprotected opens where the runtime can't enforce, and says so.
+ assert_eq!(
+ plan(
+ &NetworkSettings::preset(NetworkPreset::Unprotected),
+ local(BackendKind::Vz, "macos"),
+ &c,
+ Mode::Secure
+ )
+ .unwrap(),
+ NetworkPlan::Open {
+ note: Some(UNPROTECTED_NOTE)
+ }
+ );
+}
+
+// ----------------------------------------------------------- properties
+
+const PROBES: [&str; 22] = [
+ "1.1.1.1",
+ "8.8.8.8",
+ "2606:4700::1111",
+ "169.254.169.254",
+ "fd00:ec2::254",
+ "10.0.2.2",
+ "10.0.2.3",
+ "10.0.2.50",
+ "192.168.64.1",
+ "192.168.1.20",
+ "192.168.1.30",
+ "203.0.113.7",
+ "203.0.113.8",
+ "127.0.0.1",
+ "172.30.0.3",
+ "172.30.1.9",
+ "100.64.0.1",
+ "fd00::5",
+ "fe80::1",
+ "::1",
+ "::ffff:10.0.2.2",
+ "224.0.0.251",
+];
+
+const PORTS: [u16; 5] = [53, 22, 3000, 3200, 5432];
+
+fn entry() -> impl Strategy<Value = String> {
+ prop::sample::select(vec![
+ "all",
+ "1.1.1.1",
+ "8.8.8.0/24",
+ "10.0.0.0/8",
+ "10.0.2.0/24",
+ "10.0.2.2",
+ "192.168.1.0/24",
+ "192.168.64.1",
+ "203.0.113.7",
+ "127.0.0.1",
+ "169.254.169.254",
+ "172.30.1.0/24",
+ "fd00::/8",
+ "::/0",
+ "0.0.0.0/0",
+ ])
+ .prop_map(str::to_string)
+}
+
+fn settings() -> impl Strategy<Value = NetworkSettings> {
+ (
+ prop::sample::select(NetworkPreset::ALL.to_vec()),
+ prop::collection::vec(prop::sample::select(vec![22u16, 3000, 5432, 3200]), 0..3),
+ any::<bool>(),
+ prop::collection::vec(entry(), 0..3),
+ prop::collection::vec(entry(), 0..3),
+ prop::sample::select(vec![NetworkPreset::Internet, NetworkPreset::None]),
+ )
+ .prop_map(|(preset, ports, all, allow, deny, base)| {
+ let mut s = NetworkSettings {
+ preset,
+ custom_base: base,
+ custom: EgressPolicy { allow, deny },
+ ..Default::default()
+ };
+ match preset {
+ NetworkPreset::Localhost => {
+ s.localhost_ports = ports;
+ s.all_localhost_ports = all || s.localhost_ports.is_empty();
+ s.localhost_ports.dedup();
+ }
+ NetworkPreset::None => s.custom = EgressPolicy::default(),
+ _ => {}
+ }
+ s
+ })
+}
+
+fn every_support() -> Vec<NetworkSupport> {
+ let mut out = Vec::new();
+ for k in BACKENDS {
+ for os in ["linux", "macos", "windows"] {
+ for p in Placement::ALL {
+ let s = network_support(k, os, p);
+ if !out.contains(&s) {
+ out.push(s);
+ }
+ }
+ }
+ }
+ out
+}
+
+/// What a Space can reach once started under `plan` (`None`: it did not
+/// start).
+fn reaches(plan: &NetworkPlan, ip: IpAddr, proto: Proto, port: u16) -> Option<bool> {
+ match plan {
+ NetworkPlan::Enforce(r) => Some(r.allows_port(ip, proto, port)),
+ NetworkPlan::NoNetwork { .. } => Some(false),
+ NetworkPlan::Open { .. } => Some(true),
+ NetworkPlan::Refuse(_) => None,
+ }
+}
+
+proptest! {
+ /// No start is less strict than asked, unless the user chose
+ /// `unprotected`: wherever the plan lets the Space reach something, the
+ /// settings allow it.
+ #[test]
+ fn no_start_is_less_strict_than_asked(s in settings()) {
+ let c = ctx();
+ let asked = compile_mode(&s, &c, Mode::Secure).unwrap();
+ for support in every_support() {
+ let p = plan(&s, support, &c, Mode::Secure).unwrap();
+ if let NetworkPlan::Open { .. } = p {
+ prop_assert_eq!(s.preset, NetworkPreset::Unprotected);
+ continue;
+ }
+ for probe in PROBES {
+ for port in PORTS {
+ for proto in [Proto::Tcp, Proto::Udp] {
+ let ip = ip(probe);
+ if reaches(&p, ip, proto, port) == Some(true) {
+ prop_assert!(asked.allows_port(ip, proto, port),
+ "{:?} {:?} reaches {} {}", s, support, probe, port);
+ }
+ }
+ }
+ }
+ }
+ // And whatever is asked, the platform denies hold.
+ for probe in ["169.254.169.254", "fd00:ec2::254", "172.30.1.9"] {
+ prop_assert!(!asked.allows_port(ip(probe), Proto::Tcp, 80));
+ }
+ for host in ["10.0.2.2", "192.168.1.20"] {
+ prop_assert!(!asked.allows_port(ip(host), Proto::Tcp, 3200));
+ }
+ // Only localhost (or no protection) reaches the host.
+ if !matches!(s.preset, NetworkPreset::Localhost | NetworkPreset::Unprotected) {
+ for host in ["10.0.2.2", "192.168.64.1", "192.168.1.20", "203.0.113.7", "::ffff:10.0.2.2"] {
+ for port in PORTS {
+ prop_assert!(!asked.allows_port(ip(host), Proto::Tcp, port), "{:?} {}", s, host);
+ }
+ }
+ }
+ }
+
+ /// A child's settings, intersected with its parent's, reach nothing
+ /// either of them would not.
+ #[test]
+ fn a_child_never_reaches_more_than_its_parent(child in settings(), parent in settings()) {
+ let c = ctx();
+ let both = child.intersect(&parent);
+ prop_assert!(both.validate().is_ok(), "{:?}", both);
+ let r = compile_mode(&both, &c, Mode::Secure).unwrap();
+ let rc = compile_mode(&child, &c, Mode::Secure).unwrap();
+ let rp = compile_mode(&parent, &c, Mode::Secure).unwrap();
+ for probe in PROBES {
+ for port in PORTS {
+ let ip = ip(probe);
+ if r.allows_port(ip, Proto::Tcp, port) {
+ prop_assert!(rc.allows_port(ip, Proto::Tcp, port) && rp.allows_port(ip, Proto::Tcp, port),
+ "{:?} ∩ {:?} = {:?} reaches {} {}", child, parent, both, probe, port);
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn intersections_keep_what_both_allow() {
+ let both = localhost(&[5432]).intersect(&localhost(&[5432, 3000]));
+ assert_eq!(both, localhost(&[5432]));
+ let both = localhost(&[5432]).intersect(&NetworkSettings::preset(NetworkPreset::Lan));
+ assert_eq!(both, NetworkSettings::internet());
+ let both = NetworkSettings::internet().intersect(&custom(
+ NetworkPreset::Internet,
+ &["1.1.1.1"],
+ &["all"],
+ ));
+ let r = secure(&both);
+ assert!(r.allows(ip("1.1.1.1")) && !r.allows(ip("8.8.8.8")));
+ let both =
+ NetworkSettings::preset(NetworkPreset::Unprotected).intersect(&NetworkSettings::internet());
+ assert_eq!(both, NetworkSettings::internet());
+ let both = NetworkSettings::internet().intersect(&NetworkSettings::none());
+ assert_eq!(both, NetworkSettings::none());
+ // A child's LAN allow under an internet-only parent is dropped.
+ let both = custom(NetworkPreset::Internet, &["192.168.1.0/24"], &[])
+ .intersect(&NetworkSettings::internet());
+ assert!(both.custom.allow.is_empty(), "{both:?}");
+}
+
+#[test]
+fn net_helpers() {
+ assert!(net("10.0.0.0/8").covers(&net("10.1.0.0/16")));
+ assert!(!net("10.1.0.0/16").covers(&net("10.0.0.0/8")));
+ assert!(net("10.1.0.0/16").overlaps(&net("10.0.0.0/8")));
+ assert!(!net("10.0.0.0/8").overlaps(&net("::/0")));
+ assert_eq!(
+ Net::host(IpAddr::V4(Ipv4Addr::LOCALHOST)),
+ net("127.0.0.1/32")
+ );
+ assert_eq!(Net::host(IpAddr::V6(Ipv6Addr::LOCALHOST)), net("::1/128"));
+ assert!(Net::parse("all").is_err());
+}
+
+#[test]
+fn vms_forward_listed_localhost_ports_only() {
+ if Mode::from_env() == Mode::Legacy {
+ return;
+ }
+ assert_eq!(vm_localhost_ports(None).unwrap(), Vec::<u16>::new());
+ assert_eq!(
+ vm_localhost_ports(Some(&NetworkSettings::internet())).unwrap(),
+ Vec::<u16>::new()
+ );
+ let mut s = localhost(&[5432, 3000, 5432]);
+ assert_eq!(vm_localhost_ports(Some(&s)).unwrap(), [3000, 5432]);
+ s.all_localhost_ports = true;
+ let e = vm_localhost_ports(Some(&s)).unwrap_err();
+ assert!(e.0.contains("list them"), "{e}");
+ assert_eq!(pasta_out_spec(&[]), "none");
+ assert_eq!(pasta_out_spec(&[3000, 5432]), "3000,5432");
+}
diff --git a/libs/cua/crates/cua-vmm/src/qemu/mod.rs b/libs/cua/crates/cua-vmm/src/qemu/mod.rs
index d4b3ee63f1..32fad0023c 100644
--- a/libs/cua/crates/cua-vmm/src/qemu/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/qemu/mod.rs
@@ -226,6 +226,10 @@ pub struct QemuState {
/// inherit it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub egress: Option<crate::egress::EgressPolicy>,
+ /// Its network settings ([`crate::network`]); `None`: kept from before
+ /// them (its egress policy is migrated at start). Forks inherit them.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub network: Option<crate::network::NetworkSettings>,
/// The current run is inside its own network namespace (pasta), where
/// the egress policy is enforced.
#[serde(default)]
@@ -803,6 +807,7 @@ impl QemuRuntime {
ssh: spec_like.ssh.clone(),
restrict_network: spec_like.restrict_network,
egress: None,
+ network: None,
netns: false,
pasta_pid: None,
extra_args: spec_like.extra_args.clone(),
@@ -1164,10 +1169,30 @@ impl QemuRuntime {
// An egress policy that blocks anything: the VM runs inside its
// own network namespace, where the policy is enforced
// ([`netns_script`]).
- let netns_rules = match st.egress.as_ref() {
- Some(p) => Some(crate::egress::check(BackendKind::Qemu, p)?)
- .filter(crate::egress::Rules::blocks_anything),
- None => None,
+ //
+ // Under the secure default ([`crate::network`]) every VM on Linux
+ // runs in that namespace, policy or not: its network settings are
+ // compiled there (the host's own addresses closed, pasta's resolver
+ // open on 53) and the host's loopback is out of reach (`--no-map-gw`;
+ // `10.0.2.2` is the namespace's own loopback). Elsewhere QEMU has no
+ // such point: a runtime above refuses or starts it without network.
+ let secure = secure_netns();
+ let netns_rules = if secure {
+ Some(
+ crate::network::vm_rules(
+ st.network.as_ref(),
+ st.egress.as_ref(),
+ st.restrict_network || spec.restrict_network,
+ &netns_context(),
+ )
+ .map_err(VmmError::from)?,
+ )
+ } else {
+ match st.egress.as_ref() {
+ Some(p) => Some(crate::egress::check(BackendKind::Qemu, p)?)
+ .filter(crate::egress::Rules::blocks_anything),
+ None => None,
+ }
};
st.accel = if force_tcg {
"tcg".into()
@@ -1176,7 +1201,17 @@ impl QemuRuntime {
};
st.cpus = spec.cpus;
st.memory_mb = spec.memory_mb;
- st.restrict_network = spec.restrict_network;
+ st.restrict_network = spec.restrict_network
+ || st
+ .network
+ .as_ref()
+ .is_some_and(|n| n.preset == crate::network::NetworkPreset::None);
+ // No point to enforce rules on this host (macOS, Windows): no
+ // network at all (`restrict=on`; its published ports still answer)
+ // unless the user chose No protection.
+ if let Some(plan) = crate::network::gate(BackendKind::Qemu, &st.name, &qemu_settings(st))? {
+ st.restrict_network = !matches!(plan, crate::network::NetworkPlan::Open { .. });
+ }
if spec.gpu.is_some() {
st.gpu = spec.gpu.clone();
}
@@ -1317,11 +1352,12 @@ impl QemuRuntime {
let pasta = host::which("pasta").ok_or_else(|| {
VmmError::missing(
"pasta",
- "install passt (Ubuntu: sudo apt-get install passt): a QEMU VM with \
- an egress policy runs in a network namespace pasta creates",
+ "install passt (Ubuntu: sudo apt-get install passt): a QEMU VM runs \
+ in a network namespace pasta creates, which keeps it off this \
+ computer and your local network",
)
})?;
- std::fs::write(dir.join(NETNS_SCRIPT), netns_script(rules))?;
+ std::fs::write(dir.join(NETNS_SCRIPT), netns_script(rules, !secure))?;
let mut ports: Vec<u16> = st.ports.values().copied().collect();
if st.qmp_socket.is_none() {
ports.push(qmp_port);
@@ -1329,7 +1365,13 @@ impl QemuRuntime {
if let Some(d) = st.vnc_display {
ports.push(5900 + d);
}
- let mut a = netns_pasta_args(&ports);
+ let localhost = if secure {
+ crate::network::vm_localhost_ports(st.network.as_ref())
+ .map_err(VmmError::from)?
+ } else {
+ Vec::new()
+ };
+ let mut a = netns_pasta_args(&ports, &localhost);
a.push(NETNS_SCRIPT.into());
a.push(bin.display().to_string());
a.extend(argv.iter().cloned());
@@ -2073,7 +2115,10 @@ const SLIRP_DNS: std::net::Ipv4Addr = std::net::Ipv4Addr::new(10, 0, 2, 3);
/// host's resolver through [`DNS_FWD`], no way to the host's own loopback,
/// then the script.
#[cfg_attr(not(unix), allow(dead_code))]
-fn netns_pasta_args(ports: &[u16]) -> Vec<String> {
+fn netns_pasta_args(ports: &[u16], localhost: &[u16]) -> Vec<String> {
+ // The `localhost` preset's ports only: the guest reaches them as
+ // `10.0.2.2:<port>` (the namespace's loopback, forwarded to the host's).
+ let out = crate::network::pasta_out_spec(localhost);
let mut a: Vec<String> = [
"--config-net",
"-q",
@@ -2081,7 +2126,7 @@ fn netns_pasta_args(ports: &[u16]) -> Vec<String> {
"-u",
"none",
"-T",
- "none",
+ out.as_str(),
"-U",
"none",
"--dns-forward",
@@ -2106,28 +2151,25 @@ fn netns_pasta_args(ports: &[u16]) -> Vec<String> {
/// The script run in a VM's namespace before QEMU: the egress rules on
/// `OUTPUT` (QEMU's user-mode network opens the guest's connections from
-/// QEMU itself), a private `/etc/resolv.conf` naming pasta's DNS forward
-/// (whose verdict is the policy's for the guest's resolver, `10.0.2.3`),
-/// then QEMU (`$@`).
+/// QEMU itself), a private `/etc/resolv.conf` naming pasta's DNS forward,
+/// then QEMU (`$@`). `legacy`: an old policy's rules, where the forward
+/// gets the verdict of the guest's resolver (`10.0.2.3`); compiled network
+/// settings name the forward themselves ([`netns_context`]).
#[cfg_attr(not(unix), allow(dead_code))]
-fn netns_script(rules: &crate::egress::Rules) -> String {
- let resolver = crate::egress::Resolver {
- guest: SLIRP_DNS,
- forward: DNS_FWD,
- };
+fn netns_script(rules: &crate::egress::Rules, legacy: bool) -> String {
format!(
"{rules}printf 'nameserver {DNS_FWD}\\n' > \"$PWD/resolv.conf\"\n\
exec unshare -m sh -c 'mount --bind \"$0\" /etc/resolv.conf && exec \"$@\"' \"$PWD/resolv.conf\" \"$@\"\n",
- rules = crate::egress::ns_script(rules, crate::egress::NsHook::Output, Some(resolver)),
+ rules = netns_rules_script(rules, legacy),
)
}
/// The rules of a running namespaced VM, refilled ([`netns_script`]'s).
-fn netns_rules_script(rules: &crate::egress::Rules) -> String {
+fn netns_rules_script(rules: &crate::egress::Rules, legacy: bool) -> String {
crate::egress::ns_script(
rules,
crate::egress::NsHook::Output,
- Some(crate::egress::Resolver {
+ legacy.then_some(crate::egress::Resolver {
guest: SLIRP_DNS,
forward: DNS_FWD,
}),
@@ -2212,6 +2254,39 @@ fn vnc_password() -> String {
random_token(8)
}
+/// A VM's network settings: its own, or its old policy migrated.
+fn qemu_settings(st: &QemuState) -> crate::network::NetworkSettings {
+ st.network.clone().unwrap_or_else(|| {
+ crate::network::NetworkSettings::migrate(
+ &st.egress.clone().unwrap_or_default(),
+ st.restrict_network,
+ )
+ })
+}
+
+/// Whether VMs run in a pasta namespace with compiled network settings:
+/// on Linux, under the secure default.
+fn secure_netns() -> bool {
+ cfg!(target_os = "linux") && crate::network::Mode::from_env() == crate::network::Mode::Secure
+}
+
+/// What a VM's namespace knows for [`crate::network::compile`]: pasta's DNS
+/// forward is the resolver (open on 53); the host's own addresses (pasta
+/// would reach them) and the daemon's ports are closed. The host's loopback
+/// is not mapped at all (`--no-map-gw`), and `10.0.2.2` is the namespace's
+/// own loopback, where only this VM's forwards listen (QMP is a unix
+/// socket).
+fn netns_context() -> crate::network::NetworkContext {
+ crate::network::NetworkContext {
+ resolvers: vec![std::net::IpAddr::V4(DNS_FWD)],
+ host_aliases: vec![],
+ host_addrs: crate::network::host_addresses(),
+ tree: vec![],
+ other_trees: vec![],
+ daemon_ports: crate::network::daemon_ports(),
+ }
+}
+
/// The first child of process `pid` (pasta's command).
#[cfg_attr(not(unix), allow(dead_code))]
fn netns_child(pid: u32) -> Option<u32> {
@@ -2470,6 +2545,7 @@ impl Runtime for QemuRuntime {
ssh: None,
restrict_network: false,
egress: None,
+ network: None,
netns: false,
pasta_pid: None,
extra_args: vec![],
@@ -2519,7 +2595,17 @@ impl Runtime for QemuRuntime {
crate::types::reject_sidecars(BackendKind::Qemu, spec)?;
crate::types::reject_mounts(BackendKind::Qemu, spec)?;
crate::types::reject_injection(BackendKind::Qemu, spec)?;
- crate::egress::check(BackendKind::Qemu, &spec.egress)?;
+ // Under the secure default a host with no point for rules starts the
+ // VM without network instead of refusing its lists (`launch_once`).
+ if crate::network::gate(
+ BackendKind::Qemu,
+ &spec.name,
+ &crate::network::spec_settings(spec),
+ )?
+ .is_none()
+ {
+ crate::egress::check(BackendKind::Qemu, &spec.egress)?;
+ }
crate::cloudinit::check_guest_support(spec)?;
windows_arm_host(
spec.os,
@@ -2589,6 +2675,19 @@ impl Runtime for QemuRuntime {
if st.egress.is_none() && !spec.egress.is_empty() {
st.egress = Some(spec.egress.clone());
}
+ // Network settings: the same (a VM from before them takes the
+ // spec's, else its policy is migrated at launch).
+ if st.network.is_none() {
+ st.network = spec.network.clone();
+ }
+ // A VM asked to have no network gets QEMU's `restrict=on` too.
+ if spec
+ .network
+ .as_ref()
+ .is_some_and(|n| n.preset == crate::network::NetworkPreset::None)
+ {
+ st.restrict_network = true;
+ }
// A new VM of a configuration with a golden snapshot restores it
// (recording it first if needed) instead of booting.
if let Some(backing) = fresh_backing.as_deref()
@@ -3146,21 +3245,39 @@ impl Runtime for QemuRuntime {
name: &str,
policy: &crate::egress::EgressPolicy,
) -> Result<crate::egress::Enforcement> {
- let rules = crate::egress::check(BackendKind::Qemu, policy)?;
+ let legacy_rules = crate::egress::check(BackendKind::Qemu, policy)?;
let _owner = self.own(name).await;
let _g = self.lock.lock().await;
let mut st = self.load(name)?;
if st.kind != EntryKind::Instance {
return Err(VmmError::invalid(format!("'{name}' is not a VM instance")));
}
- if Self::is_running(&st) && !st.netns && rules.blocks_anything() {
+ if Self::is_running(&st) && !st.netns && legacy_rules.blocks_anything() {
refuse_tpm(&st, "a move into a new network namespace")?;
}
let previous = st.egress.replace(policy.clone());
+ let previous_network = st.network.clone();
+ // The lists are its network settings' own lists too.
+ st.network = Some(crate::network::NetworkSettings::with_lists(
+ st.network.take(),
+ policy,
+ ));
+ let secure = secure_netns();
+ let rules = if secure {
+ crate::network::vm_rules(
+ st.network.as_ref(),
+ None,
+ st.restrict_network,
+ &netns_context(),
+ )
+ .map_err(VmmError::from)?
+ } else {
+ legacy_rules
+ };
if Self::is_running(&st) {
let applied = if st.netns {
let pid = st.pid.expect("running");
- crate::egress::ns_apply(pid, &netns_rules_script(&rules)).await
+ crate::egress::ns_apply(pid, &netns_rules_script(&rules, !secure)).await
} else if rules.blocks_anything() {
self.relaunch(&mut st).await
} else {
@@ -3170,6 +3287,7 @@ impl Runtime for QemuRuntime {
if Self::is_running(&st) {
// Still in its old process: keep what it had.
st.egress = previous;
+ st.network = previous_network;
}
let _ = self.save(&st);
return Err(e);
@@ -3183,6 +3301,49 @@ impl Runtime for QemuRuntime {
Ok(self.load(name)?.egress.unwrap_or_default())
}
+ /// Kept with the VM. In its namespace (Linux) the rules are refilled at
+ /// once, except what pasta fixes at launch (the localhost ports), which
+ /// changes at its next start; elsewhere at its next start.
+ async fn set_network(
+ &self,
+ name: &str,
+ settings: &crate::network::NetworkSettings,
+ ) -> Result<crate::network::Applied> {
+ settings.validate()?;
+ let _g = self.lock.lock().await;
+ let mut st = self.load(name)?;
+ if st.kind != EntryKind::Instance {
+ return Err(VmmError::invalid(format!("'{name}' is not a VM instance")));
+ }
+ let before = st.network.clone();
+ st.network = Some(settings.clone());
+ st.egress = Some(settings.custom.clone());
+ let ports_change = crate::network::vm_localhost_ports(before.as_ref()).ok()
+ != crate::network::vm_localhost_ports(Some(settings)).ok();
+ let restrict_change =
+ (settings.preset == crate::network::NetworkPreset::None) != st.restrict_network;
+ let applied = if Self::is_running(&st) && st.netns && secure_netns() {
+ let rules = crate::network::vm_rules(
+ st.network.as_ref(),
+ None,
+ st.restrict_network,
+ &netns_context(),
+ )
+ .map_err(VmmError::from)?;
+ let pid = st.pid.expect("running");
+ crate::egress::ns_apply(pid, &netns_rules_script(&rules, false)).await?;
+ if ports_change || restrict_change {
+ crate::network::Applied::NextStart
+ } else {
+ crate::network::Applied::Now
+ }
+ } else {
+ crate::network::Applied::NextStart
+ };
+ self.save(&st)?;
+ Ok(applied)
+ }
+
async fn delete_checkpoint(&self, checkpoint: &str) -> Result<()> {
if let Some((vm, snap)) = checkpoint.split_once('@') {
let mut st = self.load(vm)?;
@@ -3963,6 +4124,41 @@ mod tests {
assert!(image.exists(), "the source image is never deleted");
}
+ #[test]
+ fn the_secure_default_namespace_closes_the_host_and_opens_dns() {
+ let mut ctx = netns_context();
+ ctx.host_addrs = vec!["10.0.1.5".parse().unwrap()];
+ ctx.daemon_ports = vec![4100];
+ let rules = crate::network::compile_mode(
+ &crate::network::NetworkSettings::internet(),
+ &ctx,
+ crate::network::Mode::Secure,
+ )
+ .unwrap();
+ let s = netns_script(&rules, false);
+ // pasta's DNS forward is open on 53 (no legacy verdict line).
+ assert!(
+ s.contains(
+ "-p udp -m conntrack --ctorigdst 169.254.1.53/32 --ctorigdstport 53 -j ACCEPT"
+ ),
+ "{s}"
+ );
+ assert!(!s.contains("-d 169.254.1.53/32 -p udp --dport 53"), "{s}");
+ // The host's own addresses, every address local to the namespace,
+ // metadata and the private ranges are closed.
+ assert!(s.contains("--ctorigdst 10.0.1.5/32 -j DROP"), "{s}");
+ assert!(s.contains("-m addrtype --dst-type LOCAL -j DROP"), "{s}");
+ assert!(s.contains("--ctorigdst 169.254.169.254/32 -j DROP"), "{s}");
+ assert!(s.contains("--ctorigdst 10.0.0.0/8 -j DROP"), "{s}");
+ // The daemon's port on every local address.
+ assert!(
+ s.contains(
+ "-p tcp -m addrtype --dst-type LOCAL -m conntrack --ctorigdstport 4100 -j DROP"
+ ),
+ "{s}"
+ );
+ }
+
#[test]
fn qmp_never_listens_where_the_guest_can_reach_it() {
assert_eq!(
@@ -4006,7 +4202,7 @@ mod tests {
}
.parse()
.unwrap();
- let s = netns_script(&rules);
+ let s = netns_script(&rules, true);
// The rules, on OUTPUT (QEMU itself opens the guest's
// connections), then QEMU: never the other way round.
let rules_at = s.find("iptables-restore --noflush").expect("rules");
@@ -4036,8 +4232,16 @@ mod tests {
}
.parse()
.unwrap();
- assert!(netns_script(&allowed).contains("-d 169.254.1.53/32 -p udp --dport 53 -j ACCEPT"));
- let a = netns_pasta_args(&[4000, 5901]);
+ assert!(
+ netns_script(&allowed, true).contains("-d 169.254.1.53/32 -p udp --dport 53 -j ACCEPT")
+ );
+ let a = netns_pasta_args(&[4000, 5901], &[]);
+ assert!(a.windows(2).any(|w| w[0] == "-T" && w[1] == "none"));
+ let open = netns_pasta_args(&[4000], &[5432, 3000]);
+ assert!(
+ open.windows(2).any(|w| w[0] == "-T" && w[1] == "5432,3000"),
+ "{open:?}"
+ );
let has = |pair: [&str; 2]| a.windows(2).any(|w| w[0] == pair[0] && w[1] == pair[1]);
assert!(has(["-t", "127.0.0.1/4000:4000"]) && has(["-t", "127.0.0.1/5901:5901"]));
assert!(has(["--dns-forward", "169.254.1.53"]));
diff --git a/libs/cua/crates/cua-vmm/src/qemu/snapshot.rs b/libs/cua/crates/cua-vmm/src/qemu/snapshot.rs
index d30ee698a4..477ea01322 100644
--- a/libs/cua/crates/cua-vmm/src/qemu/snapshot.rs
+++ b/libs/cua/crates/cua-vmm/src/qemu/snapshot.rs
@@ -515,6 +515,7 @@ impl QemuRuntime {
// identity, no workload): the Space's own run is the one its
// policy applies to, from its restore on.
egress: None,
+ network: None,
netns: false,
pasta_pid: None,
shared_memory: false,
@@ -1335,6 +1336,7 @@ mod tests {
bulk: false,
tpm: false,
egress: None,
+ network: None,
netns: false,
pasta_pid: None,
}
diff --git a/libs/cua/crates/cua-vmm/src/runtime.rs b/libs/cua/crates/cua-vmm/src/runtime.rs
index 32d7abc548..b2f7e7c405 100644
--- a/libs/cua/crates/cua-vmm/src/runtime.rs
+++ b/libs/cua/crates/cua-vmm/src/runtime.rs
@@ -208,6 +208,22 @@ pub trait Runtime: Send + Sync {
let _ = name;
Ok(Default::default())
}
+
+ /// Replaces instance `name`'s network settings ([`crate::network`]),
+ /// kept with it from now on (they win over a later start spec's). Says
+ /// whether the running guest is under them now or from its next start.
+ /// Runtimes that keep none refuse.
+ async fn set_network(
+ &self,
+ name: &str,
+ settings: &crate::network::NetworkSettings,
+ ) -> Result<crate::network::Applied> {
+ let _ = (name, settings);
+ Err(VmmError::Unsupported {
+ backend: self.kind().as_str(),
+ op: "changing network settings (this runtime keeps none: create the Space again)",
+ })
+ }
}
/// Resolves an OCI reference to a local bootable disk (qcow2). Implemented by
diff --git a/libs/cua/crates/cua-vmm/src/types.rs b/libs/cua/crates/cua-vmm/src/types.rs
index bf6ca995af..f1f52947e9 100644
--- a/libs/cua/crates/cua-vmm/src/types.rs
+++ b/libs/cua/crates/cua-vmm/src/types.rs
@@ -267,6 +267,17 @@ pub struct StartSpec {
/// forks apply it again, and [`crate::Runtime::set_egress`] replaces it.
#[serde(default, skip_serializing_if = "crate::egress::EgressPolicy::is_empty")]
pub egress: crate::egress::EgressPolicy,
+ /// The Space's network settings ([`crate::network`]): its preset and
+ /// lists, compiled by the runtime with what only it knows (resolver,
+ /// host aliases, tree). `None`: a caller from before network settings;
+ /// the runtime keeps to `restrict_network` and `egress`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub network: Option<crate::network::NetworkSettings>,
+ /// The tree the sandbox belongs to (its top-level Space's id): members
+ /// of one tree share a network and reach each other; other trees are
+ /// blocked. `None`: a tree of its own.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tree: Option<String>,
#[serde(default)]
pub labels: BTreeMap<String, String>,
/// Backend-specific extra arguments (appended to the qemu command line).
@@ -476,6 +487,14 @@ pub fn reject_restricted_network(backend: BackendKind, spec: &StartSpec) -> crat
if !spec.restrict_network {
return Ok(());
}
+ // Under the secure default a container's network is cut by its rules
+ // on the engine host (`none` drops everything), its published ports
+ // still answering.
+ if matches!(backend, BackendKind::Container | BackendKind::Managed)
+ && crate::network::Mode::from_env() == crate::network::Mode::Secure
+ {
+ return Ok(());
+ }
Err(crate::VmmError::Unsupported {
backend: backend.as_str(),
op: match backend {
@@ -614,6 +633,8 @@ impl StartSpec {
cloud_init_user_data: None,
restrict_network: false,
egress: Default::default(),
+ network: None,
+ tree: None,
labels: BTreeMap::new(),
extra_args: Vec::new(),
sidecars: Vec::new(),
@@ -904,9 +925,14 @@ mod tests {
assert!(reject_restricted_network(b, &spec).is_ok());
}
spec.restrict_network = true;
- for b in [BackendKind::Container, BackendKind::Lume] {
- let e = reject_restricted_network(b, &spec).unwrap_err().to_string();
- assert!(e.contains("network=\"none\""), "{e}");
+ let e = reject_restricted_network(BackendKind::Lume, &spec)
+ .unwrap_err()
+ .to_string();
+ assert!(e.contains("network=\"none\""), "{e}");
+ // A container cuts it with its engine-host rules under the secure
+ // default (the test process runs with it unless told otherwise).
+ if crate::network::Mode::from_env() == crate::network::Mode::Secure {
+ assert!(reject_restricted_network(BackendKind::Container, &spec).is_ok());
}
}
diff --git a/libs/cua/crates/cua-vmm/tests/lume_dev_image.rs b/libs/cua/crates/cua-vmm/tests/lume_dev_image.rs
new file mode 100644
index 0000000000..587a1b2672
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/tests/lume_dev_image.rs
@@ -0,0 +1,181 @@
+//! The macOS Space with developer tools (`macos:26-xcode`) is pulled like the
+//! other macOS images; when it cannot be, or the user prefers their own
+//! Xcode (`CUA_DEV_IMAGE=local`), it is built on their Mac from the full
+//! image's base (held, else pulled) with a disk check before anything starts.
+//! A built base is cloned like any other. Nothing here builds with a real
+//! Xcode.
+//!
+//! Hermetic: a fake `lume serve` records the API calls; the build itself
+//! (`derive-local.sh`) is covered by `lume::derive`'s tests and the live run.
+
+#![cfg(feature = "lume")]
+
+#[allow(dead_code)]
+#[path = "support/fake_lume.rs"]
+mod fake_lume;
+
+use std::sync::{Arc, Mutex};
+
+use cua_vmm::lume::{OwnedKind, OwnedVms, base_vm_name};
+use cua_vmm::{GuestOs, ImageSource, Runtime, StartSpec, VmmError};
+use fake_lume::{FakeLume, FakePull, PullEnd, serve, temp_home};
+use serde_json::json;
+
+const DEV: &str = "ghcr.io/trycua/macos:26-xcode";
+/// A full image base the SDK pulled earlier, under its dated pin.
+fn held_full() -> String {
+ format!(
+ "ghcr.io/trycua/macos:26-{}-fca2193@sha256:{}",
+ "20261021",
+ "a".repeat(64)
+ )
+}
+
+struct Space(u64);
+impl cua_vmm::disk::SpaceProbe for Space {
+ fn space(&self, _: &std::path::Path) -> std::io::Result<cua_vmm::disk::Space> {
+ Ok(cua_vmm::disk::Space {
+ available: self.0,
+ total: 1 << 50,
+ })
+ }
+}
+
+fn vm(name: &str) -> serde_json::Value {
+ json!({
+ "name": name, "os": "macOS", "cpuCount": 4, "memorySize": 8u64 << 30,
+ "diskSize": { "allocated": 1u64 << 30, "total": 150u64 << 30 },
+ "display": "1024x768", "status": "stopped"
+ })
+}
+
+fn spec(name: &str) -> StartSpec {
+ StartSpec::new(
+ name,
+ ImageSource::Oci {
+ reference: DEV.into(),
+ },
+ )
+ .os(GuestOs::Macos)
+ .cpus(2)
+ .memory_mb(4096)
+}
+
+fn pull(end: PullEnd) -> FakePull {
+ FakePull {
+ polls: 2,
+ step: 1 << 30,
+ total: 4 << 30,
+ end,
+ }
+}
+
+fn pulls(st: &FakeLume) -> Vec<String> {
+ st.calls
+ .iter()
+ .filter(|(_, p, _)| p == "/lume/pull/start")
+ .map(|(_, _, b)| b["image"].as_str().unwrap_or_default().to_string())
+ .collect()
+}
+
+/// One test, in order: the probe, the environment and the owned-VM records are
+/// process-wide.
+#[tokio::test]
+async fn the_published_image_is_pulled_building_is_the_fallback() {
+ temp_home();
+ let held = base_vm_name(&held_full());
+ let dev = base_vm_name(DEV);
+ OwnedVms::default().mark(&held, OwnedKind::Base, Some(&held_full()));
+
+ // 1. Published: a create pulls macos:26-xcode into the base and clones it.
+ cua_vmm::disk::set_probe(Some(Arc::new(Space(1 << 50))));
+ let state = Arc::new(Mutex::new(FakeLume {
+ pull: Some(pull(PullEnd::Completes)),
+ ..Default::default()
+ }));
+ let rt = fake_lume::runtime(serve(state.clone()).await);
+ rt.start(&spec("cua-dev-pulled")).await.unwrap();
+ {
+ let st = state.lock().unwrap();
+ assert_eq!(pulls(&st), ["macos:26-xcode"], "{:#?}", st.calls);
+ assert!(st.vms.contains_key(&dev) && st.vms.contains_key("cua-dev-pulled"));
+ }
+
+ // 2. Not published (the pull fails) and the full image is held: it falls
+ // back to building, which checks its disk (more than a pull) before
+ // anything starts. The held full image is reused, not pulled.
+ cua_vmm::disk::set_probe(Some(Arc::new(Space(38 << 30))));
+ let mut st = FakeLume {
+ pull: Some(pull(PullEnd::Fails("manifest unknown".into()))),
+ ..Default::default()
+ };
+ st.vms.insert(held.clone(), vm(&held));
+ let state = Arc::new(Mutex::new(st));
+ let rt = fake_lume::runtime(serve(state.clone()).await);
+ let err = rt.start(&spec("cua-dev-refused")).await.unwrap_err();
+ assert!(matches!(err, VmmError::InsufficientDisk(_)), "{err:?}");
+ let msg = err.to_string();
+ assert!(
+ msg.contains("build the macOS Space with developer tools")
+ && msg.contains("cua cache prune"),
+ "{msg}"
+ );
+ {
+ let st = state.lock().unwrap();
+ assert_eq!(
+ pulls(&st),
+ ["macos:26-xcode"],
+ "only the published image was tried"
+ );
+ assert!(!st.vms.contains_key(&dev) && !st.vms.contains_key("cua-dev-refused"));
+ }
+ assert!(
+ !OwnedVms::default().owns(&dev),
+ "no record of a build that never began"
+ );
+
+ // 3. A Mac that prefers its own Xcode never tries the pull.
+ // SAFETY: the only test in this binary; no other thread reads the environment.
+ unsafe { std::env::set_var("CUA_DEV_IMAGE", "local") };
+ // (the fake keeps a failed pull's record; a real Lume removes it)
+ state.lock().unwrap().pulling.clear();
+ state.lock().unwrap().calls.clear();
+ let err = rt.start(&spec("cua-dev-local")).await.unwrap_err();
+ assert!(matches!(err, VmmError::InsufficientDisk(_)), "{err:?}");
+ assert!(
+ pulls(&state.lock().unwrap()).is_empty(),
+ "no pull when local is preferred"
+ );
+ unsafe { std::env::remove_var("CUA_DEV_IMAGE") };
+
+ // 4. The base exists (pulled or built earlier): a new Space is a clone of
+ // it. No pull, no build.
+ cua_vmm::disk::set_probe(Some(Arc::new(Space(1 << 50))));
+ state.lock().unwrap().vms.insert(dev.clone(), vm(&dev));
+ state.lock().unwrap().calls.clear();
+ rt.start(&spec("cua-dev-clone")).await.unwrap();
+ let st = state.lock().unwrap();
+ assert!(pulls(&st).is_empty(), "{:#?}", st.calls);
+ let writes: Vec<String> = st
+ .calls
+ .iter()
+ .filter(|(m, _, _)| m != "GET")
+ .map(|(m, p, _)| format!("{m} {p}"))
+ .collect();
+ assert_eq!(
+ writes,
+ [
+ "POST /lume/vms/clone",
+ "PATCH /lume/vms/cua-dev-clone",
+ "POST /lume/vms/cua-dev-clone/run",
+ ],
+ "{:#?}",
+ st.calls
+ );
+ let (_, _, clone) = st
+ .calls
+ .iter()
+ .find(|(_, p, _)| p == "/lume/vms/clone")
+ .unwrap();
+ assert_eq!(clone["name"], json!(dev), "cloned from the base: {clone}");
+}
diff --git a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt
index 756f7ed9b8..3a3e0cee87 100644
--- a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt
+++ b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt
@@ -1361,6 +1361,8 @@ external fun uniffi_cua_sdk_checksum_method_space_checkpoint(
): Short
external fun uniffi_cua_sdk_checksum_method_space_close_stream(
): Short
+external fun uniffi_cua_sdk_checksum_method_space_delete_service(
+): Short
external fun uniffi_cua_sdk_checksum_method_space_displays(
): Short
external fun uniffi_cua_sdk_checksum_method_space_download(
@@ -1379,18 +1381,26 @@ external fun uniffi_cua_sdk_checksum_method_space_info(
): Short
external fun uniffi_cua_sdk_checksum_method_space_join_presence(
): Short
+external fun uniffi_cua_sdk_checksum_method_space_kept_services(
+): Short
external fun uniffi_cua_sdk_checksum_method_space_list_tools(
): Short
external fun uniffi_cua_sdk_checksum_method_space_open_stream(
): Short
+external fun uniffi_cua_sdk_checksum_method_space_put_service(
+): Short
external fun uniffi_cua_sdk_checksum_method_space_request_site_login(
): Short
+external fun uniffi_cua_sdk_checksum_method_space_restart_service(
+): Short
external fun uniffi_cua_sdk_checksum_method_space_route(
): Short
external fun uniffi_cua_sdk_checksum_method_space_screenshot(
): Short
external fun uniffi_cua_sdk_checksum_method_space_send_file(
): Short
+external fun uniffi_cua_sdk_checksum_method_space_service_logs(
+): Short
external fun uniffi_cua_sdk_checksum_method_space_services(
): Short
external fun uniffi_cua_sdk_checksum_method_space_set_presence_settings(
@@ -1403,8 +1413,12 @@ external fun uniffi_cua_sdk_checksum_method_space_spacesd(
): Short
external fun uniffi_cua_sdk_checksum_method_space_start_hotspot(
): Short
+external fun uniffi_cua_sdk_checksum_method_space_start_service(
+): Short
external fun uniffi_cua_sdk_checksum_method_space_stop_hotspot(
): Short
+external fun uniffi_cua_sdk_checksum_method_space_stop_service(
+): Short
external fun uniffi_cua_sdk_checksum_method_space_stream_session(
): Short
external fun uniffi_cua_sdk_checksum_method_space_supports(
@@ -1529,6 +1543,8 @@ external fun uniffi_cua_sdk_checksum_method_spaces_routine_set_enabled(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_routines(
): Short
+external fun uniffi_cua_sdk_checksum_method_spaces_ack_network_notice(
+): Short
external fun uniffi_cua_sdk_checksum_method_spaces_add(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_add_with_service(
@@ -1549,6 +1565,8 @@ external fun uniffi_cua_sdk_checksum_method_spaces_delete(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_delete_many(
): Short
+external fun uniffi_cua_sdk_checksum_method_spaces_delete_tree(
+): Short
external fun uniffi_cua_sdk_checksum_method_spaces_delete_volume(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_fork(
@@ -1567,6 +1585,10 @@ external fun uniffi_cua_sdk_checksum_method_spaces_list_tools_json(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_machine_health(
): Short
+external fun uniffi_cua_sdk_checksum_method_spaces_network(
+): Short
+external fun uniffi_cua_sdk_checksum_method_spaces_orphans(
+): Short
external fun uniffi_cua_sdk_checksum_method_spaces_relay_register(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_relay_unregister(
@@ -1581,10 +1603,16 @@ external fun uniffi_cua_sdk_checksum_method_spaces_resolve(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_resources(
): Short
+external fun uniffi_cua_sdk_checksum_method_spaces_set_children(
+): Short
external fun uniffi_cua_sdk_checksum_method_spaces_set_egress(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_set_lifetime(
): Short
+external fun uniffi_cua_sdk_checksum_method_spaces_set_network(
+): Short
+external fun uniffi_cua_sdk_checksum_method_spaces_set_tree_budget(
+): Short
external fun uniffi_cua_sdk_checksum_method_spaces_space(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_start(
@@ -1593,6 +1621,8 @@ external fun uniffi_cua_sdk_checksum_method_spaces_stop(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_suspend(
): Short
+external fun uniffi_cua_sdk_checksum_method_spaces_tree_budget(
+): Short
external fun uniffi_cua_sdk_checksum_method_spaces_volume_approve(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_volume_audit(
@@ -2394,6 +2424,8 @@ external fun uniffi_cua_sdk_fn_method_space_checkpoint(`ptr`: Long,`checkpoint`:
): Long
external fun uniffi_cua_sdk_fn_method_space_close_stream(`ptr`: Long,`mediaSessionId`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_space_delete_service(`ptr`: Long,`name`: RustBuffer.ByValue,
+): Long
external fun uniffi_cua_sdk_fn_method_space_displays(`ptr`: Long,
): Long
external fun uniffi_cua_sdk_fn_method_space_download(`ptr`: Long,`remotePath`: RustBuffer.ByValue,`destDir`: RustBuffer.ByValue,
@@ -2412,18 +2444,26 @@ external fun uniffi_cua_sdk_fn_method_space_info(`ptr`: Long,uniffi_out_err: Uni
): RustBuffer.ByValue
external fun uniffi_cua_sdk_fn_method_space_join_presence(`ptr`: Long,`identity`: RustBuffer.ByValue,`timeoutMs`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_space_kept_services(`ptr`: Long,
+): Long
external fun uniffi_cua_sdk_fn_method_space_list_tools(`ptr`: Long,`service`: RustBuffer.ByValue,
): Long
external fun uniffi_cua_sdk_fn_method_space_open_stream(`ptr`: Long,`options`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_space_put_service(`ptr`: Long,`def`: RustBuffer.ByValue,
+): Long
external fun uniffi_cua_sdk_fn_method_space_request_site_login(`ptr`: Long,`url`: RustBuffer.ByValue,`options`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_space_restart_service(`ptr`: Long,`name`: RustBuffer.ByValue,
+): Long
external fun uniffi_cua_sdk_fn_method_space_route(`ptr`: Long,
): Long
external fun uniffi_cua_sdk_fn_method_space_screenshot(`ptr`: Long,`options`: RustBuffer.ByValue,
): Long
external fun uniffi_cua_sdk_fn_method_space_send_file(`ptr`: Long,`localPath`: RustBuffer.ByValue,`options`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_space_service_logs(`ptr`: Long,`name`: RustBuffer.ByValue,`tailBytes`: RustBuffer.ByValue,
+): Long
external fun uniffi_cua_sdk_fn_method_space_services(`ptr`: Long,uniffi_out_err: UniffiRustCallStatus,
): RustBuffer.ByValue
external fun uniffi_cua_sdk_fn_method_space_set_presence_settings(`ptr`: Long,`cursorProbe`: RustBuffer.ByValue,
@@ -2436,8 +2476,12 @@ external fun uniffi_cua_sdk_fn_method_space_spacesd(`ptr`: Long,uniffi_out_err:
): Long
external fun uniffi_cua_sdk_fn_method_space_start_hotspot(`ptr`: Long,`setSystemProxy`: RustBuffer.ByValue,`bypass`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_space_start_service(`ptr`: Long,`name`: RustBuffer.ByValue,
+): Long
external fun uniffi_cua_sdk_fn_method_space_stop_hotspot(`ptr`: Long,
): Long
+external fun uniffi_cua_sdk_fn_method_space_stop_service(`ptr`: Long,`name`: RustBuffer.ByValue,
+): Long
external fun uniffi_cua_sdk_fn_method_space_stream_session(`ptr`: Long,`options`: RustBuffer.ByValue,`frames`: Long,`audio`: RustBuffer.ByValue,
): Long
external fun uniffi_cua_sdk_fn_method_space_supports(`ptr`: Long,`feature`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,
@@ -2580,6 +2624,8 @@ external fun uniffi_cua_sdk_fn_method_spaces_routine_set_enabled(`ptr`: Long,`id
): Long
external fun uniffi_cua_sdk_fn_method_spaces_routines(`ptr`: Long,`agent`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_spaces_ack_network_notice(`ptr`: Long,`space`: RustBuffer.ByValue,
+): Long
external fun uniffi_cua_sdk_fn_method_spaces_add(`ptr`: Long,`url`: RustBuffer.ByValue,`token`: RustBuffer.ByValue,`name`: RustBuffer.ByValue,
): Long
external fun uniffi_cua_sdk_fn_method_spaces_add_with_service(`ptr`: Long,`url`: RustBuffer.ByValue,`token`: RustBuffer.ByValue,`name`: RustBuffer.ByValue,`service`: RustBuffer.ByValue,
@@ -2600,6 +2646,8 @@ external fun uniffi_cua_sdk_fn_method_spaces_delete(`ptr`: Long,`space`: RustBuf
): Long
external fun uniffi_cua_sdk_fn_method_spaces_delete_many(`ptr`: Long,`ids`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_spaces_delete_tree(`ptr`: Long,`space`: RustBuffer.ByValue,`keepChildren`: Byte,
+): Long
external fun uniffi_cua_sdk_fn_method_spaces_delete_volume(`ptr`: Long,`name`: RustBuffer.ByValue,`force`: Byte,
): Long
external fun uniffi_cua_sdk_fn_method_spaces_fork(`ptr`: Long,`source`: RustBuffer.ByValue,`name`: RustBuffer.ByValue,
@@ -2618,6 +2666,10 @@ external fun uniffi_cua_sdk_fn_method_spaces_list_tools_json(`ptr`: Long,
): Long
external fun uniffi_cua_sdk_fn_method_spaces_machine_health(`ptr`: Long,`machine`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_spaces_network(`ptr`: Long,`space`: RustBuffer.ByValue,
+): Long
+external fun uniffi_cua_sdk_fn_method_spaces_orphans(`ptr`: Long,
+): Long
external fun uniffi_cua_sdk_fn_method_spaces_relay_register(`ptr`: Long,`space`: RustBuffer.ByValue,
): Long
external fun uniffi_cua_sdk_fn_method_spaces_relay_unregister(`ptr`: Long,`space`: RustBuffer.ByValue,
@@ -2632,10 +2684,16 @@ external fun uniffi_cua_sdk_fn_method_spaces_resolve(`ptr`: Long,`space`: RustBu
): Long
external fun uniffi_cua_sdk_fn_method_spaces_resources(`ptr`: Long,`visible`: Byte,
): Long
+external fun uniffi_cua_sdk_fn_method_spaces_set_children(`ptr`: Long,`space`: RustBuffer.ByValue,`enabled`: Byte,
+): Long
external fun uniffi_cua_sdk_fn_method_spaces_set_egress(`ptr`: Long,`space`: RustBuffer.ByValue,`policy`: RustBuffer.ByValue,
): Long
external fun uniffi_cua_sdk_fn_method_spaces_set_lifetime(`ptr`: Long,`space`: RustBuffer.ByValue,`seconds`: Long,`onExpire`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_spaces_set_network(`ptr`: Long,`space`: RustBuffer.ByValue,`settings`: RustBuffer.ByValue,`widen`: Byte,`tree`: Byte,
+): Long
+external fun uniffi_cua_sdk_fn_method_spaces_set_tree_budget(`ptr`: Long,`space`: RustBuffer.ByValue,`limits`: RustBuffer.ByValue,
+): Long
external fun uniffi_cua_sdk_fn_method_spaces_space(`ptr`: Long,`space`: RustBuffer.ByValue,
): Long
external fun uniffi_cua_sdk_fn_method_spaces_start(`ptr`: Long,`space`: RustBuffer.ByValue,
@@ -2644,6 +2702,8 @@ external fun uniffi_cua_sdk_fn_method_spaces_stop(`ptr`: Long,`space`: RustBuffe
): Long
external fun uniffi_cua_sdk_fn_method_spaces_suspend(`ptr`: Long,`space`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_spaces_tree_budget(`ptr`: Long,`space`: RustBuffer.ByValue,
+): Long
external fun uniffi_cua_sdk_fn_method_spaces_volume_approve(`ptr`: Long,`requestId`: RustBuffer.ByValue,`expiresInSecs`: RustBuffer.ByValue,
): Long
external fun uniffi_cua_sdk_fn_method_spaces_volume_audit(`ptr`: Long,`limit`: RustBuffer.ByValue,
@@ -3946,6 +4006,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_space_close_stream() != 64912.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_space_delete_service() != 14460.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_space_displays() != 30039.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -3973,15 +4036,24 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_space_join_presence() != 56636.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_space_kept_services() != 50248.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_space_list_tools() != 19376.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
if (lib.uniffi_cua_sdk_checksum_method_space_open_stream() != 19577.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_space_put_service() != 55111.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_space_request_site_login() != 2223.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_space_restart_service() != 63778.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_space_route() != 9790.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -3991,6 +4063,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_space_send_file() != 29056.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_space_service_logs() != 48773.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_space_services() != 32496.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -4009,9 +4084,15 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_space_start_hotspot() != 44744.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_space_start_service() != 13576.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_space_stop_hotspot() != 18254.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_space_stop_service() != 14671.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_space_stream_session() != 61326.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -4198,6 +4279,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_spaces_routines() != 22768.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_spaces_ack_network_notice() != 32926.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_spaces_add() != 56308.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -4222,12 +4306,15 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_spaces_create_with_progress() != 28676.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
- if (lib.uniffi_cua_sdk_checksum_method_spaces_delete() != 39986.toShort()) {
+ if (lib.uniffi_cua_sdk_checksum_method_spaces_delete() != 4316.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
if (lib.uniffi_cua_sdk_checksum_method_spaces_delete_many() != 9087.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_spaces_delete_tree() != 29454.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_spaces_delete_volume() != 11412.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -4255,6 +4342,12 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_spaces_machine_health() != 35352.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_spaces_network() != 41208.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cua_sdk_checksum_method_spaces_orphans() != 23539.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_spaces_relay_register() != 31691.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -4276,12 +4369,21 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_spaces_resources() != 12146.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_spaces_set_children() != 63927.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_spaces_set_egress() != 12366.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
if (lib.uniffi_cua_sdk_checksum_method_spaces_set_lifetime() != 62609.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_spaces_set_network() != 64671.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cua_sdk_checksum_method_spaces_set_tree_budget() != 8418.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_spaces_space() != 26355.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -4294,6 +4396,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_spaces_suspend() != 23817.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_spaces_tree_budget() != 58333.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_spaces_volume_approve() != 8640.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -17663,6 +17768,11 @@ public interface SpaceInterface {
*/
suspend fun `closeStream`(`mediaSessionId`: kotlin.String)
+ /**
+ * Stops a service and forgets it (its logs go too).
+ */
+ suspend fun `deleteService`(`name`: kotlin.String)
+
/**
* The Space's displays, primary first, with their resolution in
* physical pixels.
@@ -17726,6 +17836,11 @@ public interface SpaceInterface {
*/
suspend fun `joinPresence`(`identity`: PresenceIdentity, `timeoutMs`: kotlin.ULong?): SpacePresence
+ /**
+ * This Space's services.
+ */
+ suspend fun `keptServices`(): List<SpaceServiceInfo>
+
/**
* Tools of the Space's MCP service (`driver`, the default).
*/
@@ -17737,6 +17852,13 @@ public interface SpaceInterface {
*/
suspend fun `openStream`(`options`: SpaceStreamOptions): SpaceStreamTicket
+ /**
+ * Keeps a command running in this Space (replacing a service of that
+ * name): restarted by its policy when it ends or fails its health
+ * check, started when the Space boots, its output kept in a log file.
+ */
+ suspend fun `putService`(`def`: SpaceServiceDef): SpaceServiceInfo
+
/**
* Signs in to a site in this Space's browser with a password the user
* saved in the Cua Keyvault. The first call files a request
@@ -17747,6 +17869,11 @@ public interface SpaceInterface {
*/
suspend fun `requestSiteLogin`(`url`: kotlin.String, `options`: SiteLoginOptions?): SiteLoginReport
+ /**
+ * Restarts a service.
+ */
+ suspend fun `restartService`(`name`: kotlin.String): SpaceServiceInfo
+
/**
* Which way this Space's calls go now (see [`super::spacesd::SpacesdClient::route`]):
* `local …`, `direct …`, `relay …`, `mesh direct <ip:port> rtt <ms> ms`,
@@ -17769,6 +17896,11 @@ public interface SpaceInterface {
*/
suspend fun `sendFile`(`localPath`: kotlin.String, `options`: SpaceSendFileOptions): SpaceSendFileReport
+ /**
+ * The end of a service's log (`tail_bytes` `None`: 64 KiB).
+ */
+ suspend fun `serviceLogs`(`name`: kotlin.String, `tailBytes`: kotlin.ULong?): kotlin.String
+
/**
* The MCP services this Space exposes: `driver` when its spacesd has
* the tool registry, then every declared service (reached over generic
@@ -17808,11 +17940,21 @@ public interface SpaceInterface {
*/
suspend fun `startHotspot`(`setSystemProxy`: kotlin.Boolean?, `bypass`: List<kotlin.String>?): SpaceHotspotStatus
+ /**
+ * Starts a stopped service.
+ */
+ suspend fun `startService`(`name`: kotlin.String): SpaceServiceInfo
+
/**
* Stops this Space's hotspot. Returns the stopped Space ids.
*/
suspend fun `stopHotspot`(): List<kotlin.String>
+ /**
+ * Stops a service and keeps it stopped (also across a reboot).
+ */
+ suspend fun `stopService`(`name`: kotlin.String): SpaceServiceInfo
+
/**
* Opens a media session and delivers keyframe-gated encoded frames
* and audio to the sinks (one delivery thread; decoding stays with the
@@ -18388,6 +18530,31 @@ open class Space: Disposable, AutoCloseable, SpaceInterface
}
+ /**
+ * Stops a service and forgets it (its logs go too).
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `deleteService`(`name`: kotlin.String) {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_space_delete_service(
+ uniffiHandle,
+ FfiConverterString.lower(`name`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_void(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_void(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_void(future) },
+ // lift function
+ { Unit },
+
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* The Space's displays, primary first, with their resolution in
* physical pixels.
@@ -18606,6 +18773,30 @@ open class Space: Disposable, AutoCloseable, SpaceInterface
}
+ /**
+ * This Space's services.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `keptServices`() : List<SpaceServiceInfo> {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_space_kept_services(
+ uniffiHandle,
+
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterSequenceTypeSpaceServiceInfo.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Tools of the Space's MCP service (`driver`, the default).
*/
@@ -18655,6 +18846,32 @@ open class Space: Disposable, AutoCloseable, SpaceInterface
}
+ /**
+ * Keeps a command running in this Space (replacing a service of that
+ * name): restarted by its policy when it ends or fails its health
+ * check, started when the Space boots, its output kept in a log file.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `putService`(`def`: SpaceServiceDef) : SpaceServiceInfo {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_space_put_service(
+ uniffiHandle,
+ FfiConverterTypeSpaceServiceDef.lower(`def`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeSpaceServiceInfo.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Signs in to a site in this Space's browser with a password the user
* saved in the Cua Keyvault. The first call files a request
@@ -18684,6 +18901,30 @@ open class Space: Disposable, AutoCloseable, SpaceInterface
}
+ /**
+ * Restarts a service.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `restartService`(`name`: kotlin.String) : SpaceServiceInfo {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_space_restart_service(
+ uniffiHandle,
+ FfiConverterString.lower(`name`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeSpaceServiceInfo.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Which way this Space's calls go now (see [`super::spacesd::SpacesdClient::route`]):
* `local …`, `direct …`, `relay …`, `mesh direct <ip:port> rtt <ms> ms`,
@@ -18763,6 +19004,30 @@ open class Space: Disposable, AutoCloseable, SpaceInterface
}
+ /**
+ * The end of a service's log (`tail_bytes` `None`: 64 KiB).
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `serviceLogs`(`name`: kotlin.String, `tailBytes`: kotlin.ULong?) : kotlin.String {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_space_service_logs(
+ uniffiHandle,
+ FfiConverterString.lower(`name`),FfiConverterOptionalULong.lower(`tailBytes`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterString.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* The MCP services this Space exposes: `driver` when its spacesd has
* the tool registry, then every declared service (reached over generic
@@ -18902,6 +19167,30 @@ open class Space: Disposable, AutoCloseable, SpaceInterface
}
+ /**
+ * Starts a stopped service.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `startService`(`name`: kotlin.String) : SpaceServiceInfo {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_space_start_service(
+ uniffiHandle,
+ FfiConverterString.lower(`name`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeSpaceServiceInfo.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Stops this Space's hotspot. Returns the stopped Space ids.
*/
@@ -18926,6 +19215,30 @@ open class Space: Disposable, AutoCloseable, SpaceInterface
}
+ /**
+ * Stops a service and keeps it stopped (also across a reboot).
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `stopService`(`name`: kotlin.String) : SpaceServiceInfo {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_space_stop_service(
+ uniffiHandle,
+ FfiConverterString.lower(`name`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeSpaceServiceInfo.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Opens a media session and delivers keyframe-gated encoded frames
* and audio to the sinks (one delivery thread; decoding stays with the
@@ -20758,6 +21071,12 @@ public interface SpacesInterface {
*/
suspend fun `routines`(`agent`: kotlin.String?): List<RoutineInfo>
+ /**
+ * Marks the one-time notice about the new network defaults as shown
+ * for `space` ([`SpaceNetworkInfo::notice_pending`]).
+ */
+ suspend fun `ackNetworkNotice`(`space`: kotlin.String)
+
/**
* Adds a Space by URL (`http(s)://host:port`, `host:port`, or a
* Space id such as `local:<name>`) after a `GetCapabilities` handshake. Any other MCP
@@ -20823,7 +21142,8 @@ public interface SpacesInterface {
/**
* Deletes a Space's sandbox and forgets it (a Space added by address
- * is only forgotten). Returns what happened.
+ * is only forgotten). Its child Spaces are deleted first. Returns what
+ * happened.
*/
suspend fun `delete`(`space`: kotlin.String): kotlin.String
@@ -20834,6 +21154,12 @@ public interface SpacesInterface {
*/
suspend fun `deleteMany`(`ids`: List<kotlin.String>): List<BulkResult>
+ /**
+ * [`Spaces::delete`], with `keep_children`: its child Spaces become
+ * top-level Spaces and keep running instead of being deleted first.
+ */
+ suspend fun `deleteTree`(`space`: kotlin.String, `keepChildren`: kotlin.Boolean): kotlin.String
+
/**
* Deletes the named volume `name` and its files (their history stays
* in the Cua Volume). Refused while Spaces mount it unless `force`.
@@ -20908,6 +21234,19 @@ public interface SpacesInterface {
*/
suspend fun `machineHealth`(`machine`: kotlin.String?): MachineHealth
+ /**
+ * A Space's network: its settings, what they open, where they are
+ * enforced (or why its network is cut), and what is always blocked.
+ */
+ suspend fun `network`(`space`: kotlin.String): SpaceNetworkInfo
+
+ /**
+ * Child Spaces whose parent is gone or out of reach. The cua daemon
+ * ends a child only on proof its parent is gone (after a grace period);
+ * the rest are listed here and never ended by it.
+ */
+ suspend fun `orphans`(): List<SpaceOrphan>
+
/**
* Publishes `space` on the cua.ai relay as a machine of the signed-in
* account, the way `cua host setup` publishes this computer: the
@@ -20967,6 +21306,17 @@ public interface SpacesInterface {
*/
suspend fun `resources`(`visible`: kotlin.Boolean): ResourcesSnapshot
+ /**
+ * Lets a Space make child Spaces of its own, or stops it. While on,
+ * `cua`, the SDKs and the agent's tools in that Space create, list and
+ * delete Spaces that belong to it (on the same computer, never wider
+ * than it, ending no later than it), through a channel only it can
+ * reach. Off ends its capability at once; children it made keep running
+ * until deleted or their lifetime ends. Only for a Space the machine of
+ * this runtime runs itself.
+ */
+ suspend fun `setChildren`(`space`: kotlin.String, `enabled`: kotlin.Boolean)
+
/**
* Replaces a Space's egress policy; an empty one removes it (see
* [`EgressPolicy`]). Its host enforces it at once. A bad entry is
@@ -20984,6 +21334,22 @@ public interface SpacesInterface {
*/
suspend fun `setLifetime`(`space`: kotlin.String, `seconds`: kotlin.ULong, `onExpire`: kotlin.String?): kotlin.Long
+ /**
+ * Replaces a Space's network settings (see [`NetworkSettings`]). A
+ * child stays within its parent's unless `widen`; `tree` gives its
+ * children the same settings. They hold at once where the runtime can
+ * change a running guest's network, else from its next start
+ * (`applied`). A Space another computer runs is `Unsupported`.
+ */
+ suspend fun `setNetwork`(`space`: kotlin.String, `settings`: NetworkSettings, `widen`: kotlin.Boolean, `tree`: kotlin.Boolean): SetNetworkResult
+
+ /**
+ * Sets the budget of `space`'s tree: how many child Spaces, vCPUs and
+ * memory its children may hold at once, and what they may cost. A child
+ * that does not fit is refused with what is left. All `None` removes it.
+ */
+ suspend fun `setTreeBudget`(`space`: kotlin.String, `limits`: TreeBudgetLimits): TreeBudget
+
/**
* A connected handle to a registered Space.
*/
@@ -21014,6 +21380,12 @@ public interface SpacesInterface {
*/
suspend fun `suspend`(`space`: kotlin.String): SpacePowerReport
+ /**
+ * The budget of `space`'s tree (any Space of it) and what its
+ * children use now. Kept by the cua daemon.
+ */
+ suspend fun `treeBudget`(`space`: kotlin.String): TreeBudget
+
/**
* `volume_approve`: the request becomes a grant (with presence).
*/
@@ -22154,6 +22526,32 @@ open class Spaces: Disposable, AutoCloseable, SpacesInterface
}
+ /**
+ * Marks the one-time notice about the new network defaults as shown
+ * for `space` ([`SpaceNetworkInfo::notice_pending`]).
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `ackNetworkNotice`(`space`: kotlin.String) {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_spaces_ack_network_notice(
+ uniffiHandle,
+ FfiConverterString.lower(`space`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_void(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_void(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_void(future) },
+ // lift function
+ { Unit },
+
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Adds a Space by URL (`http(s)://host:port`, `host:port`, or a
* Space id such as `local:<name>`) after a `GetCapabilities` handshake. Any other MCP
@@ -22371,7 +22769,8 @@ open class Spaces: Disposable, AutoCloseable, SpacesInterface
/**
* Deletes a Space's sandbox and forgets it (a Space added by address
- * is only forgotten). Returns what happened.
+ * is only forgotten). Its child Spaces are deleted first. Returns what
+ * happened.
*/
@Throws(CuaException::class)
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
@@ -22420,6 +22819,31 @@ open class Spaces: Disposable, AutoCloseable, SpacesInterface
}
+ /**
+ * [`Spaces::delete`], with `keep_children`: its child Spaces become
+ * top-level Spaces and keep running instead of being deleted first.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `deleteTree`(`space`: kotlin.String, `keepChildren`: kotlin.Boolean) : kotlin.String {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_spaces_delete_tree(
+ uniffiHandle,
+ FfiConverterString.lower(`space`),FfiConverterBoolean.lower(`keepChildren`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterString.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Deletes the named volume `name` and its files (their history stays
* in the Cua Volume). Refused while Spaces mount it unless `force`.
@@ -22665,6 +23089,57 @@ open class Spaces: Disposable, AutoCloseable, SpacesInterface
}
+ /**
+ * A Space's network: its settings, what they open, where they are
+ * enforced (or why its network is cut), and what is always blocked.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `network`(`space`: kotlin.String) : SpaceNetworkInfo {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_spaces_network(
+ uniffiHandle,
+ FfiConverterString.lower(`space`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeSpaceNetworkInfo.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
+ /**
+ * Child Spaces whose parent is gone or out of reach. The cua daemon
+ * ends a child only on proof its parent is gone (after a grace period);
+ * the rest are listed here and never ended by it.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `orphans`() : List<SpaceOrphan> {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_spaces_orphans(
+ uniffiHandle,
+
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterSequenceTypeSpaceOrphan.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Publishes `space` on the cua.ai relay as a machine of the signed-in
* account, the way `cua host setup` publishes this computer: the
@@ -22858,6 +23333,37 @@ open class Spaces: Disposable, AutoCloseable, SpacesInterface
}
+ /**
+ * Lets a Space make child Spaces of its own, or stops it. While on,
+ * `cua`, the SDKs and the agent's tools in that Space create, list and
+ * delete Spaces that belong to it (on the same computer, never wider
+ * than it, ending no later than it), through a channel only it can
+ * reach. Off ends its capability at once; children it made keep running
+ * until deleted or their lifetime ends. Only for a Space the machine of
+ * this runtime runs itself.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `setChildren`(`space`: kotlin.String, `enabled`: kotlin.Boolean) {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_children(
+ uniffiHandle,
+ FfiConverterString.lower(`space`),FfiConverterBoolean.lower(`enabled`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_void(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_void(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_void(future) },
+ // lift function
+ { Unit },
+
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Replaces a Space's egress policy; an empty one removes it (see
* [`EgressPolicy`]). Its host enforces it at once. A bad entry is
@@ -22914,6 +23420,60 @@ open class Spaces: Disposable, AutoCloseable, SpacesInterface
}
+ /**
+ * Replaces a Space's network settings (see [`NetworkSettings`]). A
+ * child stays within its parent's unless `widen`; `tree` gives its
+ * children the same settings. They hold at once where the runtime can
+ * change a running guest's network, else from its next start
+ * (`applied`). A Space another computer runs is `Unsupported`.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `setNetwork`(`space`: kotlin.String, `settings`: NetworkSettings, `widen`: kotlin.Boolean, `tree`: kotlin.Boolean) : SetNetworkResult {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_network(
+ uniffiHandle,
+ FfiConverterString.lower(`space`),FfiConverterTypeNetworkSettings.lower(`settings`),FfiConverterBoolean.lower(`widen`),FfiConverterBoolean.lower(`tree`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeSetNetworkResult.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
+ /**
+ * Sets the budget of `space`'s tree: how many child Spaces, vCPUs and
+ * memory its children may hold at once, and what they may cost. A child
+ * that does not fit is refused with what is left. All `None` removes it.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `setTreeBudget`(`space`: kotlin.String, `limits`: TreeBudgetLimits) : TreeBudget {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_tree_budget(
+ uniffiHandle,
+ FfiConverterString.lower(`space`),FfiConverterTypeTreeBudgetLimits.lower(`limits`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeTreeBudget.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* A connected handle to a registered Space.
*/
@@ -23020,6 +23580,31 @@ open class Spaces: Disposable, AutoCloseable, SpacesInterface
}
+ /**
+ * The budget of `space`'s tree (any Space of it) and what its
+ * children use now. Kept by the cua daemon.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `treeBudget`(`space`: kotlin.String) : TreeBudget {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_spaces_tree_budget(
+ uniffiHandle,
+ FfiConverterString.lower(`space`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeTreeBudget.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* `volume_approve`: the request becomes a grant (with presence).
*/
@@ -38181,6 +38766,111 @@ public object FfiConverterTypeNamedVolume: FfiConverterRustBuffer<NamedVolume> {
+/**
+ * A Space's network settings: a preset and the user's own lists. The host
+ * the Space runs on compiles them to rules it enforces outside the guest.
+ *
+ * - `internet` (the default): the public internet and the Space's own
+ * tree; this computer, your local network, cloud metadata, other trees
+ * and the cua daemon are blocked;
+ * - `none`: no network;
+ * - `localhost`: `internet`, plus this computer's localhost on
+ * `localhost_ports` (every port only with `all_localhost_ports`);
+ * - `lan`: `internet`, plus your local network (not this computer);
+ * - `custom`: `custom_base` (`internet` or `none`) plus `allow` and `deny`;
+ * - `unprotected`: everything but cloud metadata, other trees and the
+ * daemon.
+ *
+ * A runtime that can't protect a Space yet starts it without network and
+ * says so (`SpaceInfo.network_note`); it never starts it open unless the
+ * preset is `unprotected`.
+ */
+data class NetworkSettings (
+ /**
+ * `internet`, `none`, `localhost`, `lan`, `custom` or `unprotected`;
+ * empty is `internet`.
+ */
+ var `preset`: kotlin.String = ""
+ ,
+ /**
+ * `localhost`: the ports of this computer's localhost the Space may
+ * reach.
+ */
+ var `localhostPorts`: List<kotlin.UShort> = listOf()
+ ,
+ /**
+ * `localhost`: every port (the daemon's stay blocked).
+ */
+ var `allLocalhostPorts`: kotlin.Boolean = false
+ ,
+ /**
+ * Destinations that stay reachable (addresses or CIDRs).
+ */
+ var `allow`: List<kotlin.String> = listOf()
+ ,
+ /**
+ * Destinations that are blocked (addresses, CIDRs or `all`).
+ */
+ var `deny`: List<kotlin.String> = listOf()
+ ,
+ /**
+ * `custom`: what it starts from, `internet` (empty) or `none`.
+ */
+ var `customBase`: kotlin.String = ""
+ ,
+ /**
+ * Set when the Space was allowed more than its parent: who and when.
+ */
+ var `widenedBy`: kotlin.String? = null
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeNetworkSettings: FfiConverterRustBuffer<NetworkSettings> {
+ override fun read(buf: ByteBuffer): NetworkSettings {
+ return NetworkSettings(
+ FfiConverterString.read(buf),
+ FfiConverterSequenceUShort.read(buf),
+ FfiConverterBoolean.read(buf),
+ FfiConverterSequenceString.read(buf),
+ FfiConverterSequenceString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: NetworkSettings) = (
+ FfiConverterString.allocationSize(value.`preset`) +
+ FfiConverterSequenceUShort.allocationSize(value.`localhostPorts`) +
+ FfiConverterBoolean.allocationSize(value.`allLocalhostPorts`) +
+ FfiConverterSequenceString.allocationSize(value.`allow`) +
+ FfiConverterSequenceString.allocationSize(value.`deny`) +
+ FfiConverterString.allocationSize(value.`customBase`) +
+ FfiConverterOptionalString.allocationSize(value.`widenedBy`)
+ )
+
+ override fun write(value: NetworkSettings, buf: ByteBuffer) {
+ FfiConverterString.write(value.`preset`, buf)
+ FfiConverterSequenceUShort.write(value.`localhostPorts`, buf)
+ FfiConverterBoolean.write(value.`allLocalhostPorts`, buf)
+ FfiConverterSequenceString.write(value.`allow`, buf)
+ FfiConverterSequenceString.write(value.`deny`, buf)
+ FfiConverterString.write(value.`customBase`, buf)
+ FfiConverterOptionalString.write(value.`widenedBy`, buf)
+ }
+}
+
+
+
/**
* One entry of the notifications feed.
*/
@@ -42097,6 +42787,53 @@ public object FfiConverterTypeServiceEndpoint: FfiConverterRustBuffer<ServiceEnd
+/**
+ * What [`Spaces::set_network`] did.
+ */
+data class SetNetworkResult (
+ /**
+ * `now` (the running guest is under them) or `next_start`.
+ */
+ var `applied`: kotlin.String
+ ,
+ /**
+ * The Space's network after the change.
+ */
+ var `network`: SpaceNetworkInfo
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeSetNetworkResult: FfiConverterRustBuffer<SetNetworkResult> {
+ override fun read(buf: ByteBuffer): SetNetworkResult {
+ return SetNetworkResult(
+ FfiConverterString.read(buf),
+ FfiConverterTypeSpaceNetworkInfo.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: SetNetworkResult) = (
+ FfiConverterString.allocationSize(value.`applied`) +
+ FfiConverterTypeSpaceNetworkInfo.allocationSize(value.`network`)
+ )
+
+ override fun write(value: SetNetworkResult, buf: ByteBuffer) {
+ FfiConverterString.write(value.`applied`, buf)
+ FfiConverterTypeSpaceNetworkInfo.write(value.`network`, buf)
+ }
+}
+
+
+
/**
* One setup step.
*/
@@ -43292,6 +44029,25 @@ data class SpaceCreateOptions (
*/
var `egress`: EgressPolicy? = null
,
+ /**
+ * Network settings (see [`NetworkSettings`]). `None`: what `network`
+ * and `egress` say (`internet` when neither says anything). A daemon
+ * too old to keep them makes the create fail.
+ */
+ var `networkSettings`: NetworkSettings? = null
+ ,
+ /**
+ * Create it as a child of this Space (id or name): its network is no
+ * more open than its parent's, and it joins the parent's tree.
+ */
+ var `parent`: kotlin.String? = null
+ ,
+ /**
+ * With `parent`: let its network be more open than its parent's
+ * (recorded on the Space).
+ */
+ var `widen`: kotlin.Boolean? = null
+ ,
/**
* With `on` a linked cloud (`aws`, `hetzner`, ...): the machine type
* its host must be (`c7g.xlarge`, `cax41`), a pin of the elastic
@@ -43303,6 +44059,12 @@ data class SpaceCreateOptions (
* With `on` a linked cloud: the region its host must be in.
*/
var `region`: kotlin.String? = null
+ ,
+ /**
+ * Lets the Space make child Spaces of its own ([`Spaces::set_children`]).
+ * `None`: off. Only a Space the machine of the runtime runs itself.
+ */
+ var `children`: kotlin.Boolean? = null
){
@@ -43345,8 +44107,12 @@ public object FfiConverterTypeSpaceCreateOptions: FfiConverterRustBuffer<SpaceCr
FfiConverterOptionalString.read(buf),
FfiConverterMapStringString.read(buf),
FfiConverterOptionalTypeEgressPolicy.read(buf),
+ FfiConverterOptionalTypeNetworkSettings.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalBoolean.read(buf),
FfiConverterOptionalString.read(buf),
FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalBoolean.read(buf),
)
}
@@ -43377,8 +44143,12 @@ public object FfiConverterTypeSpaceCreateOptions: FfiConverterRustBuffer<SpaceCr
FfiConverterOptionalString.allocationSize(value.`network`) +
FfiConverterMapStringString.allocationSize(value.`labels`) +
FfiConverterOptionalTypeEgressPolicy.allocationSize(value.`egress`) +
+ FfiConverterOptionalTypeNetworkSettings.allocationSize(value.`networkSettings`) +
+ FfiConverterOptionalString.allocationSize(value.`parent`) +
+ FfiConverterOptionalBoolean.allocationSize(value.`widen`) +
FfiConverterOptionalString.allocationSize(value.`instanceType`) +
- FfiConverterOptionalString.allocationSize(value.`region`)
+ FfiConverterOptionalString.allocationSize(value.`region`) +
+ FfiConverterOptionalBoolean.allocationSize(value.`children`)
)
override fun write(value: SpaceCreateOptions, buf: ByteBuffer) {
@@ -43408,8 +44178,12 @@ public object FfiConverterTypeSpaceCreateOptions: FfiConverterRustBuffer<SpaceCr
FfiConverterOptionalString.write(value.`network`, buf)
FfiConverterMapStringString.write(value.`labels`, buf)
FfiConverterOptionalTypeEgressPolicy.write(value.`egress`, buf)
+ FfiConverterOptionalTypeNetworkSettings.write(value.`networkSettings`, buf)
+ FfiConverterOptionalString.write(value.`parent`, buf)
+ FfiConverterOptionalBoolean.write(value.`widen`, buf)
FfiConverterOptionalString.write(value.`instanceType`, buf)
FfiConverterOptionalString.write(value.`region`, buf)
+ FfiConverterOptionalBoolean.write(value.`children`, buf)
}
}
@@ -44003,6 +44777,42 @@ data class SpaceInfo (
*/
var `egressEnforced`: EgressEnforcement?
,
+ /**
+ * Its network settings; `None` for a Space this computer keeps no
+ * record of, or one created before they existed (it gets them on its
+ * next start).
+ */
+ var `network`: NetworkSettings?
+ ,
+ /**
+ * Why its network is not what was asked, in plain words (a runtime
+ * that can't protect it yet started it without network); `None`
+ * otherwise.
+ */
+ var `networkNote`: kotlin.String?
+ ,
+ /**
+ * An update changed its network settings (an old Space moved to the
+ * new defaults): say so once.
+ */
+ var `networkNoticePending`: kotlin.Boolean
+ ,
+ /**
+ * The Space it was created from, by id; `None` for a top-level Space.
+ */
+ var `parent`: kotlin.String?
+ ,
+ /**
+ * The top-level Space of its tree, by id; `None` for a top-level
+ * Space.
+ */
+ var `root`: kotlin.String?
+ ,
+ /**
+ * How far below its tree's top-level Space it is (0: top-level).
+ */
+ var `depth`: kotlin.UInt
+ ,
/**
* Named volumes mounted in the Space (see
* [`SpaceCreateOptions::volumes`]).
@@ -44060,6 +44870,12 @@ public object FfiConverterTypeSpaceInfo: FfiConverterRustBuffer<SpaceInfo> {
FfiConverterLong.read(buf),
FfiConverterTypeEgressPolicy.read(buf),
FfiConverterOptionalTypeEgressEnforcement.read(buf),
+ FfiConverterOptionalTypeNetworkSettings.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterBoolean.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterUInt.read(buf),
FfiConverterSequenceTypeVolumeMount.read(buf),
FfiConverterOptionalTypeSpaceSharing.read(buf),
)
@@ -44096,6 +44912,12 @@ public object FfiConverterTypeSpaceInfo: FfiConverterRustBuffer<SpaceInfo> {
FfiConverterLong.allocationSize(value.`createdAtUnix`) +
FfiConverterTypeEgressPolicy.allocationSize(value.`egress`) +
FfiConverterOptionalTypeEgressEnforcement.allocationSize(value.`egressEnforced`) +
+ FfiConverterOptionalTypeNetworkSettings.allocationSize(value.`network`) +
+ FfiConverterOptionalString.allocationSize(value.`networkNote`) +
+ FfiConverterBoolean.allocationSize(value.`networkNoticePending`) +
+ FfiConverterOptionalString.allocationSize(value.`parent`) +
+ FfiConverterOptionalString.allocationSize(value.`root`) +
+ FfiConverterUInt.allocationSize(value.`depth`) +
FfiConverterSequenceTypeVolumeMount.allocationSize(value.`volumes`) +
FfiConverterOptionalTypeSpaceSharing.allocationSize(value.`sharing`)
)
@@ -44131,6 +44953,12 @@ public object FfiConverterTypeSpaceInfo: FfiConverterRustBuffer<SpaceInfo> {
FfiConverterLong.write(value.`createdAtUnix`, buf)
FfiConverterTypeEgressPolicy.write(value.`egress`, buf)
FfiConverterOptionalTypeEgressEnforcement.write(value.`egressEnforced`, buf)
+ FfiConverterOptionalTypeNetworkSettings.write(value.`network`, buf)
+ FfiConverterOptionalString.write(value.`networkNote`, buf)
+ FfiConverterBoolean.write(value.`networkNoticePending`, buf)
+ FfiConverterOptionalString.write(value.`parent`, buf)
+ FfiConverterOptionalString.write(value.`root`, buf)
+ FfiConverterUInt.write(value.`depth`, buf)
FfiConverterSequenceTypeVolumeMount.write(value.`volumes`, buf)
FfiConverterOptionalTypeSpaceSharing.write(value.`sharing`, buf)
}
@@ -44222,6 +45050,190 @@ public object FfiConverterTypeSpaceList: FfiConverterRustBuffer<SpaceList> {
+/**
+ * A Space's network as `cua network show` says it ([`Spaces::network`]).
+ */
+data class SpaceNetworkInfo (
+ /**
+ * Its settings.
+ */
+ var `settings`: NetworkSettings
+ ,
+ /**
+ * One plain line ("Internet only").
+ */
+ var `summary`: kotlin.String
+ ,
+ /**
+ * What the settings open beyond `internet`, one plain line each.
+ */
+ var `widenings`: List<kotlin.String>
+ ,
+ /**
+ * `enforced` (rules on the host, outside the guest), `no_network`
+ * (its runtime can't protect it yet), `open` (No protection) or
+ * `refused`; empty when unknown (a Space another computer runs).
+ */
+ var `enforcement`: kotlin.String
+ ,
+ /**
+ * Where the rules are enforced, or why its network is cut.
+ */
+ var `point`: kotlin.String
+ ,
+ /**
+ * Why its network is not what was asked; `None` otherwise.
+ */
+ var `note`: kotlin.String?
+ ,
+ /**
+ * Its parent and its tree's top-level Space; `None` for a top-level
+ * Space.
+ */
+ var `parent`: kotlin.String?
+ ,
+ var `root`: kotlin.String?
+ ,
+ /**
+ * What no setting opens, in plain words.
+ */
+ var `alwaysBlocked`: List<kotlin.String>
+ ,
+ /**
+ * An update changed its settings: say so once.
+ */
+ var `noticePending`: kotlin.Boolean
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeSpaceNetworkInfo: FfiConverterRustBuffer<SpaceNetworkInfo> {
+ override fun read(buf: ByteBuffer): SpaceNetworkInfo {
+ return SpaceNetworkInfo(
+ FfiConverterTypeNetworkSettings.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterSequenceString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterSequenceString.read(buf),
+ FfiConverterBoolean.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: SpaceNetworkInfo) = (
+ FfiConverterTypeNetworkSettings.allocationSize(value.`settings`) +
+ FfiConverterString.allocationSize(value.`summary`) +
+ FfiConverterSequenceString.allocationSize(value.`widenings`) +
+ FfiConverterString.allocationSize(value.`enforcement`) +
+ FfiConverterString.allocationSize(value.`point`) +
+ FfiConverterOptionalString.allocationSize(value.`note`) +
+ FfiConverterOptionalString.allocationSize(value.`parent`) +
+ FfiConverterOptionalString.allocationSize(value.`root`) +
+ FfiConverterSequenceString.allocationSize(value.`alwaysBlocked`) +
+ FfiConverterBoolean.allocationSize(value.`noticePending`)
+ )
+
+ override fun write(value: SpaceNetworkInfo, buf: ByteBuffer) {
+ FfiConverterTypeNetworkSettings.write(value.`settings`, buf)
+ FfiConverterString.write(value.`summary`, buf)
+ FfiConverterSequenceString.write(value.`widenings`, buf)
+ FfiConverterString.write(value.`enforcement`, buf)
+ FfiConverterString.write(value.`point`, buf)
+ FfiConverterOptionalString.write(value.`note`, buf)
+ FfiConverterOptionalString.write(value.`parent`, buf)
+ FfiConverterOptionalString.write(value.`root`, buf)
+ FfiConverterSequenceString.write(value.`alwaysBlocked`, buf)
+ FfiConverterBoolean.write(value.`noticePending`, buf)
+ }
+}
+
+
+
+/**
+ * A child Space whose parent is gone or out of reach ([`Spaces::orphans`]).
+ */
+data class SpaceOrphan (
+ /**
+ * The child.
+ */
+ var `space`: kotlin.String
+ ,
+ /**
+ * Its parent's id.
+ */
+ var `parent`: kotlin.String
+ ,
+ /**
+ * `ending` (its parent is provably gone: it ends after the grace) or
+ * `listed` (not this computer's to judge: it stays until deleted or its
+ * own lifetime ends).
+ */
+ var `state`: kotlin.String
+ ,
+ /**
+ * Why.
+ */
+ var `why`: kotlin.String
+ ,
+ /**
+ * Seconds until it ends (`ending` only).
+ */
+ var `endsInSecs`: kotlin.Long
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeSpaceOrphan: FfiConverterRustBuffer<SpaceOrphan> {
+ override fun read(buf: ByteBuffer): SpaceOrphan {
+ return SpaceOrphan(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterLong.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: SpaceOrphan) = (
+ FfiConverterString.allocationSize(value.`space`) +
+ FfiConverterString.allocationSize(value.`parent`) +
+ FfiConverterString.allocationSize(value.`state`) +
+ FfiConverterString.allocationSize(value.`why`) +
+ FfiConverterLong.allocationSize(value.`endsInSecs`)
+ )
+
+ override fun write(value: SpaceOrphan, buf: ByteBuffer) {
+ FfiConverterString.write(value.`space`, buf)
+ FfiConverterString.write(value.`parent`, buf)
+ FfiConverterString.write(value.`state`, buf)
+ FfiConverterString.write(value.`why`, buf)
+ FfiConverterLong.write(value.`endsInSecs`, buf)
+ }
+}
+
+
+
/**
* What [`Spaces::stop`] or [`Spaces::start`] did.
*/
@@ -44741,6 +45753,277 @@ public object FfiConverterTypeSpaceSentFile: FfiConverterRustBuffer<SpaceSentFil
+/**
+ * A command a Space keeps running ([`Space::put_service`]).
+ */
+data class SpaceServiceDef (
+ /**
+ * Name: lowercase letters, digits, `-`, `_`, `.` (1 to 63).
+ */
+ var `name`: kotlin.String
+ ,
+ /**
+ * The shell command line it runs.
+ */
+ var `command`: kotlin.String
+ ,
+ /**
+ * Extra environment.
+ */
+ var `env`: Map<kotlin.String, kotlin.String> = mapOf()
+ ,
+ /**
+ * Working directory.
+ */
+ var `cwd`: kotlin.String? = null
+ ,
+ /**
+ * When it is started again: `always` (default), `on-failure` or
+ * `never`.
+ */
+ var `restart`: kotlin.String? = null
+ ,
+ /**
+ * A health check; failing it restarts the service.
+ */
+ var `probe`: SpaceServiceProbe? = null
+ ,
+ /**
+ * Start it when the Space boots. `None`: yes.
+ */
+ var `startOnBoot`: kotlin.Boolean? = null
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeSpaceServiceDef: FfiConverterRustBuffer<SpaceServiceDef> {
+ override fun read(buf: ByteBuffer): SpaceServiceDef {
+ return SpaceServiceDef(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterMapStringString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalTypeSpaceServiceProbe.read(buf),
+ FfiConverterOptionalBoolean.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: SpaceServiceDef) = (
+ FfiConverterString.allocationSize(value.`name`) +
+ FfiConverterString.allocationSize(value.`command`) +
+ FfiConverterMapStringString.allocationSize(value.`env`) +
+ FfiConverterOptionalString.allocationSize(value.`cwd`) +
+ FfiConverterOptionalString.allocationSize(value.`restart`) +
+ FfiConverterOptionalTypeSpaceServiceProbe.allocationSize(value.`probe`) +
+ FfiConverterOptionalBoolean.allocationSize(value.`startOnBoot`)
+ )
+
+ override fun write(value: SpaceServiceDef, buf: ByteBuffer) {
+ FfiConverterString.write(value.`name`, buf)
+ FfiConverterString.write(value.`command`, buf)
+ FfiConverterMapStringString.write(value.`env`, buf)
+ FfiConverterOptionalString.write(value.`cwd`, buf)
+ FfiConverterOptionalString.write(value.`restart`, buf)
+ FfiConverterOptionalTypeSpaceServiceProbe.write(value.`probe`, buf)
+ FfiConverterOptionalBoolean.write(value.`startOnBoot`, buf)
+ }
+}
+
+
+
+/**
+ * A service and how it is doing ([`Space::services`]).
+ */
+data class SpaceServiceInfo (
+ /**
+ * Name.
+ */
+ var `name`: kotlin.String
+ ,
+ /**
+ * The command line.
+ */
+ var `command`: kotlin.String
+ ,
+ /**
+ * `starting`, `running`, `unhealthy`, `backoff`, `stopped`, `exited`
+ * or `failed`.
+ */
+ var `state`: kotlin.String
+ ,
+ /**
+ * Its process, while it runs.
+ */
+ var `pid`: kotlin.UInt
+ ,
+ /**
+ * Starts after the first.
+ */
+ var `restarts`: kotlin.UInt
+ ,
+ /**
+ * How the last process ended, if one did.
+ */
+ var `lastEnd`: kotlin.String
+ ,
+ /**
+ * The last failed health check, if the last one failed.
+ */
+ var `probeError`: kotlin.String
+ ,
+ /**
+ * `always`, `on-failure` or `never`.
+ */
+ var `restart`: kotlin.String
+ ,
+ /**
+ * Starts when the Space boots.
+ */
+ var `startOnBoot`: kotlin.Boolean
+ ,
+ /**
+ * Its log file in the Space.
+ */
+ var `logPath`: kotlin.String
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeSpaceServiceInfo: FfiConverterRustBuffer<SpaceServiceInfo> {
+ override fun read(buf: ByteBuffer): SpaceServiceInfo {
+ return SpaceServiceInfo(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterUInt.read(buf),
+ FfiConverterUInt.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterBoolean.read(buf),
+ FfiConverterString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: SpaceServiceInfo) = (
+ FfiConverterString.allocationSize(value.`name`) +
+ FfiConverterString.allocationSize(value.`command`) +
+ FfiConverterString.allocationSize(value.`state`) +
+ FfiConverterUInt.allocationSize(value.`pid`) +
+ FfiConverterUInt.allocationSize(value.`restarts`) +
+ FfiConverterString.allocationSize(value.`lastEnd`) +
+ FfiConverterString.allocationSize(value.`probeError`) +
+ FfiConverterString.allocationSize(value.`restart`) +
+ FfiConverterBoolean.allocationSize(value.`startOnBoot`) +
+ FfiConverterString.allocationSize(value.`logPath`)
+ )
+
+ override fun write(value: SpaceServiceInfo, buf: ByteBuffer) {
+ FfiConverterString.write(value.`name`, buf)
+ FfiConverterString.write(value.`command`, buf)
+ FfiConverterString.write(value.`state`, buf)
+ FfiConverterUInt.write(value.`pid`, buf)
+ FfiConverterUInt.write(value.`restarts`, buf)
+ FfiConverterString.write(value.`lastEnd`, buf)
+ FfiConverterString.write(value.`probeError`, buf)
+ FfiConverterString.write(value.`restart`, buf)
+ FfiConverterBoolean.write(value.`startOnBoot`, buf)
+ FfiConverterString.write(value.`logPath`, buf)
+ }
+}
+
+
+
+/**
+ * A health check: exactly one of `http`, `tcp`, `command`.
+ */
+data class SpaceServiceProbe (
+ /**
+ * A URL that answers 2xx or 3xx.
+ */
+ var `http`: kotlin.String? = null
+ ,
+ /**
+ * `host:port` that accepts a TCP connection.
+ */
+ var `tcp`: kotlin.String? = null
+ ,
+ /**
+ * A shell command that exits 0 when healthy.
+ */
+ var `command`: kotlin.String? = null
+ ,
+ /**
+ * Seconds between checks (default 10).
+ */
+ var `intervalSecs`: kotlin.ULong? = null
+ ,
+ /**
+ * Failed checks in a row that restart it (default 3).
+ */
+ var `failures`: kotlin.UInt? = null
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeSpaceServiceProbe: FfiConverterRustBuffer<SpaceServiceProbe> {
+ override fun read(buf: ByteBuffer): SpaceServiceProbe {
+ return SpaceServiceProbe(
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalULong.read(buf),
+ FfiConverterOptionalUInt.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: SpaceServiceProbe) = (
+ FfiConverterOptionalString.allocationSize(value.`http`) +
+ FfiConverterOptionalString.allocationSize(value.`tcp`) +
+ FfiConverterOptionalString.allocationSize(value.`command`) +
+ FfiConverterOptionalULong.allocationSize(value.`intervalSecs`) +
+ FfiConverterOptionalUInt.allocationSize(value.`failures`)
+ )
+
+ override fun write(value: SpaceServiceProbe, buf: ByteBuffer) {
+ FfiConverterOptionalString.write(value.`http`, buf)
+ FfiConverterOptionalString.write(value.`tcp`, buf)
+ FfiConverterOptionalString.write(value.`command`, buf)
+ FfiConverterOptionalULong.write(value.`intervalSecs`, buf)
+ FfiConverterOptionalUInt.write(value.`failures`, buf)
+ }
+}
+
+
+
/**
* One account a Space is shared with.
*/
@@ -47570,6 +48853,205 @@ public object FfiConverterTypeTransferResult: FfiConverterRustBuffer<TransferRes
+/**
+ * A tree's budget and what its children use ([`Spaces::tree_budget`]).
+ */
+data class TreeBudget (
+ /**
+ * The tree's top-level Space.
+ */
+ var `root`: kotlin.String
+ ,
+ /**
+ * What the owner set.
+ */
+ var `set`: TreeBudgetLimits
+ ,
+ /**
+ * Child Spaces it may hold at once.
+ */
+ var `maxSpaces`: kotlin.UInt
+ ,
+ /**
+ * vCPUs it may hold at once.
+ */
+ var `maxVcpus`: kotlin.UInt
+ ,
+ /**
+ * Memory it may hold at once (MiB).
+ */
+ var `maxMemoryMb`: kotlin.ULong
+ ,
+ /**
+ * Cost per hour it may run at.
+ */
+ var `usdPerHour`: kotlin.Double
+ ,
+ /**
+ * Cost in total it may reach, when capped.
+ */
+ var `usdTotal`: kotlin.Double?
+ ,
+ /**
+ * Child Spaces now.
+ */
+ var `spaces`: kotlin.UInt
+ ,
+ /**
+ * vCPUs they hold.
+ */
+ var `vcpus`: kotlin.UInt
+ ,
+ /**
+ * Memory they hold (MiB).
+ */
+ var `memoryMb`: kotlin.ULong
+ ,
+ /**
+ * Cost per hour they run at.
+ */
+ var `usdPerHourUsed`: kotlin.Double
+ ,
+ /**
+ * What they have cost so far.
+ */
+ var `usdSpent`: kotlin.Double
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeTreeBudget: FfiConverterRustBuffer<TreeBudget> {
+ override fun read(buf: ByteBuffer): TreeBudget {
+ return TreeBudget(
+ FfiConverterString.read(buf),
+ FfiConverterTypeTreeBudgetLimits.read(buf),
+ FfiConverterUInt.read(buf),
+ FfiConverterUInt.read(buf),
+ FfiConverterULong.read(buf),
+ FfiConverterDouble.read(buf),
+ FfiConverterOptionalDouble.read(buf),
+ FfiConverterUInt.read(buf),
+ FfiConverterUInt.read(buf),
+ FfiConverterULong.read(buf),
+ FfiConverterDouble.read(buf),
+ FfiConverterDouble.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: TreeBudget) = (
+ FfiConverterString.allocationSize(value.`root`) +
+ FfiConverterTypeTreeBudgetLimits.allocationSize(value.`set`) +
+ FfiConverterUInt.allocationSize(value.`maxSpaces`) +
+ FfiConverterUInt.allocationSize(value.`maxVcpus`) +
+ FfiConverterULong.allocationSize(value.`maxMemoryMb`) +
+ FfiConverterDouble.allocationSize(value.`usdPerHour`) +
+ FfiConverterOptionalDouble.allocationSize(value.`usdTotal`) +
+ FfiConverterUInt.allocationSize(value.`spaces`) +
+ FfiConverterUInt.allocationSize(value.`vcpus`) +
+ FfiConverterULong.allocationSize(value.`memoryMb`) +
+ FfiConverterDouble.allocationSize(value.`usdPerHourUsed`) +
+ FfiConverterDouble.allocationSize(value.`usdSpent`)
+ )
+
+ override fun write(value: TreeBudget, buf: ByteBuffer) {
+ FfiConverterString.write(value.`root`, buf)
+ FfiConverterTypeTreeBudgetLimits.write(value.`set`, buf)
+ FfiConverterUInt.write(value.`maxSpaces`, buf)
+ FfiConverterUInt.write(value.`maxVcpus`, buf)
+ FfiConverterULong.write(value.`maxMemoryMb`, buf)
+ FfiConverterDouble.write(value.`usdPerHour`, buf)
+ FfiConverterOptionalDouble.write(value.`usdTotal`, buf)
+ FfiConverterUInt.write(value.`spaces`, buf)
+ FfiConverterUInt.write(value.`vcpus`, buf)
+ FfiConverterULong.write(value.`memoryMb`, buf)
+ FfiConverterDouble.write(value.`usdPerHourUsed`, buf)
+ FfiConverterDouble.write(value.`usdSpent`, buf)
+ }
+}
+
+
+
+/**
+ * What a tree's children may hold and cost ([`Spaces::set_tree_budget`]).
+ * `None`: the default.
+ */
+data class TreeBudgetLimits (
+ /**
+ * Child Spaces at once (default 16).
+ */
+ var `maxSpaces`: kotlin.UInt? = null
+ ,
+ /**
+ * vCPUs at once (default 16).
+ */
+ var `maxVcpus`: kotlin.UInt? = null
+ ,
+ /**
+ * Memory at once, MiB (default 32768).
+ */
+ var `maxMemoryMb`: kotlin.ULong? = null
+ ,
+ /**
+ * Cost per hour, in linked clouds (default 2.0).
+ */
+ var `usdPerHour`: kotlin.Double? = null
+ ,
+ /**
+ * Cost in total (default: none).
+ */
+ var `usdTotal`: kotlin.Double? = null
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeTreeBudgetLimits: FfiConverterRustBuffer<TreeBudgetLimits> {
+ override fun read(buf: ByteBuffer): TreeBudgetLimits {
+ return TreeBudgetLimits(
+ FfiConverterOptionalUInt.read(buf),
+ FfiConverterOptionalUInt.read(buf),
+ FfiConverterOptionalULong.read(buf),
+ FfiConverterOptionalDouble.read(buf),
+ FfiConverterOptionalDouble.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: TreeBudgetLimits) = (
+ FfiConverterOptionalUInt.allocationSize(value.`maxSpaces`) +
+ FfiConverterOptionalUInt.allocationSize(value.`maxVcpus`) +
+ FfiConverterOptionalULong.allocationSize(value.`maxMemoryMb`) +
+ FfiConverterOptionalDouble.allocationSize(value.`usdPerHour`) +
+ FfiConverterOptionalDouble.allocationSize(value.`usdTotal`)
+ )
+
+ override fun write(value: TreeBudgetLimits, buf: ByteBuffer) {
+ FfiConverterOptionalUInt.write(value.`maxSpaces`, buf)
+ FfiConverterOptionalUInt.write(value.`maxVcpus`, buf)
+ FfiConverterOptionalULong.write(value.`maxMemoryMb`, buf)
+ FfiConverterOptionalDouble.write(value.`usdPerHour`, buf)
+ FfiConverterOptionalDouble.write(value.`usdTotal`, buf)
+ }
+}
+
+
+
/**
* Upload options.
*/
@@ -51135,6 +52617,38 @@ public object FfiConverterOptionalTypeImageInfo: FfiConverterRustBuffer<ImageInf
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeNetworkSettings: FfiConverterRustBuffer<NetworkSettings?> {
+ override fun read(buf: ByteBuffer): NetworkSettings? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeNetworkSettings.read(buf)
+ }
+
+ override fun allocationSize(value: NetworkSettings?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeNetworkSettings.allocationSize(value)
+ }
+ }
+
+ override fun write(value: NetworkSettings?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeNetworkSettings.write(value, buf)
+ }
+ }
+}
+
+
+
+
/**
* @suppress
*/
@@ -51615,6 +53129,38 @@ public object FfiConverterOptionalTypeSpaceInfo: FfiConverterRustBuffer<SpaceInf
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeSpaceServiceProbe: FfiConverterRustBuffer<SpaceServiceProbe?> {
+ override fun read(buf: ByteBuffer): SpaceServiceProbe? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeSpaceServiceProbe.read(buf)
+ }
+
+ override fun allocationSize(value: SpaceServiceProbe?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeSpaceServiceProbe.allocationSize(value)
+ }
+ }
+
+ override fun write(value: SpaceServiceProbe?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeSpaceServiceProbe.write(value, buf)
+ }
+ }
+}
+
+
+
+
/**
* @suppress
*/
@@ -54507,6 +56053,34 @@ public object FfiConverterSequenceTypeSpaceInfo: FfiConverterRustBuffer<List<Spa
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypeSpaceOrphan: FfiConverterRustBuffer<List<SpaceOrphan>> {
+ override fun read(buf: ByteBuffer): List<SpaceOrphan> {
+ val len = buf.getInt()
+ return List<SpaceOrphan>(len) {
+ FfiConverterTypeSpaceOrphan.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<SpaceOrphan>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypeSpaceOrphan.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<SpaceOrphan>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypeSpaceOrphan.write(it, buf)
+ }
+ }
+}
+
+
+
+
/**
* @suppress
*/
@@ -54563,6 +56137,34 @@ public object FfiConverterSequenceTypeSpaceSentFile: FfiConverterRustBuffer<List
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypeSpaceServiceInfo: FfiConverterRustBuffer<List<SpaceServiceInfo>> {
+ override fun read(buf: ByteBuffer): List<SpaceServiceInfo> {
+ val len = buf.getInt()
+ return List<SpaceServiceInfo>(len) {
+ FfiConverterTypeSpaceServiceInfo.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<SpaceServiceInfo>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypeSpaceServiceInfo.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<SpaceServiceInfo>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypeSpaceServiceInfo.write(it, buf)
+ }
+ }
+}
+
+
+
+
/**
* @suppress
*/
diff --git a/libs/cua/proto/cua/daemon/v1/egress.proto b/libs/cua/proto/cua/daemon/v1/egress.proto
index 39f76c0590..7694d8bf44 100644
--- a/libs/cua/proto/cua/daemon/v1/egress.proto
+++ b/libs/cua/proto/cua/daemon/v1/egress.proto
@@ -32,3 +32,100 @@ message SetSpaceEgressRequest {
// Response for `SpaceService.SetSpaceEgress`.
message SetSpaceEgressResponse {}
+
+// A Space's network settings: a preset, the user's own lists, and what the
+// host compiles them to. `Space.network_settings` and
+// `CreateSpaceRequest.network_settings` carry it. The presets:
+//
+// - "internet" (the default): the public internet and the Space's own
+// tree; the host, the local network, cloud metadata, other trees and the
+// daemon are blocked;
+// - "none": no network;
+// - "localhost": "internet", plus the host's loopback on
+// `localhost_ports` (every port only with `all_localhost_ports`);
+// - "lan": "internet", plus the local network (not the host itself);
+// - "custom": `custom_base` ("internet" or "none") plus `allow` and `deny`;
+// - "unprotected": everything but cloud metadata, other trees and the
+// daemon.
+//
+// `allow` and `deny` apply on top of any preset but "none": an allow is an
+// exception to a deny and to the default blocks (not the host itself, which
+// only "localhost" opens).
+message NetworkSettings {
+ // The preset word; empty is "internet".
+ string preset = 1;
+ // "localhost": the host loopback ports the Space may reach.
+ repeated uint32 localhost_ports = 2;
+ // "localhost": every port (the daemon's stay blocked).
+ bool all_localhost_ports = 3;
+ // Destinations that stay reachable (addresses or CIDRs).
+ repeated string allow = 4;
+ // Destinations that are blocked (addresses, CIDRs or "all").
+ repeated string deny = 5;
+ // "custom": what it starts from, "internet" (empty) or "none".
+ string custom_base = 6;
+ // Set when the Space was allowed more than its parent: who and when.
+ string widened_by = 7;
+}
+
+// A Space's network as `cua network show` says it.
+message SpaceNetworkInfo {
+ // Its settings.
+ NetworkSettings settings = 1;
+ // One plain line ("Internet only").
+ string summary = 2;
+ // What the settings open beyond "internet", one plain line each.
+ repeated string widenings = 3;
+ // "enforced" (rules on the host, outside the guest), "no_network" (its
+ // runtime can't protect it yet, so it has none), "open" (No protection)
+ // or "refused"; empty when unknown (a Space another machine runs).
+ string enforcement = 4;
+ // Where the rules are enforced, or why its network is cut, for people.
+ string point = 5;
+ // Why its network is not what was asked, in plain words.
+ string note = 6;
+ // Its parent and its tree's top-level Space (ids); empty for a
+ // top-level Space.
+ string parent = 7;
+ // Its tree's top-level Space.
+ string root = 8;
+ // What no setting opens, in plain words.
+ repeated string always_blocked = 9;
+ // An update changed its settings; say so once.
+ bool notice_pending = 10;
+}
+
+// Request for `SpaceService.GetSpaceNetwork`.
+message GetSpaceNetworkRequest {
+ // Space.
+ string space = 1;
+ // The caller showed the one-time notice about new network defaults:
+ // don't show it again.
+ bool ack_notice = 2;
+}
+
+// Response for `SpaceService.GetSpaceNetwork`.
+message GetSpaceNetworkResponse {
+ // The Space's network.
+ SpaceNetworkInfo network = 1;
+}
+
+// Request for `SpaceService.SetSpaceNetwork`.
+message SetSpaceNetworkRequest {
+ // Space.
+ string space = 1;
+ // The whole settings.
+ NetworkSettings settings = 2;
+ // A child: let it be more open than its parent (recorded).
+ bool widen = 3;
+ // Its children take the same settings (each within its parent's).
+ bool tree = 4;
+}
+
+// Response for `SpaceService.SetSpaceNetwork`.
+message SetSpaceNetworkResponse {
+ // "now" or "next_start".
+ string applied = 1;
+ // The Space's network after the change.
+ SpaceNetworkInfo network = 2;
+}
diff --git a/libs/cua/proto/cua/daemon/v1/spaces.proto b/libs/cua/proto/cua/daemon/v1/spaces.proto
index 3fe4852ba3..7baeaedb15 100644
--- a/libs/cua/proto/cua/daemon/v1/spaces.proto
+++ b/libs/cua/proto/cua/daemon/v1/spaces.proto
@@ -68,7 +68,8 @@ service SpaceService {
// wizard's GPU row; `gpu` of `CreateSpace`).
rpc GetGpuSupport(GetGpuSupportRequest) returns (GetGpuSupportResponse);
// Deletes a Space's sandbox and forgets it. A Space added by address
- // (`direct:`, `relay:`) is only forgotten: cua did not create it.
+ // (`direct:`, `relay:`) is only forgotten: cua did not create it. Its
+ // child Spaces are deleted first, unless `keep_children`.
rpc DeleteSpace(DeleteSpaceRequest) returns (DeleteSpaceResponse);
// Deletes several Spaces (at most 3 at a time), turning running ones off
// first. One result per Space, in order; one failure never stops the
@@ -102,6 +103,27 @@ service SpaceService {
rpc SetSpaceLifetime(SetSpaceLifetimeRequest) returns (SetSpaceLifetimeResponse);
// Replaces a Space's egress policy (empty removes it).
rpc SetSpaceEgress(SetSpaceEgressRequest) returns (SetSpaceEgressResponse);
+ // A Space's network: its settings, what they open, where they are
+ // enforced (or why its network is cut), and what is always blocked.
+ rpc GetSpaceNetwork(GetSpaceNetworkRequest) returns (GetSpaceNetworkResponse);
+ // Replaces a Space's network settings (a child's stay within its
+ // parent's unless `widen`).
+ rpc SetSpaceNetwork(SetSpaceNetworkRequest) returns (SetSpaceNetworkResponse);
+ // Lets a Space make child Spaces of its own, or stops it. Turning it off
+ // ends the Space's spawn capability at once; children it already made
+ // keep running until they are deleted or their lifetime ends.
+ rpc SetSpaceChildren(SetSpaceChildrenRequest) returns (SetSpaceChildrenResponse);
+ // A tree's budget (kept on its top-level Space) and what its children
+ // use now. `space` may be any Space of the tree.
+ rpc GetTreeBudget(GetTreeBudgetRequest) returns (GetTreeBudgetResponse);
+ // Sets a tree's budget: how many child Spaces, vCPUs and memory its
+ // children may hold at once, and what they may cost. Unset limits take
+ // the defaults; all unset removes the budget.
+ rpc SetTreeBudget(SetTreeBudgetRequest) returns (SetTreeBudgetResponse);
+ // Child Spaces whose parent is gone, or not this machine's to judge: the
+ // ones it ends after a grace period (only on proof the parent is gone)
+ // and the ones it only lists.
+ rpc ListOrphans(ListOrphansRequest) returns (ListOrphansResponse);
// Connects to a registered Space and returns a loopback env passthrough
// (`<loopback>/v1/spaces/<key>/env`) that carries the Space's credentials,
// so a client runs every `cua.env.v1` call and media WebSocket through the
@@ -275,6 +297,29 @@ message Space {
// Space that is a machine on the relay is renamed there, so its `name`
// changes instead.
string display_name = 33;
+ // Its network settings. Unset for a Space created before they existed
+ // (it gets them on its next start).
+ NetworkSettings network_settings = 34;
+ // Why its network is not what was asked, in plain words (a runtime that
+ // can't protect it yet started it without network). Empty otherwise.
+ string network_note = 35;
+ // The Space it was created from (a child), by id; empty for a top-level
+ // Space.
+ string parent = 36;
+ // The top-level Space of its tree, by id; empty for a top-level Space.
+ string root = 37;
+ // Its network settings changed by an update (an old Space moved to the
+ // new defaults); apps and the CLI say so once.
+ bool network_notice_pending = 38;
+ // How far below its tree's top-level Space it is: 0 for a top-level
+ // Space, 1 for its children, ...
+ uint32 depth = 39;
+ // How it was made: "user", "child" or "fork-batch:<id>".
+ string origin = 40;
+ // The Space may make child Spaces of its own (`SetSpaceChildren`): `cua`,
+ // the SDKs and the agent's tools in it create, list and delete Spaces
+ // that belong to it, on a channel only it can reach.
+ bool children = 43;
}
// Who a Space belongs to and who else has it (`Space.sharing`).
@@ -647,6 +692,9 @@ message SetSpaceLifetimeResponse {
message DeleteSpaceRequest {
// Space.
string space = 1;
+ // Keep its child Spaces: they become top-level Spaces and keep running.
+ // Unset: they are deleted first.
+ bool keep_children = 2;
}
// Response for `SpaceService.DeleteSpace`.
@@ -898,6 +946,33 @@ message CreateSpaceRequest {
string instance_type = 26;
// Cloud host region (a pin).
string region = 27;
+ // Network settings. Unset: what `network` and `egress` say ("internet"
+ // when neither says anything).
+ NetworkSettings network_settings = 28;
+ // Create it as a child of this Space (id or name): its network is no
+ // more open than the parent's.
+ string parent = 29;
+ // With `parent`: let it be more open than its parent (recorded on the
+ // Space).
+ // (30 and 31 are kept for other create options.)
+ bool widen = 32;
+ // Let the Space make child Spaces of its own (`SetSpaceChildren`).
+ // Unset: off.
+ optional bool children = 33;
+}
+
+// Request for `SpaceService.SetSpaceChildren`.
+message SetSpaceChildrenRequest {
+ // Id or name.
+ string space = 1;
+ // On or off.
+ bool enabled = 2;
+}
+
+// Response for `SpaceService.SetSpaceChildren`.
+message SetSpaceChildrenResponse {
+ // The Space as it is now.
+ Space space = 1;
}
// Request for `SpaceService.CreateSpaceStream`.
@@ -966,3 +1041,96 @@ message GetGpuSupportResponse {
// One entry per runtime of the location.
repeated GpuSupport runtimes = 1;
}
+
+// What a tree's children may hold and cost. Unset: the default.
+message TreeBudgetLimits {
+ // Child Spaces at once (default 16).
+ optional uint32 max_spaces = 1;
+ // vCPUs at once (default 16).
+ optional uint32 max_vcpus = 2;
+ // Memory at once, MiB (default 32768).
+ optional uint64 max_memory_mb = 3;
+ // Cost per hour of what runs at once, in linked clouds (default 2.0).
+ optional double usd_per_hour = 4;
+ // Cost in total (default: no total cap).
+ optional double usd_total = 5;
+}
+
+// Request for `SpaceService.GetTreeBudget`.
+message GetTreeBudgetRequest {
+ // Any Space of the tree (id or name).
+ string space = 1;
+}
+
+// Request for `SpaceService.SetTreeBudget`.
+message SetTreeBudgetRequest {
+ // Any Space of the tree (id or name); the budget is kept on its root.
+ string space = 1;
+ // The limits.
+ TreeBudgetLimits limits = 2;
+}
+
+// Response for `SpaceService.GetTreeBudget`.
+message GetTreeBudgetResponse {
+ // The budget and use.
+ TreeBudget budget = 1;
+}
+
+// Response for `SpaceService.SetTreeBudget`.
+message SetTreeBudgetResponse {
+ // The budget and use.
+ TreeBudget budget = 1;
+}
+
+// A tree's budget and use.
+message TreeBudget {
+ // The tree's top-level Space.
+ string root = 1;
+ // What the owner set (unset fields take the default).
+ TreeBudgetLimits set = 2;
+ // Child Spaces it may hold at once.
+ uint32 max_spaces = 3;
+ // vCPUs it may hold at once.
+ uint32 max_vcpus = 4;
+ // Memory it may hold at once (MiB).
+ uint64 max_memory_mb = 5;
+ // Cost per hour it may run at.
+ double usd_per_hour = 6;
+ // Cost in total it may reach, when capped.
+ optional double usd_total = 7;
+ // Child Spaces now (creates in flight included).
+ uint32 spaces = 8;
+ // vCPUs they hold.
+ uint32 vcpus = 9;
+ // Memory they hold (MiB).
+ uint64 memory_mb = 10;
+ // Cost per hour they run at.
+ double usd_per_hour_used = 11;
+ // What its children have cost so far.
+ double usd_spent = 12;
+}
+
+// Request for `SpaceService.ListOrphans`.
+message ListOrphansRequest {}
+
+// A child Space whose parent is gone or out of reach.
+message Orphan {
+ // The child.
+ string space = 1;
+ // Its parent's id.
+ string parent = 2;
+ // "ending": its parent is provably gone and it ends after the grace;
+ // "listed": its parent is not this machine's to judge, so it stays until
+ // deleted or its own lifetime ends.
+ string state = 3;
+ // Why, in words.
+ string why = 4;
+ // Seconds until it ends ("ending" only).
+ int64 ends_in_secs = 5;
+}
+
+// Response for `SpaceService.ListOrphans`.
+message ListOrphansResponse {
+ // By child id.
+ repeated Orphan orphans = 1;
+}
diff --git a/libs/cua/proto/cua/env/v1/host.proto b/libs/cua/proto/cua/env/v1/host.proto
index 283c54ef76..9a75c30633 100644
--- a/libs/cua/proto/cua/env/v1/host.proto
+++ b/libs/cua/proto/cua/env/v1/host.proto
@@ -265,6 +265,9 @@ message CreateHostSpaceRequest {
// instruction. A host that does not enforce it leaves
// `HostSpace.egress_enforced` empty.
HostEgressPolicy egress = 19;
+ // Network settings, compiled and enforced by the host. Unset: what
+ // `network` and `egress` say.
+ HostNetworkSettings network_settings = 20;
// Reached through this host's channel (no relay machine of its own).
bool routed = 13;
// Guest environment; the host's driver settings win on a clash.
diff --git a/libs/cua/proto/cua/env/v1/host_egress.proto b/libs/cua/proto/cua/env/v1/host_egress.proto
index b1037493b7..62fede5938 100644
--- a/libs/cua/proto/cua/env/v1/host_egress.proto
+++ b/libs/cua/proto/cua/env/v1/host_egress.proto
@@ -29,3 +29,23 @@ message SetHostSpaceEgressResponse {
// Where the policy is enforced: "host"; empty after a removal.
string enforced = 1;
}
+
+// A Space's network settings (`cua.daemon.v1.NetworkSettings`), as
+// `CreateHostSpaceRequest.network_settings` carries them to the host that
+// creates the Space and enforces them.
+message HostNetworkSettings {
+ // The preset word; empty is "internet".
+ string preset = 1;
+ // "localhost": the host loopback ports the Space may reach.
+ repeated uint32 localhost_ports = 2;
+ // "localhost": every port.
+ bool all_localhost_ports = 3;
+ // Destinations that stay reachable.
+ repeated string allow = 4;
+ // Destinations that are blocked.
+ repeated string deny = 5;
+ // "custom": "internet" (empty) or "none".
+ string custom_base = 6;
+ // Set when the Space was allowed more than its parent.
+ string widened_by = 7;
+}
diff --git a/libs/cua/proto/cua/env/v1/process.proto b/libs/cua/proto/cua/env/v1/process.proto
index d2da1724b4..8a57efac8d 100644
--- a/libs/cua/proto/cua/env/v1/process.proto
+++ b/libs/cua/proto/cua/env/v1/process.proto
@@ -55,6 +55,21 @@ service ProcessService {
// process group), and later requests carrying a lower epoch fail with
// FAILED_PRECONDITION / `ERROR_REASON_STALE_EPOCH`.
rpc AdvanceEpoch(AdvanceEpochRequest) returns (AdvanceEpochResponse);
+ // Keeps a command running as a named service: started at once, started
+ // again by its restart policy when it exits or fails its health check,
+ // started when cua-spacesd starts (after the guest boots) unless
+ // `start_on_boot` is false, and its output kept in log files. Putting a
+ // name that exists replaces it (the old process is stopped first).
+ rpc PutService(PutServiceRequest) returns (PutServiceResponse);
+ // Stops a service and forgets it (its log files go too).
+ rpc DeleteService(DeleteServiceRequest) returns (DeleteServiceResponse);
+ // Lists services with their state.
+ rpc ListServices(ListServicesRequest) returns (ListServicesResponse);
+ // Starts, stops or restarts a service. A stopped service stays stopped
+ // until started (also across a restart of cua-spacesd).
+ rpc ControlService(ControlServiceRequest) returns (ControlServiceResponse);
+ // The end of a service's log.
+ rpc GetServiceLogs(GetServiceLogsRequest) returns (GetServiceLogsResponse);
}
// What to run.
@@ -497,3 +512,171 @@ message AdvanceEpochResponse {
// Running processes killed because they carried a lower epoch.
uint32 killed = 2;
}
+
+// When a service is started again.
+enum RestartPolicy {
+ // Unset: `RESTART_POLICY_ALWAYS`.
+ RESTART_POLICY_UNSPECIFIED = 0;
+ // Whenever it ends, however it ends.
+ RESTART_POLICY_ALWAYS = 1;
+ // When it ends with a non-zero code, a signal, or a failed health check.
+ RESTART_POLICY_ON_FAILURE = 2;
+ // Never: it runs once.
+ RESTART_POLICY_NEVER = 3;
+}
+
+// How a service's health is checked. Set exactly one of `exec`, `http`,
+// `tcp`.
+message HealthProbe {
+ // A command that exits 0 when the service is healthy.
+ ProcessConfig exec = 1;
+ // A URL that answers 2xx or 3xx (`http://127.0.0.1:8080/health`).
+ string http = 2;
+ // A port that accepts a TCP connection (`127.0.0.1:5432`).
+ string tcp = 3;
+ // Between checks. Unset: 10 seconds.
+ google.protobuf.Duration interval = 4;
+ // For one check. Unset: 5 seconds.
+ google.protobuf.Duration timeout = 5;
+ // Failed checks in a row that mark it unhealthy and restart it. 0: 3.
+ uint32 failure_threshold = 6;
+ // Grace after a start before the first check counts. Unset: 10 seconds.
+ google.protobuf.Duration start_period = 7;
+}
+
+// A service: a named command kept running.
+message ServiceSpec {
+ // Name: lowercase letters, digits, `-`, `_` and `.`, 1 to 63 of them,
+ // starting with a letter or digit.
+ string name = 1;
+ // What to run (`timeout` is ignored).
+ ProcessConfig config = 2;
+ // When it is started again. Unset: always.
+ RestartPolicy restart = 3;
+ // First wait before a restart; it doubles on each quick failure. Unset:
+ // 1 second.
+ google.protobuf.Duration backoff_min = 4;
+ // Longest wait before a restart. Unset: 60 seconds.
+ google.protobuf.Duration backoff_max = 5;
+ // Health check. Unset: the service is healthy while it runs.
+ HealthProbe probe = 6;
+ // Start it when cua-spacesd starts. Unset: true.
+ optional bool start_on_boot = 7;
+ // Size at which the log file is rotated (one older file is kept). 0:
+ // 10 MiB.
+ uint64 log_max_bytes = 8;
+}
+
+// Where a service is.
+enum ServiceState {
+ // Not reported.
+ SERVICE_STATE_UNSPECIFIED = 0;
+ // Starting (or waiting for its first health check).
+ SERVICE_STATE_STARTING = 1;
+ // Running, and healthy when it has a check.
+ SERVICE_STATE_RUNNING = 2;
+ // Running, but its last checks failed.
+ SERVICE_STATE_UNHEALTHY = 3;
+ // Ended; waiting `next_start_at` to start again.
+ SERVICE_STATE_BACKOFF = 4;
+ // Stopped by a caller.
+ SERVICE_STATE_STOPPED = 5;
+ // Ended and its policy does not start it again.
+ SERVICE_STATE_EXITED = 6;
+ // Could not be started (the command does not exist, ...).
+ SERVICE_STATE_FAILED = 7;
+}
+
+// A service and how it is doing.
+message ServiceStatus {
+ // What it runs.
+ ServiceSpec spec = 1;
+ // Where it is.
+ ServiceState state = 2;
+ // Its current process, while it runs.
+ uint32 pid = 3;
+ // Starts after the first one.
+ uint32 restarts = 4;
+ // When the current (or last) process started.
+ google.protobuf.Timestamp started_at = 5;
+ // How the last process ended.
+ ProcessEnd last_end = 6;
+ // The last failed health check, empty when the last one passed.
+ string probe_error = 7;
+ // When it starts again (state `SERVICE_STATE_BACKOFF`).
+ google.protobuf.Timestamp next_start_at = 8;
+ // Its log file in the guest.
+ string log_path = 9;
+}
+
+// Request for `ProcessService.PutService`.
+message PutServiceRequest {
+ // The service.
+ ServiceSpec spec = 1;
+}
+
+// Response for `ProcessService.PutService`.
+message PutServiceResponse {
+ // Its state right after it was put.
+ ServiceStatus service = 1;
+}
+
+// Request for `ProcessService.DeleteService`.
+message DeleteServiceRequest {
+ // Name.
+ string name = 1;
+}
+
+// Response for `ProcessService.DeleteService`.
+message DeleteServiceResponse {}
+
+// Request for `ProcessService.ListServices`.
+message ListServicesRequest {}
+
+// Response for `ProcessService.ListServices`.
+message ListServicesResponse {
+ // By name.
+ repeated ServiceStatus services = 1;
+}
+
+// What `ControlService` does.
+enum ServiceAction {
+ // Not set (refused).
+ SERVICE_ACTION_UNSPECIFIED = 0;
+ // Start it (no-op when it runs).
+ SERVICE_ACTION_START = 1;
+ // Stop it and keep it stopped.
+ SERVICE_ACTION_STOP = 2;
+ // Stop it, then start it.
+ SERVICE_ACTION_RESTART = 3;
+}
+
+// Request for `ProcessService.ControlService`.
+message ControlServiceRequest {
+ // Name.
+ string name = 1;
+ // What to do.
+ ServiceAction action = 2;
+}
+
+// Response for `ProcessService.ControlService`.
+message ControlServiceResponse {
+ // Its state after the action.
+ ServiceStatus service = 1;
+}
+
+// Request for `ProcessService.GetServiceLogs`.
+message GetServiceLogsRequest {
+ // Name.
+ string name = 1;
+ // How many bytes from the end. 0: 64 KiB; at most 4 MiB.
+ uint64 tail_bytes = 2;
+}
+
+// Response for `ProcessService.GetServiceLogs`.
+message GetServiceLogsResponse {
+ // The end of its output (stdout and stderr interleaved as written).
+ bytes data = 1;
+ // True when older output was left out.
+ bool truncated = 2;
+}
diff --git a/libs/cua/proto/cua/env/v1/tunnel.proto b/libs/cua/proto/cua/env/v1/tunnel.proto
index 5538ca2637..34d1f2c131 100644
--- a/libs/cua/proto/cua/env/v1/tunnel.proto
+++ b/libs/cua/proto/cua/env/v1/tunnel.proto
@@ -16,6 +16,11 @@ import "google/protobuf/timestamp.proto";
// guest loopback relays each outbound connection over the client's
// WebSocket, and the client dials it from its own network. Replaces the
// unauthenticated rcdp-socks.
+// - Spawn: the guest-to-host channel of child Spaces. A listener on guest
+// loopback relays each connection over the WebSocket of the host that runs
+// the Space, which serves this Space's own children (create, list, delete)
+// and nothing else. The host knows which Space a connection comes from by
+// the WebSocket it opened, never by anything the guest says.
service TunnelService {
// Authorizes TCP forwarding to a guest port and returns the WebSocket to
// connect to.
@@ -30,6 +35,14 @@ service TunnelService {
rpc StopHotspot(StopHotspotRequest) returns (StopHotspotResponse);
// Reports hotspot state and counters.
rpc GetHotspotStatus(GetHotspotStatusRequest) returns (GetHotspotStatusResponse);
+ // Starts the spawn channel and installs the Space's spawn capability.
+ // Only a caller holding the Space's own token (the host that runs it) may
+ // call it; starting it again replaces the channel and the capability.
+ rpc StartSpawn(StartSpawnRequest) returns (StartSpawnResponse);
+ // Stops the spawn channel and removes the capability from the guest.
+ rpc StopSpawn(StopSpawnRequest) returns (StopSpawnResponse);
+ // Reports the spawn channel's state.
+ rpc GetSpawnStatus(GetSpawnStatusRequest) returns (GetSpawnStatusResponse);
}
// Request for `TunnelService.Forward`.
@@ -164,3 +177,61 @@ message GetHotspotStatusResponse {
// Bytes received into the guest through the hotspot.
uint64 bytes_in = 7;
}
+
+// Request for `TunnelService.StartSpawn`.
+message StartSpawnRequest {
+ // The Space's spawn capability, minted by its host. The guest writes it
+ // to the token file (0600, owner: the user cua-spacesd runs as) for
+ // clients in the Space to present on the spawn listener.
+ string capability = 1;
+ // How long the ticket accepts the host's WebSocket. Unset means 60
+ // seconds.
+ google.protobuf.Duration ticket_ttl = 2;
+ // The Space's id, for the environment of new processes (`CUA_SPACE`).
+ string space_id = 3;
+}
+
+// Response for `TunnelService.StartSpawn`.
+message StartSpawnResponse {
+ // Spawn channel id.
+ string spawn_id = 1;
+ // Ticket for the spawn WebSocket.
+ string ticket = 2;
+ // WebSocket path relative to the spacesd base URL, including the ticket,
+ // for example "/spawn?ticket=…". The host keeps this socket open; the
+ // listener refuses connections while it is closed.
+ string ws_path = 3;
+ // Guest-side listener, as a URL clients in the Space use as their cua
+ // daemon, for example "http://127.0.0.1:41234".
+ string address = 4;
+ // Where the guest wrote the capability.
+ string token_path = 5;
+ // Where the guest wrote the listener's address (one line).
+ string address_path = 6;
+}
+
+// Request for `TunnelService.StopSpawn`.
+message StopSpawnRequest {
+ // Which channel. Empty stops the current one.
+ string spawn_id = 1;
+}
+
+// Response for `TunnelService.StopSpawn`.
+message StopSpawnResponse {}
+
+// Request for `TunnelService.GetSpawnStatus`.
+message GetSpawnStatusRequest {}
+
+// Response for `TunnelService.GetSpawnStatus`.
+message GetSpawnStatusResponse {
+ // A channel is started.
+ bool started = 1;
+ // The host's WebSocket is attached.
+ bool attached = 2;
+ // Channel id, when started.
+ string spawn_id = 3;
+ // Guest-side listener URL, when started.
+ string address = 4;
+ // Open relayed connections.
+ uint32 active_connections = 5;
+}
diff --git a/libs/cua/python/src/cua/__init__.py b/libs/cua/python/src/cua/__init__.py
index ff39832f72..5d44afded2 100644
--- a/libs/cua/python/src/cua/__init__.py
+++ b/libs/cua/python/src/cua/__init__.py
@@ -204,6 +204,13 @@ async def _agent_run_stream(
_AgentRun.stream = _agent_run_stream # type: ignore[attr-defined]
+def auto(*, state_dir: Optional[str] = None, spaces_home: Optional[str] = None) -> Cua:
+ """The default runtime: inside a Space with children on, its spawn
+ channel (every Space made through it is a child of that Space); else the
+ `cua daemon` this machine runs, else a runtime in this process."""
+ return Cua.auto(CuaConfig(state_dir=state_dir, spaces_home=spaces_home))
+
+
def connect(address: Optional[str] = None, token: Optional[str] = None) -> Cua:
"""A client of a running `cua daemon` (socket path or loopback URL)."""
return Cua.connect(address, token)
diff --git a/libs/cua/python/src/cua/_native.py b/libs/cua/python/src/cua/_native.py
index d610a1828e..c65d6b4d7d 100644
--- a/libs/cua/python/src/cua/_native.py
+++ b/libs/cua/python/src/cua/_native.py
@@ -1053,6 +1053,8 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_close_stream() != 64912:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_space_delete_service() != 14460:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_displays() != 30039:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_download() != 24915:
@@ -1071,18 +1073,26 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_join_presence() != 56636:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_space_kept_services() != 50248:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_list_tools() != 19376:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_open_stream() != 19577:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_space_put_service() != 55111:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_request_site_login() != 2223:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_space_restart_service() != 63778:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_route() != 9790:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_screenshot() != 41142:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_send_file() != 29056:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_space_service_logs() != 48773:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_services() != 32496:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_set_presence_settings() != 27206:
@@ -1095,8 +1105,12 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_start_hotspot() != 44744:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_space_start_service() != 13576:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_stop_hotspot() != 18254:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_space_stop_service() != 14671:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_stream_session() != 61326:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_space_supports() != 58799:
@@ -1153,6 +1167,8 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spacestreamsession_stats() != 40219:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_spaces_ack_network_notice() != 32926:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_add() != 56308:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_add_with_service() != 4755:
@@ -1213,12 +1229,14 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_create_with_progress() != 28676:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
- if lib.uniffi_cua_sdk_checksum_method_spaces_delete() != 39986:
+ if lib.uniffi_cua_sdk_checksum_method_spaces_delete() != 4316:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_delete_build() != 6500:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_delete_many() != 9087:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_spaces_delete_tree() != 29454:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_delete_volume() != 11412:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_fork() != 18152:
@@ -1237,12 +1255,16 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_machine_health() != 35352:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_spaces_network() != 41208:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_notifications() != 10964:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_notifications_ack() != 64477:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_notify_user() != 48805:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_spaces_orphans() != 23539:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_persistent_agent_create() != 6521:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_persistent_agent_remove() != 55018:
@@ -1281,10 +1303,16 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_routines() != 22768:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_spaces_set_children() != 63927:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_set_egress() != 12366:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_set_lifetime() != 62609:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_spaces_set_network() != 64671:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_spaces_set_tree_budget() != 8418:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_space() != 26355:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_start() != 32898:
@@ -1293,6 +1321,8 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_suspend() != 23817:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_spaces_tree_budget() != 58333:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_volume_approve() != 8640:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_volume_audit() != 21166:
@@ -3723,6 +3753,11 @@ _UniffiLib.uniffi_cua_sdk_fn_method_space_close_stream.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_space_close_stream.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_space_delete_service.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_space_delete_service.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_space_displays.argtypes = (
ctypes.c_uint64,
)
@@ -3768,6 +3803,10 @@ _UniffiLib.uniffi_cua_sdk_fn_method_space_join_presence.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_space_join_presence.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_space_kept_services.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_space_kept_services.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_space_list_tools.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -3778,12 +3817,22 @@ _UniffiLib.uniffi_cua_sdk_fn_method_space_open_stream.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_space_open_stream.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_space_put_service.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_space_put_service.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_space_request_site_login.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_space_request_site_login.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_space_restart_service.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_space_restart_service.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_space_route.argtypes = (
ctypes.c_uint64,
)
@@ -3799,6 +3848,12 @@ _UniffiLib.uniffi_cua_sdk_fn_method_space_send_file.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_space_send_file.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_space_service_logs.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_space_service_logs.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_space_services.argtypes = (
ctypes.c_uint64,
ctypes.POINTER(_UniffiRustCallStatus),
@@ -3830,10 +3885,20 @@ _UniffiLib.uniffi_cua_sdk_fn_method_space_start_hotspot.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_space_start_hotspot.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_space_start_service.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_space_start_service.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_space_stop_hotspot.argtypes = (
ctypes.c_uint64,
)
_UniffiLib.uniffi_cua_sdk_fn_method_space_stop_hotspot.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_space_stop_service.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_space_stop_service.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_space_stream_session.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -3980,6 +4045,11 @@ _UniffiLib.uniffi_cua_sdk_fn_method_spacestreamsession_stats.argtypes = (
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_sdk_fn_method_spacestreamsession_stats.restype = _UniffiRustBuffer
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_ack_network_notice.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_ack_network_notice.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_add.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -4166,6 +4236,12 @@ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_delete_many.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_delete_many.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_delete_tree.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ ctypes.c_int8,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_delete_tree.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_delete_volume.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -4209,6 +4285,11 @@ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_machine_health.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_machine_health.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_network.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_network.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_notifications.argtypes = (
ctypes.c_uint64,
ctypes.c_int8,
@@ -4227,6 +4308,10 @@ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_notify_user.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_notify_user.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_orphans.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_orphans.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_persistent_agent_create.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -4335,6 +4420,12 @@ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_routines.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_routines.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_children.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ ctypes.c_int8,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_children.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_egress.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -4348,6 +4439,20 @@ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_lifetime.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_lifetime.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_network.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+ ctypes.c_int8,
+ ctypes.c_int8,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_network.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_tree_budget.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_tree_budget.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_space.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -4368,6 +4473,11 @@ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_suspend.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_suspend.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_tree_budget.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_tree_budget.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_volume_approve.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -5746,6 +5856,9 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_space_checkpoint.restype = ctypes.c_ui
_UniffiLib.uniffi_cua_sdk_checksum_method_space_close_stream.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_space_close_stream.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_delete_service.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_delete_service.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_space_displays.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_space_displays.restype = ctypes.c_uint16
@@ -5773,15 +5886,24 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_space_info.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_space_join_presence.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_space_join_presence.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_kept_services.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_kept_services.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_space_list_tools.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_space_list_tools.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_space_open_stream.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_space_open_stream.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_put_service.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_put_service.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_space_request_site_login.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_space_request_site_login.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_restart_service.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_restart_service.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_space_route.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_space_route.restype = ctypes.c_uint16
@@ -5791,6 +5913,9 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_space_screenshot.restype = ctypes.c_ui
_UniffiLib.uniffi_cua_sdk_checksum_method_space_send_file.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_space_send_file.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_service_logs.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_service_logs.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_space_services.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_space_services.restype = ctypes.c_uint16
@@ -5809,9 +5934,15 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_space_spacesd.restype = ctypes.c_uint1
_UniffiLib.uniffi_cua_sdk_checksum_method_space_start_hotspot.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_space_start_hotspot.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_start_service.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_start_service.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_space_stop_hotspot.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_space_stop_hotspot.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_stop_service.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_space_stop_service.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_space_stream_session.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_space_stream_session.restype = ctypes.c_uint16
@@ -5896,6 +6027,9 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_spacestreamsession_send_text.restype =
_UniffiLib.uniffi_cua_sdk_checksum_method_spacestreamsession_stats.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spacestreamsession_stats.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_ack_network_notice.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_ack_network_notice.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_add.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_add.restype = ctypes.c_uint16
@@ -5995,6 +6129,9 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_spaces_delete_build.restype = ctypes.c
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_delete_many.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_delete_many.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_delete_tree.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_delete_tree.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_delete_volume.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_delete_volume.restype = ctypes.c_uint16
@@ -6022,6 +6159,9 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_spaces_list_tools_json.restype = ctype
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_machine_health.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_machine_health.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_network.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_network.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_notifications.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_notifications.restype = ctypes.c_uint16
@@ -6031,6 +6171,9 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_spaces_notifications_ack.restype = cty
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_notify_user.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_notify_user.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_orphans.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_orphans.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_persistent_agent_create.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_persistent_agent_create.restype = ctypes.c_uint16
@@ -6088,12 +6231,21 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_spaces_routine_set_enabled.restype = c
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_routines.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_routines.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_set_children.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_set_children.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_set_egress.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_set_egress.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_set_lifetime.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_set_lifetime.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_set_network.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_set_network.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_set_tree_budget.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_set_tree_budget.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_space.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_space.restype = ctypes.c_uint16
@@ -6106,6 +6258,9 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_spaces_stop.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_suspend.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_suspend.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_tree_budget.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_tree_budget.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_volume_approve.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_volume_approve.restype = ctypes.c_uint16
@@ -19089,6 +19244,103 @@ class _UniffiFfiConverterTypeNamedVolume(_UniffiConverterRustBuffer):
_UniffiFfiConverterString.write(value.name, buf)
_UniffiFfiConverterSequenceString.write(value.mounted_in, buf)
+@dataclass
+class NetworkSettings:
+ """
+ A Space's network settings: a preset and the user's own lists. The host
+ the Space runs on compiles them to rules it enforces outside the guest.
+
+ - `internet` (the default): the public internet and the Space's own
+ tree; this computer, your local network, cloud metadata, other trees
+ and the cua daemon are blocked;
+ - `none`: no network;
+ - `localhost`: `internet`, plus this computer's localhost on
+ `localhost_ports` (every port only with `all_localhost_ports`);
+ - `lan`: `internet`, plus your local network (not this computer);
+ - `custom`: `custom_base` (`internet` or `none`) plus `allow` and `deny`;
+ - `unprotected`: everything but cloud metadata, other trees and the
+ daemon.
+
+ A runtime that can't protect a Space yet starts it without network and
+ says so (`SpaceInfo.network_note`); it never starts it open unless the
+ preset is `unprotected`.
+"""
+ def __init__(self, *, preset:str = "", localhost_ports:typing.List[int] = _DEFAULT, all_localhost_ports:bool = False, allow:typing.List[str] = _DEFAULT, deny:typing.List[str] = _DEFAULT, custom_base:str = "", widened_by:typing.Optional[str] = _DEFAULT):
+ self.preset = preset
+ if localhost_ports is _DEFAULT:
+ self.localhost_ports = []
+ else:
+ self.localhost_ports = localhost_ports
+ self.all_localhost_ports = all_localhost_ports
+ if allow is _DEFAULT:
+ self.allow = []
+ else:
+ self.allow = allow
+ if deny is _DEFAULT:
+ self.deny = []
+ else:
+ self.deny = deny
+ self.custom_base = custom_base
+ if widened_by is _DEFAULT:
+ self.widened_by = None
+ else:
+ self.widened_by = widened_by
+
+
+
+
+ def __str__(self):
+ return "NetworkSettings(preset={}, localhost_ports={}, all_localhost_ports={}, allow={}, deny={}, custom_base={}, widened_by={})".format(self.preset, self.localhost_ports, self.all_localhost_ports, self.allow, self.deny, self.custom_base, self.widened_by)
+ def __eq__(self, other):
+ if self.preset != other.preset:
+ return False
+ if self.localhost_ports != other.localhost_ports:
+ return False
+ if self.all_localhost_ports != other.all_localhost_ports:
+ return False
+ if self.allow != other.allow:
+ return False
+ if self.deny != other.deny:
+ return False
+ if self.custom_base != other.custom_base:
+ return False
+ if self.widened_by != other.widened_by:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeNetworkSettings(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return NetworkSettings(
+ preset=_UniffiFfiConverterString.read(buf),
+ localhost_ports=_UniffiFfiConverterSequenceUInt16.read(buf),
+ all_localhost_ports=_UniffiFfiConverterBoolean.read(buf),
+ allow=_UniffiFfiConverterSequenceString.read(buf),
+ deny=_UniffiFfiConverterSequenceString.read(buf),
+ custom_base=_UniffiFfiConverterString.read(buf),
+ widened_by=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.preset)
+ _UniffiFfiConverterSequenceUInt16.check_lower(value.localhost_ports)
+ _UniffiFfiConverterBoolean.check_lower(value.all_localhost_ports)
+ _UniffiFfiConverterSequenceString.check_lower(value.allow)
+ _UniffiFfiConverterSequenceString.check_lower(value.deny)
+ _UniffiFfiConverterString.check_lower(value.custom_base)
+ _UniffiFfiConverterOptionalString.check_lower(value.widened_by)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.preset, buf)
+ _UniffiFfiConverterSequenceUInt16.write(value.localhost_ports, buf)
+ _UniffiFfiConverterBoolean.write(value.all_localhost_ports, buf)
+ _UniffiFfiConverterSequenceString.write(value.allow, buf)
+ _UniffiFfiConverterSequenceString.write(value.deny, buf)
+ _UniffiFfiConverterString.write(value.custom_base, buf)
+ _UniffiFfiConverterOptionalString.write(value.widened_by, buf)
+
@dataclass
class NotificationInfo:
"""
@@ -23234,6 +23486,132 @@ class _UniffiFfiConverterTypeServiceEndpoint(_UniffiConverterRustBuffer):
_UniffiFfiConverterString.write(value.url, buf)
_UniffiFfiConverterSequenceTypeHttpHeader.write(value.headers, buf)
+@dataclass
+class SpaceNetworkInfo:
+ """
+ A Space's network as `cua network show` says it ([`Spaces::network`]).
+"""
+ def __init__(self, *, settings:NetworkSettings, summary:str, widenings:typing.List[str], enforcement:str, point:str, note:typing.Optional[str], parent:typing.Optional[str], root:typing.Optional[str], always_blocked:typing.List[str], notice_pending:bool):
+ self.settings = settings
+ self.summary = summary
+ self.widenings = widenings
+ self.enforcement = enforcement
+ self.point = point
+ self.note = note
+ self.parent = parent
+ self.root = root
+ self.always_blocked = always_blocked
+ self.notice_pending = notice_pending
+
+
+
+
+ def __str__(self):
+ return "SpaceNetworkInfo(settings={}, summary={}, widenings={}, enforcement={}, point={}, note={}, parent={}, root={}, always_blocked={}, notice_pending={})".format(self.settings, self.summary, self.widenings, self.enforcement, self.point, self.note, self.parent, self.root, self.always_blocked, self.notice_pending)
+ def __eq__(self, other):
+ if self.settings != other.settings:
+ return False
+ if self.summary != other.summary:
+ return False
+ if self.widenings != other.widenings:
+ return False
+ if self.enforcement != other.enforcement:
+ return False
+ if self.point != other.point:
+ return False
+ if self.note != other.note:
+ return False
+ if self.parent != other.parent:
+ return False
+ if self.root != other.root:
+ return False
+ if self.always_blocked != other.always_blocked:
+ return False
+ if self.notice_pending != other.notice_pending:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeSpaceNetworkInfo(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return SpaceNetworkInfo(
+ settings=_UniffiFfiConverterTypeNetworkSettings.read(buf),
+ summary=_UniffiFfiConverterString.read(buf),
+ widenings=_UniffiFfiConverterSequenceString.read(buf),
+ enforcement=_UniffiFfiConverterString.read(buf),
+ point=_UniffiFfiConverterString.read(buf),
+ note=_UniffiFfiConverterOptionalString.read(buf),
+ parent=_UniffiFfiConverterOptionalString.read(buf),
+ root=_UniffiFfiConverterOptionalString.read(buf),
+ always_blocked=_UniffiFfiConverterSequenceString.read(buf),
+ notice_pending=_UniffiFfiConverterBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterTypeNetworkSettings.check_lower(value.settings)
+ _UniffiFfiConverterString.check_lower(value.summary)
+ _UniffiFfiConverterSequenceString.check_lower(value.widenings)
+ _UniffiFfiConverterString.check_lower(value.enforcement)
+ _UniffiFfiConverterString.check_lower(value.point)
+ _UniffiFfiConverterOptionalString.check_lower(value.note)
+ _UniffiFfiConverterOptionalString.check_lower(value.parent)
+ _UniffiFfiConverterOptionalString.check_lower(value.root)
+ _UniffiFfiConverterSequenceString.check_lower(value.always_blocked)
+ _UniffiFfiConverterBoolean.check_lower(value.notice_pending)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterTypeNetworkSettings.write(value.settings, buf)
+ _UniffiFfiConverterString.write(value.summary, buf)
+ _UniffiFfiConverterSequenceString.write(value.widenings, buf)
+ _UniffiFfiConverterString.write(value.enforcement, buf)
+ _UniffiFfiConverterString.write(value.point, buf)
+ _UniffiFfiConverterOptionalString.write(value.note, buf)
+ _UniffiFfiConverterOptionalString.write(value.parent, buf)
+ _UniffiFfiConverterOptionalString.write(value.root, buf)
+ _UniffiFfiConverterSequenceString.write(value.always_blocked, buf)
+ _UniffiFfiConverterBoolean.write(value.notice_pending, buf)
+
+@dataclass
+class SetNetworkResult:
+ """
+ What [`Spaces::set_network`] did.
+"""
+ def __init__(self, *, applied:str, network:SpaceNetworkInfo):
+ self.applied = applied
+ self.network = network
+
+
+
+
+ def __str__(self):
+ return "SetNetworkResult(applied={}, network={})".format(self.applied, self.network)
+ def __eq__(self, other):
+ if self.applied != other.applied:
+ return False
+ if self.network != other.network:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeSetNetworkResult(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return SetNetworkResult(
+ applied=_UniffiFfiConverterString.read(buf),
+ network=_UniffiFfiConverterTypeSpaceNetworkInfo.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.applied)
+ _UniffiFfiConverterTypeSpaceNetworkInfo.check_lower(value.network)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.applied, buf)
+ _UniffiFfiConverterTypeSpaceNetworkInfo.write(value.network, buf)
+
@dataclass
class SetupStep:
"""
@@ -24172,13 +24550,38 @@ class _UniffiFfiConverterOptionalTypeEgressPolicy(_UniffiConverterRustBuffer):
else:
raise InternalError("Unexpected flag byte for optional type")
+class _UniffiFfiConverterOptionalTypeNetworkSettings(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeNetworkSettings.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeNetworkSettings.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeNetworkSettings.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
@dataclass
class SpaceCreateOptions:
"""
Options for [`Spaces::create`]: the same location / kind / runtime model
as sandboxes.
"""
- def __init__(self, *, image:typing.Optional[str] = _DEFAULT, on:typing.Optional[str] = _DEFAULT, kind:typing.Optional[str] = _DEFAULT, runtime:typing.Optional[str] = _DEFAULT, name:typing.Optional[str] = _DEFAULT, cpus:typing.Optional[int] = _DEFAULT, memory_mb:typing.Optional[int] = _DEFAULT, disk_gb:typing.Optional[int] = _DEFAULT, timeout_ms:typing.Optional[int] = _DEFAULT, wait:typing.Optional[bool] = _DEFAULT, reuse:bool = False, command:typing.Optional[typing.List[str]] = _DEFAULT, env:dict[str, str] = _DEFAULT, services:dict[str, int] = _DEFAULT, spacesd:typing.Optional[bool] = _DEFAULT, gpu:typing.Optional[str] = _DEFAULT, create_id:typing.Optional[str] = _DEFAULT, durable:bool = False, profile:typing.Optional[str] = _DEFAULT, headless:typing.Optional[bool] = _DEFAULT, forkable:typing.Optional[bool] = _DEFAULT, build:typing.Optional[BuildOptions] = _DEFAULT, volumes:typing.List[VolumeMount] = _DEFAULT, network:typing.Optional[str] = _DEFAULT, labels:dict[str, str] = _DEFAULT, egress:typing.Optional[EgressPolicy] = _DEFAULT, instance_type:typing.Optional[str] = _DEFAULT, region:typing.Optional[str] = _DEFAULT):
+ def __init__(self, *, image:typing.Optional[str] = _DEFAULT, on:typing.Optional[str] = _DEFAULT, kind:typing.Optional[str] = _DEFAULT, runtime:typing.Optional[str] = _DEFAULT, name:typing.Optional[str] = _DEFAULT, cpus:typing.Optional[int] = _DEFAULT, memory_mb:typing.Optional[int] = _DEFAULT, disk_gb:typing.Optional[int] = _DEFAULT, timeout_ms:typing.Optional[int] = _DEFAULT, wait:typing.Optional[bool] = _DEFAULT, reuse:bool = False, command:typing.Optional[typing.List[str]] = _DEFAULT, env:dict[str, str] = _DEFAULT, services:dict[str, int] = _DEFAULT, spacesd:typing.Optional[bool] = _DEFAULT, gpu:typing.Optional[str] = _DEFAULT, create_id:typing.Optional[str] = _DEFAULT, durable:bool = False, profile:typing.Optional[str] = _DEFAULT, headless:typing.Optional[bool] = _DEFAULT, forkable:typing.Optional[bool] = _DEFAULT, build:typing.Optional[BuildOptions] = _DEFAULT, volumes:typing.List[VolumeMount] = _DEFAULT, network:typing.Optional[str] = _DEFAULT, labels:dict[str, str] = _DEFAULT, egress:typing.Optional[EgressPolicy] = _DEFAULT, network_settings:typing.Optional[NetworkSettings] = _DEFAULT, parent:typing.Optional[str] = _DEFAULT, widen:typing.Optional[bool] = _DEFAULT, instance_type:typing.Optional[str] = _DEFAULT, region:typing.Optional[str] = _DEFAULT, children:typing.Optional[bool] = _DEFAULT):
if image is _DEFAULT:
self.image = None
else:
@@ -24277,6 +24680,18 @@ class SpaceCreateOptions:
self.egress = None
else:
self.egress = egress
+ if network_settings is _DEFAULT:
+ self.network_settings = None
+ else:
+ self.network_settings = network_settings
+ if parent is _DEFAULT:
+ self.parent = None
+ else:
+ self.parent = parent
+ if widen is _DEFAULT:
+ self.widen = None
+ else:
+ self.widen = widen
if instance_type is _DEFAULT:
self.instance_type = None
else:
@@ -24285,12 +24700,16 @@ class SpaceCreateOptions:
self.region = None
else:
self.region = region
+ if children is _DEFAULT:
+ self.children = None
+ else:
+ self.children = children
def __str__(self):
- return "SpaceCreateOptions(image={}, on={}, kind={}, runtime={}, name={}, cpus={}, memory_mb={}, disk_gb={}, timeout_ms={}, wait={}, reuse={}, command={}, env={}, services={}, spacesd={}, gpu={}, create_id={}, durable={}, profile={}, headless={}, forkable={}, build={}, volumes={}, network={}, labels={}, egress={}, instance_type={}, region={})".format(self.image, self.on, self.kind, self.runtime, self.name, self.cpus, self.memory_mb, self.disk_gb, self.timeout_ms, self.wait, self.reuse, self.command, self.env, self.services, self.spacesd, self.gpu, self.create_id, self.durable, self.profile, self.headless, self.forkable, self.build, self.volumes, self.network, self.labels, self.egress, self.instance_type, self.region)
+ return "SpaceCreateOptions(image={}, on={}, kind={}, runtime={}, name={}, cpus={}, memory_mb={}, disk_gb={}, timeout_ms={}, wait={}, reuse={}, command={}, env={}, services={}, spacesd={}, gpu={}, create_id={}, durable={}, profile={}, headless={}, forkable={}, build={}, volumes={}, network={}, labels={}, egress={}, network_settings={}, parent={}, widen={}, instance_type={}, region={}, children={})".format(self.image, self.on, self.kind, self.runtime, self.name, self.cpus, self.memory_mb, self.disk_gb, self.timeout_ms, self.wait, self.reuse, self.command, self.env, self.services, self.spacesd, self.gpu, self.create_id, self.durable, self.profile, self.headless, self.forkable, self.build, self.volumes, self.network, self.labels, self.egress, self.network_settings, self.parent, self.widen, self.instance_type, self.region, self.children)
def __eq__(self, other):
if self.image != other.image:
return False
@@ -24344,10 +24763,18 @@ class SpaceCreateOptions:
return False
if self.egress != other.egress:
return False
+ if self.network_settings != other.network_settings:
+ return False
+ if self.parent != other.parent:
+ return False
+ if self.widen != other.widen:
+ return False
if self.instance_type != other.instance_type:
return False
if self.region != other.region:
return False
+ if self.children != other.children:
+ return False
return True
class _UniffiFfiConverterTypeSpaceCreateOptions(_UniffiConverterRustBuffer):
@@ -24380,8 +24807,12 @@ class _UniffiFfiConverterTypeSpaceCreateOptions(_UniffiConverterRustBuffer):
network=_UniffiFfiConverterOptionalString.read(buf),
labels=_UniffiFfiConverterMapStringString.read(buf),
egress=_UniffiFfiConverterOptionalTypeEgressPolicy.read(buf),
+ network_settings=_UniffiFfiConverterOptionalTypeNetworkSettings.read(buf),
+ parent=_UniffiFfiConverterOptionalString.read(buf),
+ widen=_UniffiFfiConverterOptionalBoolean.read(buf),
instance_type=_UniffiFfiConverterOptionalString.read(buf),
region=_UniffiFfiConverterOptionalString.read(buf),
+ children=_UniffiFfiConverterOptionalBoolean.read(buf),
)
@staticmethod
@@ -24412,8 +24843,12 @@ class _UniffiFfiConverterTypeSpaceCreateOptions(_UniffiConverterRustBuffer):
_UniffiFfiConverterOptionalString.check_lower(value.network)
_UniffiFfiConverterMapStringString.check_lower(value.labels)
_UniffiFfiConverterOptionalTypeEgressPolicy.check_lower(value.egress)
+ _UniffiFfiConverterOptionalTypeNetworkSettings.check_lower(value.network_settings)
+ _UniffiFfiConverterOptionalString.check_lower(value.parent)
+ _UniffiFfiConverterOptionalBoolean.check_lower(value.widen)
_UniffiFfiConverterOptionalString.check_lower(value.instance_type)
_UniffiFfiConverterOptionalString.check_lower(value.region)
+ _UniffiFfiConverterOptionalBoolean.check_lower(value.children)
@staticmethod
def write(value, buf):
@@ -24443,8 +24878,12 @@ class _UniffiFfiConverterTypeSpaceCreateOptions(_UniffiConverterRustBuffer):
_UniffiFfiConverterOptionalString.write(value.network, buf)
_UniffiFfiConverterMapStringString.write(value.labels, buf)
_UniffiFfiConverterOptionalTypeEgressPolicy.write(value.egress, buf)
+ _UniffiFfiConverterOptionalTypeNetworkSettings.write(value.network_settings, buf)
+ _UniffiFfiConverterOptionalString.write(value.parent, buf)
+ _UniffiFfiConverterOptionalBoolean.write(value.widen, buf)
_UniffiFfiConverterOptionalString.write(value.instance_type, buf)
_UniffiFfiConverterOptionalString.write(value.region, buf)
+ _UniffiFfiConverterOptionalBoolean.write(value.children, buf)
@dataclass
class SpaceCreateProgress:
@@ -24777,7 +25216,7 @@ class SpaceInfo:
"""
A registered Space.
"""
- def __init__(self, *, id:str, name:str, display_name:str = "", provider:str, spacesd_version:str, features:typing.List[str], os:str, os_name:str, os_pretty_name:str, image:str, image_digest:str, kind:str, arch:str, services:typing.List[str], added_at:typing.Optional[str], host:str, host_name:str, power:str, power_state:str, cloud:str, cloud_place:str, cloud_delete:str, durable:str = "", stop_reason:str = "", labels:dict[str, str], expires_at_unix:int, on_expire:str, created_at_unix:int, egress:EgressPolicy, egress_enforced:typing.Optional[EgressEnforcement], volumes:typing.List[VolumeMount], sharing:typing.Optional[SpaceSharing] = None):
+ def __init__(self, *, id:str, name:str, display_name:str = "", provider:str, spacesd_version:str, features:typing.List[str], os:str, os_name:str, os_pretty_name:str, image:str, image_digest:str, kind:str, arch:str, services:typing.List[str], added_at:typing.Optional[str], host:str, host_name:str, power:str, power_state:str, cloud:str, cloud_place:str, cloud_delete:str, durable:str = "", stop_reason:str = "", labels:dict[str, str], expires_at_unix:int, on_expire:str, created_at_unix:int, egress:EgressPolicy, egress_enforced:typing.Optional[EgressEnforcement], network:typing.Optional[NetworkSettings], network_note:typing.Optional[str], network_notice_pending:bool, parent:typing.Optional[str], root:typing.Optional[str], depth:int, volumes:typing.List[VolumeMount], sharing:typing.Optional[SpaceSharing] = None):
self.id = id
self.name = name
self.display_name = display_name
@@ -24808,6 +25247,12 @@ class SpaceInfo:
self.created_at_unix = created_at_unix
self.egress = egress
self.egress_enforced = egress_enforced
+ self.network = network
+ self.network_note = network_note
+ self.network_notice_pending = network_notice_pending
+ self.parent = parent
+ self.root = root
+ self.depth = depth
self.volumes = volumes
self.sharing = sharing
@@ -24815,7 +25260,7 @@ class SpaceInfo:
def __str__(self):
- return "SpaceInfo(id={}, name={}, display_name={}, provider={}, spacesd_version={}, features={}, os={}, os_name={}, os_pretty_name={}, image={}, image_digest={}, kind={}, arch={}, services={}, added_at={}, host={}, host_name={}, power={}, power_state={}, cloud={}, cloud_place={}, cloud_delete={}, durable={}, stop_reason={}, labels={}, expires_at_unix={}, on_expire={}, created_at_unix={}, egress={}, egress_enforced={}, volumes={}, sharing={})".format(self.id, self.name, self.display_name, self.provider, self.spacesd_version, self.features, self.os, self.os_name, self.os_pretty_name, self.image, self.image_digest, self.kind, self.arch, self.services, self.added_at, self.host, self.host_name, self.power, self.power_state, self.cloud, self.cloud_place, self.cloud_delete, self.durable, self.stop_reason, self.labels, self.expires_at_unix, self.on_expire, self.created_at_unix, self.egress, self.egress_enforced, self.volumes, self.sharing)
+ return "SpaceInfo(id={}, name={}, display_name={}, provider={}, spacesd_version={}, features={}, os={}, os_name={}, os_pretty_name={}, image={}, image_digest={}, kind={}, arch={}, services={}, added_at={}, host={}, host_name={}, power={}, power_state={}, cloud={}, cloud_place={}, cloud_delete={}, durable={}, stop_reason={}, labels={}, expires_at_unix={}, on_expire={}, created_at_unix={}, egress={}, egress_enforced={}, network={}, network_note={}, network_notice_pending={}, parent={}, root={}, depth={}, volumes={}, sharing={})".format(self.id, self.name, self.display_name, self.provider, self.spacesd_version, self.features, self.os, self.os_name, self.os_pretty_name, self.image, self.image_digest, self.kind, self.arch, self.services, self.added_at, self.host, self.host_name, self.power, self.power_state, self.cloud, self.cloud_place, self.cloud_delete, self.durable, self.stop_reason, self.labels, self.expires_at_unix, self.on_expire, self.created_at_unix, self.egress, self.egress_enforced, self.network, self.network_note, self.network_notice_pending, self.parent, self.root, self.depth, self.volumes, self.sharing)
def __eq__(self, other):
if self.id != other.id:
return False
@@ -24877,6 +25322,18 @@ class SpaceInfo:
return False
if self.egress_enforced != other.egress_enforced:
return False
+ if self.network != other.network:
+ return False
+ if self.network_note != other.network_note:
+ return False
+ if self.network_notice_pending != other.network_notice_pending:
+ return False
+ if self.parent != other.parent:
+ return False
+ if self.root != other.root:
+ return False
+ if self.depth != other.depth:
+ return False
if self.volumes != other.volumes:
return False
if self.sharing != other.sharing:
@@ -24917,6 +25374,12 @@ class _UniffiFfiConverterTypeSpaceInfo(_UniffiConverterRustBuffer):
created_at_unix=_UniffiFfiConverterInt64.read(buf),
egress=_UniffiFfiConverterTypeEgressPolicy.read(buf),
egress_enforced=_UniffiFfiConverterOptionalTypeEgressEnforcement.read(buf),
+ network=_UniffiFfiConverterOptionalTypeNetworkSettings.read(buf),
+ network_note=_UniffiFfiConverterOptionalString.read(buf),
+ network_notice_pending=_UniffiFfiConverterBoolean.read(buf),
+ parent=_UniffiFfiConverterOptionalString.read(buf),
+ root=_UniffiFfiConverterOptionalString.read(buf),
+ depth=_UniffiFfiConverterUInt32.read(buf),
volumes=_UniffiFfiConverterSequenceTypeVolumeMount.read(buf),
sharing=_UniffiFfiConverterOptionalTypeSpaceSharing.read(buf),
)
@@ -24953,6 +25416,12 @@ class _UniffiFfiConverterTypeSpaceInfo(_UniffiConverterRustBuffer):
_UniffiFfiConverterInt64.check_lower(value.created_at_unix)
_UniffiFfiConverterTypeEgressPolicy.check_lower(value.egress)
_UniffiFfiConverterOptionalTypeEgressEnforcement.check_lower(value.egress_enforced)
+ _UniffiFfiConverterOptionalTypeNetworkSettings.check_lower(value.network)
+ _UniffiFfiConverterOptionalString.check_lower(value.network_note)
+ _UniffiFfiConverterBoolean.check_lower(value.network_notice_pending)
+ _UniffiFfiConverterOptionalString.check_lower(value.parent)
+ _UniffiFfiConverterOptionalString.check_lower(value.root)
+ _UniffiFfiConverterUInt32.check_lower(value.depth)
_UniffiFfiConverterSequenceTypeVolumeMount.check_lower(value.volumes)
_UniffiFfiConverterOptionalTypeSpaceSharing.check_lower(value.sharing)
@@ -24988,6 +25457,12 @@ class _UniffiFfiConverterTypeSpaceInfo(_UniffiConverterRustBuffer):
_UniffiFfiConverterInt64.write(value.created_at_unix, buf)
_UniffiFfiConverterTypeEgressPolicy.write(value.egress, buf)
_UniffiFfiConverterOptionalTypeEgressEnforcement.write(value.egress_enforced, buf)
+ _UniffiFfiConverterOptionalTypeNetworkSettings.write(value.network, buf)
+ _UniffiFfiConverterOptionalString.write(value.network_note, buf)
+ _UniffiFfiConverterBoolean.write(value.network_notice_pending, buf)
+ _UniffiFfiConverterOptionalString.write(value.parent, buf)
+ _UniffiFfiConverterOptionalString.write(value.root, buf)
+ _UniffiFfiConverterUInt32.write(value.depth, buf)
_UniffiFfiConverterSequenceTypeVolumeMount.write(value.volumes, buf)
_UniffiFfiConverterOptionalTypeSpaceSharing.write(value.sharing, buf)
@@ -25377,6 +25852,63 @@ class _UniffiFfiConverterTypeSpaceList(_UniffiConverterRustBuffer):
_UniffiFfiConverterString.write(value.notice, buf)
_UniffiFfiConverterSequenceTypeSpaceCreatingElsewhere.write(value.creating, buf)
+@dataclass
+class SpaceOrphan:
+ """
+ A child Space whose parent is gone or out of reach ([`Spaces::orphans`]).
+"""
+ def __init__(self, *, space:str, parent:str, state:str, why:str, ends_in_secs:int):
+ self.space = space
+ self.parent = parent
+ self.state = state
+ self.why = why
+ self.ends_in_secs = ends_in_secs
+
+
+
+
+ def __str__(self):
+ return "SpaceOrphan(space={}, parent={}, state={}, why={}, ends_in_secs={})".format(self.space, self.parent, self.state, self.why, self.ends_in_secs)
+ def __eq__(self, other):
+ if self.space != other.space:
+ return False
+ if self.parent != other.parent:
+ return False
+ if self.state != other.state:
+ return False
+ if self.why != other.why:
+ return False
+ if self.ends_in_secs != other.ends_in_secs:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeSpaceOrphan(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return SpaceOrphan(
+ space=_UniffiFfiConverterString.read(buf),
+ parent=_UniffiFfiConverterString.read(buf),
+ state=_UniffiFfiConverterString.read(buf),
+ why=_UniffiFfiConverterString.read(buf),
+ ends_in_secs=_UniffiFfiConverterInt64.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.space)
+ _UniffiFfiConverterString.check_lower(value.parent)
+ _UniffiFfiConverterString.check_lower(value.state)
+ _UniffiFfiConverterString.check_lower(value.why)
+ _UniffiFfiConverterInt64.check_lower(value.ends_in_secs)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.space, buf)
+ _UniffiFfiConverterString.write(value.parent, buf)
+ _UniffiFfiConverterString.write(value.state, buf)
+ _UniffiFfiConverterString.write(value.why, buf)
+ _UniffiFfiConverterInt64.write(value.ends_in_secs, buf)
+
@dataclass
class SpacePowerReport:
"""
@@ -25742,6 +26274,274 @@ class _UniffiFfiConverterTypeSpaceSendFileReport(_UniffiConverterRustBuffer):
_UniffiFfiConverterSequenceString.write(value.skipped_by_guest, buf)
_UniffiFfiConverterBoolean.write(value.verified, buf)
+@dataclass
+class SpaceServiceProbe:
+ """
+ A health check: exactly one of `http`, `tcp`, `command`.
+"""
+ def __init__(self, *, http:typing.Optional[str] = _DEFAULT, tcp:typing.Optional[str] = _DEFAULT, command:typing.Optional[str] = _DEFAULT, interval_secs:typing.Optional[int] = _DEFAULT, failures:typing.Optional[int] = _DEFAULT):
+ if http is _DEFAULT:
+ self.http = None
+ else:
+ self.http = http
+ if tcp is _DEFAULT:
+ self.tcp = None
+ else:
+ self.tcp = tcp
+ if command is _DEFAULT:
+ self.command = None
+ else:
+ self.command = command
+ if interval_secs is _DEFAULT:
+ self.interval_secs = None
+ else:
+ self.interval_secs = interval_secs
+ if failures is _DEFAULT:
+ self.failures = None
+ else:
+ self.failures = failures
+
+
+
+
+ def __str__(self):
+ return "SpaceServiceProbe(http={}, tcp={}, command={}, interval_secs={}, failures={})".format(self.http, self.tcp, self.command, self.interval_secs, self.failures)
+ def __eq__(self, other):
+ if self.http != other.http:
+ return False
+ if self.tcp != other.tcp:
+ return False
+ if self.command != other.command:
+ return False
+ if self.interval_secs != other.interval_secs:
+ return False
+ if self.failures != other.failures:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeSpaceServiceProbe(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return SpaceServiceProbe(
+ http=_UniffiFfiConverterOptionalString.read(buf),
+ tcp=_UniffiFfiConverterOptionalString.read(buf),
+ command=_UniffiFfiConverterOptionalString.read(buf),
+ interval_secs=_UniffiFfiConverterOptionalUInt64.read(buf),
+ failures=_UniffiFfiConverterOptionalUInt32.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalString.check_lower(value.http)
+ _UniffiFfiConverterOptionalString.check_lower(value.tcp)
+ _UniffiFfiConverterOptionalString.check_lower(value.command)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.interval_secs)
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.failures)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalString.write(value.http, buf)
+ _UniffiFfiConverterOptionalString.write(value.tcp, buf)
+ _UniffiFfiConverterOptionalString.write(value.command, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.interval_secs, buf)
+ _UniffiFfiConverterOptionalUInt32.write(value.failures, buf)
+
+class _UniffiFfiConverterOptionalTypeSpaceServiceProbe(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeSpaceServiceProbe.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeSpaceServiceProbe.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeSpaceServiceProbe.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class SpaceServiceDef:
+ """
+ A command a Space keeps running ([`Space::put_service`]).
+"""
+ def __init__(self, *, name:str, command:str, env:dict[str, str] = _DEFAULT, cwd:typing.Optional[str] = _DEFAULT, restart:typing.Optional[str] = _DEFAULT, probe:typing.Optional[SpaceServiceProbe] = _DEFAULT, start_on_boot:typing.Optional[bool] = _DEFAULT):
+ self.name = name
+ self.command = command
+ if env is _DEFAULT:
+ self.env = {}
+ else:
+ self.env = env
+ if cwd is _DEFAULT:
+ self.cwd = None
+ else:
+ self.cwd = cwd
+ if restart is _DEFAULT:
+ self.restart = None
+ else:
+ self.restart = restart
+ if probe is _DEFAULT:
+ self.probe = None
+ else:
+ self.probe = probe
+ if start_on_boot is _DEFAULT:
+ self.start_on_boot = None
+ else:
+ self.start_on_boot = start_on_boot
+
+
+
+
+ def __str__(self):
+ return "SpaceServiceDef(name={}, command={}, env={}, cwd={}, restart={}, probe={}, start_on_boot={})".format(self.name, self.command, self.env, self.cwd, self.restart, self.probe, self.start_on_boot)
+ def __eq__(self, other):
+ if self.name != other.name:
+ return False
+ if self.command != other.command:
+ return False
+ if self.env != other.env:
+ return False
+ if self.cwd != other.cwd:
+ return False
+ if self.restart != other.restart:
+ return False
+ if self.probe != other.probe:
+ return False
+ if self.start_on_boot != other.start_on_boot:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeSpaceServiceDef(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return SpaceServiceDef(
+ name=_UniffiFfiConverterString.read(buf),
+ command=_UniffiFfiConverterString.read(buf),
+ env=_UniffiFfiConverterMapStringString.read(buf),
+ cwd=_UniffiFfiConverterOptionalString.read(buf),
+ restart=_UniffiFfiConverterOptionalString.read(buf),
+ probe=_UniffiFfiConverterOptionalTypeSpaceServiceProbe.read(buf),
+ start_on_boot=_UniffiFfiConverterOptionalBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterString.check_lower(value.command)
+ _UniffiFfiConverterMapStringString.check_lower(value.env)
+ _UniffiFfiConverterOptionalString.check_lower(value.cwd)
+ _UniffiFfiConverterOptionalString.check_lower(value.restart)
+ _UniffiFfiConverterOptionalTypeSpaceServiceProbe.check_lower(value.probe)
+ _UniffiFfiConverterOptionalBoolean.check_lower(value.start_on_boot)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterString.write(value.command, buf)
+ _UniffiFfiConverterMapStringString.write(value.env, buf)
+ _UniffiFfiConverterOptionalString.write(value.cwd, buf)
+ _UniffiFfiConverterOptionalString.write(value.restart, buf)
+ _UniffiFfiConverterOptionalTypeSpaceServiceProbe.write(value.probe, buf)
+ _UniffiFfiConverterOptionalBoolean.write(value.start_on_boot, buf)
+
+@dataclass
+class SpaceServiceInfo:
+ """
+ A service and how it is doing ([`Space::services`]).
+"""
+ def __init__(self, *, name:str, command:str, state:str, pid:int, restarts:int, last_end:str, probe_error:str, restart:str, start_on_boot:bool, log_path:str):
+ self.name = name
+ self.command = command
+ self.state = state
+ self.pid = pid
+ self.restarts = restarts
+ self.last_end = last_end
+ self.probe_error = probe_error
+ self.restart = restart
+ self.start_on_boot = start_on_boot
+ self.log_path = log_path
+
+
+
+
+ def __str__(self):
+ return "SpaceServiceInfo(name={}, command={}, state={}, pid={}, restarts={}, last_end={}, probe_error={}, restart={}, start_on_boot={}, log_path={})".format(self.name, self.command, self.state, self.pid, self.restarts, self.last_end, self.probe_error, self.restart, self.start_on_boot, self.log_path)
+ def __eq__(self, other):
+ if self.name != other.name:
+ return False
+ if self.command != other.command:
+ return False
+ if self.state != other.state:
+ return False
+ if self.pid != other.pid:
+ return False
+ if self.restarts != other.restarts:
+ return False
+ if self.last_end != other.last_end:
+ return False
+ if self.probe_error != other.probe_error:
+ return False
+ if self.restart != other.restart:
+ return False
+ if self.start_on_boot != other.start_on_boot:
+ return False
+ if self.log_path != other.log_path:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeSpaceServiceInfo(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return SpaceServiceInfo(
+ name=_UniffiFfiConverterString.read(buf),
+ command=_UniffiFfiConverterString.read(buf),
+ state=_UniffiFfiConverterString.read(buf),
+ pid=_UniffiFfiConverterUInt32.read(buf),
+ restarts=_UniffiFfiConverterUInt32.read(buf),
+ last_end=_UniffiFfiConverterString.read(buf),
+ probe_error=_UniffiFfiConverterString.read(buf),
+ restart=_UniffiFfiConverterString.read(buf),
+ start_on_boot=_UniffiFfiConverterBoolean.read(buf),
+ log_path=_UniffiFfiConverterString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterString.check_lower(value.command)
+ _UniffiFfiConverterString.check_lower(value.state)
+ _UniffiFfiConverterUInt32.check_lower(value.pid)
+ _UniffiFfiConverterUInt32.check_lower(value.restarts)
+ _UniffiFfiConverterString.check_lower(value.last_end)
+ _UniffiFfiConverterString.check_lower(value.probe_error)
+ _UniffiFfiConverterString.check_lower(value.restart)
+ _UniffiFfiConverterBoolean.check_lower(value.start_on_boot)
+ _UniffiFfiConverterString.check_lower(value.log_path)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterString.write(value.command, buf)
+ _UniffiFfiConverterString.write(value.state, buf)
+ _UniffiFfiConverterUInt32.write(value.pid, buf)
+ _UniffiFfiConverterUInt32.write(value.restarts, buf)
+ _UniffiFfiConverterString.write(value.last_end, buf)
+ _UniffiFfiConverterString.write(value.probe_error, buf)
+ _UniffiFfiConverterString.write(value.restart, buf)
+ _UniffiFfiConverterBoolean.write(value.start_on_boot, buf)
+ _UniffiFfiConverterString.write(value.log_path, buf)
+
@dataclass
class SpaceShareEntry:
"""
@@ -28068,6 +28868,178 @@ class _UniffiFfiConverterTypeTransferResult(_UniffiConverterRustBuffer):
_UniffiFfiConverterString.write(value.sha256, buf)
_UniffiFfiConverterUInt32.write(value.resumes, buf)
+@dataclass
+class TreeBudgetLimits:
+ """
+ What a tree's children may hold and cost ([`Spaces::set_tree_budget`]).
+ `None`: the default.
+"""
+ def __init__(self, *, max_spaces:typing.Optional[int] = _DEFAULT, max_vcpus:typing.Optional[int] = _DEFAULT, max_memory_mb:typing.Optional[int] = _DEFAULT, usd_per_hour:typing.Optional[float] = _DEFAULT, usd_total:typing.Optional[float] = _DEFAULT):
+ if max_spaces is _DEFAULT:
+ self.max_spaces = None
+ else:
+ self.max_spaces = max_spaces
+ if max_vcpus is _DEFAULT:
+ self.max_vcpus = None
+ else:
+ self.max_vcpus = max_vcpus
+ if max_memory_mb is _DEFAULT:
+ self.max_memory_mb = None
+ else:
+ self.max_memory_mb = max_memory_mb
+ if usd_per_hour is _DEFAULT:
+ self.usd_per_hour = None
+ else:
+ self.usd_per_hour = usd_per_hour
+ if usd_total is _DEFAULT:
+ self.usd_total = None
+ else:
+ self.usd_total = usd_total
+
+
+
+
+ def __str__(self):
+ return "TreeBudgetLimits(max_spaces={}, max_vcpus={}, max_memory_mb={}, usd_per_hour={}, usd_total={})".format(self.max_spaces, self.max_vcpus, self.max_memory_mb, self.usd_per_hour, self.usd_total)
+ def __eq__(self, other):
+ if self.max_spaces != other.max_spaces:
+ return False
+ if self.max_vcpus != other.max_vcpus:
+ return False
+ if self.max_memory_mb != other.max_memory_mb:
+ return False
+ if self.usd_per_hour != other.usd_per_hour:
+ return False
+ if self.usd_total != other.usd_total:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeTreeBudgetLimits(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return TreeBudgetLimits(
+ max_spaces=_UniffiFfiConverterOptionalUInt32.read(buf),
+ max_vcpus=_UniffiFfiConverterOptionalUInt32.read(buf),
+ max_memory_mb=_UniffiFfiConverterOptionalUInt64.read(buf),
+ usd_per_hour=_UniffiFfiConverterOptionalFloat64.read(buf),
+ usd_total=_UniffiFfiConverterOptionalFloat64.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.max_spaces)
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.max_vcpus)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.max_memory_mb)
+ _UniffiFfiConverterOptionalFloat64.check_lower(value.usd_per_hour)
+ _UniffiFfiConverterOptionalFloat64.check_lower(value.usd_total)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalUInt32.write(value.max_spaces, buf)
+ _UniffiFfiConverterOptionalUInt32.write(value.max_vcpus, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.max_memory_mb, buf)
+ _UniffiFfiConverterOptionalFloat64.write(value.usd_per_hour, buf)
+ _UniffiFfiConverterOptionalFloat64.write(value.usd_total, buf)
+
+@dataclass
+class TreeBudget:
+ """
+ A tree's budget and what its children use ([`Spaces::tree_budget`]).
+"""
+ def __init__(self, *, root:str, set:TreeBudgetLimits, max_spaces:int, max_vcpus:int, max_memory_mb:int, usd_per_hour:float, usd_total:typing.Optional[float], spaces:int, vcpus:int, memory_mb:int, usd_per_hour_used:float, usd_spent:float):
+ self.root = root
+ self.set = set
+ self.max_spaces = max_spaces
+ self.max_vcpus = max_vcpus
+ self.max_memory_mb = max_memory_mb
+ self.usd_per_hour = usd_per_hour
+ self.usd_total = usd_total
+ self.spaces = spaces
+ self.vcpus = vcpus
+ self.memory_mb = memory_mb
+ self.usd_per_hour_used = usd_per_hour_used
+ self.usd_spent = usd_spent
+
+
+
+
+ def __str__(self):
+ return "TreeBudget(root={}, set={}, max_spaces={}, max_vcpus={}, max_memory_mb={}, usd_per_hour={}, usd_total={}, spaces={}, vcpus={}, memory_mb={}, usd_per_hour_used={}, usd_spent={})".format(self.root, self.set, self.max_spaces, self.max_vcpus, self.max_memory_mb, self.usd_per_hour, self.usd_total, self.spaces, self.vcpus, self.memory_mb, self.usd_per_hour_used, self.usd_spent)
+ def __eq__(self, other):
+ if self.root != other.root:
+ return False
+ if self.set != other.set:
+ return False
+ if self.max_spaces != other.max_spaces:
+ return False
+ if self.max_vcpus != other.max_vcpus:
+ return False
+ if self.max_memory_mb != other.max_memory_mb:
+ return False
+ if self.usd_per_hour != other.usd_per_hour:
+ return False
+ if self.usd_total != other.usd_total:
+ return False
+ if self.spaces != other.spaces:
+ return False
+ if self.vcpus != other.vcpus:
+ return False
+ if self.memory_mb != other.memory_mb:
+ return False
+ if self.usd_per_hour_used != other.usd_per_hour_used:
+ return False
+ if self.usd_spent != other.usd_spent:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeTreeBudget(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return TreeBudget(
+ root=_UniffiFfiConverterString.read(buf),
+ set=_UniffiFfiConverterTypeTreeBudgetLimits.read(buf),
+ max_spaces=_UniffiFfiConverterUInt32.read(buf),
+ max_vcpus=_UniffiFfiConverterUInt32.read(buf),
+ max_memory_mb=_UniffiFfiConverterUInt64.read(buf),
+ usd_per_hour=_UniffiFfiConverterFloat64.read(buf),
+ usd_total=_UniffiFfiConverterOptionalFloat64.read(buf),
+ spaces=_UniffiFfiConverterUInt32.read(buf),
+ vcpus=_UniffiFfiConverterUInt32.read(buf),
+ memory_mb=_UniffiFfiConverterUInt64.read(buf),
+ usd_per_hour_used=_UniffiFfiConverterFloat64.read(buf),
+ usd_spent=_UniffiFfiConverterFloat64.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.root)
+ _UniffiFfiConverterTypeTreeBudgetLimits.check_lower(value.set)
+ _UniffiFfiConverterUInt32.check_lower(value.max_spaces)
+ _UniffiFfiConverterUInt32.check_lower(value.max_vcpus)
+ _UniffiFfiConverterUInt64.check_lower(value.max_memory_mb)
+ _UniffiFfiConverterFloat64.check_lower(value.usd_per_hour)
+ _UniffiFfiConverterOptionalFloat64.check_lower(value.usd_total)
+ _UniffiFfiConverterUInt32.check_lower(value.spaces)
+ _UniffiFfiConverterUInt32.check_lower(value.vcpus)
+ _UniffiFfiConverterUInt64.check_lower(value.memory_mb)
+ _UniffiFfiConverterFloat64.check_lower(value.usd_per_hour_used)
+ _UniffiFfiConverterFloat64.check_lower(value.usd_spent)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.root, buf)
+ _UniffiFfiConverterTypeTreeBudgetLimits.write(value.set, buf)
+ _UniffiFfiConverterUInt32.write(value.max_spaces, buf)
+ _UniffiFfiConverterUInt32.write(value.max_vcpus, buf)
+ _UniffiFfiConverterUInt64.write(value.max_memory_mb, buf)
+ _UniffiFfiConverterFloat64.write(value.usd_per_hour, buf)
+ _UniffiFfiConverterOptionalFloat64.write(value.usd_total, buf)
+ _UniffiFfiConverterUInt32.write(value.spaces, buf)
+ _UniffiFfiConverterUInt32.write(value.vcpus, buf)
+ _UniffiFfiConverterUInt64.write(value.memory_mb, buf)
+ _UniffiFfiConverterFloat64.write(value.usd_per_hour_used, buf)
+ _UniffiFfiConverterFloat64.write(value.usd_spent, buf)
+
class _UniffiFfiConverterOptionalMapStringString(_UniffiConverterRustBuffer):
@classmethod
def check_lower(cls, value):
@@ -39339,6 +40311,29 @@ class _UniffiFfiConverterTypeSpacePresence:
def write(cls, value: SpacePresence, buf: _UniffiRustBuffer):
buf.write_u64(cls.lower(value))
+class _UniffiFfiConverterSequenceTypeSpaceServiceInfo(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeSpaceServiceInfo.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeSpaceServiceInfo.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeSpaceServiceInfo.read(buf) for i in range(count)
+ ]
+
class _UniffiFfiConverterSequenceTypeSpaceToolInfo(_UniffiConverterRustBuffer):
@classmethod
def check_lower(cls, value):
@@ -39906,6 +40901,11 @@ class SpaceProtocol(typing.Protocol):
async def close_stream(self, media_session_id: str) -> None:
"""
Closes a media session opened with [`Space::open_stream`].
+"""
+ raise NotImplementedError
+ async def delete_service(self, name: str) -> None:
+ """
+ Stops a service and forgets it (its logs go too).
"""
raise NotImplementedError
async def displays(self, ) -> typing.List[SpaceDisplay]:
@@ -39969,6 +40969,11 @@ class SpaceProtocol(typing.Protocol):
"""
Joins presence. Waits up to `timeout_ms` (default 10 s) for the
roster.
+"""
+ raise NotImplementedError
+ async def kept_services(self, ) -> typing.List[SpaceServiceInfo]:
+ """
+ This Space's services.
"""
raise NotImplementedError
async def list_tools(self, service: typing.Optional[str]) -> typing.List[SpaceToolInfo]:
@@ -39980,6 +40985,13 @@ class SpaceProtocol(typing.Protocol):
"""
Mints a media session (ticket + WebSocket URL) for another client
to attach to.
+"""
+ raise NotImplementedError
+ async def put_service(self, _def: SpaceServiceDef) -> SpaceServiceInfo:
+ """
+ Keeps a command running in this Space (replacing a service of that
+ name): restarted by its policy when it ends or fails its health
+ check, started when the Space boots, its output kept in a log file.
"""
raise NotImplementedError
async def request_site_login(self, url: str,options: typing.Optional[SiteLoginOptions]) -> SiteLoginReport:
@@ -39990,6 +41002,11 @@ class SpaceProtocol(typing.Protocol):
Cua, then call again with that `request_id` and the Keyvault types
the login through the Space's cua-driver (`status == "filled"`). A
declined request is an error. The password never reaches the caller.
+"""
+ raise NotImplementedError
+ async def restart_service(self, name: str) -> SpaceServiceInfo:
+ """
+ Restarts a service.
"""
raise NotImplementedError
async def route(self, ) -> str:
@@ -40012,6 +41029,11 @@ class SpaceProtocol(typing.Protocol):
"""
Drops a host file or folder into the Space's `~/Downloads[/subdir]`
(TeleportService.ReceiveFiles, per-file SHA-256).
+"""
+ raise NotImplementedError
+ async def service_logs(self, name: str,tail_bytes: typing.Optional[int]) -> str:
+ """
+ The end of a service's log (`tail_bytes` `None`: 64 KiB).
"""
raise NotImplementedError
def services(self, ) -> typing.List[str]:
@@ -40051,11 +41073,21 @@ class SpaceProtocol(typing.Protocol):
Starts the reverse-SOCKS hotspot: this host serves the Space's
egress. `set_system_proxy` points the guest's proxy settings at it
(default false here).
+"""
+ raise NotImplementedError
+ async def start_service(self, name: str) -> SpaceServiceInfo:
+ """
+ Starts a stopped service.
"""
raise NotImplementedError
async def stop_hotspot(self, ) -> typing.List[str]:
"""
Stops this Space's hotspot. Returns the stopped Space ids.
+"""
+ raise NotImplementedError
+ async def stop_service(self, name: str) -> SpaceServiceInfo:
+ """
+ Stops a service and keeps it stopped (also across a reboot).
"""
raise NotImplementedError
async def stream_session(self, options: SpaceStreamOptions,frames: FrameSink,audio: typing.Optional[AudioSink]) -> SpaceStreamSession:
@@ -40554,6 +41586,26 @@ class Space(SpaceProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def delete_service(self, name: str) -> None:
+ """
+ Stops a service and forgets it (its logs go too).
+"""
+
+ _UniffiFfiConverterString.check_lower(name)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(name),
+ )
+ _uniffi_lift_return = lambda val: None
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_space_delete_service(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_void,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_void,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_void,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def displays(self, ) -> typing.List[SpaceDisplay]:
"""
The Space's displays, primary first, with their resolution in
@@ -40744,6 +41796,23 @@ class Space(SpaceProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def kept_services(self, ) -> typing.List[SpaceServiceInfo]:
+ """
+ This Space's services.
+"""
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterSequenceTypeSpaceServiceInfo.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_space_kept_services(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def list_tools(self, service: typing.Optional[str]) -> typing.List[SpaceToolInfo]:
"""
Tools of the Space's MCP service (`driver`, the default).
@@ -40785,6 +41854,28 @@ class Space(SpaceProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def put_service(self, _def: SpaceServiceDef) -> SpaceServiceInfo:
+ """
+ Keeps a command running in this Space (replacing a service of that
+ name): restarted by its policy when it ends or fails its health
+ check, started when the Space boots, its output kept in a log file.
+"""
+
+ _UniffiFfiConverterTypeSpaceServiceDef.check_lower(_def)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeSpaceServiceDef.lower(_def),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeSpaceServiceInfo.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_space_put_service(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def request_site_login(self, url: str,options: typing.Optional[SiteLoginOptions]) -> SiteLoginReport:
"""
Signs in to a site in this Space's browser with a password the user
@@ -40813,6 +41904,26 @@ class Space(SpaceProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def restart_service(self, name: str) -> SpaceServiceInfo:
+ """
+ Restarts a service.
+"""
+
+ _UniffiFfiConverterString.check_lower(name)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(name),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeSpaceServiceInfo.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_space_restart_service(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def route(self, ) -> str:
"""
Which way this Space's calls go now (see [`super::spacesd::SpacesdClient::route`]):
@@ -40880,6 +41991,29 @@ class Space(SpaceProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def service_logs(self, name: str,tail_bytes: typing.Optional[int]) -> str:
+ """
+ The end of a service's log (`tail_bytes` `None`: 64 KiB).
+"""
+
+ _UniffiFfiConverterString.check_lower(name)
+
+ _UniffiFfiConverterOptionalUInt64.check_lower(tail_bytes)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(name),
+ _UniffiFfiConverterOptionalUInt64.lower(tail_bytes),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterString.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_space_service_logs(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
def services(self, ) -> typing.List[str]:
"""
The MCP services this Space exposes: `driver` when its spacesd has
@@ -41004,6 +42138,26 @@ class Space(SpaceProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def start_service(self, name: str) -> SpaceServiceInfo:
+ """
+ Starts a stopped service.
+"""
+
+ _UniffiFfiConverterString.check_lower(name)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(name),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeSpaceServiceInfo.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_space_start_service(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def stop_hotspot(self, ) -> typing.List[str]:
"""
Stops this Space's hotspot. Returns the stopped Space ids.
@@ -41021,6 +42175,26 @@ class Space(SpaceProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def stop_service(self, name: str) -> SpaceServiceInfo:
+ """
+ Stops a service and keeps it stopped (also across a reboot).
+"""
+
+ _UniffiFfiConverterString.check_lower(name)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(name),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeSpaceServiceInfo.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_space_stop_service(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def stream_session(self, options: SpaceStreamOptions,frames: FrameSink,audio: typing.Optional[AudioSink]) -> SpaceStreamSession:
"""
Opens a media session and delivers keyframe-gated encoded frames
@@ -41430,6 +42604,29 @@ class _UniffiFfiConverterSequenceTypeNotificationInfo(_UniffiConverterRustBuffer
_UniffiFfiConverterTypeNotificationInfo.read(buf) for i in range(count)
]
+class _UniffiFfiConverterSequenceTypeSpaceOrphan(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeSpaceOrphan.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeSpaceOrphan.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeSpaceOrphan.read(buf) for i in range(count)
+ ]
+
class _UniffiFfiConverterOptionalTypePersistentAgentOptions(_UniffiConverterRustBuffer):
@classmethod
def check_lower(cls, value):
@@ -42159,6 +43356,12 @@ class SpacesProtocol(typing.Protocol):
[`Space`] handles.
"""
+ async def ack_network_notice(self, space: str) -> None:
+ """
+ Marks the one-time notice about the new network defaults as shown
+ for `space` ([`SpaceNetworkInfo::notice_pending`]).
+"""
+ raise NotImplementedError
async def add(self, url: str,token: typing.Optional[str],name: typing.Optional[str]) -> SpaceInfo:
"""
Adds a Space by URL (`http(s)://host:port`, `host:port`, or a
@@ -42370,7 +43573,8 @@ class SpacesProtocol(typing.Protocol):
async def delete(self, space: str) -> str:
"""
Deletes a Space's sandbox and forgets it (a Space added by address
- is only forgotten). Returns what happened.
+ is only forgotten). Its child Spaces are deleted first. Returns what
+ happened.
"""
raise NotImplementedError
async def delete_build(self, build: str) -> typing.List[str]:
@@ -42386,6 +43590,12 @@ class SpacesProtocol(typing.Protocol):
Deletes several Spaces ([`Spaces::delete`] each), at most three at
a time, turning running ones off first. One result per id, in
order; one failure never stops the rest.
+"""
+ raise NotImplementedError
+ async def delete_tree(self, space: str,keep_children: bool) -> str:
+ """
+ [`Spaces::delete`], with `keep_children`: its child Spaces become
+ top-level Spaces and keep running instead of being deleted first.
"""
raise NotImplementedError
async def delete_volume(self, name: str,force: bool = False) -> int:
@@ -42460,6 +43670,12 @@ class SpacesProtocol(typing.Protocol):
id or name (asked over the relay, the mesh or its direct address);
`None` for this one. Read-only; fails plainly when that machine is
offline, not yours, or runs a Cua that predates the check.
+"""
+ raise NotImplementedError
+ async def network(self, space: str) -> SpaceNetworkInfo:
+ """
+ A Space's network: its settings, what they open, where they are
+ enforced (or why its network is cut), and what is always blocked.
"""
raise NotImplementedError
async def notifications(self, unread_only: bool,since_ms: typing.Optional[int]) -> typing.List[NotificationInfo]:
@@ -42475,6 +43691,13 @@ class SpacesProtocol(typing.Protocol):
async def notify_user(self, title: str,body: typing.Optional[str],agent: typing.Optional[str]) -> str:
"""
Posts a notification to the Cua app. Returns its id.
+"""
+ raise NotImplementedError
+ async def orphans(self, ) -> typing.List[SpaceOrphan]:
+ """
+ Child Spaces whose parent is gone or out of reach. The cua daemon
+ ends a child only on proof its parent is gone (after a grace period);
+ the rest are listed here and never ended by it.
"""
raise NotImplementedError
async def persistent_agent_create(self, name: str,harness: str,space: str,options: typing.Optional[PersistentAgentOptions]) -> PersistentAgentInfo:
@@ -42600,6 +43823,17 @@ class SpacesProtocol(typing.Protocol):
async def routines(self, agent: typing.Optional[str]) -> typing.List[RoutineInfo]:
"""
Routines (of one agent, or all).
+"""
+ raise NotImplementedError
+ async def set_children(self, space: str,enabled: bool) -> None:
+ """
+ Lets a Space make child Spaces of its own, or stops it. While on,
+ `cua`, the SDKs and the agent's tools in that Space create, list and
+ delete Spaces that belong to it (on the same computer, never wider
+ than it, ending no later than it), through a channel only it can
+ reach. Off ends its capability at once; children it made keep running
+ until deleted or their lifetime ends. Only for a Space the machine of
+ this runtime runs itself.
"""
raise NotImplementedError
async def set_egress(self, space: str,policy: EgressPolicy) -> None:
@@ -42617,6 +43851,22 @@ class SpacesProtocol(typing.Protocol):
not this process is still running. Works for a Space on this machine
or one of your machines. Returns when it ends (Unix seconds).
Embedded: recorded; the cua daemon on this machine enforces it.
+"""
+ raise NotImplementedError
+ async def set_network(self, space: str,settings: NetworkSettings,widen: bool,tree: bool) -> SetNetworkResult:
+ """
+ Replaces a Space's network settings (see [`NetworkSettings`]). A
+ child stays within its parent's unless `widen`; `tree` gives its
+ children the same settings. They hold at once where the runtime can
+ change a running guest's network, else from its next start
+ (`applied`). A Space another computer runs is `Unsupported`.
+"""
+ raise NotImplementedError
+ async def set_tree_budget(self, space: str,limits: TreeBudgetLimits) -> TreeBudget:
+ """
+ Sets the budget of `space`'s tree: how many child Spaces, vCPUs and
+ memory its children may hold at once, and what they may cost. A child
+ that does not fit is refused with what is left. All `None` removes it.
"""
raise NotImplementedError
async def space(self, space: str) -> Space:
@@ -42647,6 +43897,12 @@ class SpacesProtocol(typing.Protocol):
Suspends a local Space (a container or a QEMU VM), keeping its
memory: it resumes where it was, and its memory stays in use until
then. [`Spaces::stop`] stops it instead and frees its memory.
+"""
+ raise NotImplementedError
+ async def tree_budget(self, space: str) -> TreeBudget:
+ """
+ The budget of `space`'s tree (any Space of it) and what its
+ children use now. Kept by the cua daemon.
"""
raise NotImplementedError
async def volume_approve(self, request_id: str,expires_in_secs: typing.Optional[int]) -> DriveGrant:
@@ -42840,6 +44096,27 @@ class Spaces(SpacesProtocol):
inst = cls.__new__(cls)
inst._handle = handle
return inst
+ async def ack_network_notice(self, space: str) -> None:
+ """
+ Marks the one-time notice about the new network defaults as shown
+ for `space` ([`SpaceNetworkInfo::notice_pending`]).
+"""
+
+ _UniffiFfiConverterString.check_lower(space)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(space),
+ )
+ _uniffi_lift_return = lambda val: None
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_ack_network_notice(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_void,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_void,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_void,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def add(self, url: str,token: typing.Optional[str],name: typing.Optional[str]) -> SpaceInfo:
"""
Adds a Space by URL (`http(s)://host:port`, `host:port`, or a
@@ -43572,7 +44849,8 @@ class Spaces(SpacesProtocol):
async def delete(self, space: str) -> str:
"""
Deletes a Space's sandbox and forgets it (a Space added by address
- is only forgotten). Returns what happened.
+ is only forgotten). Its child Spaces are deleted first. Returns what
+ happened.
"""
_UniffiFfiConverterString.check_lower(space)
@@ -43635,6 +44913,30 @@ class Spaces(SpacesProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def delete_tree(self, space: str,keep_children: bool) -> str:
+ """
+ [`Spaces::delete`], with `keep_children`: its child Spaces become
+ top-level Spaces and keep running instead of being deleted first.
+"""
+
+ _UniffiFfiConverterString.check_lower(space)
+
+ _UniffiFfiConverterBoolean.check_lower(keep_children)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(space),
+ _UniffiFfiConverterBoolean.lower(keep_children),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterString.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_delete_tree(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def delete_volume(self, name: str,force: bool = False) -> int:
"""
Deletes the named volume `name` and its files (their history stays
@@ -43838,6 +45140,27 @@ class Spaces(SpacesProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def network(self, space: str) -> SpaceNetworkInfo:
+ """
+ A Space's network: its settings, what they open, where they are
+ enforced (or why its network is cut), and what is always blocked.
+"""
+
+ _UniffiFfiConverterString.check_lower(space)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(space),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeSpaceNetworkInfo.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_network(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def notifications(self, unread_only: bool,since_ms: typing.Optional[int]) -> typing.List[NotificationInfo]:
"""
The notifications feed, newest first.
@@ -43907,6 +45230,25 @@ class Spaces(SpacesProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def orphans(self, ) -> typing.List[SpaceOrphan]:
+ """
+ Child Spaces whose parent is gone or out of reach. The cua daemon
+ ends a child only on proof its parent is gone (after a grace period);
+ the rest are listed here and never ended by it.
+"""
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterSequenceTypeSpaceOrphan.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_orphans(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def persistent_agent_create(self, name: str,harness: str,space: str,options: typing.Optional[PersistentAgentOptions]) -> PersistentAgentInfo:
"""
Creates a persistent agent: `harness` working in `space`, its home at
@@ -44356,6 +45698,35 @@ class Spaces(SpacesProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def set_children(self, space: str,enabled: bool) -> None:
+ """
+ Lets a Space make child Spaces of its own, or stops it. While on,
+ `cua`, the SDKs and the agent's tools in that Space create, list and
+ delete Spaces that belong to it (on the same computer, never wider
+ than it, ending no later than it), through a channel only it can
+ reach. Off ends its capability at once; children it made keep running
+ until deleted or their lifetime ends. Only for a Space the machine of
+ this runtime runs itself.
+"""
+
+ _UniffiFfiConverterString.check_lower(space)
+
+ _UniffiFfiConverterBoolean.check_lower(enabled)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(space),
+ _UniffiFfiConverterBoolean.lower(enabled),
+ )
+ _uniffi_lift_return = lambda val: None
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_children(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_void,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_void,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_void,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def set_egress(self, space: str,policy: EgressPolicy) -> None:
"""
Replaces a Space's egress policy; an empty one removes it (see
@@ -44412,6 +45783,64 @@ class Spaces(SpacesProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def set_network(self, space: str,settings: NetworkSettings,widen: bool,tree: bool) -> SetNetworkResult:
+ """
+ Replaces a Space's network settings (see [`NetworkSettings`]). A
+ child stays within its parent's unless `widen`; `tree` gives its
+ children the same settings. They hold at once where the runtime can
+ change a running guest's network, else from its next start
+ (`applied`). A Space another computer runs is `Unsupported`.
+"""
+
+ _UniffiFfiConverterString.check_lower(space)
+
+ _UniffiFfiConverterTypeNetworkSettings.check_lower(settings)
+
+ _UniffiFfiConverterBoolean.check_lower(widen)
+
+ _UniffiFfiConverterBoolean.check_lower(tree)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(space),
+ _UniffiFfiConverterTypeNetworkSettings.lower(settings),
+ _UniffiFfiConverterBoolean.lower(widen),
+ _UniffiFfiConverterBoolean.lower(tree),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeSetNetworkResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_network(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def set_tree_budget(self, space: str,limits: TreeBudgetLimits) -> TreeBudget:
+ """
+ Sets the budget of `space`'s tree: how many child Spaces, vCPUs and
+ memory its children may hold at once, and what they may cost. A child
+ that does not fit is refused with what is left. All `None` removes it.
+"""
+
+ _UniffiFfiConverterString.check_lower(space)
+
+ _UniffiFfiConverterTypeTreeBudgetLimits.check_lower(limits)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(space),
+ _UniffiFfiConverterTypeTreeBudgetLimits.lower(limits),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeTreeBudget.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_set_tree_budget(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def space(self, space: str) -> Space:
"""
A connected handle to a registered Space.
@@ -44502,6 +45931,27 @@ class Spaces(SpacesProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def tree_budget(self, space: str) -> TreeBudget:
+ """
+ The budget of `space`'s tree (any Space of it) and what its
+ children use now. Kept by the cua daemon.
+"""
+
+ _UniffiFfiConverterString.check_lower(space)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(space),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeTreeBudget.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_tree_budget(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def volume_approve(self, request_id: str,expires_in_secs: typing.Optional[int]) -> DriveGrant:
"""
`volume_approve`: the request becomes a grant (with presence).
@@ -47519,6 +48969,7 @@ __all__ = [
"MediaOpenOptions",
"MediaStats",
"NamedVolume",
+ "NetworkSettings",
"NotificationInfo",
"Overlay",
"OverlayResult",
@@ -47560,6 +49011,8 @@ __all__ = [
"Screenshot",
"ScreenshotOptions",
"ServiceEndpoint",
+ "SpaceNetworkInfo",
+ "SetNetworkResult",
"SetupStep",
"Share",
"ShareCheck",
@@ -47582,12 +49035,16 @@ __all__ = [
"SpaceDisplay",
"SpaceHotspotStatus",
"SpaceList",
+ "SpaceOrphan",
"SpacePowerReport",
"SpaceRelayRegistration",
"SpaceResizeReport",
"SpaceSendFileOptions",
"SpaceSentFile",
"SpaceSendFileReport",
+ "SpaceServiceProbe",
+ "SpaceServiceDef",
+ "SpaceServiceInfo",
"SpaceShareEntry",
"SpaceShares",
"SpaceStreamOptions",
@@ -47620,6 +49077,8 @@ __all__ = [
"TeleportReceipt",
"ThreadView",
"TransferResult",
+ "TreeBudgetLimits",
+ "TreeBudget",
"UploadOptions",
"VideoFrame",
"ViewerLink",
diff --git a/libs/cua/python/tests/test_images.py b/libs/cua/python/tests/test_images.py
index e25709a236..ea27b8ee63 100644
--- a/libs/cua/python/tests/test_images.py
+++ b/libs/cua/python/tests/test_images.py
@@ -36,7 +36,15 @@ def _published(ref: str) -> bool:
catalog = json.loads(
(Path(__file__).resolve().parents[3] / "images/sandbox-images.json").read_text()
)
- return next((i["published"] for i in catalog["images"] if i["ref"] == ref), True)
+ # An entry built on the user's own machine (derived_from) resolves while unpublished.
+ return next(
+ (
+ i["published"] or bool(i.get("derived_from"))
+ for i in catalog["images"]
+ if i["ref"] == ref
+ ),
+ True,
+ )
@pytest.mark.parametrize(
diff --git a/libs/cua/python/tests/test_spaces.py b/libs/cua/python/tests/test_spaces.py
index c66fee3145..1b121d1379 100644
--- a/libs/cua/python/tests/test_spaces.py
+++ b/libs/cua/python/tests/test_spaces.py
@@ -34,7 +34,7 @@ class Approver(cua.TeleportApprover):
def test_every_contract_tool_maps_to_a_generated_method():
rows = cua.spaces_tool_methods()
- assert len(rows) == 114
+ assert len(rows) == 118
classes = {"Spaces": cua.Spaces, "Space": cua.Space}
for row in rows:
cls, method = row.method.split(".")
diff --git a/libs/cua/scripts/conformance/agent_case.py b/libs/cua/scripts/conformance/agent_case.py
new file mode 100644
index 0000000000..f60219b855
--- /dev/null
+++ b/libs/cua/scripts/conformance/agent_case.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python3
+"""The `agent` conformance case: a coding agent session starts in a Space and answers.
+
+Installs the coding app in the guest (a real download), serves the scripted model next to it (the
+guest-side endpoint the bench uses), adds a standby agent and waits for its session, then sends one
+turn. Exit 0 when the scripted reply arrives. Driven by `run.py`; needs a python with `mcp`.
+"""
+import argparse, asyncio, base64, os, sys, time
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[3]
+sys.path.insert(0, str(ROOT / "cua-bench" / "datasets" / "ask-first"))
+import askfirst_bench as ab # noqa: E402
+
+
+async def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--cua", required=True)
+ ap.add_argument("--space", required=True, help="local:<name>")
+ ap.add_argument("--name", required=True, help="the sandbox name")
+ ap.add_argument("--harness", default="claude-code")
+ a = ap.parse_args()
+ os.environ["CUA"] = a.cua
+ os.environ.setdefault("ANTHROPIC_API_KEY", "mock-key") # forwarded to the agent; the scripted endpoint ignores it
+ t0 = time.monotonic()
+ rc, o, e = await ab.cua("agent", "ensure", a.space, a.harness, "node", timeout=900)
+ if rc != 0:
+ sys.exit(f"agent ensure failed ({rc}): {(e or o).strip()[:200]}")
+ t_ensure = time.monotonic() - t0
+ b64 = base64.b64encode(ab.SCRIPTED_LLM.read_text().encode()).decode()
+ await ab.cua("sandbox", "exec", a.name, f"echo {b64} | base64 -d > {ab.GUEST_LLM}", timeout=60)
+ await ab.cua("sandbox", "exec", a.name, f"rm -f {ab.GUEST_LOG}; (setsid nohup node {ab.GUEST_LLM} --port {ab.PORT} --log {ab.GUEST_LOG} >/tmp/scripted_llm.out 2>&1 &) ; sleep 1", timeout=60)
+ rc, o, _ = await ab.cua("sandbox", "exec", a.name, f"curl -sS -m 2 http://127.0.0.1:{ab.PORT}/healthz", timeout=60)
+ if "ok" not in o:
+ sys.exit("the scripted model did not start in the guest")
+ member = f"conf-{int(time.time()) % 100000}"
+ space = a.space.split(":", 1)[1]
+ async with ab.CuaMcp({}) as mcp:
+ t1 = time.monotonic()
+ await mcp.call("agent_add", {"space": space, "name": member, "agent": a.harness, "base_url": f"http://127.0.0.1:{ab.PORT}",
+ "env_from_host": ["ANTHROPIC_API_KEY"], "standby": True})
+ cursor, deadline, ready = 0, time.monotonic() + 600, None
+ while time.monotonic() < deadline:
+ try:
+ page = await mcp.call("agent_events", {"space": space, "name": member, "cursor": cursor})
+ except RuntimeError:
+ await asyncio.sleep(0.25)
+ continue
+ if isinstance(page, dict):
+ cursor = page.get("cursor", cursor)
+ if any(ev.get("kind") == "session" for ev in page.get("events", [])):
+ ready = time.monotonic() - t1
+ break
+ await asyncio.sleep(0.25)
+ if ready is None:
+ sys.exit("the agent session did not start in 600 s")
+ r = await ab.member_turn(mcp, space, member, "mock: delay 300; say conformance-ok", cursor, 1, poll_s=0.05, timeout=300, until_end=True, fresh_only=True)
+ if not r.get("t_first"):
+ sys.exit("the agent did not answer")
+ total = (r["t_first"] - r["t0"]) * 1000
+ print(f"agent ok: app installed in {t_ensure:.1f}s, session in {ready:.1f}s, first reply {total:.0f} ms")
+
+
+asyncio.run(main())
diff --git a/libs/cua/scripts/conformance/entries.json b/libs/cua/scripts/conformance/entries.json
new file mode 100644
index 0000000000..16dee030ed
--- /dev/null
+++ b/libs/cua/scripts/conformance/entries.json
@@ -0,0 +1,937 @@
+{
+ "cases": [
+ {
+ "case": "ready",
+ "what": "time from create to a Space that answers"
+ },
+ {
+ "case": "policy",
+ "what": "the default network holds: internet yes; host, LAN, cloud metadata, other trees no"
+ },
+ {
+ "case": "dns",
+ "what": "names resolve in the guest, IPv4 and IPv6"
+ },
+ {
+ "case": "download",
+ "what": "the guest downloads the coding app's package"
+ },
+ {
+ "case": "registry",
+ "what": "a private image is pulled with the host-held registry credential"
+ },
+ {
+ "case": "children",
+ "what": "a home creates, lists, uses and deletes a child Space, audited"
+ },
+ {
+ "case": "agent",
+ "what": "a coding agent session starts and answers"
+ },
+ {
+ "case": "lifecycle",
+ "what": "stop and resume, and the declared pause, checkpoint and fork"
+ },
+ {
+ "case": "teardown",
+ "what": "delete leaves no Space, process, container or network"
+ }
+ ],
+ "entries": [
+ {
+ "backend": "managed",
+ "capabilities": {
+ "archs": [
+ "aarch64",
+ "x86_64"
+ ],
+ "checkpoint": true,
+ "fork": true,
+ "guests": [
+ "linux"
+ ],
+ "kvm": false,
+ "nested_virt": false,
+ "pause": true
+ },
+ "guest": "linux",
+ "hosts": [
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "children",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "agent",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "macos"
+ },
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "children",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "agent",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "windows"
+ }
+ ],
+ "id": "builtin-gvisor",
+ "kind": "container",
+ "needs": "the built-in Linux runtime (downloaded on first use)",
+ "not_runnable": null,
+ "runtime": "gvisor"
+ },
+ {
+ "backend": "managed",
+ "capabilities": {
+ "archs": [
+ "aarch64",
+ "x86_64"
+ ],
+ "checkpoint": true,
+ "fork": true,
+ "guests": [
+ "linux"
+ ],
+ "kvm": false,
+ "nested_virt": false,
+ "pause": true
+ },
+ "guest": "linux",
+ "hosts": [
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "children",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "agent",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "macos"
+ },
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "children",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "agent",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "windows"
+ }
+ ],
+ "id": "builtin-runc",
+ "kind": "container",
+ "needs": "the built-in Linux runtime (downloaded on first use)",
+ "not_runnable": null,
+ "runtime": "runc"
+ },
+ {
+ "backend": "container",
+ "capabilities": {
+ "archs": [
+ "aarch64",
+ "x86_64"
+ ],
+ "checkpoint": true,
+ "fork": true,
+ "guests": [
+ "linux"
+ ],
+ "kvm": false,
+ "nested_virt": false,
+ "pause": true
+ },
+ "guest": "linux",
+ "hosts": [
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "children",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "agent",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "linux"
+ }
+ ],
+ "id": "engine-gvisor",
+ "kind": "container",
+ "needs": "Docker or containerd with gVisor (runsc) and nftables",
+ "not_runnable": null,
+ "runtime": "gvisor"
+ },
+ {
+ "backend": "container",
+ "capabilities": {
+ "archs": [
+ "aarch64",
+ "x86_64"
+ ],
+ "checkpoint": true,
+ "fork": true,
+ "guests": [
+ "linux"
+ ],
+ "kvm": false,
+ "nested_virt": false,
+ "pause": true
+ },
+ "guest": "linux",
+ "hosts": [
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "children",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "agent",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "linux"
+ }
+ ],
+ "id": "engine-runc",
+ "kind": "container",
+ "needs": "Docker or containerd and nftables",
+ "not_runnable": null,
+ "runtime": "runc"
+ },
+ {
+ "backend": "firecracker",
+ "capabilities": {
+ "archs": [
+ "aarch64",
+ "x86_64"
+ ],
+ "checkpoint": true,
+ "fork": true,
+ "guests": [
+ "linux"
+ ],
+ "kvm": true,
+ "nested_virt": true,
+ "pause": true
+ },
+ "guest": "linux",
+ "hosts": [
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "children",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "agent",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "linux"
+ }
+ ],
+ "id": "firecracker-microvm",
+ "kind": "microvm",
+ "needs": "Linux with /dev/kvm and Firecracker",
+ "not_runnable": null,
+ "runtime": "firecracker"
+ },
+ {
+ "backend": "vz",
+ "capabilities": {
+ "archs": [
+ "aarch64"
+ ],
+ "checkpoint": true,
+ "fork": true,
+ "guests": [
+ "linux"
+ ],
+ "kvm": false,
+ "nested_virt": false,
+ "pause": true
+ },
+ "guest": "linux",
+ "hosts": [
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "refused",
+ "why": "Apple's microVM network can't be filtered per Space yet"
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "children",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "agent",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "macos"
+ }
+ ],
+ "id": "vz-microvm",
+ "kind": "microvm",
+ "needs": "an Apple silicon Mac with cua-vz and cua-microvm-init next to `cua`",
+ "not_runnable": null,
+ "runtime": "vz"
+ },
+ {
+ "backend": "containerization",
+ "capabilities": {
+ "archs": [
+ "aarch64",
+ "x86_64"
+ ],
+ "checkpoint": false,
+ "fork": false,
+ "guests": [
+ "linux"
+ ],
+ "kvm": false,
+ "nested_virt": false,
+ "pause": false
+ },
+ "guest": "linux",
+ "hosts": [
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "refused",
+ "why": "Apple's Containerization can't protect your network yet. Use the standard microVM (the default) or choose No protection."
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "children",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "agent",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "macos"
+ }
+ ],
+ "id": "containerization-microvm",
+ "kind": "microvm",
+ "needs": "macOS 26 on Apple silicon (Cua installs Apple's container itself)",
+ "not_runnable": null,
+ "runtime": "containerization"
+ },
+ {
+ "backend": "qemu",
+ "capabilities": {
+ "archs": [
+ "aarch64",
+ "x86_64"
+ ],
+ "checkpoint": true,
+ "fork": true,
+ "guests": [
+ "linux",
+ "windows",
+ "android",
+ "macos"
+ ],
+ "kvm": false,
+ "nested_virt": false,
+ "pause": true
+ },
+ "guest": "linux",
+ "hosts": [
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "refused",
+ "why": "not applicable to this guest"
+ },
+ {
+ "case": "children",
+ "expect": "refused",
+ "why": "not applicable to this guest"
+ },
+ {
+ "case": "agent",
+ "expect": "refused",
+ "why": "not applicable to this guest"
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "linux"
+ },
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "refused",
+ "why": "QEMU on this system can't filter one VM's connections yet"
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "refused",
+ "why": "not applicable to this guest"
+ },
+ {
+ "case": "children",
+ "expect": "refused",
+ "why": "not applicable to this guest"
+ },
+ {
+ "case": "agent",
+ "expect": "refused",
+ "why": "not applicable to this guest"
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "macos"
+ },
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "refused",
+ "why": "QEMU on this system can't filter one VM's connections yet"
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "refused",
+ "why": "not applicable to this guest"
+ },
+ {
+ "case": "children",
+ "expect": "refused",
+ "why": "not applicable to this guest"
+ },
+ {
+ "case": "agent",
+ "expect": "refused",
+ "why": "not applicable to this guest"
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "windows"
+ }
+ ],
+ "id": "qemu-vm",
+ "kind": "vm",
+ "needs": "qemu-system and a Linux VM image (a containerDisk)",
+ "not_runnable": null,
+ "runtime": "qemu"
+ },
+ {
+ "backend": "lume",
+ "capabilities": {
+ "archs": [
+ "aarch64"
+ ],
+ "checkpoint": false,
+ "fork": true,
+ "guests": [
+ "macos"
+ ],
+ "kvm": false,
+ "nested_virt": false,
+ "pause": false
+ },
+ "guest": "macos",
+ "hosts": [
+ {
+ "cases": [
+ {
+ "case": "ready",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "policy",
+ "expect": "refused",
+ "why": "macOS VMs can't protect your network yet, and Cua reaches a macOS VM over its network, so it can't start without one. Choose No protection to start it."
+ },
+ {
+ "case": "dns",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "download",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "registry",
+ "expect": "refused",
+ "why": "not applicable to this guest"
+ },
+ {
+ "case": "children",
+ "expect": "refused",
+ "why": "not applicable to this guest"
+ },
+ {
+ "case": "agent",
+ "expect": "refused",
+ "why": "not applicable to this guest"
+ },
+ {
+ "case": "lifecycle",
+ "expect": "pass",
+ "why": null
+ },
+ {
+ "case": "teardown",
+ "expect": "pass",
+ "why": null
+ }
+ ],
+ "os": "macos"
+ }
+ ],
+ "id": "lume-macos-vm",
+ "kind": "vm",
+ "needs": "an Apple silicon Mac with Lume and a macOS image",
+ "not_runnable": null,
+ "runtime": "lume"
+ },
+ {
+ "backend": "qemu-docker",
+ "capabilities": {
+ "archs": [],
+ "checkpoint": false,
+ "fork": false,
+ "guests": [],
+ "kvm": false,
+ "nested_virt": false,
+ "pause": false
+ },
+ "guest": "linux",
+ "hosts": [],
+ "id": "qemu-docker",
+ "kind": "vm",
+ "needs": "nothing: no runtime of this build starts QEMU inside a container",
+ "not_runnable": "no runtime of this build starts QEMU inside a container",
+ "runtime": ""
+ }
+ ]
+}
diff --git a/libs/cua/scripts/conformance/run.py b/libs/cua/scripts/conformance/run.py
new file mode 100755
index 0000000000..6ec4d000a2
--- /dev/null
+++ b/libs/cua/scripts/conformance/run.py
@@ -0,0 +1,533 @@
+#!/usr/bin/env python3
+"""Runtime conformance, live: the same cases against every runtime this computer has.
+
+The roster and what each entry must do come from `entries.json`, which is generated from
+`cua_vmm::conformance` (a test keeps the file in step). A Space behaves the same on every runtime:
+the secure default network holds, names resolve, the guest downloads packages, a private image is
+pulled with the host-held credential, a home makes and deletes child Spaces, a coding agent session
+starts, and delete leaves nothing. A runtime that cannot keep a promise refuses it at once with the
+reason the registry holds; anything else is a failure.
+
+Opt in: nothing here runs by itself. Everything is made in an isolated Cua home (never ~/.cua) with
+the daemon this script starts from the binary under test (never `cua daemon start`, which hands
+over to an installed Cua Spaces app), and everything it makes is deleted, also on failure.
+
+ CUA=/path/to/cua-spaces-cli ./run.py --entry containerization-microvm --entry vz-microvm \
+ --image ghcr.io/trycua/linux:24.04-slim --private --out results/
+
+The registry credential comes from the environment (CUA_REGISTRY_USERNAME and CUA_REGISTRY_PASSWORD)
+or, with --private, from `gh auth token`. It is passed to the daemon's environment only and never
+printed or written.
+"""
+import argparse, json, os, platform, re, shutil, subprocess, sys, tempfile, time
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+ENTRIES = json.loads((HERE / "entries.json").read_text())
+HOST_OS = {"Darwin": "macos", "Linux": "linux", "Windows": "windows"}.get(platform.system(), platform.system().lower())
+SECRET = re.compile(r"(gh[pousr]_[A-Za-z0-9]{20,}|github_pat_\w+|sk-ant-\S+)")
+# Words in an error that mean "this computer lacks what the runtime needs" (a skip, not a failure).
+MISSING = ("not installed", "is not set up", "cua-vz", "cua-microvm-init", "/dev/kvm", "needs macOS", "not available", "Missing")
+
+
+def redact(s):
+ return SECRET.sub("<redacted>", s or "")
+
+
+class Run:
+ """One isolated home with its own daemon."""
+
+ def __init__(self, cua, home, mode, env_extra, log):
+ self.cua, self.home, self.mode, self.log = cua, Path(home), mode, log
+ self.env = dict(os.environ)
+ self.env.update({
+ "CUA_HOME": str(self.home), "CUA_TELEMETRY": "0", "DO_NOT_TRACK": "1",
+ "CUA_CREDENTIAL_STORE": "test-keychain", "CUA_EXPERIMENTS": "secure-spaces,child-spaces",
+ })
+ # The daemon forwards it to the agent (`env_from_host`); the scripted model ignores the value.
+ self.env.setdefault("ANTHROPIC_API_KEY", "mock-key")
+ if mode == "open":
+ # No protection, for the cases that need a network where the runtime cannot enforce one.
+ self.env["CUA_SECURE_DEFAULT"] = "0"
+ self.env.update(env_extra)
+ self.daemon = None
+
+ def sh(self, *args, timeout=300, check=False):
+ t = time.monotonic()
+ try:
+ p = subprocess.run([self.cua, *args], capture_output=True, text=True, env=self.env, timeout=timeout)
+ rc, out, err = p.returncode, p.stdout, p.stderr
+ except subprocess.TimeoutExpired as e:
+ rc, out, err = 124, (e.stdout or b"").decode(errors="replace") if isinstance(e.stdout, bytes) else (e.stdout or ""), "timed out"
+ ms = (time.monotonic() - t) * 1000
+ out, err = redact(out), redact(err)
+ self.log(f"$ cua {' '.join(args[:6])}{' ...' if len(args) > 6 else ''} -> rc={rc} {ms:.0f}ms")
+ return rc, out, err, ms
+
+ def start(self):
+ self.home.mkdir(parents=True, exist_ok=True)
+ self.daemon = subprocess.Popen(
+ [self.cua, "daemon", "start", "--foreground", "--loopback", "127.0.0.1:0"],
+ stdout=open(self.home / "daemon.log", "w"), stderr=subprocess.STDOUT, env=self.env)
+ for _ in range(150):
+ rc, out, _, _ = self.sh("daemon", "status", timeout=30)
+ if rc == 0 and "pid" in out:
+ return True
+ if self.daemon.poll() is not None:
+ return False
+ time.sleep(0.2)
+ return False
+
+ def stop(self):
+ self.sh("daemon", "stop", timeout=60)
+ if self.daemon and self.daemon.poll() is None:
+ try:
+ self.daemon.wait(timeout=20)
+ except subprocess.TimeoutExpired:
+ self.daemon.terminate() # our own child, by handle
+
+ def exec(self, name, script, timeout=120):
+ # `sandbox exec` stops a command after 120 s by itself: give it the caller's limit.
+ return self.sh("sandbox", "exec", name, "--timeout", str(int(timeout)), script, timeout=timeout + 30)
+
+
+def create_args(entry, image, name, headless=True, extra=()):
+ a = ["sandbox", "create", image, "--kind", entry["kind"], "--name", name, "--cpu", "1", "--memory", "1GB", "--json"]
+ if entry["runtime"]:
+ a += ["--runtime", entry["runtime"]]
+ if headless:
+ a += ["--headless"]
+ return a + list(extra)
+
+
+def cases_of(entry, host):
+ for h in entry["hosts"]:
+ if h["os"] == host:
+ return {c["case"]: c for c in h["cases"]}
+ return {}
+
+
+def host_addresses():
+ """The host's own IPv4 addresses and its default gateway: none may be reachable from a guest."""
+ out = set()
+ try:
+ if HOST_OS == "macos":
+ for ifc in ("en0", "en1", "bridge100", "bridge101"):
+ r = subprocess.run(["ipconfig", "getifaddr", ifc], capture_output=True, text=True)
+ if r.stdout.strip():
+ out.add(r.stdout.strip())
+ r = subprocess.run(["route", "-n", "get", "default"], capture_output=True, text=True)
+ m = re.search(r"gateway: (\S+)", r.stdout)
+ if m:
+ out.add(m.group(1))
+ else:
+ r = subprocess.run(["ip", "-4", "-o", "addr"], capture_output=True, text=True)
+ out |= set(re.findall(r"inet (\d+\.\d+\.\d+\.\d+)", r.stdout)) - {"127.0.0.1"}
+ r = subprocess.run(["ip", "route", "show", "default"], capture_output=True, text=True)
+ m = re.search(r"via (\S+)", r.stdout)
+ if m:
+ out.add(m.group(1))
+ except OSError:
+ pass
+ # Where a guest sees the host through each runtime's own gateway.
+ out |= {"192.168.64.1", "192.168.5.2", "172.17.0.1", "10.0.2.2", "172.16.0.1", "host.docker.internal", "host.lima.internal"}
+ return sorted(out)
+
+
+class Listener:
+ """A TCP listener on every interface of the host: what 'no host' is tested against."""
+
+ def __init__(self):
+ import socket, threading
+ self.s = socket.socket()
+ self.s.bind(("0.0.0.0", 0))
+ self.s.listen(8)
+ self.port = self.s.getsockname()[1]
+ self.hits = []
+ self.alive = True
+
+ def loop():
+ while self.alive:
+ try:
+ c, a = self.s.accept()
+ except OSError:
+ return
+ self.hits.append(a[0])
+ try:
+ c.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nhi")
+ finally:
+ c.close()
+ threading.Thread(target=loop, daemon=True).start()
+
+ def close(self):
+ self.alive = False
+ self.s.close()
+
+
+def run_entry(entry, args, out_dir, log):
+ """Returns the entry's row: {case: {status, detail, ms}}."""
+ rows = {}
+ row = lambda case, status, detail="", ms=None: rows.__setitem__(case, {"status": status, "detail": detail[:600], "ms": None if ms is None else round(ms)})
+ if entry["not_runnable"]:
+ for c in ("ready",):
+ row(c, "n/a", entry["not_runnable"])
+ return rows
+ if HOST_OS not in [h["os"] for h in entry["hosts"]]:
+ row("ready", "n/a", f"does not run on {HOST_OS}")
+ return rows
+ want = cases_of(entry, HOST_OS)
+ selected = [c for c in want if want[c]["expect"] != "refused" or c == "policy"]
+ cases = [c for c in (args.cases.split(",") if args.cases else [x["case"] for x in ENTRIES["cases"]])]
+ # The registry decides which cases apply to the entry's guest (a macOS VM has no coding agent).
+ cases = [c for c in cases if c not in want or want[c]["why"] != "not applicable to this guest"]
+ image = args.image
+ private_entry = bool(args.private)
+ override = dict(x.split("=", 1) for x in (args.entry_image or []))
+ if entry["id"] in override:
+ image, private_entry = override[entry["id"]], False # a public image of that runtime's kind
+ # Short: the built-in runtime keeps Unix sockets under the home (103 bytes at most).
+ idx = [e["id"] for e in ENTRIES["entries"]].index(entry["id"])
+ home = Path(args.home_root) / f"c{idx}"
+ if len(str(home)) > 42:
+ raise SystemExit(f"the home {home} is too long for Unix socket paths: use a shorter --home-root")
+ shutil.rmtree(home, ignore_errors=True)
+ env_extra = {}
+ private = private_entry
+ if private:
+ if "CUA_REGISTRY_PASSWORD" not in os.environ:
+ tok = subprocess.run(["gh", "auth", "token"], capture_output=True, text=True).stdout.strip()
+ if not tok:
+ row("registry", "skip", "no registry credential in the environment and `gh auth token` gave none")
+ private = False
+ else:
+ env_extra["CUA_REGISTRY_USERNAME"] = args.registry_user
+ env_extra["CUA_REGISTRY_PASSWORD"] = tok
+ if args.alias:
+ (home).mkdir(parents=True, exist_ok=True)
+ (home / "image-aliases.json").write_text(json.dumps({image: args.alias}))
+ env_extra["CUA_IMAGE_ALIASES"] = str(home / "image-aliases.json")
+ for var in ("CUA_VZ", "CUA_MICROVM_INIT"):
+ if args.tools and (Path(args.tools) / {"CUA_VZ": "cua-vz", "CUA_MICROVM_INIT": "cua-microvm-init"}[var]).exists():
+ env_extra[var] = str(Path(args.tools) / {"CUA_VZ": "cua-vz", "CUA_MICROVM_INIT": "cua-microvm-init"}[var])
+ name = "conf"
+ listener = Listener()
+ run = None
+ mode = "secure"
+ try:
+ policy = want.get("policy", {"expect": "pass"})
+ # --- the secure default: held, or refused at once with the registry's reason
+ if "policy" in cases and "policy" in want:
+ run = Run(args.cua, home, "secure", env_extra, log)
+ if not run.start():
+ row("ready", "fail", "the daemon did not start: " + (home / "daemon.log").read_text()[-300:])
+ return rows
+ t = time.monotonic()
+ rc, o, e, ms = run.sh(*create_args(entry, image, name), timeout=args.timeout)
+ if policy["expect"] == "refused":
+ reason = (policy["why"] or "")[:50]
+ said = (e + o)
+ norm = lambda s: re.sub(r"\s+", " ", s)
+ if rc != 0 and norm(reason) in norm(said):
+ row("policy", "pass", f"refused at once ({ms:.0f} ms) with the registry's reason")
+ elif rc == 0:
+ row("policy", "fail", "created under the secure default although the runtime declares it cannot protect the network")
+ run.sh("sandbox", "rm", name, "-f")
+ else:
+ row("policy", "fail", "refused, but not with the declared reason: " + norm(said)[:300])
+ run.stop()
+ mode = "open"
+ run = Run(args.cua, home, "open", env_extra, log)
+ if not run.start():
+ row("ready", "fail", "the daemon did not start (open)")
+ return rows
+ rc, o, e, ms = run.sh(*create_args(entry, image, name), timeout=args.timeout)
+ if rc != 0:
+ missing = any(k in (e + o) for k in MISSING)
+ row("ready", "skip" if missing else "fail", "create failed: " + (e or o).strip()[:400])
+ return rows
+ else:
+ run = Run(args.cua, home, "secure", env_extra, log)
+ if not run.start():
+ row("ready", "fail", "the daemon did not start")
+ return rows
+ rc, o, e, ms = run.sh(*create_args(entry, image, name), timeout=args.timeout)
+ if rc != 0:
+ row("ready", "fail", "create failed: " + (e or o).strip()[:400])
+ return rows
+ ready_first = ms
+ row("ready", "pass", f"first create {ms / 1000:.1f}s", ms)
+ if private and "registry" in cases:
+ row("registry", "pass", "the private image was pulled with the host-held credential", ms)
+ elif "registry" in cases and "registry" not in rows:
+ row("registry", "skip", "the image is public (pass --private with a private image)")
+ run.sh("spaces", "add", f"local:{name}")
+ # --- network, only where the secure default holds
+ if "policy" in cases and policy["expect"] == "pass" and mode == "secure":
+ fails = []
+ rc, o, e, _ = run.exec(name, 'curl -sS -m 15 -o /dev/null -w "%{http_code}" https://registry.npmjs.org/')
+ if "200" not in o:
+ fails.append(f"internet not reachable: {o.strip()} {e.strip()[:120]}")
+ rc, o, _, _ = run.exec(name, 'curl -sS -m 4 -o /dev/null -w "%{http_code}" http://169.254.169.254/ || true')
+ if o.strip().endswith("200") or o.strip().startswith("2"):
+ fails.append("cloud metadata reachable")
+ for addr in host_addresses():
+ rc, o, _, _ = run.exec(name, f'curl -sS -m 3 -o /dev/null -w "%{{http_code}}" http://{addr}:{listener.port}/ || true', timeout=60)
+ if o.strip().endswith("200") or listener.hits:
+ fails.append(f"the host's listener answered at {addr}")
+ break
+ row("policy", "fail" if fails else "pass", "; ".join(fails) or "internet yes; metadata, host and its addresses no")
+ elif "policy" in cases and policy["expect"] == "pass" and mode != "secure":
+ row("policy", "fail", "ran open although the runtime declares it protects the network")
+ # --- dns
+ if "dns" in cases:
+ rc, o, e, ms = run.exec(name, 'getent ahosts registry.npmjs.org | head -3; python3 -c "import socket;print(len(socket.getaddrinfo(\'registry.npmjs.org\',443)))" 2>&1; curl -sS -m 20 -o /dev/null -w "curl %{http_code}" https://registry.npmjs.org/')
+ ok = rc == 0 and "curl 200" in o and "STREAM" in o
+ row("dns", "pass" if ok else "fail", (o + e).strip().replace("\n", " | ")[:300], ms)
+ # --- download
+ if "download" in cases:
+ script = ('case "$(uname -m)" in aarch64|arm64) p=linux-arm64;; *) p=linux-x64;; esac; '
+ 'u=$(curl -sS -m 30 "https://registry.npmjs.org/@anthropic-ai%2fclaude-code-$p/latest" | jq -r .dist.tarball); '
+ 'curl -sS -L -m 900 -o /dev/null -w "%{size_download} bytes in %{time_total}s from $u\\n" "$u"')
+ rc, o, e, ms = run.exec(name, script, timeout=700)
+ m = re.search(r"(\d+) bytes in ([\d.]+)s", o)
+ ok = bool(m) and int(m.group(1)) > 10_000_000
+ row("download", "pass" if ok else "fail", (o + e).strip()[:300], ms)
+ # --- children
+ if "children" in cases:
+ row_children(run, entry, name, args, row, mode)
+ # --- agent
+ if "agent" in cases:
+ row_agent(run, entry, name, args, row, image)
+ # --- lifecycle
+ if "lifecycle" in cases:
+ row_lifecycle(run, entry, name, row)
+ # --- cached ready times
+ if args.n > 0 and "ready" in cases:
+ times = []
+ for i in range(args.n):
+ run.sh("sandbox", "rm", name, "-f", timeout=300)
+ rc, o, e, ms = run.sh(*create_args(entry, image, name), timeout=args.timeout)
+ if rc != 0:
+ times.append(None)
+ break
+ times.append(round(ms))
+ run.sh("sandbox", "rm", name, "-f", timeout=300)
+ # A daemon stopped in the middle of a warm-pool burst outlives its own 30 s grace and
+ # leaves the built-in Linux VM running (a known issue): let the pool settle first.
+ time.sleep(args.settle)
+ good = [t for t in times if t]
+ if good:
+ rows["ready"]["detail"] += f"; cached x{len(good)}: " + ", ".join(f"{t / 1000:.1f}s" for t in good) + f" (median {sorted(good)[len(good) // 2] / 1000:.1f}s)"
+ rows["ready"]["cached_ms"] = good
+ finally:
+ listener.close()
+ # --- teardown, then prove nothing is left
+ if run is not None:
+ for n in (name, "conf-fork", "conf-child", "conf-big"):
+ run.sh("sandbox", "rm", n, "-f", timeout=300)
+ run.sh("sandbox", "checkpoints", "prune", timeout=120)
+ run.stop()
+ # A warm-pool member the daemon kept ready holds the built-in Linux VM up past the
+ # daemon's exit; `daemon reap` (no daemon needed) ends what a gone daemon left.
+ run.sh("daemon", "reap", timeout=300)
+ stop_apple_services(run.home)
+ ok, detail = teardown(run, entry, name)
+ if "teardown" in cases:
+ row("teardown", "pass" if ok else "fail", detail)
+ shutil.rmtree(home, ignore_errors=True) if not args.keep_home else None
+ return rows
+
+
+def row_children(run, entry, name, args, row, mode):
+ child = "conf-child"
+ img = args.child_image
+ flags = ["--kind", entry["kind"]] + (["--runtime", entry["runtime"]] if entry["runtime"] else [])
+ rc, o, e, ms = run.sh("spaces", "children", f"local:{name}", "on")
+ if rc != 0:
+ row("children", "fail", "children on: " + (e or o).strip()[:200])
+ return
+ inner = f'cua spaces create {img} {" ".join(flags)} --name {child} 2>&1 | tail -2'
+ t = time.monotonic()
+ rc, o, e, _ = run.exec(name, inner, timeout=args.timeout)
+ made = "Created" in o
+ steps = [("create", made, o.strip()[-160:])]
+ if made:
+ rc, o, e, _ = run.exec(name, f"cua spaces ls | grep -c {child}")
+ steps.append(("list", o.strip().endswith("1"), o.strip()))
+ rc, o, e, _ = run.exec(name, f'cua sandbox exec {child} "echo child-ok"', timeout=120)
+ steps.append(("use", "child-ok" in o, (o + e).strip()[-100:]))
+ # the budget: a create that cannot fit is refused, in plain words
+ rc, o, e, _ = run.exec(name, f'cua spaces create {img} {" ".join(flags)} --name conf-big --cpus 99 2>&1 | tail -2')
+ steps.append(("budget", ("budget" in o.lower() or "too many" in o.lower() or "exceed" in o.lower() or "left" in o.lower()) and "Created" not in o, o.strip()[-160:]))
+ rc, o, e, _ = run.exec(name, f"cua spaces delete {child} -f 2>&1 | tail -1; cua spaces ls | grep -c {child}")
+ steps.append(("delete", o.strip().endswith("0") and "Deleted" in o, o.strip()[-100:]))
+ audit = Path(run.home) / "children-audit.jsonl"
+ text = audit.read_text() if audit.exists() else ""
+ steps.append(("audit", '"spawn"' in text, f"{len(text.splitlines())} audit lines"))
+ bad = [f"{n}: {d}" for n, ok, d in steps if not ok]
+ row("children", "fail" if bad else "pass", "; ".join(bad) or "create, list, use, budget refusal, delete, audited", (time.monotonic() - t) * 1000)
+
+
+def row_agent(run, entry, name, args, row, image):
+ if not args.agent_python:
+ row("agent", "skip", "no --agent-python (a python with the `mcp` package) to drive the agent")
+ return
+ script = HERE / "agent_case.py"
+ t = time.monotonic()
+ p = subprocess.run([args.agent_python, str(script), "--cua", run.cua, "--space", f"local:{name}", "--name", name],
+ capture_output=True, text=True, env=run.env, timeout=1500)
+ out = redact(p.stdout + p.stderr)
+ row("agent", "pass" if p.returncode == 0 else "fail", out.strip().splitlines()[-1][:300] if out.strip() else "", (time.monotonic() - t) * 1000)
+
+
+def row_lifecycle(run, entry, name, row):
+ caps = entry["capabilities"]
+ fails, notes = [], []
+ # stop and resume
+ rc, o, e, ms = run.sh("sandbox", "suspend", name, timeout=300)
+ if rc != 0:
+ fails.append("suspend: " + (e or o).strip()[:120])
+ else:
+ rc, o, e, ms2 = run.sh("sandbox", "resume", name, timeout=600)
+ if rc != 0:
+ fails.append("resume: " + (e or o).strip()[:160])
+ else:
+ rc, o, e, _ = run.exec(name, "echo back")
+ if "back" not in o:
+ fails.append("after resume the guest does not answer")
+ notes.append(f"suspend {ms:.0f} ms, resume {ms2:.0f} ms")
+ if "restart" and not fails:
+ rc, o, e, ms = run.sh("sandbox", "restart", name, timeout=600)
+ if rc != 0:
+ fails.append("restart: " + (e or o).strip()[:160])
+ else:
+ # `restart` returns once the runtime says so: how long until the guest answers?
+ t = time.monotonic()
+ answered = None
+ while time.monotonic() - t < 180:
+ rc, o, e, _ = run.exec(name, "echo back2", timeout=30)
+ if "back2" in o:
+ answered = time.monotonic() - t
+ break
+ time.sleep(2)
+ if answered is None:
+ fails.append("after restart the guest does not answer in 180 s")
+ notes.append(f"restart {ms:.0f} ms, answering {answered * 1000 + ms:.0f} ms after the call" if answered is not None else f"restart {ms:.0f} ms")
+ # what it declares: a checkpoint and a fork, or a plain refusal
+ rc, o, e, _ = run.sh("sandbox", "checkpoint", name, "conf-ck", timeout=600)
+ if caps["checkpoint"]:
+ if rc != 0:
+ fails.append("declares checkpoints but: " + (e or o).strip()[:140])
+ else:
+ rc, o, e, _ = run.sh("sandbox", "fork", "conf-ck", "conf-fork", timeout=600) if caps["fork"] else (0, "", "", 0)
+ if caps["fork"] and rc != 0:
+ fails.append("declares forks but: " + (e or o).strip()[:140])
+ run.sh("sandbox", "rm", "conf-fork", "-f", timeout=300)
+ run.sh("sandbox", "checkpoints", "rm", "conf-ck", timeout=120)
+ else:
+ text = (e + o).strip()
+ if rc == 0:
+ fails.append("does not declare checkpoints but one was made")
+ run.sh("sandbox", "checkpoints", "rm", "conf-ck", timeout=120)
+ elif len(text) < 15:
+ fails.append("a checkpoint is refused without a plain reason")
+ else:
+ notes.append("checkpoint refused: " + text[:80])
+ row("lifecycle", "fail" if fails else "pass", "; ".join(fails + notes))
+
+
+def stop_apple_services(home):
+ """Apple's `container` services outlive a Space (cua never stops them, they are per user): the
+ ones this run's home started are stopped before the home goes."""
+ for b in Path(home).glob("vmm/containerization/install/*/bin/container"):
+ env = dict(os.environ, CONTAINER_APP_ROOT=str(Path(home) / "vmm/containerization/data"), CONTAINER_INSTALL_ROOT=str(b.parent.parent))
+ subprocess.run([str(b), "system", "stop"], capture_output=True, env=env, timeout=120)
+
+
+def teardown(run, entry, name):
+ rc, o, e, _ = run.sh("sandbox", "ls", "--embedded", timeout=60)
+ left = [l for l in o.splitlines()[1:] if l.strip()]
+ leftovers = []
+ if left:
+ leftovers.append(f"Spaces left: {len(left)}")
+ home = str(run.home)
+ # The runtimes exit with the daemon (the built-in Linux VM takes a few seconds): wait for
+ # them before the home goes, never delete a home a VM still runs from.
+ deadline = time.monotonic() + 90
+ while True:
+ ps = subprocess.run(["ps", "-axo", "pid,args"], capture_output=True, text=True).stdout
+ mine = [l for l in ps.splitlines() if home in l and "daemon" not in l and ("cua-vz" in l or "container-runtime-linux" in l or "limactl" in l or "container-apiserver" in l or "qemu" in l or "firecracker" in l)]
+ if not mine or time.monotonic() > deadline:
+ break
+ time.sleep(2)
+ if mine:
+ leftovers.append(f"{len(mine)} runtime process(es) still run after 90 s")
+ # Never leave a VM running from a home that is about to be deleted: end this run's own
+ # processes, by exact pid (they carry this run's isolated home in their command line).
+ for l in mine:
+ try:
+ os.kill(int(l.split()[0]), 15)
+ except (ValueError, OSError):
+ pass
+ return (not leftovers), "; ".join(leftovers) or "no Space, process or instance left"
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--entry", action="append", help="an entry id (repeatable); default: every entry that runs on this OS")
+ ap.add_argument("--cua", default=os.environ.get("CUA") or shutil.which("cua"))
+ ap.add_argument("--image", default="ghcr.io/trycua/linux:24.04-slim")
+ ap.add_argument("--alias", default=None, help="the package the image resolves to (a private mirror of the same tag)")
+ ap.add_argument("--child-image", default="ghcr.io/trycua/linux:24.04-slim")
+ ap.add_argument("--private", action="store_true", help="the image is private: the credential comes from the environment or `gh auth token`")
+ ap.add_argument("--registry-user", default="x")
+ ap.add_argument("--entry-image", action="append", help="ID=IMAGE: the image one entry uses (public, e.g. qemu-vm=ghcr.io/trycua/linux:24.04)")
+ ap.add_argument("--cases", default=None, help="comma list (default: all)")
+ ap.add_argument("--n", type=int, default=0, help="extra creates after deleting the Space, for the cached ready time")
+ ap.add_argument("--timeout", type=int, default=1500)
+ ap.add_argument("--settle", type=int, default=45, help="seconds the daemon is left to settle (its warm pool) before it stops")
+ ap.add_argument("--tools", default=None, help="a folder holding cua-vz and cua-microvm-init")
+ ap.add_argument("--agent-python", default=None)
+ ap.add_argument("--home-root", default="/tmp/cua-conf",
+ help="where the isolated Cua homes are made (short: Unix socket paths are limited)")
+ ap.add_argument("--keep-home", action="store_true")
+ ap.add_argument("--out", default=str(HERE / "results"))
+ args = ap.parse_args()
+ if not args.cua:
+ sys.exit("set CUA (or --cua) to the binary under test")
+ out = Path(args.out)
+ out.mkdir(parents=True, exist_ok=True)
+ wanted = args.entry or [e["id"] for e in ENTRIES["entries"] if not e["not_runnable"] and HOST_OS in [h["os"] for h in e["hosts"]]]
+ by_id = {e["id"]: e for e in ENTRIES["entries"]}
+ matrix = {}
+ logf = open(out / "conformance.log", "a")
+
+ def log(msg):
+ logf.write(f"[{time.strftime('%H:%M:%S')}] {redact(msg)}\n")
+ logf.flush()
+
+ for eid in wanted:
+ entry = by_id[eid]
+ log(f"== {eid}")
+ print(f"== {eid}", flush=True)
+ load = subprocess.run(["uptime"], capture_output=True, text=True).stdout.strip().split("load averages:")[-1].strip()
+ try:
+ rows = run_entry(entry, args, out, log)
+ except Exception as e: # a crash is a failure, with its words
+ rows = {"ready": {"status": "fail", "detail": f"driver error: {redact(str(e))[:300]}", "ms": None}}
+ matrix[eid] = {"host": HOST_OS, "load": load, "cases": rows}
+ for c, r in rows.items():
+ print(f" {c:10} {r['status']:8} {r['detail'][:110]}", flush=True)
+ (out / "matrix.json").write_text(json.dumps(matrix, indent=1))
+ # a summary a person can read
+ lines = ["| Runtime | " + " | ".join(c["case"] for c in ENTRIES["cases"]) + " |", "|---|" + "---|" * len(ENTRIES["cases"])]
+ for eid, m in matrix.items():
+ lines.append(f"| {eid} | " + " | ".join(m["cases"].get(c["case"], {}).get("status", "-") for c in ENTRIES["cases"]) + " |")
+ (out / "matrix.md").write_text("\n".join(lines) + "\n")
+ print("\n".join(lines))
+ failed = [eid for eid, m in matrix.items() if any(r["status"] == "fail" for r in m["cases"].values())]
+ sys.exit(1 if failed else 0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/cua/skills/cua-spaces/SKILL.md b/libs/cua/skills/cua-spaces/SKILL.md
index 3f8b399873..09a4353c06 100644
--- a/libs/cua/skills/cua-spaces/SKILL.md
+++ b/libs/cua/skills/cua-spaces/SKILL.md
@@ -26,12 +26,46 @@ created when the task ends.
| Tool | Use |
|---|---|
-| `space_bash` | Run a shell command (`space`, `command`, optional `timeout`). |
+| `space_bash` | Run a shell command (`space`, `command`, optional `timeout`). For anything under a minute. |
+| `space_job` | Run a long command in the background (`action`: `start`, `status`, `logs`, `cancel`, `list`). See "Long work" below. |
| `space_write` | Write text to a file. |
| `upload` / `download` | Copy files or folders in and out. |
| `send_file` | Drop a host file into the Space's Downloads (sha256 verified). |
| `list_tools` / `call_tool` | Reach MCP services running inside the Space. |
+## Long work
+
+Builds, test suites and waits on CI take minutes. Do not hold a `space_bash`
+call open for them: a job started with `space_job` keeps running when you stop,
+disconnect or the Space's daemon restarts, and it can wake you when it ends.
+
+Long work (a build, a test suite, a wait on CI): never sit inside one call. Start it with space_job (action start, notify true, a name of a few words), post one line in the thread saying what you started, then end your turn. When it ends the thread gets `JOB <id> <state> exit=<n> ...` with the end of the log, and you receive it as your next task; read more with space_job logs (offset: the next_offset you were given). If you cannot be woken, poll with space_job logs and follow_ms instead of sleeping in space_bash.
+
+- `space_job {action: "start", command, name, notify: true}` returns a job id
+ at once. `cwd`, `env` and `timeout` (seconds) are optional.
+- `space_job {action: "logs", job, offset}` reads the log from a byte offset
+ and returns `next_offset`; `follow_ms` (at most 25000) waits for output.
+ Without `offset` you get the end of the log. `status` is the state plus the
+ last few KB. `list` shows the Space's jobs. `cancel` stops the whole process
+ tree.
+- `state` is `running`, `exited` (with `exit_code`), `cancelled`, `timed_out`
+ or `lost` (the Space restarted and the job died with it).
+- To wait for something that is not your own command, use `until` instead of
+ `command`: `{file: path}`, `{port: 5432}`, `{command: "test -f x"}` or
+ `{pr_checks: "owner/repo#123"}` (the pull request's required checks, through
+ `gh` signed in inside the Space). The job ends when the condition holds, so
+ `notify: true` wakes you at that moment.
+
+## Working with other agents
+
+Working with other agents (a parent Space and its child Spaces, or any agents in one Space): 1. Before you start, thread_read and note what others have claimed. 2. Post `CLAIM <what> | files: <paths or branch> | until: <when>` for what you will change. Do not edit files or branches another agent's live CLAIM covers: @mention the owner and wait for the reply. 3. A claim is live until its `until` passes or its owner posts DONE or RELEASE; once it has expired you may take it, and you say so in the thread. 4. Report with one structured line: `DONE <what> | <result> | next: <step>` or `BLOCKED <what> | needs: <thing> | from @who`. 5. Keep messages short, one @mention per request, and never your own name.
+
+Example, for any task: `CLAIM refactor the parser | files: src/parser/** on
+branch parser-refactor | until: 16:00` ... `DONE refactor the parser | merged
+into the branch, tests pass | next: docs`. A parent Space's agent that starts
+agents in child Spaces gives each one the parent thread's join link (see
+`thread_join_code_create`), so the whole group reads and posts in one place.
+
## Show it to the user
| Tool | Use |
diff --git a/libs/cua/spaces-contract/fixtures/control/session.json b/libs/cua/spaces-contract/fixtures/control/session.json
index 1ac5c9d093..548210ba81 100644
--- a/libs/cua/spaces-contract/fixtures/control/session.json
+++ b/libs/cua/spaces-contract/fixtures/control/session.json
@@ -44,6 +44,28 @@
],
"metering": "cloud"
},
+ {
+ "tool": "network_show",
+ "sdk_symbol": "Spaces::network_info",
+ "providers": [
+ "cloud",
+ "local",
+ "direct",
+ "relay"
+ ],
+ "metering": "free"
+ },
+ {
+ "tool": "network_set",
+ "sdk_symbol": "Spaces::set_network",
+ "providers": [
+ "cloud",
+ "local",
+ "direct",
+ "relay"
+ ],
+ "metering": "free"
+ },
{
"tool": "delete_space",
"sdk_symbol": "Space::delete",
@@ -99,6 +121,17 @@
],
"metering": "free"
},
+ {
+ "tool": "space_job",
+ "sdk_symbol": "Space::job",
+ "providers": [
+ "cloud",
+ "local",
+ "direct",
+ "relay"
+ ],
+ "metering": "free"
+ },
{
"tool": "space_write",
"sdk_symbol": "Space::write_text",
@@ -231,6 +264,17 @@
],
"metering": "free"
},
+ {
+ "tool": "space_service",
+ "sdk_symbol": "Space::keep_service",
+ "providers": [
+ "cloud",
+ "local",
+ "direct",
+ "relay"
+ ],
+ "metering": "free"
+ },
{
"tool": "agent_start",
"sdk_symbol": "Space::start_agent",
diff --git a/libs/cua/spaces-contract/manifest.json b/libs/cua/spaces-contract/manifest.json
index 679ffbc72b..8d5bc06465 100644
--- a/libs/cua/spaces-contract/manifest.json
+++ b/libs/cua/spaces-contract/manifest.json
@@ -9,7 +9,7 @@
"mcp_stdio",
"mcp_streamable_http"
],
- "tool_count": 114,
+ "tool_count": 118,
"categories": [
{
"id": "lifecycle",
@@ -462,6 +462,13 @@
],
"input_schema": {
"properties": {
+ "allow": {
+ "description": "Destinations to allow (addresses or CIDRs) on top of `network`.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
"command": {
"description": "Entrypoint override (argv), for example\n`[\"python\", \"-m\", \"my_mcp\", \"--port\", \"8765\"]`.",
"items": {
@@ -475,6 +482,13 @@
"minimum": 0,
"type": "integer"
},
+ "deny": {
+ "description": "Destinations to block (addresses, CIDRs or `all`).",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
"durable": {
"description": "Keep it on the user's machines (with `on` `auto`): when its machine\ngoes away it is created again on another one, with the same name\n(its disk starts fresh); `list_spaces` shows it with `durable` (its\nname), and `delete_space` deletes it for good. Default false.",
"type": "boolean"
@@ -530,10 +544,18 @@
"description": "Name. Default: a generated `space-<hex>`.",
"type": "string"
},
+ "network": {
+ "description": "Its network: `internet` (default: the internet and its own tree;\nthis computer, the local network, cloud metadata and other trees are\nblocked), `none`, or `custom` / `custom:none` with `allow` and\n`deny`. Presets that open more (`localhost:<ports>`, `lan`,\n`unprotected`) are the user's to choose: refused here.",
+ "type": "string"
+ },
"on": {
"description": "Where it runs: `local` (this computer, free), `auto` (the\nleast-loaded of the user's computers that can take it: this one and\nthe ones signed in to the user's account that provide Spaces, Modal\nonly when connected and no computer has room), `aws`, `gcp` or\n`modal` (your own cloud account, billed there), or `host:<computer>`:\none of the user's own computers that\nprovides Spaces (`cua host setup --share both` on it), named by\nid or by words from its name (\"host:spare mac mini\" matches \"Mac\nmini (spare)\" or `dillons-mac-mini`). Default: the user's default\nlocation (`cua config set default.on`, `CUA_DEFAULT_ON`), else\n`local`; never `auto` unless asked. Not `direct:<addr>`: that is one already-running Space at a\nfixed address, attached with `add_space`, not a host this can create\non. An existing computer is added with `add_space`, not created.",
"type": "string"
},
+ "parent": {
+ "description": "Create it as a child of this Space (id or name): it joins the\nparent's tree, and its network is no more open than the parent's.",
+ "type": "string"
+ },
"region": {
"description": "With `on` a linked cloud: the region (Hetzner location) its host must\nbe in. Default: any the cloud offers.",
"type": "string"
@@ -574,6 +596,130 @@
"type": "object"
}
},
+ {
+ "name": "network_show",
+ "category": "lifecycle",
+ "description": "Show a Space's network: preset, what it opens, where it is enforced, what is always blocked.",
+ "instructions": "Shows a Space's network: its preset (`internet` by default: the internet and its own tree, with this computer, the local network, cloud metadata and other trees blocked), what it opens beyond that, where the rules are enforced (outside the guest), or why it has no network (a runtime that can't protect it yet starts it without network), and what is always blocked. When a connection fails, check here before retrying: a blocked destination stays blocked.",
+ "platforms": [
+ "macos",
+ "windows",
+ "linux"
+ ],
+ "providers": [
+ "cloud",
+ "local",
+ "direct",
+ "relay"
+ ],
+ "metering": "free",
+ "capabilities": [
+ "space.network.read"
+ ],
+ "requires": [],
+ "host_requires": [],
+ "annotations": {
+ "read_only": true,
+ "destructive": false,
+ "idempotent": true,
+ "open_world": true
+ },
+ "sdk_symbol": "Spaces.network(space)",
+ "rust_symbol": "Spaces::network_info",
+ "notes": [],
+ "result": "JSON: `settings` (preset, lists), `summary`, `widenings` (what it opens beyond internet), `enforcement` (`enforced`, `no_network`, `open`, `refused`), `point`, `note`, `parent`, `root`, `always_blocked`, `notice_pending`.",
+ "errors": [
+ "invalid_argument",
+ "not_found"
+ ],
+ "input_schema": {
+ "properties": {
+ "space": {
+ "description": "Space id or name.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "space"
+ ],
+ "type": "object"
+ }
+ },
+ {
+ "name": "network_set",
+ "category": "lifecycle",
+ "description": "Tighten a Space's network: internet, none or custom lists. Opening more is the user's to do.",
+ "instructions": "Changes a Space's network to `internet`, `none`, or `custom` (from internet) / `custom:none` with `allow` and `deny` (addresses or CIDRs). It can only tighten: anything that opens more than the Space has now (this computer's localhost, the local network, No protection, an allow beyond its preset) is refused; the user does that with `cua network set` or the app. A child stays within its parent's. tree=true gives its children the same settings. Applies at once where the runtime can, else at the Space's next start (`applied`).",
+ "platforms": [
+ "macos",
+ "windows",
+ "linux"
+ ],
+ "providers": [
+ "cloud",
+ "local",
+ "direct",
+ "relay"
+ ],
+ "metering": "free",
+ "capabilities": [
+ "space.network.write"
+ ],
+ "requires": [],
+ "host_requires": [],
+ "annotations": {
+ "read_only": false,
+ "destructive": false,
+ "idempotent": true,
+ "open_world": true
+ },
+ "sdk_symbol": "Spaces.set_network(space, settings, widen, tree)",
+ "rust_symbol": "Spaces::set_network",
+ "notes": [],
+ "result": "JSON: `applied` (`now` or `next_start`) and `network` (as network_show).",
+ "errors": [
+ "invalid_argument",
+ "wrong_provider",
+ "not_found",
+ "sandbox"
+ ],
+ "input_schema": {
+ "additionalProperties": false,
+ "properties": {
+ "allow": {
+ "description": "Destinations to allow (addresses or CIDRs).",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "deny": {
+ "description": "Destinations to block (addresses, CIDRs or `all`).",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "network": {
+ "description": "`internet`, `none`, or `custom` / `custom:none` with `allow` and\n`deny`. Opening more than the Space has now is the user's to do\n(`cua network set`, or the app): refused here.",
+ "type": "string"
+ },
+ "space": {
+ "description": "Space id or name.",
+ "type": "string"
+ },
+ "tree": {
+ "description": "Its child Spaces take the same settings (each within its parent's).",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "space",
+ "network"
+ ],
+ "type": "object"
+ }
+ },
{
"name": "delete_space",
"category": "lifecycle",
@@ -862,6 +1008,172 @@
"type": "object"
}
},
+ {
+ "name": "space_job",
+ "category": "commands-and-files",
+ "description": "Run a long command in the Space as a background job: tail its log, cancel it, or get woken when it ends.",
+ "instructions": "Use this instead of space_bash for anything that takes more than a minute (builds, test suites, installs, waiting on CI). `start` returns a job id at once and the command keeps running when you stop, disconnect, or the Space's daemon restarts. Read it with `logs` (pass the returned `next_offset` as `offset` to read on; `follow_ms` waits for output) or `status`; stop it with `cancel`; `list` shows the Space's jobs. Pass `notify: true` to be woken: the Space's thread gets one message `JOB <id> <state> exit=<n> ...` with the end of the log, and as an agent member you receive it as your next turn, so you can end your turn instead of polling. `until` makes a job that waits for a file, a port, a command or a pull request's required checks; its end is the condition. Output is stdout and stderr together. Linux and macOS guests.",
+ "platforms": [
+ "macos",
+ "windows",
+ "linux"
+ ],
+ "providers": [
+ "cloud",
+ "local",
+ "direct",
+ "relay"
+ ],
+ "metering": "free",
+ "capabilities": [
+ "space.exec",
+ "space.exec.shell",
+ "space.exec.jobs"
+ ],
+ "requires": [],
+ "host_requires": [],
+ "annotations": {
+ "read_only": false,
+ "destructive": true,
+ "idempotent": false,
+ "open_world": true
+ },
+ "sdk_symbol": "Space.job(_:)",
+ "rust_symbol": "Space::job",
+ "notes": [
+ "A job is a command that outlives the call, the connection and a restart of the Space's daemon; its state is files in the Space (`~/.cua/jobs/<id>`). Guests that are not Windows."
+ ],
+ "result": "JSON. `start`: `job`, `state`, `log_command` and a `hint`. `status`, `logs`: `job`, `name`, `state` (`running`, `exited`, `cancelled`, `timed_out` or `lost`), `exit_code`, `signal`, `started_at` and `ended_at` (unix seconds), `elapsed_s`, `size` (log bytes), and for `logs` `offset`, `next_offset`, `text` and `more`. `cancel`: the final status. `list`: `jobs`.",
+ "errors": [
+ "not_found",
+ "wrong_provider"
+ ],
+ "input_schema": {
+ "properties": {
+ "action": {
+ "description": "`start` (begin a job), `status` (state and the end of its log),\n`logs` (read the log from a byte offset), `cancel` (stop it) or\n`list` (this Space's jobs, newest first).",
+ "type": "string"
+ },
+ "command": {
+ "description": "`start`: the command line, run with `/bin/sh -c` in the background. It\nkeeps running when you or your connection go away. Give this or\n`until`.",
+ "type": "string"
+ },
+ "cwd": {
+ "description": "`start`: the directory to run in. Default: the Space user's home.",
+ "type": "string"
+ },
+ "env": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "description": "`start`: environment variables for the command.",
+ "type": "object"
+ },
+ "follow_ms": {
+ "description": "`logs`: when there is nothing new after `offset` and the job is\nrunning, wait up to this many milliseconds (at most 25000) for output\nor for the job to end. Default 0.",
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "job": {
+ "description": "`status`, `logs`, `cancel`: the job id `start` returned.",
+ "type": "string"
+ },
+ "limit": {
+ "description": "`logs`: most bytes to return (default 16000, at most 262144).",
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "name": {
+ "description": "`start`: a short label for the job (\"unit tests\"), shown in listings\nand in the message that wakes you.",
+ "type": "string"
+ },
+ "notify": {
+ "description": "`start`: wake me when the job ends. The Space's thread gets one\nmessage with the job's result and the end of its log, addressed to\nyou when you are an agent member of the Space (so you can finish your\nturn and sleep), and the person gets a notification. Default false.",
+ "type": "boolean"
+ },
+ "offset": {
+ "description": "`logs`: the byte offset to read from (the `next_offset` of the\nprevious call). Without it: the last `limit` bytes.",
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "space": {
+ "description": "Space id or name.",
+ "type": "string"
+ },
+ "timeout": {
+ "description": "`start`: seconds before the job is stopped. Default: none.",
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "until": {
+ "description": "`start`: wait for a condition instead of running `command`. The job\nends when the condition holds (exit 0), or after `timeout`.",
+ "properties": {
+ "command": {
+ "description": "Wait for this shell command to exit 0.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "file": {
+ "description": "Wait for this path to exist in the Space.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "host": {
+ "description": "With `port`: the host. Default 127.0.0.1.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "interval": {
+ "description": "Seconds between checks (1 to 300). Default 5 (30 for `pr_checks`).",
+ "format": "uint64",
+ "minimum": 0,
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "port": {
+ "description": "Wait for this TCP port to accept connections (on `host`, default\n127.0.0.1).",
+ "format": "uint16",
+ "maximum": 65535,
+ "minimum": 0,
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "pr_checks": {
+ "description": "Wait for a GitHub pull request's required checks to finish with `gh`\n(signed in inside the Space): a number, a URL or `owner/repo#123`.\nThe job exits 0 when they pass and 1 when one fails.",
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "type": "object"
+ },
+ "wake": {
+ "description": "`start` with `notify`: the agent member to wake instead of you.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "space",
+ "action"
+ ],
+ "type": "object"
+ }
+ },
{
"name": "space_write",
"category": "commands-and-files",
@@ -1570,6 +1882,95 @@
"type": "object"
}
},
+ {
+ "name": "space_service",
+ "category": "services",
+ "description": "Keep a command running in the Space: restarts, health checks, start on boot, logs.",
+ "instructions": "Keeps a command running in the Space: cua-spacesd starts it at once, starts it again by its `restart` policy when it ends (waiting longer after each quick failure, up to a minute), restarts it when its health check (`http`, `tcp` or `check`, one of them) fails 3 times in a row, starts it when the Space boots unless start_on_boot is false, and keeps its output in a log file in the Space (`logs`). `stop` keeps it stopped, across a reboot too, until `start`. `add` with a name that exists replaces it.",
+ "platforms": [
+ "macos",
+ "windows",
+ "linux"
+ ],
+ "providers": [
+ "cloud",
+ "local",
+ "direct",
+ "relay"
+ ],
+ "metering": "free",
+ "capabilities": [
+ "space.services.keep"
+ ],
+ "requires": [],
+ "host_requires": [],
+ "annotations": {
+ "read_only": false,
+ "destructive": true,
+ "idempotent": false,
+ "open_world": true
+ },
+ "sdk_symbol": "space.keepRunning.service(_:)",
+ "rust_symbol": "Space::keep_service",
+ "notes": [],
+ "result": "JSON: `add`, `start`, `stop` and `restart` give the service (`name`, `command`, `state`, `pid`, `restarts`, `last_end`, `probe_error`, `restart`, `start_on_boot`, `log_path`); `list` gives `services`; `logs` gives `logs` (text); `remove` gives `removed`.",
+ "errors": [
+ "capability_missing",
+ "invalid_argument",
+ "not_found"
+ ],
+ "input_schema": {
+ "properties": {
+ "action": {
+ "description": "`add` (or replace), `list`, `start`, `stop`, `restart`, `remove` or\n`logs`.",
+ "type": "string"
+ },
+ "check": {
+ "description": "`add`: health check, a shell command that exits 0 when healthy.",
+ "type": "string"
+ },
+ "command": {
+ "description": "`add`: the shell command line to keep running.",
+ "type": "string"
+ },
+ "http": {
+ "description": "`add`: health check, a URL that answers 2xx or 3xx.",
+ "type": "string"
+ },
+ "name": {
+ "description": "Service name (every action but `list`): lowercase letters, digits,\n`-`, `_` and `.`.",
+ "type": "string"
+ },
+ "restart": {
+ "description": "`add`: when to start it again: `always` (default), `on-failure` or\n`never`.",
+ "type": "string"
+ },
+ "space": {
+ "description": "Space id or name.",
+ "type": "string"
+ },
+ "start_on_boot": {
+ "description": "`add`: start it when the Space boots (default true).",
+ "type": "boolean"
+ },
+ "tail_bytes": {
+ "description": "`logs`: bytes from the end (default 64 KiB).",
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "tcp": {
+ "description": "`add`: health check, `host:port` that accepts a connection.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "space",
+ "action"
+ ],
+ "type": "object"
+ }
+ },
{
"name": "agent_start",
"category": "agents",
diff --git a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift
index 91694388b1..4674eac953 100644
--- a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift
+++ b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift
@@ -9015,6 +9015,11 @@ public protocol SpaceProtocol: AnyObject, Sendable {
*/
func closeStream(mediaSessionId: String) async throws
+ /**
+ * Stops a service and forgets it (its logs go too).
+ */
+ func deleteService(name: String) async throws
+
/**
* The Space's displays, primary first, with their resolution in
* physical pixels.
@@ -9078,6 +9083,11 @@ public protocol SpaceProtocol: AnyObject, Sendable {
*/
func joinPresence(identity: PresenceIdentity, timeoutMs: UInt64?) async throws -> SpacePresence
+ /**
+ * This Space's services.
+ */
+ func keptServices() async throws -> [SpaceServiceInfo]
+
/**
* Tools of the Space's MCP service (`driver`, the default).
*/
@@ -9089,6 +9099,13 @@ public protocol SpaceProtocol: AnyObject, Sendable {
*/
func openStream(options: SpaceStreamOptions) async throws -> SpaceStreamTicket
+ /**
+ * Keeps a command running in this Space (replacing a service of that
+ * name): restarted by its policy when it ends or fails its health
+ * check, started when the Space boots, its output kept in a log file.
+ */
+ func putService(def: SpaceServiceDef) async throws -> SpaceServiceInfo
+
/**
* Signs in to a site in this Space's browser with a password the user
* saved in the Cua Keyvault. The first call files a request
@@ -9099,6 +9116,11 @@ public protocol SpaceProtocol: AnyObject, Sendable {
*/
func requestSiteLogin(url: String, options: SiteLoginOptions?) async throws -> SiteLoginReport
+ /**
+ * Restarts a service.
+ */
+ func restartService(name: String) async throws -> SpaceServiceInfo
+
/**
* Which way this Space's calls go now (see [`super::spacesd::SpacesdClient::route`]):
* `local …`, `direct …`, `relay …`, `mesh direct <ip:port> rtt <ms> ms`,
@@ -9121,6 +9143,11 @@ public protocol SpaceProtocol: AnyObject, Sendable {
*/
func sendFile(localPath: String, options: SpaceSendFileOptions) async throws -> SpaceSendFileReport
+ /**
+ * The end of a service's log (`tail_bytes` `None`: 64 KiB).
+ */
+ func serviceLogs(name: String, tailBytes: UInt64?) async throws -> String
+
/**
* The MCP services this Space exposes: `driver` when its spacesd has
* the tool registry, then every declared service (reached over generic
@@ -9160,11 +9187,21 @@ public protocol SpaceProtocol: AnyObject, Sendable {
*/
func startHotspot(setSystemProxy: Bool?, bypass: [String]?) async throws -> SpaceHotspotStatus
+ /**
+ * Starts a stopped service.
+ */
+ func startService(name: String) async throws -> SpaceServiceInfo
+
/**
* Stops this Space's hotspot. Returns the stopped Space ids.
*/
func stopHotspot() async throws -> [String]
+ /**
+ * Stops a service and keeps it stopped (also across a reboot).
+ */
+ func stopService(name: String) async throws -> SpaceServiceInfo
+
/**
* Opens a media session and delivers keyframe-gated encoded frames
* and audio to the sinks (one delivery thread; decoding stays with the
@@ -9631,6 +9668,26 @@ open func closeStream(mediaSessionId: String)async throws {
)
}
+ /**
+ * Stops a service and forgets it (its logs go too).
+ */
+open func deleteService(name: String)async throws {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_space_delete_service(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(name)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_void,
+ completeFunc: ffi_cua_sdk_rust_future_complete_void,
+ freeFunc: ffi_cua_sdk_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* The Space's displays, primary first, with their resolution in
* physical pixels.
@@ -9811,6 +9868,26 @@ open func joinPresence(identity: PresenceIdentity, timeoutMs: UInt64?)async thro
)
}
+ /**
+ * This Space's services.
+ */
+open func keptServices()async throws -> [SpaceServiceInfo] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_space_kept_services(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeSpaceServiceInfo.lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Tools of the Space's MCP service (`driver`, the default).
*/
@@ -9852,6 +9929,28 @@ open func openStream(options: SpaceStreamOptions)async throws -> SpaceStreamTic
)
}
+ /**
+ * Keeps a command running in this Space (replacing a service of that
+ * name): restarted by its policy when it ends or fails its health
+ * check, started when the Space boots, its output kept in a log file.
+ */
+open func putService(def: SpaceServiceDef)async throws -> SpaceServiceInfo {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_space_put_service(
+ self.uniffiCloneHandle(),
+ FfiConverterTypeSpaceServiceDef_lower(def)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeSpaceServiceInfo_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Signs in to a site in this Space's browser with a password the user
* saved in the Cua Keyvault. The first call files a request
@@ -9877,6 +9976,26 @@ open func requestSiteLogin(url: String, options: SiteLoginOptions?)async throws
)
}
+ /**
+ * Restarts a service.
+ */
+open func restartService(name: String)async throws -> SpaceServiceInfo {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_space_restart_service(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(name)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeSpaceServiceInfo_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Which way this Space's calls go now (see [`super::spacesd::SpacesdClient::route`]):
* `local …`, `direct …`, `relay …`, `mesh direct <ip:port> rtt <ms> ms`,
@@ -9944,6 +10063,26 @@ open func sendFile(localPath: String, options: SpaceSendFileOptions)async throws
)
}
+ /**
+ * The end of a service's log (`tail_bytes` `None`: 64 KiB).
+ */
+open func serviceLogs(name: String, tailBytes: UInt64?)async throws -> String {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_space_service_logs(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(name),FfiConverterOptionUInt64.lower(tailBytes)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterString.lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* The MCP services this Space exposes: `driver` when its spacesd has
* the tool registry, then every declared service (reached over generic
@@ -10055,6 +10194,26 @@ open func startHotspot(setSystemProxy: Bool?, bypass: [String]?)async throws ->
)
}
+ /**
+ * Starts a stopped service.
+ */
+open func startService(name: String)async throws -> SpaceServiceInfo {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_space_start_service(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(name)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeSpaceServiceInfo_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Stops this Space's hotspot. Returns the stopped Space ids.
*/
@@ -10075,6 +10234,26 @@ open func stopHotspot()async throws -> [String] {
)
}
+ /**
+ * Stops a service and keeps it stopped (also across a reboot).
+ */
+open func stopService(name: String)async throws -> SpaceServiceInfo {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_space_stop_service(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(name)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeSpaceServiceInfo_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Opens a media session and delivers keyframe-gated encoded frames
* and audio to the sinks (one delivery thread; decoding stays with the
@@ -11328,6 +11507,12 @@ public protocol SpacesProtocol: AnyObject, Sendable {
*/
func routines(agent: String?) async throws -> [RoutineInfo]
+ /**
+ * Marks the one-time notice about the new network defaults as shown
+ * for `space` ([`SpaceNetworkInfo::notice_pending`]).
+ */
+ func ackNetworkNotice(space: String) async throws
+
/**
* Adds a Space by URL (`http(s)://host:port`, `host:port`, or a
* Space id such as `local:<name>`) after a `GetCapabilities` handshake. Any other MCP
@@ -11393,7 +11578,8 @@ public protocol SpacesProtocol: AnyObject, Sendable {
/**
* Deletes a Space's sandbox and forgets it (a Space added by address
- * is only forgotten). Returns what happened.
+ * is only forgotten). Its child Spaces are deleted first. Returns what
+ * happened.
*/
func delete(space: String) async throws -> String
@@ -11404,6 +11590,12 @@ public protocol SpacesProtocol: AnyObject, Sendable {
*/
func deleteMany(ids: [String]) async throws -> [BulkResult]
+ /**
+ * [`Spaces::delete`], with `keep_children`: its child Spaces become
+ * top-level Spaces and keep running instead of being deleted first.
+ */
+ func deleteTree(space: String, keepChildren: Bool) async throws -> String
+
/**
* Deletes the named volume `name` and its files (their history stays
* in the Cua Volume). Refused while Spaces mount it unless `force`.
@@ -11478,6 +11670,19 @@ public protocol SpacesProtocol: AnyObject, Sendable {
*/
func machineHealth(machine: String?) async throws -> MachineHealth
+ /**
+ * A Space's network: its settings, what they open, where they are
+ * enforced (or why its network is cut), and what is always blocked.
+ */
+ func network(space: String) async throws -> SpaceNetworkInfo
+
+ /**
+ * Child Spaces whose parent is gone or out of reach. The cua daemon
+ * ends a child only on proof its parent is gone (after a grace period);
+ * the rest are listed here and never ended by it.
+ */
+ func orphans() async throws -> [SpaceOrphan]
+
/**
* Publishes `space` on the cua.ai relay as a machine of the signed-in
* account, the way `cua host setup` publishes this computer: the
@@ -11537,6 +11742,17 @@ public protocol SpacesProtocol: AnyObject, Sendable {
*/
func resources(visible: Bool) async throws -> ResourcesSnapshot
+ /**
+ * Lets a Space make child Spaces of its own, or stops it. While on,
+ * `cua`, the SDKs and the agent's tools in that Space create, list and
+ * delete Spaces that belong to it (on the same computer, never wider
+ * than it, ending no later than it), through a channel only it can
+ * reach. Off ends its capability at once; children it made keep running
+ * until deleted or their lifetime ends. Only for a Space the machine of
+ * this runtime runs itself.
+ */
+ func setChildren(space: String, enabled: Bool) async throws
+
/**
* Replaces a Space's egress policy; an empty one removes it (see
* [`EgressPolicy`]). Its host enforces it at once. A bad entry is
@@ -11554,6 +11770,22 @@ public protocol SpacesProtocol: AnyObject, Sendable {
*/
func setLifetime(space: String, seconds: UInt64, onExpire: String?) async throws -> Int64
+ /**
+ * Replaces a Space's network settings (see [`NetworkSettings`]). A
+ * child stays within its parent's unless `widen`; `tree` gives its
+ * children the same settings. They hold at once where the runtime can
+ * change a running guest's network, else from its next start
+ * (`applied`). A Space another computer runs is `Unsupported`.
+ */
+ func setNetwork(space: String, settings: NetworkSettings, widen: Bool, tree: Bool) async throws -> SetNetworkResult
+
+ /**
+ * Sets the budget of `space`'s tree: how many child Spaces, vCPUs and
+ * memory its children may hold at once, and what they may cost. A child
+ * that does not fit is refused with what is left. All `None` removes it.
+ */
+ func setTreeBudget(space: String, limits: TreeBudgetLimits) async throws -> TreeBudget
+
/**
* A connected handle to a registered Space.
*/
@@ -11584,6 +11816,12 @@ public protocol SpacesProtocol: AnyObject, Sendable {
*/
func suspend(space: String) async throws -> SpacePowerReport
+ /**
+ * The budget of `space`'s tree (any Space of it) and what its
+ * children use now. Kept by the cua daemon.
+ */
+ func treeBudget(space: String) async throws -> TreeBudget
+
/**
* `volume_approve`: the request becomes a grant (with presence).
*/
@@ -12541,6 +12779,27 @@ open func routines(agent: String?)async throws -> [RoutineInfo] {
)
}
+ /**
+ * Marks the one-time notice about the new network defaults as shown
+ * for `space` ([`SpaceNetworkInfo::notice_pending`]).
+ */
+open func ackNetworkNotice(space: String)async throws {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_spaces_ack_network_notice(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(space)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_void,
+ completeFunc: ffi_cua_sdk_rust_future_complete_void,
+ freeFunc: ffi_cua_sdk_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Adds a Space by URL (`http(s)://host:port`, `host:port`, or a
* Space id such as `local:<name>`) after a `GetCapabilities` handshake. Any other MCP
@@ -12726,7 +12985,8 @@ open func createWithProgress(options: SpaceCreateOptions, listener: SpaceCreateL
/**
* Deletes a Space's sandbox and forgets it (a Space added by address
- * is only forgotten). Returns what happened.
+ * is only forgotten). Its child Spaces are deleted first. Returns what
+ * happened.
*/
open func delete(space: String)async throws -> String {
return
@@ -12767,6 +13027,27 @@ open func deleteMany(ids: [String])async throws -> [BulkResult] {
)
}
+ /**
+ * [`Spaces::delete`], with `keep_children`: its child Spaces become
+ * top-level Spaces and keep running instead of being deleted first.
+ */
+open func deleteTree(space: String, keepChildren: Bool)async throws -> String {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_spaces_delete_tree(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(space),FfiConverterBool.lower(keepChildren)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterString.lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Deletes the named volume `name` and its files (their history stays
* in the Cua Volume). Refused while Spaces mount it unless `force`.
@@ -12976,6 +13257,49 @@ open func machineHealth(machine: String?)async throws -> MachineHealth {
)
}
+ /**
+ * A Space's network: its settings, what they open, where they are
+ * enforced (or why its network is cut), and what is always blocked.
+ */
+open func network(space: String)async throws -> SpaceNetworkInfo {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_spaces_network(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(space)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeSpaceNetworkInfo_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
+ /**
+ * Child Spaces whose parent is gone or out of reach. The cua daemon
+ * ends a child only on proof its parent is gone (after a grace period);
+ * the rest are listed here and never ended by it.
+ */
+open func orphans()async throws -> [SpaceOrphan] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_spaces_orphans(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeSpaceOrphan.lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Publishes `space` on the cua.ai relay as a machine of the signed-in
* account, the way `cua host setup` publishes this computer: the
@@ -13140,6 +13464,32 @@ open func resources(visible: Bool)async throws -> ResourcesSnapshot {
)
}
+ /**
+ * Lets a Space make child Spaces of its own, or stops it. While on,
+ * `cua`, the SDKs and the agent's tools in that Space create, list and
+ * delete Spaces that belong to it (on the same computer, never wider
+ * than it, ending no later than it), through a channel only it can
+ * reach. Off ends its capability at once; children it made keep running
+ * until deleted or their lifetime ends. Only for a Space the machine of
+ * this runtime runs itself.
+ */
+open func setChildren(space: String, enabled: Bool)async throws {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_spaces_set_children(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(space),FfiConverterBool.lower(enabled)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_void,
+ completeFunc: ffi_cua_sdk_rust_future_complete_void,
+ freeFunc: ffi_cua_sdk_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Replaces a Space's egress policy; an empty one removes it (see
* [`EgressPolicy`]). Its host enforces it at once. A bad entry is
@@ -13187,6 +13537,52 @@ open func setLifetime(space: String, seconds: UInt64, onExpire: String?)async th
)
}
+ /**
+ * Replaces a Space's network settings (see [`NetworkSettings`]). A
+ * child stays within its parent's unless `widen`; `tree` gives its
+ * children the same settings. They hold at once where the runtime can
+ * change a running guest's network, else from its next start
+ * (`applied`). A Space another computer runs is `Unsupported`.
+ */
+open func setNetwork(space: String, settings: NetworkSettings, widen: Bool, tree: Bool)async throws -> SetNetworkResult {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_spaces_set_network(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(space),FfiConverterTypeNetworkSettings_lower(settings),FfiConverterBool.lower(widen),FfiConverterBool.lower(tree)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeSetNetworkResult_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
+ /**
+ * Sets the budget of `space`'s tree: how many child Spaces, vCPUs and
+ * memory its children may hold at once, and what they may cost. A child
+ * that does not fit is refused with what is left. All `None` removes it.
+ */
+open func setTreeBudget(space: String, limits: TreeBudgetLimits)async throws -> TreeBudget {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_spaces_set_tree_budget(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(space),FfiConverterTypeTreeBudgetLimits_lower(limits)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeTreeBudget_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* A connected handle to a registered Space.
*/
@@ -13277,6 +13673,27 @@ open func suspend(space: String)async throws -> SpacePowerReport {
)
}
+ /**
+ * The budget of `space`'s tree (any Space of it) and what its
+ * children use now. Kept by the cua daemon.
+ */
+open func treeBudget(space: String)async throws -> TreeBudget {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_spaces_tree_budget(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(space)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeTreeBudget_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* `volume_approve`: the request becomes a grant (with presence).
*/
@@ -30718,6 +31135,145 @@ public func FfiConverterTypeNamedVolume_lower(_ value: NamedVolume) -> RustBuffe
}
+/**
+ * A Space's network settings: a preset and the user's own lists. The host
+ * the Space runs on compiles them to rules it enforces outside the guest.
+ *
+ * - `internet` (the default): the public internet and the Space's own
+ * tree; this computer, your local network, cloud metadata, other trees
+ * and the cua daemon are blocked;
+ * - `none`: no network;
+ * - `localhost`: `internet`, plus this computer's localhost on
+ * `localhost_ports` (every port only with `all_localhost_ports`);
+ * - `lan`: `internet`, plus your local network (not this computer);
+ * - `custom`: `custom_base` (`internet` or `none`) plus `allow` and `deny`;
+ * - `unprotected`: everything but cloud metadata, other trees and the
+ * daemon.
+ *
+ * A runtime that can't protect a Space yet starts it without network and
+ * says so (`SpaceInfo.network_note`); it never starts it open unless the
+ * preset is `unprotected`.
+ */
+public struct NetworkSettings: Equatable, Hashable {
+ /**
+ * `internet`, `none`, `localhost`, `lan`, `custom` or `unprotected`;
+ * empty is `internet`.
+ */
+ public var preset: String
+ /**
+ * `localhost`: the ports of this computer's localhost the Space may
+ * reach.
+ */
+ public var localhostPorts: [UInt16]
+ /**
+ * `localhost`: every port (the daemon's stay blocked).
+ */
+ public var allLocalhostPorts: Bool
+ /**
+ * Destinations that stay reachable (addresses or CIDRs).
+ */
+ public var allow: [String]
+ /**
+ * Destinations that are blocked (addresses, CIDRs or `all`).
+ */
+ public var deny: [String]
+ /**
+ * `custom`: what it starts from, `internet` (empty) or `none`.
+ */
+ public var customBase: String
+ /**
+ * Set when the Space was allowed more than its parent: who and when.
+ */
+ public var widenedBy: String?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * `internet`, `none`, `localhost`, `lan`, `custom` or `unprotected`;
+ * empty is `internet`.
+ */preset: String = "",
+ /**
+ * `localhost`: the ports of this computer's localhost the Space may
+ * reach.
+ */localhostPorts: [UInt16] = [],
+ /**
+ * `localhost`: every port (the daemon's stay blocked).
+ */allLocalhostPorts: Bool = false,
+ /**
+ * Destinations that stay reachable (addresses or CIDRs).
+ */allow: [String] = [],
+ /**
+ * Destinations that are blocked (addresses, CIDRs or `all`).
+ */deny: [String] = [],
+ /**
+ * `custom`: what it starts from, `internet` (empty) or `none`.
+ */customBase: String = "",
+ /**
+ * Set when the Space was allowed more than its parent: who and when.
+ */widenedBy: String? = nil) {
+ self.preset = preset
+ self.localhostPorts = localhostPorts
+ self.allLocalhostPorts = allLocalhostPorts
+ self.allow = allow
+ self.deny = deny
+ self.customBase = customBase
+ self.widenedBy = widenedBy
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension NetworkSettings: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeNetworkSettings: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> NetworkSettings {
+ return
+ try NetworkSettings(
+ preset: FfiConverterString.read(from: &buf),
+ localhostPorts: FfiConverterSequenceUInt16.read(from: &buf),
+ allLocalhostPorts: FfiConverterBool.read(from: &buf),
+ allow: FfiConverterSequenceString.read(from: &buf),
+ deny: FfiConverterSequenceString.read(from: &buf),
+ customBase: FfiConverterString.read(from: &buf),
+ widenedBy: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: NetworkSettings, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.preset, into: &buf)
+ FfiConverterSequenceUInt16.write(value.localhostPorts, into: &buf)
+ FfiConverterBool.write(value.allLocalhostPorts, into: &buf)
+ FfiConverterSequenceString.write(value.allow, into: &buf)
+ FfiConverterSequenceString.write(value.deny, into: &buf)
+ FfiConverterString.write(value.customBase, into: &buf)
+ FfiConverterOptionString.write(value.widenedBy, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeNetworkSettings_lift(_ buf: RustBuffer) throws -> NetworkSettings {
+ return try FfiConverterTypeNetworkSettings.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeNetworkSettings_lower(_ value: NetworkSettings) -> RustBuffer {
+ return FfiConverterTypeNetworkSettings.lower(value)
+}
+
+
/**
* One entry of the notifications feed.
*/
@@ -36029,6 +36585,75 @@ public func FfiConverterTypeServiceEndpoint_lower(_ value: ServiceEndpoint) -> R
}
+/**
+ * What [`Spaces::set_network`] did.
+ */
+public struct SetNetworkResult: Equatable, Hashable {
+ /**
+ * `now` (the running guest is under them) or `next_start`.
+ */
+ public var applied: String
+ /**
+ * The Space's network after the change.
+ */
+ public var network: SpaceNetworkInfo
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * `now` (the running guest is under them) or `next_start`.
+ */applied: String,
+ /**
+ * The Space's network after the change.
+ */network: SpaceNetworkInfo) {
+ self.applied = applied
+ self.network = network
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SetNetworkResult: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSetNetworkResult: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SetNetworkResult {
+ return
+ try SetNetworkResult(
+ applied: FfiConverterString.read(from: &buf),
+ network: FfiConverterTypeSpaceNetworkInfo.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: SetNetworkResult, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.applied, into: &buf)
+ FfiConverterTypeSpaceNetworkInfo.write(value.network, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSetNetworkResult_lift(_ buf: RustBuffer) throws -> SetNetworkResult {
+ return try FfiConverterTypeSetNetworkResult.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSetNetworkResult_lower(_ value: SetNetworkResult) -> RustBuffer {
+ return FfiConverterTypeSetNetworkResult.lower(value)
+}
+
+
/**
* One setup step.
*/
@@ -37579,6 +38204,22 @@ public struct SpaceCreateOptions: Equatable, Hashable {
* to enforce it makes the create fail.
*/
public var egress: EgressPolicy?
+ /**
+ * Network settings (see [`NetworkSettings`]). `None`: what `network`
+ * and `egress` say (`internet` when neither says anything). A daemon
+ * too old to keep them makes the create fail.
+ */
+ public var networkSettings: NetworkSettings?
+ /**
+ * Create it as a child of this Space (id or name): its network is no
+ * more open than its parent's, and it joins the parent's tree.
+ */
+ public var parent: String?
+ /**
+ * With `parent`: let its network be more open than its parent's
+ * (recorded on the Space).
+ */
+ public var widen: Bool?
/**
* With `on` a linked cloud (`aws`, `hetzner`, ...): the machine type
* its host must be (`c7g.xlarge`, `cax41`), a pin of the elastic
@@ -37589,6 +38230,11 @@ public struct SpaceCreateOptions: Equatable, Hashable {
* With `on` a linked cloud: the region its host must be in.
*/
public var region: String?
+ /**
+ * Lets the Space make child Spaces of its own ([`Spaces::set_children`]).
+ * `None`: off. Only a Space the machine of the runtime runs itself.
+ */
+ public var children: Bool?
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -37719,6 +38365,19 @@ public struct SpaceCreateOptions: Equatable, Hashable {
* created. Not with `durable`, `reuse` or `wait = false`; a daemon too old
* to enforce it makes the create fail.
*/egress: EgressPolicy? = nil,
+ /**
+ * Network settings (see [`NetworkSettings`]). `None`: what `network`
+ * and `egress` say (`internet` when neither says anything). A daemon
+ * too old to keep them makes the create fail.
+ */networkSettings: NetworkSettings? = nil,
+ /**
+ * Create it as a child of this Space (id or name): its network is no
+ * more open than its parent's, and it joins the parent's tree.
+ */parent: String? = nil,
+ /**
+ * With `parent`: let its network be more open than its parent's
+ * (recorded on the Space).
+ */widen: Bool? = nil,
/**
* With `on` a linked cloud (`aws`, `hetzner`, ...): the machine type
* its host must be (`c7g.xlarge`, `cax41`), a pin of the elastic
@@ -37726,7 +38385,11 @@ public struct SpaceCreateOptions: Equatable, Hashable {
*/instanceType: String? = nil,
/**
* With `on` a linked cloud: the region its host must be in.
- */region: String? = nil) {
+ */region: String? = nil,
+ /**
+ * Lets the Space make child Spaces of its own ([`Spaces::set_children`]).
+ * `None`: off. Only a Space the machine of the runtime runs itself.
+ */children: Bool? = nil) {
self.image = image
self.on = on
self.kind = kind
@@ -37753,8 +38416,12 @@ public struct SpaceCreateOptions: Equatable, Hashable {
self.network = network
self.labels = labels
self.egress = egress
+ self.networkSettings = networkSettings
+ self.parent = parent
+ self.widen = widen
self.instanceType = instanceType
self.region = region
+ self.children = children
}
@@ -37799,8 +38466,12 @@ public struct FfiConverterTypeSpaceCreateOptions: FfiConverterRustBuffer {
network: FfiConverterOptionString.read(from: &buf),
labels: FfiConverterDictionaryStringString.read(from: &buf),
egress: FfiConverterOptionTypeEgressPolicy.read(from: &buf),
+ networkSettings: FfiConverterOptionTypeNetworkSettings.read(from: &buf),
+ parent: FfiConverterOptionString.read(from: &buf),
+ widen: FfiConverterOptionBool.read(from: &buf),
instanceType: FfiConverterOptionString.read(from: &buf),
- region: FfiConverterOptionString.read(from: &buf)
+ region: FfiConverterOptionString.read(from: &buf),
+ children: FfiConverterOptionBool.read(from: &buf)
)
}
@@ -37831,8 +38502,12 @@ public struct FfiConverterTypeSpaceCreateOptions: FfiConverterRustBuffer {
FfiConverterOptionString.write(value.network, into: &buf)
FfiConverterDictionaryStringString.write(value.labels, into: &buf)
FfiConverterOptionTypeEgressPolicy.write(value.egress, into: &buf)
+ FfiConverterOptionTypeNetworkSettings.write(value.networkSettings, into: &buf)
+ FfiConverterOptionString.write(value.parent, into: &buf)
+ FfiConverterOptionBool.write(value.widen, into: &buf)
FfiConverterOptionString.write(value.instanceType, into: &buf)
FfiConverterOptionString.write(value.region, into: &buf)
+ FfiConverterOptionBool.write(value.children, into: &buf)
}
}
@@ -38566,6 +39241,36 @@ public struct SpaceInfo: Equatable, Hashable {
* Where `egress` is enforced; `None` without one.
*/
public var egressEnforced: EgressEnforcement?
+ /**
+ * Its network settings; `None` for a Space this computer keeps no
+ * record of, or one created before they existed (it gets them on its
+ * next start).
+ */
+ public var network: NetworkSettings?
+ /**
+ * Why its network is not what was asked, in plain words (a runtime
+ * that can't protect it yet started it without network); `None`
+ * otherwise.
+ */
+ public var networkNote: String?
+ /**
+ * An update changed its network settings (an old Space moved to the
+ * new defaults): say so once.
+ */
+ public var networkNoticePending: Bool
+ /**
+ * The Space it was created from, by id; `None` for a top-level Space.
+ */
+ public var parent: String?
+ /**
+ * The top-level Space of its tree, by id; `None` for a top-level
+ * Space.
+ */
+ public var root: String?
+ /**
+ * How far below its tree's top-level Space it is (0: top-level).
+ */
+ public var depth: UInt32
/**
* Named volumes mounted in the Space (see
* [`SpaceCreateOptions::volumes`]).
@@ -38697,6 +39402,30 @@ public struct SpaceInfo: Equatable, Hashable {
/**
* Where `egress` is enforced; `None` without one.
*/egressEnforced: EgressEnforcement?,
+ /**
+ * Its network settings; `None` for a Space this computer keeps no
+ * record of, or one created before they existed (it gets them on its
+ * next start).
+ */network: NetworkSettings?,
+ /**
+ * Why its network is not what was asked, in plain words (a runtime
+ * that can't protect it yet started it without network); `None`
+ * otherwise.
+ */networkNote: String?,
+ /**
+ * An update changed its network settings (an old Space moved to the
+ * new defaults): say so once.
+ */networkNoticePending: Bool,
+ /**
+ * The Space it was created from, by id; `None` for a top-level Space.
+ */parent: String?,
+ /**
+ * The top-level Space of its tree, by id; `None` for a top-level
+ * Space.
+ */root: String?,
+ /**
+ * How far below its tree's top-level Space it is (0: top-level).
+ */depth: UInt32,
/**
* Named volumes mounted in the Space (see
* [`SpaceCreateOptions::volumes`]).
@@ -38735,6 +39464,12 @@ public struct SpaceInfo: Equatable, Hashable {
self.createdAtUnix = createdAtUnix
self.egress = egress
self.egressEnforced = egressEnforced
+ self.network = network
+ self.networkNote = networkNote
+ self.networkNoticePending = networkNoticePending
+ self.parent = parent
+ self.root = root
+ self.depth = depth
self.volumes = volumes
self.sharing = sharing
}
@@ -38785,6 +39520,12 @@ public struct FfiConverterTypeSpaceInfo: FfiConverterRustBuffer {
createdAtUnix: FfiConverterInt64.read(from: &buf),
egress: FfiConverterTypeEgressPolicy.read(from: &buf),
egressEnforced: FfiConverterOptionTypeEgressEnforcement.read(from: &buf),
+ network: FfiConverterOptionTypeNetworkSettings.read(from: &buf),
+ networkNote: FfiConverterOptionString.read(from: &buf),
+ networkNoticePending: FfiConverterBool.read(from: &buf),
+ parent: FfiConverterOptionString.read(from: &buf),
+ root: FfiConverterOptionString.read(from: &buf),
+ depth: FfiConverterUInt32.read(from: &buf),
volumes: FfiConverterSequenceTypeVolumeMount.read(from: &buf),
sharing: FfiConverterOptionTypeSpaceSharing.read(from: &buf)
)
@@ -38821,6 +39562,12 @@ public struct FfiConverterTypeSpaceInfo: FfiConverterRustBuffer {
FfiConverterInt64.write(value.createdAtUnix, into: &buf)
FfiConverterTypeEgressPolicy.write(value.egress, into: &buf)
FfiConverterOptionTypeEgressEnforcement.write(value.egressEnforced, into: &buf)
+ FfiConverterOptionTypeNetworkSettings.write(value.network, into: &buf)
+ FfiConverterOptionString.write(value.networkNote, into: &buf)
+ FfiConverterBool.write(value.networkNoticePending, into: &buf)
+ FfiConverterOptionString.write(value.parent, into: &buf)
+ FfiConverterOptionString.write(value.root, into: &buf)
+ FfiConverterUInt32.write(value.depth, into: &buf)
FfiConverterSequenceTypeVolumeMount.write(value.volumes, into: &buf)
FfiConverterOptionTypeSpaceSharing.write(value.sharing, into: &buf)
}
@@ -38961,6 +39708,258 @@ public func FfiConverterTypeSpaceList_lower(_ value: SpaceList) -> RustBuffer {
}
+/**
+ * A Space's network as `cua network show` says it ([`Spaces::network`]).
+ */
+public struct SpaceNetworkInfo: Equatable, Hashable {
+ /**
+ * Its settings.
+ */
+ public var settings: NetworkSettings
+ /**
+ * One plain line ("Internet only").
+ */
+ public var summary: String
+ /**
+ * What the settings open beyond `internet`, one plain line each.
+ */
+ public var widenings: [String]
+ /**
+ * `enforced` (rules on the host, outside the guest), `no_network`
+ * (its runtime can't protect it yet), `open` (No protection) or
+ * `refused`; empty when unknown (a Space another computer runs).
+ */
+ public var enforcement: String
+ /**
+ * Where the rules are enforced, or why its network is cut.
+ */
+ public var point: String
+ /**
+ * Why its network is not what was asked; `None` otherwise.
+ */
+ public var note: String?
+ /**
+ * Its parent and its tree's top-level Space; `None` for a top-level
+ * Space.
+ */
+ public var parent: String?
+ public var root: String?
+ /**
+ * What no setting opens, in plain words.
+ */
+ public var alwaysBlocked: [String]
+ /**
+ * An update changed its settings: say so once.
+ */
+ public var noticePending: Bool
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Its settings.
+ */settings: NetworkSettings,
+ /**
+ * One plain line ("Internet only").
+ */summary: String,
+ /**
+ * What the settings open beyond `internet`, one plain line each.
+ */widenings: [String],
+ /**
+ * `enforced` (rules on the host, outside the guest), `no_network`
+ * (its runtime can't protect it yet), `open` (No protection) or
+ * `refused`; empty when unknown (a Space another computer runs).
+ */enforcement: String,
+ /**
+ * Where the rules are enforced, or why its network is cut.
+ */point: String,
+ /**
+ * Why its network is not what was asked; `None` otherwise.
+ */note: String?,
+ /**
+ * Its parent and its tree's top-level Space; `None` for a top-level
+ * Space.
+ */parent: String?, root: String?,
+ /**
+ * What no setting opens, in plain words.
+ */alwaysBlocked: [String],
+ /**
+ * An update changed its settings: say so once.
+ */noticePending: Bool) {
+ self.settings = settings
+ self.summary = summary
+ self.widenings = widenings
+ self.enforcement = enforcement
+ self.point = point
+ self.note = note
+ self.parent = parent
+ self.root = root
+ self.alwaysBlocked = alwaysBlocked
+ self.noticePending = noticePending
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SpaceNetworkInfo: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSpaceNetworkInfo: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SpaceNetworkInfo {
+ return
+ try SpaceNetworkInfo(
+ settings: FfiConverterTypeNetworkSettings.read(from: &buf),
+ summary: FfiConverterString.read(from: &buf),
+ widenings: FfiConverterSequenceString.read(from: &buf),
+ enforcement: FfiConverterString.read(from: &buf),
+ point: FfiConverterString.read(from: &buf),
+ note: FfiConverterOptionString.read(from: &buf),
+ parent: FfiConverterOptionString.read(from: &buf),
+ root: FfiConverterOptionString.read(from: &buf),
+ alwaysBlocked: FfiConverterSequenceString.read(from: &buf),
+ noticePending: FfiConverterBool.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: SpaceNetworkInfo, into buf: inout [UInt8]) {
+ FfiConverterTypeNetworkSettings.write(value.settings, into: &buf)
+ FfiConverterString.write(value.summary, into: &buf)
+ FfiConverterSequenceString.write(value.widenings, into: &buf)
+ FfiConverterString.write(value.enforcement, into: &buf)
+ FfiConverterString.write(value.point, into: &buf)
+ FfiConverterOptionString.write(value.note, into: &buf)
+ FfiConverterOptionString.write(value.parent, into: &buf)
+ FfiConverterOptionString.write(value.root, into: &buf)
+ FfiConverterSequenceString.write(value.alwaysBlocked, into: &buf)
+ FfiConverterBool.write(value.noticePending, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSpaceNetworkInfo_lift(_ buf: RustBuffer) throws -> SpaceNetworkInfo {
+ return try FfiConverterTypeSpaceNetworkInfo.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSpaceNetworkInfo_lower(_ value: SpaceNetworkInfo) -> RustBuffer {
+ return FfiConverterTypeSpaceNetworkInfo.lower(value)
+}
+
+
+/**
+ * A child Space whose parent is gone or out of reach ([`Spaces::orphans`]).
+ */
+public struct SpaceOrphan: Equatable, Hashable {
+ /**
+ * The child.
+ */
+ public var space: String
+ /**
+ * Its parent's id.
+ */
+ public var parent: String
+ /**
+ * `ending` (its parent is provably gone: it ends after the grace) or
+ * `listed` (not this computer's to judge: it stays until deleted or its
+ * own lifetime ends).
+ */
+ public var state: String
+ /**
+ * Why.
+ */
+ public var why: String
+ /**
+ * Seconds until it ends (`ending` only).
+ */
+ public var endsInSecs: Int64
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * The child.
+ */space: String,
+ /**
+ * Its parent's id.
+ */parent: String,
+ /**
+ * `ending` (its parent is provably gone: it ends after the grace) or
+ * `listed` (not this computer's to judge: it stays until deleted or its
+ * own lifetime ends).
+ */state: String,
+ /**
+ * Why.
+ */why: String,
+ /**
+ * Seconds until it ends (`ending` only).
+ */endsInSecs: Int64) {
+ self.space = space
+ self.parent = parent
+ self.state = state
+ self.why = why
+ self.endsInSecs = endsInSecs
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SpaceOrphan: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSpaceOrphan: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SpaceOrphan {
+ return
+ try SpaceOrphan(
+ space: FfiConverterString.read(from: &buf),
+ parent: FfiConverterString.read(from: &buf),
+ state: FfiConverterString.read(from: &buf),
+ why: FfiConverterString.read(from: &buf),
+ endsInSecs: FfiConverterInt64.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: SpaceOrphan, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.space, into: &buf)
+ FfiConverterString.write(value.parent, into: &buf)
+ FfiConverterString.write(value.state, into: &buf)
+ FfiConverterString.write(value.why, into: &buf)
+ FfiConverterInt64.write(value.endsInSecs, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSpaceOrphan_lift(_ buf: RustBuffer) throws -> SpaceOrphan {
+ return try FfiConverterTypeSpaceOrphan.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSpaceOrphan_lower(_ value: SpaceOrphan) -> RustBuffer {
+ return FfiConverterTypeSpaceOrphan.lower(value)
+}
+
+
/**
* What [`Spaces::stop`] or [`Spaces::start`] did.
*/
@@ -39686,6 +40685,377 @@ public func FfiConverterTypeSpaceSentFile_lower(_ value: SpaceSentFile) -> RustB
}
+/**
+ * A command a Space keeps running ([`Space::put_service`]).
+ */
+public struct SpaceServiceDef: Equatable, Hashable {
+ /**
+ * Name: lowercase letters, digits, `-`, `_`, `.` (1 to 63).
+ */
+ public var name: String
+ /**
+ * The shell command line it runs.
+ */
+ public var command: String
+ /**
+ * Extra environment.
+ */
+ public var env: [String: String]
+ /**
+ * Working directory.
+ */
+ public var cwd: String?
+ /**
+ * When it is started again: `always` (default), `on-failure` or
+ * `never`.
+ */
+ public var restart: String?
+ /**
+ * A health check; failing it restarts the service.
+ */
+ public var probe: SpaceServiceProbe?
+ /**
+ * Start it when the Space boots. `None`: yes.
+ */
+ public var startOnBoot: Bool?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Name: lowercase letters, digits, `-`, `_`, `.` (1 to 63).
+ */name: String,
+ /**
+ * The shell command line it runs.
+ */command: String,
+ /**
+ * Extra environment.
+ */env: [String: String] = [:],
+ /**
+ * Working directory.
+ */cwd: String? = nil,
+ /**
+ * When it is started again: `always` (default), `on-failure` or
+ * `never`.
+ */restart: String? = nil,
+ /**
+ * A health check; failing it restarts the service.
+ */probe: SpaceServiceProbe? = nil,
+ /**
+ * Start it when the Space boots. `None`: yes.
+ */startOnBoot: Bool? = nil) {
+ self.name = name
+ self.command = command
+ self.env = env
+ self.cwd = cwd
+ self.restart = restart
+ self.probe = probe
+ self.startOnBoot = startOnBoot
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SpaceServiceDef: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSpaceServiceDef: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SpaceServiceDef {
+ return
+ try SpaceServiceDef(
+ name: FfiConverterString.read(from: &buf),
+ command: FfiConverterString.read(from: &buf),
+ env: FfiConverterDictionaryStringString.read(from: &buf),
+ cwd: FfiConverterOptionString.read(from: &buf),
+ restart: FfiConverterOptionString.read(from: &buf),
+ probe: FfiConverterOptionTypeSpaceServiceProbe.read(from: &buf),
+ startOnBoot: FfiConverterOptionBool.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: SpaceServiceDef, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterString.write(value.command, into: &buf)
+ FfiConverterDictionaryStringString.write(value.env, into: &buf)
+ FfiConverterOptionString.write(value.cwd, into: &buf)
+ FfiConverterOptionString.write(value.restart, into: &buf)
+ FfiConverterOptionTypeSpaceServiceProbe.write(value.probe, into: &buf)
+ FfiConverterOptionBool.write(value.startOnBoot, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSpaceServiceDef_lift(_ buf: RustBuffer) throws -> SpaceServiceDef {
+ return try FfiConverterTypeSpaceServiceDef.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSpaceServiceDef_lower(_ value: SpaceServiceDef) -> RustBuffer {
+ return FfiConverterTypeSpaceServiceDef.lower(value)
+}
+
+
+/**
+ * A service and how it is doing ([`Space::services`]).
+ */
+public struct SpaceServiceInfo: Equatable, Hashable {
+ /**
+ * Name.
+ */
+ public var name: String
+ /**
+ * The command line.
+ */
+ public var command: String
+ /**
+ * `starting`, `running`, `unhealthy`, `backoff`, `stopped`, `exited`
+ * or `failed`.
+ */
+ public var state: String
+ /**
+ * Its process, while it runs.
+ */
+ public var pid: UInt32
+ /**
+ * Starts after the first.
+ */
+ public var restarts: UInt32
+ /**
+ * How the last process ended, if one did.
+ */
+ public var lastEnd: String
+ /**
+ * The last failed health check, if the last one failed.
+ */
+ public var probeError: String
+ /**
+ * `always`, `on-failure` or `never`.
+ */
+ public var restart: String
+ /**
+ * Starts when the Space boots.
+ */
+ public var startOnBoot: Bool
+ /**
+ * Its log file in the Space.
+ */
+ public var logPath: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Name.
+ */name: String,
+ /**
+ * The command line.
+ */command: String,
+ /**
+ * `starting`, `running`, `unhealthy`, `backoff`, `stopped`, `exited`
+ * or `failed`.
+ */state: String,
+ /**
+ * Its process, while it runs.
+ */pid: UInt32,
+ /**
+ * Starts after the first.
+ */restarts: UInt32,
+ /**
+ * How the last process ended, if one did.
+ */lastEnd: String,
+ /**
+ * The last failed health check, if the last one failed.
+ */probeError: String,
+ /**
+ * `always`, `on-failure` or `never`.
+ */restart: String,
+ /**
+ * Starts when the Space boots.
+ */startOnBoot: Bool,
+ /**
+ * Its log file in the Space.
+ */logPath: String) {
+ self.name = name
+ self.command = command
+ self.state = state
+ self.pid = pid
+ self.restarts = restarts
+ self.lastEnd = lastEnd
+ self.probeError = probeError
+ self.restart = restart
+ self.startOnBoot = startOnBoot
+ self.logPath = logPath
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SpaceServiceInfo: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSpaceServiceInfo: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SpaceServiceInfo {
+ return
+ try SpaceServiceInfo(
+ name: FfiConverterString.read(from: &buf),
+ command: FfiConverterString.read(from: &buf),
+ state: FfiConverterString.read(from: &buf),
+ pid: FfiConverterUInt32.read(from: &buf),
+ restarts: FfiConverterUInt32.read(from: &buf),
+ lastEnd: FfiConverterString.read(from: &buf),
+ probeError: FfiConverterString.read(from: &buf),
+ restart: FfiConverterString.read(from: &buf),
+ startOnBoot: FfiConverterBool.read(from: &buf),
+ logPath: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: SpaceServiceInfo, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterString.write(value.command, into: &buf)
+ FfiConverterString.write(value.state, into: &buf)
+ FfiConverterUInt32.write(value.pid, into: &buf)
+ FfiConverterUInt32.write(value.restarts, into: &buf)
+ FfiConverterString.write(value.lastEnd, into: &buf)
+ FfiConverterString.write(value.probeError, into: &buf)
+ FfiConverterString.write(value.restart, into: &buf)
+ FfiConverterBool.write(value.startOnBoot, into: &buf)
+ FfiConverterString.write(value.logPath, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSpaceServiceInfo_lift(_ buf: RustBuffer) throws -> SpaceServiceInfo {
+ return try FfiConverterTypeSpaceServiceInfo.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSpaceServiceInfo_lower(_ value: SpaceServiceInfo) -> RustBuffer {
+ return FfiConverterTypeSpaceServiceInfo.lower(value)
+}
+
+
+/**
+ * A health check: exactly one of `http`, `tcp`, `command`.
+ */
+public struct SpaceServiceProbe: Equatable, Hashable {
+ /**
+ * A URL that answers 2xx or 3xx.
+ */
+ public var http: String?
+ /**
+ * `host:port` that accepts a TCP connection.
+ */
+ public var tcp: String?
+ /**
+ * A shell command that exits 0 when healthy.
+ */
+ public var command: String?
+ /**
+ * Seconds between checks (default 10).
+ */
+ public var intervalSecs: UInt64?
+ /**
+ * Failed checks in a row that restart it (default 3).
+ */
+ public var failures: UInt32?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * A URL that answers 2xx or 3xx.
+ */http: String? = nil,
+ /**
+ * `host:port` that accepts a TCP connection.
+ */tcp: String? = nil,
+ /**
+ * A shell command that exits 0 when healthy.
+ */command: String? = nil,
+ /**
+ * Seconds between checks (default 10).
+ */intervalSecs: UInt64? = nil,
+ /**
+ * Failed checks in a row that restart it (default 3).
+ */failures: UInt32? = nil) {
+ self.http = http
+ self.tcp = tcp
+ self.command = command
+ self.intervalSecs = intervalSecs
+ self.failures = failures
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SpaceServiceProbe: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSpaceServiceProbe: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SpaceServiceProbe {
+ return
+ try SpaceServiceProbe(
+ http: FfiConverterOptionString.read(from: &buf),
+ tcp: FfiConverterOptionString.read(from: &buf),
+ command: FfiConverterOptionString.read(from: &buf),
+ intervalSecs: FfiConverterOptionUInt64.read(from: &buf),
+ failures: FfiConverterOptionUInt32.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: SpaceServiceProbe, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.http, into: &buf)
+ FfiConverterOptionString.write(value.tcp, into: &buf)
+ FfiConverterOptionString.write(value.command, into: &buf)
+ FfiConverterOptionUInt64.write(value.intervalSecs, into: &buf)
+ FfiConverterOptionUInt32.write(value.failures, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSpaceServiceProbe_lift(_ buf: RustBuffer) throws -> SpaceServiceProbe {
+ return try FfiConverterTypeSpaceServiceProbe.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSpaceServiceProbe_lower(_ value: SpaceServiceProbe) -> RustBuffer {
+ return FfiConverterTypeSpaceServiceProbe.lower(value)
+}
+
+
/**
* One account a Space is shared with.
*/
@@ -43584,6 +44954,275 @@ public func FfiConverterTypeTransferResult_lower(_ value: TransferResult) -> Rus
}
+/**
+ * A tree's budget and what its children use ([`Spaces::tree_budget`]).
+ */
+public struct TreeBudget: Equatable, Hashable {
+ /**
+ * The tree's top-level Space.
+ */
+ public var root: String
+ /**
+ * What the owner set.
+ */
+ public var set: TreeBudgetLimits
+ /**
+ * Child Spaces it may hold at once.
+ */
+ public var maxSpaces: UInt32
+ /**
+ * vCPUs it may hold at once.
+ */
+ public var maxVcpus: UInt32
+ /**
+ * Memory it may hold at once (MiB).
+ */
+ public var maxMemoryMb: UInt64
+ /**
+ * Cost per hour it may run at.
+ */
+ public var usdPerHour: Double
+ /**
+ * Cost in total it may reach, when capped.
+ */
+ public var usdTotal: Double?
+ /**
+ * Child Spaces now.
+ */
+ public var spaces: UInt32
+ /**
+ * vCPUs they hold.
+ */
+ public var vcpus: UInt32
+ /**
+ * Memory they hold (MiB).
+ */
+ public var memoryMb: UInt64
+ /**
+ * Cost per hour they run at.
+ */
+ public var usdPerHourUsed: Double
+ /**
+ * What they have cost so far.
+ */
+ public var usdSpent: Double
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * The tree's top-level Space.
+ */root: String,
+ /**
+ * What the owner set.
+ */set: TreeBudgetLimits,
+ /**
+ * Child Spaces it may hold at once.
+ */maxSpaces: UInt32,
+ /**
+ * vCPUs it may hold at once.
+ */maxVcpus: UInt32,
+ /**
+ * Memory it may hold at once (MiB).
+ */maxMemoryMb: UInt64,
+ /**
+ * Cost per hour it may run at.
+ */usdPerHour: Double,
+ /**
+ * Cost in total it may reach, when capped.
+ */usdTotal: Double?,
+ /**
+ * Child Spaces now.
+ */spaces: UInt32,
+ /**
+ * vCPUs they hold.
+ */vcpus: UInt32,
+ /**
+ * Memory they hold (MiB).
+ */memoryMb: UInt64,
+ /**
+ * Cost per hour they run at.
+ */usdPerHourUsed: Double,
+ /**
+ * What they have cost so far.
+ */usdSpent: Double) {
+ self.root = root
+ self.set = set
+ self.maxSpaces = maxSpaces
+ self.maxVcpus = maxVcpus
+ self.maxMemoryMb = maxMemoryMb
+ self.usdPerHour = usdPerHour
+ self.usdTotal = usdTotal
+ self.spaces = spaces
+ self.vcpus = vcpus
+ self.memoryMb = memoryMb
+ self.usdPerHourUsed = usdPerHourUsed
+ self.usdSpent = usdSpent
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension TreeBudget: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeTreeBudget: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> TreeBudget {
+ return
+ try TreeBudget(
+ root: FfiConverterString.read(from: &buf),
+ set: FfiConverterTypeTreeBudgetLimits.read(from: &buf),
+ maxSpaces: FfiConverterUInt32.read(from: &buf),
+ maxVcpus: FfiConverterUInt32.read(from: &buf),
+ maxMemoryMb: FfiConverterUInt64.read(from: &buf),
+ usdPerHour: FfiConverterDouble.read(from: &buf),
+ usdTotal: FfiConverterOptionDouble.read(from: &buf),
+ spaces: FfiConverterUInt32.read(from: &buf),
+ vcpus: FfiConverterUInt32.read(from: &buf),
+ memoryMb: FfiConverterUInt64.read(from: &buf),
+ usdPerHourUsed: FfiConverterDouble.read(from: &buf),
+ usdSpent: FfiConverterDouble.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: TreeBudget, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.root, into: &buf)
+ FfiConverterTypeTreeBudgetLimits.write(value.set, into: &buf)
+ FfiConverterUInt32.write(value.maxSpaces, into: &buf)
+ FfiConverterUInt32.write(value.maxVcpus, into: &buf)
+ FfiConverterUInt64.write(value.maxMemoryMb, into: &buf)
+ FfiConverterDouble.write(value.usdPerHour, into: &buf)
+ FfiConverterOptionDouble.write(value.usdTotal, into: &buf)
+ FfiConverterUInt32.write(value.spaces, into: &buf)
+ FfiConverterUInt32.write(value.vcpus, into: &buf)
+ FfiConverterUInt64.write(value.memoryMb, into: &buf)
+ FfiConverterDouble.write(value.usdPerHourUsed, into: &buf)
+ FfiConverterDouble.write(value.usdSpent, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTreeBudget_lift(_ buf: RustBuffer) throws -> TreeBudget {
+ return try FfiConverterTypeTreeBudget.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTreeBudget_lower(_ value: TreeBudget) -> RustBuffer {
+ return FfiConverterTypeTreeBudget.lower(value)
+}
+
+
+/**
+ * What a tree's children may hold and cost ([`Spaces::set_tree_budget`]).
+ * `None`: the default.
+ */
+public struct TreeBudgetLimits: Equatable, Hashable {
+ /**
+ * Child Spaces at once (default 16).
+ */
+ public var maxSpaces: UInt32?
+ /**
+ * vCPUs at once (default 16).
+ */
+ public var maxVcpus: UInt32?
+ /**
+ * Memory at once, MiB (default 32768).
+ */
+ public var maxMemoryMb: UInt64?
+ /**
+ * Cost per hour, in linked clouds (default 2.0).
+ */
+ public var usdPerHour: Double?
+ /**
+ * Cost in total (default: none).
+ */
+ public var usdTotal: Double?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Child Spaces at once (default 16).
+ */maxSpaces: UInt32? = nil,
+ /**
+ * vCPUs at once (default 16).
+ */maxVcpus: UInt32? = nil,
+ /**
+ * Memory at once, MiB (default 32768).
+ */maxMemoryMb: UInt64? = nil,
+ /**
+ * Cost per hour, in linked clouds (default 2.0).
+ */usdPerHour: Double? = nil,
+ /**
+ * Cost in total (default: none).
+ */usdTotal: Double? = nil) {
+ self.maxSpaces = maxSpaces
+ self.maxVcpus = maxVcpus
+ self.maxMemoryMb = maxMemoryMb
+ self.usdPerHour = usdPerHour
+ self.usdTotal = usdTotal
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension TreeBudgetLimits: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeTreeBudgetLimits: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> TreeBudgetLimits {
+ return
+ try TreeBudgetLimits(
+ maxSpaces: FfiConverterOptionUInt32.read(from: &buf),
+ maxVcpus: FfiConverterOptionUInt32.read(from: &buf),
+ maxMemoryMb: FfiConverterOptionUInt64.read(from: &buf),
+ usdPerHour: FfiConverterOptionDouble.read(from: &buf),
+ usdTotal: FfiConverterOptionDouble.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: TreeBudgetLimits, into buf: inout [UInt8]) {
+ FfiConverterOptionUInt32.write(value.maxSpaces, into: &buf)
+ FfiConverterOptionUInt32.write(value.maxVcpus, into: &buf)
+ FfiConverterOptionUInt64.write(value.maxMemoryMb, into: &buf)
+ FfiConverterOptionDouble.write(value.usdPerHour, into: &buf)
+ FfiConverterOptionDouble.write(value.usdTotal, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTreeBudgetLimits_lift(_ buf: RustBuffer) throws -> TreeBudgetLimits {
+ return try FfiConverterTypeTreeBudgetLimits.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTreeBudgetLimits_lower(_ value: TreeBudgetLimits) -> RustBuffer {
+ return FfiConverterTypeTreeBudgetLimits.lower(value)
+}
+
+
/**
* Upload options.
*/
@@ -47248,6 +48887,30 @@ fileprivate struct FfiConverterOptionTypeImageInfo: FfiConverterRustBuffer {
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeNetworkSettings: FfiConverterRustBuffer {
+ typealias SwiftType = NetworkSettings?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeNetworkSettings.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeNetworkSettings.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -47608,6 +49271,30 @@ fileprivate struct FfiConverterOptionTypeSpaceInfo: FfiConverterRustBuffer {
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeSpaceServiceProbe: FfiConverterRustBuffer {
+ typealias SwiftType = SpaceServiceProbe?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeSpaceServiceProbe.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeSpaceServiceProbe.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -50117,6 +51804,31 @@ fileprivate struct FfiConverterSequenceTypeSpaceInfo: FfiConverterRustBuffer {
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeSpaceOrphan: FfiConverterRustBuffer {
+ typealias SwiftType = [SpaceOrphan]
+
+ public static func write(_ value: [SpaceOrphan], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeSpaceOrphan.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [SpaceOrphan] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [SpaceOrphan]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeSpaceOrphan.read(from: &buf))
+ }
+ return seq
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -50167,6 +51879,31 @@ fileprivate struct FfiConverterSequenceTypeSpaceSentFile: FfiConverterRustBuffer
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeSpaceServiceInfo: FfiConverterRustBuffer {
+ typealias SwiftType = [SpaceServiceInfo]
+
+ public static func write(_ value: [SpaceServiceInfo], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeSpaceServiceInfo.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [SpaceServiceInfo] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [SpaceServiceInfo]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeSpaceServiceInfo.read(from: &buf))
+ }
+ return seq
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -52175,6 +53912,9 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_space_close_stream() != 64912) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_space_delete_service() != 14460) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_space_displays() != 30039) {
return InitializationResult.apiChecksumMismatch
}
@@ -52202,15 +53942,24 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_space_join_presence() != 56636) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_space_kept_services() != 50248) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_space_list_tools() != 19376) {
return InitializationResult.apiChecksumMismatch
}
if (uniffi_cua_sdk_checksum_method_space_open_stream() != 19577) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_space_put_service() != 55111) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_space_request_site_login() != 2223) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_space_restart_service() != 63778) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_space_route() != 9790) {
return InitializationResult.apiChecksumMismatch
}
@@ -52220,6 +53969,9 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_space_send_file() != 29056) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_space_service_logs() != 48773) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_space_services() != 32496) {
return InitializationResult.apiChecksumMismatch
}
@@ -52238,9 +53990,15 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_space_start_hotspot() != 44744) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_space_start_service() != 13576) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_space_stop_hotspot() != 18254) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_space_stop_service() != 14671) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_space_stream_session() != 61326) {
return InitializationResult.apiChecksumMismatch
}
@@ -52427,6 +54185,9 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_spaces_routines() != 22768) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_spaces_ack_network_notice() != 32926) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_spaces_add() != 56308) {
return InitializationResult.apiChecksumMismatch
}
@@ -52451,12 +54212,15 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_spaces_create_with_progress() != 28676) {
return InitializationResult.apiChecksumMismatch
}
- if (uniffi_cua_sdk_checksum_method_spaces_delete() != 39986) {
+ if (uniffi_cua_sdk_checksum_method_spaces_delete() != 4316) {
return InitializationResult.apiChecksumMismatch
}
if (uniffi_cua_sdk_checksum_method_spaces_delete_many() != 9087) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_spaces_delete_tree() != 29454) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_spaces_delete_volume() != 11412) {
return InitializationResult.apiChecksumMismatch
}
@@ -52484,6 +54248,12 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_spaces_machine_health() != 35352) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_spaces_network() != 41208) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_sdk_checksum_method_spaces_orphans() != 23539) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_spaces_relay_register() != 31691) {
return InitializationResult.apiChecksumMismatch
}
@@ -52505,12 +54275,21 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_spaces_resources() != 12146) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_spaces_set_children() != 63927) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_spaces_set_egress() != 12366) {
return InitializationResult.apiChecksumMismatch
}
if (uniffi_cua_sdk_checksum_method_spaces_set_lifetime() != 62609) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_spaces_set_network() != 64671) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_sdk_checksum_method_spaces_set_tree_budget() != 8418) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_spaces_space() != 26355) {
return InitializationResult.apiChecksumMismatch
}
@@ -52523,6 +54302,9 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_spaces_suspend() != 23817) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_spaces_tree_budget() != 58333) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_spaces_volume_approve() != 8640) {
return InitializationResult.apiChecksumMismatch
}
diff --git a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h
index 6867f7a83d..f80d14e9ad 100644
--- a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h
+++ b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h
@@ -1779,6 +1779,11 @@ uint64_t uniffi_cua_sdk_fn_method_space_checkpoint(uint64_t ptr, RustBuffer chec
uint64_t uniffi_cua_sdk_fn_method_space_close_stream(uint64_t ptr, RustBuffer media_session_id
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_DELETE_SERVICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_DELETE_SERVICE
+uint64_t uniffi_cua_sdk_fn_method_space_delete_service(uint64_t ptr, RustBuffer name
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_DISPLAYS
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_DISPLAYS
uint64_t uniffi_cua_sdk_fn_method_space_displays(uint64_t ptr
@@ -1824,6 +1829,11 @@ RustBuffer uniffi_cua_sdk_fn_method_space_info(uint64_t ptr, RustCallStatus *_No
uint64_t uniffi_cua_sdk_fn_method_space_join_presence(uint64_t ptr, RustBuffer identity, RustBuffer timeout_ms
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_KEPT_SERVICES
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_KEPT_SERVICES
+uint64_t uniffi_cua_sdk_fn_method_space_kept_services(uint64_t ptr
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_LIST_TOOLS
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_LIST_TOOLS
uint64_t uniffi_cua_sdk_fn_method_space_list_tools(uint64_t ptr, RustBuffer service
@@ -1834,11 +1844,21 @@ uint64_t uniffi_cua_sdk_fn_method_space_list_tools(uint64_t ptr, RustBuffer serv
uint64_t uniffi_cua_sdk_fn_method_space_open_stream(uint64_t ptr, RustBuffer options
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_PUT_SERVICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_PUT_SERVICE
+uint64_t uniffi_cua_sdk_fn_method_space_put_service(uint64_t ptr, RustBuffer def
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_REQUEST_SITE_LOGIN
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_REQUEST_SITE_LOGIN
uint64_t uniffi_cua_sdk_fn_method_space_request_site_login(uint64_t ptr, RustBuffer url, RustBuffer options
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_RESTART_SERVICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_RESTART_SERVICE
+uint64_t uniffi_cua_sdk_fn_method_space_restart_service(uint64_t ptr, RustBuffer name
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_ROUTE
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_ROUTE
uint64_t uniffi_cua_sdk_fn_method_space_route(uint64_t ptr
@@ -1854,6 +1874,11 @@ uint64_t uniffi_cua_sdk_fn_method_space_screenshot(uint64_t ptr, RustBuffer opti
uint64_t uniffi_cua_sdk_fn_method_space_send_file(uint64_t ptr, RustBuffer local_path, RustBuffer options
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_SERVICE_LOGS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_SERVICE_LOGS
+uint64_t uniffi_cua_sdk_fn_method_space_service_logs(uint64_t ptr, RustBuffer name, RustBuffer tail_bytes
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_SERVICES
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_SERVICES
RustBuffer uniffi_cua_sdk_fn_method_space_services(uint64_t ptr, RustCallStatus *_Nonnull out_status
@@ -1884,11 +1909,21 @@ uint64_t uniffi_cua_sdk_fn_method_space_spacesd(uint64_t ptr, RustCallStatus *_N
uint64_t uniffi_cua_sdk_fn_method_space_start_hotspot(uint64_t ptr, RustBuffer set_system_proxy, RustBuffer bypass
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_START_SERVICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_START_SERVICE
+uint64_t uniffi_cua_sdk_fn_method_space_start_service(uint64_t ptr, RustBuffer name
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_STOP_HOTSPOT
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_STOP_HOTSPOT
uint64_t uniffi_cua_sdk_fn_method_space_stop_hotspot(uint64_t ptr
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_STOP_SERVICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_STOP_SERVICE
+uint64_t uniffi_cua_sdk_fn_method_space_stop_service(uint64_t ptr, RustBuffer name
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_STREAM_SESSION
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACE_STREAM_SESSION
uint64_t uniffi_cua_sdk_fn_method_space_stream_session(uint64_t ptr, RustBuffer options, uint64_t frames, RustBuffer audio
@@ -2244,6 +2279,11 @@ uint64_t uniffi_cua_sdk_fn_method_spaces_routine_set_enabled(uint64_t ptr, RustB
uint64_t uniffi_cua_sdk_fn_method_spaces_routines(uint64_t ptr, RustBuffer agent
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_ACK_NETWORK_NOTICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_ACK_NETWORK_NOTICE
+uint64_t uniffi_cua_sdk_fn_method_spaces_ack_network_notice(uint64_t ptr, RustBuffer space
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_ADD
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_ADD
uint64_t uniffi_cua_sdk_fn_method_spaces_add(uint64_t ptr, RustBuffer url, RustBuffer token, RustBuffer name
@@ -2294,6 +2334,11 @@ uint64_t uniffi_cua_sdk_fn_method_spaces_delete(uint64_t ptr, RustBuffer space
uint64_t uniffi_cua_sdk_fn_method_spaces_delete_many(uint64_t ptr, RustBuffer ids
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_DELETE_TREE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_DELETE_TREE
+uint64_t uniffi_cua_sdk_fn_method_spaces_delete_tree(uint64_t ptr, RustBuffer space, int8_t keep_children
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_DELETE_VOLUME
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_DELETE_VOLUME
uint64_t uniffi_cua_sdk_fn_method_spaces_delete_volume(uint64_t ptr, RustBuffer name, int8_t force
@@ -2339,6 +2384,16 @@ uint64_t uniffi_cua_sdk_fn_method_spaces_list_tools_json(uint64_t ptr
uint64_t uniffi_cua_sdk_fn_method_spaces_machine_health(uint64_t ptr, RustBuffer machine
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_NETWORK
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_NETWORK
+uint64_t uniffi_cua_sdk_fn_method_spaces_network(uint64_t ptr, RustBuffer space
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_ORPHANS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_ORPHANS
+uint64_t uniffi_cua_sdk_fn_method_spaces_orphans(uint64_t ptr
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_RELAY_REGISTER
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_RELAY_REGISTER
uint64_t uniffi_cua_sdk_fn_method_spaces_relay_register(uint64_t ptr, RustBuffer space
@@ -2374,6 +2429,11 @@ uint64_t uniffi_cua_sdk_fn_method_spaces_resolve(uint64_t ptr, RustBuffer space
uint64_t uniffi_cua_sdk_fn_method_spaces_resources(uint64_t ptr, int8_t visible
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_SET_CHILDREN
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_SET_CHILDREN
+uint64_t uniffi_cua_sdk_fn_method_spaces_set_children(uint64_t ptr, RustBuffer space, int8_t enabled
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_SET_EGRESS
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_SET_EGRESS
uint64_t uniffi_cua_sdk_fn_method_spaces_set_egress(uint64_t ptr, RustBuffer space, RustBuffer policy
@@ -2384,6 +2444,16 @@ uint64_t uniffi_cua_sdk_fn_method_spaces_set_egress(uint64_t ptr, RustBuffer spa
uint64_t uniffi_cua_sdk_fn_method_spaces_set_lifetime(uint64_t ptr, RustBuffer space, uint64_t seconds, RustBuffer on_expire
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_SET_NETWORK
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_SET_NETWORK
+uint64_t uniffi_cua_sdk_fn_method_spaces_set_network(uint64_t ptr, RustBuffer space, RustBuffer settings, int8_t widen, int8_t tree
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_SET_TREE_BUDGET
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_SET_TREE_BUDGET
+uint64_t uniffi_cua_sdk_fn_method_spaces_set_tree_budget(uint64_t ptr, RustBuffer space, RustBuffer limits
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_SPACE
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_SPACE
uint64_t uniffi_cua_sdk_fn_method_spaces_space(uint64_t ptr, RustBuffer space
@@ -2404,6 +2474,11 @@ uint64_t uniffi_cua_sdk_fn_method_spaces_stop(uint64_t ptr, RustBuffer space
uint64_t uniffi_cua_sdk_fn_method_spaces_suspend(uint64_t ptr, RustBuffer space
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_TREE_BUDGET
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_TREE_BUDGET
+uint64_t uniffi_cua_sdk_fn_method_spaces_tree_budget(uint64_t ptr, RustBuffer space
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_VOLUME_APPROVE
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_VOLUME_APPROVE
uint64_t uniffi_cua_sdk_fn_method_spaces_volume_approve(uint64_t ptr, RustBuffer request_id, RustBuffer expires_in_secs
@@ -5226,6 +5301,12 @@ uint16_t uniffi_cua_sdk_checksum_method_space_checkpoint(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_CLOSE_STREAM
uint16_t uniffi_cua_sdk_checksum_method_space_close_stream(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_DELETE_SERVICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_DELETE_SERVICE
+uint16_t uniffi_cua_sdk_checksum_method_space_delete_service(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_DISPLAYS
@@ -5280,6 +5361,12 @@ uint16_t uniffi_cua_sdk_checksum_method_space_info(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_JOIN_PRESENCE
uint16_t uniffi_cua_sdk_checksum_method_space_join_presence(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_KEPT_SERVICES
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_KEPT_SERVICES
+uint16_t uniffi_cua_sdk_checksum_method_space_kept_services(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_LIST_TOOLS
@@ -5292,12 +5379,24 @@ uint16_t uniffi_cua_sdk_checksum_method_space_list_tools(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_OPEN_STREAM
uint16_t uniffi_cua_sdk_checksum_method_space_open_stream(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_PUT_SERVICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_PUT_SERVICE
+uint16_t uniffi_cua_sdk_checksum_method_space_put_service(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_REQUEST_SITE_LOGIN
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_REQUEST_SITE_LOGIN
uint16_t uniffi_cua_sdk_checksum_method_space_request_site_login(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_RESTART_SERVICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_RESTART_SERVICE
+uint16_t uniffi_cua_sdk_checksum_method_space_restart_service(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_ROUTE
@@ -5316,6 +5415,12 @@ uint16_t uniffi_cua_sdk_checksum_method_space_screenshot(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_SEND_FILE
uint16_t uniffi_cua_sdk_checksum_method_space_send_file(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_SERVICE_LOGS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_SERVICE_LOGS
+uint16_t uniffi_cua_sdk_checksum_method_space_service_logs(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_SERVICES
@@ -5352,12 +5457,24 @@ uint16_t uniffi_cua_sdk_checksum_method_space_spacesd(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_START_HOTSPOT
uint16_t uniffi_cua_sdk_checksum_method_space_start_hotspot(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_START_SERVICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_START_SERVICE
+uint16_t uniffi_cua_sdk_checksum_method_space_start_service(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_STOP_HOTSPOT
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_STOP_HOTSPOT
uint16_t uniffi_cua_sdk_checksum_method_space_stop_hotspot(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_STOP_SERVICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_STOP_SERVICE
+uint16_t uniffi_cua_sdk_checksum_method_space_stop_service(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACE_STREAM_SESSION
@@ -5730,6 +5847,12 @@ uint16_t uniffi_cua_sdk_checksum_method_spaces_routine_set_enabled(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_ROUTINES
uint16_t uniffi_cua_sdk_checksum_method_spaces_routines(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_ACK_NETWORK_NOTICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_ACK_NETWORK_NOTICE
+uint16_t uniffi_cua_sdk_checksum_method_spaces_ack_network_notice(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_ADD
@@ -5790,6 +5913,12 @@ uint16_t uniffi_cua_sdk_checksum_method_spaces_delete(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_DELETE_MANY
uint16_t uniffi_cua_sdk_checksum_method_spaces_delete_many(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_DELETE_TREE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_DELETE_TREE
+uint16_t uniffi_cua_sdk_checksum_method_spaces_delete_tree(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_DELETE_VOLUME
@@ -5844,6 +5973,18 @@ uint16_t uniffi_cua_sdk_checksum_method_spaces_list_tools_json(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_MACHINE_HEALTH
uint16_t uniffi_cua_sdk_checksum_method_spaces_machine_health(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_NETWORK
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_NETWORK
+uint16_t uniffi_cua_sdk_checksum_method_spaces_network(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_ORPHANS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_ORPHANS
+uint16_t uniffi_cua_sdk_checksum_method_spaces_orphans(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_RELAY_REGISTER
@@ -5886,6 +6027,12 @@ uint16_t uniffi_cua_sdk_checksum_method_spaces_resolve(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_RESOURCES
uint16_t uniffi_cua_sdk_checksum_method_spaces_resources(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_SET_CHILDREN
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_SET_CHILDREN
+uint16_t uniffi_cua_sdk_checksum_method_spaces_set_children(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_SET_EGRESS
@@ -5898,6 +6045,18 @@ uint16_t uniffi_cua_sdk_checksum_method_spaces_set_egress(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_SET_LIFETIME
uint16_t uniffi_cua_sdk_checksum_method_spaces_set_lifetime(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_SET_NETWORK
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_SET_NETWORK
+uint16_t uniffi_cua_sdk_checksum_method_spaces_set_network(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_SET_TREE_BUDGET
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_SET_TREE_BUDGET
+uint16_t uniffi_cua_sdk_checksum_method_spaces_set_tree_budget(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_SPACE
@@ -5922,6 +6081,12 @@ uint16_t uniffi_cua_sdk_checksum_method_spaces_stop(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_SUSPEND
uint16_t uniffi_cua_sdk_checksum_method_spaces_suspend(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_TREE_BUDGET
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_TREE_BUDGET
+uint16_t uniffi_cua_sdk_checksum_method_spaces_tree_budget(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_VOLUME_APPROVE
diff --git a/libs/cua/swift/Tests/CuaTests/ImageTests.swift b/libs/cua/swift/Tests/CuaTests/ImageTests.swift
index a0ec2cbfca..2d92f08de1 100644
--- a/libs/cua/swift/Tests/CuaTests/ImageTests.swift
+++ b/libs/cua/swift/Tests/CuaTests/ImageTests.swift
@@ -15,7 +15,8 @@ private func published(_ ref: String) -> Bool {
let images = json["images"] as? [[String: Any]],
let entry = images.first(where: { $0["ref"] as? String == ref })
else { return true }
- return entry["published"] as? Bool ?? true
+ // An entry built on the user's own machine (derived_from) resolves while unpublished.
+ return (entry["published"] as? Bool ?? true) || entry["derived_from"] != nil
}
private func expectRef(_ ref: String, _ make: () throws -> String) {
diff --git a/libs/cua/swift/Tests/CuaTests/SpacesTests.swift b/libs/cua/swift/Tests/CuaTests/SpacesTests.swift
index a9c882c3fe..08e7927614 100644
--- a/libs/cua/swift/Tests/CuaTests/SpacesTests.swift
+++ b/libs/cua/swift/Tests/CuaTests/SpacesTests.swift
@@ -125,7 +125,7 @@ func exerciseSpaces(_ cua: Cua, _ fx: Fixtures, tmp: URL, teleport: Bool = false
@Suite(.serialized) struct SpacesTests {
@Test func everyContractToolMapsToAGeneratedMethod() {
let rows = spacesToolMethods()
- #expect(rows.count == 114)
+ #expect(rows.count == 118)
// Swift spells `Class.method_name` as `methodName` on the generated
// protocol; check each against the protocol's requirement list.
let spaceMethods: Set<String> = [
@@ -144,14 +144,14 @@ func exerciseSpaces(_ cua: Cua, _ fx: Fixtures, tmp: URL, teleport: Bool = false
"volumeRequestAccess", "volumeRequests", "volumeApprove", "volumeDeny", "volumeAudit",
"volumeStorage", "volumeStorageSet", "volumeMountStatus", "volumeMount", "volumeUnmount",
"volumeSyncStatus", "volumeSyncEvents", "volumeSyncResolve", "volumeCacheStats",
- "volumeCacheSet", "volumeCacheClear",
+ "volumeCacheSet", "volumeCacheClear", "network", "setNetwork",
]
let spaceHandle: Set<String> = [
"bash", "write", "home", "upload", "download", "sendFile", "listTools", "callTool",
"windows", "openStream", "closeStream", "streamSession", "joinPresence",
"teleportManifest", "teleport", "startHotspot", "stopHotspot", "hotspotStatus",
"agentStart", "agentStatus", "agentMessage", "agentStop", "agentList",
- "agentEvents", "agentInterrupt", "requestSiteLogin", "share", "unshare", "shares",
+ "agentEvents", "agentInterrupt", "requestSiteLogin", "share", "unshare", "shares", "putService",
]
for row in rows {
let parts = row.method.split(separator: ".").map(String.init)
diff --git a/libs/cua/typescript/src/native/cua_sdk-ffi.ts b/libs/cua/typescript/src/native/cua_sdk-ffi.ts
index 2ece776763..f05a35877c 100644
--- a/libs/cua/typescript/src/native/cua_sdk-ffi.ts
+++ b/libs/cua/typescript/src/native/cua_sdk-ffi.ts
@@ -2103,6 +2103,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_delete_service": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_displays": {
args: [FfiType.Handle],
ret: FfiType.Handle,
@@ -2148,6 +2153,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_kept_services": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_list_tools": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2158,11 +2168,21 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_put_service": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_request_site_login": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_restart_service": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_route": {
args: [FfiType.Handle],
ret: FfiType.Handle,
@@ -2178,6 +2198,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_service_logs": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_services": {
args: [FfiType.Handle],
ret: FfiType.RustBuffer,
@@ -2208,11 +2233,21 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_start_service": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_stop_hotspot": {
args: [FfiType.Handle],
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_space_stop_service": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_space_stream_session": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2353,6 +2388,11 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_sdk_fn_method_spaces_ack_network_notice": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_add": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2518,6 +2558,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_delete_tree": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_delete_volume": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],
ret: FfiType.Handle,
@@ -2563,6 +2608,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_network": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_notifications": {
args: [FfiType.Handle, FfiType.Int8, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2578,6 +2628,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_orphans": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_persistent_agent_create": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2673,6 +2728,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_set_children": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_set_egress": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2683,6 +2743,16 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_set_network": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.Int8, FfiType.Int8],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_sdk_fn_method_spaces_set_tree_budget": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_space": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -2703,6 +2773,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_tree_budget": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_volume_approve": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -4608,6 +4683,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_delete_service": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_displays": {
args: [],
ret: FfiType.UInt16,
@@ -4653,6 +4733,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_kept_services": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_list_tools": {
args: [],
ret: FfiType.UInt16,
@@ -4663,11 +4748,21 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_put_service": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_request_site_login": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_restart_service": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_route": {
args: [],
ret: FfiType.UInt16,
@@ -4683,6 +4778,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_service_logs": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_services": {
args: [],
ret: FfiType.UInt16,
@@ -4713,11 +4813,21 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_start_service": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_stop_hotspot": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_space_stop_service": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_space_stream_session": {
args: [],
ret: FfiType.UInt16,
@@ -4858,6 +4968,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_ack_network_notice": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_add": {
args: [],
ret: FfiType.UInt16,
@@ -5023,6 +5138,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_delete_tree": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_delete_volume": {
args: [],
ret: FfiType.UInt16,
@@ -5068,6 +5188,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_network": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_notifications": {
args: [],
ret: FfiType.UInt16,
@@ -5083,6 +5208,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_orphans": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_persistent_agent_create": {
args: [],
ret: FfiType.UInt16,
@@ -5178,6 +5308,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_set_children": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_set_egress": {
args: [],
ret: FfiType.UInt16,
@@ -5188,6 +5323,16 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_set_network": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_sdk_checksum_method_spaces_set_tree_budget": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_space": {
args: [],
ret: FfiType.UInt16,
@@ -5208,6 +5353,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_tree_budget": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_volume_approve": {
args: [],
ret: FfiType.UInt16,
@@ -6265,6 +6415,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_space_capabilities_json(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_sdk_fn_method_space_checkpoint(uniffiSelf: bigint, checkpoint: Uint8Array, pin: number): bigint;
uniffi_cua_sdk_fn_method_space_close_stream(uniffiSelf: bigint, mediaSessionId: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_space_delete_service(uniffiSelf: bigint, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_displays(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_space_download(uniffiSelf: bigint, remotePath: Uint8Array, destDir: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_fork(uniffiSelf: bigint, name: Uint8Array): bigint;
@@ -6274,19 +6425,25 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_space_id(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_sdk_fn_method_space_info(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_sdk_fn_method_space_join_presence(uniffiSelf: bigint, identity: Uint8Array, timeoutMs: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_space_kept_services(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_space_list_tools(uniffiSelf: bigint, service: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_open_stream(uniffiSelf: bigint, options: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_space_put_service(uniffiSelf: bigint, def: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_request_site_login(uniffiSelf: bigint, url: Uint8Array, options: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_space_restart_service(uniffiSelf: bigint, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_route(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_space_screenshot(uniffiSelf: bigint, options: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_send_file(uniffiSelf: bigint, localPath: Uint8Array, options: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_space_service_logs(uniffiSelf: bigint, name: Uint8Array, tailBytes: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_services(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_sdk_fn_method_space_set_presence_settings(uniffiSelf: bigint, cursorProbe: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_share(uniffiSelf: bigint, who: Uint8Array, role: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_shares(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_space_spacesd(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_sdk_fn_method_space_start_hotspot(uniffiSelf: bigint, setSystemProxy: Uint8Array, bypass: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_space_start_service(uniffiSelf: bigint, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_stop_hotspot(uniffiSelf: bigint): bigint;
+ uniffi_cua_sdk_fn_method_space_stop_service(uniffiSelf: bigint, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_stream_session(uniffiSelf: bigint, options: Uint8Array, frames: bigint, audio: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_space_supports(uniffiSelf: bigint, feature: Uint8Array, uniffi_out_err: UniffiRustCallStatus): number;
uniffi_cua_sdk_fn_method_space_teleport(uniffiSelf: bigint, app: Uint8Array, scope: Uint8Array, approver: bigint, requestId: Uint8Array): bigint;
@@ -6315,6 +6472,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_spacestreamsession_request_keyframe(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): void;
uniffi_cua_sdk_fn_method_spacestreamsession_send_text(uniffiSelf: bigint, json: Uint8Array, uniffi_out_err: UniffiRustCallStatus): void;
uniffi_cua_sdk_fn_method_spacestreamsession_stats(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_sdk_fn_method_spaces_ack_network_notice(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_add(uniffiSelf: bigint, url: Uint8Array, token: Uint8Array, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_add_with_service(uniffiSelf: bigint, url: Uint8Array, token: Uint8Array, name: Uint8Array, service: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_agent_capabilities(uniffiSelf: bigint): bigint;
@@ -6348,6 +6506,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_spaces_delete(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_delete_build(uniffiSelf: bigint, build: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_delete_many(uniffiSelf: bigint, ids: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_delete_tree(uniffiSelf: bigint, space: Uint8Array, keepChildren: number): bigint;
uniffi_cua_sdk_fn_method_spaces_delete_volume(uniffiSelf: bigint, name: Uint8Array, force: number): bigint;
uniffi_cua_sdk_fn_method_spaces_fork(uniffiSelf: bigint, source: Uint8Array, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_gpu_support(uniffiSelf: bigint, on: Uint8Array): bigint;
@@ -6357,9 +6516,11 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_spaces_list_known(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_spaces_list_tools_json(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_spaces_machine_health(uniffiSelf: bigint, machine: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_network(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_notifications(uniffiSelf: bigint, unreadOnly: number, sinceMs: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_notifications_ack(uniffiSelf: bigint, ids: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_notify_user(uniffiSelf: bigint, title: Uint8Array, body: Uint8Array, agent: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_orphans(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_spaces_persistent_agent_create(uniffiSelf: bigint, name: Uint8Array, harness: Uint8Array, space: Uint8Array, options: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_persistent_agent_remove(uniffiSelf: bigint, name: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_persistent_agent_save(uniffiSelf: bigint, name: Uint8Array): bigint;
@@ -6379,12 +6540,16 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_spaces_routine_remove(uniffiSelf: bigint, id: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_routine_set_enabled(uniffiSelf: bigint, id: Uint8Array, enabled: number): bigint;
uniffi_cua_sdk_fn_method_spaces_routines(uniffiSelf: bigint, agent: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_set_children(uniffiSelf: bigint, space: Uint8Array, enabled: number): bigint;
uniffi_cua_sdk_fn_method_spaces_set_egress(uniffiSelf: bigint, space: Uint8Array, policy: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_set_lifetime(uniffiSelf: bigint, space: Uint8Array, seconds: bigint, onExpire: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_set_network(uniffiSelf: bigint, space: Uint8Array, settings: Uint8Array, widen: number, tree: number): bigint;
+ uniffi_cua_sdk_fn_method_spaces_set_tree_budget(uniffiSelf: bigint, space: Uint8Array, limits: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_space(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_start(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_stop(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_suspend(uniffiSelf: bigint, space: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_tree_budget(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_volume_approve(uniffiSelf: bigint, requestId: Uint8Array, expiresInSecs: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_volume_audit(uniffiSelf: bigint, limit: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_volume_cache_clear(uniffiSelf: bigint): bigint;
@@ -6766,6 +6931,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_space_capabilities_json(): number;
uniffi_cua_sdk_checksum_method_space_checkpoint(): number;
uniffi_cua_sdk_checksum_method_space_close_stream(): number;
+ uniffi_cua_sdk_checksum_method_space_delete_service(): number;
uniffi_cua_sdk_checksum_method_space_displays(): number;
uniffi_cua_sdk_checksum_method_space_download(): number;
uniffi_cua_sdk_checksum_method_space_fork(): number;
@@ -6775,19 +6941,25 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_space_id(): number;
uniffi_cua_sdk_checksum_method_space_info(): number;
uniffi_cua_sdk_checksum_method_space_join_presence(): number;
+ uniffi_cua_sdk_checksum_method_space_kept_services(): number;
uniffi_cua_sdk_checksum_method_space_list_tools(): number;
uniffi_cua_sdk_checksum_method_space_open_stream(): number;
+ uniffi_cua_sdk_checksum_method_space_put_service(): number;
uniffi_cua_sdk_checksum_method_space_request_site_login(): number;
+ uniffi_cua_sdk_checksum_method_space_restart_service(): number;
uniffi_cua_sdk_checksum_method_space_route(): number;
uniffi_cua_sdk_checksum_method_space_screenshot(): number;
uniffi_cua_sdk_checksum_method_space_send_file(): number;
+ uniffi_cua_sdk_checksum_method_space_service_logs(): number;
uniffi_cua_sdk_checksum_method_space_services(): number;
uniffi_cua_sdk_checksum_method_space_set_presence_settings(): number;
uniffi_cua_sdk_checksum_method_space_share(): number;
uniffi_cua_sdk_checksum_method_space_shares(): number;
uniffi_cua_sdk_checksum_method_space_spacesd(): number;
uniffi_cua_sdk_checksum_method_space_start_hotspot(): number;
+ uniffi_cua_sdk_checksum_method_space_start_service(): number;
uniffi_cua_sdk_checksum_method_space_stop_hotspot(): number;
+ uniffi_cua_sdk_checksum_method_space_stop_service(): number;
uniffi_cua_sdk_checksum_method_space_stream_session(): number;
uniffi_cua_sdk_checksum_method_space_supports(): number;
uniffi_cua_sdk_checksum_method_space_teleport(): number;
@@ -6816,6 +6988,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_spacestreamsession_request_keyframe(): number;
uniffi_cua_sdk_checksum_method_spacestreamsession_send_text(): number;
uniffi_cua_sdk_checksum_method_spacestreamsession_stats(): number;
+ uniffi_cua_sdk_checksum_method_spaces_ack_network_notice(): number;
uniffi_cua_sdk_checksum_method_spaces_add(): number;
uniffi_cua_sdk_checksum_method_spaces_add_with_service(): number;
uniffi_cua_sdk_checksum_method_spaces_agent_capabilities(): number;
@@ -6849,6 +7022,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_spaces_delete(): number;
uniffi_cua_sdk_checksum_method_spaces_delete_build(): number;
uniffi_cua_sdk_checksum_method_spaces_delete_many(): number;
+ uniffi_cua_sdk_checksum_method_spaces_delete_tree(): number;
uniffi_cua_sdk_checksum_method_spaces_delete_volume(): number;
uniffi_cua_sdk_checksum_method_spaces_fork(): number;
uniffi_cua_sdk_checksum_method_spaces_gpu_support(): number;
@@ -6858,9 +7032,11 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_spaces_list_known(): number;
uniffi_cua_sdk_checksum_method_spaces_list_tools_json(): number;
uniffi_cua_sdk_checksum_method_spaces_machine_health(): number;
+ uniffi_cua_sdk_checksum_method_spaces_network(): number;
uniffi_cua_sdk_checksum_method_spaces_notifications(): number;
uniffi_cua_sdk_checksum_method_spaces_notifications_ack(): number;
uniffi_cua_sdk_checksum_method_spaces_notify_user(): number;
+ uniffi_cua_sdk_checksum_method_spaces_orphans(): number;
uniffi_cua_sdk_checksum_method_spaces_persistent_agent_create(): number;
uniffi_cua_sdk_checksum_method_spaces_persistent_agent_remove(): number;
uniffi_cua_sdk_checksum_method_spaces_persistent_agent_save(): number;
@@ -6880,12 +7056,16 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_spaces_routine_remove(): number;
uniffi_cua_sdk_checksum_method_spaces_routine_set_enabled(): number;
uniffi_cua_sdk_checksum_method_spaces_routines(): number;
+ uniffi_cua_sdk_checksum_method_spaces_set_children(): number;
uniffi_cua_sdk_checksum_method_spaces_set_egress(): number;
uniffi_cua_sdk_checksum_method_spaces_set_lifetime(): number;
+ uniffi_cua_sdk_checksum_method_spaces_set_network(): number;
+ uniffi_cua_sdk_checksum_method_spaces_set_tree_budget(): number;
uniffi_cua_sdk_checksum_method_spaces_space(): number;
uniffi_cua_sdk_checksum_method_spaces_start(): number;
uniffi_cua_sdk_checksum_method_spaces_stop(): number;
uniffi_cua_sdk_checksum_method_spaces_suspend(): number;
+ uniffi_cua_sdk_checksum_method_spaces_tree_budget(): number;
uniffi_cua_sdk_checksum_method_spaces_volume_approve(): number;
uniffi_cua_sdk_checksum_method_spaces_volume_audit(): number;
uniffi_cua_sdk_checksum_method_spaces_volume_cache_clear(): number;
diff --git a/libs/cua/typescript/src/native/cua_sdk.ts b/libs/cua/typescript/src/native/cua_sdk.ts
index ee84d72a64..3d13db0056 100644
--- a/libs/cua/typescript/src/native/cua_sdk.ts
+++ b/libs/cua/typescript/src/native/cua_sdk.ts
@@ -13905,6 +13905,118 @@ const FfiConverterTypeNamedVolume = (() => {
return new FFIConverter();
})();
+/**
+ * A Space's network settings: a preset and the user's own lists. The host
+ * the Space runs on compiles them to rules it enforces outside the guest.
+ *
+ * - `internet` (the default): the public internet and the Space's own
+ * tree; this computer, your local network, cloud metadata, other trees
+ * and the cua daemon are blocked;
+ * - `none`: no network;
+ * - `localhost`: `internet`, plus this computer's localhost on
+ * `localhost_ports` (every port only with `all_localhost_ports`);
+ * - `lan`: `internet`, plus your local network (not this computer);
+ * - `custom`: `custom_base` (`internet` or `none`) plus `allow` and `deny`;
+ * - `unprotected`: everything but cloud metadata, other trees and the
+ * daemon.
+ *
+ * A runtime that can't protect a Space yet starts it without network and
+ * says so (`SpaceInfo.network_note`); it never starts it open unless the
+ * preset is `unprotected`.
+ */
+export type NetworkSettings = {
+ /**
+ * `internet`, `none`, `localhost`, `lan`, `custom` or `unprotected`;
+ * empty is `internet`.
+ */
+ preset: string,
+ /**
+ * `localhost`: the ports of this computer's localhost the Space may
+ * reach.
+ */
+ localhostPorts: Array<number>,
+ /**
+ * `localhost`: every port (the daemon's stay blocked).
+ */
+ allLocalhostPorts: boolean,
+ /**
+ * Destinations that stay reachable (addresses or CIDRs).
+ */
+ allow: Array<string>,
+ /**
+ * Destinations that are blocked (addresses, CIDRs or `all`).
+ */
+ deny: Array<string>,
+ /**
+ * `custom`: what it starts from, `internet` (empty) or `none`.
+ */
+ customBase: string,
+ /**
+ * Set when the Space was allowed more than its parent: who and when.
+ */
+ widenedBy?: string
+}
+
+/**
+ * Generated factory for {@link NetworkSettings} record objects.
+ */
+export const NetworkSettings = (() => {
+ const defaults = () => ({
+ preset: "",
+ localhostPorts: [],
+ allLocalhostPorts: false,
+ allow: [],
+ deny: [],
+ customBase: "",
+ widenedBy: undefined
+ });
+ const create = (() => {
+ return uniffiCreateRecord<NetworkSettings, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<NetworkSettings>,
+ });
+})();
+
+const FfiConverterTypeNetworkSettings = (() => {
+ type TypeName = NetworkSettings;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ preset: FfiConverterString.read(from),
+ localhostPorts: FfiConverterSequenceUInt16.read(from),
+ allLocalhostPorts: FfiConverterBool.read(from),
+ allow: FfiConverterSequenceString.read(from),
+ deny: FfiConverterSequenceString.read(from),
+ customBase: FfiConverterString.read(from),
+ widenedBy: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.preset, into);
+ FfiConverterSequenceUInt16.write(value.localhostPorts, into);
+ FfiConverterBool.write(value.allLocalhostPorts, into);
+ FfiConverterSequenceString.write(value.allow, into);
+ FfiConverterSequenceString.write(value.deny, into);
+ FfiConverterString.write(value.customBase, into);
+ FfiConverterOptionalString.write(value.widenedBy, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.preset) +
+ FfiConverterSequenceUInt16.allocationSize(value.localhostPorts) +
+ FfiConverterBool.allocationSize(value.allLocalhostPorts) +
+ FfiConverterSequenceString.allocationSize(value.allow) +
+ FfiConverterSequenceString.allocationSize(value.deny) +
+ FfiConverterString.allocationSize(value.customBase) +
+ FfiConverterOptionalString.allocationSize(value.widenedBy);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* One entry of the notifications feed.
*/
@@ -18000,6 +18112,166 @@ const FfiConverterTypeServiceEndpoint = (() => {
return new FFIConverter();
})();
+/**
+ * A Space's network as `cua network show` says it ([`Spaces::network`]).
+ */
+export type SpaceNetworkInfo = {
+ /**
+ * Its settings.
+ */
+ settings: NetworkSettings,
+ /**
+ * One plain line ("Internet only").
+ */
+ summary: string,
+ /**
+ * What the settings open beyond `internet`, one plain line each.
+ */
+ widenings: Array<string>,
+ /**
+ * `enforced` (rules on the host, outside the guest), `no_network`
+ * (its runtime can't protect it yet), `open` (No protection) or
+ * `refused`; empty when unknown (a Space another computer runs).
+ */
+ enforcement: string,
+ /**
+ * Where the rules are enforced, or why its network is cut.
+ */
+ point: string,
+ /**
+ * Why its network is not what was asked; `None` otherwise.
+ */
+ note?: string,
+ /**
+ * Its parent and its tree's top-level Space; `None` for a top-level
+ * Space.
+ */
+ parent?: string,
+ root?: string,
+ /**
+ * What no setting opens, in plain words.
+ */
+ alwaysBlocked: Array<string>,
+ /**
+ * An update changed its settings: say so once.
+ */
+ noticePending: boolean
+}
+
+/**
+ * Generated factory for {@link SpaceNetworkInfo} record objects.
+ */
+export const SpaceNetworkInfo = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SpaceNetworkInfo, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SpaceNetworkInfo>,
+ });
+})();
+
+const FfiConverterTypeSpaceNetworkInfo = (() => {
+ type TypeName = SpaceNetworkInfo;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ settings: FfiConverterTypeNetworkSettings.read(from),
+ summary: FfiConverterString.read(from),
+ widenings: FfiConverterSequenceString.read(from),
+ enforcement: FfiConverterString.read(from),
+ point: FfiConverterString.read(from),
+ note: FfiConverterOptionalString.read(from),
+ parent: FfiConverterOptionalString.read(from),
+ root: FfiConverterOptionalString.read(from),
+ alwaysBlocked: FfiConverterSequenceString.read(from),
+ noticePending: FfiConverterBool.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterTypeNetworkSettings.write(value.settings, into);
+ FfiConverterString.write(value.summary, into);
+ FfiConverterSequenceString.write(value.widenings, into);
+ FfiConverterString.write(value.enforcement, into);
+ FfiConverterString.write(value.point, into);
+ FfiConverterOptionalString.write(value.note, into);
+ FfiConverterOptionalString.write(value.parent, into);
+ FfiConverterOptionalString.write(value.root, into);
+ FfiConverterSequenceString.write(value.alwaysBlocked, into);
+ FfiConverterBool.write(value.noticePending, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterTypeNetworkSettings.allocationSize(value.settings) +
+ FfiConverterString.allocationSize(value.summary) +
+ FfiConverterSequenceString.allocationSize(value.widenings) +
+ FfiConverterString.allocationSize(value.enforcement) +
+ FfiConverterString.allocationSize(value.point) +
+ FfiConverterOptionalString.allocationSize(value.note) +
+ FfiConverterOptionalString.allocationSize(value.parent) +
+ FfiConverterOptionalString.allocationSize(value.root) +
+ FfiConverterSequenceString.allocationSize(value.alwaysBlocked) +
+ FfiConverterBool.allocationSize(value.noticePending);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * What [`Spaces::set_network`] did.
+ */
+export type SetNetworkResult = {
+ /**
+ * `now` (the running guest is under them) or `next_start`.
+ */
+ applied: string,
+ /**
+ * The Space's network after the change.
+ */
+ network: SpaceNetworkInfo
+}
+
+/**
+ * Generated factory for {@link SetNetworkResult} record objects.
+ */
+export const SetNetworkResult = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SetNetworkResult, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SetNetworkResult>,
+ });
+})();
+
+const FfiConverterTypeSetNetworkResult = (() => {
+ type TypeName = SetNetworkResult;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ applied: FfiConverterString.read(from),
+ network: FfiConverterTypeSpaceNetworkInfo.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.applied, into);
+ FfiConverterTypeSpaceNetworkInfo.write(value.network, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.applied) +
+ FfiConverterTypeSpaceNetworkInfo.allocationSize(value.network);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* One setup step.
*/
@@ -19175,6 +19447,22 @@ export type SpaceCreateOptions = {
* to enforce it makes the create fail.
*/
egress?: EgressPolicy,
+ /**
+ * Network settings (see [`NetworkSettings`]). `None`: what `network`
+ * and `egress` say (`internet` when neither says anything). A daemon
+ * too old to keep them makes the create fail.
+ */
+ networkSettings?: NetworkSettings,
+ /**
+ * Create it as a child of this Space (id or name): its network is no
+ * more open than its parent's, and it joins the parent's tree.
+ */
+ parent?: string,
+ /**
+ * With `parent`: let its network be more open than its parent's
+ * (recorded on the Space).
+ */
+ widen?: boolean,
/**
* With `on` a linked cloud (`aws`, `hetzner`, ...): the machine type
* its host must be (`c7g.xlarge`, `cax41`), a pin of the elastic
@@ -19184,7 +19472,12 @@ export type SpaceCreateOptions = {
/**
* With `on` a linked cloud: the region its host must be in.
*/
- region?: string
+ region?: string,
+ /**
+ * Lets the Space make child Spaces of its own ([`Spaces::set_children`]).
+ * `None`: off. Only a Space the machine of the runtime runs itself.
+ */
+ children?: boolean
}
/**
@@ -19218,8 +19511,12 @@ export const SpaceCreateOptions = (() => {
network: undefined,
labels: new Map(),
egress: undefined,
+ networkSettings: undefined,
+ parent: undefined,
+ widen: undefined,
instanceType: undefined,
- region: undefined
+ region: undefined,
+ children: undefined
});
const create = (() => {
return uniffiCreateRecord<SpaceCreateOptions, ReturnType<typeof defaults>>(defaults);
@@ -19262,8 +19559,12 @@ const FfiConverterTypeSpaceCreateOptions = (() => {
network: FfiConverterOptionalString.read(from),
labels: FfiConverterMapStringString.read(from),
egress: FfiConverterOptionalTypeEgressPolicy.read(from),
+ networkSettings: FfiConverterOptionalTypeNetworkSettings.read(from),
+ parent: FfiConverterOptionalString.read(from),
+ widen: FfiConverterOptionalBoolean.read(from),
instanceType: FfiConverterOptionalString.read(from),
- region: FfiConverterOptionalString.read(from)
+ region: FfiConverterOptionalString.read(from),
+ children: FfiConverterOptionalBoolean.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
@@ -19293,8 +19594,12 @@ const FfiConverterTypeSpaceCreateOptions = (() => {
FfiConverterOptionalString.write(value.network, into);
FfiConverterMapStringString.write(value.labels, into);
FfiConverterOptionalTypeEgressPolicy.write(value.egress, into);
+ FfiConverterOptionalTypeNetworkSettings.write(value.networkSettings, into);
+ FfiConverterOptionalString.write(value.parent, into);
+ FfiConverterOptionalBoolean.write(value.widen, into);
FfiConverterOptionalString.write(value.instanceType, into);
FfiConverterOptionalString.write(value.region, into);
+ FfiConverterOptionalBoolean.write(value.children, into);
}
allocationSize(value: TypeName): number {
return FfiConverterOptionalString.allocationSize(value.image) +
@@ -19323,8 +19628,12 @@ const FfiConverterTypeSpaceCreateOptions = (() => {
FfiConverterOptionalString.allocationSize(value.network) +
FfiConverterMapStringString.allocationSize(value.labels) +
FfiConverterOptionalTypeEgressPolicy.allocationSize(value.egress) +
+ FfiConverterOptionalTypeNetworkSettings.allocationSize(value.networkSettings) +
+ FfiConverterOptionalString.allocationSize(value.parent) +
+ FfiConverterOptionalBoolean.allocationSize(value.widen) +
FfiConverterOptionalString.allocationSize(value.instanceType) +
- FfiConverterOptionalString.allocationSize(value.region);
+ FfiConverterOptionalString.allocationSize(value.region) +
+ FfiConverterOptionalBoolean.allocationSize(value.children);
}
};
@@ -19779,6 +20088,36 @@ export type SpaceInfo = {
* Where `egress` is enforced; `None` without one.
*/
egressEnforced?: EgressEnforcement,
+ /**
+ * Its network settings; `None` for a Space this computer keeps no
+ * record of, or one created before they existed (it gets them on its
+ * next start).
+ */
+ network?: NetworkSettings,
+ /**
+ * Why its network is not what was asked, in plain words (a runtime
+ * that can't protect it yet started it without network); `None`
+ * otherwise.
+ */
+ networkNote?: string,
+ /**
+ * An update changed its network settings (an old Space moved to the
+ * new defaults): say so once.
+ */
+ networkNoticePending: boolean,
+ /**
+ * The Space it was created from, by id; `None` for a top-level Space.
+ */
+ parent?: string,
+ /**
+ * The top-level Space of its tree, by id; `None` for a top-level
+ * Space.
+ */
+ root?: string,
+ /**
+ * How far below its tree's top-level Space it is (0: top-level).
+ */
+ depth: number,
/**
* Named volumes mounted in the Space (see
* [`SpaceCreateOptions::volumes`]).
@@ -19846,6 +20185,12 @@ const FfiConverterTypeSpaceInfo = (() => {
createdAtUnix: FfiConverterInt64.read(from),
egress: FfiConverterTypeEgressPolicy.read(from),
egressEnforced: FfiConverterOptionalTypeEgressEnforcement.read(from),
+ network: FfiConverterOptionalTypeNetworkSettings.read(from),
+ networkNote: FfiConverterOptionalString.read(from),
+ networkNoticePending: FfiConverterBool.read(from),
+ parent: FfiConverterOptionalString.read(from),
+ root: FfiConverterOptionalString.read(from),
+ depth: FfiConverterUInt32.read(from),
volumes: FfiConverterSequenceTypeVolumeMount.read(from),
sharing: FfiConverterOptionalTypeSpaceSharing.read(from)
};
@@ -19881,6 +20226,12 @@ const FfiConverterTypeSpaceInfo = (() => {
FfiConverterInt64.write(value.createdAtUnix, into);
FfiConverterTypeEgressPolicy.write(value.egress, into);
FfiConverterOptionalTypeEgressEnforcement.write(value.egressEnforced, into);
+ FfiConverterOptionalTypeNetworkSettings.write(value.network, into);
+ FfiConverterOptionalString.write(value.networkNote, into);
+ FfiConverterBool.write(value.networkNoticePending, into);
+ FfiConverterOptionalString.write(value.parent, into);
+ FfiConverterOptionalString.write(value.root, into);
+ FfiConverterUInt32.write(value.depth, into);
FfiConverterSequenceTypeVolumeMount.write(value.volumes, into);
FfiConverterOptionalTypeSpaceSharing.write(value.sharing, into);
}
@@ -19915,6 +20266,12 @@ const FfiConverterTypeSpaceInfo = (() => {
FfiConverterInt64.allocationSize(value.createdAtUnix) +
FfiConverterTypeEgressPolicy.allocationSize(value.egress) +
FfiConverterOptionalTypeEgressEnforcement.allocationSize(value.egressEnforced) +
+ FfiConverterOptionalTypeNetworkSettings.allocationSize(value.network) +
+ FfiConverterOptionalString.allocationSize(value.networkNote) +
+ FfiConverterBool.allocationSize(value.networkNoticePending) +
+ FfiConverterOptionalString.allocationSize(value.parent) +
+ FfiConverterOptionalString.allocationSize(value.root) +
+ FfiConverterUInt32.allocationSize(value.depth) +
FfiConverterSequenceTypeVolumeMount.allocationSize(value.volumes) +
FfiConverterOptionalTypeSpaceSharing.allocationSize(value.sharing);
@@ -20328,6 +20685,81 @@ const FfiConverterTypeSpaceList = (() => {
return new FFIConverter();
})();
+/**
+ * A child Space whose parent is gone or out of reach ([`Spaces::orphans`]).
+ */
+export type SpaceOrphan = {
+ /**
+ * The child.
+ */
+ space: string,
+ /**
+ * Its parent's id.
+ */
+ parent: string,
+ /**
+ * `ending` (its parent is provably gone: it ends after the grace) or
+ * `listed` (not this computer's to judge: it stays until deleted or its
+ * own lifetime ends).
+ */
+ state: string,
+ /**
+ * Why.
+ */
+ why: string,
+ /**
+ * Seconds until it ends (`ending` only).
+ */
+ endsInSecs: bigint
+}
+
+/**
+ * Generated factory for {@link SpaceOrphan} record objects.
+ */
+export const SpaceOrphan = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SpaceOrphan, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SpaceOrphan>,
+ });
+})();
+
+const FfiConverterTypeSpaceOrphan = (() => {
+ type TypeName = SpaceOrphan;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ space: FfiConverterString.read(from),
+ parent: FfiConverterString.read(from),
+ state: FfiConverterString.read(from),
+ why: FfiConverterString.read(from),
+ endsInSecs: FfiConverterInt64.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.space, into);
+ FfiConverterString.write(value.parent, into);
+ FfiConverterString.write(value.state, into);
+ FfiConverterString.write(value.why, into);
+ FfiConverterInt64.write(value.endsInSecs, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.space) +
+ FfiConverterString.allocationSize(value.parent) +
+ FfiConverterString.allocationSize(value.state) +
+ FfiConverterString.allocationSize(value.why) +
+ FfiConverterInt64.allocationSize(value.endsInSecs);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* What [`Spaces::stop`] or [`Spaces::start`] did.
*/
@@ -20765,6 +21197,286 @@ const FfiConverterTypeSpaceSendFileReport = (() => {
return new FFIConverter();
})();
+/**
+ * A health check: exactly one of `http`, `tcp`, `command`.
+ */
+export type SpaceServiceProbe = {
+ /**
+ * A URL that answers 2xx or 3xx.
+ */
+ http?: string,
+ /**
+ * `host:port` that accepts a TCP connection.
+ */
+ tcp?: string,
+ /**
+ * A shell command that exits 0 when healthy.
+ */
+ command?: string,
+ /**
+ * Seconds between checks (default 10).
+ */
+ intervalSecs?: bigint,
+ /**
+ * Failed checks in a row that restart it (default 3).
+ */
+ failures?: number
+}
+
+/**
+ * Generated factory for {@link SpaceServiceProbe} record objects.
+ */
+export const SpaceServiceProbe = (() => {
+ const defaults = () => ({
+ http: undefined,
+ tcp: undefined,
+ command: undefined,
+ intervalSecs: undefined,
+ failures: undefined
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SpaceServiceProbe, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SpaceServiceProbe>,
+ });
+})();
+
+const FfiConverterTypeSpaceServiceProbe = (() => {
+ type TypeName = SpaceServiceProbe;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ http: FfiConverterOptionalString.read(from),
+ tcp: FfiConverterOptionalString.read(from),
+ command: FfiConverterOptionalString.read(from),
+ intervalSecs: FfiConverterOptionalUInt64.read(from),
+ failures: FfiConverterOptionalUInt32.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalString.write(value.http, into);
+ FfiConverterOptionalString.write(value.tcp, into);
+ FfiConverterOptionalString.write(value.command, into);
+ FfiConverterOptionalUInt64.write(value.intervalSecs, into);
+ FfiConverterOptionalUInt32.write(value.failures, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalString.allocationSize(value.http) +
+ FfiConverterOptionalString.allocationSize(value.tcp) +
+ FfiConverterOptionalString.allocationSize(value.command) +
+ FfiConverterOptionalUInt64.allocationSize(value.intervalSecs) +
+ FfiConverterOptionalUInt32.allocationSize(value.failures);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * A command a Space keeps running ([`Space::put_service`]).
+ */
+export type SpaceServiceDef = {
+ /**
+ * Name: lowercase letters, digits, `-`, `_`, `.` (1 to 63).
+ */
+ name: string,
+ /**
+ * The shell command line it runs.
+ */
+ command: string,
+ /**
+ * Extra environment.
+ */
+ env: Map<string, string>,
+ /**
+ * Working directory.
+ */
+ cwd?: string,
+ /**
+ * When it is started again: `always` (default), `on-failure` or
+ * `never`.
+ */
+ restart?: string,
+ /**
+ * A health check; failing it restarts the service.
+ */
+ probe?: SpaceServiceProbe,
+ /**
+ * Start it when the Space boots. `None`: yes.
+ */
+ startOnBoot?: boolean
+}
+
+/**
+ * Generated factory for {@link SpaceServiceDef} record objects.
+ */
+export const SpaceServiceDef = (() => {
+ const defaults = () => ({
+ env: new Map(),
+ cwd: undefined,
+ restart: undefined,
+ probe: undefined,
+ startOnBoot: undefined
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SpaceServiceDef, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SpaceServiceDef>,
+ });
+})();
+
+const FfiConverterTypeSpaceServiceDef = (() => {
+ type TypeName = SpaceServiceDef;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ name: FfiConverterString.read(from),
+ command: FfiConverterString.read(from),
+ env: FfiConverterMapStringString.read(from),
+ cwd: FfiConverterOptionalString.read(from),
+ restart: FfiConverterOptionalString.read(from),
+ probe: FfiConverterOptionalTypeSpaceServiceProbe.read(from),
+ startOnBoot: FfiConverterOptionalBoolean.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.name, into);
+ FfiConverterString.write(value.command, into);
+ FfiConverterMapStringString.write(value.env, into);
+ FfiConverterOptionalString.write(value.cwd, into);
+ FfiConverterOptionalString.write(value.restart, into);
+ FfiConverterOptionalTypeSpaceServiceProbe.write(value.probe, into);
+ FfiConverterOptionalBoolean.write(value.startOnBoot, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.name) +
+ FfiConverterString.allocationSize(value.command) +
+ FfiConverterMapStringString.allocationSize(value.env) +
+ FfiConverterOptionalString.allocationSize(value.cwd) +
+ FfiConverterOptionalString.allocationSize(value.restart) +
+ FfiConverterOptionalTypeSpaceServiceProbe.allocationSize(value.probe) +
+ FfiConverterOptionalBoolean.allocationSize(value.startOnBoot);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * A service and how it is doing ([`Space::services`]).
+ */
+export type SpaceServiceInfo = {
+ /**
+ * Name.
+ */
+ name: string,
+ /**
+ * The command line.
+ */
+ command: string,
+ /**
+ * `starting`, `running`, `unhealthy`, `backoff`, `stopped`, `exited`
+ * or `failed`.
+ */
+ state: string,
+ /**
+ * Its process, while it runs.
+ */
+ pid: number,
+ /**
+ * Starts after the first.
+ */
+ restarts: number,
+ /**
+ * How the last process ended, if one did.
+ */
+ lastEnd: string,
+ /**
+ * The last failed health check, if the last one failed.
+ */
+ probeError: string,
+ /**
+ * `always`, `on-failure` or `never`.
+ */
+ restart: string,
+ /**
+ * Starts when the Space boots.
+ */
+ startOnBoot: boolean,
+ /**
+ * Its log file in the Space.
+ */
+ logPath: string
+}
+
+/**
+ * Generated factory for {@link SpaceServiceInfo} record objects.
+ */
+export const SpaceServiceInfo = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SpaceServiceInfo, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SpaceServiceInfo>,
+ });
+})();
+
+const FfiConverterTypeSpaceServiceInfo = (() => {
+ type TypeName = SpaceServiceInfo;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ name: FfiConverterString.read(from),
+ command: FfiConverterString.read(from),
+ state: FfiConverterString.read(from),
+ pid: FfiConverterUInt32.read(from),
+ restarts: FfiConverterUInt32.read(from),
+ lastEnd: FfiConverterString.read(from),
+ probeError: FfiConverterString.read(from),
+ restart: FfiConverterString.read(from),
+ startOnBoot: FfiConverterBool.read(from),
+ logPath: FfiConverterString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.name, into);
+ FfiConverterString.write(value.command, into);
+ FfiConverterString.write(value.state, into);
+ FfiConverterUInt32.write(value.pid, into);
+ FfiConverterUInt32.write(value.restarts, into);
+ FfiConverterString.write(value.lastEnd, into);
+ FfiConverterString.write(value.probeError, into);
+ FfiConverterString.write(value.restart, into);
+ FfiConverterBool.write(value.startOnBoot, into);
+ FfiConverterString.write(value.logPath, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.name) +
+ FfiConverterString.allocationSize(value.command) +
+ FfiConverterString.allocationSize(value.state) +
+ FfiConverterUInt32.allocationSize(value.pid) +
+ FfiConverterUInt32.allocationSize(value.restarts) +
+ FfiConverterString.allocationSize(value.lastEnd) +
+ FfiConverterString.allocationSize(value.probeError) +
+ FfiConverterString.allocationSize(value.restart) +
+ FfiConverterBool.allocationSize(value.startOnBoot) +
+ FfiConverterString.allocationSize(value.logPath);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* One account a Space is shared with.
*/
@@ -23433,6 +24145,207 @@ const FfiConverterTypeTransferResult = (() => {
return new FFIConverter();
})();
+/**
+ * What a tree's children may hold and cost ([`Spaces::set_tree_budget`]).
+ * `None`: the default.
+ */
+export type TreeBudgetLimits = {
+ /**
+ * Child Spaces at once (default 16).
+ */
+ maxSpaces?: number,
+ /**
+ * vCPUs at once (default 16).
+ */
+ maxVcpus?: number,
+ /**
+ * Memory at once, MiB (default 32768).
+ */
+ maxMemoryMb?: bigint,
+ /**
+ * Cost per hour, in linked clouds (default 2.0).
+ */
+ usdPerHour?: number,
+ /**
+ * Cost in total (default: none).
+ */
+ usdTotal?: number
+}
+
+/**
+ * Generated factory for {@link TreeBudgetLimits} record objects.
+ */
+export const TreeBudgetLimits = (() => {
+ const defaults = () => ({
+ maxSpaces: undefined,
+ maxVcpus: undefined,
+ maxMemoryMb: undefined,
+ usdPerHour: undefined,
+ usdTotal: undefined
+ });
+ const create = (() => {
+ return uniffiCreateRecord<TreeBudgetLimits, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<TreeBudgetLimits>,
+ });
+})();
+
+const FfiConverterTypeTreeBudgetLimits = (() => {
+ type TypeName = TreeBudgetLimits;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ maxSpaces: FfiConverterOptionalUInt32.read(from),
+ maxVcpus: FfiConverterOptionalUInt32.read(from),
+ maxMemoryMb: FfiConverterOptionalUInt64.read(from),
+ usdPerHour: FfiConverterOptionalFloat64.read(from),
+ usdTotal: FfiConverterOptionalFloat64.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalUInt32.write(value.maxSpaces, into);
+ FfiConverterOptionalUInt32.write(value.maxVcpus, into);
+ FfiConverterOptionalUInt64.write(value.maxMemoryMb, into);
+ FfiConverterOptionalFloat64.write(value.usdPerHour, into);
+ FfiConverterOptionalFloat64.write(value.usdTotal, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalUInt32.allocationSize(value.maxSpaces) +
+ FfiConverterOptionalUInt32.allocationSize(value.maxVcpus) +
+ FfiConverterOptionalUInt64.allocationSize(value.maxMemoryMb) +
+ FfiConverterOptionalFloat64.allocationSize(value.usdPerHour) +
+ FfiConverterOptionalFloat64.allocationSize(value.usdTotal);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * A tree's budget and what its children use ([`Spaces::tree_budget`]).
+ */
+export type TreeBudget = {
+ /**
+ * The tree's top-level Space.
+ */
+ root: string,
+ /**
+ * What the owner set.
+ */
+ set: TreeBudgetLimits,
+ /**
+ * Child Spaces it may hold at once.
+ */
+ maxSpaces: number,
+ /**
+ * vCPUs it may hold at once.
+ */
+ maxVcpus: number,
+ /**
+ * Memory it may hold at once (MiB).
+ */
+ maxMemoryMb: bigint,
+ /**
+ * Cost per hour it may run at.
+ */
+ usdPerHour: number,
+ /**
+ * Cost in total it may reach, when capped.
+ */
+ usdTotal?: number,
+ /**
+ * Child Spaces now.
+ */
+ spaces: number,
+ /**
+ * vCPUs they hold.
+ */
+ vcpus: number,
+ /**
+ * Memory they hold (MiB).
+ */
+ memoryMb: bigint,
+ /**
+ * Cost per hour they run at.
+ */
+ usdPerHourUsed: number,
+ /**
+ * What they have cost so far.
+ */
+ usdSpent: number
+}
+
+/**
+ * Generated factory for {@link TreeBudget} record objects.
+ */
+export const TreeBudget = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<TreeBudget, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<TreeBudget>,
+ });
+})();
+
+const FfiConverterTypeTreeBudget = (() => {
+ type TypeName = TreeBudget;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ root: FfiConverterString.read(from),
+ set: FfiConverterTypeTreeBudgetLimits.read(from),
+ maxSpaces: FfiConverterUInt32.read(from),
+ maxVcpus: FfiConverterUInt32.read(from),
+ maxMemoryMb: FfiConverterUInt64.read(from),
+ usdPerHour: FfiConverterFloat64.read(from),
+ usdTotal: FfiConverterOptionalFloat64.read(from),
+ spaces: FfiConverterUInt32.read(from),
+ vcpus: FfiConverterUInt32.read(from),
+ memoryMb: FfiConverterUInt64.read(from),
+ usdPerHourUsed: FfiConverterFloat64.read(from),
+ usdSpent: FfiConverterFloat64.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.root, into);
+ FfiConverterTypeTreeBudgetLimits.write(value.set, into);
+ FfiConverterUInt32.write(value.maxSpaces, into);
+ FfiConverterUInt32.write(value.maxVcpus, into);
+ FfiConverterUInt64.write(value.maxMemoryMb, into);
+ FfiConverterFloat64.write(value.usdPerHour, into);
+ FfiConverterOptionalFloat64.write(value.usdTotal, into);
+ FfiConverterUInt32.write(value.spaces, into);
+ FfiConverterUInt32.write(value.vcpus, into);
+ FfiConverterUInt64.write(value.memoryMb, into);
+ FfiConverterFloat64.write(value.usdPerHourUsed, into);
+ FfiConverterFloat64.write(value.usdSpent, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.root) +
+ FfiConverterTypeTreeBudgetLimits.allocationSize(value.set) +
+ FfiConverterUInt32.allocationSize(value.maxSpaces) +
+ FfiConverterUInt32.allocationSize(value.maxVcpus) +
+ FfiConverterUInt64.allocationSize(value.maxMemoryMb) +
+ FfiConverterFloat64.allocationSize(value.usdPerHour) +
+ FfiConverterOptionalFloat64.allocationSize(value.usdTotal) +
+ FfiConverterUInt32.allocationSize(value.spaces) +
+ FfiConverterUInt32.allocationSize(value.vcpus) +
+ FfiConverterUInt64.allocationSize(value.memoryMb) +
+ FfiConverterFloat64.allocationSize(value.usdPerHourUsed) +
+ FfiConverterFloat64.allocationSize(value.usdSpent);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* Upload options.
*/
@@ -37823,6 +38736,10 @@ export interface SpaceLike {
* Closes a media session opened with [`Space::open_stream`].
*/
closeStream(mediaSessionId: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
+/**
+ * Stops a service and forgets it (its logs go too).
+ */
+ deleteService(name: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
/**
* The Space's displays, primary first, with their resolution in
* physical pixels.
@@ -37877,6 +38794,10 @@ export interface SpaceLike {
* roster.
*/
joinPresence(identity: PresenceIdentity, timeoutMs: bigint | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpacePresenceLike>;
+/**
+ * This Space's services.
+ */
+ keptServices(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<SpaceServiceInfo>>;
/**
* Tools of the Space's MCP service (`driver`, the default).
*/
@@ -37886,6 +38807,12 @@ export interface SpaceLike {
* to attach to.
*/
openStream(options: SpaceStreamOptions, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceStreamTicket>;
+/**
+ * Keeps a command running in this Space (replacing a service of that
+ * name): restarted by its policy when it ends or fails its health
+ * check, started when the Space boots, its output kept in a log file.
+ */
+ putService(def: SpaceServiceDef, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceServiceInfo>;
/**
* Signs in to a site in this Space's browser with a password the user
* saved in the Cua Keyvault. The first call files a request
@@ -37895,6 +38822,10 @@ export interface SpaceLike {
* declined request is an error. The password never reaches the caller.
*/
requestSiteLogin(url: string, options: SiteLoginOptions | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SiteLoginReport>;
+/**
+ * Restarts a service.
+ */
+ restartService(name: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceServiceInfo>;
/**
* Which way this Space's calls go now (see [`super::spacesd::SpacesdClient::route`]):
* `local …`, `direct …`, `relay …`, `mesh direct <ip:port> rtt <ms> ms`,
@@ -37914,6 +38845,10 @@ export interface SpaceLike {
* (TeleportService.ReceiveFiles, per-file SHA-256).
*/
sendFile(localPath: string, options: SpaceSendFileOptions, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceSendFileReport>;
+/**
+ * The end of a service's log (`tail_bytes` `None`: 64 KiB).
+ */
+ serviceLogs(name: string, tailBytes: bigint | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
/**
* The MCP services this Space exposes: `driver` when its spacesd has
* the tool registry, then every declared service (reached over generic
@@ -37947,10 +38882,18 @@ export interface SpaceLike {
* (default false here).
*/
startHotspot(setSystemProxy: boolean | undefined, bypass: Array<string> | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceHotspotStatus>;
+/**
+ * Starts a stopped service.
+ */
+ startService(name: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceServiceInfo>;
/**
* Stops this Space's hotspot. Returns the stopped Space ids.
*/
stopHotspot(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<string>>;
+/**
+ * Stops a service and keeps it stopped (also across a reboot).
+ */
+ stopService(name: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceServiceInfo>;
/**
* Opens a media session and delivers keyframe-gated encoded frames
* and audio to the sinks (one delivery thread; decoding stays with the
@@ -38587,6 +39530,36 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Stops a service and forgets it (its logs go too).
+ */
+ async deleteService(name: string, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_delete_service(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_void,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_void,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_void,
+ /*liftFunc:*/ (_v) => {},
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* The Space's displays, primary first, with their resolution in
* physical pixels.
@@ -38777,16 +39750,389 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * This Space's hotspot status.
+ * This Space's hotspot status.
+ */
+ async hotspotStatus(asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceHotspotStatus>> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_hotspot_status(
+ uniffiTypeSpaceObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeSpaceHotspotStatus.lift.bind(FfiConverterSequenceTypeSpaceHotspotStatus),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Id.
+ */
+ id(): string {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterString.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_id(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Connection-time snapshot; never refreshed. With spacesd, handshake
+ * `os`, `os_name`, `os_pretty_name` replace record values; missing/unknown
+ * families clear them. Other fields and non-spacesd services retain
+ * registry/discovery values. `Spaces.list()`/`Spaces.resolve()` remain record views.
+ */
+ info(): SpaceInfo {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterTypeSpaceInfo.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_info(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Joins presence. Waits up to `timeout_ms` (default 10 s) for the
+ * roster.
+ */
+ async joinPresence(identity: PresenceIdentity, timeoutMs: bigint | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SpacePresenceLike> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_join_presence(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterTypePresenceIdentity.lower(identity, nativeModule().rustbuffer_alloc),FfiConverterOptionalUInt64.lower(timeoutMs, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_u64,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_u64,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_u64,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_u64,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSpacePresence.lift.bind(FfiConverterTypeSpacePresence),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * This Space's services.
+ */
+ async keptServices(asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceServiceInfo>> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_kept_services(
+ uniffiTypeSpaceObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeSpaceServiceInfo.lift.bind(FfiConverterSequenceTypeSpaceServiceInfo),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Tools of the Space's MCP service (`driver`, the default).
+ */
+ async listTools(service: string | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceToolInfo>> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_list_tools(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalString.lower(service, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeSpaceToolInfo.lift.bind(FfiConverterSequenceTypeSpaceToolInfo),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Mints a media session (ticket + WebSocket URL) for another client
+ * to attach to.
+ */
+ async openStream(options: SpaceStreamOptions, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceStreamTicket> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_open_stream(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterTypeSpaceStreamOptions.lower(options, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSpaceStreamTicket.lift.bind(FfiConverterTypeSpaceStreamTicket),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Keeps a command running in this Space (replacing a service of that
+ * name): restarted by its policy when it ends or fails its health
+ * check, started when the Space boots, its output kept in a log file.
+ */
+ async putService(def: SpaceServiceDef, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceServiceInfo> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_put_service(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterTypeSpaceServiceDef.lower(def, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSpaceServiceInfo.lift.bind(FfiConverterTypeSpaceServiceInfo),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Signs in to a site in this Space's browser with a password the user
+ * saved in the Cua Keyvault. The first call files a request
+ * (`status == "pending"` with a `request_id`); the user approves it in
+ * Cua, then call again with that `request_id` and the Keyvault types
+ * the login through the Space's cua-driver (`status == "filled"`). A
+ * declined request is an error. The password never reaches the caller.
+ */
+ async requestSiteLogin(url: string, options: SiteLoginOptions | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SiteLoginReport> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_request_site_login(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(url, nativeModule().rustbuffer_alloc),FfiConverterOptionalTypeSiteLoginOptions.lower(options, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSiteLoginReport.lift.bind(FfiConverterTypeSiteLoginReport),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Restarts a service.
+ */
+ async restartService(name: string, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceServiceInfo> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_restart_service(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSpaceServiceInfo.lift.bind(FfiConverterTypeSpaceServiceInfo),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Which way this Space's calls go now (see [`super::spacesd::SpacesdClient::route`]):
+ * `local …`, `direct …`, `relay …`, `mesh direct <ip:port> rtt <ms> ms`,
+ * `mesh relayed` or `cloud`; empty when the Space runs no cua-spacesd.
+ * In daemon mode it is the daemon's connection to the Space.
+ */
+ async route(asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_route(
+ uniffiTypeSpaceObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Captures the Space's display: PNG at full size on the primary
+ * display unless `options` say otherwise (for a small preview,
+ * [`Space::thumbnail`] reads the shared cache instead). Fails with
+ * `CapabilityMissing` (`spacesd`) when the image runs no cua-spacesd.
*/
- async hotspotStatus(asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceHotspotStatus>> /*throws*/ {
+ async screenshot(options: ScreenshotOptions | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<Screenshot> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_hotspot_status(
- uniffiTypeSpaceObjectFactory.clonePointer(this)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_screenshot(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalTypeScreenshotOptions.lower(options, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -38798,86 +40144,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterSequenceTypeSpaceHotspotStatus.lift.bind(FfiConverterSequenceTypeSpaceHotspotStatus),
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- /*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
- );
- } catch (__error: any) {
- if (uniffiIsDebug && __error instanceof Error) {
- __error.stack = __stack;
- }
- throw __error;
- }
- }
-
-/**
- * Id.
- */
- id(): string {
- return ((__rb: Uint8Array) => {
- try {
- return FfiConverterString.lift(__rb);
- } finally {
- nativeModule().rustbuffer_free(__rb);
- }
- })(uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_id(
- uniffiTypeSpaceObjectFactory.clonePointer(this),
- callStatus);
- },
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- ));
- }
-
-/**
- * Connection-time snapshot; never refreshed. With spacesd, handshake
- * `os`, `os_name`, `os_pretty_name` replace record values; missing/unknown
- * families clear them. Other fields and non-spacesd services retain
- * registry/discovery values. `Spaces.list()`/`Spaces.resolve()` remain record views.
- */
- info(): SpaceInfo {
- return ((__rb: Uint8Array) => {
- try {
- return FfiConverterTypeSpaceInfo.lift(__rb);
- } finally {
- nativeModule().rustbuffer_free(__rb);
- }
- })(uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_info(
- uniffiTypeSpaceObjectFactory.clonePointer(this),
- callStatus);
- },
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- ));
- }
-
-/**
- * Joins presence. Waits up to `timeout_ms` (default 10 s) for the
- * roster.
- */
- async joinPresence(identity: PresenceIdentity, timeoutMs: bigint | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SpacePresenceLike> /*throws*/ {
- const __stack = uniffiIsDebug ? new Error().stack : undefined;
- try {
- return await uniffiRustCallAsync(
- /*rustCaller:*/ uniffiCaller,
- /*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_join_presence(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterTypePresenceIdentity.lower(identity, nativeModule().rustbuffer_alloc),FfiConverterOptionalUInt64.lower(timeoutMs, nativeModule().rustbuffer_alloc)
- );
- },
- /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_u64,
- /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_u64,
- /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_u64,
- /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_u64,
- // Async returns always go through the JS-side converter: the
- // FFI symbol returns the future handle (u64), and the user-level
- // RustBuffer comes back via the shared `rust_future_complete_*`
- // export. The bytes the runtime hands back must be deserialized
- // here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSpacePresence.lift.bind(FfiConverterTypeSpacePresence),
+ /*liftFunc:*/ FfiConverterTypeScreenshot.lift.bind(FfiConverterTypeScreenshot),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -38891,16 +40158,17 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Tools of the Space's MCP service (`driver`, the default).
+ * Drops a host file or folder into the Space's `~/Downloads[/subdir]`
+ * (TeleportService.ReceiveFiles, per-file SHA-256).
*/
- async listTools(service: string | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceToolInfo>> /*throws*/ {
+ async sendFile(localPath: string, options: SpaceSendFileOptions, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceSendFileReport> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_list_tools(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalString.lower(service, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_send_file(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(localPath, nativeModule().rustbuffer_alloc),FfiConverterTypeSpaceSendFileOptions.lower(options, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -38912,7 +40180,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterSequenceTypeSpaceToolInfo.lift.bind(FfiConverterSequenceTypeSpaceToolInfo),
+ /*liftFunc:*/ FfiConverterTypeSpaceSendFileReport.lift.bind(FfiConverterTypeSpaceSendFileReport),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -38926,17 +40194,16 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Mints a media session (ticket + WebSocket URL) for another client
- * to attach to.
+ * The end of a service's log (`tail_bytes` `None`: 64 KiB).
*/
- async openStream(options: SpaceStreamOptions, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceStreamTicket> /*throws*/ {
+ async serviceLogs(name: string, tailBytes: bigint | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_open_stream(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterTypeSpaceStreamOptions.lower(options, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_service_logs(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc),FfiConverterOptionalUInt64.lower(tailBytes, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -38948,7 +40215,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSpaceStreamTicket.lift.bind(FfiConverterTypeSpaceStreamTicket),
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -38962,71 +40229,48 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Signs in to a site in this Space's browser with a password the user
- * saved in the Cua Keyvault. The first call files a request
- * (`status == "pending"` with a `request_id`); the user approves it in
- * Cua, then call again with that `request_id` and the Keyvault types
- * the login through the Space's cua-driver (`status == "filled"`). A
- * declined request is an error. The password never reaches the caller.
+ * The MCP services this Space exposes: `driver` when its spacesd has
+ * the tool registry, then every declared service (reached over generic
+ * MCP; no spacesd needed).
*/
- async requestSiteLogin(url: string, options: SiteLoginOptions | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SiteLoginReport> /*throws*/ {
- const __stack = uniffiIsDebug ? new Error().stack : undefined;
- try {
- return await uniffiRustCallAsync(
- /*rustCaller:*/ uniffiCaller,
- /*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_request_site_login(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(url, nativeModule().rustbuffer_alloc),FfiConverterOptionalTypeSiteLoginOptions.lower(options, nativeModule().rustbuffer_alloc)
- );
+ services(): Array<string> {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterSequenceString.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_sdk_fn_method_space_services(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),
+ callStatus);
},
- /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
- /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
- /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
- /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
- // Async returns always go through the JS-side converter: the
- // FFI symbol returns the future handle (u64), and the user-level
- // RustBuffer comes back via the shared `rust_future_complete_*`
- // export. The bytes the runtime hands back must be deserialized
- // here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSiteLoginReport.lift.bind(FfiConverterTypeSiteLoginReport),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- /*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
- );
- } catch (__error: any) {
- if (uniffiIsDebug && __error instanceof Error) {
- __error.stack = __stack;
- }
- throw __error;
- }
+ ));
}
/**
- * Which way this Space's calls go now (see [`super::spacesd::SpacesdClient::route`]):
- * `local …`, `direct …`, `relay …`, `mesh direct <ip:port> rtt <ms> ms`,
- * `mesh relayed` or `cloud`; empty when the Space runs no cua-spacesd.
- * In daemon mode it is the daemon's connection to the Space.
+ * Sets this Space's presence settings. `cursor_probe`: whether
+ * cua-spacesd may read the real cursor shape by briefly moving the idle
+ * guest pointer to a participant's position (on by default); `None`
+ * leaves it unchanged.
*/
- async route(asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ async setPresenceSettings(cursorProbe: boolean | undefined = undefined, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_route(
- uniffiTypeSpaceObjectFactory.clonePointer(this)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_set_presence_settings(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalBoolean.lower(cursorProbe, nativeModule().rustbuffer_alloc)
);
},
- /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
- /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
- /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
- /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
- // Async returns always go through the JS-side converter: the
- // FFI symbol returns the future handle (u64), and the user-level
- // RustBuffer comes back via the shared `rust_future_complete_*`
- // export. The bytes the runtime hands back must be deserialized
- // here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_void,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_void,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_void,
+ /*liftFunc:*/ (_v) => {},
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -39040,19 +40284,18 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Captures the Space's display: PNG at full size on the primary
- * display unless `options` say otherwise (for a small preview,
- * [`Space::thumbnail`] reads the shared cache instead). Fails with
- * `CapabilityMissing` (`spacesd`) when the image runs no cua-spacesd.
+ * Lets `who` (a verified email or an account id) watch (`viewer`,
+ * the default) or use (`editor`) this Space through the relay. A Space
+ * that is not a host is attached to the relay on its first share.
*/
- async screenshot(options: ScreenshotOptions | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<Screenshot> /*throws*/ {
+ async share(who: string, role: string | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceShares> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_screenshot(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalTypeScreenshotOptions.lower(options, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_share(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(who, nativeModule().rustbuffer_alloc),FfiConverterOptionalString.lower(role, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -39064,7 +40307,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeScreenshot.lift.bind(FfiConverterTypeScreenshot),
+ /*liftFunc:*/ FfiConverterTypeSpaceShares.lift.bind(FfiConverterTypeSpaceShares),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -39078,17 +40321,16 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Drops a host file or folder into the Space's `~/Downloads[/subdir]`
- * (TeleportService.ReceiveFiles, per-file SHA-256).
+ * Who this Space is shared with, and who of them is connected now.
*/
- async sendFile(localPath: string, options: SpaceSendFileOptions, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceSendFileReport> /*throws*/ {
+ async shares(asyncOpts_?: { signal: AbortSignal }): Promise<SpaceShares> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_send_file(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(localPath, nativeModule().rustbuffer_alloc),FfiConverterTypeSpaceSendFileOptions.lower(options, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_shares(
+ uniffiTypeSpaceObjectFactory.clonePointer(this)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -39100,7 +40342,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSpaceSendFileReport.lift.bind(FfiConverterTypeSpaceSendFileReport),
+ /*liftFunc:*/ FfiConverterTypeSpaceShares.lift.bind(FfiConverterTypeSpaceShares),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -39114,20 +40356,13 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * The MCP services this Space exposes: `driver` when its spacesd has
- * the tool registry, then every declared service (reached over generic
- * MCP; no spacesd needed).
+ * The cua-spacesd client over the connection this Space authenticated.
*/
- services(): Array<string> {
- return ((__rb: Uint8Array) => {
- try {
- return FfiConverterSequenceString.lift(__rb);
- } finally {
- nativeModule().rustbuffer_free(__rb);
- }
- })(uniffiCaller.rustCall(
+ spacesd(): SpacesdClientLike /*throws*/ {
+ return FfiConverterTypeSpacesdClient.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError),
/*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_services(
+ return nativeModule().uniffi_cua_sdk_fn_method_space_spacesd(
uniffiTypeSpaceObjectFactory.clonePointer(this),
callStatus);
},
@@ -39136,51 +40371,18 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Sets this Space's presence settings. `cursor_probe`: whether
- * cua-spacesd may read the real cursor shape by briefly moving the idle
- * guest pointer to a participant's position (on by default); `None`
- * leaves it unchanged.
- */
- async setPresenceSettings(cursorProbe: boolean | undefined = undefined, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
- const __stack = uniffiIsDebug ? new Error().stack : undefined;
- try {
- return await uniffiRustCallAsync(
- /*rustCaller:*/ uniffiCaller,
- /*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_set_presence_settings(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalBoolean.lower(cursorProbe, nativeModule().rustbuffer_alloc)
- );
- },
- /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,
- /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_void,
- /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_void,
- /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_void,
- /*liftFunc:*/ (_v) => {},
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- /*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
- );
- } catch (__error: any) {
- if (uniffiIsDebug && __error instanceof Error) {
- __error.stack = __stack;
- }
- throw __error;
- }
- }
-
-/**
- * Lets `who` (a verified email or an account id) watch (`viewer`,
- * the default) or use (`editor`) this Space through the relay. A Space
- * that is not a host is attached to the relay on its first share.
+ * Starts the reverse-SOCKS hotspot: this host serves the Space's
+ * egress. `set_system_proxy` points the guest's proxy settings at it
+ * (default false here).
*/
- async share(who: string, role: string | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceShares> /*throws*/ {
+ async startHotspot(setSystemProxy: boolean | undefined, bypass: Array<string> | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceHotspotStatus> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_share(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(who, nativeModule().rustbuffer_alloc),FfiConverterOptionalString.lower(role, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_start_hotspot(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalBoolean.lower(setSystemProxy, nativeModule().rustbuffer_alloc),FfiConverterOptionalSequenceString.lower(bypass, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -39192,7 +40394,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSpaceShares.lift.bind(FfiConverterTypeSpaceShares),
+ /*liftFunc:*/ FfiConverterTypeSpaceHotspotStatus.lift.bind(FfiConverterTypeSpaceHotspotStatus),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -39206,16 +40408,16 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Who this Space is shared with, and who of them is connected now.
+ * Starts a stopped service.
*/
- async shares(asyncOpts_?: { signal: AbortSignal }): Promise<SpaceShares> /*throws*/ {
+ async startService(name: string, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceServiceInfo> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_shares(
- uniffiTypeSpaceObjectFactory.clonePointer(this)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_start_service(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -39227,7 +40429,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSpaceShares.lift.bind(FfiConverterTypeSpaceShares),
+ /*liftFunc:*/ FfiConverterTypeSpaceServiceInfo.lift.bind(FfiConverterTypeSpaceServiceInfo),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -39241,33 +40443,16 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * The cua-spacesd client over the connection this Space authenticated.
- */
- spacesd(): SpacesdClientLike /*throws*/ {
- return FfiConverterTypeSpacesdClient.lift(uniffiCaller.rustCallWithError(
- /*liftError:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError),
- /*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_spacesd(
- uniffiTypeSpaceObjectFactory.clonePointer(this),
- callStatus);
- },
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- ));
- }
-
-/**
- * Starts the reverse-SOCKS hotspot: this host serves the Space's
- * egress. `set_system_proxy` points the guest's proxy settings at it
- * (default false here).
+ * Stops this Space's hotspot. Returns the stopped Space ids.
*/
- async startHotspot(setSystemProxy: boolean | undefined, bypass: Array<string> | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceHotspotStatus> /*throws*/ {
+ async stopHotspot(asyncOpts_?: { signal: AbortSignal }): Promise<Array<string>> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_start_hotspot(
- uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterOptionalBoolean.lower(setSystemProxy, nativeModule().rustbuffer_alloc),FfiConverterOptionalSequenceString.lower(bypass, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_stop_hotspot(
+ uniffiTypeSpaceObjectFactory.clonePointer(this)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -39279,7 +40464,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeSpaceHotspotStatus.lift.bind(FfiConverterTypeSpaceHotspotStatus),
+ /*liftFunc:*/ FfiConverterSequenceString.lift.bind(FfiConverterSequenceString),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -39293,16 +40478,16 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Stops this Space's hotspot. Returns the stopped Space ids.
+ * Stops a service and keeps it stopped (also across a reboot).
*/
- async stopHotspot(asyncOpts_?: { signal: AbortSignal }): Promise<Array<string>> /*throws*/ {
+ async stopService(name: string, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceServiceInfo> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_sdk_fn_method_space_stop_hotspot(
- uniffiTypeSpaceObjectFactory.clonePointer(this)
+ return nativeModule().uniffi_cua_sdk_fn_method_space_stop_service(
+ uniffiTypeSpaceObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
@@ -39314,7 +40499,7 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterSequenceString.lift.bind(FfiConverterSequenceString),
+ /*liftFunc:*/ FfiConverterTypeSpaceServiceInfo.lift.bind(FfiConverterTypeSpaceServiceInfo),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
/*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
@@ -40496,6 +41681,11 @@ const FfiConverterTypeResourcesWatch = new FfiConverterObject(uniffiTypeResource
*/
export interface SpacesLike {
+/**
+ * Marks the one-time notice about the new network defaults as shown
+ * for `space` ([`SpaceNetworkInfo::notice_pending`]).
+ */
+ ackNetworkNotice(space: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
/**
* Adds a Space by URL (`http(s)://host:port`, `host:port`, or a
* Space id such as `local:<name>`) after a `GetCapabilities` handshake. Any other MCP
@@ -40676,7 +41866,8 @@ export interface SpacesLike {
createWithProgress(options: SpaceCreateOptions, listener: SpaceCreateListener, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceCreateResult>;
/**
* Deletes a Space's sandbox and forgets it (a Space added by address
- * is only forgotten). Returns what happened.
+ * is only forgotten). Its child Spaces are deleted first. Returns what
+ * happened.
*/
delete_(space: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
/**
@@ -40692,6 +41883,11 @@ export interface SpacesLike {
* order; one failure never stops the rest.
*/
deleteMany(ids: Array<string>, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<BulkResult>>;
+/**
+ * [`Spaces::delete`], with `keep_children`: its child Spaces become
+ * top-level Spaces and keep running instead of being deleted first.
+ */
+ deleteTree(space: string, keepChildren: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
/**
* Deletes the named volume `name` and its files (their history stays
* in the Cua Volume). Refused while Spaces mount it unless `force`.
@@ -40757,6 +41953,11 @@ export interface SpacesLike {
* offline, not yours, or runs a Cua that predates the check.
*/
machineHealth(machine: string | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<MachineHealth>;
+/**
+ * A Space's network: its settings, what they open, where they are
+ * enforced (or why its network is cut), and what is always blocked.
+ */
+ network(space: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpaceNetworkInfo>;
/**
* The notifications feed, newest first.
*/
@@ -40769,6 +41970,12 @@ export interface SpacesLike {
* Posts a notification to the Cua app. Returns its id.
*/
notifyUser(title: string, body: string | undefined, agent: string | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
+/**
+ * Child Spaces whose parent is gone or out of reach. The cua daemon
+ * ends a child only on proof its parent is gone (after a grace period);
+ * the rest are listed here and never ended by it.
+ */
+ orphans(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<SpaceOrphan>>;
/**
* Creates a persistent agent: `harness` working in `space`, its home at
* `agents/<name>/` in the Cua Volume.
@@ -40875,6 +42082,16 @@ export interface SpacesLike {
* Routines (of one agent, or all).
*/
routines(agent: string | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<RoutineInfo>>;
+/**
+ * Lets a Space make child Spaces of its own, or stops it. While on,
+ * `cua`, the SDKs and the agent's tools in that Space create, list and
+ * delete Spaces that belong to it (on the same computer, never wider
+ * than it, ending no later than it), through a channel only it can
+ * reach. Off ends its capability at once; children it made keep running
+ * until deleted or their lifetime ends. Only for a Space the machine of
+ * this runtime runs itself.
+ */
+ setChildren(space: string, enabled: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
/**
* Replaces a Space's egress policy; an empty one removes it (see
* [`EgressPolicy`]). Its host enforces it at once. A bad entry is
@@ -40890,6 +42107,20 @@ export interface SpacesLike {
* Embedded: recorded; the cua daemon on this machine enforces it.
*/
setLifetime(space: string, seconds: bigint, onExpire: string | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<bigint>;
+/**
+ * Replaces a Space's network settings (see [`NetworkSettings`]). A
+ * child stays within its parent's unless `widen`; `tree` gives its
+ * children the same settings. They hold at once where the runtime can
+ * change a running guest's network, else from its next start
+ * (`applied`). A Space another computer runs is `Unsupported`.
+ */
+ setNetwork(space: string, settings: NetworkSettings, widen: boolean, tree: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SetNetworkResult>;
+/**
+ * Sets the budget of `space`'s tree: how many child Spaces, vCPUs and
+ * memory its children may hold at once, and what they may cost. A child
+ * that does not fit is refused with what is left. All `None` removes it.
+ */
+ setTreeBudget(space: string, limits: TreeBudgetLimits, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<TreeBudget>;
/**
* A connected handle to a registered Space.
*/
@@ -40916,6 +42147,11 @@ export interface SpacesLike {
* then. [`Spaces::stop`] stops it instead and frees its memory.
*/
suspend(space: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpacePowerReport>;
+/**
+ * The budget of `space`'s tree (any Space of it) and what its
+ * children use now. Kept by the cua daemon.
+ */
+ treeBudget(space: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<TreeBudget>;
/**
* `volume_approve`: the request becomes a grant (with presence).
*/
@@ -41069,6 +42305,37 @@ private constructor(pointer: UniffiHandle) {
+/**
+ * Marks the one-time notice about the new network defaults as shown
+ * for `space` ([`SpaceNetworkInfo::notice_pending`]).
+ */
+ async ackNetworkNotice(space: string, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_ack_network_notice(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_void,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_void,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_void,
+ /*liftFunc:*/ (_v) => {},
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Adds a Space by URL (`http(s)://host:port`, `host:port`, or a
* Space id such as `local:<name>`) after a `GetCapabilities` handshake. Any other MCP
@@ -42179,7 +43446,8 @@ private constructor(pointer: UniffiHandle) {
/**
* Deletes a Space's sandbox and forgets it (a Space added by address
- * is only forgotten). Returns what happened.
+ * is only forgotten). Its child Spaces are deleted first. Returns what
+ * happened.
*/
async delete_(space: string, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
@@ -42288,6 +43556,42 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * [`Spaces::delete`], with `keep_children`: its child Spaces become
+ * top-level Spaces and keep running instead of being deleted first.
+ */
+ async deleteTree(space: string, keepChildren: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_delete_tree(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(keepChildren, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Deletes the named volume `name` and its files (their history stays
* in the Cua Volume). Refused while Spaces mount it unless `force`.
@@ -42632,6 +43936,42 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * A Space's network: its settings, what they open, where they are
+ * enforced (or why its network is cut), and what is always blocked.
+ */
+ async network(space: string, asyncOpts_?: { signal: AbortSignal }): Promise<SpaceNetworkInfo> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_network(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSpaceNetworkInfo.lift.bind(FfiConverterTypeSpaceNetworkInfo),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* The notifications feed, newest first.
*/
@@ -42737,6 +44077,43 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Child Spaces whose parent is gone or out of reach. The cua daemon
+ * ends a child only on proof its parent is gone (after a grace period);
+ * the rest are listed here and never ended by it.
+ */
+ async orphans(asyncOpts_?: { signal: AbortSignal }): Promise<Array<SpaceOrphan>> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_orphans(
+ uniffiTypeSpacesObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeSpaceOrphan.lift.bind(FfiConverterSequenceTypeSpaceOrphan),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Creates a persistent agent: `harness` working in `space`, its home at
* `agents/<name>/` in the Cua Volume.
@@ -43422,6 +44799,42 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Lets a Space make child Spaces of its own, or stops it. While on,
+ * `cua`, the SDKs and the agent's tools in that Space create, list and
+ * delete Spaces that belong to it (on the same computer, never wider
+ * than it, ending no later than it), through a channel only it can
+ * reach. Off ends its capability at once; children it made keep running
+ * until deleted or their lifetime ends. Only for a Space the machine of
+ * this runtime runs itself.
+ */
+ async setChildren(space: string, enabled: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_set_children(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(enabled, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_void,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_void,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_void,
+ /*liftFunc:*/ (_v) => {},
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Replaces a Space's egress policy; an empty one removes it (see
* [`EgressPolicy`]). Its host enforces it at once. A bad entry is
@@ -43494,6 +44907,82 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Replaces a Space's network settings (see [`NetworkSettings`]). A
+ * child stays within its parent's unless `widen`; `tree` gives its
+ * children the same settings. They hold at once where the runtime can
+ * change a running guest's network, else from its next start
+ * (`applied`). A Space another computer runs is `Unsupported`.
+ */
+ async setNetwork(space: string, settings: NetworkSettings, widen: boolean, tree: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<SetNetworkResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_set_network(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc),FfiConverterTypeNetworkSettings.lower(settings, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(widen, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(tree, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSetNetworkResult.lift.bind(FfiConverterTypeSetNetworkResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Sets the budget of `space`'s tree: how many child Spaces, vCPUs and
+ * memory its children may hold at once, and what they may cost. A child
+ * that does not fit is refused with what is left. All `None` removes it.
+ */
+ async setTreeBudget(space: string, limits: TreeBudgetLimits, asyncOpts_?: { signal: AbortSignal }): Promise<TreeBudget> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_set_tree_budget(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc),FfiConverterTypeTreeBudgetLimits.lower(limits, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeTreeBudget.lift.bind(FfiConverterTypeTreeBudget),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* A connected handle to a registered Space.
*/
@@ -43644,6 +45133,42 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * The budget of `space`'s tree (any Space of it) and what its
+ * children use now. Kept by the cua daemon.
+ */
+ async treeBudget(space: string, asyncOpts_?: { signal: AbortSignal }): Promise<TreeBudget> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_tree_budget(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeTreeBudget.lift.bind(FfiConverterTypeTreeBudget),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* `volume_approve`: the request becomes a grant (with presence).
*/
@@ -46380,6 +47905,9 @@ const FfiConverterSequenceTypeVolumeMount = new FfiConverterArray(FfiConverterTy
// FfiConverter for EgressPolicy | undefined
const FfiConverterOptionalTypeEgressPolicy = new FfiConverterOptional(FfiConverterTypeEgressPolicy);
+// FfiConverter for NetworkSettings | undefined
+const FfiConverterOptionalTypeNetworkSettings = new FfiConverterOptional(FfiConverterTypeNetworkSettings);
+
// FfiConverter for EgressEnforcement | undefined
const FfiConverterOptionalTypeEgressEnforcement = new FfiConverterOptional(FfiConverterTypeEgressEnforcement);
@@ -46401,6 +47929,9 @@ const FfiConverterSequenceTypeSpaceCreatingElsewhere = new FfiConverterArray(Ffi
// FfiConverter for Array<SpaceSentFile>
const FfiConverterSequenceTypeSpaceSentFile = new FfiConverterArray(FfiConverterTypeSpaceSentFile);
+// FfiConverter for SpaceServiceProbe | undefined
+const FfiConverterOptionalTypeSpaceServiceProbe = new FfiConverterOptional(FfiConverterTypeSpaceServiceProbe);
+
// FfiConverter for Array<SpaceShareEntry>
const FfiConverterSequenceTypeSpaceShareEntry = new FfiConverterArray(FfiConverterTypeSpaceShareEntry);
@@ -46563,6 +48094,9 @@ const FfiConverterOptionalTypePresencePoint = new FfiConverterOptional(FfiConver
// FfiConverter for Array<PresenceDrawable>
const FfiConverterSequenceTypePresenceDrawable = new FfiConverterArray(FfiConverterTypePresenceDrawable);
+// FfiConverter for Array<SpaceServiceInfo>
+const FfiConverterSequenceTypeSpaceServiceInfo = new FfiConverterArray(FfiConverterTypeSpaceServiceInfo);
+
// FfiConverter for Array<SpaceToolInfo>
const FfiConverterSequenceTypeSpaceToolInfo = new FfiConverterArray(FfiConverterTypeSpaceToolInfo);
@@ -46584,6 +48118,9 @@ const FfiConverterSequenceTypeSpacesHost = new FfiConverterArray(FfiConverterTyp
// FfiConverter for Array<NotificationInfo>
const FfiConverterSequenceTypeNotificationInfo = new FfiConverterArray(FfiConverterTypeNotificationInfo);
+// FfiConverter for Array<SpaceOrphan>
+const FfiConverterSequenceTypeSpaceOrphan = new FfiConverterArray(FfiConverterTypeSpaceOrphan);
+
// FfiConverter for PersistentAgentOptions | undefined
const FfiConverterOptionalTypePersistentAgentOptions = new FfiConverterOptional(FfiConverterTypePersistentAgentOptions);
@@ -47506,6 +49043,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_space_close_stream() !== 64912) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_close_stream");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_delete_service() !== 14460) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_delete_service");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_displays() !== 30039) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_displays");
}
@@ -47533,15 +49073,24 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_space_join_presence() !== 56636) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_join_presence");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_kept_services() !== 50248) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_kept_services");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_list_tools() !== 19376) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_list_tools");
}
if (nativeModule().uniffi_cua_sdk_checksum_method_space_open_stream() !== 19577) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_open_stream");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_put_service() !== 55111) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_put_service");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_request_site_login() !== 2223) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_request_site_login");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_restart_service() !== 63778) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_restart_service");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_route() !== 9790) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_route");
}
@@ -47551,6 +49100,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_space_send_file() !== 29056) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_send_file");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_service_logs() !== 48773) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_service_logs");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_services() !== 32496) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_services");
}
@@ -47569,9 +49121,15 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_space_start_hotspot() !== 44744) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_start_hotspot");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_start_service() !== 13576) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_start_service");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_stop_hotspot() !== 18254) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_stop_hotspot");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_space_stop_service() !== 14671) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_stop_service");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_space_stream_session() !== 61326) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_space_stream_session");
}
@@ -47656,6 +49214,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spacestreamsession_stats() !== 40219) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spacestreamsession_stats");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_ack_network_notice() !== 32926) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_ack_network_notice");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_add() !== 56308) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_add");
}
@@ -47746,7 +49307,7 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_create_with_progress() !== 28676) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_create_with_progress");
}
- if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_delete() !== 39986) {
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_delete() !== 4316) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_delete");
}
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_delete_build() !== 6500) {
@@ -47755,6 +49316,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_delete_many() !== 9087) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_delete_many");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_delete_tree() !== 29454) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_delete_tree");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_delete_volume() !== 11412) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_delete_volume");
}
@@ -47782,6 +49346,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_machine_health() !== 35352) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_machine_health");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_network() !== 41208) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_network");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_notifications() !== 10964) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_notifications");
}
@@ -47791,6 +49358,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_notify_user() !== 48805) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_notify_user");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_orphans() !== 23539) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_orphans");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_persistent_agent_create() !== 6521) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_persistent_agent_create");
}
@@ -47848,12 +49418,21 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_routines() !== 22768) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_routines");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_set_children() !== 63927) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_set_children");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_set_egress() !== 12366) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_set_egress");
}
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_set_lifetime() !== 62609) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_set_lifetime");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_set_network() !== 64671) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_set_network");
+ }
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_set_tree_budget() !== 8418) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_set_tree_budget");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_space() !== 26355) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_space");
}
@@ -47866,6 +49445,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_suspend() !== 23817) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_suspend");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_tree_budget() !== 58333) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_tree_budget");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_volume_approve() !== 8640) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_volume_approve");
}
@@ -48319,6 +49901,7 @@ export default Object.freeze({
FfiConverterTypeMediaSession,
FfiConverterTypeMediaStats,
FfiConverterTypeNamedVolume,
+ FfiConverterTypeNetworkSettings,
FfiConverterTypeNotificationInfo,
FfiConverterTypeOverlay,
FfiConverterTypeOverlayResult,
@@ -48378,6 +49961,7 @@ export default Object.freeze({
FfiConverterTypeScreenshotOptions,
FfiConverterTypeService,
FfiConverterTypeServiceEndpoint,
+ FfiConverterTypeSetNetworkResult,
FfiConverterTypeSetupStep,
FfiConverterTypeShare,
FfiConverterTypeShareAccess,
@@ -48402,6 +49986,8 @@ export default Object.freeze({
FfiConverterTypeSpaceHotspotStatus,
FfiConverterTypeSpaceInfo,
FfiConverterTypeSpaceList,
+ FfiConverterTypeSpaceNetworkInfo,
+ FfiConverterTypeSpaceOrphan,
FfiConverterTypeSpacePowerReport,
FfiConverterTypeSpacePresence,
FfiConverterTypeSpaceRelayRegistration,
@@ -48410,6 +49996,9 @@ export default Object.freeze({
FfiConverterTypeSpaceSendFileOptions,
FfiConverterTypeSpaceSendFileReport,
FfiConverterTypeSpaceSentFile,
+ FfiConverterTypeSpaceServiceDef,
+ FfiConverterTypeSpaceServiceInfo,
+ FfiConverterTypeSpaceServiceProbe,
FfiConverterTypeSpaceShareEntry,
FfiConverterTypeSpaceShares,
FfiConverterTypeSpaceSharing,
@@ -48454,6 +50043,8 @@ export default Object.freeze({
FfiConverterTypeTeleportReceipt,
FfiConverterTypeThreadView,
FfiConverterTypeTransferResult,
+ FfiConverterTypeTreeBudget,
+ FfiConverterTypeTreeBudgetLimits,
FfiConverterTypeUploadOptions,
FfiConverterTypeVideoFrame,
FfiConverterTypeViewerLink,
diff --git a/libs/cua/typescript/test/image.test.mjs b/libs/cua/typescript/test/image.test.mjs
index e06233b8c6..328b980b5d 100644
--- a/libs/cua/typescript/test/image.test.mjs
+++ b/libs/cua/typescript/test/image.test.mjs
@@ -30,7 +30,11 @@ import { readFileSync } from "node:fs"
const catalog = JSON.parse(
readFileSync(new URL("../../../images/sandbox-images.json", import.meta.url), "utf8"),
)
-const published = (ref) => catalog.images.find((i) => i.ref === ref)?.published ?? true
+// An entry built on the user's own machine (derived_from) resolves while unpublished.
+const published = (ref) => {
+ const entry = catalog.images.find((i) => i.ref === ref)
+ return (entry?.published ?? true) || Boolean(entry?.derived_from)
+}
const expectRef = (fn, ref) => {
if (published(ref)) {
assert.equal(fn(), ref)
diff --git a/libs/cua/typescript/test/spaces.test.mjs b/libs/cua/typescript/test/spaces.test.mjs
index 79310584c5..ad37e7f3a1 100644
--- a/libs/cua/typescript/test/spaces.test.mjs
+++ b/libs/cua/typescript/test/spaces.test.mjs
@@ -45,7 +45,7 @@ function findFile(dir, name, budget = { n: 0 }) {
test("every contract tool maps to a generated method", () => {
const rows = spacesApi.spacesToolMethods()
- assert.equal(rows.length, 114)
+ assert.equal(rows.length, 118)
const classes = { Spaces: spacesApi.Spaces, Space: spacesApi.Space }
for (const row of rows) {
const [cls, method] = row.method.split(".")
@@ -259,7 +259,7 @@ async function daemonExercise(cli, teleport) {
const discovery = JSON.parse(readFileSync(join(home, "daemon.json"), "utf8"))
const session = new McpSession(new McpHttpTransport({ url: discovery.loopback_url, token: discovery.token }))
const tools = await session.listTools()
- assert.equal(tools.length, 113)
+ assert.equal(tools.length, 117)
const rows = await session.callJson("list_spaces")
assert.deepEqual(rows.map((r) => r.id), [info.id])
assert.equal(await session.callText("space_bash", { space: info.id, command: "echo webview" }), "webview\n[exit 0]")
diff --git a/libs/images/bench/osworld/image.json b/libs/images/bench/osworld/image.json
index 9e22fd54bf..66885584aa 100644
--- a/libs/images/bench/osworld/image.json
+++ b/libs/images/bench/osworld/image.json
@@ -88,6 +88,8 @@
"presence",
"presence.cursor_shape",
"hotspot",
+ "spawn",
+ "process.services",
"relay_attach",
"tunnel.forward",
"audio.desktop",
diff --git a/libs/images/bench/osworld/vm/customize.sh b/libs/images/bench/osworld/vm/customize.sh
index e1528ef5a8..cf675a57f8 100755
--- a/libs/images/bench/osworld/vm/customize.sh
+++ b/libs/images/bench/osworld/vm/customize.sh
@@ -17,6 +17,8 @@
# - cua-seed-token.service: the image has no cloud-init, so the spacesd
# token of a local SDK boot is read from its NoCloud seed (token and
# spacesd.env only; ignored when a claim share is present);
+# - cua-ipopts.service: CVE-2026-98432 interim guard (drops inbound IPv4
+# packets with IP options; this disk's kernel is the upstream 6.5);
# - netplan DHCP on any en*/eth* NIC (KubeVirt), cloud-init network off;
# - /dev/uinput for the `input` group, `user` in `input`;
# - /etc/X11/xorg.conf.d/10-cua-noblank.conf: no X screen saver or DPMS;
@@ -30,6 +32,8 @@ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BENCH="$(cd "$HERE/.." && pwd)"
REPO="$(cd "$HERE/../../../../.." && pwd)"
DESK="$REPO/libs/images/linux/files"
+# CVE-2026-98432 interim guard shared by every Linux VM variant.
+COMMON_VM="$REPO/libs/images/common/vm/files/cua-ipopts"
WORK="$OUT/work"
mkdir -p "$WORK" "$OUT"
export LIBGUESTFS_BACKEND="${LIBGUESTFS_BACKEND:-direct}"
@@ -87,6 +91,8 @@ mkdir-p /etc/systemd/system/cua-spacesd.service.d
mkdir-p /etc/systemd/system/cua-env-token-sync.service.d
mkdir-p /etc/cloud/cloud.cfg.d
mkdir-p /etc/modules-load.d
+mkdir-p /etc/sysctl.d
+mkdir-p /etc/systemd/system/sysinit.target.wants
mkdir-p /etc/X11/xorg.conf.d
upload $SPACESD /usr/local/bin/cua-spacesd
chmod 0755 /usr/local/bin/cua-spacesd
@@ -118,6 +124,12 @@ ln-sf /etc/systemd/system/cua-spacesd.service /etc/systemd/system/multi-user.tar
ln-sf /etc/systemd/system/cua-env-token-sync.service /etc/systemd/system/multi-user.target.wants/cua-env-token-sync.service
ln-sf /etc/systemd/system/cua-spacesd.service /etc/systemd/system/cua-env-driver.service
ln-sf /etc/systemd/system/cua-spacesd.service /etc/systemd/system/cua-guestd.service
+upload $COMMON_VM/cua-ipopts-guard /opt/cua/bin/cua-ipopts-guard
+chmod 0755 /opt/cua/bin/cua-ipopts-guard
+upload $COMMON_VM/cua-ipopts.nft /etc/cua-image/cua-ipopts.nft
+upload $COMMON_VM/cua-ipopts.service /etc/systemd/system/cua-ipopts.service
+upload $COMMON_VM/90-cua-ipopts.conf /etc/sysctl.d/90-cua-ipopts.conf
+ln-sf /etc/systemd/system/cua-ipopts.service /etc/systemd/system/sysinit.target.wants/cua-ipopts.service
upload $HERE/files/99-cua-dhcp.yaml /etc/netplan/99-cua-dhcp.yaml
chmod 0600 /etc/netplan/99-cua-dhcp.yaml
upload $HERE/files/99-cua-disable-network-config.cfg /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg
@@ -146,8 +158,9 @@ is-file /usr/local/bin/cua-spacesd
is-symlink /etc/systemd/system/multi-user.target.wants/cua-spacesd.service
cat /etc/systemd/system/cua-spacesd.service.d/10-osworld.conf
is-file /home/user/server/main.py
+is-symlink /etc/systemd/system/sysinit.target.wants/cua-ipopts.service
EOF
-[ "$(grep -c '^true$' "$WORK/verify.txt")" = 3 ] || { echo "verification failed" >&2; exit 1; }
+[ "$(grep -c '^true$' "$WORK/verify.txt")" = 4 ] || { echo "verification failed" >&2; exit 1; }
log "sparsify (fstrim) + flatten"
virt-sparsify --in-place "$overlay"
qemu-img convert -O qcow2 -c -p -m 8 -W "$overlay" "$OUT/disk.img"
diff --git a/libs/images/bench/web/image.json b/libs/images/bench/web/image.json
index 04b2360e20..e28ce28b81 100644
--- a/libs/images/bench/web/image.json
+++ b/libs/images/bench/web/image.json
@@ -196,6 +196,8 @@
],
"features_optional": [
"hotspot",
+ "spawn",
+ "process.services",
"relay_attach",
"h264_hw",
"audio.per_app",
diff --git a/libs/images/common/tests/ip-options-guard-guest.sh b/libs/images/common/tests/ip-options-guard-guest.sh
new file mode 100755
index 0000000000..54db3fe613
--- /dev/null
+++ b/libs/images/common/tests/ip-options-guard-guest.sh
@@ -0,0 +1,136 @@
+#!/usr/bin/env bash
+# Runs inside a booted guest (systemd PID 1, root, CAP_NET_ADMIN): proves the
+# CVE-2026-98432 interim guard drops IPv4-options packets before TCP and leaves
+# normal traffic and other firewall tables alone. Everything stays on this
+# guest's own loopback and two private network namespaces.
+set -uo pipefail
+pass=0 fail=0
+ok() { pass=$((pass + 1)); echo "ok $*"; }
+bad() { fail=$((fail + 1)); echo "FAIL $*"; }
+check() { local name="$1"; shift; if "$@"; then ok "$name"; else bad "$name"; fi; }
+GUARD=/opt/cua/bin/cua-ipopts-guard
+echo "kernel: $(uname -r)"
+
+# Python helpers: a TCP connect with raw IP_OPTIONS set on the client socket.
+cat >/tmp/ipopt_client.py <<'PY'
+import socket, sys
+# kind: none | rr | ts | lsrr | ssrr
+kind, host, port = sys.argv[1], sys.argv[2], int(sys.argv[3])
+opts = {
+ "none": b"",
+ "rr": bytes([7, 11, 4]) + bytes(8) + b"\x01", # Record Route + NOP pad
+ "ts": bytes([0x44, 12, 5, 0]) + bytes(8), # Timestamp
+ "lsrr": bytes([0x83, 7, 4, 127, 0, 0, 1]) + b"\x01", # loose source route
+ "ssrr": bytes([0x89, 7, 4, 127, 0, 0, 1]) + b"\x01", # strict source route
+}[kind]
+s = socket.socket(); s.settimeout(3)
+if opts:
+ s.setsockopt(socket.IPPROTO_IP, socket.IP_OPTIONS, opts)
+try:
+ s.connect((host, port)); print("CONNECTED"); sys.exit(0)
+except OSError as e:
+ print("NOCONNECT", type(e).__name__); sys.exit(1)
+PY
+cat >/tmp/listener.py <<'PY'
+import socket, sys
+s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+s.bind((sys.argv[1], int(sys.argv[2]))); s.listen(16)
+while True:
+ c, _ = s.accept(); c.close()
+PY
+connects() { python3 /tmp/ipopt_client.py "$@" >/dev/null; }
+
+# 1. booted with the unit enabled and the table loaded
+check "unit enabled at boot" systemctl is-enabled --quiet cua-ipopts.service
+check "unit active" systemctl is-active --quiet cua-ipopts.service
+check "table cua_ipopts loaded" bash -c "nft list table ip cua_ipopts >/dev/null"
+check "source routing off (sysctl)" test "$(sysctl -n net.ipv4.conf.all.accept_source_route)" = 0
+
+# 2. loopback / local-process trigger path: IP_OPTIONS set by an unprivileged
+# process on a client socket, SYN over 127.0.0.1 to a local listener.
+python3 /tmp/listener.py 127.0.0.1 8080 & L1=$!
+sleep 1
+check "lo: plain connect works" connects none 127.0.0.1 8080
+for k in rr ts lsrr ssrr; do
+ check "lo: SYN with $k option is dropped" bash -c "! python3 /tmp/ipopt_client.py $k 127.0.0.1 8080 >/dev/null"
+done
+drops="$(nft list chain ip cua_ipopts prerouting | sed -n 's/.*counter packets \([0-9]*\).*/\1/p')"
+check "drop counter counted them (packets=$drops)" test "${drops:-0}" -ge 4
+
+# 3. baseline: with the guard stopped the same RR / TS SYN reaches the listener
+# (proves the test sends a real options packet and the guard is what drops it).
+systemctl stop cua-ipopts.service
+check "baseline lo: table removed on stop" bash -c '! nft list table ip cua_ipopts >/dev/null 2>&1'
+for k in rr ts; do
+ check "baseline lo: $k SYN connects without the guard" connects $k 127.0.0.1 8080
+done
+systemctl start cua-ipopts.service
+check "restart: guard back" bash -c "nft list table ip cua_ipopts >/dev/null"
+check "lo again: rr dropped" bash -c '! python3 /tmp/ipopt_client.py rr 127.0.0.1 8080 >/dev/null'
+kill $L1 2>/dev/null
+
+# 4. routed path: crafted packets over a veth pair into a private namespace
+ip netns add srv; ip link add vcli type veth peer name vsrv; ip link set vsrv netns srv
+ip addr add 10.77.0.1/24 dev vcli; ip link set vcli up
+ip netns exec srv ip addr add 10.77.0.2/24 dev vsrv
+ip netns exec srv ip link set vsrv up; ip netns exec srv ip link set lo up
+# the guard must also be inside the namespace that owns the socket
+ip netns exec srv env CUA_IPOPTS_RULES=/etc/cua-image/cua-ipopts.nft "$GUARD" start
+ip netns exec srv python3 /tmp/listener.py 10.77.0.2 9090 & L2=$!
+sleep 1
+cat >/tmp/craft.py <<'PY'
+import sys
+from scapy.all import IP, TCP, ICMP, UDP, IPOption_RR, IPOption_Timestamp, sr1, conf
+conf.verb = 0
+what, dst = sys.argv[1], sys.argv[2]
+if what == "syn": p = IP(dst=dst)/TCP(sport=40001, dport=9090, flags="S", seq=1)
+elif what == "syn-rr": p = IP(dst=dst, options=[IPOption_RR()])/TCP(sport=40002, dport=9090, flags="S", seq=1)
+elif what == "syn-ts": p = IP(dst=dst, options=[IPOption_Timestamp(flg=0)])/TCP(sport=40003, dport=9090, flags="S", seq=1)
+elif what == "echo": p = IP(dst=dst)/ICMP()
+elif what == "echo-rr":p = IP(dst=dst, options=[IPOption_RR()])/ICMP()
+r = sr1(p, timeout=2)
+if r is None: print("NOREPLY"); sys.exit(1)
+if what.startswith("syn"):
+ f = int(r[TCP].flags); print("SYNACK" if f & 0x12 == 0x12 else "OTHER flags=%x" % f); sys.exit(0 if f & 0x12 == 0x12 else 2)
+print("REPLY"); sys.exit(0)
+PY
+check "routed: normal SYN gets SYN-ACK" python3 /tmp/craft.py syn 10.77.0.2
+check "routed: SYN with RR gets no reply" bash -c '! python3 /tmp/craft.py syn-rr 10.77.0.2 >/dev/null'
+check "routed: SYN with Timestamp gets no reply" bash -c '! python3 /tmp/craft.py syn-ts 10.77.0.2 >/dev/null'
+check "routed: normal ping works" python3 /tmp/craft.py echo 10.77.0.2
+check "routed: ping -R (RR) is dropped" bash -c '! python3 /tmp/craft.py echo-rr 10.77.0.2 >/dev/null'
+check "routed: normal TCP connect via the kernel stack" connects none 10.77.0.2 9090
+srvdrops="$(ip netns exec srv nft list chain ip cua_ipopts prerouting | sed -n 's/.*counter packets \([0-9]*\).*/\1/p')"
+check "routed: namespace counter saw the options packets (packets=$srvdrops)" test "${srvdrops:-0}" -ge 3
+kill $L2 2>/dev/null
+
+# 5. coexistence and idempotence
+nft add table ip other_fw; nft add chain ip other_fw input '{ type filter hook input priority 0; policy accept; }'
+nft add rule ip other_fw input tcp dport 22 accept
+"$GUARD" start; "$GUARD" start
+check "reload keeps one rule" test "$(nft list table ip cua_ipopts | grep -c 'ip hdrlength')" = 1
+check "other firewall table untouched" bash -c 'nft list table ip other_fw | grep -q "tcp dport 22 accept"'
+"$GUARD" stop
+check "stop removes only the guard" bash -c '! nft list table ip cua_ipopts >/dev/null 2>&1 && nft list table ip other_fw >/dev/null'
+nft delete table ip other_fw
+
+# 6. iptables fallback (image without nft): hide nft, load, test loopback
+mkdir -p /tmp/ipt-only; ln -sf "$(command -v iptables)" /tmp/ipt-only/iptables
+for b in sh cat sed grep; do ln -sf "$(command -v $b)" /tmp/ipt-only/$b; done
+python3 /tmp/listener.py 127.0.0.1 8081 & L3=$!
+sleep 1
+if PATH=/tmp/ipt-only "$GUARD" start 2>/tmp/ipt.err; then
+ check "iptables fallback: plain connect works" connects none 127.0.0.1 8081
+ check "iptables fallback: rr SYN dropped" bash -c '! python3 /tmp/ipopt_client.py rr 127.0.0.1 8081 >/dev/null'
+ check "iptables fallback: ts SYN dropped" bash -c '! python3 /tmp/ipopt_client.py ts 127.0.0.1 8081 >/dev/null'
+ PATH=/tmp/ipt-only "$GUARD" stop
+ check "iptables fallback: stop restores" connects rr 127.0.0.1 8081
+else
+ echo "SKIP iptables fallback (load failed: $(head -c 200 /tmp/ipt.err))"
+fi
+kill $L3 2>/dev/null
+systemctl restart cua-ipopts.service
+
+ip netns del srv 2>/dev/null
+echo "RESULT pass=$pass fail=$fail"
+[ "$fail" = 0 ]
diff --git a/libs/images/common/tests/ip-options-guard.Dockerfile b/libs/images/common/tests/ip-options-guard.Dockerfile
new file mode 100644
index 0000000000..ca8b7005ea
--- /dev/null
+++ b/libs/images/common/tests/ip-options-guard.Dockerfile
@@ -0,0 +1,22 @@
+# syntax=docker/dockerfile:1.7
+# Throwaway systemd-as-PID-1 Ubuntu container for test-ip-options-guard.sh: the
+# CVE-2026-98432 guard installed with the same COPY and `systemctl enable` lines
+# as common/vm/Dockerfile (a static check in test-ip-options-guard-static.sh
+# keeps the two in step). Build context: libs/images.
+FROM ubuntu:24.04
+ENV DEBIAN_FRONTEND=noninteractive
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ systemd systemd-sysv dbus kmod iproute2 nftables iptables iputils-ping \
+ python3 python3-scapy procps ca-certificates \
+ && sed -i -E 's#^(mozilla/(emSign_ECC_Root_CA_-_G3|Comodo_AAA_Services_root)\.crt)$#!\1#' /etc/ca-certificates.conf \
+ && update-ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
+COPY common/vm/files/cua-ipopts/cua-ipopts-guard /opt/cua/bin/cua-ipopts-guard
+COPY common/vm/files/cua-ipopts/cua-ipopts.nft /etc/cua-image/cua-ipopts.nft
+COPY common/vm/files/cua-ipopts/cua-ipopts.service /etc/systemd/system/cua-ipopts.service
+COPY common/vm/files/cua-ipopts/90-cua-ipopts.conf /etc/sysctl.d/90-cua-ipopts.conf
+COPY common/tests/ip-options-guard-guest.sh /opt/cua/tests/ip-options-guard-guest.sh
+RUN chmod 0755 /opt/cua/bin/cua-ipopts-guard /opt/cua/tests/ip-options-guard-guest.sh \
+ && systemctl enable cua-ipopts.service
+STOPSIGNAL SIGRTMIN+3
+CMD ["/sbin/init"]
diff --git a/libs/images/common/tests/test-ip-options-guard-static.sh b/libs/images/common/tests/test-ip-options-guard-static.sh
new file mode 100755
index 0000000000..8fe138ac4a
--- /dev/null
+++ b/libs/images/common/tests/test-ip-options-guard-static.sh
@@ -0,0 +1,94 @@
+#!/usr/bin/env bash
+# Static checks for the CVE-2026-98432 interim guard: the files exist, every
+# Linux VM recipe installs and enables them, the ruleset stays in its own table,
+# and the CVE watch (common/vm/cve-kernel-watch.json) agrees with the kernels the
+# images' evidence recorded. No Docker, no network.
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+IMAGES="$(cd "$HERE/../.." && pwd)"
+G="$IMAGES/common/vm/files/cua-ipopts"
+pass=0 fail=0
+ok() { pass=$((pass + 1)); }
+bad() { fail=$((fail + 1)); echo "FAIL $*"; }
+has() { # name file pattern (fixed string)
+ if grep -qF -- "$3" "$2"; then ok; else bad "$1: '$3' missing from ${2#"$IMAGES"/}"; fi
+}
+
+for f in cua-ipopts.nft cua-ipopts-guard cua-ipopts.service 90-cua-ipopts.conf; do
+ [ -s "$G/$f" ] && ok || bad "missing $f"
+done
+[ -x "$G/cua-ipopts-guard" ] && ok || bad "cua-ipopts-guard is not executable"
+
+# ruleset: own table, early hook, header-length drop, never a global flush
+has ruleset "$G/cua-ipopts.nft" "table ip cua_ipopts"
+has ruleset "$G/cua-ipopts.nft" "hook prerouting priority -450"
+has ruleset "$G/cua-ipopts.nft" "ip hdrlength > 5"
+has ruleset "$G/cua-ipopts.nft" "delete table ip cua_ipopts"
+if grep -qE '^[[:space:]]*flush[[:space:]]+ruleset' "$G/cua-ipopts.nft"; then bad "ruleset flushes other tables"; else ok; fi
+if grep -nE '^[[:space:]]*(delete|flush)[[:space:]]+(table|chain)' "$G/cua-ipopts.nft" | grep -v cua_ipopts >/dev/null; then bad "ruleset touches another table"; else ok; fi
+
+# unit: before the network, runs the guard, enabled at sysinit
+has unit "$G/cua-ipopts.service" "Before=network-pre.target"
+has unit "$G/cua-ipopts.service" "ExecStart=/opt/cua/bin/cua-ipopts-guard start"
+has unit "$G/cua-ipopts.service" "WantedBy=sysinit.target"
+has sysctl "$G/90-cua-ipopts.conf" "net.ipv4.conf.all.accept_source_route = 0"
+
+# every VM recipe installs it
+for df in common/vm/Dockerfile omarchy/vm.Dockerfile; do
+ for f in "cua-ipopts-guard /opt/cua/bin/cua-ipopts-guard" \
+ "cua-ipopts.nft /etc/cua-image/cua-ipopts.nft" \
+ "cua-ipopts.service /etc/systemd/system/cua-ipopts.service" \
+ "90-cua-ipopts.conf /etc/sysctl.d/90-cua-ipopts.conf"; do
+ has "$df" "$IMAGES/$df" "common/vm/files/cua-ipopts/$f"
+ done
+ has "$df" "$IMAGES/$df" "cua-ipopts.service"
+done
+has "common/vm/Dockerfile enable" "$IMAGES/common/vm/Dockerfile" "qemu-guest-agent cua-ipopts.service"
+has "common/vm/Dockerfile nft" "$IMAGES/common/vm/Dockerfile" "iproute2 nftables"
+has "omarchy nft" "$IMAGES/omarchy/vm.Dockerfile" "dosfstools nftables"
+has "omarchy enable" "$IMAGES/omarchy/vm.Dockerfile" "systemctl enable cua-ipopts.service"
+has "osworld upload" "$IMAGES/bench/osworld/vm/customize.sh" 'upload $COMMON_VM/cua-ipopts.nft /etc/cua-image/cua-ipopts.nft'
+has "osworld unit" "$IMAGES/bench/osworld/vm/customize.sh" 'ln-sf /etc/systemd/system/cua-ipopts.service /etc/systemd/system/sysinit.target.wants/cua-ipopts.service'
+has "osworld verify" "$IMAGES/bench/osworld/vm/customize.sh" 'is-symlink /etc/systemd/system/sysinit.target.wants/cua-ipopts.service'
+
+# the runtime test's throwaway image installs it with the same lines as the recipe
+while IFS= read -r line; do
+ grep -qxF -- "$line" "$IMAGES/common/tests/ip-options-guard.Dockerfile" && ok || bad "runtime-test Dockerfile drifted: $line"
+done < <(grep -E '^COPY common/vm/files/cua-ipopts/' "$IMAGES/common/vm/Dockerfile")
+
+# CVE watch
+python3 - "$IMAGES" <<'PY' || fail=$((fail + 1))
+import json, os, re, sys
+images = sys.argv[1]
+w = json.load(open(f"{images}/common/vm/cve-kernel-watch.json"))
+def key(v):
+ return tuple(int(x) for x in re.findall(r"\d+", v.split("-generic")[0].split("-virtual")[0]))
+bad = False
+for img, ev in w["images"].items():
+ path = f"{images}/{img}/evidence/{ev}"
+ doc = json.load(open(path))
+ kernels = set()
+ def walk(o):
+ if isinstance(o, dict):
+ for k, v in o.items():
+ if k == "kernel" and isinstance(v, str): kernels.add(v)
+ else: walk(v)
+ elif isinstance(o, list):
+ for v in o: walk(v)
+ walk(doc)
+ for k in sorted(kernels):
+ series = ".".join(map(str, key(k)[:2]))
+ s = w["series"].get(series)
+ if s is None:
+ print(f"FAIL {img}: kernel {k} is in series {series}, which cve-kernel-watch.json does not list"); bad = True; continue
+ fixed = s["fixed"]
+ if fixed and key(k) >= key(fixed):
+ print(f"NOTE {img}: kernel {k} is at or above {fixed}; the guard can be removed from this image")
+ elif s["published"]:
+ print(f"FAIL {img}: kernel {k} is older than the published fix {fixed}; rebuild and republish the image"); bad = True
+ else:
+ print(f"watch {img}: kernel {k} < {fixed or 'no fix'} (fix not published yet); covered by the guard")
+sys.exit(1 if bad else 0)
+PY
+echo "static: pass=$pass fail=$fail"
+[ "$fail" = 0 ]
diff --git a/libs/images/common/tests/test-ip-options-guard.sh b/libs/images/common/tests/test-ip-options-guard.sh
new file mode 100755
index 0000000000..48e6e16f2e
--- /dev/null
+++ b/libs/images/common/tests/test-ip-options-guard.sh
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+# Opt-in runtime test for the CVE-2026-98432 interim guard. Builds a throwaway
+# systemd Ubuntu container carrying the guard exactly as common/vm/Dockerfile
+# installs it, boots it (privileged, its own network namespace and cgroup), and
+# runs ip-options-guard-guest.sh inside. Crafted packets only ever travel on the
+# container's own loopback and a veth pair between two of its namespaces.
+#
+# CUA_TEST_DOCKER=1 libs/images/common/tests/test-ip-options-guard.sh
+#
+# Uses whatever docker the environment points at (set DOCKER_HOST / DOCKER_CONFIG
+# for an isolated engine). Stops and removes its container on exit.
+set -euo pipefail
+[ "${CUA_TEST_DOCKER:-}" = 1 ] || { echo "skipped: set CUA_TEST_DOCKER=1 to run (needs a Docker engine that allows --privileged)"; exit 0; }
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+CTX="$(cd "$HERE/../.." && pwd)" # libs/images
+NAME="cua-ipopts-test-$$"
+IMG="cua-ipopts-test:$$"
+cleanup() { docker rm -f "$NAME" >/dev/null 2>&1 || true; docker rmi -f "$IMG" >/dev/null 2>&1 || true; }
+trap cleanup EXIT
+docker build -q -f "$HERE/ip-options-guard.Dockerfile" -t "$IMG" "$CTX" >/dev/null
+docker run -d --name "$NAME" --privileged --cgroupns=host --tmpfs /run --tmpfs /run/lock \
+ -v /sys/fs/cgroup:/sys/fs/cgroup:rw "$IMG" >/dev/null
+for _ in $(seq 1 60); do
+ st="$(docker exec "$NAME" systemctl is-system-running 2>/dev/null || true)"
+ case "$st" in running|degraded) break ;; esac; sleep 1
+done
+docker exec "$NAME" /opt/cua/tests/ip-options-guard-guest.sh
diff --git a/libs/images/common/tools/tests/fixtures/manifest.linux.json b/libs/images/common/tools/tests/fixtures/manifest.linux.json
index e110f73825..2c6cf24f84 100644
--- a/libs/images/common/tools/tests/fixtures/manifest.linux.json
+++ b/libs/images/common/tools/tests/fixtures/manifest.linux.json
@@ -93,6 +93,8 @@
"features_not_applicable": [],
"features_optional": [
"hotspot",
+ "spawn",
+ "process.services",
"relay_attach",
"h264_hw",
"audio.per_app",
diff --git a/libs/images/common/vm/Dockerfile b/libs/images/common/vm/Dockerfile
index 8dbba22a28..48008659fe 100644
--- a/libs/images/common/vm/Dockerfile
+++ b/libs/images/common/vm/Dockerfile
@@ -53,6 +53,14 @@ COPY common/vm/files/99-kubevirt.yaml /etc/netplan/99-kubevirt.yaml
COPY common/vm/files/fstab /etc/fstab
COPY common/vm/files/99-cua-cloud.cfg /etc/cloud/cloud.cfg.d/99-cua-cloud.cfg
+# CVE-2026-98432 interim guard (IPv4 options dropped before TCP). Remove once
+# linux-image-virtual is at or above the fixed version for noble; see
+# docs/content/docs/spaces/guides/ip-options-guard.mdx.
+COPY common/vm/files/cua-ipopts/cua-ipopts-guard /opt/cua/bin/cua-ipopts-guard
+COPY common/vm/files/cua-ipopts/cua-ipopts.nft /etc/cua-image/cua-ipopts.nft
+COPY common/vm/files/cua-ipopts/cua-ipopts.service /etc/systemd/system/cua-ipopts.service
+COPY common/vm/files/cua-ipopts/90-cua-ipopts.conf /etc/sysctl.d/90-cua-ipopts.conf
+
RUN chmod 600 /etc/netplan/99-kubevirt.yaml \
&& rm -f /etc/netplan/50-cloud-init.yaml /etc/ssh/ssh_host_* /var/lib/dbus/machine-id
# (machine-id, hostname, resolv.conf and /.dockerenv are build-time bind mounts;
@@ -60,7 +68,8 @@ RUN chmod 600 /etc/netplan/99-kubevirt.yaml \
# systemd owns the VM: enable the base services plus the image's own units, and
# keep supervisord (the container PID 1) from also starting them.
-RUN systemctl enable systemd-networkd systemd-resolved ssh.socket qemu-guest-agent \
+RUN chmod 0755 /opt/cua/bin/cua-ipopts-guard \
+ && systemctl enable systemd-networkd systemd-resolved ssh.socket qemu-guest-agent cua-ipopts.service \
&& if systemctl list-unit-files supervisor.service >/dev/null 2>&1; then systemctl mask supervisor.service; fi \
&& if [ -f /etc/cua-image/vm-units ]; then \
grep -v '^[[:space:]]*\(#\|$\)' /etc/cua-image/vm-units | xargs -r systemctl enable; \
diff --git a/libs/images/common/vm/cve-kernel-watch.json b/libs/images/common/vm/cve-kernel-watch.json
new file mode 100644
index 0000000000..e0a855842c
--- /dev/null
+++ b/libs/images/common/vm/cve-kernel-watch.json
@@ -0,0 +1,13 @@
+{
+ "cve": "CVE-2026-98432",
+ "guard": "libs/images/common/vm/files/cua-ipopts",
+ "note": "Set published to true for a series once the distribution ships a kernel at or above fixed (Ubuntu noble: linux 6.8.0-149). From then on test-ip-options-guard-static.sh fails for any VM image whose recorded kernel is older (rebuild it) and reports the guard as removable for images at or above it. A series with published false is covered by the guard only. Upstream fixed: 5.10.272, 5.15.223, 6.1.190, 6.6.159, 6.12.113, 6.18.56, 7.2.10, 7.3.",
+ "series": {
+ "6.8": {"distribution": "Ubuntu 24.04 noble linux-image-virtual", "fixed": "6.8.0-149", "published": false},
+ "6.5": {"distribution": "Ubuntu 22.04 HWE (OSWorld upstream disk, end of life)", "fixed": null, "published": false}
+ },
+ "images": {
+ "bench/web": "containerdisk-local-arm64-doctor.json",
+ "bench/osworld": "containerdisk-local-amd64-doctor.json"
+ }
+}
diff --git a/libs/images/common/vm/files/cua-ipopts/90-cua-ipopts.conf b/libs/images/common/vm/files/cua-ipopts/90-cua-ipopts.conf
new file mode 100644
index 0000000000..a7141fa355
--- /dev/null
+++ b/libs/images/common/vm/files/cua-ipopts/90-cua-ipopts.conf
@@ -0,0 +1,3 @@
+# CVE-2026-98432 interim guard: never honour source-routed IPv4 packets.
+net.ipv4.conf.all.accept_source_route = 0
+net.ipv4.conf.default.accept_source_route = 0
diff --git a/libs/images/common/vm/files/cua-ipopts/cua-ipopts-guard b/libs/images/common/vm/files/cua-ipopts/cua-ipopts-guard
new file mode 100755
index 0000000000..7ade777796
--- /dev/null
+++ b/libs/images/common/vm/files/cua-ipopts/cua-ipopts-guard
@@ -0,0 +1,45 @@
+#!/bin/sh
+# Load or remove the CVE-2026-98432 interim guard (see cua-ipopts.nft).
+# cua-ipopts-guard start | stop | status
+# nft is the normal path. iptables (xt_u32) is the fallback for an image that
+# has no nft (the upstream OSWorld disk). Only the cua_ipopts table / the
+# CUA_IPOPTS chain is ever touched.
+set -eu
+RULES="${CUA_IPOPTS_RULES:-/etc/cua-image/cua-ipopts.nft}"
+
+have() { command -v "$1" >/dev/null 2>&1; }
+
+start() {
+ if have nft; then
+ nft -f "$RULES"
+ elif have iptables; then
+ iptables -w -t raw -N CUA_IPOPTS 2>/dev/null || iptables -w -t raw -F CUA_IPOPTS
+ iptables -w -t raw -A CUA_IPOPTS -p igmp -j RETURN
+ # IHL (low nibble of byte 0) between 6 and 15 means IP options.
+ iptables -w -t raw -A CUA_IPOPTS -m u32 --u32 "0>>24&0xF=6:15" -j DROP
+ iptables -w -t raw -C PREROUTING -j CUA_IPOPTS 2>/dev/null \
+ || iptables -w -t raw -I PREROUTING 1 -j CUA_IPOPTS
+ else
+ echo "cua-ipopts-guard: neither nft nor iptables found" >&2
+ exit 1
+ fi
+}
+
+stop() {
+ if have nft; then nft delete table ip cua_ipopts 2>/dev/null || true; fi
+ if have iptables; then
+ while iptables -w -t raw -D PREROUTING -j CUA_IPOPTS 2>/dev/null; do :; done
+ iptables -w -t raw -F CUA_IPOPTS 2>/dev/null || true
+ iptables -w -t raw -X CUA_IPOPTS 2>/dev/null || true
+ fi
+}
+
+case "${1:-start}" in
+ start) start ;;
+ stop) stop ;;
+ status)
+ if have nft && nft list table ip cua_ipopts 2>/dev/null; then exit 0; fi
+ if have iptables && iptables -w -t raw -S CUA_IPOPTS 2>/dev/null; then exit 0; fi
+ echo "cua-ipopts-guard: not loaded" >&2; exit 1 ;;
+ *) echo "usage: $0 start|stop|status" >&2; exit 2 ;;
+esac
diff --git a/libs/images/common/vm/files/cua-ipopts/cua-ipopts.nft b/libs/images/common/vm/files/cua-ipopts/cua-ipopts.nft
new file mode 100644
index 0000000000..a1059f93b4
--- /dev/null
+++ b/libs/images/common/vm/files/cua-ipopts/cua-ipopts.nft
@@ -0,0 +1,25 @@
+# Interim guard for CVE-2026-98432 (Linux IPv4 use-after-free reachable from a
+# remote TCP SYN that carries Record Route / Timestamp options). Drops every
+# inbound IPv4 packet that has IP options, before it reaches TCP. That covers
+# Record Route, Timestamp, loose and strict source route; nft has no Timestamp
+# matcher, so the rule keys on the header length (more than 20 bytes) instead
+# of on one option. IGMP is left alone: it legitimately carries Router Alert
+# and never reaches TCP.
+#
+# Own table, own name: loading it never touches another table, and a user's
+# later firewall (ufw, Docker, nftables.service without `flush ruleset`) keeps
+# working. The add/delete/define sequence makes reloading idempotent.
+#
+# Remove once the image's kernel is at or above the fixed version of its
+# series (see docs/content/docs/spaces/guides/ip-options-guard.mdx).
+add table ip cua_ipopts
+delete table ip cua_ipopts
+table ip cua_ipopts {
+ chain prerouting {
+ # -450 runs before IP defragmentation (-400) and conntrack (-200/-300),
+ # and ahead of the usual filter chains (0).
+ type filter hook prerouting priority -450; policy accept;
+ ip protocol igmp accept
+ ip hdrlength > 5 counter drop comment "CVE-2026-98432: inbound IPv4 options"
+ }
+}
diff --git a/libs/images/common/vm/files/cua-ipopts/cua-ipopts.service b/libs/images/common/vm/files/cua-ipopts/cua-ipopts.service
new file mode 100644
index 0000000000..cdee31634f
--- /dev/null
+++ b/libs/images/common/vm/files/cua-ipopts/cua-ipopts.service
@@ -0,0 +1,21 @@
+[Unit]
+Description=Drop inbound IPv4 packets with IP options (CVE-2026-98432 interim guard)
+Documentation=https://docs.cua.ai/docs/spaces/guides/ip-options-guard
+DefaultDependencies=no
+After=systemd-modules-load.service local-fs.target
+# Load after nftables.service when a user enables it, so a `flush ruleset`
+# there cannot remove the guard.
+After=nftables.service
+Before=network-pre.target
+Wants=network-pre.target
+Conflicts=shutdown.target
+Before=shutdown.target
+
+[Service]
+Type=oneshot
+RemainAfterExit=yes
+ExecStart=/opt/cua/bin/cua-ipopts-guard start
+ExecStop=/opt/cua/bin/cua-ipopts-guard stop
+
+[Install]
+WantedBy=sysinit.target
diff --git a/libs/images/linux/image.json b/libs/images/linux/image.json
index d539821ee8..3ef7776678 100644
--- a/libs/images/linux/image.json
+++ b/libs/images/linux/image.json
@@ -180,6 +180,8 @@
],
"features_optional": [
"hotspot",
+ "spawn",
+ "process.services",
"relay_attach",
"h264_hw",
"audio.per_app",
diff --git a/libs/images/macos/annotate.sh b/libs/images/macos/annotate.sh
index 90efe607b5..92260750c2 100755
--- a/libs/images/macos/annotate.sh
+++ b/libs/images/macos/annotate.sh
@@ -11,7 +11,8 @@
# Adds: ai.cua.image.os=macos, ai.cua.spacesd=true, ai.cua.env-driver=true
# (pre-rename key), ai.cua.image.variant=lume, ai.cua.image.variants
# {"lume": "<repo>:NEW_TAG"}, ai.cua.image.source (<repo>:SOURCE_TAG@digest),
-# org.opencontainers.image.source, and with the options ai.cua.image.tier and
+# org.opencontainers.image.source, and with the options ai.cua.image.tier (the
+# xcode tier also gets ai.cua.image.notice: its Apple-license notice) and
# ai.cua.image.content-key (tools/content-key.py; a scheduled rebuild moves
# a floating tag only when its key differs). Move the floating tag afterwards with
# `crane tag <repo>@<printed digest> 26`, once the strict doctor passed on
@@ -39,6 +40,7 @@ crane manifest "$REPOSITORY@$src_digest" >"$WORK/src.json"
[ "$(jq -r .mediaType "$WORK/src.json")" = "$MT" ] || { echo "$SRC is not an OCI manifest" >&2; exit 1; }
jq --arg variants "{\"lume\":\"$REPOSITORY:$NEW\"}" --arg source "$REPOSITORY:$SRC@$src_digest" \
--arg tier "$TIER" --arg key "$KEY" \
+ --arg notice "Xcode and the iOS Simulator runtimes in this image are Apple software under Apple's license, for use on Apple-branded hardware." \
'.annotations = ((.annotations // {}) + {
"ai.cua.image.os": "macos",
"ai.cua.spacesd": "true",
@@ -48,6 +50,7 @@ jq --arg variants "{\"lume\":\"$REPOSITORY:$NEW\"}" --arg source "$REPOSITORY:$S
"ai.cua.image.source": $source,
"org.opencontainers.image.source": "https://github.com/trycua/cua"}
+ (if $tier != "" then {"ai.cua.image.tier": $tier} else {} end)
+ + (if $tier == "xcode" then {"ai.cua.image.notice": $notice} else {} end)
+ (if $key != "" then {"ai.cua.image.content-key": $key} else {} end))' \
"$WORK/src.json" >"$WORK/new.json"
# Content is unchanged: same config and layers.
diff --git a/libs/images/macos/build.sh b/libs/images/macos/build.sh
index 08108210ba..0ae80c8d10 100755
--- a/libs/images/macos/build.sh
+++ b/libs/images/macos/build.sh
@@ -34,7 +34,6 @@
# and /etc/cua-image/spacesd-source. With --app the doctor
# expects the bundle's own build-info git_sha.
# --push TAG after the gate passes, `lume push` TAG to the macos repo
-# (slim and full only: the xcode tier is never pushed).
# TAG must be a new immutable pin of this tier
# (<version>[-slim|-xcode[-X.Y]]-<yyyymmdd>-<sha7>);
# scripts/images/check-tag-safety.sh refuses anything else.
@@ -99,10 +98,6 @@ if [ "$TIER" != slim ] && [ -z "$BASE_VM" ]; then
echo "--tier $TIER builds on the gated VM of the tier below: pass --base-vm" >&2; exit 2
fi
[ -n "$MEMORY" ] || { [ "$TIER" = xcode ] && MEMORY=8GB || MEMORY=4GB; }
-if [ -n "$PUSH_TAG" ] && [ "$TIER" = xcode ]; then
- echo "the xcode tier is never pushed: it carries Xcode, which Apple's terms do not let us redistribute (each Mac derives it: derive-local.sh)" >&2
- exit 2
-fi
MACOS_BASE_IMAGE="$MACOS_BASE_REPO:$MACOS_BASE_TAG"
BASE_IMAGE="${BASE_IMAGE:-$MACOS_BASE_IMAGE}"
VM="${VM:-cua-e2e-macos-$TIER-$$}"
@@ -184,11 +179,29 @@ case "$TIER" in
fetch "$UV_URL" "$UV_SHA256"; fetch "$NODE_URL" "$NODE_SHA256"; fetch "$PNPM_URL" "$PNPM_SHA256"
fetch "$GO_URL" "$GO_SHA256"; fetch "$RUSTUP_URL" "$RUSTUP_SHA256" ;;
xcode)
+ # Xcode comes from this Mac, never from a sign-in: the pinned .xip in
+ # the runner's cache if it has one, else the pinned Xcode.app installed
+ # on the runner (what a GitHub macOS image has preinstalled too).
+ # shellcheck source=files/xcode-source.sh
+ . "$HERE/files/xcode-source.sh"
+ mkdir -p "$SETUP/xcode"
xip="$XCODE_CACHE/$XCODE_XIP"
- [ -f "$xip" ] || { echo "$xip is missing: put the Xcode $XCODE_VERSION .xip in CUA_XCODE_CACHE" >&2; exit 2; }
- [ "$(shasum -a 1 "$xip" | cut -d' ' -f1)" = "$XCODE_XIP_SHA1" ] ||
- { echo "checksum mismatch: $xip" >&2; exit 1; }
- ln -f "$xip" "$SETUP/cache/" 2>/dev/null || cp "$xip" "$SETUP/cache/"
+ if [ -f "$xip" ]; then
+ [ "$(shasum -a 1 "$xip" | cut -d' ' -f1)" = "$XCODE_XIP_SHA1" ] ||
+ { echo "checksum mismatch: $xip" >&2; exit 1; }
+ ln -f "$xip" "$SETUP/cache/" 2>/dev/null || cp "$xip" "$SETUP/cache/"
+ else
+ app=""
+ for c in "${CUA_XCODE_APP:-}" "/Applications/Xcode_$XCODE_VERSION.app" "$(xcode-select -p 2>/dev/null | sed 's|/Contents/Developer$||')" /Applications/Xcode*.app; do
+ [ -n "$c" ] && [ -d "$c" ] && [ "$(plist "$c" CFBundleShortVersionString)" = "$XCODE_VERSION" ] && { app="$c"; break; }
+ done
+ [ -n "$app" ] || { echo "no Xcode $XCODE_VERSION on this runner: put $XCODE_XIP in $XCODE_CACHE, or install Xcode $XCODE_VERSION (/Applications/Xcode_$XCODE_VERSION.app)" >&2; exit 2; }
+ [ "$(/usr/libexec/PlistBuddy -c 'Print :ProductBuildVersion' "$app/Contents/version.plist")" = "$XCODE_BUILD" ] ||
+ { echo "$app is not build $XCODE_BUILD" >&2; exit 1; }
+ log "using the runner's $app (build $XCODE_BUILD)"
+ stage_xcode "$app" "$SETUP/xcode"
+ : >"$SETUP/xcode/pinned"
+ fi
fetch_xcode_tools ;;
esac
"$SETUP/Cua Spacesd.app/Contents/MacOS/cua-spacesd" build-info >"$OUT/build-info.json"
diff --git a/libs/images/macos/derive-local.sh b/libs/images/macos/derive-local.sh
index 1a81bb0b5d..3d815d2cb8 100755
--- a/libs/images/macos/derive-local.sh
+++ b/libs/images/macos/derive-local.sh
@@ -1,8 +1,11 @@
#!/usr/bin/env bash
# Derive the macOS Space with developer tools (the xcode tier) on THIS Mac,
-# from the published full tier and an Xcode that is already here. Nothing it
-# makes is ever pushed: Apple's terms let you run Xcode on your own Mac, in a
-# VM on it, but not hand it to others (see versions.env, check-tag-safety.sh).
+# from the published full tier and an Xcode that is already here. The default
+# way to get the tier is to pull the published ghcr.io/trycua/macos:26-xcode;
+# this is the fallback for when that image is not available, or for a Mac that
+# already has the Xcode it wants and the user prefers to use it. Xcode and the
+# iOS Simulator runtimes are Apple software under Apple's license, for use on
+# Apple-branded hardware: this refuses to run anywhere else.
#
# libs/images/macos/derive-local.sh --base-vm NAME [--name VM] [--xcode PATH]
# [--out DIR] [--memory 8GB] [--keep-going-low-disk] [--json]
@@ -37,6 +40,7 @@ FLOOR_GB="${CUA_DEV_IMAGE_FLOOR_GB:-10}"
# Growth the derive needs beyond Xcode itself: iOS runtime, Metal toolchain,
# tools, Simulator data and caches while building.
EXTRA_GB="${CUA_DEV_IMAGE_EXTRA_GB:-18}"
+# shellcheck disable=SC2034 # XCODE is read by find_xcode (files/xcode-source.sh)
while [ $# -gt 0 ]; do
case "$1" in
--base-vm) BASE_VM="$2"; shift 2 ;;
@@ -65,26 +69,8 @@ lume() {
esac
}
guest() { lume ssh -t "${2:-120}" "$VM" "$1" </dev/null; }
-plist() { /usr/libexec/PlistBuddy -c "Print :$2" "$1/Contents/Info.plist" 2>/dev/null; }
-
-# --- the Xcode on this Mac -------------------------------------------------------
-find_xcode() {
- local c best="" bestv="" v
- if [ -n "$XCODE" ]; then echo "$XCODE"; return 0; fi
- if [ -n "${CUA_XCODE_APP:-}" ]; then echo "$CUA_XCODE_APP"; return 0; fi
- local sel; sel="$(xcode-select -p 2>/dev/null || true)"
- case "$sel" in */Xcode*.app/Contents/Developer) c="${sel%/Contents/Developer}"; [ -d "$c" ] && { echo "$c"; return 0; } ;; esac
- for c in /Applications/Xcode*.app; do
- [ -d "$c" ] || continue
- v="$(plist "$c" CFBundleShortVersionString || true)"; [ -n "$v" ] || continue
- if [ -z "$best" ] || [ "$(printf '%s\n%s\n' "$bestv" "$v" | sort -V | tail -1)" = "$v" ]; then best="$c" bestv="$v"; fi
- done
- [ -z "$best" ] || { echo "$best"; return 0; }
- for c in "${CUA_XCODE_CACHE:-$HOME/XcodesCache}"/Xcode*.xip "$HOME"/Downloads/Xcode*.xip; do
- [ -f "$c" ] && { echo "$c"; return 0; }
- done
- return 1
-}
+# shellcheck source=files/xcode-source.sh
+. "$HERE/files/xcode-source.sh"
if ! SRC="$(find_xcode)"; then
cat >&2 <<'MSG'
No Xcode on this Mac. Apple requires a signed-in download, so Cua cannot fetch one for you.
@@ -119,6 +105,8 @@ MSG
exit 4
fi
+[ "$(uname -s)" = Darwin ] && [ "$(uname -m)" = arm64 ] ||
+ { echo "The macOS Space with developer tools runs only on Apple-branded hardware with Apple silicon." >&2; exit 2; }
command -v "$LUME_BIN" >/dev/null || { echo "lume is required" >&2; exit 2; }
# --- stage: scripts, pins, tools ----------------------------------------------------------
@@ -129,14 +117,8 @@ cp "$HERE/files/tier-xcode.sh" "$HERE/versions.env" "$SETUP/"
# shellcheck source=files/fetch.sh
. "$HERE/files/fetch.sh"
fetch_xcode_tools
-# The Xcode, as one archive: the guest reads the share over virtiofs, which
-# cannot follow an app bundle's framework links, but a zip keeps them, the
-# signatures and the extended attributes. An .xip goes in as it is.
-case "$SRC" in
- *.app) log "archiving $(basename "$SRC") for the guest"
- ditto -c -k --sequesterRsrc --keepParent "$SRC" "$SETUP/xcode/$(basename "$SRC").zip" ;;
- *) cp -c "$SRC" "$SETUP/xcode/" 2>/dev/null || cp "$SRC" "$SETUP/xcode/" ;;
-esac
+log "packing $(basename "$SRC") for the guest"
+stage_xcode "$SRC" "$SETUP/xcode"
cleanup() {
lume stop "$VM" >/dev/null 2>&1 || true
diff --git a/libs/images/macos/files/tier-xcode.sh b/libs/images/macos/files/tier-xcode.sh
index ea0652c96c..ccd038a2de 100755
--- a/libs/images/macos/files/tier-xcode.sh
+++ b/libs/images/macos/files/tier-xcode.sh
@@ -10,13 +10,14 @@
# STAGE/cache/$XCODE_XIP the pinned archive of CI's runner (build.sh); its
# SHA-1 is checked here and the build must be
# $XCODE_BUILD
-# STAGE/xcode/*.zip|*.app an Xcode already installed on the host Mac
-# (derive-local.sh sends a ditto zip), copied as is
+# STAGE/xcode/*.zip|*.app an Xcode already installed on the host Mac (a ditto
+# zip); with STAGE/xcode/pinned (build.sh, the pinned
+# build) the pin checks apply, else any Xcode is taken
# STAGE/xcode/*.xip an archive the user downloaded (derive-local.sh);
# xip checks Apple's signature while it expands
# and lands at /Applications/Xcode_<version>.app, selected, licensed and
-# first-launched. This tier is never published (Apple's terms), so the Xcode
-# is always the one the Mac's owner already has or downloaded.
+# first-launched. No sign-in is involved: the Xcode is one that is already on
+# the Mac (or runner) building the image.
#
# Installs, all pinned in versions.env:
# Xcode, Metal toolchain, iOS simulator runtime Apple (no sign-in)
@@ -51,6 +52,9 @@ if [ -f "$C/$XCODE_XIP" ]; then
{ echo "checksum mismatch: $C/$XCODE_XIP" >&2; exit 1; }
src="$C/$XCODE_XIP" pinned=1
else
+ # An Xcode build.sh staged from the runner's own installed Xcode (the same
+ # pinned build): the pin checks apply to it too.
+ [ ! -e "$STAGE/xcode/pinned" ] || pinned=1
for f in "$STAGE"/xcode/*.zip "$STAGE"/xcode/*.app "$STAGE"/xcode/*.xip; do
[ -e "$f" ] && { src="$f"; break; }
done
diff --git a/libs/images/macos/files/xcode-source.sh b/libs/images/macos/files/xcode-source.sh
new file mode 100644
index 0000000000..ee6a20c7e8
--- /dev/null
+++ b/libs/images/macos/files/xcode-source.sh
@@ -0,0 +1,38 @@
+# shellcheck shell=bash
+# Sourced by build.sh and derive-local.sh: find an Xcode on this Mac and stage
+# it for the guest. Needs no Apple credentials: it only uses an Xcode that is
+# already here (installed, or an .xip somebody downloaded).
+# XCODE an explicit Xcode.app or .xip (optional)
+plist() { /usr/libexec/PlistBuddy -c "Print :$2" "$1/Contents/Info.plist" 2>/dev/null; }
+
+# find_xcode prints the Xcode to use: $XCODE, $CUA_XCODE_APP, the one xcode-select
+# names, else the newest /Applications/Xcode*.app, else an Xcode*.xip in
+# $CUA_XCODE_CACHE (default ~/XcodesCache) or ~/Downloads. Fails when none.
+find_xcode() {
+ local c best="" bestv="" v sel
+ if [ -n "${XCODE:-}" ]; then echo "$XCODE"; return 0; fi
+ if [ -n "${CUA_XCODE_APP:-}" ]; then echo "$CUA_XCODE_APP"; return 0; fi
+ sel="$(xcode-select -p 2>/dev/null || true)"
+ case "$sel" in */Xcode*.app/Contents/Developer) c="${sel%/Contents/Developer}"; [ -d "$c" ] && { echo "$c"; return 0; } ;; esac
+ for c in /Applications/Xcode*.app; do
+ [ -d "$c" ] || continue
+ v="$(plist "$c" CFBundleShortVersionString || true)"; [ -n "$v" ] || continue
+ if [ -z "$best" ] || [ "$(printf '%s\n%s\n' "$bestv" "$v" | sort -V | tail -1)" = "$v" ]; then best="$c" bestv="$v"; fi
+ done
+ [ -z "$best" ] || { echo "$best"; return 0; }
+ for c in "${CUA_XCODE_CACHE:-$HOME/XcodesCache}"/Xcode*.xip "$HOME"/Downloads/Xcode*.xip; do
+ [ -f "$c" ] && { echo "$c"; return 0; }
+ done
+ return 1
+}
+
+# stage_xcode SRC DIR puts the Xcode into DIR as one file the guest can read
+# over the share. The guest's virtiofs cannot follow an app bundle's framework
+# links, but a zip keeps them, the signatures and the extended attributes; an
+# .xip goes in as it is.
+stage_xcode() {
+ case "$1" in
+ *.app) ditto -c -k --sequesterRsrc --keepParent "$1" "$2/$(basename "$1").zip" ;;
+ *) cp -c "$1" "$2/" 2>/dev/null || cp "$1" "$2/" ;;
+ esac
+}
diff --git a/libs/images/macos/image.json b/libs/images/macos/image.json
index 3638d21270..b75fdf998b 100644
--- a/libs/images/macos/image.json
+++ b/libs/images/macos/image.json
@@ -64,6 +64,8 @@
],
"features_optional": [
"hotspot",
+ "spawn",
+ "process.services",
"relay_attach",
"h264_hw",
"audio.desktop",
@@ -240,7 +242,7 @@
},
"xcode": {
"from": "full",
- "description": "Full plus Xcode (the Mac's own, copied in when the image is built on it), the matching iOS simulator runtime, the Metal toolchain, Rust iOS targets, CocoaPods, XcodeGen, sccache and a warmed Simulator device: the macOS Space with developer tools. Built on each user's Mac and never published (Apple's terms).",
+ "description": "Full plus Xcode 26.6 (selected), its iOS 26.5 simulator runtime, the Metal toolchain, Rust iOS targets, CocoaPods, XcodeGen, sccache and a warmed Simulator device: the macOS Space with developer tools. Xcode and the Simulator runtimes are Apple software under Apple's license, for use on Apple-branded hardware.",
"claims": {
"tools": {
"xcodebuild": {
diff --git a/libs/images/macos/release-tier.sh b/libs/images/macos/release-tier.sh
index e0c1d4c71f..45b9d75833 100755
--- a/libs/images/macos/release-tier.sh
+++ b/libs/images/macos/release-tier.sh
@@ -54,12 +54,6 @@ while [ $# -gt 0 ]; do
done
# shellcheck source=versions.env
. "$HERE/versions.env"
-# The xcode tier carries Xcode, SDKs and simulator runtimes: Apple's terms do
-# not allow redistributing them, so it is built and gated here but never
-# pushed. Each Mac derives it (derive-local.sh).
-never_xcode() {
- [ "$TIER" != xcode ] || { echo "the xcode tier is never $1: it carries Xcode (see versions.env)" >&2; exit 2; }
-}
pin() {
[[ "$STAMP" =~ ^[0-9]{8}-[0-9a-f]{7}$ ]] || { echo "--stamp is <yyyymmdd>-<sha7>" >&2; exit 2; }
local p
@@ -142,7 +136,6 @@ PY
cp "$d"/* "$EVIDENCE/doctor/arm64-lume/"
;;
push)
- never_xcode pushed
p="$(pin)"; vm="$(vm_name "$TIER")"
digest="$("$HERE/push.sh" "$vm" "$p-raw" | tail -1)"
python3 -c 'import json,sys;json.dump({"tag":sys.argv[1],"digest":sys.argv[2],"vm":sys.argv[3]},open(sys.argv[4],"w"))' \
@@ -150,7 +143,6 @@ push)
cat "$EVIDENCE/raw.json"
;;
publish)
- never_xcode published
p="$(pin)"
[ "$(crane digest "$REPOSITORY:$p-raw")" = "$(jget "$EVIDENCE/raw.json" digest)" ] ||
{ echo "$p-raw no longer holds the pushed digest" >&2; exit 1; }
@@ -192,7 +184,6 @@ print(f"verified {rec['repo']}:{rec['tag']} {rec['lume']} ({len(pin.get('layers'
PY
;;
promote)
- never_xcode promoted
rec="$EVIDENCE/pushed.json"
tag="$(jget "$rec" tag)" digest="$(jget "$rec" lume)"
[ "$(jget "$rec" tier)" = "$TIER" ] || { echo "$rec is not the $TIER tier" >&2; exit 1; }
diff --git a/libs/images/macos/versions.env b/libs/images/macos/versions.env
index 52ac80d460..1e119f2730 100644
--- a/libs/images/macos/versions.env
+++ b/libs/images/macos/versions.env
@@ -55,17 +55,17 @@ GO_URL=https://go.dev/dl/go1.27.1.darwin-arm64.tar.gz
GO_SHA256=ee215d57e0ec269c60cc9ceca68e6bda321ba9ee5afe24f4b0988703c2d87d12
# --- xcode --------------------------------------------------------------------
-# The macOS Space with developer tools. Apple's terms allow Xcode on the Mac
-# that runs the VM, not redistribution, so this tier is never pushed to a
-# registry (check-tag-safety.sh, release-tier.sh and the image workflow refuse
-# it); each Mac derives it from the published full tier (derive-local.sh) with
-# an Xcode that is already on that Mac. Apple needs a signed-in download for a
-# new copy, so the Xcode is, in order: an installed Xcode.app, or an .xip from
-# CUA_XCODE_CACHE (default ~/XcodesCache). Apple and xcodereleases.com publish
-# SHA-1 for the archive; xip also checks Apple's signature on expand.
-# XCODE_* below is the version CI builds and gates the tier with (build.sh
-# --tier xcode needs that .xip in the runner's cache); a Mac deriving it
-# locally may use any Xcode its guest macOS supports.
+# The macOS Space with developer tools. Xcode and the Simulator runtimes are
+# Apple software under Apple's license, for use on Apple-branded hardware (the
+# image carries a notice, annotate.sh). CI needs no sign-in: it uses the pinned
+# Xcode already on the runner, the pinned .xip in CUA_XCODE_CACHE (default
+# ~/XcodesCache) when there is one, or the Xcode.app installed there. Apple and
+# xcodereleases.com publish SHA-1 for the archive; xip also checks Apple's
+# signature on expand.
+# XCODE_* below is the version CI builds, gates and publishes the tier with
+# (build.sh --tier xcode needs exactly that Xcode on the runner). Users pull
+# the published tier; a Mac that builds it locally instead (derive-local.sh) may
+# use any Xcode its guest macOS supports.
XCODE_VERSION=26.6
XCODE_BUILD=17F113
XCODE_XIP=Xcode_26.6_Apple_silicon.xip
diff --git a/libs/images/omarchy/Dockerfile b/libs/images/omarchy/Dockerfile
index d48c68b95f..b657cfb8c2 100644
--- a/libs/images/omarchy/Dockerfile
+++ b/libs/images/omarchy/Dockerfile
@@ -92,6 +92,8 @@ RUN set -eu; \
pacman -Q omarchy-dev omarchy-settings-dev cua-driver-bin cua-hyprland-plugin hyprland; \
test -x /usr/bin/cua-driver; test -f /usr/lib/cua/hyprland/cua-hyprland-plugin.so; \
yes | pacman -Scc >/dev/null; rm -f /tmp/packages.desktop; \
+ install -d /etc/cua-image; \
+ cp /etc/pacman.d/mirrorlist /etc/cua-image/pacman-mirrorlist.build; \
mv /etc/pacman.d/mirrorlist.omarchy /etc/pacman.d/mirrorlist
# CUA-1948: the compromised eMudhra intermediates. Arch's ca-certificates-mozilla
@@ -100,6 +102,21 @@ RUN set -eu; \
COPY omarchy/files/distrust-emudhra.sh /tmp/distrust-emudhra.sh
RUN sh /tmp/distrust-emudhra.sh && rm -f /tmp/distrust-emudhra.sh
+# Stopgap (CUA-3107) until cua-hyprland-plugin is qualified for Hyprland 0.57:
+# the plugin pins hyprland=0.56.2-4, but the Omarchy edge config (omarchy-dev,
+# which has no old versions to pin) moved to 0.57 on 2026-11-01 and sets
+# misc.bell_sound, a key 0.56 does not have. Hyprland 0.56 then rejects the
+# whole hl.config block in looknfeel.lua (focus_on_activate, dwindle,
+# cursor, ...) and shows a config-error bar over the desktop, and the doctor's
+# grid fixture never shows in a screenshot. Drop only that key, and only while
+# the installed Hyprland is older than 0.57.
+RUN set -eu; \
+ hv="$(pacman -Q hyprland | cut -d' ' -f2)"; \
+ if [ "$(vercmp "$hv" 0.57.0)" -lt 0 ]; then \
+ grep -rl 'bell_sound' /usr/share/omarchy/default/hypr | xargs -r sed -i '/^[[:space:]]*bell_sound[[:space:]]*=/d'; \
+ if grep -rn 'bell_sound' /usr/share/omarchy/default/hypr; then echo "ERROR: misc.bell_sound is still set for Hyprland $hv" >&2; exit 1; fi; \
+ fi
+
# The desktop user (uid 1000, like every libs/images desktop), seeded from
# Omarchy's /etc/skel and its unattended setup: the default theme applied
# headless, first-run and finalize marked done (they are interactive), and the
diff --git a/libs/images/omarchy/image.json b/libs/images/omarchy/image.json
index 2308626334..f142b3d097 100644
--- a/libs/images/omarchy/image.json
+++ b/libs/images/omarchy/image.json
@@ -172,6 +172,8 @@
"features_optional": [
"background_input",
"hotspot",
+ "spawn",
+ "process.services",
"relay_attach",
"h264_hw",
"audio.desktop",
diff --git a/libs/images/omarchy/vm.Dockerfile b/libs/images/omarchy/vm.Dockerfile
index 1ebe3cc845..edd3165e6d 100644
--- a/libs/images/omarchy/vm.Dockerfile
+++ b/libs/images/omarchy/vm.Dockerfile
@@ -16,17 +16,22 @@ USER root
# mkinitcpio-cua.conf and pacman's kernel hooks are allowed to fail. Limine's
# "FAT32 boot partition not found" hook error in the build log is therefore
# expected and harmless (it is in green runs too).
-# mirror.omarchy.org keeps no old package versions and can be mid-sync, so
-# the sync database saved by the rootfs build goes stale within minutes
-# (404, or "Exceeded the maximum allowed file size"). The first attempt uses
-# it; retries refresh it with -Syu, which keeps the transaction consistent.
+# The VM layer installs from the same dated Arch archive snapshot as the rootfs
+# (/etc/cua-image/pacman-mirrorlist.build). mirror.omarchy.org keeps no old
+# package versions, and a rolling `pacman -Syu` upgrades hyprland past the exact
+# version cua-hyprland-plugin pins ("installing hyprland (0.57.0-1) breaks
+# dependency 'hyprland=0.56.2-4'", failing every build from 2026-10-31). Retries
+# refresh the snapshot database with -Sy and never upgrade the system.
COPY omarchy/files/mkinitcpio-cua.conf /etc/cua-image/mkinitcpio-cua.conf
RUN set -eu; \
+ test -s /etc/cua-image/pacman-mirrorlist.build || { echo "ERROR: /etc/cua-image/pacman-mirrorlist.build is missing: rebuild the omarchy rootfs image from this branch (the VM layer must install from the same Arch snapshot as the rootfs)." >&2; exit 1; }; \
+ cp /etc/pacman.d/mirrorlist /tmp/mirrorlist.final; \
+ cp /etc/cua-image/pacman-mirrorlist.build /etc/pacman.d/mirrorlist; \
pacman -Q | sort >/tmp/rootfs-packages; \
- pkgs="linux mkinitcpio cloud-init cloud-guest-utils openssh qemu-guest-agent e2fsprogs dosfstools"; \
+ pkgs="linux mkinitcpio cloud-init cloud-guest-utils openssh qemu-guest-agent e2fsprogs dosfstools nftables"; \
for attempt in 1 2 3 4; do \
if [ "$attempt" = 1 ]; then pacman -S --noconfirm --needed $pkgs && break; \
- else pacman -Syu --noconfirm --needed $pkgs && break; fi; \
+ else pacman -Sy --noconfirm --needed $pkgs && break; fi; \
[ "$attempt" = 4 ] && exit 1; echo "pacman attempt $attempt failed; refreshing the database and retrying" >&2; sleep 30; done; \
kver="$(ls /usr/lib/modules | sort -V | tail -1)"; \
install -m 0644 "/usr/lib/modules/$kver/vmlinuz" /boot/vmlinuz-linux; \
@@ -37,10 +42,19 @@ RUN set -eu; \
rm -f /boot/initramfs-linux*.img; \
pacman -Q | sort | comm -13 /tmp/rootfs-packages - | cut -d' ' -f1 >/etc/cua-image/variant-packages; \
rm -f /tmp/rootfs-packages; \
+ pacman -Q hyprland cua-hyprland-plugin >/dev/null || { echo "ERROR: hyprland and cua-hyprland-plugin are not both installed after the VM layer; the plugin pins an exact hyprland version." >&2; exit 1; }; \
+ cp /tmp/mirrorlist.final /etc/pacman.d/mirrorlist; rm -f /tmp/mirrorlist.final; \
yes | pacman -Scc >/dev/null
COPY common/vm/files/fstab /etc/fstab
COPY common/vm/files/99-cua-cloud.cfg /etc/cloud/cloud.cfg.d/99-cua-cloud.cfg
+# CVE-2026-98432 interim guard (IPv4 options dropped before TCP); remove once the
+# snapshot's kernel is at or above the fixed version for its series.
+COPY common/vm/files/cua-ipopts/cua-ipopts-guard /opt/cua/bin/cua-ipopts-guard
+COPY common/vm/files/cua-ipopts/cua-ipopts.nft /etc/cua-image/cua-ipopts.nft
+COPY common/vm/files/cua-ipopts/cua-ipopts.service /etc/systemd/system/cua-ipopts.service
+COPY common/vm/files/cua-ipopts/90-cua-ipopts.conf /etc/sysctl.d/90-cua-ipopts.conf
+RUN chmod 0755 /opt/cua/bin/cua-ipopts-guard && systemctl enable cua-ipopts.service
COPY omarchy/files/kubevirt.nmconnection /etc/NetworkManager/system-connections/kubevirt.nmconnection
RUN chmod 600 /etc/NetworkManager/system-connections/kubevirt.nmconnection \
&& rm -f /etc/ssh/ssh_host_* /var/lib/dbus/machine-id
diff --git a/libs/images/sandbox-images.json b/libs/images/sandbox-images.json
index e6b5af560e..1e7929bf09 100644
--- a/libs/images/sandbox-images.json
+++ b/libs/images/sandbox-images.json
@@ -247,17 +247,18 @@
"ref": "ghcr.io/trycua/macos:26-xcode",
"group": "canonical",
"os": "macos",
- "name": "macOS Tahoe 26 with Xcode",
+ "name": "macOS Tahoe 26 with developer tools",
"distro": { "id": "macos", "name": "macOS Tahoe 26" },
"tier": "xcode",
"variant": "vm",
- "summary": "The default macOS image plus one pinned Xcode, its iOS simulator runtime and the Metal toolchain. Local only.",
+ "summary": "The macOS Space with developer tools: the default macOS image plus Xcode, its iOS Simulator runtime, Rust iOS targets, CocoaPods, XcodeGen and sccache. Xcode and the Simulator runtimes are Apple software under Apple's license, for use on Apple-branded hardware. Local only.",
"spacesd": true,
"browsers": ["safari", "chrome"],
"arch": ["arm64"],
"local": "lume",
"cloud": null,
"published": false,
+ "derived_from": "ghcr.io/trycua/macos:26",
"sdk": "Image.macos(tier=\"xcode\")",
"guide": "/lume/quickstart"
},
diff --git a/libs/python/cua-sandbox/tests/test_image.py b/libs/python/cua-sandbox/tests/test_image.py
index c57d3bac30..dfc4ddc71d 100644
--- a/libs/python/cua-sandbox/tests/test_image.py
+++ b/libs/python/cua-sandbox/tests/test_image.py
@@ -288,7 +288,15 @@ def _published(ref):
root = Path(__file__).resolve().parents[3]
catalog = json.loads((root / "images/sandbox-images.json").read_text())
- return next((i["published"] for i in catalog["images"] if i["ref"] == ref), True)
+ # An entry built on the user's own machine (derived_from) resolves while unpublished.
+ return next(
+ (
+ i["published"] or bool(i.get("derived_from"))
+ for i in catalog["images"]
+ if i["ref"] == ref
+ ),
+ True,
+ )
class TestTiersAndOmarchy:
diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
index 9217cb6fa1..18727594d7 100644
--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
@@ -17070,6 +17070,17 @@ public struct AppExperiments: Equatable, Hashable {
* ([`crate::settings::resolve_new_ui`]); kept for older files and builds.
*/
public var webUi: Bool
+ /**
+ * Secure Spaces: a Space reaches the internet and nothing else on the
+ * network unless it is opened. Off unless turned on; the daemon enforces
+ * it (the switch is kept in the cua home).
+ */
+ public var secureSpaces: Bool
+ /**
+ * Child Spaces: a Space may make Spaces of its own. Off unless turned
+ * on; the daemon enforces it (the switch is kept in the cua home).
+ */
+ public var childSpaces: Bool
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -17087,11 +17098,22 @@ public struct AppExperiments: Equatable, Hashable {
/**
* The shared web UI is the main window. Always on in the macOS shell
* ([`crate::settings::resolve_new_ui`]); kept for older files and builds.
- */webUi: Bool) {
+ */webUi: Bool,
+ /**
+ * Secure Spaces: a Space reaches the internet and nothing else on the
+ * network unless it is opened. Off unless turned on; the daemon enforces
+ * it (the switch is kept in the cua home).
+ */secureSpaces: Bool,
+ /**
+ * Child Spaces: a Space may make Spaces of its own. Off unless turned
+ * on; the daemon enforces it (the switch is kept in the cua home).
+ */childSpaces: Bool) {
self.cuaVolume = cuaVolume
self.yourCloud = yourCloud
self.sharing = sharing
self.webUi = webUi
+ self.secureSpaces = secureSpaces
+ self.childSpaces = childSpaces
}
@@ -17113,7 +17135,9 @@ public struct FfiConverterTypeAppExperiments: FfiConverterRustBuffer {
cuaVolume: FfiConverterBool.read(from: &buf),
yourCloud: FfiConverterBool.read(from: &buf),
sharing: FfiConverterBool.read(from: &buf),
- webUi: FfiConverterBool.read(from: &buf)
+ webUi: FfiConverterBool.read(from: &buf),
+ secureSpaces: FfiConverterBool.read(from: &buf),
+ childSpaces: FfiConverterBool.read(from: &buf)
)
}
@@ -17122,6 +17146,8 @@ public struct FfiConverterTypeAppExperiments: FfiConverterRustBuffer {
FfiConverterBool.write(value.yourCloud, into: &buf)
FfiConverterBool.write(value.sharing, into: &buf)
FfiConverterBool.write(value.webUi, into: &buf)
+ FfiConverterBool.write(value.secureSpaces, into: &buf)
+ FfiConverterBool.write(value.childSpaces, into: &buf)
}
}
@@ -80684,7 +80710,9 @@ public func appSettingsInputFromJson(json: String)throws -> AppSettingsInput {
})
}
/**
- * Reads the settings file (defaults when missing or damaged).
+ * Reads the settings file (defaults when missing or damaged). The
+ * experiments the daemon enforces (Secure Spaces, Child Spaces) are what
+ * the cua home keeps, so `cua experiments enable` shows in the app.
*/
public func appSettingsLoad(path: String) -> AppSettings {
return try! FfiConverterTypeAppSettings_lift(try! rustCall() {
@@ -80717,7 +80745,8 @@ public func appSettingsResolveNewUi(settings: AppSettings, version: String) -> A
})
}
/**
- * Writes the settings file.
+ * Writes the settings file, and keeps the experiments the daemon enforces
+ * where it reads them (the cua home).
*/
public func appSettingsSave(path: String, settings: AppSettings)throws {try rustCallWithError(FfiConverterTypeCuaError_lift) {
uniffi_cua_spaces_ffi_fn_func_app_settings_save(
@@ -82802,7 +82831,7 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_spaces_ffi_checksum_func_app_settings_input_from_json() != 15437) {
return InitializationResult.apiChecksumMismatch
}
- if (uniffi_cua_spaces_ffi_checksum_func_app_settings_load() != 42027) {
+ if (uniffi_cua_spaces_ffi_checksum_func_app_settings_load() != 48517) {
return InitializationResult.apiChecksumMismatch
}
if (uniffi_cua_spaces_ffi_checksum_func_app_settings_page() != 454) {
@@ -82811,7 +82840,7 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_spaces_ffi_checksum_func_app_settings_resolve_new_ui() != 48081) {
return InitializationResult.apiChecksumMismatch
}
- if (uniffi_cua_spaces_ffi_checksum_func_app_settings_save() != 30129) {
+ if (uniffi_cua_spaces_ffi_checksum_func_app_settings_save() != 62204) {
return InitializationResult.apiChecksumMismatch
}
if (uniffi_cua_spaces_ffi_checksum_func_app_settings_with_storage() != 34252) {
diff --git a/libs/spaces-sdk-swift/Sources/CuaSpaces/MCPSurface.swift b/libs/spaces-sdk-swift/Sources/CuaSpaces/MCPSurface.swift
index 31c86bf291..e6336e5a2a 100644
--- a/libs/spaces-sdk-swift/Sources/CuaSpaces/MCPSurface.swift
+++ b/libs/spaces-sdk-swift/Sources/CuaSpaces/MCPSurface.swift
@@ -481,3 +481,42 @@ public struct SiteLogin: Sendable, Equatable {
public let targetID: String?
public let tabID: String?
}
+
+// MARK: - Keep running
+
+/// Commands the Space keeps running: restarted by their policy when they end
+/// or fail their health check, started when the Space boots, their output
+/// kept in a log file in the Space.
+public struct KeepRunning: Sendable {
+ let space: Space
+
+ /// Calls `space_service` with `action` and its arguments, and returns
+ /// the tool's JSON answer (`services`, a service, `logs` or `removed`).
+ @discardableResult
+ public func service(_ action: String, _ arguments: [String: JSONValue] = [:]) async throws -> JSONValue {
+ var args = arguments
+ args["space"] = .string(space.id.rawValue)
+ args["action"] = .string(action)
+ return try await space.connection.callTool("space_service", args)
+ }
+
+ /// Keeps `command` running as `name` (replacing a service of that name).
+ @discardableResult
+ public func add(_ name: String, command: String, restart: String = "always") async throws -> JSONValue {
+ try await service("add", ["name": .string(name), "command": .string(command),
+ "restart": .string(restart)])
+ }
+
+ /// The Space's services.
+ public func list() async throws -> JSONValue { try await service("list") }
+
+ /// Stops a service and forgets it.
+ public func remove(_ name: String) async throws {
+ _ = try await service("remove", ["name": .string(name)])
+ }
+}
+
+extension Space {
+ /// Commands this Space keeps running (`space_service`).
+ public var keepRunning: KeepRunning { KeepRunning(space: self) }
+}
diff --git a/libs/spaces-sdk-swift/Tests/CuaSpacesTests/FakeSpace.swift b/libs/spaces-sdk-swift/Tests/CuaSpacesTests/FakeSpace.swift
index b3209a8651..69e0135a6f 100644
--- a/libs/spaces-sdk-swift/Tests/CuaSpacesTests/FakeSpace.swift
+++ b/libs/spaces-sdk-swift/Tests/CuaSpacesTests/FakeSpace.swift
@@ -316,6 +316,9 @@ actor FakeSpacesBackend: SpacesTransport {
// own desktop, not a structured result. Nothing to render.
return .string("Pinned \(arguments["space"]?.stringValue ?? "") on your desktop.")
+ case "space_service":
+ return .object(["services": .array([])])
+
case "space_write":
let path = arguments["path"]?.stringValue ?? ""
files.insert(Self.expand(path))
diff --git a/libs/spaces-sdk-swift/Tests/CuaSpacesTests/ToolCoverageTests.swift b/libs/spaces-sdk-swift/Tests/CuaSpacesTests/ToolCoverageTests.swift
index 2afff37c77..52999ef2bf 100644
--- a/libs/spaces-sdk-swift/Tests/CuaSpacesTests/ToolCoverageTests.swift
+++ b/libs/spaces-sdk-swift/Tests/CuaSpacesTests/ToolCoverageTests.swift
@@ -95,6 +95,7 @@ import Testing
// --- The Space's own MCP services -----------------------------------
_ = try await space.services.tools() // list_tools
_ = try await space.services.call("screenshot") // call_tool
+ _ = try await space.keepRunning.service("list") // space_service
// --- Agents ----------------------------------------------------------
let run = try await space.startAgent(prompt: "x") // agent_start
diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.json
index 904526c546..c8a919763e 100644
--- a/scripts/docs-generators/cli-specs/cua.json
+++ b/scripts/docs-generators/cli-specs/cua.json
@@ -9985,6 +9985,245 @@
"subcommands": [],
"usage": "cua build [OPTIONS] [CONTEXT]"
},
+ {
+ "abstract": "What a Space can reach on the network, and changing it: `show`, `set`, `log`. An experiment: see `cua experiments`",
+ "aliases": [],
+ "arguments": [],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "network",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [
+ {
+ "abstract": "What a Space can reach: its preset, what it opens, where it is enforced, and what is always blocked",
+ "after_help": "Examples:\n cua network show studio\n cua network show local:studio --json",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Space id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "show",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua network show [OPTIONS] <SPACE>"
+ },
+ {
+ "abstract": "Change what a Space can reach. A child Space stays within its parent's unless `--widen`",
+ "after_help": "Examples:\n # This computer's Postgres and dev server only\n cua network set studio --network localhost:5432,3000\n # Your local network too\n cua network set studio --network lan\n # Only these destinations\n cua network set studio --network custom:none --allow 140.82.112.0/20\n # Back to the default\n cua network set studio --network internet",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Space id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "A child Space: let it reach more than its parent (recorded on the Space)",
+ "hidden": false,
+ "name": "widen",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ },
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "Its child Spaces get the same settings (each within its parent's)",
+ "hidden": false,
+ "name": "tree",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ }
+ ],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "set",
+ "options": [
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "`internet`, `none`, `localhost:<ports>` (or `localhost:all`), `lan`, `custom`, `custom:none` or `unprotected` (No protection)",
+ "hidden": false,
+ "is_optional": false,
+ "multiple_values": false,
+ "name": "network",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "string",
+ "value_name": "PRESET"
+ },
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "Allow this destination (IP or CIDR; repeat for more)",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "allow",
+ "possible_values": [],
+ "repeatable": true,
+ "short_name": null,
+ "takes_value": true,
+ "type": "string",
+ "value_name": "ADDR|CIDR"
+ },
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "Block this destination (IP, CIDR or `all`; repeat for more)",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "deny",
+ "possible_values": [],
+ "repeatable": true,
+ "short_name": null,
+ "takes_value": true,
+ "type": "string",
+ "value_name": "ADDR|CIDR|all"
+ }
+ ],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua network set [OPTIONS] --network <PRESET> <SPACE>"
+ },
+ {
+ "abstract": "What a Space tried to reach and was blocked, most recent first",
+ "after_help": "Examples:\n cua network log studio",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Space id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "log",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua network log [OPTIONS] <SPACE>"
+ }
+ ],
+ "usage": "cua network [OPTIONS] <COMMAND>"
+ },
+ {
+ "abstract": "Features that are still being built, one switch each: `list`, `enable`, `disable`",
+ "aliases": [],
+ "arguments": [],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "experiments",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [
+ {
+ "abstract": "Every experiment and whether it is on",
+ "after_help": "Examples:\n cua experiments list\n cua experiments list --json",
+ "aliases": [],
+ "arguments": [],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "list",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua experiments list [OPTIONS]"
+ },
+ {
+ "abstract": "Turn an experiment on",
+ "after_help": "Examples:\n cua experiments enable secure-spaces",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "The experiment's name, as `cua experiments` lists it",
+ "hidden": false,
+ "is_optional": false,
+ "name": "NAME",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "enable",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua experiments enable [OPTIONS] <NAME>"
+ },
+ {
+ "abstract": "Turn an experiment off. Nothing it made is deleted",
+ "after_help": "Examples:\n cua experiments disable secure-spaces",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "The experiment's name, as `cua experiments` lists it",
+ "hidden": false,
+ "is_optional": false,
+ "name": "NAME",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "disable",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua experiments disable [OPTIONS] <NAME>"
+ }
+ ],
+ "usage": "cua experiments [OPTIONS] <COMMAND>"
+ },
{
"abstract": "Images: local OCI pull/build/push",
"aliases": [
@@ -13939,6 +14178,17 @@
"repeatable": false,
"short_name": null,
"takes_value": false
+ },
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "List child Spaces under their parent, indented (otherwise the parent's row counts them)",
+ "hidden": false,
+ "name": "tree",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
}
],
"hidden": false,
@@ -14096,6 +14346,17 @@
"short_name": null,
"takes_value": false
},
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "Let it make child Spaces of its own: `cua`, the SDKs and the agent's tools in it create, list and delete Spaces that belong to it, on this computer, never wider than it (`cua spaces children`). Agent runs turn this on by themselves",
+ "hidden": false,
+ "name": "children",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ },
{
"aliases": [],
"default_value": false,
@@ -14106,6 +14367,17 @@
"repeatable": false,
"short_name": null,
"takes_value": false
+ },
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "With --parent: let its network be more open than its parent's (recorded on the Space)",
+ "hidden": false,
+ "name": "widen",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
}
],
"hidden": false,
@@ -14324,51 +14596,87 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Block this destination from the guest's first instruction (IP, CIDR or `all`; repeat for more). Enforced by the host, outside the guest. See `cua spaces egress`",
+ "help": "Its network: `internet` (the default: the internet and its own tree; this computer, your local network, cloud metadata and other trees are blocked), `none`, `localhost:5432,3000` (also this computer's localhost on those ports), `lan` (also your local network), `custom` / `custom:none` (with --allow/--deny), or `unprotected` (No protection). Enforced by the host, outside the guest. See `cua network`",
"hidden": false,
"is_optional": true,
"multiple_values": false,
- "name": "egress-deny",
+ "name": "network",
"possible_values": [],
- "repeatable": true,
+ "repeatable": false,
"short_name": null,
"takes_value": true,
"type": "string",
- "value_name": "ADDR|CIDR|all"
+ "value_name": "PRESET"
},
{
- "aliases": [],
+ "aliases": [
+ "egress-deny"
+ ],
"default_value": null,
"env": null,
- "help": "Keep this destination reachable where --egress-deny blocks it",
+ "help": "Block this destination (IP, CIDR or `all`; repeat for more)",
"hidden": false,
"is_optional": true,
"multiple_values": false,
- "name": "egress-allow",
+ "name": "deny",
"possible_values": [],
"repeatable": true,
"short_name": null,
"takes_value": true,
"type": "string",
"value_name": "ADDR|CIDR|all"
- }
- ],
- "subcommand_optional": false,
- "subcommands": [],
- "usage": "cua spaces create [OPTIONS] [IMAGE]"
- },
- {
- "abstract": "Keep Spaces of one image ready where the elastic pool puts them, so the next creates of that shape start in a fraction of a second (`--list` shows the prewarms, `--remove ID` ends one)",
- "after_help": "Examples:\n cua spaces prewarm ghcr.io/trycua/linux:24.04-slim --count 16 --on aws --ttl 1h\n cua spaces prewarm linux --count 4 --kind container --cpus 1 --memory-mb 512\n cua spaces prewarm --list\n cua spaces prewarm --remove pw-1a2b3c",
- "aliases": [],
- "arguments": [
+ },
{
+ "aliases": [
+ "egress-allow"
+ ],
"default_value": null,
- "help": "Image (an alias or a registry reference)",
+ "env": null,
+ "help": "Allow this destination, also where a block covers it (IP or CIDR; repeat for more)",
"hidden": false,
"is_optional": true,
- "name": "IMAGE",
- "possible_values": [],
+ "multiple_values": false,
+ "name": "allow",
+ "possible_values": [],
+ "repeatable": true,
+ "short_name": null,
+ "takes_value": true,
+ "type": "string",
+ "value_name": "ADDR|CIDR"
+ },
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "Create it as a child of this Space: it joins the parent's tree (they reach each other) and its network is no more open than the parent's. With `--parent`, the children are deleted, stopped and suspended with it",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "parent",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "string",
+ "value_name": "SPACE"
+ }
+ ],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua spaces create [OPTIONS] [IMAGE]"
+ },
+ {
+ "abstract": "Keep Spaces of one image ready where the elastic pool puts them, so the next creates of that shape start in a fraction of a second (`--list` shows the prewarms, `--remove ID` ends one)",
+ "after_help": "Examples:\n cua spaces prewarm ghcr.io/trycua/linux:24.04-slim --count 16 --on aws --ttl 1h\n cua spaces prewarm linux --count 4 --kind container --cpus 1 --memory-mb 512\n cua spaces prewarm --list\n cua spaces prewarm --remove pw-1a2b3c",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Image (an alias or a registry reference)",
+ "hidden": false,
+ "is_optional": true,
+ "name": "IMAGE",
+ "possible_values": [],
"repeatable": false,
"type": "string"
}
@@ -14610,6 +14918,565 @@
"subcommands": [],
"usage": "cua spaces egress [OPTIONS] <SPACE>"
},
+ {
+ "abstract": "Let a Space make child Spaces of its own, or stop it. While on, `cua`, the SDKs and the agent's tools inside it create, list and delete Spaces that belong to it: on this computer, with its egress rules, ending no later than it, through a channel only it can reach. Off ends its capability at once; children it made keep running until deleted or their lifetime ends",
+ "after_help": "Examples:\n cua spaces children studio on\n cua spaces children studio off",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Space id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "`on` or `off`",
+ "hidden": false,
+ "is_optional": false,
+ "name": "STATE",
+ "possible_values": [
+ "on",
+ "off"
+ ],
+ "repeatable": false,
+ "type": "on | off"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "children",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua spaces children [OPTIONS] <SPACE> <STATE>"
+ },
+ {
+ "abstract": "Show or set a tree's budget: how many child Spaces, vCPUs and memory its children may hold at once, and what they may cost. A child that does not fit is refused with what is left. Without flags it shows the budget and what the children use",
+ "after_help": "Examples:\n cua spaces budget studio\n cua spaces budget studio --spaces 32 --cpus 64 --memory 131072\n cua spaces budget studio --usd-per-hour 5 --usd-total 50\n cua spaces budget studio --clear",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Any Space of the tree (id or name)",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "Back to the defaults",
+ "hidden": false,
+ "name": "clear",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ }
+ ],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "budget",
+ "options": [
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "Child Spaces at once (default 16)",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "spaces",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "integer",
+ "value_name": "SPACES"
+ },
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "vCPUs at once (default 16)",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "cpus",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "integer",
+ "value_name": "CPUS"
+ },
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "Memory at once, in MiB (default 32768)",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "memory",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "integer",
+ "value_name": "MIB"
+ },
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "Cost per hour in linked clouds, in dollars (default 2)",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "usd-per-hour",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "number",
+ "value_name": "USD"
+ },
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "Cost in total, in dollars (default: none)",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "usd-total",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "number",
+ "value_name": "USD"
+ }
+ ],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua spaces budget [OPTIONS] <SPACE>"
+ },
+ {
+ "abstract": "List child Spaces whose parent is gone or out of reach. The daemon ends a child only on proof its parent is gone, after a grace period; the others stay until you delete them or their lifetime ends",
+ "after_help": "Examples:\n cua spaces orphans",
+ "aliases": [],
+ "arguments": [],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "orphans",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua spaces orphans [OPTIONS]"
+ },
+ {
+ "abstract": "Keep a command running in a Space: started again when it exits or fails its health check (with a backoff), started when the Space boots, its output kept in a log file in the Space",
+ "aliases": [],
+ "arguments": [],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "service",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [
+ {
+ "abstract": "Keep a command running (replaces a service of that name)",
+ "after_help": "Examples:\n cua spaces service add studio web -- python3 -m http.server 8080\n cua spaces service add studio web --http http://127.0.0.1:8080/ -- python3 -m http.server 8080\n cua spaces service add studio job --restart on-failure -- ./run.sh",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Space id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "Service name (lowercase letters, digits, `-`, `_`, `.`)",
+ "hidden": false,
+ "is_optional": false,
+ "name": "NAME",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "The command (after `--`)",
+ "hidden": false,
+ "is_optional": false,
+ "name": "COMMAND",
+ "possible_values": [],
+ "repeatable": true,
+ "type": "string"
+ }
+ ],
+ "flags": [
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "Do not start it when the Space boots",
+ "hidden": false,
+ "name": "no-boot",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ }
+ ],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "add",
+ "options": [
+ {
+ "aliases": [],
+ "default_value": "always",
+ "env": null,
+ "help": "When to start it again: always, on-failure or never",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "restart",
+ "possible_values": [
+ "always",
+ "on-failure",
+ "never"
+ ],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "always | on-failure | never",
+ "value_name": "RESTART"
+ },
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "Health check: a URL that answers 2xx or 3xx",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "http",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "string",
+ "value_name": "HTTP"
+ },
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "Health check: `host:port` that accepts a connection",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "tcp",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "string",
+ "value_name": "TCP"
+ },
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "Health check: a shell command that exits 0 when healthy",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "check",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "string",
+ "value_name": "CHECK"
+ },
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "`KEY=VALUE` for its environment (repeat for more)",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "env",
+ "possible_values": [],
+ "repeatable": true,
+ "short_name": null,
+ "takes_value": true,
+ "type": "string",
+ "value_name": "KEY=VALUE"
+ },
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "Working directory in the Space",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "cwd",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "string",
+ "value_name": "CWD"
+ }
+ ],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua spaces service add [OPTIONS] <SPACE> <NAME> -- <COMMAND>..."
+ },
+ {
+ "abstract": "List a Space's services",
+ "after_help": "Examples:\n cua spaces service ls studio",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Space id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "ls",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua spaces service ls [OPTIONS] <SPACE>"
+ },
+ {
+ "abstract": "Show the end of a service's log",
+ "after_help": "Examples:\n cua spaces service logs studio web",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Space id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "Service name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "NAME",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "logs",
+ "options": [
+ {
+ "aliases": [],
+ "default_value": "65536",
+ "env": null,
+ "help": "Bytes from the end",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "tail",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "integer",
+ "value_name": "TAIL"
+ }
+ ],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua spaces service logs [OPTIONS] <SPACE> <NAME>"
+ },
+ {
+ "abstract": "Start a stopped service",
+ "after_help": "Examples:\n cua spaces service start studio web",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Space id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "Service name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "NAME",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "start",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua spaces service start [OPTIONS] <SPACE> <NAME>"
+ },
+ {
+ "abstract": "Stop a service and keep it stopped",
+ "after_help": "Examples:\n cua spaces service stop studio web",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Space id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "Service name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "NAME",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "stop",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua spaces service stop [OPTIONS] <SPACE> <NAME>"
+ },
+ {
+ "abstract": "Restart a service",
+ "after_help": "Examples:\n cua spaces service restart studio web",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Space id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "Service name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "NAME",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "restart",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua spaces service restart [OPTIONS] <SPACE> <NAME>"
+ },
+ {
+ "abstract": "Stop a service and forget it",
+ "after_help": "Examples:\n cua spaces service rm studio web",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Space id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "Service name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "NAME",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "rm",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua spaces service rm [OPTIONS] <SPACE> <NAME>"
+ }
+ ],
+ "usage": "cua spaces service [OPTIONS] <COMMAND>"
+ },
{
"abstract": "Cancel a create that is still running (here, in the daemon, or in another terminal): it stops and what it made is removed. Finished image downloads stay cached. Ctrl-C during `cua spaces create` does the same",
"after_help": "Examples:\n cua spaces cancel local:space-1a2b3c\n cua spaces cancel studio",
@@ -14693,6 +15560,17 @@
"repeatable": false,
"short_name": "f",
"takes_value": false
+ },
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "Keep its child Spaces: they become top-level Spaces and keep running (otherwise they are deleted first)",
+ "hidden": false,
+ "name": "keep-children",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
}
],
"hidden": false,
diff --git a/scripts/docs-generators/cua-cli.ts b/scripts/docs-generators/cua-cli.ts
index 4c36a08175..24e6bf7c3a 100644
--- a/scripts/docs-generators/cua-cli.ts
+++ b/scripts/docs-generators/cua-cli.ts
@@ -95,10 +95,16 @@ export interface CuaDumpDocs {
export const CLI_GROUPS: CliGroup[] = [
{
slug: 'spaces-and-computers',
- title: 'Spaces, computers and teams',
+ title: 'Spaces',
+ summary: 'Your Spaces, what they can reach, and keeping commands running in them',
+ commands: ['spaces', 'network'],
+ },
+ {
+ slug: 'computers-and-teams',
+ title: 'Computers and teams',
summary:
- 'Your Spaces and machines, unattended access on this machine, devices, teams, your remote use this month, and a cua-spacesd by URL',
- commands: ['spaces', 'machines', 'host', 'devices', 'team', 'usage', 'spacesd', 'share'],
+ 'Your computers, unattended access on this computer, teams, sharing, your remote use this month, and a cua-spacesd by URL',
+ commands: ['machines', 'host', 'devices', 'team', 'usage', 'spacesd', 'share'],
},
{
slug: 'files-teleport-and-keys',
@@ -134,7 +140,7 @@ export const CLI_GROUPS: CliGroup[] = [
slug: 'account-and-setup',
title: 'Account and setup',
summary: 'Sign in and out, user defaults, the cua daemon, health checks and usage telemetry',
- commands: ['auth', 'config', 'daemon', 'doctor', 'telemetry'],
+ commands: ['auth', 'config', 'daemon', 'doctor', 'telemetry', 'experiments'],
},
{
slug: 'pool',
diff --git a/scripts/docs-generators/cua-sdk.ts b/scripts/docs-generators/cua-sdk.ts
index 770a9f8f4e..092ce10502 100644
--- a/scripts/docs-generators/cua-sdk.ts
+++ b/scripts/docs-generators/cua-sdk.ts
@@ -505,7 +505,41 @@ export const PAGES: PageSpec[] = [
description: 'The Spaces registry: create, add, resolve, delete and remove Spaces, their create options, and agent runs in a Space.',
intro:
'`cua.spaces()` returns the `Spaces` registry. Create a Space where `on` says (local or cloud), or add an existing machine by URL, then open a [`Space`](/cua-sdk/reference/spaces/space). See [resize](/cua-sdk/reference/spaces/resize) to change a local VM\'s shape.',
- items: ['Spaces', 'SpaceInfo', 'spaces_tool_methods', 'SpacesToolMethod'],
+ items: ['Spaces'],
+ },
+ {
+ slug: 'spaces/info',
+ title: 'Space records',
+ description: 'What a Space listing returns, and the Spaces tools `cua mcp` serves with the typed method that covers each.',
+ intro: '`SpaceInfo` is one row of a Spaces listing. `spaces_tool_methods` lists every Spaces tool with the method of `Spaces` or `Space` that covers it.',
+ items: ['SpaceInfo', 'spaces_tool_methods', 'SpacesToolMethod'],
+ },
+ {
+ slug: 'spaces/network',
+ title: 'Network settings (experiment)',
+ description: 'What a Space can reach: its network preset, the allow and deny lists, and deleting a Space together with its children.',
+ intro:
+ 'These calls belong to the Secure Spaces experiment (`cua experiments enable secure-spaces`) and are refused while it is off. `Spaces.network` says what a Space can reach and where that is enforced, `set_network` changes it (a child Space stays within its parent\'s unless widened), and `delete_tree` deletes a Space with or without its children. See [A Space\'s network](/cua-sdk/guides/egress).',
+ items: ['NetworkSettings', 'SpaceNetworkInfo', 'SetNetworkResult'],
+ members: [{ object: 'Spaces', title: 'Network', methods: ['network', 'ack_network_notice', 'set_network', 'delete_tree'] }],
+ },
+ {
+ slug: 'spaces/children',
+ title: 'Child Spaces (experiment)',
+ description: 'Let a Space make Spaces of its own, set the budget of its tree and list orphans.',
+ intro:
+ 'These calls belong to the Child Spaces experiment (`cua experiments enable child-spaces`) and are refused while it is off. `set_children` lets a Space make children through a channel only it can reach; `tree_budget` and `set_tree_budget` bound what a tree may hold and spend; `orphans` lists children whose parent is gone. See [Child Spaces](/spaces/guides/child-spaces).',
+ items: ['TreeBudget', 'TreeBudgetLimits', 'SpaceOrphan'],
+ members: [{ object: 'Spaces', title: 'Children', methods: ['set_children', 'tree_budget', 'set_tree_budget', 'orphans'] }],
+ },
+ {
+ slug: 'spaces/services',
+ title: 'Kept commands (experiment)',
+ description: 'Keep a command running in a Space: restarts, health checks, start on boot and logs.',
+ intro:
+ 'These calls belong to the Child Spaces experiment (`cua experiments enable child-spaces`) for adding a service; listing, stopping and removing work either way. See [Keep a command running](/spaces/guides/keep-a-command-running).',
+ items: ['SpaceServiceDef', 'SpaceServiceProbe', 'SpaceServiceInfo'],
+ members: [{ object: 'Space', title: 'Services', methods: ['put_service', 'kept_services', 'start_service', 'stop_service', 'restart_service', 'delete_service', 'service_logs'] }],
},
{
slug: 'spaces/resize',
diff --git a/scripts/docs-generators/sandbox.ts b/scripts/docs-generators/sandbox.ts
index 8ae104a6d1..64c53274d9 100644
--- a/scripts/docs-generators/sandbox.ts
+++ b/scripts/docs-generators/sandbox.ts
@@ -348,7 +348,7 @@ export type SandboxImageList = {
export const IMAGE_LIST_PATH = 'libs/images/sandbox-images.json';
-const OPTIONAL_IMAGE_FIELDS = ['guide', 'lock', 'benchmarks', 'sdk', 'digest', 'sizes', 'tier', 'gpu'];
+const OPTIONAL_IMAGE_FIELDS = ['guide', 'lock', 'benchmarks', 'sdk', 'digest', 'sizes', 'tier', 'gpu', 'derived_from'];
/** The tag suffix each tier puts before `-disk`: `<os-version>[-<tier>][-disk]`. */
const TIER_SUFFIX: Record<string, string> = { slim: '-slim', full: '', xcode: '-xcode', docker: '-docker' };
diff --git a/scripts/docs-generators/spaces.ts b/scripts/docs-generators/spaces.ts
index 65696984d3..fb2217be57 100644
--- a/scripts/docs-generators/spaces.ts
+++ b/scripts/docs-generators/spaces.ts
@@ -48,8 +48,14 @@ export const PAGES: Array<{ slug: string; title: string; description: string; ca
{
slug: 'spaces',
title: 'Spaces tools',
- description: 'Create, run, stream, share and serve from a Space: the Spaces tools with their parameters, results and errors.',
- categories: ['lifecycle', 'commands-and-files', 'streams-and-display', 'services', 'hotspot', 'sharing', 'cloud'],
+ description: 'Create, run, stream and serve from a Space: the Spaces tools with their parameters, results and errors.',
+ categories: ['lifecycle', 'commands-and-files', 'streams-and-display', 'services', 'hotspot'],
+ },
+ {
+ slug: 'sharing-and-cloud',
+ title: 'Sharing and cloud tools',
+ description: 'Share a Space with other accounts, and create Spaces in your own cloud: the tools with their parameters, results and errors.',
+ categories: ['sharing', 'cloud'],
},
{
slug: 'agents',
diff --git a/scripts/images/check-tag-safety.sh b/scripts/images/check-tag-safety.sh
index ced843c0da..ecd299e4b6 100755
--- a/scripts/images/check-tag-safety.sh
+++ b/scripts/images/check-tag-safety.sh
@@ -126,12 +126,6 @@ for ref in "${refs[@]}"; do
if [ "$tag" = latest ] && in_list "$nrepo" "${CANONICAL_REPOS[@]}"; then
echo "REFUSED $ref: canonical repos never carry latest" >&2; refused=1; continue
fi
- # Xcode (with its SDKs and simulator runtimes) is Apple's: the macOS Space
- # with developer tools is built on each user's own Mac and never pushed.
- if [[ "$nrepo" == ghcr.io/trycua/macos && "$tag" == *-xcode* ]]; then
- echo "REFUSED $ref: images with Xcode are not redistributable and are never published (libs/images/macos/derive-local.sh builds one per Mac)" >&2
- refused=1; continue
- fi
rc=0; cur="$(remote_digest "$ref")" || rc=$?
[ "$rc" = 0 ] || exit 2
if [ -z "$cur" ]; then echo "ok $ref (new tag)"; continue; fi
diff --git a/scripts/images/manifests/windows-2022.json b/scripts/images/manifests/windows-2022.json
index acc7ac72ee..3c39f769d4 100644
--- a/scripts/images/manifests/windows-2022.json
+++ b/scripts/images/manifests/windows-2022.json
@@ -35,6 +35,8 @@
],
"features_optional": [
"hotspot",
+ "spawn",
+ "process.services",
"relay_attach",
"teleport.*",
"audio.desktop",
diff --git a/scripts/images/sync-cua-vmm-recipe.sh b/scripts/images/sync-cua-vmm-recipe.sh
new file mode 100755
index 0000000000..b362d9b6d6
--- /dev/null
+++ b/scripts/images/sync-cua-vmm-recipe.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# Refresh the copies of the macOS recipe files that cua-vmm embeds
+# (libs/cua/crates/cua-vmm/recipe/), from libs/images/macos. A test in
+# scripts/images/tests fails when they differ.
+set -euo pipefail
+root="$(cd "$(dirname "$0")/../.." && pwd)"
+src="$root/libs/images/macos"
+dst="$root/libs/cua/crates/cua-vmm/recipe"
+mkdir -p "$dst"
+cp "$src/derive-local.sh" "$dst/macos-derive-local.sh"
+cp "$src/versions.env" "$dst/macos-versions.env"
+cp "$src/files/tier-xcode.sh" "$dst/macos-tier-xcode.sh"
+cp "$src/files/fetch.sh" "$dst/macos-fetch.sh"
+cp "$src/files/xcode-source.sh" "$dst/macos-xcode-source.sh"
diff --git a/scripts/images/test-check-tag-safety.sh b/scripts/images/test-check-tag-safety.sh
index 08cedc14b0..6357b7be82 100755
--- a/scripts/images/test-check-tag-safety.sh
+++ b/scripts/images/test-check-tag-safety.sh
@@ -44,10 +44,8 @@ L=ghcr.io/trycua/linux M=ghcr.io/trycua/macos W=ghcr.io/trycua/windows
check 0 --moving $L:24.04-slim
check 0 --moving $L:24.04-slim-disk
check 0 --moving $M:26
-check 1 --moving $M:26-xcode # Xcode images are never published
-check 1 --moving $M:26-xcode-26.1
-check 1 $M:26-xcode-26.1-20261101-abcdef1 # not even a new pin
-check 0 --moving $M:26-slim
+check 0 --moving $M:26-xcode
+check 0 --moving $M:26-xcode-26.1
check 0 --moving $W:15-disk
check 1 --moving $L:main # not in the grammar
check 1 --moving $L:24.04-full # full is the unsuffixed tag
diff --git a/scripts/images/tests/test_macos_dev_image.py b/scripts/images/tests/test_macos_dev_image.py
index 7254f81b21..8e3ad15c9e 100644
--- a/scripts/images/tests/test_macos_dev_image.py
+++ b/scripts/images/tests/test_macos_dev_image.py
@@ -1,7 +1,7 @@
"""Recipe lint and drift guards for the macOS Space with developer tools (the
-xcode tier of libs/images/macos): its pins, claims and catalog entry agree,
-every script parses, and nothing can publish an image that carries Xcode
-(Apple's terms do not let us redistribute it)."""
+xcode tier of libs/images/macos): its pins and claims agree, every script
+parses, the tier is published like the others, and what carries Xcode says
+whose software it is and where it may run."""
from __future__ import annotations
@@ -18,6 +18,7 @@ HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
MACOS = os.path.join(ROOT, "libs", "images", "macos")
CATALOG = os.path.join(ROOT, "libs", "images", "sandbox-images.json")
+WORKFLOW = os.path.join(ROOT, ".github", "workflows", "cd-image-macos.yml")
SCRIPTS = [
"build.sh",
"derive-local.sh",
@@ -27,6 +28,8 @@ SCRIPTS = [
"files/tier-xcode.sh",
"files/tier-full.sh",
"files/fetch.sh",
+ "files/xcode-source.sh",
+ "annotate.sh",
"dev-image-gate.sh",
"files/dev-image-gate-guest.sh",
]
@@ -61,7 +64,7 @@ class Recipe(unittest.TestCase):
@unittest.skipUnless(shutil.which("shellcheck"), "shellcheck not installed")
def test_new_scripts_pass_shellcheck(self):
- for s in ["derive-local.sh", "files/tier-xcode.sh", "files/fetch.sh"]:
+ for s in ["derive-local.sh", "files/tier-xcode.sh", "files/fetch.sh", "files/xcode-source.sh"]:
r = run(["shellcheck", "-x", "-S", "warning", os.path.join(MACOS, s)])
self.assertEqual(r.returncode, 0, f"{s}: {r.stdout}")
@@ -106,7 +109,7 @@ class Recipe(unittest.TestCase):
def test_derive_stages_what_the_tier_script_reads(self):
derive = open(os.path.join(MACOS, "derive-local.sh")).read()
- for needle in ("tier-xcode.sh", "versions.env", "fetch_xcode_tools", "xcode/"):
+ for needle in ("tier-xcode.sh", "versions.env", "fetch_xcode_tools", "xcode-source.sh"):
self.assertIn(needle, derive)
@@ -124,13 +127,33 @@ class Gate(unittest.TestCase):
self.assertIn(needle, guest)
-class NeverPublished(unittest.TestCase):
- def test_no_xcode_ref_is_published_in_the_catalog(self):
- for e in json.load(open(CATALOG))["images"]:
- if "xcode" in e["ref"]:
- self.assertFalse(e["published"], e["ref"])
-
- def test_tag_safety_refuses_xcode_tags(self):
+class Published(unittest.TestCase):
+ def test_workflow_still_builds_gates_and_publishes_every_tier(self):
+ wf = open(WORKFLOW).read()
+ self.assertIn("upto=xcode publish=true", wf)
+ self.assertRegex(wf, r"slim\) tag=26-slim ;; full\) tag=26 ;; xcode\) tag=26-xcode")
+
+ def test_ci_needs_no_apple_credentials(self):
+ build = open(os.path.join(MACOS, "build.sh")).read()
+ # The pinned Xcode comes from the runner (an installed Xcode.app or a
+ # cached .xip), never from a download with an Apple ID.
+ self.assertIn("xcode-source.sh", build)
+ self.assertIn("XCODE_BUILD", build)
+ for secret in ("XCODES_USERNAME", "XCODES_PASSWORD", "APPLE_ID", "xcodes download", "xcodes install"):
+ for name in ("build.sh", "files/tier-xcode.sh", "derive-local.sh", "files/xcode-source.sh"):
+ self.assertNotIn(secret, open(os.path.join(MACOS, name)).read(), (secret, name))
+ self.assertNotIn("XCODES_", open(WORKFLOW).read())
+
+ def test_the_tier_says_it_is_apple_software_for_apple_hardware(self):
+ image = json.load(open(os.path.join(MACOS, "image.json")))
+ desc = image["tiers"]["xcode"]["description"]
+ self.assertIn("Apple software", desc)
+ self.assertIn("Apple-branded hardware", desc)
+ annotate = open(os.path.join(MACOS, "annotate.sh")).read()
+ self.assertIn("ai.cua.image.notice", annotate)
+ self.assertIn("Apple-branded hardware", annotate)
+
+ def test_tag_safety_lets_the_xcode_tier_float(self):
tmp = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmp, True)
crane = os.path.join(tmp, "crane")
@@ -138,25 +161,8 @@ class NeverPublished(unittest.TestCase):
f.write("#!/bin/sh\necho 'MANIFEST_UNKNOWN' >&2\nexit 1\n")
os.chmod(crane, 0o755)
guard = os.path.join(ROOT, "scripts", "images", "check-tag-safety.sh")
- env = dict(os.environ, CRANE=crane)
- for tag in ("26-xcode", "26-xcode-26.6", "26-xcode-26.6-20261101-abcdef1"):
- for extra in ([], ["--moving"]):
- r = run([guard, *extra, f"{MACOS_REPO}:{tag}"], env=env)
- self.assertEqual(r.returncode, 1, f"{tag} {extra}: {r.stdout}{r.stderr}")
- self.assertIn("never published", r.stderr)
- ok = run([guard, f"{MACOS_REPO}:26-slim-20261101-abcdef1"], env=env)
- self.assertEqual(ok.returncode, 0, ok.stderr)
-
- def test_release_tier_and_build_refuse_to_push_xcode(self):
- for args in (["push", "--tier", "xcode", "--prefix", "cua-e2e-x", "--stamp", "20261101-abcdef1", "--evidence", "/nonexistent"],
- ["publish", "--tier", "xcode", "--stamp", "20261101-abcdef1", "--evidence", "/nonexistent"],
- ["promote", "--tier", "xcode", "--evidence", "/nonexistent"]):
- r = run([os.path.join(MACOS, "release-tier.sh"), *args])
- self.assertEqual(r.returncode, 2, r.stderr)
- self.assertIn("never", r.stderr)
- r = run([os.path.join(MACOS, "build.sh"), "--tier", "xcode", "--base-vm", "x", "--push", "26-xcode-26.6-20261101-abcdef1"])
- self.assertEqual(r.returncode, 2, r.stderr)
- self.assertIn("never pushed", r.stderr)
+ r = run([guard, f"{MACOS_REPO}:26-xcode-20261101-abcdef1"], env=dict(os.environ, CRANE=crane))
+ self.assertEqual(r.returncode, 0, r.stderr)
@unittest.skipUnless(sys.platform == "darwin", "derive-local.sh reads Xcode bundles (macOS)")
@@ -172,6 +178,11 @@ class DeriveLocal(unittest.TestCase):
"<key>LSMinimumSystemVersion</key><string>26.2</string></dict></plist>")
return os.path.dirname(app)
+ def test_refuses_off_apple_hardware_in_the_script(self):
+ text = open(self.script).read()
+ self.assertIn("Apple-branded hardware", text)
+ self.assertIn('uname -m', text)
+
def test_needs_a_base_vm(self):
r = run([self.script])
self.assertEqual(r.returncode, 2)
@@ -200,5 +211,26 @@ class DeriveLocal(unittest.TestCase):
self.assertIn("developer.apple.com", r.stderr)
+
+class CuaVmmRecipeCopies(unittest.TestCase):
+ """cua-vmm embeds committed copies of the recipe (so the Rust build reads
+ only libs/cua); they must equal libs/images/macos."""
+
+ COPIES = {
+ "derive-local.sh": "macos-derive-local.sh",
+ "versions.env": "macos-versions.env",
+ "files/tier-xcode.sh": "macos-tier-xcode.sh",
+ "files/fetch.sh": "macos-fetch.sh",
+ "files/xcode-source.sh": "macos-xcode-source.sh",
+ }
+
+ def test_the_copies_match_the_recipe(self):
+ recipe = os.path.join(ROOT, "libs", "cua", "crates", "cua-vmm", "recipe")
+ for source, name in self.COPIES.items():
+ with open(os.path.join(MACOS, source), "rb") as a, open(os.path.join(recipe, name), "rb") as b:
+ self.assertEqual(
+ a.read(), b.read(), f"{name} is behind {source}: run scripts/images/sync-cua-vmm-recipe.sh"
+ )
+
if __name__ == "__main__":
unittest.main()
diff --git a/scripts/images/tests/test_macos_dev_image_catalog.py b/scripts/images/tests/test_macos_dev_image_catalog.py
new file mode 100644
index 0000000000..fa6e6bc3fc
--- /dev/null
+++ b/scripts/images/tests/test_macos_dev_image_catalog.py
@@ -0,0 +1,34 @@
+"""The macOS Space with developer tools in the image catalog: named for the
+product, with the published full image as the local-build fallback."""
+
+from __future__ import annotations
+
+import json
+import os
+import unittest
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+CATALOG = os.path.join(HERE, "..", "..", "..", "libs", "images", "sandbox-images.json")
+MACOS_REPO = "ghcr.io/trycua/" + "macos"
+
+
+class Catalog(unittest.TestCase):
+ def test_catalog_entry_is_named_for_the_product(self):
+ with open(CATALOG) as f:
+ catalog = json.load(f)
+ entries = [e for e in catalog["images"] if e["ref"] == MACOS_REPO + ":26-xcode"]
+ self.assertEqual(len(entries), 1)
+ e = entries[0]
+ # published and its digest go together (the release pipeline records both)
+ self.assertEqual(e["published"], "digest" in e)
+ self.assertEqual(e["tier"], "xcode")
+ self.assertIn("developer tools", e["name"])
+ # Built on the user's Mac from the published full image.
+ parent = e["derived_from"]
+ self.assertEqual(parent, MACOS_REPO + ":26")
+ self.assertTrue(any(i["ref"] == parent and i["published"] for i in catalog["images"]))
+ self.assertEqual([i["ref"] for i in catalog["images"] if "derived_from" in i], [e["ref"]])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/e2e/cua-sdk/rust/Cargo.lock b/tests/e2e/cua-sdk/rust/Cargo.lock
index 74c94fc659..76b95753e0 100644
--- a/tests/e2e/cua-sdk/rust/Cargo.lock
+++ b/tests/e2e/cua-sdk/rust/Cargo.lock
@@ -1475,6 +1475,7 @@ dependencies = [
"cua-spacesd-client",
"cua-vmm",
"futures-util",
+ "hmac 0.12.1",
"http",
"http-body-util",
"humantime",
diff --git a/tests/e2e/local-runtimes/Cargo.lock b/tests/e2e/local-runtimes/Cargo.lock
index 4e83015525..5bd5d08885 100644
--- a/tests/e2e/local-runtimes/Cargo.lock
+++ b/tests/e2e/local-runtimes/Cargo.lock
@@ -1251,6 +1251,7 @@ dependencies = [
"cua-spacesd-client",
"cua-vmm",
"futures-util",
+ "hmac 0.12.1",
"http",
"http-body-util",
"humantime",
@@ -1298,6 +1299,7 @@ dependencies = [
"cua-image",
"cua-sandbox-core",
"cua-spaces",
+ "cua-spaces-contract",
"cua-spacesd-client",
"cua-vmm",
"serde_json",
diff --git a/tests/e2e/local-runtimes/Cargo.toml b/tests/e2e/local-runtimes/Cargo.toml
index cf9fe778e6..fdf5181f41 100644
--- a/tests/e2e/local-runtimes/Cargo.toml
+++ b/tests/e2e/local-runtimes/Cargo.toml
@@ -13,6 +13,7 @@ cua-daemon = { path = "../../../libs/cua/crates/cua-daemon", default-features =
cua-sandbox-core = { path = "../../../libs/cua/crates/cua-sandbox-core" }
# builtin_linux.rs creates a Space through the Spaces SDK the apps use.
cua-spaces = { path = "../../../libs/cua/crates/cua-spaces" }
+cua-spaces-contract = { path = "../../../libs/cua/crates/cua-spaces-contract" }
# microvm.rs checks cua-spacesd accepts the Space's token.
cua-spacesd-client = { path = "../../../libs/cua/crates/cua-spacesd-client" }
base64 = "0.22"
diff --git a/tests/e2e/local-runtimes/tests/oci_any.rs b/tests/e2e/local-runtimes/tests/oci_any.rs
index dd843115d9..7c676b53db 100644
--- a/tests/e2e/local-runtimes/tests/oci_any.rs
+++ b/tests/e2e/local-runtimes/tests/oci_any.rs
@@ -90,11 +90,31 @@ async fn http_get(addr: std::net::SocketAddr, path: &str) -> (String, String) {
)
}
-#[tokio::test(flavor = "multi_thread")]
-async fn any_oci_image_is_a_full_space() {
+#[test]
+fn any_oci_image_is_a_full_space() {
if !gated("CUA_E2E_OCI_ANY") {
return;
}
+ // The create path's futures are large in a debug build: run the test on
+ // a thread with a stack sized for them rather than the test thread's.
+ std::thread::Builder::new()
+ .name("oci_any".into())
+ .stack_size(64 << 20)
+ .spawn(|| {
+ tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(4)
+ .thread_stack_size(16 << 20)
+ .enable_all()
+ .build()
+ .expect("tokio runtime")
+ .block_on(Box::pin(any_oci_image_body()))
+ })
+ .expect("spawn the e2e thread")
+ .join()
+ .unwrap_or_else(|p| std::panic::resume_unwind(p));
+}
+
+async fn any_oci_image_body() {
init_tracing();
let home = std::env::var("CUA_HOME").expect("set CUA_HOME to a temporary directory");
assert!(
diff --git a/tests/e2e/local-runtimes/tests/space_jobs.rs b/tests/e2e/local-runtimes/tests/space_jobs.rs
new file mode 100644
index 0000000000..89946a329b
--- /dev/null
+++ b/tests/e2e/local-runtimes/tests/space_jobs.rs
@@ -0,0 +1,334 @@
+//! Background jobs in a real Linux Space (`CUA_E2E_SPACE_JOBS=1`).
+//!
+//! For each image, the test creates a Space through the Spaces SDK the apps
+//! use and:
+//!
+//! 1. runs the runtime-agnostic conformance checks (`space_jobs::conformance`:
+//! exit status, log offsets, follow, cancel, timeout, conditions, list);
+//! 2. starts a two minute job that prints a line every five seconds, then
+//! drops every client connection to the Space: the job keeps running and a
+//! new connection reads its log from the offset the old one reached;
+//! 3. checks the job ended `exited`, exit 0, with every tick in order.
+//!
+//! A second test (`a_job_outlives_a_daemon_restart`) runs cua-spacesd in a
+//! plain container under a restart loop, kills it while a job runs, and checks
+//! the job's log kept growing and its result is intact. It needs the `docker`
+//! command on `PATH` (and `DOCKER_HOST` for the engine to use).
+//!
+//! The daemon side (a finished job waking an agent) is tested against the same
+//! kind of Space in `cua-spaces-ext/tests/e2e_space_job_wake.rs`, because this
+//! crate is MIT and may not depend on the source-available crates.
+//!
+//! | env | meaning |
+//! |---|---|
+//! | `CUA_HOME` | required, a temporary directory (never `~/.cua`); keep it short |
+//! | `CUA_E2E_SPACE_JOBS_IMAGES` | comma separated images (default `alpine:3.20,python:3.12-slim`) |
+//! | `CUA_E2E_OCI_ANY_RUNTIME` | the container engine (default `auto`; `runc` where there is no gVisor) |
+//! | `CUA_SPACESD_STATIC` | the static Linux cua-spacesd to inject |
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use cua_daemon::local::VmmLocal;
+use cua_e2e_local_runtimes::{gated, init_tracing, run_id};
+use cua_sandbox_core::placement::{Kind, On};
+use cua_spaces::space_jobs::{self, conformance};
+use cua_spaces::{Space, SpaceCreate, SpaceCreated, Spaces};
+use cua_spaces_contract::inputs as i;
+
+fn spaces(home: &std::path::Path) -> Spaces {
+ Spaces::builder()
+ .home(home)
+ .download_dir(home.join("downloads"))
+ .operator_display(Arc::new(cua_spaces::operator::NoDisplay))
+ .local_runtime(Arc::new(VmmLocal::default()))
+ .probe_timeout(Duration::from_secs(20))
+ .build()
+}
+
+async fn create(spaces: &Spaces, image: &str, name: &str) -> cua_spaces::SpaceInfo {
+ let created = spaces
+ .create(SpaceCreate {
+ image: Some(image.into()),
+ on: Some(On::Local),
+ kind: Kind::Container,
+ runtime: std::env::var("CUA_E2E_OCI_ANY_RUNTIME")
+ .ok()
+ .map(|r| cua_sandbox_core::placement::Runtime::parse(&r).expect("a runtime"))
+ .unwrap_or_default(),
+ name: Some(name.into()),
+ cpus: Some(1),
+ memory_mb: Some(1024),
+ timeout: Some(Duration::from_secs(600)),
+ ..Default::default()
+ })
+ .await
+ .unwrap_or_else(|e| panic!("create {image}: {e}"));
+ let SpaceCreated::Ready { info, .. } = created else {
+ panic!("{image} is not ready: {created:?}");
+ };
+ info
+}
+
+/// The Space's cua-spacesd pids, by name, as its own shell sees them.
+async fn spacesd_pids(space: &Space) -> Vec<String> {
+ let out = space
+ .bash(
+ "pidof cua-spacesd 2>/dev/null || pgrep -x cua-spacesd",
+ Duration::from_secs(30),
+ )
+ .await
+ .expect("pidof");
+ out.stdout.split_whitespace().map(str::to_string).collect()
+}
+
+/// Answers once the Space's daemon does, for up to `within`.
+async fn space_again(spaces: &Spaces, id: &str, within: Duration) -> Space {
+ let until = Instant::now() + within;
+ loop {
+ if let Ok(space) = spaces.space(id).await
+ && space
+ .bash("true", Duration::from_secs(10))
+ .await
+ .is_ok_and(|o| o.success())
+ {
+ return space;
+ }
+ assert!(
+ Instant::now() < until,
+ "the Space did not answer in {within:?}"
+ );
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ }
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_job_outlives_the_client_and_the_daemon() {
+ if !gated("CUA_E2E_SPACE_JOBS") {
+ return;
+ }
+ init_tracing();
+ let home = std::env::var("CUA_HOME").expect("set CUA_HOME to a temporary directory");
+ assert!(
+ !home.is_empty() && !home.ends_with("/.cua"),
+ "never the real cua home"
+ );
+ let reg = tempfile::tempdir().unwrap();
+ let spaces = spaces(reg.path());
+ let images = std::env::var("CUA_E2E_SPACE_JOBS_IMAGES")
+ .unwrap_or_else(|_| "alpine:3.20,python:3.12-slim".into());
+ for image in images.split(',').map(str::trim).filter(|i| !i.is_empty()) {
+ let name = format!("e2e-jobs-{}-{}", run_id(), image.split(':').next().unwrap());
+ let info = create(&spaces, image, &name).await;
+ eprintln!("{image}: {}", info.id);
+ let space = spaces.space(&info.id).await.unwrap();
+
+ // 1. The conformance checks.
+ let t = Instant::now();
+ conformance::run(&space)
+ .await
+ .unwrap_or_else(|e| panic!("{image}: {e}"));
+ eprintln!(
+ "TIMING {image} conformance: {:.1}s",
+ t.elapsed().as_secs_f64()
+ );
+
+ // 2. A two minute job, then every client goes away.
+ let started = space
+ .job_start(&i::SpaceJob {
+ action: "start".into(),
+ name: Some("two minute job".into()),
+ command: Some(
+ "i=0; while [ $i -lt 24 ]; do echo tick $i; i=$((i+1)); sleep 5; done; echo finished"
+ .into(),
+ ),
+ ..Default::default()
+ })
+ .await
+ .expect("start the long job");
+ let job = started.job.clone();
+ eprintln!("{image}: job {job} started");
+ tokio::time::sleep(Duration::from_secs(12)).await;
+ let seen = space
+ .job_logs(&job, Some(0), 1000, Duration::ZERO)
+ .await
+ .unwrap();
+ assert!(seen.text.contains("tick 0"), "{image}: {seen:?}");
+ let offset = seen.next_offset;
+ drop(space);
+ spaces.forget_connection(&info.id).await.unwrap();
+ tokio::time::sleep(Duration::from_secs(15)).await;
+
+ let space = spaces.space(&info.id).await.unwrap();
+ let after = space
+ .job_logs(&job, Some(offset), 1000, Duration::ZERO)
+ .await
+ .unwrap();
+ assert_eq!(after.status.state, "running", "{image}: {after:?}");
+ assert!(
+ after.text.contains("tick 3") || after.text.contains("tick 2"),
+ "{image}: the job kept printing while no client was connected: {after:?}"
+ );
+
+ // 3. It ends exited 0 with every tick, in order.
+ let end = Instant::now() + Duration::from_secs(180);
+ let done = loop {
+ let st = space.job_status(&job).await.unwrap();
+ if st.finished() {
+ break st;
+ }
+ assert!(Instant::now() < end, "{image}: the job did not end");
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ };
+ assert_eq!(
+ (done.state.as_str(), done.exit_code),
+ ("exited", Some(0)),
+ "{image}: {done:?}"
+ );
+ assert!(
+ done.elapsed_s >= 110,
+ "{image}: ran {}s, expected about 120",
+ done.elapsed_s
+ );
+ let full = space
+ .job_logs(&job, Some(0), 100_000, Duration::ZERO)
+ .await
+ .unwrap();
+ let ticks: Vec<&str> = full.text.lines().collect();
+ let want: Vec<String> = (0..24)
+ .map(|n| format!("tick {n}"))
+ .chain(std::iter::once("finished".to_string()))
+ .collect();
+ assert_eq!(
+ ticks, want,
+ "{image}: the log has every line, once, in order"
+ );
+ eprintln!("{image}: {}", space_jobs::result_line(&done));
+ drop(space);
+ spaces.delete(&info.id).await.unwrap();
+ }
+}
+
+fn docker(args: &[&str]) -> String {
+ let out = std::process::Command::new("docker")
+ .args(args)
+ .output()
+ .expect("the docker command");
+ assert!(
+ out.status.success(),
+ "docker {args:?}: {}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ String::from_utf8_lossy(&out.stdout).trim().to_string()
+}
+
+/// Removes the container however the test ends.
+struct Container(String);
+impl Drop for Container {
+ fn drop(&mut self) {
+ let _ = std::process::Command::new("docker")
+ .args(["rm", "-f", &self.0])
+ .output();
+ }
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_job_outlives_a_daemon_restart() {
+ if !gated("CUA_E2E_SPACE_JOBS") {
+ return;
+ }
+ init_tracing();
+ let bin = std::path::PathBuf::from(
+ std::env::var("CUA_SPACESD_STATIC").expect("set CUA_SPACESD_STATIC"),
+ );
+ let name = format!("cua-e2e-jobs-restart-{}", run_id());
+ let _guard = Container(name.clone());
+ let token = format!("tok-{}", run_id());
+ docker(&[
+ "run",
+ "-d",
+ "--name",
+ &name,
+ "-p",
+ "127.0.0.1::3211",
+ "-e",
+ &format!("CUA_ENV_TOKEN={token}"),
+ "-v",
+ &format!("{}:/cua-spacesd:ro", bin.display()),
+ "alpine:3.20",
+ "sh",
+ "-c",
+ "while true; do /cua-spacesd; sleep 1; done",
+ ]);
+ let addr = docker(&["port", &name, "3211"]);
+ let addr = addr.lines().next().unwrap().to_string();
+
+ let reg = tempfile::tempdir().unwrap();
+ let spaces = spaces(reg.path());
+ let info = spaces
+ .add(
+ &format!("http://{addr}"),
+ Some(token.clone()),
+ Some("restart".into()),
+ )
+ .await
+ .expect("add the Space");
+ let space = space_again(&spaces, &info.id, Duration::from_secs(60)).await;
+
+ let job = space
+ .job_start(&i::SpaceJob {
+ action: "start".into(),
+ name: Some("survives a restart".into()),
+ command: Some(
+ "i=0; while [ $i -lt 12 ]; do echo tick $i; i=$((i+1)); sleep 5; done; echo finished"
+ .into(),
+ ),
+ ..Default::default()
+ })
+ .await
+ .expect("start")
+ .job;
+ tokio::time::sleep(Duration::from_secs(12)).await;
+ let before = spacesd_pids(&space).await;
+ docker(&["exec", &name, "sh", "-c", "kill $(pidof cua-spacesd)"]);
+ drop(space);
+ spaces.forget_connection(&info.id).await.unwrap();
+ let space = space_again(&spaces, &info.id, Duration::from_secs(60)).await;
+ let after = spacesd_pids(&space).await;
+ assert!(
+ !after.is_empty() && after != before,
+ "cua-spacesd did not restart: {before:?} -> {after:?}"
+ );
+ eprintln!("cua-spacesd {before:?} -> {after:?}");
+ let mid = space
+ .job_logs(&job, Some(0), 1000, Duration::ZERO)
+ .await
+ .unwrap();
+ assert_eq!(mid.status.state, "running", "{mid:?}");
+ assert!(mid.text.contains("tick 0"), "{mid:?}");
+
+ let end = Instant::now() + Duration::from_secs(120);
+ let done = loop {
+ let st = space.job_status(&job).await.unwrap();
+ if st.finished() {
+ break st;
+ }
+ assert!(Instant::now() < end, "the job did not end");
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ };
+ assert_eq!(
+ (done.state.as_str(), done.exit_code),
+ ("exited", Some(0)),
+ "{done:?}"
+ );
+ let full = space
+ .job_logs(&job, Some(0), 100_000, Duration::ZERO)
+ .await
+ .unwrap();
+ let want: Vec<String> = (0..12)
+ .map(|n| format!("tick {n}"))
+ .chain(std::iter::once("finished".to_string()))
+ .collect();
+ assert_eq!(full.text.lines().collect::<Vec<_>>(), want);
+ eprintln!("{}", space_jobs::result_line(&done));
+}