Skip to main content

agentos_client/
lib.rs

1#![forbid(unsafe_code)]
2
3//! # agentos-client
4//!
5//! High-level Rust client SDK for the Agent OS native sidecar. This is a 1:1 port of the TypeScript
6//! `AgentOs` client (`packages/core/src/agent-os.ts`): every public method, option type, return
7//! type, event, and error maps across with identical semantics.
8//!
9//! The client spawns the native `agentos-native-sidecar` binary and speaks the framed BARE
10//! protocol over its stdio (see [`transport`]). It does NOT embed the kernel in-process and does NOT
11//! define a new sidecar wire protocol. The generated agentOS language execution schema surface comes
12//! from `agentos_sidecar_client::wire`.
13//!
14//! See the companion design docs in `~/.agents/specs/rust-client-sdk/` (ADR-001, spec, reference,
15//! checklist) for the architecture, type-mapping, error taxonomy, and streaming model.
16
17pub mod agent_os;
18pub(crate) mod command_line;
19pub mod config;
20pub mod cron;
21pub mod error;
22pub mod fs;
23pub mod language_execution;
24pub mod net;
25mod output_replay;
26pub mod process;
27pub mod sidecar;
28pub mod software;
29pub mod stream;
30pub mod transport;
31
32/// Same-version managed service integration, deliberately excluded from the
33/// default public Core SDK. This keeps config projection/transport access out
34/// of adapters without adding an unmatched public `AgentOs` method.
35#[cfg(feature = "service-internals")]
36#[doc(hidden)]
37pub mod service_internals {
38    /// Create a VM and install its required package set before returning it to
39    /// a managed service. A failed install tears the partially booted VM down,
40    /// so service adapters do not need to duplicate boot rollback logic.
41    pub async fn create_with_initial_software(
42        options: crate::AgentOsConfig,
43        sources: Vec<crate::PackageSource>,
44    ) -> Result<(crate::AgentOs, Vec<crate::InstalledSoftware>), crate::ClientError> {
45        let vm = crate::AgentOs::create(options).await?;
46        let mut installed = Vec::with_capacity(sources.len());
47        for source in sources {
48            match vm.install_software(source).await {
49                Ok(package) => installed.push(package),
50                Err(error) => {
51                    return match vm.shutdown().await {
52                        Ok(()) => Err(error),
53                        Err(cleanup_error) => Err(crate::ClientError::Sidecar(format!(
54                            "initial software installation failed: {error}; VM cleanup also failed: {cleanup_error}"
55                        ))),
56                    };
57                }
58            }
59        }
60        Ok((vm, installed))
61    }
62
63    /// Worker shutdown owns the entire child, including failed VM leases.
64    pub async fn shutdown_package_session(
65        session: &crate::AgentOsPackageSession,
66    ) -> Result<(), crate::ClientError> {
67        session.shutdown_worker().await
68    }
69
70    /// Compare only the VM config document, not runtime kind or ConfigureVm
71    /// fields. The actor fixes its runtime kind and separately classifies
72    /// hosted filesystem/software fields and any fields absent from this projection.
73    pub async fn vm_config_equivalent(
74        vm: &crate::AgentOs,
75        before: &crate::AgentOsConfig,
76        after: &crate::AgentOsConfig,
77        before_restart_identity: Vec<String>,
78        after_restart_identity: Vec<String>,
79    ) -> Result<bool, crate::ClientError> {
80        vm.vm_config_equivalent(
81            before,
82            after,
83            before_restart_identity,
84            after_restart_identity,
85        )
86        .await
87    }
88}
89
90/// Same-version sidecar bridge while the resolver still lives in this crate.
91/// Removed when package acquisition/cache ownership moves out of Core.
92#[cfg(feature = "sidecar-internals")]
93#[doc(hidden)]
94pub mod sidecar_internals {
95    pub fn package_acquisition_timeout_ms(resolver: &crate::PackageResolver) -> u64 {
96        resolver.acquisition_timeout_ms()
97    }
98}
99
100// ---------------------------------------------------------------------------
101// Centralized constants (ADR-001 §6 / spec.md §7)
102// ---------------------------------------------------------------------------
103
104/// Bounded exited-shell exit-code retention (for `wait_shell` after exit).
105pub const CLOSED_SHELL_EXIT_CODE_RETENTION_LIMIT: usize = 2048;
106
107/// Two-phase shell-drain timeout during dispose (milliseconds).
108pub const SHELL_DISPOSE_TIMEOUT_MS: u64 = 5_000;
109
110/// VM lifecycle ready timeout during `create` (milliseconds).
111pub const VM_READY_TIMEOUT_MS: u64 = 10_000;
112
113/// Maximum scheduled cron jobs per VM.
114pub const CRON_JOB_LIMIT: usize = 1024;
115
116// ---------------------------------------------------------------------------
117// Public re-exports
118// ---------------------------------------------------------------------------
119
120pub use agent_os::{AgentOs, PackageDescriptor, SoftwareInfo};
121pub use error::{ClientError, ClientResult, ResourceLimitDetails};
122pub use language_execution::{
123    CodeEvaluationResult, CodeExecutionResult, ContextDescriptor, ExecutionPtyOptions,
124    InlineExecutionOptions, JavaScriptExecutionOptions, JavaScriptModuleFormat,
125    LanguageExecutionOptions, LanguageSpawnOptions, ProcessDescriptor, TypeScriptDiagnostic,
126};
127#[cfg(feature = "sidecar-internals")]
128pub use sidecar::configure_shared_sidecar_package_cache;
129#[cfg(any(feature = "service-internals", feature = "sidecar-internals"))]
130pub use sidecar::AgentOsPackageSession;
131pub use sidecar::{
132    AgentOsSidecar, AgentOsSidecarDescription, AgentOsSidecarPlacement, SidecarState,
133};
134pub use stream::{ByteStream, Subscription};
135
136pub use config::{
137    node_modules_mount, AgentOsConfig, AgentOsConfigBuilder, AgentOsLimits, AgentOsPackageLimits,
138    AgentOsSidecarConfig, ExecutionLimits, FsPermissionRule, FsPermissions, HostFunction,
139    HostFunctionCallback, HostFunctionCollection, HostFunctionCollections, HostFunctionLimits,
140    HttpLimits, JsRuntimeLimits, MountConfig, MountPlugin, OverlayMountConfig, PackageRef,
141    PatternPermissionRule, PatternPermissions, PermissionMode, Permissions, PluginLimits,
142    PythonLimits, ResourceLimits, RootFilesystemConfig, RootFilesystemKind, RootFilesystemMode,
143    RootLowerInput, RulePermissions, ScheduleCallback, ScheduleDriver, ScheduleEntry,
144    ScheduleHandle, SidecarJsBridgeCall, SidecarJsBridgeCallback, SidecarSqliteCallback,
145    SoftwareInput, SoftwareKind, TimerScheduleDriver, TlsLimits, VmGroupConfig,
146    VmSqliteCallbackRequest, VmSqliteCallbackResponse, VmSqliteDescriptor, VmSqliteQueryResult,
147    VmSqliteStatement, VmSqliteValue, VmUserAccountConfig, VmUserConfig, WasmLimits,
148    VM_SQLITE_CALLBACK_NAMESPACE,
149};
150
151pub use process::{
152    ExecOptions, ExecResult, ProcessExit, ProcessInfo, ProcessOutput, ProcessOutputEvent,
153    ProcessOutputReplay, ProcessStatus, ProcessStream, ProcessTreeNode, SpawnHandle, SpawnOptions,
154    SpawnStdio, SpawnedProcessInfo, StdinInput, TimingMitigation,
155};
156
157pub use net::{HttpRequest, HttpResponse, HttpStreamChunk, HttpStreamHead};
158
159pub use software::{
160    configure_process_package_cache, process_package_cache_stats, validate_package_source,
161    InstalledSoftware, PackageManifestInfo, PackageResolver, PackageResolverOptions, PackageSource,
162    ProcessPackageCacheOptions, ProcessPackageCacheStats, VerifiedPackage,
163    DEFAULT_MAX_PACKAGE_BYTES,
164};
165
166pub use fs::{
167    BatchReadResult, BatchWriteEntry, BatchWriteResult, DirEntry, DirEntryType,
168    DynamicMountDescriptor, FileContent, FilesystemEntry, FilesystemEntryEncoding,
169    FilesystemSnapshotEntries, FilesystemSnapshotExport, MkdirOptions, MountInfo,
170    ReaddirRecursiveOptions, RemoveOptions, RootSnapshotExport, SnapshotExportKind,
171    VirtualDirEntry, VirtualFileSystem, VirtualStat,
172};
173
174pub use shell::{
175    ConnectTerminalOptions, OpenShellOptions, ShellData, ShellExit, ShellHandle, TerminalInfo,
176    TerminalOutputEvent, TerminalSnapshot,
177};
178
179pub use cron::{
180    CronAction, CronActionInfo, CronEvent, CronJobHandle, CronJobInfo, CronJobOptions, CronManager,
181    CronOverlap,
182};
183
184// `shell` is declared here because its methods live in a sibling module to keep `lib.rs` re-exports
185// flat; the module file itself is `shell.rs`.
186pub mod shell;