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