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 bindings = agentos_vm_config::BindingLimitsConfig {
451        default_binding_timeout_ms: legacy_u64(
452            metadata,
453            "limits.bindings.default_binding_timeout_ms",
454        ),
455        max_binding_timeout_ms: legacy_u64(metadata, "limits.bindings.max_binding_timeout_ms"),
456        max_registered_collections: legacy_u64(
457            metadata,
458            "limits.bindings.max_registered_collections",
459        ),
460        max_registered_bindings_per_vm: legacy_u64(
461            metadata,
462            "limits.bindings.max_registered_bindings_per_vm",
463        ),
464        max_bindings_per_collection: legacy_u64(
465            metadata,
466            "limits.bindings.max_bindings_per_collection",
467        ),
468        max_binding_schema_bytes: legacy_u64(metadata, "limits.bindings.max_binding_schema_bytes"),
469        max_examples_per_binding: legacy_u64(metadata, "limits.bindings.max_examples_per_binding"),
470        max_binding_example_input_bytes: legacy_u64(
471            metadata,
472            "limits.bindings.max_binding_example_input_bytes",
473        ),
474    };
475    let plugins = agentos_vm_config::PluginLimitsConfig {
476        max_persisted_manifest_bytes: legacy_u64(
477            metadata,
478            "limits.plugins.max_persisted_manifest_bytes",
479        ),
480        max_persisted_manifest_file_bytes: legacy_u64(
481            metadata,
482            "limits.plugins.max_persisted_manifest_file_bytes",
483        ),
484    };
485    let acp = agentos_vm_config::AcpLimitsConfig {
486        max_read_line_bytes: legacy_u64(metadata, "limits.acp.max_read_line_bytes"),
487        stdout_buffer_byte_limit: legacy_u64(metadata, "limits.acp.stdout_buffer_byte_limit"),
488        max_completed_message_bytes: legacy_u64(metadata, "limits.acp.max_completed_message_bytes"),
489        max_turn_output_bytes: legacy_u64(metadata, "limits.acp.max_turn_output_bytes"),
490        max_prompt_bytes: legacy_u64(metadata, "limits.acp.max_prompt_bytes"),
491        max_prompt_blocks: legacy_u64(metadata, "limits.acp.max_prompt_blocks"),
492        max_fallback_continuation_bytes: legacy_u64(
493            metadata,
494            "limits.acp.max_fallback_continuation_bytes",
495        ),
496        max_session_history_bytes: legacy_u64(metadata, "limits.acp.max_session_history_bytes"),
497        max_session_history_events: legacy_u64(metadata, "limits.acp.max_session_history_events"),
498        max_history_page_entries: legacy_u64(metadata, "limits.acp.max_history_page_entries"),
499        max_session_list_entries: legacy_u64(metadata, "limits.acp.max_session_list_entries"),
500        max_sessions_per_vm: legacy_u64(metadata, "limits.acp.max_sessions_per_vm"),
501        max_prompts_per_session: legacy_u64(metadata, "limits.acp.max_prompts_per_session"),
502        max_prompts_per_vm: legacy_u64(metadata, "limits.acp.max_prompts_per_vm"),
503        max_pending_permissions_per_session: legacy_u64(
504            metadata,
505            "limits.acp.max_pending_permissions_per_session",
506        ),
507        max_pending_permissions_per_vm: legacy_u64(
508            metadata,
509            "limits.acp.max_pending_permissions_per_vm",
510        ),
511        max_permission_outcomes_per_session: legacy_u64(
512            metadata,
513            "limits.acp.max_permission_outcomes_per_session",
514        ),
515        max_permission_outcomes_per_vm: legacy_u64(
516            metadata,
517            "limits.acp.max_permission_outcomes_per_vm",
518        ),
519    };
520    let sqlite = agentos_vm_config::SqliteLimitsConfig {
521        max_result_bytes: legacy_u64(metadata, "limits.sqlite.max_result_bytes"),
522    };
523    let js_runtime = agentos_vm_config::JsRuntimeLimitsConfig {
524        v8_heap_limit_mb: legacy_u64(metadata, "limits.js_runtime.v8_heap_limit_mb"),
525        sync_rpc_wait_timeout_ms: legacy_u64(
526            metadata,
527            "limits.js_runtime.sync_rpc_wait_timeout_ms",
528        ),
529        cpu_time_limit_ms: legacy_u64(metadata, "limits.js_runtime.cpu_time_limit_ms"),
530        wall_clock_limit_ms: legacy_u64(metadata, "limits.js_runtime.wall_clock_limit_ms"),
531        import_cache_materialize_timeout_ms: legacy_u64(
532            metadata,
533            "limits.js_runtime.import_cache_materialize_timeout_ms",
534        ),
535        captured_output_limit_bytes: legacy_u64(
536            metadata,
537            "limits.js_runtime.captured_output_limit_bytes",
538        ),
539        stdin_buffer_limit_bytes: legacy_u64(
540            metadata,
541            "limits.js_runtime.stdin_buffer_limit_bytes",
542        ),
543        event_payload_limit_bytes: legacy_u64(
544            metadata,
545            "limits.js_runtime.event_payload_limit_bytes",
546        ),
547        max_timers: legacy_u64(metadata, "limits.js_runtime.max_timers"),
548        v8_ipc_max_frame_bytes: legacy_u64(metadata, "limits.js_runtime.v8_ipc_max_frame_bytes"),
549    };
550    let python = agentos_vm_config::PythonLimitsConfig {
551        output_buffer_max_bytes: legacy_u64(metadata, "limits.python.output_buffer_max_bytes"),
552        execution_timeout_ms: legacy_u64(metadata, "limits.python.execution_timeout_ms"),
553        max_old_space_mb: legacy_u64(metadata, "limits.python.max_old_space_mb"),
554        vfs_rpc_timeout_ms: legacy_u64(metadata, "limits.python.vfs_rpc_timeout_ms"),
555    };
556    let wasm = agentos_vm_config::WasmLimitsConfig {
557        max_module_file_bytes: legacy_u64(metadata, "limits.wasm.max_module_file_bytes"),
558        captured_output_limit_bytes: legacy_u64(
559            metadata,
560            "limits.wasm.captured_output_limit_bytes",
561        ),
562        sync_read_limit_bytes: legacy_u64(metadata, "limits.wasm.sync_read_limit_bytes"),
563        prewarm_timeout_ms: legacy_u64(metadata, "limits.wasm.prewarm_timeout_ms"),
564        runner_heap_limit_mb: legacy_u64(metadata, "limits.wasm.runner_heap_limit_mb"),
565        runner_cpu_time_limit_ms: legacy_u64(metadata, "limits.wasm.runner_cpu_time_limit_ms"),
566    };
567    let process = agentos_vm_config::ProcessLimitsConfig {
568        max_spawn_file_actions: legacy_u64(metadata, "limits.process.max_spawn_file_actions")
569            .or_else(|| legacy_u64(metadata, "limits.wasm.max_spawn_file_actions")),
570        max_spawn_file_action_bytes: legacy_u64(
571            metadata,
572            "limits.process.max_spawn_file_action_bytes",
573        )
574        .or_else(|| legacy_u64(metadata, "limits.wasm.max_spawn_file_action_bytes")),
575        pending_stdin_bytes: legacy_u64(metadata, "limits.process.pending_stdin_bytes"),
576        pending_event_count: legacy_u64(metadata, "limits.process.pending_event_count"),
577        pending_event_bytes: legacy_u64(metadata, "limits.process.pending_event_bytes"),
578    };
579
580    let config = agentos_vm_config::VmLimitsConfig {
581        reactor: None,
582        resources: legacy_has_resource_limits(&resources).then_some(resources),
583        http: http.max_fetch_response_bytes.is_some().then_some(http),
584        udp: None,
585        tls: None,
586        http2: None,
587        bindings: legacy_has_binding_limits(&bindings).then_some(bindings),
588        plugins: legacy_has_plugin_limits(&plugins).then_some(plugins),
589        acp: legacy_has_acp_limits(&acp).then_some(acp),
590        sqlite: sqlite.max_result_bytes.is_some().then_some(sqlite),
591        js_runtime: legacy_has_js_runtime_limits(&js_runtime).then_some(js_runtime),
592        python: legacy_has_python_limits(&python).then_some(python),
593        wasm: legacy_has_wasm_limits(&wasm).then_some(wasm),
594        process: legacy_has_process_limits(&process).then_some(process),
595    };
596
597    if config.resources.is_none()
598        && config.http.is_none()
599        && config.bindings.is_none()
600        && config.plugins.is_none()
601        && config.acp.is_none()
602        && config.sqlite.is_none()
603        && config.js_runtime.is_none()
604        && config.python.is_none()
605        && config.wasm.is_none()
606        && config.process.is_none()
607    {
608        None
609    } else {
610        Some(config)
611    }
612}
613
614fn legacy_u64(metadata: &std::collections::BTreeMap<String, String>, key: &str) -> Option<u64> {
615    metadata.get(key).map(|value| {
616        value
617            .parse::<u64>()
618            .unwrap_or_else(|error| panic!("parse {key}: {error}"))
619    })
620}
621
622fn legacy_has_resource_limits(config: &agentos_vm_config::ResourceLimitsConfig) -> bool {
623    config.cpu_count.is_some()
624        || config.max_processes.is_some()
625        || config.max_open_fds.is_some()
626        || config.max_pipes.is_some()
627        || config.max_ptys.is_some()
628        || config.max_sockets.is_some()
629        || config.max_connections.is_some()
630        || config.max_socket_buffered_bytes.is_some()
631        || config.max_socket_datagram_queue_len.is_some()
632        || config.max_filesystem_bytes.is_some()
633        || config.max_inode_count.is_some()
634        || config.max_blocking_read_ms.is_some()
635        || config.max_pread_bytes.is_some()
636        || config.max_fd_write_bytes.is_some()
637        || config.max_process_argv_bytes.is_some()
638        || config.max_process_env_bytes.is_some()
639        || config.max_readdir_entries.is_some()
640        || config.max_wasm_fuel.is_some()
641        || config.max_wasm_memory_bytes.is_some()
642        || config.max_wasm_stack_bytes.is_some()
643}
644
645fn legacy_has_binding_limits(config: &agentos_vm_config::BindingLimitsConfig) -> bool {
646    config.default_binding_timeout_ms.is_some()
647        || config.max_binding_timeout_ms.is_some()
648        || config.max_registered_collections.is_some()
649        || config.max_registered_bindings_per_vm.is_some()
650        || config.max_bindings_per_collection.is_some()
651        || config.max_binding_schema_bytes.is_some()
652        || config.max_examples_per_binding.is_some()
653        || config.max_binding_example_input_bytes.is_some()
654}
655
656fn legacy_has_plugin_limits(config: &agentos_vm_config::PluginLimitsConfig) -> bool {
657    config.max_persisted_manifest_bytes.is_some()
658        || config.max_persisted_manifest_file_bytes.is_some()
659}
660
661fn legacy_has_acp_limits(config: &agentos_vm_config::AcpLimitsConfig) -> bool {
662    config.max_read_line_bytes.is_some()
663        || config.stdout_buffer_byte_limit.is_some()
664        || config.max_completed_message_bytes.is_some()
665        || config.max_turn_output_bytes.is_some()
666        || config.max_prompt_bytes.is_some()
667        || config.max_prompt_blocks.is_some()
668        || config.max_fallback_continuation_bytes.is_some()
669        || config.max_session_history_bytes.is_some()
670        || config.max_session_history_events.is_some()
671        || config.max_history_page_entries.is_some()
672        || config.max_session_list_entries.is_some()
673        || config.max_sessions_per_vm.is_some()
674        || config.max_prompts_per_session.is_some()
675        || config.max_prompts_per_vm.is_some()
676        || config.max_pending_permissions_per_session.is_some()
677        || config.max_pending_permissions_per_vm.is_some()
678        || config.max_permission_outcomes_per_session.is_some()
679        || config.max_permission_outcomes_per_vm.is_some()
680}
681
682fn legacy_has_js_runtime_limits(config: &agentos_vm_config::JsRuntimeLimitsConfig) -> bool {
683    config.v8_heap_limit_mb.is_some()
684        || config.sync_rpc_wait_timeout_ms.is_some()
685        || config.cpu_time_limit_ms.is_some()
686        || config.wall_clock_limit_ms.is_some()
687        || config.import_cache_materialize_timeout_ms.is_some()
688        || config.captured_output_limit_bytes.is_some()
689        || config.stdin_buffer_limit_bytes.is_some()
690        || config.event_payload_limit_bytes.is_some()
691        || config.max_timers.is_some()
692        || config.v8_ipc_max_frame_bytes.is_some()
693}
694
695fn legacy_has_python_limits(config: &agentos_vm_config::PythonLimitsConfig) -> bool {
696    config.output_buffer_max_bytes.is_some()
697        || config.execution_timeout_ms.is_some()
698        || config.max_old_space_mb.is_some()
699        || config.vfs_rpc_timeout_ms.is_some()
700}
701
702fn legacy_has_wasm_limits(config: &agentos_vm_config::WasmLimitsConfig) -> bool {
703    config.max_module_file_bytes.is_some()
704        || config.captured_output_limit_bytes.is_some()
705        || config.sync_read_limit_bytes.is_some()
706        || config.prewarm_timeout_ms.is_some()
707        || config.runner_heap_limit_mb.is_some()
708        || config.runner_cpu_time_limit_ms.is_some()
709}
710
711fn legacy_has_process_limits(config: &agentos_vm_config::ProcessLimitsConfig) -> bool {
712    config.max_spawn_file_actions.is_some()
713        || config.max_spawn_file_action_bytes.is_some()
714        || config.pending_stdin_bytes.is_some()
715        || config.pending_event_count.is_some()
716        || config.pending_event_bytes.is_some()
717}
718
719// Ownership-scope constructor ergonomics. The generated BARE union exposes only the
720// tuple-wrapped variants (`ConnectionOwnership`/`SessionOwnership`/`VmOwnership`); restore
721// the hand-written `connection`/`session`/`vm` helpers the sidecar relies on. These live in
722// `wire` (not `protocol`) for the same orphan-rule reason as the impls above: `protocol.rs`
723// is `#[path]`-included by integration tests where the generated type is foreign.
724impl crate::generated_protocol::v1::OwnershipScope {
725    pub fn connection(connection_id: impl Into<String>) -> Self {
726        Self::ConnectionOwnership(crate::generated_protocol::v1::ConnectionOwnership {
727            connection_id: connection_id.into(),
728        })
729    }
730
731    pub fn session(connection_id: impl Into<String>, session_id: impl Into<String>) -> Self {
732        Self::SessionOwnership(crate::generated_protocol::v1::SessionOwnership {
733            connection_id: connection_id.into(),
734            session_id: session_id.into(),
735        })
736    }
737
738    pub fn vm(
739        connection_id: impl Into<String>,
740        session_id: impl Into<String>,
741        vm_id: impl Into<String>,
742    ) -> Self {
743        Self::VmOwnership(crate::generated_protocol::v1::VmOwnership {
744            connection_id: connection_id.into(),
745            session_id: session_id.into(),
746            vm_id: vm_id.into(),
747        })
748    }
749}
750
751pub const PROTOCOL_NAME: &str = "agentos-native-sidecar";
752pub const PROTOCOL_VERSION: u16 = 8;
753// 16 MiB: large enough to carry a trusted-client CreateVm config that inlines an
754// entire base-filesystem snapshot, while still bounding a single frame.
755pub const DEFAULT_MAX_FRAME_BYTES: usize = 16 * 1024 * 1024;
756
757#[derive(Debug, Clone, PartialEq, Eq)]
758pub enum ProtocolCodecError {
759    TruncatedFrame {
760        actual: usize,
761    },
762    LengthPrefixMismatch {
763        declared: usize,
764        actual: usize,
765    },
766    FrameTooLarge {
767        size: usize,
768        max: usize,
769    },
770    UnsupportedSchema {
771        name: String,
772        version: u16,
773    },
774    InvalidRequestId,
775    InvalidRequestDirection {
776        request_id: RequestId,
777        expected: RequestDirection,
778    },
779    EmptyOwnershipField {
780        field: &'static str,
781    },
782    EmptyAuthToken,
783    InvalidOwnershipScope {
784        required: OwnershipRequirement,
785        actual: OwnershipRequirement,
786    },
787    SerializeFailure(String),
788    DeserializeFailure(String),
789}
790
791impl fmt::Display for ProtocolCodecError {
792    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
793        match self {
794            Self::TruncatedFrame { actual } => {
795                write!(
796                    f,
797                    "protocol frame is truncated: only {actual} bytes provided"
798                )
799            }
800            Self::LengthPrefixMismatch { declared, actual } => write!(
801                f,
802                "protocol frame length prefix mismatch: declared {declared} bytes, got {actual}",
803            ),
804            Self::FrameTooLarge { size, max } => {
805                write!(f, "protocol frame is {size} bytes, limit is {max}")
806            }
807            Self::UnsupportedSchema { name, version } => write!(
808                f,
809                "unsupported protocol schema {name}@{version}; expected {PROTOCOL_NAME}@{PROTOCOL_VERSION}",
810            ),
811            Self::InvalidRequestId => write!(f, "protocol request identifiers must be non-zero"),
812            Self::InvalidRequestDirection {
813                request_id,
814                expected,
815            } => write!(f, "protocol request id {request_id} must be {expected}",),
816            Self::EmptyOwnershipField { field } => {
817                write!(f, "protocol ownership field `{field}` cannot be empty")
818            }
819            Self::EmptyAuthToken => {
820                write!(f, "authenticate requests require a non-empty auth token")
821            }
822            Self::InvalidOwnershipScope { required, actual } => write!(
823                f,
824                "protocol frame requires {required} ownership but carried {actual}",
825            ),
826            Self::SerializeFailure(message) => {
827                write!(f, "protocol frame serialization failed: {message}")
828            }
829            Self::DeserializeFailure(message) => {
830                write!(f, "protocol frame deserialization failed: {message}")
831            }
832        }
833    }
834}
835
836impl Error for ProtocolCodecError {}
837
838#[derive(Debug, Clone, Copy, PartialEq, Eq)]
839pub enum OwnershipRequirement {
840    Any,
841    Connection,
842    Session,
843    Vm,
844    SessionOrVm,
845}
846
847impl fmt::Display for OwnershipRequirement {
848    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849        match self {
850            Self::Any => write!(f, "any"),
851            Self::Connection => write!(f, "connection"),
852            Self::Session => write!(f, "session"),
853            Self::Vm => write!(f, "vm"),
854            Self::SessionOrVm => write!(f, "session-or-vm"),
855        }
856    }
857}
858
859#[derive(Debug, Clone, Copy, PartialEq, Eq)]
860pub enum RequestDirection {
861    Host,
862    Sidecar,
863}
864
865impl fmt::Display for RequestDirection {
866    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
867        match self {
868            Self::Host => write!(f, "positive"),
869            Self::Sidecar => write!(f, "negative"),
870        }
871    }
872}
873
874#[derive(Debug, Clone, PartialEq, Eq)]
875pub struct WireDispatchResult {
876    pub response: ResponseFrame,
877    pub events: Vec<EventFrame>,
878}
879
880#[derive(Debug, Clone, PartialEq, Eq)]
881pub struct CompatDispatchResult {
882    pub response: crate::protocol::ResponseFrame,
883    pub events: Vec<crate::protocol::EventFrame>,
884}
885
886#[derive(Debug, Clone)]
887pub struct WireFrameCodec {
888    max_frame_bytes: usize,
889}
890
891impl WireFrameCodec {
892    pub fn new(max_frame_bytes: usize) -> Self {
893        Self { max_frame_bytes }
894    }
895
896    pub fn max_frame_bytes(&self) -> usize {
897        self.max_frame_bytes
898    }
899
900    pub fn encode(&self, frame: &ProtocolFrame) -> Result<Vec<u8>, ProtocolCodecError> {
901        validate_frame(frame)?;
902
903        let payload = serde_bare::to_vec(frame)
904            .map_err(|error| ProtocolCodecError::SerializeFailure(error.to_string()))?;
905        if payload.len() > self.max_frame_bytes {
906            return Err(ProtocolCodecError::FrameTooLarge {
907                size: payload.len(),
908                max: self.max_frame_bytes,
909            });
910        }
911
912        let length =
913            u32::try_from(payload.len()).map_err(|_| ProtocolCodecError::FrameTooLarge {
914                size: payload.len(),
915                max: u32::MAX as usize,
916            })?;
917
918        let mut encoded = Vec::with_capacity(4 + payload.len());
919        encoded.extend_from_slice(&length.to_be_bytes());
920        encoded.extend_from_slice(&payload);
921        Ok(encoded)
922    }
923
924    pub fn decode(&self, bytes: &[u8]) -> Result<ProtocolFrame, ProtocolCodecError> {
925        let payload = self.checked_payload(bytes)?;
926        let frame = serde_bare::from_slice(payload)
927            .map_err(|error| ProtocolCodecError::DeserializeFailure(error.to_string()))?;
928        validate_frame(&frame)?;
929        Ok(frame)
930    }
931
932    /// Encode a frame as a bare message WITHOUT the 4-byte length prefix.
933    ///
934    /// Stream transports (stdio) use [`encode`] so frames can be delimited in a
935    /// byte stream. Message transports where the boundary is the call itself
936    /// (the browser `pushFrame` / `postMessage` path) use this so the on-wire
937    /// bytes match the TypeScript `encodeProtocolFramePayload(frame, "bare")`,
938    /// which emits the raw bare frame with no prefix.
939    pub fn encode_message(&self, frame: &ProtocolFrame) -> Result<Vec<u8>, ProtocolCodecError> {
940        validate_frame(frame)?;
941        let payload = serde_bare::to_vec(frame)
942            .map_err(|error| ProtocolCodecError::SerializeFailure(error.to_string()))?;
943        if payload.len() > self.max_frame_bytes {
944            return Err(ProtocolCodecError::FrameTooLarge {
945                size: payload.len(),
946                max: self.max_frame_bytes,
947            });
948        }
949        Ok(payload)
950    }
951
952    /// Decode a bare message produced by [`encode_message`] (no length prefix).
953    pub fn decode_message(&self, bytes: &[u8]) -> Result<ProtocolFrame, ProtocolCodecError> {
954        if bytes.len() > self.max_frame_bytes {
955            return Err(ProtocolCodecError::FrameTooLarge {
956                size: bytes.len(),
957                max: self.max_frame_bytes,
958            });
959        }
960        let frame = serde_bare::from_slice(bytes)
961            .map_err(|error| ProtocolCodecError::DeserializeFailure(error.to_string()))?;
962        validate_frame(&frame)?;
963        Ok(frame)
964    }
965
966    fn checked_payload<'a>(&self, bytes: &'a [u8]) -> Result<&'a [u8], ProtocolCodecError> {
967        if bytes.len() < 4 {
968            return Err(ProtocolCodecError::TruncatedFrame {
969                actual: bytes.len(),
970            });
971        }
972
973        let declared =
974            u32::from_be_bytes(bytes[..4].try_into().expect("length prefix is four bytes"))
975                as usize;
976        if declared > self.max_frame_bytes {
977            return Err(ProtocolCodecError::FrameTooLarge {
978                size: declared,
979                max: self.max_frame_bytes,
980            });
981        }
982
983        let actual = bytes.len() - 4;
984        if declared != actual {
985            return Err(ProtocolCodecError::LengthPrefixMismatch { declared, actual });
986        }
987
988        Ok(&bytes[4..])
989    }
990}
991
992impl Default for WireFrameCodec {
993    fn default() -> Self {
994        Self::new(DEFAULT_MAX_FRAME_BYTES)
995    }
996}
997
998pub fn protocol_schema() -> ProtocolSchema {
999    ProtocolSchema::current()
1000}
1001
1002impl ProtocolSchema {
1003    pub fn current() -> Self {
1004        Self {
1005            name: PROTOCOL_NAME.to_string(),
1006            version: PROTOCOL_VERSION,
1007        }
1008    }
1009}
1010
1011impl Default for ProtocolSchema {
1012    fn default() -> Self {
1013        Self::current()
1014    }
1015}
1016
1017pub fn request_frame_to_compat(
1018    request: RequestFrame,
1019) -> Result<crate::protocol::RequestFrame, ProtocolCodecError> {
1020    match crate::protocol::from_generated_protocol_frame(ProtocolFrame::RequestFrame(request))? {
1021        crate::protocol::ProtocolFrame::Request(request) => Ok(request),
1022        crate::protocol::ProtocolFrame::Response(_)
1023        | crate::protocol::ProtocolFrame::Event(_)
1024        | crate::protocol::ProtocolFrame::SidecarRequest(_)
1025        | crate::protocol::ProtocolFrame::SidecarResponse(_)
1026        | crate::protocol::ProtocolFrame::Control(_) => {
1027            Err(ProtocolCodecError::DeserializeFailure(String::from(
1028                "wire request frame converted to non-request compatibility frame",
1029            )))
1030        }
1031    }
1032}
1033
1034pub fn ownership_scope_to_compat(ownership: OwnershipScope) -> crate::protocol::OwnershipScope {
1035    crate::protocol::from_generated_ownership_scope(ownership)
1036}
1037
1038pub fn request_payload_to_compat(
1039    ownership: &crate::protocol::OwnershipScope,
1040    payload: RequestPayload,
1041) -> Result<crate::protocol::RequestPayload, ProtocolCodecError> {
1042    match crate::protocol::from_generated_protocol_frame(ProtocolFrame::RequestFrame(
1043        RequestFrame {
1044            schema: protocol_schema(),
1045            request_id: 1,
1046            ownership: crate::protocol::to_generated_ownership_scope(ownership),
1047            payload,
1048        },
1049    ))? {
1050        crate::protocol::ProtocolFrame::Request(request) => Ok(request.payload),
1051        crate::protocol::ProtocolFrame::Response(_)
1052        | crate::protocol::ProtocolFrame::Event(_)
1053        | crate::protocol::ProtocolFrame::SidecarRequest(_)
1054        | crate::protocol::ProtocolFrame::SidecarResponse(_)
1055        | crate::protocol::ProtocolFrame::Control(_) => {
1056            Err(ProtocolCodecError::DeserializeFailure(String::from(
1057                "wire request payload converted to non-request compatibility frame",
1058            )))
1059        }
1060    }
1061}
1062
1063pub fn response_payload_from_compat(
1064    ownership: &crate::protocol::OwnershipScope,
1065    payload: crate::protocol::ResponsePayload,
1066) -> Result<ResponsePayload, ProtocolCodecError> {
1067    match crate::protocol::to_generated_protocol_frame(&crate::protocol::ProtocolFrame::Response(
1068        crate::protocol::ResponseFrame::new(1, ownership.clone(), payload),
1069    ))? {
1070        ProtocolFrame::ResponseFrame(response) => Ok(response.payload),
1071        ProtocolFrame::RequestFrame(_)
1072        | ProtocolFrame::EventFrame(_)
1073        | ProtocolFrame::SidecarRequestFrame(_)
1074        | ProtocolFrame::SidecarResponseFrame(_)
1075        | ProtocolFrame::ControlFrame(_) => Err(ProtocolCodecError::SerializeFailure(
1076            String::from("compatibility response payload converted to non-response wire frame"),
1077        )),
1078    }
1079}
1080
1081pub fn event_frame_from_compat(
1082    event: crate::protocol::EventFrame,
1083) -> Result<EventFrame, ProtocolCodecError> {
1084    match crate::protocol::to_generated_protocol_frame(&crate::protocol::ProtocolFrame::Event(
1085        event,
1086    ))? {
1087        ProtocolFrame::EventFrame(event) => Ok(event),
1088        ProtocolFrame::RequestFrame(_)
1089        | ProtocolFrame::ResponseFrame(_)
1090        | ProtocolFrame::SidecarRequestFrame(_)
1091        | ProtocolFrame::SidecarResponseFrame(_)
1092        | ProtocolFrame::ControlFrame(_) => Err(ProtocolCodecError::SerializeFailure(
1093            String::from("compatibility event converted to non-event wire frame"),
1094        )),
1095    }
1096}
1097
1098pub fn event_frame_to_compat(
1099    event: EventFrame,
1100) -> Result<crate::protocol::EventFrame, ProtocolCodecError> {
1101    match crate::protocol::from_generated_protocol_frame(ProtocolFrame::EventFrame(event))? {
1102        crate::protocol::ProtocolFrame::Event(event) => Ok(event),
1103        crate::protocol::ProtocolFrame::Request(_)
1104        | crate::protocol::ProtocolFrame::Response(_)
1105        | crate::protocol::ProtocolFrame::SidecarRequest(_)
1106        | crate::protocol::ProtocolFrame::SidecarResponse(_)
1107        | crate::protocol::ProtocolFrame::Control(_) => {
1108            Err(ProtocolCodecError::DeserializeFailure(String::from(
1109                "wire event converted to non-event compatibility frame",
1110            )))
1111        }
1112    }
1113}
1114
1115pub fn sidecar_request_frame_from_compat(
1116    request: crate::protocol::SidecarRequestFrame,
1117) -> Result<SidecarRequestFrame, ProtocolCodecError> {
1118    match crate::protocol::to_generated_protocol_frame(
1119        &crate::protocol::ProtocolFrame::SidecarRequest(request),
1120    )? {
1121        ProtocolFrame::SidecarRequestFrame(request) => Ok(request),
1122        ProtocolFrame::RequestFrame(_)
1123        | ProtocolFrame::ResponseFrame(_)
1124        | ProtocolFrame::EventFrame(_)
1125        | ProtocolFrame::SidecarResponseFrame(_)
1126        | ProtocolFrame::ControlFrame(_) => {
1127            Err(ProtocolCodecError::SerializeFailure(String::from(
1128                "compatibility sidecar request converted to non-sidecar-request wire frame",
1129            )))
1130        }
1131    }
1132}
1133
1134pub fn sidecar_request_payload_to_compat(
1135    ownership: &crate::protocol::OwnershipScope,
1136    payload: SidecarRequestPayload,
1137) -> Result<crate::protocol::SidecarRequestPayload, ProtocolCodecError> {
1138    match crate::protocol::from_generated_protocol_frame(ProtocolFrame::SidecarRequestFrame(
1139        SidecarRequestFrame {
1140            schema: protocol_schema(),
1141            request_id: -1,
1142            ownership: crate::protocol::to_generated_ownership_scope(ownership),
1143            payload,
1144        },
1145    ))? {
1146        crate::protocol::ProtocolFrame::SidecarRequest(request) => Ok(request.payload),
1147        crate::protocol::ProtocolFrame::Request(_)
1148        | crate::protocol::ProtocolFrame::Response(_)
1149        | crate::protocol::ProtocolFrame::Event(_)
1150        | crate::protocol::ProtocolFrame::SidecarResponse(_)
1151        | crate::protocol::ProtocolFrame::Control(_) => {
1152            Err(ProtocolCodecError::DeserializeFailure(String::from(
1153                "wire sidecar request payload converted to non-sidecar-request compatibility frame",
1154            )))
1155        }
1156    }
1157}
1158
1159pub fn sidecar_response_frame_to_compat(
1160    response: SidecarResponseFrame,
1161) -> Result<crate::protocol::SidecarResponseFrame, ProtocolCodecError> {
1162    match crate::protocol::from_generated_protocol_frame(ProtocolFrame::SidecarResponseFrame(
1163        response,
1164    ))? {
1165        crate::protocol::ProtocolFrame::SidecarResponse(response) => Ok(response),
1166        crate::protocol::ProtocolFrame::Request(_)
1167        | crate::protocol::ProtocolFrame::Response(_)
1168        | crate::protocol::ProtocolFrame::Event(_)
1169        | crate::protocol::ProtocolFrame::SidecarRequest(_)
1170        | crate::protocol::ProtocolFrame::Control(_) => {
1171            Err(ProtocolCodecError::DeserializeFailure(String::from(
1172                "wire sidecar response converted to non-sidecar-response compatibility frame",
1173            )))
1174        }
1175    }
1176}
1177
1178pub fn sidecar_response_frame_from_compat(
1179    response: crate::protocol::SidecarResponseFrame,
1180) -> Result<SidecarResponseFrame, ProtocolCodecError> {
1181    match crate::protocol::to_generated_protocol_frame(
1182        &crate::protocol::ProtocolFrame::SidecarResponse(response),
1183    )? {
1184        ProtocolFrame::SidecarResponseFrame(response) => Ok(response),
1185        ProtocolFrame::RequestFrame(_)
1186        | ProtocolFrame::ResponseFrame(_)
1187        | ProtocolFrame::EventFrame(_)
1188        | ProtocolFrame::SidecarRequestFrame(_)
1189        | ProtocolFrame::ControlFrame(_) => {
1190            Err(ProtocolCodecError::SerializeFailure(String::from(
1191                "compatibility sidecar response converted to non-sidecar-response wire frame",
1192            )))
1193        }
1194    }
1195}
1196
1197pub fn dispatch_result_from_compat(
1198    result: CompatDispatchResult,
1199) -> Result<WireDispatchResult, ProtocolCodecError> {
1200    let response = match crate::protocol::to_generated_protocol_frame(
1201        &crate::protocol::ProtocolFrame::Response(result.response),
1202    )? {
1203        ProtocolFrame::ResponseFrame(response) => response,
1204        ProtocolFrame::RequestFrame(_)
1205        | ProtocolFrame::EventFrame(_)
1206        | ProtocolFrame::SidecarRequestFrame(_)
1207        | ProtocolFrame::SidecarResponseFrame(_)
1208        | ProtocolFrame::ControlFrame(_) => {
1209            return Err(ProtocolCodecError::SerializeFailure(String::from(
1210                "compatibility dispatch response converted to non-response wire frame",
1211            )));
1212        }
1213    };
1214
1215    let events = result
1216        .events
1217        .into_iter()
1218        .map(|event| {
1219            match crate::protocol::to_generated_protocol_frame(
1220                &crate::protocol::ProtocolFrame::Event(event),
1221            )? {
1222                ProtocolFrame::EventFrame(event) => Ok(event),
1223                ProtocolFrame::RequestFrame(_)
1224                | ProtocolFrame::ResponseFrame(_)
1225                | ProtocolFrame::SidecarRequestFrame(_)
1226                | ProtocolFrame::SidecarResponseFrame(_)
1227                | ProtocolFrame::ControlFrame(_) => Err(ProtocolCodecError::SerializeFailure(
1228                    String::from("compatibility dispatch event converted to non-event wire frame"),
1229                )),
1230            }
1231        })
1232        .collect::<Result<Vec<_>, _>>()?;
1233
1234    Ok(WireDispatchResult { response, events })
1235}
1236
1237fn validate_frame(frame: &ProtocolFrame) -> Result<(), ProtocolCodecError> {
1238    match frame {
1239        ProtocolFrame::RequestFrame(frame) => {
1240            validate_schema(&frame.schema)?;
1241            validate_request_id(frame.request_id)
1242        }
1243        ProtocolFrame::ResponseFrame(frame) => {
1244            validate_schema(&frame.schema)?;
1245            validate_request_id(frame.request_id)
1246        }
1247        ProtocolFrame::EventFrame(frame) => validate_schema(&frame.schema),
1248        ProtocolFrame::SidecarRequestFrame(frame) => {
1249            validate_schema(&frame.schema)?;
1250            validate_request_id(frame.request_id)
1251        }
1252        ProtocolFrame::SidecarResponseFrame(frame) => {
1253            validate_schema(&frame.schema)?;
1254            validate_request_id(frame.request_id)
1255        }
1256        ProtocolFrame::ControlFrame(frame) => validate_schema(&frame.schema),
1257    }
1258}
1259
1260fn validate_schema(schema: &ProtocolSchema) -> Result<(), ProtocolCodecError> {
1261    if schema.name != PROTOCOL_NAME || schema.version != PROTOCOL_VERSION {
1262        return Err(ProtocolCodecError::UnsupportedSchema {
1263            name: schema.name.clone(),
1264            version: schema.version,
1265        });
1266    }
1267    Ok(())
1268}
1269
1270fn validate_request_id(request_id: RequestId) -> Result<(), ProtocolCodecError> {
1271    if request_id == 0 {
1272        return Err(ProtocolCodecError::InvalidRequestId);
1273    }
1274    Ok(())
1275}
1276
1277#[cfg(test)]
1278mod tests {
1279    use super::*;
1280    use crate::generated_protocol::v1::{
1281        FsPermissionScope, PatternPermissionScope, PermissionMode,
1282    };
1283    use std::collections::BTreeMap;
1284
1285    #[test]
1286    fn legacy_metadata_preserves_js_runtime_limits_with_only_new_fields() {
1287        let metadata = BTreeMap::from([(
1288            String::from("limits.js_runtime.cpu_time_limit_ms"),
1289            String::from("123"),
1290        )]);
1291
1292        let config = legacy_limits_config(&metadata).expect("limits config");
1293        let js_runtime = config.js_runtime.expect("js runtime limits");
1294
1295        assert_eq!(js_runtime.cpu_time_limit_ms, Some(123));
1296    }
1297
1298    #[test]
1299    fn legacy_metadata_preserves_wasm_limits_with_only_new_fields() {
1300        let metadata = BTreeMap::from([(
1301            String::from("limits.wasm.prewarm_timeout_ms"),
1302            String::from("456"),
1303        )]);
1304
1305        let config = legacy_limits_config(&metadata).expect("limits config");
1306        let wasm = config.wasm.expect("wasm limits");
1307
1308        assert_eq!(wasm.prewarm_timeout_ms, Some(456));
1309    }
1310
1311    #[test]
1312    fn legacy_metadata_preserves_wasm_runner_heap_limit_as_only_new_field() {
1313        let metadata = BTreeMap::from([(
1314            String::from("limits.wasm.runner_heap_limit_mb"),
1315            String::from("789"),
1316        )]);
1317
1318        let config = legacy_limits_config(&metadata).expect("limits config");
1319        let wasm = config.wasm.expect("wasm limits");
1320
1321        assert_eq!(wasm.runner_heap_limit_mb, Some(789));
1322    }
1323
1324    #[test]
1325    fn legacy_metadata_preserves_wasm_runner_cpu_limit_as_only_new_field() {
1326        let metadata = BTreeMap::from([(
1327            String::from("limits.wasm.runner_cpu_time_limit_ms"),
1328            String::from("987"),
1329        )]);
1330
1331        let config = legacy_limits_config(&metadata).expect("limits config");
1332        let wasm = config.wasm.expect("wasm limits");
1333
1334        assert_eq!(wasm.runner_cpu_time_limit_ms, Some(987));
1335    }
1336
1337    #[test]
1338    fn permissions_policy_default_matches_no_policy_deny_all() {
1339        let policy = PermissionsPolicy::default();
1340
1341        assert!(matches!(
1342            policy.fs,
1343            Some(FsPermissionScope::PermissionMode(PermissionMode::Deny))
1344        ));
1345        for scope in [
1346            policy.network,
1347            policy.child_process,
1348            policy.process,
1349            policy.env,
1350            policy.binding,
1351        ] {
1352            assert!(matches!(
1353                scope,
1354                Some(PatternPermissionScope::PermissionMode(PermissionMode::Deny))
1355            ));
1356        }
1357    }
1358
1359    #[test]
1360    fn permissions_policy_allow_all_remains_explicit() {
1361        let policy = PermissionsPolicy::allow_all();
1362
1363        assert!(matches!(
1364            policy.fs,
1365            Some(FsPermissionScope::PermissionMode(PermissionMode::Allow))
1366        ));
1367        for scope in [
1368            policy.network,
1369            policy.child_process,
1370            policy.process,
1371            policy.env,
1372            policy.binding,
1373        ] {
1374            assert!(matches!(
1375                scope,
1376                Some(PatternPermissionScope::PermissionMode(
1377                    PermissionMode::Allow
1378                ))
1379            ));
1380        }
1381    }
1382}