Skip to main content

agentos_sidecar_protocol/
wire.rs

1//! Generated Secure Exec sidecar wire protocol surface.
2//!
3//! This module is the public generated protocol entrypoint. The hand-written
4//! `protocol` module remains an internal compatibility layer while callers move
5//! to generated wire frames.
6
7use std::error::Error;
8use std::fmt;
9
10pub use crate::generated_protocol::v1::*;
11
12// The generated BARE types intentionally omit `Copy`/`Default`; restore them on the
13// crate-local generated types so the wider sidecar keeps the ergonomics it relies on
14// after the hand-written protocol types were replaced with these aliases. These live in
15// `wire` (not `protocol`) because `protocol.rs` is `#[path]`-included by integration
16// tests, where the generated types would be foreign and the impls would break the orphan rule.
17impl Copy for crate::generated_protocol::v1::GuestFilesystemOperation {}
18impl Copy for crate::generated_protocol::v1::RootFilesystemMode {}
19impl Copy for crate::generated_protocol::v1::WasmPermissionTier {}
20
21// `derive(Default)` cannot be added: these are foreign generated types, so the
22// `Default` impl must be written by hand here (orphan rule).
23#[allow(clippy::derivable_impls)]
24impl Default for crate::generated_protocol::v1::RootFilesystemEntryKind {
25    fn default() -> Self {
26        Self::File
27    }
28}
29
30impl Default for crate::generated_protocol::v1::RootFilesystemEntry {
31    fn default() -> Self {
32        Self {
33            path: String::new(),
34            kind: crate::generated_protocol::v1::RootFilesystemEntryKind::File,
35            mode: None,
36            uid: None,
37            gid: None,
38            content: None,
39            encoding: None,
40            target: None,
41            executable: false,
42        }
43    }
44}
45
46#[allow(clippy::derivable_impls)]
47impl Default for crate::generated_protocol::v1::RootFilesystemMode {
48    fn default() -> Self {
49        Self::Ephemeral
50    }
51}
52
53#[allow(clippy::derivable_impls)]
54impl Default for crate::generated_protocol::v1::RootFilesystemDescriptor {
55    fn default() -> Self {
56        Self {
57            mode: crate::generated_protocol::v1::RootFilesystemMode::default(),
58            disable_default_base_layer: false,
59            lowers: Vec::new(),
60            bootstrap_entries: Vec::new(),
61        }
62    }
63}
64
65impl crate::generated_protocol::v1::PermissionsPolicy {
66    pub fn deny_all() -> Self {
67        use crate::generated_protocol::v1::{
68            FsPermissionScope, PatternPermissionScope, PermissionMode,
69        };
70        Self {
71            fs: Some(FsPermissionScope::PermissionMode(PermissionMode::Deny)),
72            network: Some(PatternPermissionScope::PermissionMode(PermissionMode::Deny)),
73            child_process: Some(PatternPermissionScope::PermissionMode(PermissionMode::Deny)),
74            process: Some(PatternPermissionScope::PermissionMode(PermissionMode::Deny)),
75            env: Some(PatternPermissionScope::PermissionMode(PermissionMode::Deny)),
76            binding: Some(PatternPermissionScope::PermissionMode(PermissionMode::Deny)),
77        }
78    }
79
80    pub fn allow_all() -> Self {
81        use crate::generated_protocol::v1::{
82            FsPermissionScope, PatternPermissionScope, PermissionMode,
83        };
84        Self {
85            fs: Some(FsPermissionScope::PermissionMode(PermissionMode::Allow)),
86            network: Some(PatternPermissionScope::PermissionMode(
87                PermissionMode::Allow,
88            )),
89            child_process: Some(PatternPermissionScope::PermissionMode(
90                PermissionMode::Allow,
91            )),
92            process: Some(PatternPermissionScope::PermissionMode(
93                PermissionMode::Allow,
94            )),
95            env: Some(PatternPermissionScope::PermissionMode(
96                PermissionMode::Allow,
97            )),
98            binding: Some(PatternPermissionScope::PermissionMode(
99                PermissionMode::Allow,
100            )),
101        }
102    }
103}
104
105impl Default for crate::generated_protocol::v1::PermissionsPolicy {
106    fn default() -> Self {
107        Self::deny_all()
108    }
109}
110
111impl crate::generated_protocol::v1::CreateVmRequest {
112    pub fn json_config(
113        runtime: crate::generated_protocol::v1::GuestRuntimeKind,
114        config: agentos_vm_config::CreateVmConfig,
115    ) -> Self {
116        Self {
117            runtime,
118            config: serde_json::to_string(&config).expect("serialize create VM config"),
119        }
120    }
121
122    pub fn legacy_test_config(
123        runtime: crate::generated_protocol::v1::GuestRuntimeKind,
124        metadata: std::collections::HashMap<String, String>,
125        root_filesystem: crate::generated_protocol::v1::RootFilesystemDescriptor,
126        permissions: Option<crate::generated_protocol::v1::PermissionsPolicy>,
127    ) -> Self {
128        let metadata: std::collections::BTreeMap<_, _> = metadata.into_iter().collect();
129        let mut config = agentos_vm_config::CreateVmConfig {
130            cwd: metadata.get("cwd").cloned(),
131            env: legacy_env_config(&metadata),
132            root_filesystem: legacy_root_filesystem_config(root_filesystem),
133            permissions: permissions.map(permissions_policy_config_from_wire),
134            limits: legacy_limits_config(&metadata),
135            dns: legacy_dns_config(&metadata),
136            native_root: legacy_native_root_config(&metadata),
137            listen: legacy_listen_config(&metadata),
138            ..Default::default()
139        };
140        config.loopback_exempt_ports = legacy_loopback_exempt_ports(&config.env);
141        Self::json_config(runtime, config)
142    }
143}
144
145fn legacy_env_config(
146    metadata: &std::collections::BTreeMap<String, String>,
147) -> std::collections::BTreeMap<String, String> {
148    metadata
149        .iter()
150        .filter_map(|(key, value)| {
151            key.strip_prefix("env.")
152                .map(|name| (name.to_string(), value.clone()))
153        })
154        .collect()
155}
156
157fn legacy_root_filesystem_config(
158    descriptor: crate::generated_protocol::v1::RootFilesystemDescriptor,
159) -> agentos_vm_config::RootFilesystemConfig {
160    agentos_vm_config::RootFilesystemConfig {
161        mode: match descriptor.mode {
162            crate::generated_protocol::v1::RootFilesystemMode::Ephemeral => {
163                agentos_vm_config::RootFilesystemMode::Ephemeral
164            }
165            crate::generated_protocol::v1::RootFilesystemMode::ReadOnly => {
166                agentos_vm_config::RootFilesystemMode::ReadOnly
167            }
168        },
169        disable_default_base_layer: descriptor.disable_default_base_layer,
170        lowers: descriptor
171            .lowers
172            .into_iter()
173            .map(legacy_root_lower_config)
174            .collect(),
175        bootstrap_entries: descriptor
176            .bootstrap_entries
177            .into_iter()
178            .map(legacy_root_entry_config)
179            .collect(),
180    }
181}
182
183fn legacy_root_lower_config(
184    lower: crate::generated_protocol::v1::RootFilesystemLowerDescriptor,
185) -> agentos_vm_config::RootFilesystemLowerDescriptor {
186    match lower {
187        crate::generated_protocol::v1::RootFilesystemLowerDescriptor::SnapshotRootFilesystemLower(
188            snapshot,
189        ) => agentos_vm_config::RootFilesystemLowerDescriptor::Snapshot {
190            entries: snapshot
191                .entries
192                .into_iter()
193                .map(legacy_root_entry_config)
194                .collect(),
195        },
196        crate::generated_protocol::v1::RootFilesystemLowerDescriptor::BundledBaseFilesystemLower => {
197            agentos_vm_config::RootFilesystemLowerDescriptor::BundledBaseFilesystem
198        }
199    }
200}
201
202fn legacy_root_entry_config(
203    entry: crate::generated_protocol::v1::RootFilesystemEntry,
204) -> agentos_vm_config::RootFilesystemEntry {
205    agentos_vm_config::RootFilesystemEntry {
206        path: entry.path,
207        kind: match entry.kind {
208            crate::generated_protocol::v1::RootFilesystemEntryKind::File => {
209                agentos_vm_config::RootFilesystemEntryKind::File
210            }
211            crate::generated_protocol::v1::RootFilesystemEntryKind::Directory => {
212                agentos_vm_config::RootFilesystemEntryKind::Directory
213            }
214            crate::generated_protocol::v1::RootFilesystemEntryKind::Symlink => {
215                agentos_vm_config::RootFilesystemEntryKind::Symlink
216            }
217        },
218        mode: entry.mode,
219        uid: entry.uid,
220        gid: entry.gid,
221        content: entry.content,
222        encoding: entry.encoding.map(|encoding| match encoding {
223            crate::generated_protocol::v1::RootFilesystemEntryEncoding::Utf8 => {
224                agentos_vm_config::RootFilesystemEntryEncoding::Utf8
225            }
226            crate::generated_protocol::v1::RootFilesystemEntryEncoding::Base64 => {
227                agentos_vm_config::RootFilesystemEntryEncoding::Base64
228            }
229        }),
230        target: entry.target,
231        executable: entry.executable,
232    }
233}
234
235pub fn permissions_policy_config_from_wire(
236    permissions: crate::generated_protocol::v1::PermissionsPolicy,
237) -> agentos_vm_config::PermissionsPolicy {
238    agentos_vm_config::PermissionsPolicy {
239        fs: permissions.fs.map(legacy_fs_permission_scope_config),
240        network: permissions
241            .network
242            .map(legacy_pattern_permission_scope_config),
243        child_process: permissions
244            .child_process
245            .map(legacy_pattern_permission_scope_config),
246        process: permissions
247            .process
248            .map(legacy_pattern_permission_scope_config),
249        env: permissions.env.map(legacy_pattern_permission_scope_config),
250        binding: permissions
251            .binding
252            .map(legacy_pattern_permission_scope_config),
253    }
254}
255
256fn legacy_permission_mode_config(
257    mode: crate::generated_protocol::v1::PermissionMode,
258) -> agentos_vm_config::PermissionMode {
259    match mode {
260        crate::generated_protocol::v1::PermissionMode::Allow => {
261            agentos_vm_config::PermissionMode::Allow
262        }
263        crate::generated_protocol::v1::PermissionMode::Ask => {
264            agentos_vm_config::PermissionMode::Ask
265        }
266        crate::generated_protocol::v1::PermissionMode::Deny => {
267            agentos_vm_config::PermissionMode::Deny
268        }
269    }
270}
271
272fn legacy_fs_permission_scope_config(
273    scope: crate::generated_protocol::v1::FsPermissionScope,
274) -> agentos_vm_config::FsPermissionScope {
275    match scope {
276        crate::generated_protocol::v1::FsPermissionScope::PermissionMode(mode) => {
277            agentos_vm_config::FsPermissionScope::Mode(legacy_permission_mode_config(mode))
278        }
279        crate::generated_protocol::v1::FsPermissionScope::FsPermissionRuleSet(rules) => {
280            agentos_vm_config::FsPermissionScope::Rules(agentos_vm_config::FsPermissionRuleSet {
281                default: rules.default.map(legacy_permission_mode_config),
282                rules: rules
283                    .rules
284                    .into_iter()
285                    .map(|rule| agentos_vm_config::FsPermissionRule {
286                        mode: legacy_permission_mode_config(rule.mode),
287                        operations: rule.operations,
288                        paths: rule.paths,
289                    })
290                    .collect(),
291            })
292        }
293    }
294}
295
296fn legacy_pattern_permission_scope_config(
297    scope: crate::generated_protocol::v1::PatternPermissionScope,
298) -> agentos_vm_config::PatternPermissionScope {
299    match scope {
300        crate::generated_protocol::v1::PatternPermissionScope::PermissionMode(mode) => {
301            agentos_vm_config::PatternPermissionScope::Mode(legacy_permission_mode_config(mode))
302        }
303        crate::generated_protocol::v1::PatternPermissionScope::PatternPermissionRuleSet(rules) => {
304            agentos_vm_config::PatternPermissionScope::Rules(
305                agentos_vm_config::PatternPermissionRuleSet {
306                    default: rules.default.map(legacy_permission_mode_config),
307                    rules: rules
308                        .rules
309                        .into_iter()
310                        .map(|rule| agentos_vm_config::PatternPermissionRule {
311                            mode: legacy_permission_mode_config(rule.mode),
312                            operations: rule.operations,
313                            patterns: rule.patterns,
314                        })
315                        .collect(),
316                },
317            )
318        }
319    }
320}
321
322fn legacy_dns_config(
323    metadata: &std::collections::BTreeMap<String, String>,
324) -> Option<agentos_vm_config::VmDnsConfig> {
325    let mut dns = agentos_vm_config::VmDnsConfig::default();
326    if let Some(value) = metadata.get("network.dns.servers") {
327        dns.name_servers = value
328            .split(',')
329            .map(str::trim)
330            .filter(|entry| !entry.is_empty())
331            .map(str::to_string)
332            .collect();
333    }
334    for (key, value) in metadata {
335        let Some(hostname) = key.strip_prefix("network.dns.override.") else {
336            continue;
337        };
338        dns.overrides.insert(
339            hostname.to_string(),
340            value
341                .split(',')
342                .map(str::trim)
343                .filter(|entry| !entry.is_empty())
344                .map(str::to_string)
345                .collect(),
346        );
347    }
348    if dns.name_servers.is_empty() && dns.overrides.is_empty() {
349        None
350    } else {
351        Some(dns)
352    }
353}
354
355fn legacy_native_root_config(
356    metadata: &std::collections::BTreeMap<String, String>,
357) -> Option<agentos_vm_config::NativeRootFilesystemConfig> {
358    let id = metadata.get("rootFilesystem.nativePlugin.id")?;
359    let config = metadata
360        .get("rootFilesystem.nativePlugin.config")
361        .map(|value| serde_json::from_str(value).expect("parse native root plugin config"))
362        .unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));
363    let read_only = metadata
364        .get("rootFilesystem.nativePlugin.readOnly")
365        .map(|value| value.parse::<bool>().expect("parse native root readOnly"))
366        .unwrap_or(false);
367    Some(agentos_vm_config::NativeRootFilesystemConfig {
368        plugin: agentos_vm_config::MountPluginDescriptor {
369            id: id.clone(),
370            config,
371        },
372        read_only,
373    })
374}
375
376fn legacy_listen_config(
377    metadata: &std::collections::BTreeMap<String, String>,
378) -> Option<agentos_vm_config::VmListenPolicyConfig> {
379    let listen = agentos_vm_config::VmListenPolicyConfig {
380        port_min: metadata
381            .get("network.listen.port_min")
382            .map(|value| value.parse::<u16>().expect("parse network.listen.port_min")),
383        port_max: metadata
384            .get("network.listen.port_max")
385            .map(|value| value.parse::<u16>().expect("parse network.listen.port_max")),
386        allow_privileged: metadata
387            .get("network.listen.allow_privileged")
388            .map(|value| {
389                value
390                    .parse::<bool>()
391                    .expect("parse network.listen.allow_privileged")
392            }),
393    };
394    if listen.port_min.is_none() && listen.port_max.is_none() && listen.allow_privileged.is_none() {
395        None
396    } else {
397        Some(listen)
398    }
399}
400
401fn legacy_loopback_exempt_ports(env: &std::collections::BTreeMap<String, String>) -> Vec<u16> {
402    let Some(value) = env.get("AGENTOS_LOOPBACK_EXEMPT_PORTS") else {
403        return Vec::new();
404    };
405    serde_json::from_str::<Vec<serde_json::Value>>(value)
406        .unwrap_or_default()
407        .into_iter()
408        .filter_map(|value| match value {
409            serde_json::Value::Number(number) => number.as_u64(),
410            serde_json::Value::String(value) => value.parse::<u64>().ok(),
411            _ => None,
412        })
413        .filter_map(|port| u16::try_from(port).ok())
414        .collect()
415}
416
417fn legacy_limits_config(
418    metadata: &std::collections::BTreeMap<String, String>,
419) -> Option<agentos_vm_config::VmLimitsConfig> {
420    let resources = agentos_vm_config::ResourceLimitsConfig {
421        cpu_count: legacy_u64(metadata, "resource.cpu_count"),
422        max_processes: legacy_u64(metadata, "resource.max_processes"),
423        max_open_fds: legacy_u64(metadata, "resource.max_open_fds"),
424        max_pipes: legacy_u64(metadata, "resource.max_pipes"),
425        max_ptys: legacy_u64(metadata, "resource.max_ptys"),
426        max_sockets: legacy_u64(metadata, "resource.max_sockets"),
427        max_connections: legacy_u64(metadata, "resource.max_connections"),
428        max_socket_buffered_bytes: legacy_u64(metadata, "resource.max_socket_buffered_bytes"),
429        max_socket_datagram_queue_len: legacy_u64(
430            metadata,
431            "resource.max_socket_datagram_queue_len",
432        ),
433        max_filesystem_bytes: legacy_u64(metadata, "resource.max_filesystem_bytes"),
434        max_inode_count: legacy_u64(metadata, "resource.max_inode_count"),
435        max_blocking_read_ms: legacy_u64(metadata, "resource.max_blocking_read_ms"),
436        max_pread_bytes: legacy_u64(metadata, "resource.max_pread_bytes"),
437        max_fd_write_bytes: legacy_u64(metadata, "resource.max_fd_write_bytes"),
438        max_process_argv_bytes: legacy_u64(metadata, "resource.max_process_argv_bytes"),
439        max_process_env_bytes: legacy_u64(metadata, "resource.max_process_env_bytes"),
440        max_readdir_entries: legacy_u64(metadata, "resource.max_readdir_entries"),
441        max_recursive_fs_depth: legacy_u64(metadata, "resource.max_recursive_fs_depth"),
442        max_recursive_fs_entries: legacy_u64(metadata, "resource.max_recursive_fs_entries"),
443        max_wasm_fuel: legacy_u64(metadata, "resource.max_wasm_fuel"),
444        max_wasm_memory_bytes: legacy_u64(metadata, "resource.max_wasm_memory_bytes"),
445        max_wasm_stack_bytes: legacy_u64(metadata, "resource.max_wasm_stack_bytes"),
446    };
447    let http = agentos_vm_config::HttpLimitsConfig {
448        max_fetch_response_bytes: legacy_u64(metadata, "limits.http.max_fetch_response_bytes"),
449    };
450    let tools = agentos_vm_config::ToolLimitsConfig {
451        default_tool_timeout_ms: legacy_u64(metadata, "limits.tools.default_tool_timeout_ms"),
452        max_tool_timeout_ms: legacy_u64(metadata, "limits.tools.max_tool_timeout_ms"),
453        max_registered_toolkits: legacy_u64(metadata, "limits.tools.max_registered_toolkits"),
454        max_registered_tools_per_vm: legacy_u64(
455            metadata,
456            "limits.tools.max_registered_tools_per_vm",
457        ),
458        max_tools_per_toolkit: legacy_u64(metadata, "limits.tools.max_tools_per_toolkit"),
459        max_tool_schema_bytes: legacy_u64(metadata, "limits.tools.max_tool_schema_bytes"),
460        max_tool_examples_per_tool: legacy_u64(metadata, "limits.tools.max_tool_examples_per_tool"),
461        max_tool_example_input_bytes: legacy_u64(
462            metadata,
463            "limits.tools.max_tool_example_input_bytes",
464        ),
465    };
466    let plugins = agentos_vm_config::PluginLimitsConfig {
467        max_persisted_manifest_bytes: legacy_u64(
468            metadata,
469            "limits.plugins.max_persisted_manifest_bytes",
470        ),
471        max_persisted_manifest_file_bytes: legacy_u64(
472            metadata,
473            "limits.plugins.max_persisted_manifest_file_bytes",
474        ),
475    };
476    let acp = agentos_vm_config::AcpLimitsConfig {
477        max_read_line_bytes: legacy_u64(metadata, "limits.acp.max_read_line_bytes"),
478        stdout_buffer_byte_limit: legacy_u64(metadata, "limits.acp.stdout_buffer_byte_limit"),
479    };
480    let js_runtime = agentos_vm_config::JsRuntimeLimitsConfig {
481        v8_heap_limit_mb: legacy_u64(metadata, "limits.js_runtime.v8_heap_limit_mb"),
482        sync_rpc_wait_timeout_ms: legacy_u64(
483            metadata,
484            "limits.js_runtime.sync_rpc_wait_timeout_ms",
485        ),
486        cpu_time_limit_ms: legacy_u64(metadata, "limits.js_runtime.cpu_time_limit_ms"),
487        wall_clock_limit_ms: legacy_u64(metadata, "limits.js_runtime.wall_clock_limit_ms"),
488        import_cache_materialize_timeout_ms: legacy_u64(
489            metadata,
490            "limits.js_runtime.import_cache_materialize_timeout_ms",
491        ),
492        captured_output_limit_bytes: legacy_u64(
493            metadata,
494            "limits.js_runtime.captured_output_limit_bytes",
495        ),
496        stdin_buffer_limit_bytes: legacy_u64(
497            metadata,
498            "limits.js_runtime.stdin_buffer_limit_bytes",
499        ),
500        event_payload_limit_bytes: legacy_u64(
501            metadata,
502            "limits.js_runtime.event_payload_limit_bytes",
503        ),
504        v8_ipc_max_frame_bytes: legacy_u64(metadata, "limits.js_runtime.v8_ipc_max_frame_bytes"),
505    };
506    let python = agentos_vm_config::PythonLimitsConfig {
507        output_buffer_max_bytes: legacy_u64(metadata, "limits.python.output_buffer_max_bytes"),
508        execution_timeout_ms: legacy_u64(metadata, "limits.python.execution_timeout_ms"),
509        max_old_space_mb: legacy_u64(metadata, "limits.python.max_old_space_mb"),
510        vfs_rpc_timeout_ms: legacy_u64(metadata, "limits.python.vfs_rpc_timeout_ms"),
511    };
512    let wasm = agentos_vm_config::WasmLimitsConfig {
513        max_module_file_bytes: legacy_u64(metadata, "limits.wasm.max_module_file_bytes"),
514        captured_output_limit_bytes: legacy_u64(
515            metadata,
516            "limits.wasm.captured_output_limit_bytes",
517        ),
518        sync_read_limit_bytes: legacy_u64(metadata, "limits.wasm.sync_read_limit_bytes"),
519        prewarm_timeout_ms: legacy_u64(metadata, "limits.wasm.prewarm_timeout_ms"),
520        runner_heap_limit_mb: legacy_u64(metadata, "limits.wasm.runner_heap_limit_mb"),
521    };
522
523    let config = agentos_vm_config::VmLimitsConfig {
524        resources: legacy_has_resource_limits(&resources).then_some(resources),
525        http: http.max_fetch_response_bytes.is_some().then_some(http),
526        tools: legacy_has_tool_limits(&tools).then_some(tools),
527        plugins: legacy_has_plugin_limits(&plugins).then_some(plugins),
528        acp: legacy_has_acp_limits(&acp).then_some(acp),
529        js_runtime: legacy_has_js_runtime_limits(&js_runtime).then_some(js_runtime),
530        python: legacy_has_python_limits(&python).then_some(python),
531        wasm: legacy_has_wasm_limits(&wasm).then_some(wasm),
532    };
533
534    if config.resources.is_none()
535        && config.http.is_none()
536        && config.tools.is_none()
537        && config.plugins.is_none()
538        && config.acp.is_none()
539        && config.js_runtime.is_none()
540        && config.python.is_none()
541        && config.wasm.is_none()
542    {
543        None
544    } else {
545        Some(config)
546    }
547}
548
549fn legacy_u64(metadata: &std::collections::BTreeMap<String, String>, key: &str) -> Option<u64> {
550    metadata.get(key).map(|value| {
551        value
552            .parse::<u64>()
553            .unwrap_or_else(|error| panic!("parse {key}: {error}"))
554    })
555}
556
557fn legacy_has_resource_limits(config: &agentos_vm_config::ResourceLimitsConfig) -> bool {
558    config.cpu_count.is_some()
559        || config.max_processes.is_some()
560        || config.max_open_fds.is_some()
561        || config.max_pipes.is_some()
562        || config.max_ptys.is_some()
563        || config.max_sockets.is_some()
564        || config.max_connections.is_some()
565        || config.max_socket_buffered_bytes.is_some()
566        || config.max_socket_datagram_queue_len.is_some()
567        || config.max_filesystem_bytes.is_some()
568        || config.max_inode_count.is_some()
569        || config.max_blocking_read_ms.is_some()
570        || config.max_pread_bytes.is_some()
571        || config.max_fd_write_bytes.is_some()
572        || config.max_process_argv_bytes.is_some()
573        || config.max_process_env_bytes.is_some()
574        || config.max_readdir_entries.is_some()
575        || config.max_wasm_fuel.is_some()
576        || config.max_wasm_memory_bytes.is_some()
577        || config.max_wasm_stack_bytes.is_some()
578}
579
580fn legacy_has_tool_limits(config: &agentos_vm_config::ToolLimitsConfig) -> bool {
581    config.default_tool_timeout_ms.is_some()
582        || config.max_tool_timeout_ms.is_some()
583        || config.max_registered_toolkits.is_some()
584        || config.max_registered_tools_per_vm.is_some()
585        || config.max_tools_per_toolkit.is_some()
586        || config.max_tool_schema_bytes.is_some()
587        || config.max_tool_examples_per_tool.is_some()
588        || config.max_tool_example_input_bytes.is_some()
589}
590
591fn legacy_has_plugin_limits(config: &agentos_vm_config::PluginLimitsConfig) -> bool {
592    config.max_persisted_manifest_bytes.is_some()
593        || config.max_persisted_manifest_file_bytes.is_some()
594}
595
596fn legacy_has_acp_limits(config: &agentos_vm_config::AcpLimitsConfig) -> bool {
597    config.max_read_line_bytes.is_some() || config.stdout_buffer_byte_limit.is_some()
598}
599
600fn legacy_has_js_runtime_limits(config: &agentos_vm_config::JsRuntimeLimitsConfig) -> bool {
601    config.v8_heap_limit_mb.is_some()
602        || config.sync_rpc_wait_timeout_ms.is_some()
603        || config.cpu_time_limit_ms.is_some()
604        || config.wall_clock_limit_ms.is_some()
605        || config.import_cache_materialize_timeout_ms.is_some()
606        || config.captured_output_limit_bytes.is_some()
607        || config.stdin_buffer_limit_bytes.is_some()
608        || config.event_payload_limit_bytes.is_some()
609        || config.v8_ipc_max_frame_bytes.is_some()
610}
611
612fn legacy_has_python_limits(config: &agentos_vm_config::PythonLimitsConfig) -> bool {
613    config.output_buffer_max_bytes.is_some()
614        || config.execution_timeout_ms.is_some()
615        || config.max_old_space_mb.is_some()
616        || config.vfs_rpc_timeout_ms.is_some()
617}
618
619fn legacy_has_wasm_limits(config: &agentos_vm_config::WasmLimitsConfig) -> bool {
620    config.max_module_file_bytes.is_some()
621        || config.captured_output_limit_bytes.is_some()
622        || config.sync_read_limit_bytes.is_some()
623        || config.prewarm_timeout_ms.is_some()
624        || config.runner_heap_limit_mb.is_some()
625}
626
627// Ownership-scope constructor ergonomics. The generated BARE union exposes only the
628// tuple-wrapped variants (`ConnectionOwnership`/`SessionOwnership`/`VmOwnership`); restore
629// the hand-written `connection`/`session`/`vm` helpers the sidecar relies on. These live in
630// `wire` (not `protocol`) for the same orphan-rule reason as the impls above: `protocol.rs`
631// is `#[path]`-included by integration tests where the generated type is foreign.
632impl crate::generated_protocol::v1::OwnershipScope {
633    pub fn connection(connection_id: impl Into<String>) -> Self {
634        Self::ConnectionOwnership(crate::generated_protocol::v1::ConnectionOwnership {
635            connection_id: connection_id.into(),
636        })
637    }
638
639    pub fn session(connection_id: impl Into<String>, session_id: impl Into<String>) -> Self {
640        Self::SessionOwnership(crate::generated_protocol::v1::SessionOwnership {
641            connection_id: connection_id.into(),
642            session_id: session_id.into(),
643        })
644    }
645
646    pub fn vm(
647        connection_id: impl Into<String>,
648        session_id: impl Into<String>,
649        vm_id: impl Into<String>,
650    ) -> Self {
651        Self::VmOwnership(crate::generated_protocol::v1::VmOwnership {
652            connection_id: connection_id.into(),
653            session_id: session_id.into(),
654            vm_id: vm_id.into(),
655        })
656    }
657}
658
659pub const PROTOCOL_NAME: &str = "agentos-native-sidecar";
660pub const PROTOCOL_VERSION: u16 = 7;
661// 16 MiB: large enough to carry a trusted-client CreateVm config that inlines an
662// entire base-filesystem snapshot, while still bounding a single frame.
663pub const DEFAULT_MAX_FRAME_BYTES: usize = 16 * 1024 * 1024;
664
665#[derive(Debug, Clone, PartialEq, Eq)]
666pub enum ProtocolCodecError {
667    TruncatedFrame {
668        actual: usize,
669    },
670    LengthPrefixMismatch {
671        declared: usize,
672        actual: usize,
673    },
674    FrameTooLarge {
675        size: usize,
676        max: usize,
677    },
678    UnsupportedSchema {
679        name: String,
680        version: u16,
681    },
682    InvalidRequestId,
683    InvalidRequestDirection {
684        request_id: RequestId,
685        expected: RequestDirection,
686    },
687    EmptyOwnershipField {
688        field: &'static str,
689    },
690    EmptyAuthToken,
691    InvalidOwnershipScope {
692        required: OwnershipRequirement,
693        actual: OwnershipRequirement,
694    },
695    SerializeFailure(String),
696    DeserializeFailure(String),
697}
698
699impl fmt::Display for ProtocolCodecError {
700    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
701        match self {
702            Self::TruncatedFrame { actual } => {
703                write!(
704                    f,
705                    "protocol frame is truncated: only {actual} bytes provided"
706                )
707            }
708            Self::LengthPrefixMismatch { declared, actual } => write!(
709                f,
710                "protocol frame length prefix mismatch: declared {declared} bytes, got {actual}",
711            ),
712            Self::FrameTooLarge { size, max } => {
713                write!(f, "protocol frame is {size} bytes, limit is {max}")
714            }
715            Self::UnsupportedSchema { name, version } => write!(
716                f,
717                "unsupported protocol schema {name}@{version}; expected {PROTOCOL_NAME}@{PROTOCOL_VERSION}",
718            ),
719            Self::InvalidRequestId => write!(f, "protocol request identifiers must be non-zero"),
720            Self::InvalidRequestDirection {
721                request_id,
722                expected,
723            } => write!(f, "protocol request id {request_id} must be {expected}",),
724            Self::EmptyOwnershipField { field } => {
725                write!(f, "protocol ownership field `{field}` cannot be empty")
726            }
727            Self::EmptyAuthToken => {
728                write!(f, "authenticate requests require a non-empty auth token")
729            }
730            Self::InvalidOwnershipScope { required, actual } => write!(
731                f,
732                "protocol frame requires {required} ownership but carried {actual}",
733            ),
734            Self::SerializeFailure(message) => {
735                write!(f, "protocol frame serialization failed: {message}")
736            }
737            Self::DeserializeFailure(message) => {
738                write!(f, "protocol frame deserialization failed: {message}")
739            }
740        }
741    }
742}
743
744impl Error for ProtocolCodecError {}
745
746#[derive(Debug, Clone, Copy, PartialEq, Eq)]
747pub enum OwnershipRequirement {
748    Any,
749    Connection,
750    Session,
751    Vm,
752    SessionOrVm,
753}
754
755impl fmt::Display for OwnershipRequirement {
756    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
757        match self {
758            Self::Any => write!(f, "any"),
759            Self::Connection => write!(f, "connection"),
760            Self::Session => write!(f, "session"),
761            Self::Vm => write!(f, "vm"),
762            Self::SessionOrVm => write!(f, "session-or-vm"),
763        }
764    }
765}
766
767#[derive(Debug, Clone, Copy, PartialEq, Eq)]
768pub enum RequestDirection {
769    Host,
770    Sidecar,
771}
772
773impl fmt::Display for RequestDirection {
774    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
775        match self {
776            Self::Host => write!(f, "positive"),
777            Self::Sidecar => write!(f, "negative"),
778        }
779    }
780}
781
782#[derive(Debug, Clone, PartialEq, Eq)]
783pub struct WireDispatchResult {
784    pub response: ResponseFrame,
785    pub events: Vec<EventFrame>,
786}
787
788#[derive(Debug, Clone, PartialEq, Eq)]
789pub struct CompatDispatchResult {
790    pub response: crate::protocol::ResponseFrame,
791    pub events: Vec<crate::protocol::EventFrame>,
792}
793
794#[derive(Debug, Clone)]
795pub struct WireFrameCodec {
796    max_frame_bytes: usize,
797}
798
799impl WireFrameCodec {
800    pub fn new(max_frame_bytes: usize) -> Self {
801        Self { max_frame_bytes }
802    }
803
804    pub fn max_frame_bytes(&self) -> usize {
805        self.max_frame_bytes
806    }
807
808    pub fn encode(&self, frame: &ProtocolFrame) -> Result<Vec<u8>, ProtocolCodecError> {
809        validate_frame(frame)?;
810
811        let payload = serde_bare::to_vec(frame)
812            .map_err(|error| ProtocolCodecError::SerializeFailure(error.to_string()))?;
813        if payload.len() > self.max_frame_bytes {
814            return Err(ProtocolCodecError::FrameTooLarge {
815                size: payload.len(),
816                max: self.max_frame_bytes,
817            });
818        }
819
820        let length =
821            u32::try_from(payload.len()).map_err(|_| ProtocolCodecError::FrameTooLarge {
822                size: payload.len(),
823                max: u32::MAX as usize,
824            })?;
825
826        let mut encoded = Vec::with_capacity(4 + payload.len());
827        encoded.extend_from_slice(&length.to_be_bytes());
828        encoded.extend_from_slice(&payload);
829        Ok(encoded)
830    }
831
832    pub fn decode(&self, bytes: &[u8]) -> Result<ProtocolFrame, ProtocolCodecError> {
833        let payload = self.checked_payload(bytes)?;
834        let frame = serde_bare::from_slice(payload)
835            .map_err(|error| ProtocolCodecError::DeserializeFailure(error.to_string()))?;
836        validate_frame(&frame)?;
837        Ok(frame)
838    }
839
840    /// Encode a frame as a bare message WITHOUT the 4-byte length prefix.
841    ///
842    /// Stream transports (stdio) use [`encode`] so frames can be delimited in a
843    /// byte stream. Message transports where the boundary is the call itself
844    /// (the browser `pushFrame` / `postMessage` path) use this so the on-wire
845    /// bytes match the TypeScript `encodeProtocolFramePayload(frame, "bare")`,
846    /// which emits the raw bare frame with no prefix.
847    pub fn encode_message(&self, frame: &ProtocolFrame) -> Result<Vec<u8>, ProtocolCodecError> {
848        validate_frame(frame)?;
849        let payload = serde_bare::to_vec(frame)
850            .map_err(|error| ProtocolCodecError::SerializeFailure(error.to_string()))?;
851        if payload.len() > self.max_frame_bytes {
852            return Err(ProtocolCodecError::FrameTooLarge {
853                size: payload.len(),
854                max: self.max_frame_bytes,
855            });
856        }
857        Ok(payload)
858    }
859
860    /// Decode a bare message produced by [`encode_message`] (no length prefix).
861    pub fn decode_message(&self, bytes: &[u8]) -> Result<ProtocolFrame, ProtocolCodecError> {
862        if bytes.len() > self.max_frame_bytes {
863            return Err(ProtocolCodecError::FrameTooLarge {
864                size: bytes.len(),
865                max: self.max_frame_bytes,
866            });
867        }
868        let frame = serde_bare::from_slice(bytes)
869            .map_err(|error| ProtocolCodecError::DeserializeFailure(error.to_string()))?;
870        validate_frame(&frame)?;
871        Ok(frame)
872    }
873
874    fn checked_payload<'a>(&self, bytes: &'a [u8]) -> Result<&'a [u8], ProtocolCodecError> {
875        if bytes.len() < 4 {
876            return Err(ProtocolCodecError::TruncatedFrame {
877                actual: bytes.len(),
878            });
879        }
880
881        let declared =
882            u32::from_be_bytes(bytes[..4].try_into().expect("length prefix is four bytes"))
883                as usize;
884        if declared > self.max_frame_bytes {
885            return Err(ProtocolCodecError::FrameTooLarge {
886                size: declared,
887                max: self.max_frame_bytes,
888            });
889        }
890
891        let actual = bytes.len() - 4;
892        if declared != actual {
893            return Err(ProtocolCodecError::LengthPrefixMismatch { declared, actual });
894        }
895
896        Ok(&bytes[4..])
897    }
898}
899
900impl Default for WireFrameCodec {
901    fn default() -> Self {
902        Self::new(DEFAULT_MAX_FRAME_BYTES)
903    }
904}
905
906pub fn protocol_schema() -> ProtocolSchema {
907    ProtocolSchema::current()
908}
909
910impl ProtocolSchema {
911    pub fn current() -> Self {
912        Self {
913            name: PROTOCOL_NAME.to_string(),
914            version: PROTOCOL_VERSION,
915        }
916    }
917}
918
919impl Default for ProtocolSchema {
920    fn default() -> Self {
921        Self::current()
922    }
923}
924
925pub fn request_frame_to_compat(
926    request: RequestFrame,
927) -> Result<crate::protocol::RequestFrame, ProtocolCodecError> {
928    match crate::protocol::from_generated_protocol_frame(ProtocolFrame::RequestFrame(request))? {
929        crate::protocol::ProtocolFrame::Request(request) => Ok(request),
930        crate::protocol::ProtocolFrame::Response(_)
931        | crate::protocol::ProtocolFrame::Event(_)
932        | crate::protocol::ProtocolFrame::SidecarRequest(_)
933        | crate::protocol::ProtocolFrame::SidecarResponse(_) => {
934            Err(ProtocolCodecError::DeserializeFailure(String::from(
935                "wire request frame converted to non-request compatibility frame",
936            )))
937        }
938    }
939}
940
941pub fn ownership_scope_to_compat(ownership: OwnershipScope) -> crate::protocol::OwnershipScope {
942    crate::protocol::from_generated_ownership_scope(ownership)
943}
944
945pub fn request_payload_to_compat(
946    ownership: &crate::protocol::OwnershipScope,
947    payload: RequestPayload,
948) -> Result<crate::protocol::RequestPayload, ProtocolCodecError> {
949    match crate::protocol::from_generated_protocol_frame(ProtocolFrame::RequestFrame(
950        RequestFrame {
951            schema: protocol_schema(),
952            request_id: 1,
953            ownership: crate::protocol::to_generated_ownership_scope(ownership),
954            payload,
955        },
956    ))? {
957        crate::protocol::ProtocolFrame::Request(request) => Ok(request.payload),
958        crate::protocol::ProtocolFrame::Response(_)
959        | crate::protocol::ProtocolFrame::Event(_)
960        | crate::protocol::ProtocolFrame::SidecarRequest(_)
961        | crate::protocol::ProtocolFrame::SidecarResponse(_) => {
962            Err(ProtocolCodecError::DeserializeFailure(String::from(
963                "wire request payload converted to non-request compatibility frame",
964            )))
965        }
966    }
967}
968
969pub fn response_payload_from_compat(
970    ownership: &crate::protocol::OwnershipScope,
971    payload: crate::protocol::ResponsePayload,
972) -> Result<ResponsePayload, ProtocolCodecError> {
973    match crate::protocol::to_generated_protocol_frame(&crate::protocol::ProtocolFrame::Response(
974        crate::protocol::ResponseFrame::new(1, ownership.clone(), payload),
975    ))? {
976        ProtocolFrame::ResponseFrame(response) => Ok(response.payload),
977        ProtocolFrame::RequestFrame(_)
978        | ProtocolFrame::EventFrame(_)
979        | ProtocolFrame::SidecarRequestFrame(_)
980        | ProtocolFrame::SidecarResponseFrame(_) => Err(ProtocolCodecError::SerializeFailure(
981            String::from("compatibility response payload converted to non-response wire frame"),
982        )),
983    }
984}
985
986pub fn event_frame_from_compat(
987    event: crate::protocol::EventFrame,
988) -> Result<EventFrame, ProtocolCodecError> {
989    match crate::protocol::to_generated_protocol_frame(&crate::protocol::ProtocolFrame::Event(
990        event,
991    ))? {
992        ProtocolFrame::EventFrame(event) => Ok(event),
993        ProtocolFrame::RequestFrame(_)
994        | ProtocolFrame::ResponseFrame(_)
995        | ProtocolFrame::SidecarRequestFrame(_)
996        | ProtocolFrame::SidecarResponseFrame(_) => Err(ProtocolCodecError::SerializeFailure(
997            String::from("compatibility event converted to non-event wire frame"),
998        )),
999    }
1000}
1001
1002pub fn event_frame_to_compat(
1003    event: EventFrame,
1004) -> Result<crate::protocol::EventFrame, ProtocolCodecError> {
1005    match crate::protocol::from_generated_protocol_frame(ProtocolFrame::EventFrame(event))? {
1006        crate::protocol::ProtocolFrame::Event(event) => Ok(event),
1007        crate::protocol::ProtocolFrame::Request(_)
1008        | crate::protocol::ProtocolFrame::Response(_)
1009        | crate::protocol::ProtocolFrame::SidecarRequest(_)
1010        | crate::protocol::ProtocolFrame::SidecarResponse(_) => {
1011            Err(ProtocolCodecError::DeserializeFailure(String::from(
1012                "wire event converted to non-event compatibility frame",
1013            )))
1014        }
1015    }
1016}
1017
1018pub fn sidecar_request_frame_from_compat(
1019    request: crate::protocol::SidecarRequestFrame,
1020) -> Result<SidecarRequestFrame, ProtocolCodecError> {
1021    match crate::protocol::to_generated_protocol_frame(
1022        &crate::protocol::ProtocolFrame::SidecarRequest(request),
1023    )? {
1024        ProtocolFrame::SidecarRequestFrame(request) => Ok(request),
1025        ProtocolFrame::RequestFrame(_)
1026        | ProtocolFrame::ResponseFrame(_)
1027        | ProtocolFrame::EventFrame(_)
1028        | ProtocolFrame::SidecarResponseFrame(_) => {
1029            Err(ProtocolCodecError::SerializeFailure(String::from(
1030                "compatibility sidecar request converted to non-sidecar-request wire frame",
1031            )))
1032        }
1033    }
1034}
1035
1036pub fn sidecar_request_payload_to_compat(
1037    ownership: &crate::protocol::OwnershipScope,
1038    payload: SidecarRequestPayload,
1039) -> Result<crate::protocol::SidecarRequestPayload, ProtocolCodecError> {
1040    match crate::protocol::from_generated_protocol_frame(ProtocolFrame::SidecarRequestFrame(
1041        SidecarRequestFrame {
1042            schema: protocol_schema(),
1043            request_id: -1,
1044            ownership: crate::protocol::to_generated_ownership_scope(ownership),
1045            payload,
1046        },
1047    ))? {
1048        crate::protocol::ProtocolFrame::SidecarRequest(request) => Ok(request.payload),
1049        crate::protocol::ProtocolFrame::Request(_)
1050        | crate::protocol::ProtocolFrame::Response(_)
1051        | crate::protocol::ProtocolFrame::Event(_)
1052        | crate::protocol::ProtocolFrame::SidecarResponse(_) => {
1053            Err(ProtocolCodecError::DeserializeFailure(String::from(
1054                "wire sidecar request payload converted to non-sidecar-request compatibility frame",
1055            )))
1056        }
1057    }
1058}
1059
1060pub fn sidecar_response_frame_to_compat(
1061    response: SidecarResponseFrame,
1062) -> Result<crate::protocol::SidecarResponseFrame, ProtocolCodecError> {
1063    match crate::protocol::from_generated_protocol_frame(ProtocolFrame::SidecarResponseFrame(
1064        response,
1065    ))? {
1066        crate::protocol::ProtocolFrame::SidecarResponse(response) => Ok(response),
1067        crate::protocol::ProtocolFrame::Request(_)
1068        | crate::protocol::ProtocolFrame::Response(_)
1069        | crate::protocol::ProtocolFrame::Event(_)
1070        | crate::protocol::ProtocolFrame::SidecarRequest(_) => {
1071            Err(ProtocolCodecError::DeserializeFailure(String::from(
1072                "wire sidecar response converted to non-sidecar-response compatibility frame",
1073            )))
1074        }
1075    }
1076}
1077
1078pub fn sidecar_response_frame_from_compat(
1079    response: crate::protocol::SidecarResponseFrame,
1080) -> Result<SidecarResponseFrame, ProtocolCodecError> {
1081    match crate::protocol::to_generated_protocol_frame(
1082        &crate::protocol::ProtocolFrame::SidecarResponse(response),
1083    )? {
1084        ProtocolFrame::SidecarResponseFrame(response) => Ok(response),
1085        ProtocolFrame::RequestFrame(_)
1086        | ProtocolFrame::ResponseFrame(_)
1087        | ProtocolFrame::EventFrame(_)
1088        | ProtocolFrame::SidecarRequestFrame(_) => {
1089            Err(ProtocolCodecError::SerializeFailure(String::from(
1090                "compatibility sidecar response converted to non-sidecar-response wire frame",
1091            )))
1092        }
1093    }
1094}
1095
1096pub fn dispatch_result_from_compat(
1097    result: CompatDispatchResult,
1098) -> Result<WireDispatchResult, ProtocolCodecError> {
1099    let response = match crate::protocol::to_generated_protocol_frame(
1100        &crate::protocol::ProtocolFrame::Response(result.response),
1101    )? {
1102        ProtocolFrame::ResponseFrame(response) => response,
1103        ProtocolFrame::RequestFrame(_)
1104        | ProtocolFrame::EventFrame(_)
1105        | ProtocolFrame::SidecarRequestFrame(_)
1106        | ProtocolFrame::SidecarResponseFrame(_) => {
1107            return Err(ProtocolCodecError::SerializeFailure(String::from(
1108                "compatibility dispatch response converted to non-response wire frame",
1109            )));
1110        }
1111    };
1112
1113    let events = result
1114        .events
1115        .into_iter()
1116        .map(|event| {
1117            match crate::protocol::to_generated_protocol_frame(
1118                &crate::protocol::ProtocolFrame::Event(event),
1119            )? {
1120                ProtocolFrame::EventFrame(event) => Ok(event),
1121                ProtocolFrame::RequestFrame(_)
1122                | ProtocolFrame::ResponseFrame(_)
1123                | ProtocolFrame::SidecarRequestFrame(_)
1124                | ProtocolFrame::SidecarResponseFrame(_) => {
1125                    Err(ProtocolCodecError::SerializeFailure(String::from(
1126                        "compatibility dispatch event converted to non-event wire frame",
1127                    )))
1128                }
1129            }
1130        })
1131        .collect::<Result<Vec<_>, _>>()?;
1132
1133    Ok(WireDispatchResult { response, events })
1134}
1135
1136fn validate_frame(frame: &ProtocolFrame) -> Result<(), ProtocolCodecError> {
1137    match frame {
1138        ProtocolFrame::RequestFrame(frame) => {
1139            validate_schema(&frame.schema)?;
1140            validate_request_id(frame.request_id)
1141        }
1142        ProtocolFrame::ResponseFrame(frame) => {
1143            validate_schema(&frame.schema)?;
1144            validate_request_id(frame.request_id)
1145        }
1146        ProtocolFrame::EventFrame(frame) => validate_schema(&frame.schema),
1147        ProtocolFrame::SidecarRequestFrame(frame) => {
1148            validate_schema(&frame.schema)?;
1149            validate_request_id(frame.request_id)
1150        }
1151        ProtocolFrame::SidecarResponseFrame(frame) => {
1152            validate_schema(&frame.schema)?;
1153            validate_request_id(frame.request_id)
1154        }
1155    }
1156}
1157
1158fn validate_schema(schema: &ProtocolSchema) -> Result<(), ProtocolCodecError> {
1159    if schema.name != PROTOCOL_NAME || schema.version != PROTOCOL_VERSION {
1160        return Err(ProtocolCodecError::UnsupportedSchema {
1161            name: schema.name.clone(),
1162            version: schema.version,
1163        });
1164    }
1165    Ok(())
1166}
1167
1168fn validate_request_id(request_id: RequestId) -> Result<(), ProtocolCodecError> {
1169    if request_id == 0 {
1170        return Err(ProtocolCodecError::InvalidRequestId);
1171    }
1172    Ok(())
1173}
1174
1175#[cfg(test)]
1176mod tests {
1177    use super::*;
1178    use crate::generated_protocol::v1::{
1179        FsPermissionScope, PatternPermissionScope, PermissionMode,
1180    };
1181    use std::collections::BTreeMap;
1182
1183    #[test]
1184    fn legacy_metadata_preserves_js_runtime_limits_with_only_new_fields() {
1185        let metadata = BTreeMap::from([(
1186            String::from("limits.js_runtime.cpu_time_limit_ms"),
1187            String::from("123"),
1188        )]);
1189
1190        let config = legacy_limits_config(&metadata).expect("limits config");
1191        let js_runtime = config.js_runtime.expect("js runtime limits");
1192
1193        assert_eq!(js_runtime.cpu_time_limit_ms, Some(123));
1194    }
1195
1196    #[test]
1197    fn legacy_metadata_preserves_wasm_limits_with_only_new_fields() {
1198        let metadata = BTreeMap::from([(
1199            String::from("limits.wasm.prewarm_timeout_ms"),
1200            String::from("456"),
1201        )]);
1202
1203        let config = legacy_limits_config(&metadata).expect("limits config");
1204        let wasm = config.wasm.expect("wasm limits");
1205
1206        assert_eq!(wasm.prewarm_timeout_ms, Some(456));
1207    }
1208
1209    #[test]
1210    fn legacy_metadata_preserves_wasm_runner_heap_limit_as_only_new_field() {
1211        let metadata = BTreeMap::from([(
1212            String::from("limits.wasm.runner_heap_limit_mb"),
1213            String::from("789"),
1214        )]);
1215
1216        let config = legacy_limits_config(&metadata).expect("limits config");
1217        let wasm = config.wasm.expect("wasm limits");
1218
1219        assert_eq!(wasm.runner_heap_limit_mb, Some(789));
1220    }
1221
1222    #[test]
1223    fn permissions_policy_default_matches_no_policy_deny_all() {
1224        let policy = PermissionsPolicy::default();
1225
1226        assert!(matches!(
1227            policy.fs,
1228            Some(FsPermissionScope::PermissionMode(PermissionMode::Deny))
1229        ));
1230        for scope in [
1231            policy.network,
1232            policy.child_process,
1233            policy.process,
1234            policy.env,
1235            policy.binding,
1236        ] {
1237            assert!(matches!(
1238                scope,
1239                Some(PatternPermissionScope::PermissionMode(PermissionMode::Deny))
1240            ));
1241        }
1242    }
1243
1244    #[test]
1245    fn permissions_policy_allow_all_remains_explicit() {
1246        let policy = PermissionsPolicy::allow_all();
1247
1248        assert!(matches!(
1249            policy.fs,
1250            Some(FsPermissionScope::PermissionMode(PermissionMode::Allow))
1251        ));
1252        for scope in [
1253            policy.network,
1254            policy.child_process,
1255            policy.process,
1256            policy.env,
1257            policy.binding,
1258        ] {
1259            assert!(matches!(
1260                scope,
1261                Some(PatternPermissionScope::PermissionMode(
1262                    PermissionMode::Allow
1263                ))
1264            ));
1265        }
1266    }
1267}