Skip to main content

agentos_client/
config.rs

1//! Configuration types: `AgentOsConfig` (= TS `AgentOsOptions`), the permissions tree, root
2//! filesystem config, mount config, and the schedule-driver abstraction.
3//!
4//! Ported from `packages/core/src/agent-os.ts` (`AgentOsOptions`), `runtime.ts` (`Permissions`),
5//! `layers.ts` / `overlay-filesystem.ts` (root/overlay), and `cron/` (schedule driver).
6//!
7//! Non-serializable parameters (`MountConfig::Plain.driver`, `CronAction::Callback`) are in-process
8//! only and become `Arc<dyn ...>` trait objects; they cannot cross the wire and are gated exactly as
9//! the actor layer gates them.
10
11use 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/// Resolved client options (= TS `AgentOsOptions`). All fields optional with documented defaults.
32///
33/// Keep this Rust mirror in sync with `packages/core/src/agent-os.ts::AgentOsOptions`
34/// and `packages/core/src/options-schema.ts::agentOsOptionsSchema`.
35#[derive(Default)]
36pub struct AgentOsConfig {
37    /// VM-scoped SQLite backend shared by VFS metadata/storage and agentOS
38    /// durable state.
39    pub database: Option<agentos_vm_config::VmSqliteDescriptor>,
40    /// Trusted callback for [`VmSqliteDescriptor::HostCallback`]. Hosted actors
41    /// use this to execute VM database operations through Rivet SQLite.
42    pub sidecar_sqlite_callback: Option<SidecarSqliteCallback>,
43    /// Initial virtual Linux credentials and account record. Defaults to `1000:1000` (`agentos`).
44    pub user: Option<VmUserConfig>,
45    /// Complete initial VM environment. `None` selects the sidecar's bundled base environment;
46    /// `Some(empty)` deliberately starts with an empty environment.
47    pub environment: Option<BTreeMap<String, String>>,
48    /// Software packages to install (flattened). Default `[]`.
49    pub software: Vec<SoftwareInput>,
50    /// Package directories to project into the VM's `/opt/agentos` tree (the
51    /// agentos package projection). Each entry is a host dir containing an
52    /// `agentos-package.json` manifest + the package payload. Default `[]`.
53    pub packages: Vec<PackageRef>,
54    /// Guest mount point for the package projection. Default `/opt/agentos`
55    /// (agentos's `OPT_AGENTOS_ROOT`) when `None`.
56    pub packages_mount_at: Option<String>,
57    /// Trusted Core package acquisition limits and local-test transport policy.
58    /// Hosted actor callers cannot configure this process-owned policy.
59    pub package_resolver: Option<crate::software::PackageResolverOptions>,
60    /// Registry packages and URL or path sources installed after boot, before
61    /// [`crate::AgentOs::create`] returns (= TS `software` registry and URL
62    /// entries). Registry names resolve before the VM is created. Default `[]`.
63    pub software_sources: Vec<crate::software_registry::SoftwareSource>,
64    /// Where registry sources resolve (= TS `softwareRegistry`). Default:
65    /// `https://releases.rivet.dev/agent-os/` at this client's release.
66    pub software_registry: Option<crate::software_registry::SoftwareRegistryOptions>,
67    /// Loopback ports exempt from the default outbound-to-host block.
68    pub loopback_exempt_ports: Vec<u16>,
69    /// Allowed Node.js builtins. Default: the hardened native-bridge set.
70    pub allowed_node_builtins: Option<Vec<String>>,
71    /// Opt in to a high-resolution monotonic clock for guest JavaScript.
72    /// `None` selects the hardened millisecond-resolution default.
73    pub high_resolution_time: Option<bool>,
74    /// Root filesystem configuration. Default: overlay + bundled base snapshot.
75    pub root_filesystem: RootFilesystemConfig,
76    /// Additional mounts.
77    pub mounts: Vec<MountConfig>,
78    /// Schedule driver used by the cron manager. Default: [`TimerScheduleDriver`].
79    pub schedule_driver: Option<Arc<dyn ScheduleDriver>>,
80    /// Host function collections to register, keyed by collection name.
81    pub host_functions: HostFunctionCollections,
82    /// Rust-only sidecar callback handler for `js_bridge`-style plugin requests.
83    pub sidecar_js_bridge_callback: Option<SidecarJsBridgeCallback>,
84    /// Permission policy. Default: allow-all.
85    pub permissions: Option<Permissions>,
86    /// Operator-tunable VM limits. Default: sidecar/kernel built-ins.
87    pub limits: Option<AgentOsLimits>,
88    /// Sidecar placement/config. Default: shared `default` pool.
89    pub sidecar: Option<AgentOsSidecarConfig>,
90    /// Absolute path to the `agentos-native-sidecar` binary, resolved from the npm
91    /// package on the TypeScript side. Threaded to `SidecarProcess::spawn`
92    /// instead of relying on the
93    /// `AGENTOS_SIDECAR_BIN` env var. `None` falls back to env, then `PATH`.
94    pub sidecar_binary_path: Option<String>,
95}
96
97/// Builder for [`AgentOsConfig`].
98#[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    /// Validate the complete VM configuration without starting a sidecar.
226    ///
227    /// Hosted adapters use this to reject invalid creation input before Rivet
228    /// persists actor state. The same serializer is used by [`AgentOs::create`](crate::AgentOs::create),
229    /// so validation cannot drift into an actor-owned copy.
230    pub fn validate(&self) -> Result<(), crate::ClientError> {
231        crate::agent_os::validate_config(self)
232    }
233}
234
235/// The kind of a software package, which decides how it is mounted into the VM. Mirrors the TS
236/// descriptor `type` discriminator (`packages/core/src/packages.ts`).
237#[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    /// A directory of wasm command binaries. Mounted at `/__agentos/commands/{index}/` so the
242    /// sidecar's command discovery can resolve guest commands (`echo`, `sh`, `grep`, ...).
243    #[default]
244    WasmCommands,
245    /// A host-function package. Not mounted as a command directory.
246    HostFunction,
247}
248
249/// A flattened software package input.
250#[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    /// How the package is mounted into the VM. Defaults to [`SoftwareKind::WasmCommands`].
257    #[serde(default)]
258    pub kind: SoftwareKind,
259}
260
261/// A reference to a packed `.aospkg` package for the `/opt/agentos`
262/// projection. A directory path remains accepted for local transition
263/// fixtures.
264#[cfg_attr(feature = "contract", derive(ts_rs::TS))]
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
266pub struct PackageRef {
267    /// Serialized as `packagePath` — the single package-ref spelling on every
268    /// JSON boundary (registry exports, actor config, client config).
269    #[serde(rename = "packagePath")]
270    pub path: String,
271}
272
273/// A host-side host function callback. Receives the validated JSON input, returns a JSON result or an
274/// error string. Stays host-side (never crosses to the guest); the guest invokes it by name via the
275/// sidecar host-callback channel.
276pub 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/// A sidecar-initiated `js_bridge`-style filesystem callback.
285#[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
293/// Host-side handler for sidecar `JsBridgeCallRequest` payloads.
294///
295/// This is Rust-only and intentionally not JSON-serializable. Managed services
296/// use it to bind native sidecar storage to their durable database without
297/// teaching agentOS about the hosting framework.
298pub 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/// A single host function. The key it is registered under names it, and the
308/// input schema's `description` documents it for the agent.
309#[derive(Clone)]
310pub struct HostFunction {
311    /// JSON Schema for the host function input (forwarded to the sidecar `register_host_callbacks` definition).
312    pub input_schema: serde_json::Value,
313    pub timeout_ms: Option<u64>,
314    /// Host-side implementation, invoked when the guest calls `<collection>:<function>`.
315    pub execute: HostFunctionCallback,
316}
317
318/// One collection of host functions, keyed by function name. Each key becomes a
319/// subcommand of the collection's CLI binary and a method on its guest global.
320pub type HostFunctionCollection = BTreeMap<String, HostFunction>;
321
322/// Host function collections, keyed by collection name (in-process;
323/// implementations stay host-side). Each key becomes the CLI binary
324/// `agentos-{name}` and a frozen guest global; functions are exposed to the
325/// guest as `<collection>:<function>` and dispatched back to
326/// [`HostFunction::execute`] via the sidecar host-callback channel.
327pub type HostFunctionCollections = BTreeMap<String, HostFunctionCollection>;
328
329/// A host function resolved to the names the VM uses.
330#[derive(Clone)]
331pub struct ResolvedHostFunction {
332    /// Kebab-case command name. Becomes the CLI subcommand.
333    pub name: String,
334    /// Taken from the input schema's `description`.
335    pub description: String,
336    pub input_schema: serde_json::Value,
337    pub timeout_ms: Option<u64>,
338    pub execute: HostFunctionCallback,
339}
340
341/// A collection resolved to the names the VM uses. Keys arrive as identifiers
342/// and are converted once here, so the rest of the client and the sidecar only
343/// ever see kebab-case command names.
344#[derive(Clone)]
345pub struct ResolvedHostFunctions {
346    /// Kebab-case collection name. Becomes the CLI suffix: `agentos-{name}`.
347    pub name: String,
348    pub functions: Vec<ResolvedHostFunction>,
349}
350
351/// Convert a registration key to its command name. `listOrders` and
352/// `list-orders` both become `list-orders`, so the guest sees one spelling
353/// whichever the caller wrote. Mirrors `hostFunctionCommandName` in the
354/// TypeScript client.
355pub 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
397/// The description the agent sees, taken from the input schema's `description`.
398fn 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
406/// Resolve the caller's collections into the shape the client and sidecar use.
407/// Fails on a key that cannot become a command name, and on two keys that
408/// collide once converted.
409pub 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// ---------------------------------------------------------------------------
450// VM limits (agent-os.ts AgentOsLimits / sidecar/limits.ts)
451// ---------------------------------------------------------------------------
452
453/// Operator-tunable runtime limits for a VM. Every field is optional; unset fields fall back to the
454/// sidecar defaults.
455#[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/// Per-VM TLS plaintext buffering overrides. Omitted fields use sidecar defaults.
636#[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/// Per-VM language-execution retention and warning overrides.
647#[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// ---------------------------------------------------------------------------
923// Permissions tree (runtime.ts)
924// ---------------------------------------------------------------------------
925
926/// Top-level permission policy. All domains optional (`allowAll` when omitted).
927#[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/// `"allow"` or `"deny"`.
955#[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/// `PermissionMode | RulePermissions<FsPermissionRule>`.
964#[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/// `PermissionMode | RulePermissions<PatternPermissionRule>` (network/childProcess/process/env/binding).
973#[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/// `{ default?: PermissionMode; rules: T[] }`.
982#[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/// `{ mode; operations?; paths? }`.
993#[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/// `{ mode; operations?; patterns? }`.
1006#[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// ---------------------------------------------------------------------------
1019// Root filesystem (layers.ts / overlay-filesystem.ts)
1020// ---------------------------------------------------------------------------
1021
1022/// Root filesystem configuration. Default: overlay + bundled base snapshot.
1023#[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/// The root filesystem kind.
1055#[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/// Root filesystem mode.
1065#[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/// A lower (immutable) snapshot layer input.
1074#[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    /// The bundled base filesystem snapshot.
1079    BundledBaseFilesystem,
1080    /// A snapshot export (`{ kind: "snapshot-export", source }`).
1081    #[serde(untagged)]
1082    SnapshotExport(crate::fs::RootSnapshotExport),
1083}
1084
1085// ---------------------------------------------------------------------------
1086// Mounts
1087// ---------------------------------------------------------------------------
1088
1089/// A filesystem mount. `Plain.driver` is an in-process trait object and cannot cross the wire.
1090pub enum MountConfig {
1091    /// Plain mount over an in-process [`VirtualFileSystem`] driver.
1092    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 plugin mount (`{ id; config? }`).
1100    Native {
1101        path: String,
1102        plugin: MountPlugin,
1103        guest_source: Option<String>,
1104        guest_fstype: Option<String>,
1105        read_only: bool,
1106    },
1107    /// Overlay mount (`{ type: "overlay"; store; mode?; lowers }`).
1108    Overlay {
1109        path: String,
1110        filesystem: OverlayMountConfig,
1111    },
1112}
1113
1114/// A native mount plugin descriptor.
1115#[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
1123/// Mount a host `node_modules` directory into the VM at `/root/node_modules`.
1124///
1125/// Rust mirror of TS `nodeModulesMount(...)` (`packages/core/src/host-dir-mount.ts`).
1126/// This is the explicit, mount-based replacement for the removed `moduleAccessCwd`
1127/// option: the guest module resolver reads the mounted tree through the kernel VFS,
1128/// so the caller supplies exactly the `node_modules` directory whose packages should
1129/// be resolvable in the guest. The mount is read-only.
1130pub 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/// Overlay mount filesystem config.
1147#[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
1158// ---------------------------------------------------------------------------
1159// Sidecar config
1160// ---------------------------------------------------------------------------
1161
1162/// How the client obtains its sidecar handle.
1163pub enum AgentOsSidecarConfig {
1164    /// Use (or create) a shared pooled sidecar (`pool` default `"default"`).
1165    Shared { pool: Option<String> },
1166    /// Use an explicit sidecar handle.
1167    Explicit {
1168        handle: Arc<crate::sidecar::AgentOsSidecar>,
1169    },
1170}
1171
1172// ---------------------------------------------------------------------------
1173// Schedule driver
1174// ---------------------------------------------------------------------------
1175
1176/// The callback fired by a [`ScheduleDriver`] when a schedule entry triggers.
1177///
1178/// Mirrors the TS `ScheduleEntry.callback: () => void | Promise<void>`. The cron manager passes a
1179/// closure that runs one job execution; the driver awaits it (and, for the default driver, reschedules
1180/// the next cron fire afterwards).
1181pub type ScheduleCallback = Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>;
1182
1183/// A schedule entry handed to a [`ScheduleDriver`]. Mirrors TS `ScheduleEntry`
1184/// (`cron/schedule-driver.ts`).
1185#[derive(Clone)]
1186pub struct ScheduleEntry {
1187    /// Unique ID for this job.
1188    pub id: String,
1189    /// 5/6/7-field cron expression OR an ISO-8601 one-shot timestamp.
1190    pub schedule: String,
1191    /// Called when the schedule fires.
1192    pub callback: ScheduleCallback,
1193}
1194
1195/// Driver-owned scheduling abstraction. Mirrors the TS `ScheduleDriver` interface
1196/// (`cron/schedule-driver.ts`) exactly: the driver parses the schedule, arms the timer, reschedules
1197/// cron entries after each fire, and tears everything down on [`ScheduleDriver::dispose`]. This is the
1198/// documented extension point: a custom driver (deterministic virtual-time test driver, fire-immediately
1199/// driver, etc.) fully controls timing.
1200pub trait ScheduleDriver: Send + Sync {
1201    /// Schedule a callback to fire on a cron expression or at a specific time. Returns a cancellation
1202    /// handle.
1203    fn schedule(&self, entry: ScheduleEntry) -> ScheduleHandle;
1204
1205    /// Cancel a previously scheduled entry.
1206    fn cancel(&self, handle: &ScheduleHandle);
1207
1208    /// Tear down all scheduled work.
1209    fn dispose(&self);
1210}
1211
1212/// Handle to a scheduled entry. Mirrors TS `ScheduleHandle { id }`. Identifies the entry to cancel via
1213/// [`ScheduleDriver::cancel`].
1214#[derive(Clone)]
1215pub struct ScheduleHandle {
1216    pub id: String,
1217}
1218
1219/// Default schedule driver backed by `tokio` timers and the system clock.
1220///
1221/// Mirrors the TS `TimerScheduleDriver`: for cron expressions it computes the next fire time and arms
1222/// a single timer, rescheduling after each fire; for one-shot timestamps it fires once and removes the
1223/// entry. Driver-held timer tasks are tracked so [`ScheduleDriver::cancel`] / [`ScheduleDriver::dispose`]
1224/// can abort them.
1225#[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    /// Arm the next fire for `entry`. For a one-shot or an exhausted cron the entry is dropped. For a
1238    /// recurring cron the timer reschedules itself after firing the callback. `cancel` is the per-entry
1239    /// cancellation token shared with the registry slot.
1240    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                // No upcoming run (one-shot in the past, or exhausted cron).
1258                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            // The driver is fire-and-forget; errors are the caller's responsibility.
1276            (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        // Replace any existing timer for this id, cancelling it first.
1292        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}