1use std::collections::BTreeMap;
12use std::sync::Arc;
13
14use serde::{Deserialize, Serialize};
15
16use crate::fs::VirtualFileSystem;
17pub use agentos_vm_config::{
18 VmGroupConfig, VmSqliteCallbackRequest, VmSqliteCallbackResponse, VmSqliteDescriptor,
19 VmSqliteQueryResult, VmSqliteStatement, VmSqliteValue, VmUserAccountConfig, VmUserConfig,
20 VM_SQLITE_CALLBACK_NAMESPACE,
21};
22
23pub type SidecarSqliteCallback = Arc<
24 dyn Fn(
25 VmSqliteCallbackRequest,
26 ) -> futures::future::BoxFuture<'static, Result<VmSqliteCallbackResponse, String>>
27 + Send
28 + Sync,
29>;
30
31#[derive(Default)]
36pub struct AgentOsConfig {
37 pub database: Option<agentos_vm_config::VmSqliteDescriptor>,
40 pub sidecar_sqlite_callback: Option<SidecarSqliteCallback>,
43 pub user: Option<VmUserConfig>,
45 pub environment: Option<BTreeMap<String, String>>,
48 pub software: Vec<SoftwareInput>,
50 pub packages: Vec<PackageRef>,
54 pub packages_mount_at: Option<String>,
57 pub package_resolver: Option<crate::software::PackageResolverOptions>,
60 pub software_sources: Vec<crate::software_registry::SoftwareSource>,
64 pub software_registry: Option<crate::software_registry::SoftwareRegistryOptions>,
67 pub loopback_exempt_ports: Vec<u16>,
69 pub allowed_node_builtins: Option<Vec<String>>,
71 pub high_resolution_time: Option<bool>,
74 pub root_filesystem: RootFilesystemConfig,
76 pub mounts: Vec<MountConfig>,
78 pub schedule_driver: Option<Arc<dyn ScheduleDriver>>,
80 pub host_functions: HostFunctionCollections,
82 pub sidecar_js_bridge_callback: Option<SidecarJsBridgeCallback>,
84 pub permissions: Option<Permissions>,
86 pub limits: Option<AgentOsLimits>,
88 pub sidecar: Option<AgentOsSidecarConfig>,
90 pub sidecar_binary_path: Option<String>,
95}
96
97#[derive(Default)]
99pub struct AgentOsConfigBuilder {
100 config: AgentOsConfig,
101}
102
103impl AgentOsConfigBuilder {
104 pub fn new() -> Self {
105 Self::default()
106 }
107
108 pub fn database(mut self, database: agentos_vm_config::VmSqliteDescriptor) -> Self {
109 self.config.database = Some(database);
110 self
111 }
112
113 pub fn sidecar_sqlite_callback(mut self, callback: SidecarSqliteCallback) -> Self {
114 self.config.sidecar_sqlite_callback = Some(callback);
115 self
116 }
117
118 pub fn packages(mut self, packages: Vec<PackageRef>) -> Self {
119 self.config.packages = packages;
120 self
121 }
122
123 pub fn packages_mount_at(mut self, mount_at: impl Into<String>) -> Self {
124 self.config.packages_mount_at = Some(mount_at.into());
125 self
126 }
127
128 pub fn package_resolver(mut self, options: crate::software::PackageResolverOptions) -> Self {
129 self.config.package_resolver = Some(options);
130 self
131 }
132
133 pub fn software_sources(
134 mut self,
135 sources: Vec<crate::software_registry::SoftwareSource>,
136 ) -> Self {
137 self.config.software_sources = sources;
138 self
139 }
140
141 pub fn software_registry(
142 mut self,
143 options: crate::software_registry::SoftwareRegistryOptions,
144 ) -> Self {
145 self.config.software_registry = Some(options);
146 self
147 }
148
149 pub fn loopback_exempt_ports(mut self, ports: Vec<u16>) -> Self {
150 self.config.loopback_exempt_ports = ports;
151 self
152 }
153
154 pub fn allowed_node_builtins(mut self, builtins: Vec<String>) -> Self {
155 self.config.allowed_node_builtins = Some(builtins);
156 self
157 }
158
159 pub fn user(mut self, user: VmUserConfig) -> Self {
160 self.config.user = Some(user);
161 self
162 }
163
164 pub fn environment(mut self, environment: BTreeMap<String, String>) -> Self {
165 self.config.environment = Some(environment);
166 self
167 }
168
169 pub fn high_resolution_time(mut self, enabled: bool) -> Self {
170 self.config.high_resolution_time = Some(enabled);
171 self
172 }
173
174 pub fn root_filesystem(mut self, root: RootFilesystemConfig) -> Self {
175 self.config.root_filesystem = root;
176 self
177 }
178
179 pub fn mounts(mut self, mounts: Vec<MountConfig>) -> Self {
180 self.config.mounts = mounts;
181 self
182 }
183
184 pub fn schedule_driver(mut self, driver: Arc<dyn ScheduleDriver>) -> Self {
185 self.config.schedule_driver = Some(driver);
186 self
187 }
188
189 pub fn host_functions(mut self, host_functions: HostFunctionCollections) -> Self {
190 self.config.host_functions = host_functions;
191 self
192 }
193
194 pub fn sidecar_js_bridge_callback(mut self, callback: SidecarJsBridgeCallback) -> Self {
195 self.config.sidecar_js_bridge_callback = Some(callback);
196 self
197 }
198
199 pub fn permissions(mut self, permissions: Permissions) -> Self {
200 self.config.permissions = Some(permissions);
201 self
202 }
203
204 pub fn limits(mut self, limits: AgentOsLimits) -> Self {
205 self.config.limits = Some(limits);
206 self
207 }
208
209 pub fn sidecar(mut self, sidecar: AgentOsSidecarConfig) -> Self {
210 self.config.sidecar = Some(sidecar);
211 self
212 }
213
214 pub fn sidecar_binary_path(mut self, path: impl Into<String>) -> Self {
215 self.config.sidecar_binary_path = Some(path.into());
216 self
217 }
218
219 pub fn build(self) -> AgentOsConfig {
220 self.config
221 }
222}
223
224impl AgentOsConfig {
225 pub fn validate(&self) -> Result<(), crate::ClientError> {
231 crate::agent_os::validate_config(self)
232 }
233}
234
235#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
238#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
239#[serde(rename_all = "kebab-case")]
240pub enum SoftwareKind {
241 #[default]
244 WasmCommands,
245 HostFunction,
247}
248
249#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub struct SoftwareInput {
253 pub package: String,
254 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub version: Option<String>,
256 #[serde(default)]
258 pub kind: SoftwareKind,
259}
260
261#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
266pub struct PackageRef {
267 #[serde(rename = "packagePath")]
270 pub path: String,
271}
272
273pub type HostFunctionCallback = Arc<
277 dyn Fn(
278 serde_json::Value,
279 ) -> futures::future::BoxFuture<'static, Result<serde_json::Value, String>>
280 + Send
281 + Sync,
282>;
283
284#[derive(Debug, Clone, PartialEq, Eq)]
286pub struct SidecarJsBridgeCall {
287 pub call_id: String,
288 pub mount_id: String,
289 pub operation: String,
290 pub args: serde_json::Value,
291}
292
293pub type SidecarJsBridgeCallback = Arc<
299 dyn Fn(
300 SidecarJsBridgeCall,
301 )
302 -> futures::future::BoxFuture<'static, Result<Option<serde_json::Value>, String>>
303 + Send
304 + Sync,
305>;
306
307#[derive(Clone)]
310pub struct HostFunction {
311 pub input_schema: serde_json::Value,
313 pub timeout_ms: Option<u64>,
314 pub execute: HostFunctionCallback,
316}
317
318pub type HostFunctionCollection = BTreeMap<String, HostFunction>;
321
322pub type HostFunctionCollections = BTreeMap<String, HostFunctionCollection>;
328
329#[derive(Clone)]
331pub struct ResolvedHostFunction {
332 pub name: String,
334 pub description: String,
336 pub input_schema: serde_json::Value,
337 pub timeout_ms: Option<u64>,
338 pub execute: HostFunctionCallback,
339}
340
341#[derive(Clone)]
345pub struct ResolvedHostFunctions {
346 pub name: String,
348 pub functions: Vec<ResolvedHostFunction>,
349}
350
351pub fn host_function_command_name(key: &str) -> String {
356 let mut out = String::with_capacity(key.len() + 4);
357 let chars: Vec<char> = key.chars().collect();
358 for (index, character) in chars.iter().enumerate() {
359 if character.is_ascii_uppercase() && index > 0 {
360 let previous = chars[index - 1];
361 let next_is_lower = chars
362 .get(index + 1)
363 .is_some_and(|next| next.is_ascii_lowercase());
364 if previous.is_ascii_lowercase()
365 || previous.is_ascii_digit()
366 || (previous.is_ascii_uppercase() && next_is_lower)
367 {
368 out.push('-');
369 }
370 }
371 out.extend(character.to_lowercase());
372 }
373 out
374}
375
376fn is_command_name(name: &str) -> bool {
377 !name.is_empty()
378 && !name.starts_with('-')
379 && !name.ends_with('-')
380 && !name.contains("--")
381 && name.chars().all(|character| {
382 character.is_ascii_lowercase() || character.is_ascii_digit() || character == '-'
383 })
384}
385
386fn to_command_name(kind: &str, key: &str) -> Result<String, String> {
387 let name = host_function_command_name(key);
388 if is_command_name(&name) {
389 Ok(name)
390 } else {
391 Err(format!(
392 "{kind} name \"{key}\" must be alphanumeric, written in camelCase or with single hyphen separators"
393 ))
394 }
395}
396
397fn schema_description(input_schema: &serde_json::Value) -> String {
399 input_schema
400 .get("description")
401 .and_then(serde_json::Value::as_str)
402 .unwrap_or_default()
403 .to_string()
404}
405
406pub fn resolve_host_functions(
410 collections: &HostFunctionCollections,
411) -> Result<Vec<ResolvedHostFunctions>, String> {
412 let mut resolved = Vec::with_capacity(collections.len());
413 let mut seen_collections: BTreeMap<String, String> = BTreeMap::new();
414
415 for (collection_key, collection) in collections {
416 let name = to_command_name("Host function collection", collection_key)?;
417 if let Some(collided) = seen_collections.get(&name) {
418 return Err(format!(
419 "Host function collections \"{collided}\" and \"{collection_key}\" both resolve to the command name \"{name}\""
420 ));
421 }
422 seen_collections.insert(name.clone(), collection_key.clone());
423
424 let mut functions = Vec::with_capacity(collection.len());
425 let mut seen_functions: BTreeMap<String, String> = BTreeMap::new();
426 for (function_key, definition) in collection {
427 let function_name = to_command_name("Host function", function_key)?;
428 if let Some(collided) = seen_functions.get(&function_name) {
429 return Err(format!(
430 "Host functions \"{collided}\" and \"{function_key}\" in collection \"{collection_key}\" both resolve to the command name \"{function_name}\""
431 ));
432 }
433 seen_functions.insert(function_name.clone(), function_key.clone());
434 functions.push(ResolvedHostFunction {
435 name: function_name,
436 description: schema_description(&definition.input_schema),
437 input_schema: definition.input_schema.clone(),
438 timeout_ms: definition.timeout_ms,
439 execute: definition.execute.clone(),
440 });
441 }
442
443 resolved.push(ResolvedHostFunctions { name, functions });
444 }
445
446 Ok(resolved)
447}
448
449#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
456#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
457#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
458#[serde(deny_unknown_fields)]
459pub struct AgentOsLimits {
460 #[serde(
461 default,
462 rename = "agentosPackages",
463 skip_serializing_if = "Option::is_none"
464 )]
465 #[cfg_attr(feature = "contract", ts(optional))]
466 pub agentos_packages: Option<AgentOsPackageLimits>,
467 #[serde(default, skip_serializing_if = "Option::is_none")]
468 pub resources: Option<ResourceLimits>,
469 #[serde(default, skip_serializing_if = "Option::is_none")]
470 pub http: Option<HttpLimits>,
471 #[serde(default, skip_serializing_if = "Option::is_none")]
472 #[cfg_attr(feature = "contract", ts(optional))]
473 pub tls: Option<TlsLimits>,
474 #[serde(
475 default,
476 rename = "hostFunctions",
477 skip_serializing_if = "Option::is_none"
478 )]
479 pub host_functions: Option<HostFunctionLimits>,
480 #[serde(default, skip_serializing_if = "Option::is_none")]
481 pub plugins: Option<PluginLimits>,
482 #[serde(default, skip_serializing_if = "Option::is_none")]
483 pub sqlite: Option<SqliteLimits>,
484 #[serde(default, rename = "jsRuntime", skip_serializing_if = "Option::is_none")]
485 pub js_runtime: Option<JsRuntimeLimits>,
486 #[serde(default, skip_serializing_if = "Option::is_none")]
487 pub python: Option<PythonLimits>,
488 #[serde(default, skip_serializing_if = "Option::is_none")]
489 pub wasm: Option<WasmLimits>,
490 #[serde(default, skip_serializing_if = "Option::is_none")]
491 #[cfg_attr(feature = "contract", ts(optional))]
492 pub execution: Option<ExecutionLimits>,
493 #[serde(default, skip_serializing_if = "Option::is_none")]
494 pub process: Option<ProcessLimits>,
495}
496
497#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
498#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
499#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
500#[serde(rename_all = "camelCase", deny_unknown_fields)]
501pub struct AgentOsPackageLimits {
502 #[serde(default, skip_serializing_if = "Option::is_none")]
503 #[cfg_attr(feature = "contract", ts(optional))]
504 pub max_mounts: Option<u64>,
505}
506
507#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
508#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
509#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
510#[serde(deny_unknown_fields)]
511pub struct ResourceLimits {
512 #[serde(default, rename = "cpuCount", skip_serializing_if = "Option::is_none")]
513 pub cpu_count: Option<u64>,
514 #[serde(
515 default,
516 rename = "maxProcesses",
517 skip_serializing_if = "Option::is_none"
518 )]
519 pub max_processes: Option<u64>,
520 #[serde(
521 default,
522 rename = "maxOpenFds",
523 skip_serializing_if = "Option::is_none"
524 )]
525 pub max_open_fds: Option<u64>,
526 #[serde(default, rename = "maxPipes", skip_serializing_if = "Option::is_none")]
527 pub max_pipes: Option<u64>,
528 #[serde(default, rename = "maxPtys", skip_serializing_if = "Option::is_none")]
529 pub max_ptys: Option<u64>,
530 #[serde(
531 default,
532 rename = "maxSockets",
533 skip_serializing_if = "Option::is_none"
534 )]
535 pub max_sockets: Option<u64>,
536 #[serde(
537 default,
538 rename = "maxConnections",
539 skip_serializing_if = "Option::is_none"
540 )]
541 pub max_connections: Option<u64>,
542 #[serde(
543 default,
544 rename = "maxSocketBufferedBytes",
545 skip_serializing_if = "Option::is_none"
546 )]
547 pub max_socket_buffered_bytes: Option<u64>,
548 #[serde(
549 default,
550 rename = "maxSocketDatagramQueueLen",
551 skip_serializing_if = "Option::is_none"
552 )]
553 pub max_socket_datagram_queue_len: Option<u64>,
554 #[serde(
555 default,
556 rename = "maxFilesystemBytes",
557 skip_serializing_if = "Option::is_none"
558 )]
559 pub max_filesystem_bytes: Option<u64>,
560 #[serde(
561 default,
562 rename = "maxInodeCount",
563 skip_serializing_if = "Option::is_none"
564 )]
565 pub max_inode_count: Option<u64>,
566 #[serde(
567 default,
568 rename = "maxBlockingReadMs",
569 skip_serializing_if = "Option::is_none"
570 )]
571 pub max_blocking_read_ms: Option<u64>,
572 #[serde(
573 default,
574 rename = "maxPreadBytes",
575 skip_serializing_if = "Option::is_none"
576 )]
577 pub max_pread_bytes: Option<u64>,
578 #[serde(
579 default,
580 rename = "maxFdWriteBytes",
581 skip_serializing_if = "Option::is_none"
582 )]
583 pub max_fd_write_bytes: Option<u64>,
584 #[serde(
585 default,
586 rename = "maxProcessArgvBytes",
587 skip_serializing_if = "Option::is_none"
588 )]
589 pub max_process_argv_bytes: Option<u64>,
590 #[serde(
591 default,
592 rename = "maxProcessEnvBytes",
593 skip_serializing_if = "Option::is_none"
594 )]
595 pub max_process_env_bytes: Option<u64>,
596 #[serde(
597 default,
598 rename = "maxReaddirEntries",
599 skip_serializing_if = "Option::is_none"
600 )]
601 pub max_readdir_entries: Option<u64>,
602 #[serde(
603 default,
604 rename = "maxWasmFuel",
605 skip_serializing_if = "Option::is_none"
606 )]
607 pub max_wasm_fuel: Option<u64>,
608 #[serde(
609 default,
610 rename = "maxWasmMemoryBytes",
611 skip_serializing_if = "Option::is_none"
612 )]
613 pub max_wasm_memory_bytes: Option<u64>,
614 #[serde(
615 default,
616 rename = "maxWasmStackBytes",
617 skip_serializing_if = "Option::is_none"
618 )]
619 pub max_wasm_stack_bytes: Option<u64>,
620}
621
622#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
623#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
624#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
625#[serde(deny_unknown_fields)]
626pub struct HttpLimits {
627 #[serde(
628 default,
629 rename = "maxFetchResponseBytes",
630 skip_serializing_if = "Option::is_none"
631 )]
632 pub max_fetch_response_bytes: Option<u64>,
633}
634
635#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
637#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
638#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
639#[serde(rename_all = "camelCase", deny_unknown_fields)]
640pub struct TlsLimits {
641 #[serde(default, skip_serializing_if = "Option::is_none")]
642 #[cfg_attr(feature = "contract", ts(optional))]
643 pub max_buffered_bytes: Option<u64>,
644}
645
646#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
648#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
649#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
650#[serde(rename_all = "camelCase", deny_unknown_fields)]
651pub struct ExecutionLimits {
652 #[serde(default, skip_serializing_if = "Option::is_none")]
653 #[cfg_attr(feature = "contract", ts(optional))]
654 pub completed_ttl_ms: Option<u64>,
655 #[serde(default, skip_serializing_if = "Option::is_none")]
656 #[cfg_attr(feature = "contract", ts(optional))]
657 pub max_completed_executions: Option<u64>,
658 #[serde(default, skip_serializing_if = "Option::is_none")]
659 #[cfg_attr(feature = "contract", ts(optional))]
660 pub live_execution_warning_threshold: Option<u64>,
661}
662
663#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
664#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
665#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
666#[serde(deny_unknown_fields)]
667pub struct HostFunctionLimits {
668 #[serde(
669 default,
670 rename = "defaultTimeoutMs",
671 skip_serializing_if = "Option::is_none"
672 )]
673 pub default_timeout_ms: Option<u64>,
674 #[serde(
675 default,
676 rename = "maxTimeoutMs",
677 skip_serializing_if = "Option::is_none"
678 )]
679 pub max_timeout_ms: Option<u64>,
680 #[serde(
681 default,
682 rename = "maxRegisteredCollections",
683 skip_serializing_if = "Option::is_none"
684 )]
685 pub max_registered_collections: Option<u64>,
686 #[serde(
687 default,
688 rename = "maxRegisteredFunctionsPerVm",
689 skip_serializing_if = "Option::is_none"
690 )]
691 pub max_registered_functions_per_vm: Option<u64>,
692 #[serde(
693 default,
694 rename = "maxFunctionsPerCollection",
695 skip_serializing_if = "Option::is_none"
696 )]
697 pub max_functions_per_collection: Option<u64>,
698 #[serde(
699 default,
700 rename = "maxSchemaBytes",
701 skip_serializing_if = "Option::is_none"
702 )]
703 pub max_schema_bytes: Option<u64>,
704 #[serde(
705 default,
706 rename = "maxExamplesPerFunction",
707 skip_serializing_if = "Option::is_none"
708 )]
709 pub max_examples_per_function: Option<u64>,
710 #[serde(
711 default,
712 rename = "maxExampleInputBytes",
713 skip_serializing_if = "Option::is_none"
714 )]
715 pub max_example_input_bytes: Option<u64>,
716}
717
718#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
719#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
720#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
721#[serde(deny_unknown_fields)]
722pub struct PluginLimits {
723 #[serde(
724 default,
725 rename = "maxPersistedManifestBytes",
726 skip_serializing_if = "Option::is_none"
727 )]
728 pub max_persisted_manifest_bytes: Option<u64>,
729 #[serde(
730 default,
731 rename = "maxPersistedManifestFileBytes",
732 skip_serializing_if = "Option::is_none"
733 )]
734 pub max_persisted_manifest_file_bytes: Option<u64>,
735}
736
737#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
738#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
739#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
740#[serde(deny_unknown_fields)]
741pub struct SqliteLimits {
742 #[serde(
743 default,
744 rename = "maxResultBytes",
745 skip_serializing_if = "Option::is_none"
746 )]
747 pub max_result_bytes: Option<u64>,
748}
749
750#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
751#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
752#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
753#[serde(deny_unknown_fields)]
754pub struct JsRuntimeLimits {
755 #[serde(
756 default,
757 rename = "v8HeapLimitMb",
758 skip_serializing_if = "Option::is_none"
759 )]
760 pub v8_heap_limit_mb: Option<u64>,
761 #[serde(
762 default,
763 rename = "syncRpcWaitTimeoutMs",
764 skip_serializing_if = "Option::is_none"
765 )]
766 pub sync_rpc_wait_timeout_ms: Option<u64>,
767 #[serde(
768 default,
769 rename = "cpuTimeLimitMs",
770 skip_serializing_if = "Option::is_none"
771 )]
772 pub cpu_time_limit_ms: Option<u64>,
773 #[serde(
774 default,
775 rename = "wallClockLimitMs",
776 skip_serializing_if = "Option::is_none"
777 )]
778 pub wall_clock_limit_ms: Option<u64>,
779 #[serde(
780 default,
781 rename = "importCacheMaterializeTimeoutMs",
782 skip_serializing_if = "Option::is_none"
783 )]
784 pub import_cache_materialize_timeout_ms: Option<u64>,
785 #[serde(
786 default,
787 rename = "capturedOutputLimitBytes",
788 skip_serializing_if = "Option::is_none"
789 )]
790 pub captured_output_limit_bytes: Option<u64>,
791 #[serde(
792 default,
793 rename = "stdinBufferLimitBytes",
794 skip_serializing_if = "Option::is_none"
795 )]
796 pub stdin_buffer_limit_bytes: Option<u64>,
797 #[serde(
798 default,
799 rename = "eventPayloadLimitBytes",
800 skip_serializing_if = "Option::is_none"
801 )]
802 pub event_payload_limit_bytes: Option<u64>,
803 #[serde(
804 default,
805 rename = "v8IpcMaxFrameBytes",
806 skip_serializing_if = "Option::is_none"
807 )]
808 pub v8_ipc_max_frame_bytes: Option<u64>,
809}
810
811#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
812#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
813#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
814#[serde(deny_unknown_fields)]
815pub struct PythonLimits {
816 #[serde(
817 default,
818 rename = "outputBufferMaxBytes",
819 skip_serializing_if = "Option::is_none"
820 )]
821 pub output_buffer_max_bytes: Option<u64>,
822 #[serde(
823 default,
824 rename = "executionTimeoutMs",
825 skip_serializing_if = "Option::is_none"
826 )]
827 pub execution_timeout_ms: Option<u64>,
828 #[serde(
829 default,
830 rename = "maxOldSpaceMb",
831 skip_serializing_if = "Option::is_none"
832 )]
833 pub max_old_space_mb: Option<u64>,
834 #[serde(
835 default,
836 rename = "vfsRpcTimeoutMs",
837 skip_serializing_if = "Option::is_none"
838 )]
839 pub vfs_rpc_timeout_ms: Option<u64>,
840}
841
842#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
843#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
844#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
845#[serde(deny_unknown_fields)]
846pub struct WasmLimits {
847 #[serde(
848 default,
849 rename = "maxModuleFileBytes",
850 skip_serializing_if = "Option::is_none"
851 )]
852 pub max_module_file_bytes: Option<u64>,
853 #[serde(
854 default,
855 rename = "capturedOutputLimitBytes",
856 skip_serializing_if = "Option::is_none"
857 )]
858 pub captured_output_limit_bytes: Option<u64>,
859 #[serde(
860 default,
861 rename = "syncReadLimitBytes",
862 skip_serializing_if = "Option::is_none"
863 )]
864 pub sync_read_limit_bytes: Option<u64>,
865 #[serde(
866 default,
867 rename = "prewarmTimeoutMs",
868 skip_serializing_if = "Option::is_none"
869 )]
870 pub prewarm_timeout_ms: Option<u64>,
871 #[serde(
872 default,
873 rename = "runnerHeapLimitMb",
874 skip_serializing_if = "Option::is_none"
875 )]
876 pub runner_heap_limit_mb: Option<u64>,
877 #[serde(
878 default,
879 rename = "runnerCpuTimeLimitMs",
880 skip_serializing_if = "Option::is_none"
881 )]
882 pub runner_cpu_time_limit_ms: Option<u64>,
883}
884
885#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
886#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
887#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
888#[serde(deny_unknown_fields)]
889pub struct ProcessLimits {
890 #[serde(
891 default,
892 rename = "maxSpawnFileActions",
893 skip_serializing_if = "Option::is_none"
894 )]
895 pub max_spawn_file_actions: Option<u64>,
896 #[serde(
897 default,
898 rename = "maxSpawnFileActionBytes",
899 skip_serializing_if = "Option::is_none"
900 )]
901 pub max_spawn_file_action_bytes: Option<u64>,
902 #[serde(
903 default,
904 rename = "pendingStdinBytes",
905 skip_serializing_if = "Option::is_none"
906 )]
907 pub pending_stdin_bytes: Option<u64>,
908 #[serde(
909 default,
910 rename = "pendingEventCount",
911 skip_serializing_if = "Option::is_none"
912 )]
913 pub pending_event_count: Option<u64>,
914 #[serde(
915 default,
916 rename = "pendingEventBytes",
917 skip_serializing_if = "Option::is_none"
918 )]
919 pub pending_event_bytes: Option<u64>,
920}
921
922#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
928#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
929#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
930#[serde(deny_unknown_fields)]
931pub struct Permissions {
932 #[serde(default, skip_serializing_if = "Option::is_none")]
933 pub fs: Option<FsPermissions>,
934 #[serde(default, skip_serializing_if = "Option::is_none")]
935 pub network: Option<PatternPermissions>,
936 #[serde(
937 default,
938 rename = "childProcess",
939 skip_serializing_if = "Option::is_none"
940 )]
941 pub child_process: Option<PatternPermissions>,
942 #[serde(default, skip_serializing_if = "Option::is_none")]
943 pub process: Option<PatternPermissions>,
944 #[serde(default, skip_serializing_if = "Option::is_none")]
945 pub env: Option<PatternPermissions>,
946 #[serde(
947 default,
948 rename = "hostFunction",
949 skip_serializing_if = "Option::is_none"
950 )]
951 pub host_function: Option<PatternPermissions>,
952}
953
954#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
956#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
957#[serde(rename_all = "lowercase")]
958pub enum PermissionMode {
959 Allow,
960 Deny,
961}
962
963#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
965#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
966#[serde(untagged)]
967pub enum FsPermissions {
968 Mode(PermissionMode),
969 Rules(RulePermissions<FsPermissionRule>),
970}
971
972#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
974#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
975#[serde(untagged)]
976pub enum PatternPermissions {
977 Mode(PermissionMode),
978 Rules(RulePermissions<PatternPermissionRule>),
979}
980
981#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
983#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
984#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
985#[serde(deny_unknown_fields)]
986pub struct RulePermissions<T> {
987 #[serde(default, skip_serializing_if = "Option::is_none")]
988 pub default: Option<PermissionMode>,
989 pub rules: Vec<T>,
990}
991
992#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
994#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
995#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
996#[serde(deny_unknown_fields)]
997pub struct FsPermissionRule {
998 pub mode: PermissionMode,
999 #[serde(default, skip_serializing_if = "Option::is_none")]
1000 pub operations: Option<Vec<String>>,
1001 #[serde(default, skip_serializing_if = "Option::is_none")]
1002 pub paths: Option<Vec<String>>,
1003}
1004
1005#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
1007#[cfg_attr(feature = "contract", ts(rename_all = "camelCase"))]
1008#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1009#[serde(deny_unknown_fields)]
1010pub struct PatternPermissionRule {
1011 pub mode: PermissionMode,
1012 #[serde(default, skip_serializing_if = "Option::is_none")]
1013 pub operations: Option<Vec<String>>,
1014 #[serde(default, skip_serializing_if = "Option::is_none")]
1015 pub patterns: Option<Vec<String>>,
1016}
1017
1018#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
1024#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1025pub struct RootFilesystemConfig {
1026 #[serde(default, rename = "type")]
1027 pub kind: RootFilesystemKind,
1028 #[serde(default, skip_serializing_if = "Option::is_none")]
1029 pub mode: Option<RootFilesystemMode>,
1030 #[serde(
1031 default,
1032 rename = "nativePlugin",
1033 skip_serializing_if = "Option::is_none"
1034 )]
1035 pub native_plugin: Option<MountPlugin>,
1036 #[serde(default, rename = "disableDefaultBaseLayer")]
1037 pub disable_default_base_layer: bool,
1038 #[serde(default)]
1039 pub lowers: Vec<RootLowerInput>,
1040}
1041
1042impl Default for RootFilesystemConfig {
1043 fn default() -> Self {
1044 Self {
1045 kind: RootFilesystemKind::Overlay,
1046 mode: None,
1047 native_plugin: None,
1048 disable_default_base_layer: false,
1049 lowers: Vec::new(),
1050 }
1051 }
1052}
1053
1054#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
1056#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1057#[serde(rename_all = "lowercase")]
1058pub enum RootFilesystemKind {
1059 #[default]
1060 Overlay,
1061 Native,
1062}
1063
1064#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
1066#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1067#[serde(rename_all = "kebab-case")]
1068pub enum RootFilesystemMode {
1069 Ephemeral,
1070 ReadOnly,
1071}
1072
1073#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
1075#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1076#[serde(tag = "kind", rename_all = "kebab-case")]
1077pub enum RootLowerInput {
1078 BundledBaseFilesystem,
1080 #[serde(untagged)]
1082 SnapshotExport(crate::fs::RootSnapshotExport),
1083}
1084
1085pub enum MountConfig {
1091 Plain {
1093 path: String,
1094 driver: Arc<dyn VirtualFileSystem>,
1095 guest_source: Option<String>,
1096 guest_fstype: Option<String>,
1097 read_only: bool,
1098 },
1099 Native {
1101 path: String,
1102 plugin: MountPlugin,
1103 guest_source: Option<String>,
1104 guest_fstype: Option<String>,
1105 read_only: bool,
1106 },
1107 Overlay {
1109 path: String,
1110 filesystem: OverlayMountConfig,
1111 },
1112}
1113
1114#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
1116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1117pub struct MountPlugin {
1118 pub id: String,
1119 #[serde(default, skip_serializing_if = "Option::is_none")]
1120 pub config: Option<serde_json::Value>,
1121}
1122
1123pub fn node_modules_mount(host_node_modules_dir: impl Into<String>) -> MountConfig {
1131 MountConfig::Native {
1132 path: "/root/node_modules".to_string(),
1133 plugin: MountPlugin {
1134 id: "host_dir".to_string(),
1135 config: Some(serde_json::json!({
1136 "hostPath": host_node_modules_dir.into(),
1137 "readOnly": true,
1138 })),
1139 },
1140 guest_source: Some(String::from("host_dir")),
1141 guest_fstype: Some(String::from("host_dir")),
1142 read_only: true,
1143 }
1144}
1145
1146#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
1148#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1149pub struct OverlayMountConfig {
1150 #[serde(rename = "type")]
1151 pub kind: String,
1152 pub store: serde_json::Value,
1153 #[serde(default, skip_serializing_if = "Option::is_none")]
1154 pub mode: Option<RootFilesystemMode>,
1155 pub lowers: Vec<RootLowerInput>,
1156}
1157
1158pub enum AgentOsSidecarConfig {
1164 Shared { pool: Option<String> },
1166 Explicit {
1168 handle: Arc<crate::sidecar::AgentOsSidecar>,
1169 },
1170}
1171
1172pub type ScheduleCallback = Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>;
1182
1183#[derive(Clone)]
1186pub struct ScheduleEntry {
1187 pub id: String,
1189 pub schedule: String,
1191 pub callback: ScheduleCallback,
1193}
1194
1195pub trait ScheduleDriver: Send + Sync {
1201 fn schedule(&self, entry: ScheduleEntry) -> ScheduleHandle;
1204
1205 fn cancel(&self, handle: &ScheduleHandle);
1207
1208 fn dispose(&self);
1210}
1211
1212#[derive(Clone)]
1215pub struct ScheduleHandle {
1216 pub id: String,
1217}
1218
1219#[derive(Default)]
1226pub struct TimerScheduleDriver {
1227 timers: Arc<scc::HashMap<String, tokio_util::sync::CancellationToken>>,
1228}
1229
1230impl TimerScheduleDriver {
1231 pub fn new() -> Self {
1232 Self {
1233 timers: Arc::new(scc::HashMap::new()),
1234 }
1235 }
1236
1237 fn schedule_next(
1241 timers: Arc<scc::HashMap<String, tokio_util::sync::CancellationToken>>,
1242 entry: ScheduleEntry,
1243 cancel: tokio_util::sync::CancellationToken,
1244 ) {
1245 let now = chrono::Utc::now();
1246 let parsed = match crate::cron::parse_schedule(&entry.schedule) {
1247 Ok(parsed) => parsed,
1248 Err(_) => {
1249 let _ = timers.remove(&entry.id);
1250 return;
1251 }
1252 };
1253 let is_cron = parsed.is_cron();
1254 let next = match crate::cron::resolve_next_run(&parsed, now) {
1255 Some(next) => next,
1256 None => {
1257 let _ = timers.remove(&entry.id);
1259 return;
1260 }
1261 };
1262
1263 let delay = (next - now).to_std().unwrap_or(std::time::Duration::ZERO);
1264
1265 tokio::spawn(async move {
1266 tokio::select! {
1267 _ = cancel.cancelled() => {
1268 return;
1269 }
1270 _ = tokio::time::sleep(delay) => {}
1271 }
1272 if cancel.is_cancelled() {
1273 return;
1274 }
1275 (entry.callback)().await;
1277
1278 if is_cron && timers.contains(&entry.id) {
1279 Self::schedule_next(Arc::clone(&timers), entry, cancel);
1280 } else {
1281 let _ = timers.remove(&entry.id);
1282 }
1283 });
1284 }
1285}
1286
1287impl ScheduleDriver for TimerScheduleDriver {
1288 fn schedule(&self, entry: ScheduleEntry) -> ScheduleHandle {
1289 let id = entry.id.clone();
1290 let cancel = tokio_util::sync::CancellationToken::new();
1291 if let Some((_, old)) = self.timers.remove(&id) {
1293 old.cancel();
1294 }
1295 let _ = self.timers.insert(id.clone(), cancel.clone());
1296
1297 Self::schedule_next(Arc::clone(&self.timers), entry, cancel);
1298
1299 ScheduleHandle { id }
1300 }
1301
1302 fn cancel(&self, handle: &ScheduleHandle) {
1303 if let Some((_, cancel)) = self.timers.remove(&handle.id) {
1304 cancel.cancel();
1305 }
1306 }
1307
1308 fn dispose(&self) {
1309 self.timers.scan(|_, cancel| cancel.cancel());
1310 self.timers.clear();
1311 }
1312}