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