diff --git a/crates/dim-agent-capabilities/examples/host_platform_bubblewrap_spike.rs b/crates/dim-agent-capabilities/examples/host_platform_bubblewrap_spike.rs index 5c99b0d3bc..0efc2d4288 100644 --- a/crates/dim-agent-capabilities/examples/host_platform_bubblewrap_spike.rs +++ b/crates/dim-agent-capabilities/examples/host_platform_bubblewrap_spike.rs @@ -3,7 +3,7 @@ #[cfg(target_os = "linux")] mod linux { use dim_agent_capabilities::host_platform::{ - EXEC_SHELL_UNAVAILABLE, HostPlatform, ProcessSpec, PtySize, ShellStatus, + EXEC_SHELL_UNAVAILABLE, ExecHost, ProcessSpec, PtySize, ShellStatus, }; use serde_json::json; use std::{ @@ -144,7 +144,7 @@ mod linux { spec } - async fn run(platform: &HostPlatform, spec: ProcessSpec) -> Result { + async fn run(platform: &ExecHost, spec: ProcessSpec) -> Result { let mut tree = platform.spawn(spec)?; let (mut stdout, mut stderr) = (tree.stdout(), tree.stderr()); let (mut out, mut err) = (Vec::new(), Vec::new()); @@ -201,7 +201,7 @@ mod linux { std::fs::create_dir(&readonly)?; let helper = readonly.join("probe"); std::fs::copy(std::env::current_exe()?, &helper)?; - let platform = HostPlatform::current(ShellStatus::Unavailable { + let platform = ExecHost::current(ShellStatus::Unavailable { code: EXEC_SHELL_UNAVAILABLE, reason: "Explicit probe argv".into(), })?; @@ -295,7 +295,7 @@ mod linux { let fixture = Fixture(root); let readonly = fixture.0.join("readonly"); std::fs::create_dir(&readonly)?; - let platform = HostPlatform::current(ShellStatus::Unavailable { + let platform = ExecHost::current(ShellStatus::Unavailable { code: EXEC_SHELL_UNAVAILABLE, reason: "Explicit probe argv".into(), })?; @@ -426,7 +426,7 @@ mod linux { } let helper = readonly.join("probe"); std::fs::copy(std::env::current_exe()?, &helper)?; - let platform = HostPlatform::current(ShellStatus::Unavailable { + let platform = ExecHost::current(ShellStatus::Unavailable { code: EXEC_SHELL_UNAVAILABLE, reason: "Explicit probe argv".into(), })?; diff --git a/crates/dim-agent-capabilities/examples/host_platform_isolation_spike.rs b/crates/dim-agent-capabilities/examples/host_platform_isolation_spike.rs index 7d72d7577b..e38598e70a 100644 --- a/crates/dim-agent-capabilities/examples/host_platform_isolation_spike.rs +++ b/crates/dim-agent-capabilities/examples/host_platform_isolation_spike.rs @@ -3,7 +3,7 @@ #[cfg(target_os = "macos")] mod macos { use dim_agent_capabilities::host_platform::{ - EXEC_SHELL_UNAVAILABLE, HostPlatform, ProcessSpec, PtySize, ShellStatus, + EXEC_SHELL_UNAVAILABLE, ExecHost, ProcessSpec, PtySize, ShellStatus, }; use serde_json::json; use std::{ @@ -69,7 +69,7 @@ mod macos { spec } - async fn run(platform: &HostPlatform, spec: ProcessSpec) -> Result { + async fn run(platform: &ExecHost, spec: ProcessSpec) -> Result { let mut tree = platform.spawn(spec)?; let (mut stdout, mut stderr) = (tree.stdout(), tree.stderr()); let (mut out, mut err) = (Vec::new(), Vec::new()); @@ -112,7 +112,7 @@ mod macos { std::fs::write(&secret, "private-sentinel")?; std::fs::write(workspace.join("input"), "workspace-input")?; std::os::unix::fs::symlink(&private, workspace.join("escape"))?; - let platform = HostPlatform::current(ShellStatus::Unavailable { + let platform = ExecHost::current(ShellStatus::Unavailable { code: EXEC_SHELL_UNAVAILABLE, reason: "The probe passes explicit argv.".into(), })?; diff --git a/crates/dim-agent-capabilities/examples/host_platform_landlock_spike.rs b/crates/dim-agent-capabilities/examples/host_platform_landlock_spike.rs index 1158fa4bce..8d65848232 100644 --- a/crates/dim-agent-capabilities/examples/host_platform_landlock_spike.rs +++ b/crates/dim-agent-capabilities/examples/host_platform_landlock_spike.rs @@ -3,7 +3,7 @@ #[cfg(target_os = "linux")] mod linux { use dim_agent_capabilities::host_platform::{ - EXEC_SHELL_UNAVAILABLE, HostPlatform, ProcessSpec, PtySize, ShellStatus, + EXEC_SHELL_UNAVAILABLE, ExecHost, ProcessSpec, PtySize, ShellStatus, }; use serde_json::json; use std::{ @@ -157,7 +157,7 @@ mod linux { spec.args = args; Ok(spec) } - async fn run(platform: &HostPlatform, spec: ProcessSpec) -> Result { + async fn run(platform: &ExecHost, spec: ProcessSpec) -> Result { let mut tree = platform.spawn(spec)?; let (mut stdout, mut stderr) = (tree.stdout(), tree.stderr()); let (mut out, mut err) = (Vec::new(), Vec::new()); @@ -202,7 +202,7 @@ mod linux { std::fs::write(&secret, "private-sentinel")?; std::fs::write(workspace.join("input"), "workspace-input")?; std::os::unix::fs::symlink(&private, workspace.join("escape"))?; - let platform = HostPlatform::current(ShellStatus::Unavailable { + let platform = ExecHost::current(ShellStatus::Unavailable { code: EXEC_SHELL_UNAVAILABLE, reason: "The probe passes explicit argv.".into(), })?; diff --git a/crates/dim-agent-capabilities/src/file_access.rs b/crates/dim-agent-capabilities/src/file_access.rs index c15072e70d..3c5b3d4aba 100644 --- a/crates/dim-agent-capabilities/src/file_access.rs +++ b/crates/dim-agent-capabilities/src/file_access.rs @@ -1,7 +1,7 @@ //! Session file facts and on-demand worktree membership. use crate::{ host::{HostError, HostFuture, SessionFiles}, - host_platform::{HostPlatform, ProcessSpec}, + host_platform::{ExecHost, ProcessSpec}, session_grants::SessionGrantsHost, workspace_tools::files::canonical_prefix, }; @@ -140,7 +140,7 @@ pub fn install(builder: &mut AgentBuilder) { struct Facts { config: Arc, - platform: Arc, + platform_roots: Vec, files: Arc, grants: Arc, worktrees: Arc, @@ -174,7 +174,6 @@ impl ReadFileAccessFacts for Facts { let mut facts = FileFacts { workspace: path.starts_with(&workspace), system: self - .platform .platform_roots .iter() .any(|root| path.starts_with(root)), @@ -214,7 +213,7 @@ impl ReadFileAccessFacts for Facts { struct FileAccessFactsPlugin { config: Key, - platform: Key, + platform: Key, files: Key, grants: Key, identity: Key, @@ -268,7 +267,7 @@ impl DynPlugin for FileAccessFactsPlugin { self.service.clone(), Arc::new(FileAccessFacts(Arc::new(Facts { config, - platform, + platform_roots: platform.facts().platform_roots.to_vec(), files: ctx.require_at(&self.files)?, grants: ctx.require_at(&self.grants)?, worktrees, @@ -308,7 +307,7 @@ struct State { struct Worktrees { ctx: Ctx, - platform: Arc, + platform: Arc, lifecycle: Arc, session: String, workspace: PathBuf, @@ -320,7 +319,7 @@ struct Worktrees { impl Worktrees { fn new( ctx: Ctx, - platform: Arc, + platform: Arc, lifecycle: Arc, session: String, workspace: PathBuf, diff --git a/crates/dim-agent-capabilities/src/hooks/runner.rs b/crates/dim-agent-capabilities/src/hooks/runner.rs index f4e526bc37..b7f56573de 100644 --- a/crates/dim-agent-capabilities/src/hooks/runner.rs +++ b/crates/dim-agent-capabilities/src/hooks/runner.rs @@ -14,7 +14,7 @@ use crate::{ handlers, }, host::{HostError, HostFuture}, - host_platform::{HostPlatform, Os}, + host_platform::{ConfiguredCommand, ConfiguredEnd, ConfiguredError, ExecHost, Os}, input_queue::{CheckSubmission, SubmitCheckReply, SubmitCheckRequest, SubmitChecks}, permission::{AdmissionDecision, AdviseTool, Permission, ToolAdviceReply, ToolAdviceRequest}, tool_registry::ToolRegistry, @@ -43,10 +43,7 @@ use std::{ sync::{Arc, Mutex}, time::{Duration, Instant}, }; -use tokio::{ - io::{AsyncRead, AsyncReadExt}, - sync::mpsc, -}; +use tokio::sync::mpsc; use tokio_util::{sync::CancellationToken, task::TaskTracker}; /// A hook's stdout is bounded; more than this is a failure (A.3). @@ -106,7 +103,7 @@ type PendingRun = Pin + Send>>; /// The Session service that reads the sources and runs commands. pub struct HooksRuntime { sources: Arc, - platform: Arc, + platform: Arc, config: Arc, identity: Arc, cancel: CancellationToken, @@ -383,80 +380,36 @@ impl HooksRuntime { cancel: &CancellationToken, gate: Option<&CancellationToken>, ) -> HookResult { - let command = handler.command(self.platform.os == Os::Windows); + let command = handler.command(self.platform.facts().os == Os::Windows); let started = Instant::now(); - let mut spec = match self - .platform - .build_process_spec(command, Path::new(&self.config.cwd)) - .await - { - Ok((spec, _)) => spec, - Err(error) => { - let result = failed(format!("{}: {}", error.code, error.reason), &[]); - self.report(handler, &result, started.elapsed()); - return result; - } + let request = ConfiguredCommand { + command: command.into(), + cwd: self.config.cwd.clone().into(), + env: self.environment(handler), + stdin, + timeout: handler.timeout, + stdout_limit: STDOUT_LIMIT, + stderr_limit: STDERR_LIMIT, }; - spec.env = hook_env(spec.env, &self.environment(handler)); - if gate.is_some_and(|gate| gate.is_cancelled()) { - return HookResult::Failed { - reason: UNLOADED.into(), - stderr: String::new(), - }; - } - let mut tree = match self.platform.spawn_with_stdin(spec, stdin) { - Ok(tree) => tree, + let result = match self.platform.configured(request, cancel, gate).await { + Err(ConfiguredError::Unloaded) => return unloaded_run(handler).result, Err(error) => { - let result = failed(format!("spawn failed: {error}"), &[]); + let result = failed(error.to_string(), error.stderr()); self.report(handler, &result, started.elapsed()); return result; } - }; - let mut stdout = tree.stdout(); - let mut stderr = tree.stderr(); - enum End { - Done( - (Vec, bool), - (Vec, bool), - std::io::Result, + Ok(ConfiguredEnd::Cancelled) => failed("cancelled", &[]), + Ok(ConfiguredEnd::TimedOut) => failed( + format!("timed out after {}s", handler.timeout.as_secs()), + &[], ), - Cancelled, - TimedOut, - } - let end = tokio::select! { - biased; - _ = cancel.cancelled() => End::Cancelled, - _ = tokio::time::sleep(handler.timeout) => End::TimedOut, - (out, err, status) = async { - tokio::join!( - read_capped(&mut stdout, STDOUT_LIMIT), - read_capped(&mut stderr, STDERR_LIMIT), - tree.wait(), - ) - } => End::Done(out, err, status), - }; - let result = match end { - End::Cancelled => { - let _ = tree.terminate().await; - failed("cancelled", &[]) - } - End::TimedOut => { - let _ = tree.terminate().await; - failed( - format!("timed out after {}s", handler.timeout.as_secs()), - &[], - ) - } - End::Done((bytes, overflow), (stderr, _), status) => { - let status = match status { - Ok(status) => status, - // A run whose end cannot be read still reports (§7). - Err(error) => { - let result = failed(format!("wait failed: {error}"), &stderr); - self.report(handler, &result, started.elapsed()); - return result; - } - }; + Ok(ConfiguredEnd::Exited { + stdout: bytes, + stdout_truncated: overflow, + stderr, + status, + .. + }) => { if overflow { failed("stdout exceeded 64 KiB", &stderr) } else if status.code() == Some(2) { @@ -498,59 +451,36 @@ impl HooksRuntime { ); } - fn environment(&self, handler: &HookHandler) -> Vec<(&'static str, OsString)> { - let mut vars = vec![ - ("DIM_PROJECT_DIR", OsString::from(self.config.cwd.clone())), - ("DIM_HOOK_EVENT", OsString::from(handler.event.name())), + fn environment( + &self, + handler: &HookHandler, + ) -> std::collections::BTreeMap> { + let mut env: std::collections::BTreeMap<_, _> = MANAGED_ENV + .into_iter() + .map(|key| (OsString::from(key), None)) + .collect(); + for (key, value) in [ + ("DIM_PROJECT_DIR", Some(OsString::from(&self.config.cwd))), + ("DIM_HOOK_EVENT", Some(OsString::from(handler.event.name()))), ( "DIM_SESSION_ID", - OsString::from(self.identity.session_id.clone()), + Some(OsString::from(&self.identity.session_id)), ), - ]; - if let Some(home) = self.sources.0.home() { - vars.push(("DIMCODE_HOME", home.into_os_string())); - } - if let Some(root) = &handler.plugin_root { - vars.push(("DIM_PLUGIN_ROOT", root.clone().into_os_string())); - } - vars - } -} - -fn hook_env( - env: Vec<(OsString, OsString)>, - vars: &[(&'static str, OsString)], -) -> Vec<(OsString, OsString)> { - let mut env: Vec<(OsString, OsString)> = env - .into_iter() - .filter(|(key, _)| !MANAGED_ENV.iter().any(|name| key == name)) - .collect(); - env.extend( - vars.iter() - .map(|(key, value)| (OsString::from(*key), value.clone())), - ); - env -} - -/// Reads at most `limit` bytes and drains the rest, so the writer never -/// blocks; the bool says more was written. -async fn read_capped(reader: &mut R, limit: usize) -> (Vec, bool) { - let mut kept = Vec::new(); - let mut buffer = [0u8; 8192]; - let mut overflow = false; - loop { - match reader.read(&mut buffer).await { - Ok(0) | Err(_) => return (kept, overflow), - Ok(read) => { - let room = limit.saturating_sub(kept.len()); - if read <= room { - kept.extend_from_slice(&buffer[..read]); - } else { - kept.extend_from_slice(&buffer[..room]); - overflow = true; - } - } + ( + "DIMCODE_HOME", + self.sources.0.home().map(|home| home.into_os_string()), + ), + ( + "DIM_PLUGIN_ROOT", + handler + .plugin_root + .as_ref() + .map(|root| root.as_os_str().into()), + ), + ] { + env.insert(key.into(), value); } + env } } @@ -993,7 +923,7 @@ impl CheckSubmission for PromptSubmitCheck { pub struct HooksSessionPlugin { sources: Key, - platform: Key, + platform: Key, config: Key, identity: Key, checks: Key, @@ -2829,10 +2759,10 @@ mod tests { #[cfg(unix)] fn test_runtime(dir: &Path, sources: Arc) -> Arc { use crate::host_platform::{ - ExecShellRuntime, HostPlatform, OutputEncoding, ShellEdition, ShellSource, ShellStatus, + ExecHost, ExecShellRuntime, OutputEncoding, ShellEdition, ShellSource, ShellStatus, }; std::fs::create_dir_all(dir.join("home")).unwrap(); - let mut platform = HostPlatform::current(ShellStatus::Available(ExecShellRuntime { + let mut platform = ExecHost::current(ShellStatus::Available(ExecShellRuntime { executable_path: "/bin/sh".into(), edition: ShellEdition::Sh, source: ShellSource::Fallback, diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 5a4cd2d430..fb0c7b22e6 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -24,7 +24,12 @@ use tokio::{ }; use tokio_util::sync::CancellationToken; +mod configured; mod confined; +pub use configured::{ConfiguredCommand, ConfiguredEnd, ConfiguredError}; +mod face; +pub(crate) mod shell; +pub use face::{HostFacts, HostInfo}; mod exec_shell_settings; #[cfg(unix)] mod isolation; @@ -62,6 +67,12 @@ pub enum Os { Linux, Windows, } +impl serde::Serialize for Os { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.node_platform()) + } +} + impl Os { pub const CURRENT: Os = if cfg!(windows) { Os::Windows @@ -80,7 +91,8 @@ impl Os { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "kebab-case")] pub enum ShellEdition { Bash, Zsh, @@ -121,7 +133,8 @@ impl ShellEdition { } } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "lowercase")] pub enum ShellSource { /// The executable path configured in `exec-shell.json`. Explicit, @@ -132,19 +145,23 @@ pub enum ShellSource { /// The Windows automatic order `pwsh -> Windows PowerShell -> cmd`. Automatic, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "lowercase")] pub enum OutputEncoding { Utf8, Unknown, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] pub struct ExecShellRuntime { + #[serde(rename = "executable")] pub executable_path: PathBuf, pub edition: ShellEdition, pub source: ShellSource, pub output_encoding: OutputEncoding, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[serde(tag = "state", rename_all = "lowercase")] pub enum ShellStatus { Available(ExecShellRuntime), Unavailable { code: &'static str, reason: String }, @@ -216,7 +233,14 @@ const ENVIRONMENT: &[&str] = &[ /// Process facts and the source of the exec shell preference. #[derive(Clone)] -pub struct HostPlatform { +pub(crate) enum ExecutionTask { + Command(Arc), + Shell(Arc), +} + +#[derive(Clone)] +pub struct ExecHost { + mounted: std::sync::Weak, pub home: PathBuf, pub os: Os, /// Node's `process.arch` name (`arm64`, `x64`), as the TS texts use it. @@ -229,8 +253,12 @@ pub struct HostPlatform { /// The fixed system roots, captured when the platform mounts. The sandbox /// and file-access facts read this one list. pub platform_roots: Vec, + pub(crate) commands: Arc>>, + pub(crate) command_shutdown: CancellationToken, + pub(crate) command_workers: tokio_util::task::TaskTracker, shell: Arc>, shell_file: Option<(Arc, usize, PathBuf)>, + command_files: Option<(Arc, usize, PathBuf)>, pub(crate) execution: Option>, /// The installed runtimes a started process finds at the end of its /// `PATH`; `None` is a host that installs none. @@ -242,9 +270,9 @@ struct ResolvedShell { status: ShellStatus, } -impl std::fmt::Debug for HostPlatform { +impl std::fmt::Debug for ExecHost { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("HostPlatform") + f.debug_struct("ExecHost") .field("home", &self.home) .field("os", &self.os) .field("arch", &self.arch) @@ -258,7 +286,7 @@ impl std::fmt::Debug for HostPlatform { } } -/// A child process started by [`HostPlatform::spawn`]. +/// A child process started by [`ExecHost::spawn`]. pub struct ProcessSpec { pub executable: PathBuf, /// The shell argv is built by the caller; the model command is one element. @@ -276,14 +304,16 @@ pub struct ProcessSpecError { /// Whether a new process can be sandboxed on this host, or why it cannot. The /// Process isolation control shows this; preparation reads the same backend. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(tag = "state", rename_all = "lowercase")] pub enum SandboxBackend { Available, Unavailable { reason: &'static str }, } /// What a consumer keeps for a process that -/// [`HostPlatform::prepare_isolated_process`] sandboxed. +/// [`ExecHost::prepare_isolated_process`] sandboxed. +#[derive(Clone, Copy)] pub(crate) struct Isolation; impl Isolation { @@ -335,7 +365,7 @@ impl Drop for TemporaryDirectory { } } -impl HostPlatform { +impl ExecHost { /// Facts of the current process with an already resolved shell. pub fn current(shell: ShellStatus) -> io::Result { let env: Vec<_> = std::env::vars_os().collect(); @@ -352,11 +382,16 @@ impl HostPlatform { timezone: iana_time_zone::get_timezone().ok(), env, platform_roots: platform_roots(), + commands: Arc::default(), + command_shutdown: CancellationToken::new(), + command_workers: tokio_util::task::TaskTracker::new(), + mounted: Default::default(), shell: Arc::new(Mutex::new(ResolvedShell { config: Ok(None), status: shell, })), shell_file: None, + command_files: None, execution: None, toolchain: None, }) @@ -499,7 +534,7 @@ const RUNTIME_BIN_ENV_KEYS: [&str; 5] = [ ]; const PLUGIN_BIN_DIRS_ENV: &str = "DIMCODE_PLUGIN_BIN_DIRS"; -impl HostPlatform { +impl ExecHost { /// The downloaded runtimes installed under the plan in effect, node first; /// empty without the port. An entry whose bin directory is not inside its /// archive directory is skipped: the sandbox grant is the root, so the two @@ -627,7 +662,7 @@ fn windows_network_share(path: &Path) -> bool { } /// TS `buildEnv`: the service start environment with forced overrides. -fn build_env(platform: &HostPlatform) -> Vec<(OsString, OsString)> { +fn build_env(platform: &ExecHost) -> Vec<(OsString, OsString)> { let mut env: Vec<(OsString, OsString)> = platform.env.clone(); if platform.os == Os::Windows && let Some(entry) = env.iter_mut().find(|(key, _)| { @@ -772,7 +807,7 @@ fn append_toolchain_path(env: &mut Vec<(OsString, OsString)>, directories: &[Pat async fn prepend_runtime_path( command: &str, env: &[(OsString, OsString)], - platform: &HostPlatform, + platform: &ExecHost, shell: &Path, edition: ShellEdition, cwd: &Path, @@ -804,7 +839,7 @@ async fn prepend_runtime_path( async fn map_git_bash_entries( entries: &[String], - platform: &HostPlatform, + platform: &ExecHost, shell: &Path, env: &[(OsString, OsString)], cwd: &Path, @@ -874,7 +909,7 @@ fn git_bash_cygpath(bash: &Path) -> Option { } /// Runs a product helper and returns its stdout. -async fn capture(platform: &HostPlatform, spec: ProcessSpec) -> Result { +async fn capture(platform: &ExecHost, spec: ProcessSpec) -> Result { let mut tree = platform.spawn(spec).map_err(|error| error.to_string())?; let mut stdout = tree.stdout(); drop(tree.stderr()); @@ -988,13 +1023,15 @@ pub struct HostPlatformConfig { /// `exec-shell.json`: FileStorage root index and relative path. `None` /// means the profile has no home; the shell is resolved automatically. pub exec_shell_file: Option<(usize, PathBuf)>, + /// Storage root and relative directory holding retained command logs. + pub command_files: Option<(usize, PathBuf)>, /// The user home the platform reports. `None` uses the process home; a /// host that runs with an isolated home sets it, so every capability /// resolves `~` and the user Skill root inside that home. pub home: Option, } -/// Process plugin providing `P:HostPlatform`. +/// Process plugin providing `execHost`. pub struct HostPlatformPlugin { config: HostPlatformConfig, /// File storage only when a local configuration source is configured. @@ -1019,7 +1056,7 @@ impl HostPlatformPlugin { } /// File storage only when a local configuration source is configured. fn uses_storage(config: &HostPlatformConfig) -> bool { - config.exec_shell_file.is_some() + config.exec_shell_file.is_some() || config.command_files.is_some() } impl DynPlugin for HostPlatformPlugin { fn name(&self) -> &str { @@ -1051,18 +1088,44 @@ impl DynPlugin for HostPlatformPlugin { }; let env: Vec<_> = std::env::vars_os().collect(); let shell = resolve_shell(config.clone(), &env).await; - let mut platform = HostPlatform::current(shell) + let mut platform = ExecHost::current(shell) .map_err(|error| rutis::Error::from(ErrorKind::PluginFailed(error.into())))?; if let Some(home) = &self.config.home { platform.home = home.clone(); } + platform.command_files = self + .config + .command_files + .clone() + .zip(storage.clone()) + .map(|((root, directory), files)| (files, root, directory)); platform.shell_file = shell_file; let execution = ctx.require_at(&self.execution)?; platform.execution = Some(execution.clone()); let toolchain = ctx.require_at(&self.toolchain)?; platform.toolchain = Some(toolchain.clone()); platform.shell.lock().await.config = config; - ctx.provide_as::(Arc::new(platform))?; + platform.command_shutdown = ctx.cancellation_token().child_token(); + let platform = Arc::new_cyclic(|mounted| { + platform.mounted = mounted.clone(); + platform + }); + let owner = platform.clone(); + ctx.effect(move || async move { + { + let _admission = owner.commands.lock().unwrap(); + owner.command_shutdown.cancel(); + } + owner.command_workers.close(); + owner.command_workers.wait().await; + owner.commands.lock().unwrap().clear(); + Ok(()) + })?; + ctx.provide_at( + rutis_bridge::session::host_key("execHost"), + platform.clone() as Arc, + )?; + ctx.provide_as::(platform)?; Ok(Effect::Done) }) } @@ -2180,7 +2243,7 @@ async fn wait_job_exit(pid: u32) -> io::Result<()> { } } -impl HostPlatform { +impl ExecHost { /// Resolves the persistent shell: bash, zsh, pwsh, or Windows PowerShell. /// Other shells fall back per the platform rules. pub async fn persistent_shell(&self) -> ShellStatus { @@ -2289,14 +2352,38 @@ impl HostPlatform { /// [`exec_root`](Self::exec_root), and syncs its parent. An absent /// directory counts as removed. The caller has decided with the /// ownership rows that no Session still needs it (ADR 013 D4). - pub fn remove_exec_directory(&self, path: &Path) -> io::Result<()> { + pub async fn remove_output_directory(&self, path: PathBuf) -> io::Result<()> { let root = self.exec_root(); - if path == root || !path.starts_with(&root) { + tokio::task::spawn_blocking(move || Self::remove_exec_directory(&root, &path)) + .await + .map_err(io::Error::other)? + } + + fn remove_exec_directory(root: &Path, path: &Path) -> io::Result<()> { + let relative = path.strip_prefix(root).ok(); + if relative.is_none_or(|relative| { + relative.as_os_str().is_empty() + || relative + .components() + .any(|c| !matches!(c, std::path::Component::Normal(_))) + }) { return Err(io::Error::new( io::ErrorKind::InvalidInput, "not a persistent shell output directory", )); } + let parent = path.parent().expect("strict descendant of execRoot"); + match std::fs::canonicalize(parent) { + Ok(canonical) if canonical != parent => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "not a persistent shell output directory", + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error), + Ok(_) => {} + } match std::fs::remove_dir_all(path) { Ok(()) => {} Err(error) if error.kind() == io::ErrorKind::NotFound => {} @@ -2310,6 +2397,36 @@ impl HostPlatform { } } +/// The name of the signal that ended a process, as `exec` reports it. +#[cfg(unix)] +pub fn signal_name(status: ExitStatus) -> Option { + use std::os::unix::process::ExitStatusExt; + let signal = status.signal()?; + let name = match signal { + libc::SIGHUP => "SIGHUP", + libc::SIGINT => "SIGINT", + libc::SIGQUIT => "SIGQUIT", + libc::SIGILL => "SIGILL", + libc::SIGTRAP => "SIGTRAP", + libc::SIGABRT => "SIGABRT", + libc::SIGBUS => "SIGBUS", + libc::SIGFPE => "SIGFPE", + libc::SIGKILL => "SIGKILL", + libc::SIGUSR1 => "SIGUSR1", + libc::SIGSEGV => "SIGSEGV", + libc::SIGUSR2 => "SIGUSR2", + libc::SIGPIPE => "SIGPIPE", + libc::SIGALRM => "SIGALRM", + libc::SIGTERM => "SIGTERM", + _ => return Some(format!("SIG{signal}")), + }; + Some(name.into()) +} +#[cfg(windows)] +pub fn signal_name(_: ExitStatus) -> Option { + None +} + fn find_executable(name: &str) -> Option { let path_var = std::env::var_os("PATH")?; for entry in std::env::split_paths(&path_var) { @@ -2325,11 +2442,8 @@ fn find_executable(name: &str) -> Option { mod tests { use super::*; - fn host_with( - env: &[(&str, &str)], - toolchains: Option>, - ) -> HostPlatform { - let mut platform = HostPlatform::current(ShellStatus::Unavailable { + fn host_with(env: &[(&str, &str)], toolchains: Option>) -> ExecHost { + let mut platform = ExecHost::current(ShellStatus::Unavailable { code: "test", reason: String::new(), }) @@ -2429,7 +2543,7 @@ mod tests { source: ShellSource::Login, output_encoding: OutputEncoding::Utf8, }); - let platform = HostPlatform::current(shell.clone()).unwrap(); + let platform = ExecHost::current(shell.clone()).unwrap(); let (spec, _) = platform .build_process_spec("true", Path::new("/")) .await @@ -2440,7 +2554,7 @@ mod tests { "without the port the command is unchanged" ); - let mut installed = HostPlatform::current(shell).unwrap(); + let mut installed = ExecHost::current(shell).unwrap(); installed.env = vec![]; let installed = installed.with_toolchain_source(ToolchainSourceHost::fixed(vec![toolchain( @@ -2476,7 +2590,7 @@ mod tests { std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); let workspace = base.join("workspace"); std::fs::create_dir_all(&workspace).unwrap(); - let mut platform = HostPlatform::current(ShellStatus::Available(ExecShellRuntime { + let mut platform = ExecHost::current(ShellStatus::Available(ExecShellRuntime { executable_path: "/bin/sh".into(), edition: ShellEdition::Sh, source: ShellSource::Login, diff --git a/crates/dim-agent-capabilities/src/host_platform/configured.rs b/crates/dim-agent-capabilities/src/host_platform/configured.rs new file mode 100644 index 0000000000..d32518a5f5 --- /dev/null +++ b/crates/dim-agent-capabilities/src/host_platform/configured.rs @@ -0,0 +1,132 @@ +use super::{ExecHost, ProcessSpecError}; +use std::{ + collections::BTreeMap, ffi::OsString, path::PathBuf, process::ExitStatus, time::Duration, +}; +use tokio::io::{AsyncRead, AsyncReadExt}; +use tokio_util::sync::CancellationToken; + +pub struct ConfiguredCommand { + pub command: String, + pub cwd: PathBuf, + pub env: BTreeMap>, + pub stdin: Vec, + pub timeout: Duration, + pub stdout_limit: usize, + pub stderr_limit: usize, +} + +pub enum ConfiguredEnd { + Exited { + status: ExitStatus, + stdout: Vec, + stderr: Vec, + stdout_truncated: bool, + stderr_truncated: bool, + }, + Cancelled, + TimedOut, +} + +#[derive(Debug)] +pub enum ConfiguredError { + Prepare(ProcessSpecError), + Unloaded, + Spawn(std::io::Error), + Wait(std::io::Error, Vec), +} + +impl ConfiguredError { + pub fn stderr(&self) -> &[u8] { + match self { + Self::Wait(_, stderr) => stderr, + _ => &[], + } + } +} + +impl std::fmt::Display for ConfiguredError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Prepare(error) => write!(f, "{}: {}", error.code, error.reason), + Self::Unloaded => f.write_str("unloaded"), + Self::Spawn(error) => write!(f, "spawn failed: {error}"), + Self::Wait(error, _) => write!(f, "wait failed: {error}"), + } + } +} + +impl ExecHost { + pub async fn configured( + &self, + request: ConfiguredCommand, + cancel: &CancellationToken, + gate: Option<&CancellationToken>, + ) -> Result { + let (mut spec, _) = self + .build_process_spec(&request.command, &request.cwd) + .await + .map_err(ConfiguredError::Prepare)?; + spec.env.retain(|(name, _)| !request.env.contains_key(name)); + spec.env.extend( + request + .env + .into_iter() + .filter_map(|(key, value)| value.map(|value| (key, value))), + ); + if gate.is_some_and(CancellationToken::is_cancelled) { + return Err(ConfiguredError::Unloaded); + } + let mut tree = self + .spawn_with_stdin(spec, request.stdin) + .map_err(ConfiguredError::Spawn)?; + let mut stdout = tree.stdout(); + let mut stderr = tree.stderr(); + let end = tokio::select! { + biased; + _ = cancel.cancelled() => ConfiguredEnd::Cancelled, + _ = tokio::time::sleep(request.timeout) => ConfiguredEnd::TimedOut, + (out, err, status) = async { + tokio::join!( + read_capped(&mut stdout, request.stdout_limit), + read_capped(&mut stderr, request.stderr_limit), + tree.wait() + ) + } => { + return match status { + Ok(status) => Ok(ConfiguredEnd::Exited { + status, + stdout: out.0, + stderr: err.0, + stdout_truncated: out.1, + stderr_truncated: err.1, + }), + Err(error) => Err(ConfiguredError::Wait(error, err.0)) + } + } + }; + let _ = tree.terminate().await; + Ok(end) + } +} + +/// Reads at most `limit` bytes and drains the rest, so the writer never +/// blocks; the bool says more was written. +async fn read_capped(reader: &mut R, limit: usize) -> (Vec, bool) { + let mut kept = Vec::new(); + let mut buffer = [0u8; 8192]; + let mut overflow = false; + loop { + match reader.read(&mut buffer).await { + Ok(0) | Err(_) => return (kept, overflow), + Ok(read) => { + let room = limit.saturating_sub(kept.len()); + if read <= room { + kept.extend_from_slice(&buffer[..read]); + } else { + kept.extend_from_slice(&buffer[..room]); + overflow = true; + } + } + } + } +} diff --git a/crates/dim-agent-capabilities/src/host_platform/confined.rs b/crates/dim-agent-capabilities/src/host_platform/confined.rs index 5c8564529a..1b20740912 100644 --- a/crates/dim-agent-capabilities/src/host_platform/confined.rs +++ b/crates/dim-agent-capabilities/src/host_platform/confined.rs @@ -1,7 +1,7 @@ //! A host-owned helper process: its own file and network boundary, a timeout //! and bounded output, see //! `docs/architecture/rust-agent/plugins/HostPlatform.md`. -use super::{HostPlatform, ProcessSpec, ProcessTree, env_var}; +use super::{ExecHost, ProcessSpec, ProcessTree, env_var}; use std::{ ffi::{OsStr, OsString}, io, @@ -19,7 +19,8 @@ use tokio_util::sync::CancellationToken; /// set is closed: every rule a variant adds is recorded in /// `docs/architecture/rust-agent/plugins/HostPlatform.md` with the denial it /// answers. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "camelCase")] pub enum SystemServices { /// No system service: the helper reads the system baseline, its own /// executable and [`Confinement::read`], and writes [`Confinement::write`]; @@ -140,7 +141,7 @@ impl std::error::Error for ConfinedError { } } -impl HostPlatform { +impl ExecHost { /// Starts a host-owned helper under its own boundary and collects its /// bounded output. The helper reads the system baseline, its executable /// and `confinement.read`; writes only inside `confinement.write`; reaches diff --git a/crates/dim-agent-capabilities/src/host_platform/exec_shell_settings.rs b/crates/dim-agent-capabilities/src/host_platform/exec_shell_settings.rs index da64a485cf..bf409de3b0 100644 --- a/crates/dim-agent-capabilities/src/host_platform/exec_shell_settings.rs +++ b/crates/dim-agent-capabilities/src/host_platform/exec_shell_settings.rs @@ -1,4 +1,4 @@ -use super::{HostPlatform, ShellStatus, native, parse_preference, resolve_shell}; +use super::{ExecHost, ShellStatus, native, parse_preference, resolve_shell}; use crate::file_storage::FileStorageError; use serde::Serialize; use sha2::{Digest, Sha256}; @@ -51,7 +51,7 @@ fn optional_bytes( } } -impl HostPlatform { +impl ExecHost { async fn shell_settings_snapshot( &self, bytes: Option<&[u8]>, diff --git a/crates/dim-agent-capabilities/src/host_platform/face.rs b/crates/dim-agent-capabilities/src/host_platform/face.rs new file mode 100644 index 0000000000..e413f7d215 --- /dev/null +++ b/crates/dim-agent-capabilities/src/host_platform/face.rs @@ -0,0 +1,739 @@ +use super::{ + ConfinedError, ConfinedSpec, Confinement, ExecHost, Os, SandboxBackend, ShellStatus, + SystemServices, +}; +use crate::port_faces::{self, Empty}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use rutis_bridge::session::{HostDispatch, Reply, Value}; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeMap, path::PathBuf, sync::Arc, time::Duration}; +use tokio_util::sync::CancellationToken; + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HostFacts<'a> { + pub os: Os, + pub arch: &'a str, + pub home: &'a std::path::Path, + #[serde(skip_serializing_if = "Option::is_none")] + pub timezone: Option<&'a str>, + pub platform_roots: &'a [PathBuf], +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HostInfo<'a> { + #[serde(flatten)] + pub facts: HostFacts<'a>, + pub exec_root: PathBuf, + pub backend: SandboxBackend, + pub exec_shell: ShellStatus, +} + +impl ExecHost { + pub(crate) async fn retained_output_page( + &self, + path: &std::path::Path, + cursor: u64, + limit: usize, + ) -> Result< + crate::workspace_tools::background::OutputPage, + crate::workspace_tools::background::OutputPageError, + > { + use crate::workspace_tools::{ + background::{OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page}, + exec::OUTPUT_FILE_BYTE_LIMIT, + }; + use std::io::SeekFrom; + use tokio::io::{AsyncReadExt, AsyncSeekExt}; + if let Some((files, root, _)) = &self.command_files + && let Ok(relative) = path.strip_prefix( + files + .root_path(*root) + .map_err(|_| OutputPageError::Unavailable)?, + ) + { + let file = files + .path(*root, relative) + .map_err(|_| OutputPageError::Unavailable)?; + let cancel = CancellationToken::new(); + let _guard = cancel.clone().drop_guard(); + let reader = files + .open_read(&file, &cancel) + .await + .map_err(|_| OutputPageError::Unavailable)?; + let size = reader + .len() + .saturating_sub(cursor) + .min((limit + PAGE_CHAR_TRAILING_BYTES) as u64) as usize; + let mut bytes = Vec::with_capacity(size); + while bytes.len() < size { + let chunk = reader + .read_at(cursor + bytes.len() as u64, size - bytes.len(), &cancel) + .await + .map_err(|_| OutputPageError::Unavailable)?; + if chunk.is_empty() { + break; + } + bytes.extend_from_slice(&chunk); + } + return decode_page( + &bytes, + cursor, + limit, + reader.len() >= crate::workspace_tools::exec::OUTPUT_FILE_BYTE_LIMIT, + ); + } + let mut file = tokio::fs::File::open(path) + .await + .map_err(|_| OutputPageError::Unavailable)?; + file.seek(SeekFrom::Start(cursor)) + .await + .map_err(|_| OutputPageError::Unavailable)?; + let mut buffer = vec![0u8; limit + PAGE_CHAR_TRAILING_BYTES]; + let mut read = 0; + while read < buffer.len() { + match file.read(&mut buffer[read..]).await { + Ok(0) => break, + Ok(bytes) => read += bytes, + Err(_) => return Err(OutputPageError::Unavailable), + } + } + let truncated = file + .metadata() + .await + .map(|m| m.len() >= OUTPUT_FILE_BYTE_LIMIT) + .unwrap_or(false); + decode_page(&buffer[..read], cursor, limit, truncated) + } + pub fn facts(&self) -> HostFacts<'_> { + HostFacts { + os: self.os, + arch: &self.arch, + home: &self.home, + timezone: self.timezone.as_deref(), + platform_roots: &self.platform_roots, + } + } + + pub async fn info(&self) -> HostInfo<'_> { + HostInfo { + facts: self.facts(), + exec_root: self.exec_root(), + backend: self.sandbox_backend(), + exec_shell: self.exec_shell().await, + } + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ConfinedRequest { + program: PathBuf, + args: Vec, + read: Vec, + write: Vec, + #[serde(default)] + env: BTreeMap, + timeout_ms: u64, + output_limit: OutputLimits, + services: SystemServices, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct OutputLimits { + stdout: usize, + stderr: usize, +} + +async fn confined( + owner: Arc, + request: ConfinedRequest, + cancel: CancellationToken, +) -> Reply { + let spec = ConfinedSpec { + executable: request.program, + args: request.args.into_iter().map(Into::into).collect(), + env: request + .env + .into_iter() + .map(|(k, v)| (k.into(), v.into())) + .collect(), + }; + let confinement = Confinement { + read: request.read, + write: request.write, + services: request.services, + timeout: Duration::from_millis(request.timeout_ms), + stdout_limit: request.output_limit.stdout, + stderr_limit: request.output_limit.stderr, + }; + let result = owner + .spawn_confined(spec, confinement, cancel) + .await + .map_err(|error| { + let code = match &error { + ConfinedError::InvalidPath { .. } => "InvalidPath", + ConfinedError::TimedOut => "TimedOut", + ConfinedError::OutputLimit { .. } => "OutputLimit", + ConfinedError::Cancelled => "Cancelled", + ConfinedError::Spawn(_) => "Spawn", + ConfinedError::Cleanup(_) => "Cleanup", + }; + rutis_bridge::exports::failure("ExecHostError", code, error.to_string(), None) + })?; + Ok(serde_json::json!({ + "status": result.status.code(), + "stdout": STANDARD.encode(result.stdout), + "stderr": STANDARD.encode(result.stderr), + "confined": result.confined, + "stdoutTruncated": false, + "stderrTruncated": false, + }) + .into()) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct TaskRequest { + #[serde(rename = "taskId")] + task_id: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct StartCommand { + timeout_ms: Option, + task_id: String, + command: String, + cwd: PathBuf, + workspace: PathBuf, + roots: Vec, + output_dir: PathBuf, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct StartShell { + task_id: String, + cwd: PathBuf, + workspace: PathBuf, + roots: Vec, + output_dir: PathBuf, + cols: u16, + rows: u16, +} +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ShellWrite { + task_id: String, + data: String, +} +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ShellResize { + task_id: String, + cols: u16, + rows: u16, +} +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct WaitCommand { + task_id: String, + timeout_ms: Option, +} + +fn exec_error(code: &str, message: impl Into) -> rutis_bridge::session::Error { + rutis_bridge::exports::failure("ExecHostError", code, message.into(), None) +} + +#[derive(Deserialize)] +#[serde(untagged, rename_all_fields = "camelCase", deny_unknown_fields)] +enum OutputRequest { + Task { + task_id: String, + cursor: Option, + limit: Option, + }, + File { + output_path: PathBuf, + cursor: Option, + limit: Option, + }, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RemoveOutputDirectory { + path: PathBuf, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ConfiguredRequest { + command: String, + cwd: PathBuf, + #[serde(default)] + env: BTreeMap>, + stdin: Option, + timeout_ms: u64, + limits: OutputLimits, +} + +async fn configured( + owner: Arc, + request: ConfiguredRequest, + cancel: CancellationToken, +) -> Reply { + let stdin = STANDARD + .decode(request.stdin.unwrap_or_default()) + .map_err(|error| port_faces::invalid("execHost", error))?; + let request = super::ConfiguredCommand { + command: request.command, + cwd: request.cwd, + env: request + .env + .into_iter() + .map(|(k, v)| (k.into(), v.map(Into::into))) + .collect(), + stdin, + timeout: Duration::from_millis(request.timeout_ms), + stdout_limit: request.limits.stdout, + stderr_limit: request.limits.stderr, + }; + let started = std::time::Instant::now(); + let end = owner + .configured(request, &cancel, Some(&cancel)) + .await + .map_err(|error| { + use super::ConfiguredError; + let code = match &error { + ConfiguredError::Prepare(error) => error.code, + ConfiguredError::Spawn(_) => "spawn", + ConfiguredError::Wait(_, _) => "wait", + ConfiguredError::Unloaded => "cancelled", + }; + rutis_bridge::exports::failure("ExecHostError", code, error.to_string(), None) + })?; + use super::ConfiguredEnd; + let (status, exit, stdout, stderr, stdout_truncated, stderr_truncated) = match end { + ConfiguredEnd::Exited { + status, + stdout, + stderr, + stdout_truncated, + stderr_truncated, + } => ( + if status.code().is_some() { + "exited" + } else { + "signaled" + }, + Some(status), + stdout, + stderr, + stdout_truncated, + stderr_truncated, + ), + ConfiguredEnd::Cancelled => ("cancelled", None, Vec::new(), Vec::new(), false, false), + ConfiguredEnd::TimedOut => ("timed_out", None, Vec::new(), Vec::new(), false, false), + }; + let mut reply = serde_json::json!({ + "status":status,"durationMs":started.elapsed().as_millis() as u64, + "stdout":STANDARD.encode(stdout),"stderr":STANDARD.encode(stderr), + "stdoutTruncated":stdout_truncated,"stderrTruncated":stderr_truncated, + }); + if let Some(exit) = exit { + if let Some(code) = exit.code() { + reply["exitCode"] = code.into(); + } + if let Some(signal) = super::signal_name(exit) { + reply["signal"] = signal.into(); + } + } + Ok(reply.into()) +} + +impl ExecHost { + fn process( + self: Arc, + run: impl FnOnce(Arc, CancellationToken) -> F + Send + 'static, + ) -> Reply + where + F: Future + Send + 'static, + { + let cancel = self.command_shutdown.child_token(); + let calls = self.command_workers.clone(); + Ok(Value::cancellable_future(async move { + let hold = calls.token(); + if cancel.is_cancelled() { + return Err(rutis_bridge::exports::failure( + "ExecHostError", + "cancelled", + "execution host closed".into(), + None, + )); + } + let _dropped = cancel.clone().drop_guard(); + tokio::spawn(async move { + let _hold = hold; + run(self, cancel).await + }) + .await + .map_err(|error| { + rutis_bridge::exports::failure("ExecHostError", "failed", error.to_string(), None) + })? + })) + } +} + +impl HostDispatch for ExecHost { + fn methods(&self) -> Option { + Some(serde_json::json!({ + "shell":"async","write":"async","resize":"async","output":"async", "start":"async", "wait":"async", "kill":"async", "settle":"async", + "info":"async", "confined":"async", "configured":"async", + "removeOutputDirectory":"async", "retainOutput":"async", "tail":"async" + })) + } + + fn invoke(&self, method: &str, args: Value) -> Reply { + let owner = self + .mounted + .upgrade() + .ok_or_else(|| exec_error("cancelled", "execution host closed"))?; + if method == "output" { + use crate::workspace_tools::background::{OUTPUT_PAGE_BYTES, OUTPUT_PAGE_BYTES_MAX}; + let request: OutputRequest = port_faces::request("execHost", args)?; + return Ok(Value::cancellable_future(async move { + if let OutputRequest::Task { + task_id, + cursor, + limit, + } = &request + && let Some(shell) = owner.shell_task(task_id) + { + let limit = limit + .unwrap_or(OUTPUT_PAGE_BYTES) + .min(OUTPUT_PAGE_BYTES_MAX) as usize; + if limit == 0 { + return Err(exec_error("invalid", "limit must be at least 1")); + } + return rutis_bridge::session::arg( + &shell + .page(*cursor, limit) + .map_err(|e| exec_error("output_unavailable", e.to_string()))?, + ); + } + let (task, path, cursor, limit) = match request { + OutputRequest::Task { + task_id, + cursor, + limit, + } => ( + Some( + owner + .command_task(&task_id) + .map_err(|e| exec_error("task_unknown", e.to_string()))?, + ), + None, + cursor, + limit, + ), + OutputRequest::File { + output_path, + cursor, + limit, + } => (None, Some(output_path), cursor, limit), + }; + let cursor = cursor.unwrap_or(0); + let limit = limit + .unwrap_or(OUTPUT_PAGE_BYTES) + .min(OUTPUT_PAGE_BYTES_MAX) as usize; + if limit == 0 { + return Err(exec_error("invalid", "limit must be at least 1")); + } + let page = if let Some(task) = task { + task.page(cursor, limit) + .await + .map_err(|e| exec_error("output_unavailable", e.to_string()))? + } else { + let path = path.expect("file request"); + let (files, root, directory) = + owner.command_files.as_ref().ok_or_else(|| { + exec_error( + "output_unavailable", + "Command output storage is unavailable", + ) + })?; + let base = files + .root_path(*root) + .map_err(|e| exec_error("output_unavailable", e.to_string()))?; + if !path.starts_with(base.join(directory)) { + return Err(exec_error( + "invalid", + "Path is outside command output storage", + )); + } + owner + .retained_output_page(&path, cursor, limit) + .await + .map_err(|e| exec_error("output_unavailable", e.to_string()))? + }; + let mut reply = serde_json::json!(page); + reply["retainedFrom"] = 0.into(); + rutis_bridge::session::arg(&reply) + })); + } + if matches!(method, "write" | "resize") { + enum Action { + Write(Vec), + Resize(super::PtySize), + } + let (id, action) = if method == "write" { + let ShellWrite { task_id, data } = port_faces::request("execHost", args)?; + ( + task_id, + Action::Write( + STANDARD + .decode(data) + .map_err(|e| exec_error("invalid", e.to_string()))?, + ), + ) + } else { + let ShellResize { + task_id, + cols, + rows, + } = port_faces::request("execHost", args)?; + (task_id, Action::Resize(super::PtySize { cols, rows })) + }; + let shell = self + .shell_task(&id) + .ok_or_else(|| exec_error("task_unknown", "Unknown shell task"))?; + return Ok(Value::future(async move { + match action { + Action::Write(bytes) => shell.write(&bytes).await, + Action::Resize(size) => shell.resize(size).await, + } + .map_err(|e| exec_error("failed", e.to_string()))?; + rutis_bridge::session::arg(&Empty {}) + })); + } + if matches!(method, "start" | "shell") { + enum Launch { + Command(String, Option), + Shell(super::PtySize), + } + let (task_id, cwd, workspace, mut roots, output_dir, launch) = if method == "shell" { + let StartShell { + task_id, + cwd, + workspace, + roots, + output_dir, + cols, + rows, + } = port_faces::request("execHost", args)?; + ( + task_id, + cwd, + workspace, + roots, + output_dir, + Launch::Shell(super::PtySize { cols, rows }), + ) + } else { + let StartCommand { + task_id, + cwd, + workspace, + roots, + output_dir, + command, + timeout_ms, + } = port_faces::request("execHost", args)?; + ( + task_id, + cwd, + workspace, + roots, + output_dir, + Launch::Command(command, timeout_ms), + ) + }; + return Ok(Value::cancellable_future(async move { + if task_id.is_empty() + || task_id.contains(['/', '\\', '\0', ':']) + || matches!(task_id.as_str(), "." | "..") + { + return Err(exec_error( + "invalid", + "taskId must be a single filename component", + )); + } + if !cwd.is_absolute() + || !workspace.is_absolute() + || !output_dir.is_absolute() + || roots.iter().any(|root| !root.is_absolute()) + { + return Err(exec_error("invalid", "execution paths must be absolute")); + } + if !tokio::fs::metadata(&cwd) + .await + .is_ok_and(|metadata| metadata.is_dir()) + { + return Err(exec_error("cwd_not_found", "Working directory not found")); + } + if !roots.contains(&workspace) { + roots.push(workspace); + } + let path = match launch { + Launch::Command(command, timeout_ms) => { + let (spec, _) = owner + .build_process_spec(&command, &cwd) + .await + .map_err(|e| exec_error(e.code, e.reason))?; + owner + .start_command(&task_id, spec, &roots, &output_dir, timeout_ms) + .await + .map_err(|e| exec_error(e.code, e.reason))? + .retain_task() + } + Launch::Shell(size) => { + tokio::fs::create_dir_all(&output_dir) + .await + .map_err(|e| exec_error("io", e.to_string()))?; + owner + .start_shell(&task_id, &cwd, &roots, &output_dir, size, None) + .await + .map_err(|e| exec_error(e.code, e.reason))? + .0 + .output_path() + .to_owned() + } + }; + rutis_bridge::session::arg(&serde_json::json!({"outputPath":path})) + })); + } + if method == "wait" { + let WaitCommand { + task_id, + timeout_ms, + } = port_faces::request("execHost", args)?; + if let Some(shell) = self.shell_task(&task_id) { + return Ok(Value::cancellable_future(async move { + rutis_bridge::session::arg(&shell.wait(timeout_ms).await) + })); + } + let task = self + .command_task(&task_id) + .map_err(|e| exec_error("task_unknown", e.to_string()))?; + return Ok(Value::cancellable_future(async move { + rutis_bridge::session::arg(&task.wait(timeout_ms).await) + })); + } + if matches!(method, "kill" | "settle") { + let TaskRequest { task_id } = port_faces::request("execHost", args)?; + if let Some(shell) = owner.shell_task(&task_id) { + let kill = method == "kill"; + return Ok(Value::future(async move { + if kill { + shell + .terminate() + .await + .map_err(|e| exec_error("failed", e.to_string()))?; + } else if shell.exit().is_some() { + owner.settle_shell(&task_id, &shell); + } else { + return Err(exec_error("task_running", "Cannot settle a running shell")); + } + rutis_bridge::session::arg(&Empty {}) + })); + } + let task = owner + .command_task(&task_id) + .map_err(|e| exec_error("task_unknown", e.to_string()))?; + let kill = method == "kill"; + return Ok(Value::future(async move { + if kill { + task.terminate() + .await + .map_err(|e| exec_error("failed", e.to_string()))?; + } else { + if !task.ended() { + return Err(exec_error( + "task_running", + "Cannot settle a running command", + )); + } + owner.settle_command(&task_id, &task); + } + rutis_bridge::session::arg(&Empty {}) + })); + } + if matches!(method, "retainOutput" | "tail") { + let TaskRequest { task_id } = port_faces::request("execHost", args)?; + if method == "tail" + && let Some(shell) = owner.shell_task(&task_id) + { + return Ok(Value::future(async move { + rutis_bridge::session::arg(&shell.tail()) + })); + } + let retain = method == "retainOutput"; + return Ok(Value::future(async move { + let result = if retain { + owner + .retain_output(&task_id) + .await + .map(|path| serde_json::json!({"outputPath": path})) + } else { + owner + .tail(&task_id) + .await + .map(|tail| serde_json::json!(tail)) + }; + result.map(Into::into).map_err(|error| { + let code = match error { + crate::workspace_tools::exec::CaptureError::Unknown => "task_unknown", + crate::workspace_tools::exec::CaptureError::Unavailable(_) => { + "output_unavailable" + } + }; + rutis_bridge::exports::failure("ExecHostError", code, error.to_string(), None) + }) + })); + } + if method == "configured" { + let request = port_faces::request("execHost", args)?; + return owner.process(move |owner, cancel| configured(owner, request, cancel)); + } + if method == "removeOutputDirectory" { + let RemoveOutputDirectory { path } = port_faces::request("execHost", args)?; + return Ok(Value::future(async move { + owner.remove_output_directory(path).await.map_err(|error| { + let code = if error.kind() == std::io::ErrorKind::InvalidInput { + "invalid" + } else { + "io" + }; + rutis_bridge::exports::failure("ExecHostError", code, error.to_string(), None) + })?; + rutis_bridge::session::arg(&Empty {}) + })); + } + if method == "confined" { + let request = port_faces::request("execHost", args)?; + return owner.process(move |owner, cancel| confined(owner, request, cancel)); + } + if method != "info" { + return Err(port_faces::unknown_method("execHost", method)); + } + let Empty {} = port_faces::request("execHost", args).map_err(|error| { + rutis_bridge::exports::failure("ExecHostError", "invalid", error.to_string(), None) + })?; + Ok(Value::cancellable_future(async move { + rutis_bridge::session::arg(&owner.info().await) + })) + } +} diff --git a/crates/dim-agent-capabilities/src/host_platform/isolation.rs b/crates/dim-agent-capabilities/src/host_platform/isolation.rs index 5468798c69..b483183181 100644 --- a/crates/dim-agent-capabilities/src/host_platform/isolation.rs +++ b/crates/dim-agent-capabilities/src/host_platform/isolation.rs @@ -1,6 +1,6 @@ //! The process boundary the sandbox switch applies, before ordinary spawn/PTY. use super::{ - ENVIRONMENT, HostPlatform, Isolation, ProcessSpec, ProcessSpecError, SystemServices, + ENVIRONMENT, ExecHost, Isolation, ProcessSpec, ProcessSpecError, SystemServices, TemporaryDirectory, }; use std::path::Path; @@ -85,7 +85,7 @@ pub(super) fn validate_overlap( Ok(()) } -impl HostPlatform { +impl ExecHost { pub(crate) async fn prepare_isolated_process( &self, mut spec: ProcessSpec, @@ -158,7 +158,7 @@ impl HostPlatform { /// confined command needs to run it. They are never the reported home, its /// `runtimes` directory, or writable; a `system` interpreter contributes none, /// because the user's own `PATH` already reaches it. -fn toolchain_roots(platform: &HostPlatform) -> Vec { +fn toolchain_roots(platform: &ExecHost) -> Vec { let runtimes = platform.home.join("runtimes"); let mut roots: Vec = Vec::new(); for toolchain in platform.installed_toolchains() { @@ -178,7 +178,7 @@ fn toolchain_roots(platform: &HostPlatform) -> Vec { /// sandbox switch grants them to agent commands, and a host-owned confined /// helper reads them without the switch. pub(super) async fn baseline_read_paths( - platform: &HostPlatform, + platform: &ExecHost, #[cfg_attr( not(target_os = "macos"), expect( @@ -271,7 +271,7 @@ async fn temporary_directory() -> std::io::Result { #[cfg(target_os = "macos")] pub(super) fn prepare( - _host: &HostPlatform, + _host: &ExecHost, mut spec: ProcessSpec, read_only: &[(PathBuf, PathBuf)], read_only_files: &[(PathBuf, PathBuf)], @@ -378,7 +378,7 @@ pub(super) fn prepare( #[cfg(not(target_os = "macos"))] pub(super) fn prepare( - host: &HostPlatform, + host: &ExecHost, mut spec: ProcessSpec, read_only: &[(PathBuf, PathBuf)], read_only_files: &[(PathBuf, PathBuf)], @@ -519,7 +519,7 @@ async fn bubblewrap_unshares_the_network_only_when_the_switch_is_off() { let bwrap = base.join("bwrap"); std::fs::write(&bwrap, "#!/bin/sh\nexit 0\n").unwrap(); std::fs::set_permissions(&bwrap, std::fs::Permissions::from_mode(0o755)).unwrap(); - let mut host = HostPlatform::current(super::ShellStatus::Unavailable { + let mut host = ExecHost::current(super::ShellStatus::Unavailable { code: "test", reason: String::new(), }) @@ -551,7 +551,7 @@ async fn bubblewrap_unshares_the_network_only_when_the_switch_is_off() { #[cfg(target_os = "macos")] #[tokio::test] async fn seatbelt_allows_network_only_when_the_switch_is_on() { - let host = HostPlatform::current(super::ShellStatus::Unavailable { + let host = ExecHost::current(super::ShellStatus::Unavailable { code: "test", reason: String::new(), }) @@ -589,7 +589,7 @@ fn profile_text(spec: &ProcessSpec) -> String { #[cfg(target_os = "macos")] #[tokio::test] async fn seatbelt_grants_on_device_recognition_services_only_when_asked() { - let host = HostPlatform::current(super::ShellStatus::Unavailable { + let host = ExecHost::current(super::ShellStatus::Unavailable { code: "test", reason: String::new(), }) diff --git a/crates/dim-agent-capabilities/src/host_platform/shell.rs b/crates/dim-agent-capabilities/src/host_platform/shell.rs new file mode 100644 index 0000000000..c4ed624cab --- /dev/null +++ b/crates/dim-agent-capabilities/src/host_platform/shell.rs @@ -0,0 +1,310 @@ +use super::{ + ExecHost, ExecShellRuntime, ProcessSpec, ProcessSpecError, PtyProcessTree, PtySize, + ShellEdition, ShellStatus, +}; +use crate::workspace_tools::{ + background::{OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page}, + exec::{bounded_preview, tail_bytes}, +}; +use serde_json::{Value, json}; +use std::{ + io::{self, Read}, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, + time::{Duration, Instant}, +}; +use tokio::sync::{Mutex as AsyncMutex, watch}; +use tokio_util::sync::CancellationToken; + +const RETAINED: usize = 64 * 1024; + +#[derive(Default)] +struct Capture { + text: String, + total: u64, +} + +pub(crate) struct ShellTask { + pty: AsyncMutex>, + capture: Mutex, + terminal: watch::Sender>, + kill: CancellationToken, + timeout: CancellationToken, + path: PathBuf, + started: Instant, +} + +#[derive(Clone)] +pub(crate) struct ShellExit { + pub(crate) exit: Option, + status: &'static str, + error: Option, + duration: u64, +} + +impl ExecHost { + pub(crate) async fn start_shell( + &self, + id: &str, + cwd: &Path, + roots: &[PathBuf], + directory: &Path, + size: PtySize, + output: Option>, + ) -> Result<(Arc, ExecShellRuntime), ProcessSpecError> { + let runtime = match self.persistent_shell().await { + ShellStatus::Available(shell) => shell, + ShellStatus::Unavailable { code, reason } => { + return Err(ProcessSpecError { code, reason }); + } + }; + let args: &[&str] = match runtime.edition { + ShellEdition::Pwsh | ShellEdition::WindowsPowershell => { + &["-NoLogo", "-NoProfile", "-Command"] + } + _ => &["-i"], + }; + let spec = ProcessSpec { + executable: runtime.executable_path.clone(), + args: args.iter().map(|s| (*s).into()).collect(), + cwd: cwd.into(), + env: self + .env + .iter() + .cloned() + .chain([ + ("GIT_PAGER".into(), "cat".into()), + ("NO_COLOR".into(), "1".into()), + ("TERM".into(), "dumb".into()), + ("PAGER".into(), "cat".into()), + ]) + .collect(), + }; + let (spec, temporary, _) = self + .prepare_isolated_process(spec, roots, Some(directory)) + .await?; + let mut commands = self.commands.lock().unwrap(); + if self.command_shutdown.is_cancelled() { + return Err(ProcessSpecError { + code: "cancelled", + reason: "Execution host closed".into(), + }); + } + if commands.contains_key(id) { + return Err(ProcessSpecError { + code: "task_exists", + reason: "Execution task already exists".into(), + }); + } + let mut pty = self.spawn_pty(spec, size).map_err(|e| ProcessSpecError { + code: "failed", + reason: e.to_string(), + })?; + pty.hold(temporary); + let mut reader = pty.take_reader(); + let shell = Arc::new(ShellTask { + pty: AsyncMutex::new(Some(pty)), + capture: Mutex::default(), + terminal: watch::channel(None).0, + kill: CancellationToken::new(), + timeout: CancellationToken::new(), + path: directory.join(format!("{id}.log")), + started: Instant::now(), + }); + commands.insert(id.into(), super::ExecutionTask::Shell(shell.clone())); + let pump = Arc::downgrade(&shell); + let (drained, reader_finished) = tokio::sync::oneshot::channel(); + std::thread::spawn(move || { + let mut bytes = [0; 4096]; + while let Ok(n) = reader.read(&mut bytes) { + if n == 0 { + break; + } + let Some(pump) = pump.upgrade() else { + break; + }; + let chunk = crate::shell_session::regularize_output(&bytes[..n]); + let mut capture = pump.capture.lock().unwrap(); + if pump.exit().is_some() { + break; + } + capture.total += chunk.len() as u64; + capture.text.push_str(&chunk); + if capture.text.len() > RETAINED { + let dropped = capture.text.len() - tail_bytes(&capture.text, RETAINED).len(); + capture.text.drain(..dropped); + } + if let Some(sender) = &output { + let _ = sender.send(chunk); + } + } + let _ = drained.send(()); + }); + let worker = shell.clone(); + let shutdown = self.command_shutdown.clone(); + self.command_workers.spawn(async move { + let mut poll = tokio::time::interval(Duration::from_millis(100)); + let (exit, status, error) = loop { + let stop = tokio::select! { + biased; + _=poll.tick()=>None, + _=worker.timeout.cancelled()=>Some("timed_out"), + _=worker.kill.cancelled()=>Some("cancelled"), + _=shutdown.cancelled()=>Some("cancelled"), + }; + let mut guard = worker.pty.lock().await; + let tree = guard.as_mut().expect("shell worker owns the process"); + if let Some(status) = stop { + match tree.terminate().await { + Ok(()) => break (None, status, None), + Err(e) => break (None, "failed", Some(e.to_string())), + } + } + match tree.try_wait() { + Ok(Some(exit)) => { + let status = if exit.signal().is_some() { + "signaled" + } else { + "exited" + }; + break (Some(exit), status, None); + } + Ok(None) => {} + Err(e) => { + let _ = tree.terminate().await; + break (None, "failed", Some(e.to_string())); + } + } + }; + worker.pty.lock().await.take(); + let _ = tokio::time::timeout( + crate::workspace_tools::exec::EXIT_STDIO_GRACE, + reader_finished, + ) + .await; + let _capture = worker.capture.lock().unwrap(); + + worker.terminal.send_replace(Some(ShellExit { + exit, + status, + error, + duration: worker.started.elapsed().as_millis() as u64, + })); + }); + Ok((shell, runtime)) + } + pub(crate) fn shell_task(&self, id: &str) -> Option> { + match self.commands.lock().unwrap().get(id) { + Some(super::ExecutionTask::Shell(shell)) => Some(shell.clone()), + _ => None, + } + } + pub(crate) fn settle_shell(&self, id: &str, shell: &Arc) { + let mut shells = self.commands.lock().unwrap(); + if matches!(shells.get(id),Some(super::ExecutionTask::Shell(s)) if Arc::ptr_eq(s,shell)) { + shells.remove(id); + } + } +} + +impl ShellTask { + pub(crate) fn output_path(&self) -> &Path { + &self.path + } + pub(crate) fn exit(&self) -> Option { + self.terminal.borrow().clone() + } + pub(crate) async fn done(&self) -> ShellExit { + self.terminal + .subscribe() + .wait_for(Option::is_some) + .await + .expect("shell owner publishes completion") + .as_ref() + .unwrap() + .clone() + } + pub(crate) async fn terminate(&self) -> io::Result<()> { + self.kill.cancel(); + self.done() + .await + .error + .map_or(Ok(()), |e| Err(io::Error::other(e))) + } + pub(crate) async fn write(&self, data: &[u8]) -> io::Result<()> { + self.pty + .lock() + .await + .as_mut() + .ok_or_else(|| io::Error::other("Shell is not running"))? + .write(data) + } + pub(crate) async fn job_pid(&self, pid: u32) -> io::Result { + self.pty + .lock() + .await + .as_ref() + .ok_or_else(|| io::Error::other("Shell is not running"))? + .job_pid(pid) + } + pub(crate) async fn resize(&self, size: PtySize) -> io::Result<()> { + self.pty + .lock() + .await + .as_ref() + .ok_or_else(|| io::Error::other("Shell is not running"))? + .resize(size) + } + pub(crate) fn page(&self, cursor: Option, limit: usize) -> Result { + let capture = self.capture.lock().unwrap(); + let first = capture.total - capture.text.len() as u64; + let cursor = cursor.unwrap_or(first); + if cursor < first { + return Ok( + json!({"text":"","bytes":0,"retainedFrom":first,"reset":true,"truncated":true}), + ); + } + let start = (cursor - first).min(capture.text.len() as u64) as usize; + let end = (start + limit + PAGE_CHAR_TRAILING_BYTES).min(capture.text.len()); + let mut reply = json!(decode_page( + &capture.text.as_bytes()[start..end], + cursor, + limit, + first != 0 + )?); + reply["retainedFrom"] = first.into(); + Ok(reply) + } + pub(crate) fn tail(&self) -> Value { + let capture = self.capture.lock().unwrap(); + let (text, truncated) = bounded_preview(&capture.text, capture.total as usize); + json!({"text":text,"totalBytes":capture.total,"truncated":truncated}) + } + pub(crate) async fn wait(&self, ms: Option) -> Value { + let end = if let Some(ms) = ms { + tokio::select! { + biased; + end = self.done() => end, + _ = tokio::time::sleep(Duration::from_millis(ms)) => { + self.timeout.cancel(); + self.done().await + } + } + } else { + self.done().await + }; + let tail = self.tail(); + let capture = self.capture.lock().unwrap(); + let mut reply = json!({"status":end.status,"durationMs":end.duration,"outputPath":self.path, + "outputBytes":capture.total,"outputTruncated":capture.total>capture.text.len() as u64, + "preview":tail["text"],"previewTruncated":tail["truncated"]}); + if let Some(exit) = end.exit { + if let Some(signal) = exit.signal() { + reply["signal"] = signal.into(); + } else { + reply["exitCode"] = exit.exit_code().into(); + } + } + reply + } +} diff --git a/crates/dim-agent-capabilities/src/lib.rs b/crates/dim-agent-capabilities/src/lib.rs index 588447991e..48d133f66f 100644 --- a/crates/dim-agent-capabilities/src/lib.rs +++ b/crates/dim-agent-capabilities/src/lib.rs @@ -123,7 +123,8 @@ fn register_names_in(catalog: &mut dim_agent_runtime::names::ServiceCatalog) { register::(catalog, branch); register::(catalog, branch); catalog.register_shared_instance("branchLine", BRANCH_GROUP); - register::(catalog, None); + register::(catalog, None); + catalog.register_shared("execHost"); register::(catalog, None); register::(catalog, None); catalog.register_shared("fsHost"); diff --git a/crates/dim-agent-capabilities/src/permission.rs b/crates/dim-agent-capabilities/src/permission.rs index cd4b8346df..98f4bf762a 100644 --- a/crates/dim-agent-capabilities/src/permission.rs +++ b/crates/dim-agent-capabilities/src/permission.rs @@ -14,7 +14,7 @@ use crate::{ file_access::FileAccessFacts, host::{CancelledFn, HostError, HostFuture, call_until_cancelled}, - host_platform::HostPlatform, + host_platform::ExecHost, workspace_tools::files::{Access, canonical_prefix, resolve_path}, }; use dim_agent_runtime::{ @@ -204,7 +204,7 @@ pub struct Permission { /// looked up at decision time, never while the part loads. ctx: Ctx, facts: Key, - platform: Key, + platform: Key, session_id: String, cwd: PathBuf, inner: Mutex, @@ -329,7 +329,7 @@ impl Permission { .then(|| { self.ctx .get_at(&self.platform) - .map(|platform| platform.home.clone()) + .map(|platform| platform.facts().home.to_owned()) }) .flatten(); let read_facts = (category == Risk::Read) @@ -839,7 +839,7 @@ pub struct PermissionPlugin { rules: Key, facts: Key, identity: Key, - platform: Key, + platform: Key, timeline: Key, dispatcher: Key, } diff --git a/crates/dim-agent-capabilities/src/prompt_sources.rs b/crates/dim-agent-capabilities/src/prompt_sources.rs index c26f7c52b4..f42c4d81e9 100644 --- a/crates/dim-agent-capabilities/src/prompt_sources.rs +++ b/crates/dim-agent-capabilities/src/prompt_sources.rs @@ -7,7 +7,7 @@ use crate::{ context_block, host::{HostError, HostFuture, LoadPrompt, PromptHost}, host_platform::{ - ExecShellRuntime, HostPlatform, Os, OutputEncoding, ShellEdition, ShellStatus, + ExecHost, ExecShellRuntime, HostInfo, Os, OutputEncoding, ShellEdition, ShellStatus, }, prompt::Prompt, prompt_registry::{PromptRegistry, PromptRegistryPlugin, targets}, @@ -223,22 +223,13 @@ fn xml_tag(name: &str, value: &str) -> String { /// The runtime environment (TS `renderRuntimeEnvironment`): one tag per /// line, values escaped; the date is its own source. -fn environment( - platform: &HostPlatform, - shell: &ShellStatus, - cwd: &str, - policy: &PromptSourcesConfig, -) -> String { - let os = match platform.os { - Os::Macos => "darwin", - Os::Linux => "linux", - Os::Windows => "win32", - }; +fn environment(platform: &HostInfo<'_>, cwd: &str, policy: &PromptSourcesConfig) -> String { + let os = platform.facts.os.node_platform(); let mut entries = vec![ xml_tag("cwd", cwd), - xml_tag("home", &platform.home.to_string_lossy()), + xml_tag("home", &platform.facts.home.to_string_lossy()), ]; - match shell { + match &platform.exec_shell { ShellStatus::Available(ExecShellRuntime { executable_path, edition, @@ -261,7 +252,7 @@ fn environment( OutputEncoding::Unknown => "unknown", }, )); - if platform.os == Os::Windows { + if platform.facts.os == Os::Windows { let guidance = policy .file_encoding_guidance .as_deref() @@ -274,7 +265,7 @@ fn environment( } } entries.push(xml_tag("platform", os)); - if let Some(timezone) = &platform.timezone { + if let Some(timezone) = platform.facts.timezone { entries.push(xml_tag("timezone", timezone)); } format!("\n{}\n", entries.join("\n")) @@ -450,7 +441,8 @@ impl PromptSourcesBranch { } struct Sources { - platform: Arc, + home: PathBuf, + platform: Arc, config: Arc, today: Today, stopped: CancellationToken, @@ -483,7 +475,7 @@ impl LoadPrompt for Sources { PROJECT_INSTRUCTIONS | USER_INSTRUCTIONS => { let body = load_instructions( &self.config.cwd, - &self.platform.home, + &self.home, target.source == PROJECT_INSTRUCTIONS, ) .await?; @@ -496,8 +488,7 @@ impl LoadPrompt for Sources { } ENVIRONMENT => ( Some(environment( - &self.platform, - &self.platform.exec_shell().await, + &self.platform.info().await, &self.config.cwd, &self.policy, )), @@ -538,7 +529,7 @@ impl LoadPrompt for Sources { /// Session part: registers each of its sources with the prompt registry. pub struct PromptSourcesPlugin { - platform: Key, + platform: Key, config: Key, registry: Key, language: Key, @@ -612,6 +603,7 @@ impl DynPlugin for PromptSourcesPlugin { } } let sources: Arc = Arc::new(Sources { + home: platform.facts().home.to_owned(), platform, config, today: self.today.clone(), diff --git a/crates/dim-agent-capabilities/src/shell_input.rs b/crates/dim-agent-capabilities/src/shell_input.rs index 848504363b..e8fba02267 100644 --- a/crates/dim-agent-capabilities/src/shell_input.rs +++ b/crates/dim-agent-capabilities/src/shell_input.rs @@ -11,14 +11,14 @@ //! Session (`SessionLifecycle::take_hold`), so an idle unload never ends it. use crate::{ context_block::{element, raw, text}, - host_platform::{HostPlatform, ProcessTree}, + host_platform::{ExecHost, ProcessTree, signal_name}, methods::{ Interruption, MethodCall, MethodDecl, Progress, RpcError, SessionMethods, params, reply, }, prompt_guide::{GuideEntries, GuideEntry, GuideScope}, timeline_tree::TreeCommands, workspace_tools::exec::{ - OutputSink, bounded_preview, capture_preview, pump, sanitize, signal_name, tail_bytes, + OutputSink, bounded_preview, capture_preview, pump, sanitize, tail_bytes, }, }; use dim_agent_runtime::{ @@ -131,7 +131,7 @@ struct Registry { } struct ShellInput { - platform: Arc, + platform: Arc, cwd: PathBuf, tree: Arc, lifecycle: Arc, @@ -547,7 +547,7 @@ const SHELL_INPUT_ENTRY: &str = r#" { - let dialect = match runtime.edition { - ShellEdition::Pwsh | ShellEdition::WindowsPowershell => ShellDialect::Pwsh, - _ => ShellDialect::Posix, - }; - (runtime.executable_path.clone(), dialect) - } - ShellStatus::Unavailable { reason, .. } => { - return Err(HostError::failed(reason)); - } - }; - let args = shell_args(dialect); - let env = self - .host - .env - .iter() - .cloned() - .chain([ - ("GIT_PAGER".into(), "cat".into()), - ("NO_COLOR".into(), "1".into()), - ("TERM".into(), "dumb".into()), - ("PAGER".into(), "cat".into()), - ]) - .collect(); - let spec = crate::host_platform::ProcessSpec { - executable: exe.clone(), - args, - cwd: self.config.cwd.clone(), - env, - }; - // The persistent shell adds no failure note (host-platform-isolation.md#visibility). let roots = match self.facts.as_ref().and_then(|(ctx, key)| ctx.get_at(key)) { Some(facts) => { facts @@ -566,23 +558,33 @@ impl ShellSession { } None => vec![self.config.cwd.clone()], }; - let (spec, temporary, _) = self - .host - .prepare_isolated_process(spec, &roots, Some(&self.config.output_dir)) - .await - .map_err(|error| HostError::failed(format!("{}: {}", error.code, error.reason)))?; - let mut pty = self + let id = format!("shell-{}", uuid::Uuid::new_v4()); + let (output, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let (task, runtime) = self .host - .spawn_pty( - spec, + .start_shell( + &id, + &self.config.cwd, + &roots, + &self.config.output_dir, PtySize { cols: 500, rows: 50, }, + Some(output), ) - .map_err(|e| HostError::failed(e.to_string()))?; - pty.hold(temporary); - let reader = pty.take_reader(); + .await + .map_err(|error| HostError::failed(error.reason))?; + let dialect = match runtime.edition { + ShellEdition::Pwsh | ShellEdition::WindowsPowershell => ShellDialect::Pwsh, + _ => ShellDialect::Posix, + }; + let exe = runtime.executable_path; + let pty = NativeShell { + task, + host: self.host.clone(), + id, + }; let generation = { let mut inner = self.inner.lock().await; if self.lifecycle.is_cancelled() { @@ -599,24 +601,6 @@ impl ShellSession { inner.pty = Some(pty); inner.generation }; - let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::>>(); - std::thread::spawn(move || { - let mut reader = reader; - let mut buf = [0u8; 4096]; - loop { - match reader.read(&mut buf) { - Ok(0) | Err(_) => { - let _ = tx.send(None); - break; - } - Ok(n) => { - if tx.send(Some(buf[..n].to_vec())).is_err() { - break; - } - } - } - } - }); let this = self.clone(); let lifecycle = self.lifecycle.clone(); { @@ -629,8 +613,8 @@ impl ShellSession { biased; _ = lifecycle.cancelled() => break, chunk = rx.recv(), if reading => match chunk { - Some(Some(bytes)) => { - this.handle_output(®ularize_output(&bytes)).await; + Some(text) => { + this.handle_output(&text).await; } _ => { reading = false; @@ -640,8 +624,8 @@ impl ShellSession { Liveness::Alive => {} Liveness::Replaced => break, Liveness::Dead(status) => { - while let Ok(Some(bytes)) = rx.try_recv() { - this.handle_output(®ularize_output(&bytes)).await; + while let Ok(text) = rx.try_recv() { + this.handle_output(&text).await; } this.handle_shell_exit(generation, status).await; break; @@ -707,7 +691,7 @@ impl ShellSession { } if tokio::time::Instant::now() >= deadline { let mut inner = self.inner.lock().await; - if let Some(mut pty) = inner.pty.take() { + if let Some(pty) = inner.pty.take() { let _ = pty.terminate().await; } let captured = inner.retained.clone(); @@ -734,6 +718,7 @@ impl ShellSession { return Err(HostError::failed("Shell is not running")); }; pty.write(line.as_bytes()) + .await .map_err(|e| HostError::failed(format!("Shell write failed: {e}")))?; inner.capture = Some(capture); Ok(()) @@ -803,10 +788,9 @@ impl ShellSession { } match inner.pty.as_mut() { None => Liveness::Dead(None), - Some(pty) => match pty.try_wait() { - Ok(None) => Liveness::Alive, - Ok(status) => Liveness::Dead(status), - Err(_) => Liveness::Dead(None), + Some(pty) => match pty.exit() { + None => Liveness::Alive, + Some(end) => Liveness::Dead(end.exit), }, } } @@ -990,7 +974,7 @@ impl ShellSession { { let mut inner = self.inner.lock().await; if let Some(pty) = inner.pty.as_mut() { - let _ = pty.write(b"\x03"); + let _ = pty.write(b"\x03").await; } } let deadline = tokio::time::Instant::now() + STOP_WAIT; @@ -1021,7 +1005,7 @@ impl ShellSession { if tokio::time::Instant::now() >= deadline { let mut inner = self.inner.lock().await; inner.capture = None; - if let Some(mut pty) = inner.pty.take() { + if let Some(pty) = inner.pty.take() { let _ = pty.terminate().await; } inner.shell_exit = Some("[shell was terminated]".into()); @@ -1231,16 +1215,14 @@ impl ShellSession { pty, background, .. } = &mut *inner; if let Some(task) = background.get_mut(&task_id) { - task.pid = code - .parse::() - .map_err(|_| { - std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid job pid") - }) - .and_then(|pid| { - pty.as_ref() - .ok_or_else(|| std::io::Error::other("shell exited"))? - .job_pid(pid) - }); + task.pid = match (code.parse::(), pty.as_ref()) { + (Ok(pid), Some(shell)) => shell.job_pid(pid).await, + (Ok(_), None) => Err(std::io::Error::other("shell exited")), + (Err(_), _) => Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "Invalid job pid", + )), + }; } break; } @@ -1322,7 +1304,7 @@ impl ShellSession { capture.settle(capture.pending.len()); } if let Some(pty) = inner.pty.as_mut() { - let _ = pty.write(b"\x03"); + let _ = pty.write(b"\x03").await; } } let deadline = tokio::time::Instant::now() + STOP_WAIT; @@ -1353,7 +1335,7 @@ impl ShellSession { inner.occupy_tail = Some(capture.output); } if !found { - if let Some(mut pty) = inner.pty.take() { + if let Some(pty) = inner.pty.take() { let _ = pty.terminate().await; } inner.shell_exit = Some("[shell was terminated]".into()); @@ -1413,6 +1395,7 @@ impl ShellSession { return Err(HostError::failed("Shell is not running")); }; pty.write(format!("{line}\n").as_bytes()) + .await .map_err(|e| HostError::failed(format!("Shell write failed: {e}"))) } } @@ -1455,7 +1438,7 @@ pub struct ShellSessionPlugin { stop: Key, timeline: Key, dispatcher: Key, - host: Key, + host: Key, lifecycle: Key, session_config: Key, identity: Key, @@ -1535,7 +1518,7 @@ impl DynPlugin for ShellSessionPlugin { service.lifecycle.cancel(); { let mut inner = service.inner.lock().await; - if let Some(mut pty) = inner.pty.take() { + if let Some(pty) = inner.pty.take() { let _ = pty.terminate().await; } for queued in inner.queue.drain(..) { @@ -1567,13 +1550,6 @@ impl DynPlugin for ShellSessionPlugin { } } -fn shell_args(dialect: ShellDialect) -> Vec { - match dialect { - ShellDialect::Posix => vec!["-i".into()], - ShellDialect::Pwsh => vec!["-NoLogo".into(), "-NoProfile".into(), "-Command".into()], - } -} - /// Declares the command the call sent to the shell (session boundary A.6): /// the exit status the end marker carried, or none while it was still /// running. @@ -1718,7 +1694,7 @@ fn marker_hold(text: &str) -> usize { .map_or(text.len(), |len| text.len() - len) } -fn regularize_output(bytes: &[u8]) -> String { +pub(crate) fn regularize_output(bytes: &[u8]) -> String { let text = String::from_utf8_lossy(bytes); let mut out = String::new(); let mut chars = text.chars().peekable(); diff --git a/crates/dim-agent-capabilities/src/shell_tools.rs b/crates/dim-agent-capabilities/src/shell_tools.rs index 235f47f5db..ac81a4f448 100644 --- a/crates/dim-agent-capabilities/src/shell_tools.rs +++ b/crates/dim-agent-capabilities/src/shell_tools.rs @@ -5,7 +5,7 @@ use crate::{ host::{ToolDriver, ToolExecutionContext, ToolHost}, - host_platform::{HostPlatform, ISOLATION_SUMMARY}, + host_platform::{ExecHost, HostFacts, ISOLATION_SUMMARY}, shell_session::{CallContext, ShellSession}, timeline_tree::TreeCommands, }; @@ -17,7 +17,7 @@ use serde_json::json; use std::sync::Arc; /// The `execute` tool definition. -fn execute_definition(platform: &HostPlatform) -> dim_agent_types::ToolDefinition { +fn execute_definition(platform: &HostFacts<'_>) -> dim_agent_types::ToolDefinition { let mut env_line = format!( "Environment: {}/{}", platform.os.node_platform(), @@ -45,15 +45,13 @@ fn execute_definition(platform: &HostPlatform) -> dim_agent_types::ToolDefinitio /// The tool driver. struct ShellToolsDriver { - platform: Arc, + definition: dim_agent_types::ToolDefinition, tree: Arc, } impl ToolDriver for ShellToolsDriver { fn definitions(&self) -> Vec { - let mut definition = execute_definition(&self.platform); - definition.risk = Some("execute_process".into()); - vec![definition] + vec![self.definition.clone()] } fn execute( @@ -109,7 +107,7 @@ pub fn install(builder: &mut AgentBuilder) { /// The plugin. pub struct ShellToolsPlugin { host: Key, - platform: Key, + platform: Key, tree: Key, } @@ -134,7 +132,9 @@ impl DynPlugin for ShellToolsPlugin { Box::pin(async move { let platform = ctx.require_at(&self.platform)?; let tree = ctx.require_at(&self.tree)?; - let driver = Arc::new(ShellToolsDriver { platform, tree }); + let mut definition = execute_definition(&platform.facts()); + definition.risk = Some("execute_process".into()); + let driver = Arc::new(ShellToolsDriver { definition, tree }); ctx.provide_at(self.host.clone(), Arc::new(ToolHost(driver)))?; Ok(Effect::Done) }) diff --git a/crates/dim-agent-capabilities/src/skills/catalog.rs b/crates/dim-agent-capabilities/src/skills/catalog.rs index e5164ef5d8..9eb7b41d7a 100644 --- a/crates/dim-agent-capabilities/src/skills/catalog.rs +++ b/crates/dim-agent-capabilities/src/skills/catalog.rs @@ -6,7 +6,7 @@ use super::{ install, }; use crate::{ - host_platform::HostPlatform, + host_platform::ExecHost, settings::{SettingsChanged, settings_changes}, skill_settings::{ SOURCE, SettingsVersion, SkillInstallSource, SkillInstallation, SkillSettings, @@ -722,7 +722,7 @@ fn validate_selection(selection: &[SelectedSkill]) -> Result, /// The Skills plugin: `SkillsCatalog` at the process, and the Session and /// branch parts it registers ([`super::register_parts`]). pub struct SkillsCatalogPlugin { - platform: Key, + platform: Key, settings: Key, parts: Key, } @@ -751,7 +751,7 @@ impl DynPlugin for SkillsCatalogPlugin { let platform = ctx.require_at(&self.platform)?; let settings = ctx.require_at(&self.settings)?; let parts = ctx.require_at(&self.parts)?; - let catalog = Self::mount(ctx, (platform, settings)).await?; + let catalog = Self::mount(ctx, (platform.facts().home.to_owned(), settings)).await?; ctx.provide_at(owner_key(), catalog.clone())?; let binding = Arc::new(super::SkillsCatalogBinding::new(catalog)); ctx.provide_as::(binding.clone())?; @@ -770,7 +770,7 @@ impl SkillsCatalogPlugin { /// and registers the parts there too ([`super::register_parts`]). pub async fn mount( ctx: &Ctx, - (platform, settings): (Arc, Arc), + (home, settings): (PathBuf, Arc), ) -> Result, Error> { let settings = settings.0.clone(); let lifecycle = ctx.cancellation_token(); @@ -786,7 +786,7 @@ impl SkillsCatalogPlugin { .await .map_err(|error| SkillsError::SettingsRead(error.to_string())); let catalog = Arc::new(SkillsCatalog { - user_root: platform.home.join(SKILLS_DIR), + user_root: home.join(SKILLS_DIR), settings: settings.clone(), state: tokio::sync::Mutex::new(CatalogState { user: None, diff --git a/crates/dim-agent-capabilities/src/workspace_tools/background.rs b/crates/dim-agent-capabilities/src/workspace_tools/background.rs index ba5e487c04..07c41a94bb 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/background.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/background.rs @@ -5,7 +5,7 @@ //! dispatch of every `exec/ended` that is not `cancelled`. Each running task //! holds its Session (`SessionLifecycle::take_hold`) until its `exec/ended` is //! appended, so an idle unload never ends it (idle unload §5, R2). -use super::exec::{ExecProcess, OUTPUT_FILE_BYTE_LIMIT, Output, recovered_result, sanitize}; +use super::exec::{ExecProcess, Output, recovered_result, sanitize}; use crate::{ context_block, prompt_guide::{GuideEntries, GuideEntry, GuideScope}, @@ -20,13 +20,9 @@ use rutis::Ctx; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use std::{ collections::HashMap, - io::SeekFrom, sync::{Arc, Mutex}, }; -use tokio::{ - io::{AsyncReadExt, AsyncSeekExt}, - sync::watch, -}; +use tokio::sync::watch; use tokio_util::{sync::CancellationToken, task::TaskTracker}; pub struct StartRequest { @@ -130,9 +126,64 @@ pub struct OutputPage { pub truncated: bool, } +pub(crate) fn decode_page( + buffer: &[u8], + cursor: u64, + limit: usize, + truncated: bool, +) -> Result { + // The file holds the pipe decoder's output, so its bytes are valid + // UTF-8; every completed write ends on a character boundary, though a + // reader can catch a write while it is in progress and see the file + // end inside a character. The page ends at the last character + // boundary at or before `limit`, so a character the limit splits is + // served whole: at the start of the next page when the cut falls + // after other characters, and whole in this page when the budget cuts + // the very first character. A page therefore consumes at least one + // character while the file holds one, and can carry up to `limit` + // plus three bytes. Complete characters before a trailing partial one + // are served normally; only a cursor opening inside a character, or a + // file ending inside the first character at the cursor, leaves the + // page with nothing whole to serve, and it stays empty for that call. + let read = buffer.len(); + let budget = read.min(limit); + let mut end = std::str::from_utf8(&buffer[..budget]).map_or_else(|e| e.valid_up_to(), str::len); + if end == 0 && read > 0 { + let whole = match buffer[0] { + 0xc2..=0xdf => 2, + 0xe0..=0xef => 3, + 0xf0..=0xf4 => 4, + _ => 0, + }; + // Only a character the read completed is served whole; one the + // read cut short stays for the next call, which sees the write + // finish. + if whole <= read { + end = whole; + } + } + // The writer appends only valid UTF-8, and the loop above ends the slice on a boundary. + let text = + sanitize(std::str::from_utf8(&buffer[..end]).map_err(|_| OutputPageError::Unavailable)?); + // A read that reached the page budget found at least `limit` bytes, + // so `nextCursor` lets the client continue immediately; a shorter + // read ended at the file's current length, which a running task may + // extend later, so the client advances by `bytes` and asks again. + // The read length decides it: the file's size races with the + // appender. An empty page (caught up, ended, or a client cursor + // inside a character) carries no `nextCursor`. + let next_cursor = (read >= limit && end > 0).then_some(cursor + end as u64); + Ok(OutputPage { + text, + bytes: end as u64, + next_cursor, + truncated, + }) +} + /// How far a page may exceed its budget to hold a whole character: a UTF-8 /// character is at most four bytes, so at most three lie past the limit. -const PAGE_CHAR_TRAILING_BYTES: usize = 3; +pub(crate) const PAGE_CHAR_TRAILING_BYTES: usize = 3; struct Task { description: String, @@ -170,6 +221,7 @@ struct State { } pub struct BackgroundExec { + platform: Arc, timeline: Arc, from: Option, /// Gives each task its Session hold. @@ -379,85 +431,19 @@ impl BackgroundExec { (start.output_path, ended, None) } }; - let mut file = tokio::fs::File::open(&output_path) - .await - .map_err(|_| OutputPageError::Unavailable)?; - file.seek(SeekFrom::Start(cursor)) - .await - .map_err(|_| OutputPageError::Unavailable)?; - let mut buffer = vec![0u8; limit + PAGE_CHAR_TRAILING_BYTES]; - let mut read = 0; - while read < buffer.len() { - match file.read(&mut buffer[read..]).await { - Ok(0) => break, - Ok(bytes) => read += bytes, - Err(_) => return Err(OutputPageError::Unavailable), - } - } - // The file holds the pipe decoder's output, so its bytes are valid - // UTF-8; every completed write ends on a character boundary, though a - // reader can catch a write while it is in progress and see the file - // end inside a character. The page ends at the last character - // boundary at or before `limit`, so a character the limit splits is - // served whole: at the start of the next page when the cut falls - // after other characters, and whole in this page when the budget cuts - // the very first character. A page therefore consumes at least one - // character while the file holds one, and can carry up to `limit` - // plus three bytes. Complete characters before a trailing partial one - // are served normally; only a cursor opening inside a character, or a - // file ending inside the first character at the cursor, leaves the - // page with nothing whole to serve, and it stays empty for that call. - let mut end = read.min(limit); - while end > 0 && std::str::from_utf8(&buffer[..end]).is_err() { - end -= 1; - } - if end == 0 && read > 0 { - let whole = match buffer[0] { - 0xc2..=0xdf => 2, - 0xe0..=0xef => 3, - 0xf0..=0xf4 => 4, - _ => 0, - }; - // Only a character the read completed is served whole; one the - // read cut short stays for the next call, which sees the write - // finish. - if whole <= read { - end = whole; - } - } - // The writer appends only valid UTF-8, and the loop above ends the slice on a boundary. - let text = - sanitize(std::str::from_utf8(&buffer[..end]).expect("the page ends on a boundary")); - // A read that reached the page budget found at least `limit` bytes, - // so `nextCursor` lets the client continue immediately; a shorter - // read ended at the file's current length, which a running task may - // extend later, so the client advances by `bytes` and asks again. - // The read length decides it: the file's size races with the - // appender. An empty page (caught up, ended, or a client cursor - // inside a character) carries no `nextCursor`. - let next_cursor = (read >= limit && end > 0).then_some(cursor + end as u64); - let truncated = match ended + let mut page = self + .platform + .retained_output_page(std::path::Path::new(&output_path), cursor, limit) + .await?; + if let Some(truncated) = ended .as_ref() .and_then(|data| output_truncated(&data.result)) { - Some(truncated) => truncated, - None => match &live { - Some(output) => output.truncated().await, - // Only the recovery terminal (`recovered_result`) carries no - // flag; its truncation is the file's size alone. - None => file - .metadata() - .await - .map(|metadata| metadata.len() >= OUTPUT_FILE_BYTE_LIMIT) - .unwrap_or(false), - }, - }; - Ok(OutputPage { - text, - bytes: end as u64, - next_cursor, - truncated, - }) + page.truncated = truncated; + } else if let Some(output) = live { + page.truncated = output.truncated().await; + } + Ok(page) } /// Waits until the task ends, or `timeout_ms` elapses: what @@ -977,6 +963,7 @@ fn output_truncated(result: &ToolResult) -> Option { const EXEC_ENTRY: &str = r#": something you started has finished, failed or been cancelled, such as a background command. It is information, not a new request. The output preview belongs to that command. Use the read tool with its output path to read the full result. If the work it belongs to is no longer wanted, note the result and do not restart that work."#; pub struct BackgroundExecPlugin { + platform: Key, exec: Key, timeline: Key, dispatcher: Key, @@ -987,6 +974,7 @@ pub struct BackgroundExecPlugin { impl BackgroundExecPlugin { pub fn new(names: &Names<'_>) -> rutis::Result { Ok(Self { + platform: names.key()?, exec: names.key()?, timeline: names.key()?, dispatcher: names.key()?, @@ -1002,6 +990,7 @@ impl DynPlugin for BackgroundExecPlugin { } fn injects(&self) -> Vec { vec![ + self.platform.erase(), self.timeline.erase(), self.dispatcher.erase(), self.session.erase(), @@ -1061,6 +1050,7 @@ impl DynPlugin for BackgroundExecPlugin { position }); let service = Arc::new(BackgroundExec { + platform: ctx.require_at(&self.platform)?, timeline, from, session, diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index 42eec5167b..6982b4a52d 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -1,7 +1,7 @@ //! The `exec` tool, copied from TS `packages/agent/src/tool/builtin/exec/` //! (`tool.ts`, `process.ts`, `shell.ts`, `validate.ts`, `output.ts`). Only the //! differences in `docs/architecture/rust-agent/plugins/WorkspaceTools.md` apply: -//! processes start through `HostPlatform::spawn`, and a command that moves to +//! processes start through `ExecHost::spawn`, and a command that moves to //! the background is handed to this branch's `BackgroundExec`. use super::{ WorkspaceTools, @@ -10,8 +10,8 @@ use super::{ use crate::{ host::{HostError, ToolExecutionContext}, host_platform::{ - EXEC_SHELL_CONFIG_INVALID, EXEC_SHELL_UNAVAILABLE, HostPlatform, ISOLATION_SUMMARY, - Isolation, Os, ProcessTree, ShellEdition, ShellKind, TemporaryDirectory, + EXEC_SHELL_CONFIG_INVALID, EXEC_SHELL_UNAVAILABLE, ExecHost, ISOLATION_SUMMARY, Isolation, + Os, ProcessSpec, ProcessSpecError, ProcessTree, ShellEdition, ShellKind, signal_name, }, tool_registry::definition, }; @@ -41,12 +41,12 @@ const OUTPUT_PREVIEW_MAX_BYTES: usize = 50 * 1024; const PREVIEW_BUFFER_HEADROOM_BYTES: usize = OUTPUT_PREVIEW_MAX_BYTES * 2; /// Maximum bytes written to one exec output file. Read by the paged output /// read (`BackgroundExec::output_page`) as the file-level truncation signal. -pub(super) const OUTPUT_FILE_BYTE_LIMIT: u64 = 64 * 1024 * 1024; +pub(crate) const OUTPUT_FILE_BYTE_LIMIT: u64 = 64 * 1024 * 1024; /// Pipe reading continues this long after the root process exits. pub const EXIT_STDIO_GRACE: Duration = Duration::from_millis(100); const DESCRIPTION_CHARS: usize = 200; -pub fn definition_for(platform: &HostPlatform) -> ToolDefinition { +pub fn definition_for(platform: &crate::host_platform::HostFacts<'_>) -> ToolDefinition { let mut env_line = format!( "Environment: {}/{}", platform.os.node_platform(), @@ -1630,15 +1630,15 @@ fn high_cost_target(raw: &str, cwd: &str, home: &str) -> bool { } /// TS `path.ts` resolution of the `cwd` argument. -fn resolve_cwd(value: &str, cwd: &Path, platform: &HostPlatform) -> PathBuf { +fn resolve_cwd(value: &str, cwd: &Path, home: &Path, os: Os) -> PathBuf { let expanded = if value == "~" { - platform.home.clone() + home.to_owned() } else if let Some(rest) = value .strip_prefix("~/") .or_else(|| value.strip_prefix("~\\")) { - platform.home.join(rest) - } else if platform.os == Os::Windows { + home.join(rest) + } else if os == Os::Windows { PathBuf::from(correct_windows_path(value)) } else { PathBuf::from(value) @@ -1920,12 +1920,26 @@ pub trait OutputSink: Send + Sync { fn push(&self, text: &str) -> impl Future + Send; } -pub(super) struct Output { +pub(crate) struct Output { capture: Mutex, /// Cancelled when the capture failed; the command is then terminated. failed: CancellationToken, } impl Output { + async fn ensure_file(&self) -> Result { + let mut capture = self.capture.lock().await; + if let Some(failure) = &capture.failure { + return Err(failure.clone()); + } + match capture.create_file().await { + Ok(()) => Ok(capture.path.to_string_lossy().into_owned()), + Err(error) => { + let error = error.to_string(); + capture.failure = Some(error.clone()); + Err(error) + } + } + } pub(super) async fn preview(&self) -> String { truncate_preview(&self.capture.lock().await.preview) } @@ -1934,6 +1948,143 @@ impl Output { self.capture.lock().await.truncated } } +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OutputTail { + pub text: String, + pub total_bytes: u64, + pub truncated: bool, +} + +#[derive(Debug, thiserror::Error)] +pub enum CaptureError { + #[error("Unknown execution task")] + Unknown, + #[error("{0}")] + Unavailable(String), +} + +impl ExecHost { + pub(crate) async fn start_command( + self: &Arc, + task_id: &str, + spec: ProcessSpec, + roots: &[PathBuf], + output_dir: &Path, + timeout: Option, + ) -> Result { + let (spec, temporary, isolation) = self.prepare_isolated_process(spec, roots, None).await?; + let mut commands = self.commands.lock().unwrap(); + if self.command_shutdown.is_cancelled() { + return Err(ProcessSpecError { + code: "cancelled", + reason: "Execution host closed".into(), + }); + } + if commands.contains_key(task_id) { + return Err(ProcessSpecError { + code: "task_exists", + reason: "Execution task already exists".into(), + }); + } + let mut tree = self.spawn(spec).map_err(|error| ProcessSpecError { + code: "exec_invalid_request", + reason: format!("Failed to spawn process: {error}"), + })?; + tree.hold(temporary); + let output = Arc::new(Output { + capture: Mutex::new(Capture { + path: output_dir.join(format!("{task_id}.log")), + inline: String::new(), + inline_units: 0, + preview: String::new(), + file: None, + file_bytes: 0, + output_bytes: 0, + truncated: false, + failure: None, + }), + failed: CancellationToken::new(), + }); + let stop_pumps = CancellationToken::new(); + let started = Instant::now(); + let pumps = vec![ + tokio::spawn(pump(tree.stdout(), output.clone(), stop_pumps.clone())), + tokio::spawn(pump(tree.stderr(), output.clone(), stop_pumps.clone())), + ]; + let (observed_tx, observed) = tokio::sync::watch::channel(None); + let (terminal_tx, terminal) = tokio::sync::watch::channel(None); + let task = Arc::new(CommandTask { + output: output.clone(), + path: output_dir.join(format!("{task_id}.log")), + started, + isolation, + kill: CancellationToken::new(), + timeout: CancellationToken::new(), + observed, + terminal, + }); + commands.insert( + task_id.to_owned(), + crate::host_platform::ExecutionTask::Command(task.clone()), + ); + let running = RunningCommand { + tree, + stop_pumps, + pumps, + output: output.clone(), + }; + let worker = task.clone(); + let shutdown = self.command_shutdown.clone(); + self.command_workers.spawn(async move { + running + .supervise(&worker, timeout, shutdown, observed_tx, terminal_tx) + .await; + }); + Ok(ExecProcess { + host: self.clone(), + task_id: task_id.to_owned(), + output, + task, + settle_on_drop: true, + }) + } + + pub(crate) fn command_task(&self, task_id: &str) -> Result, CaptureError> { + match self.commands.lock().unwrap().get(task_id) { + Some(crate::host_platform::ExecutionTask::Command(task)) => Ok(task.clone()), + _ => Err(CaptureError::Unknown), + } + } + + pub(crate) fn settle_command(&self, task_id: &str, task: &Arc) { + let mut commands = self.commands.lock().unwrap(); + if matches!( + commands.get(task_id), + Some(crate::host_platform::ExecutionTask::Command(held)) if Arc::ptr_eq(held, task) + ) { + commands.remove(task_id); + } + } + pub async fn retain_output(&self, task_id: &str) -> Result { + self.command_task(task_id)? + .output + .ensure_file() + .await + .map_err(CaptureError::Unavailable) + } + pub async fn tail(&self, task_id: &str) -> Result { + let task = self.command_task(task_id)?; + let output = &task.output; + let capture = output.capture.lock().await; + Ok(OutputTail { + text: truncate_preview(&capture.preview), + total_bytes: capture.output_bytes, + truncated: capture.truncated, + }) + } +} + impl OutputSink for Output { async fn push(&self, text: &str) { if text.is_empty() { @@ -1993,13 +2144,16 @@ pub async fn pump( } /// What ended the wait for a running command. +#[derive(Clone, Copy)] pub(super) enum Observed { + Cancelled, Exited(ExitStatus), TimedOut, OutputFailed, } /// Summary of a settled command's output. +#[derive(Clone)] struct Settled { output_path: Option, output_bytes: u64, @@ -2020,48 +2174,73 @@ impl Settled { } } -/// A started command: its process tree, the pipe readers and the output. -/// One owner at a time; moved from the handler to the supervising task. -pub struct ExecProcess { +pub(crate) struct CommandTask { + output: Arc, + path: PathBuf, + started: Instant, + isolation: Option, + pub(crate) kill: CancellationToken, + pub(crate) timeout: CancellationToken, + observed: tokio::sync::watch::Receiver>>, + terminal: tokio::sync::watch::Receiver>>, +} + +struct CommandTerminal { + observed: Result, + termination_error: Option, + duration_ms: u64, + output: Settled, +} + +struct RunningCommand { tree: ProcessTree, - pub(super) output: Arc, + output: Arc, pumps: Vec>, stop_pumps: CancellationToken, - started: Instant, - deadline: Option, - /// Set when HostPlatform sandboxed the command. - isolation: Option, } -impl ExecProcess { - /// Waits for the root exit, the total deadline or an output failure; - /// cancel safe, terminates nothing. An exit already there wins. - pub(super) async fn next(&mut self) -> io::Result { - let deadline = self.deadline; - tokio::select! { + +impl RunningCommand { + async fn supervise( + mut self, + task: &CommandTask, + timeout: Option, + shutdown: CancellationToken, + observed_tx: tokio::sync::watch::Sender>>, + terminal_tx: tokio::sync::watch::Sender>>, + ) { + let deadline = timeout.map(|ms| task.started + Duration::from_millis(ms)); + let observed = tokio::select! { biased; - status = self.tree.wait() => status.map(Observed::Exited), - _ = async { tokio::time::sleep_until(deadline.expect("guarded")).await }, - if deadline.is_some() => Ok(Observed::TimedOut), + status = self.tree.wait() => { + status.map(Observed::Exited).map_err(|error| error.to_string()) + }, + _ = async { tokio::time::sleep_until(deadline.expect("guarded")).await }, if deadline.is_some() => Ok(Observed::TimedOut), + _ = task.timeout.cancelled() => Ok(Observed::TimedOut), _ = self.output.failed.cancelled() => Ok(Observed::OutputFailed), - } - } - pub(super) async fn terminate(&mut self) -> io::Result<()> { - self.tree.terminate().await - } - async fn ensure_file(&self) -> Result { - let mut capture = self.output.capture.lock().await; - if let Some(failure) = &capture.failure { - return Err(failure.clone()); - } - match capture.create_file().await { - Ok(()) => Ok(capture.path.to_string_lossy().into_owned()), - Err(error) => { - let error = error.to_string(); - capture.failure = Some(error.clone()); - Err(error) - } - } + _ = task.kill.cancelled() => Ok(Observed::Cancelled), + _ = shutdown.cancelled() => Ok(Observed::Cancelled), + }; + let duration_ms = task.started.elapsed().as_millis() as u64; + observed_tx.send_replace(Some(observed.clone())); + let termination_error = if matches!(observed, Ok(Observed::Exited(_))) { + None + } else { + self.tree + .terminate() + .await + .err() + .map(|error| error.to_string()) + }; + let output = self.close().await; + drop(self); + terminal_tx.send_replace(Some(Arc::new(CommandTerminal { + observed, + duration_ms, + termination_error, + output, + }))); } + /// Starts the bounded pipe drain and waits for output writes to finish. async fn close(&mut self) -> Settled { self.stop_pumps.cancel(); @@ -2087,20 +2266,165 @@ impl ExecProcess { failure: capture.failure.clone(), } } +} +impl CommandTask { + pub(crate) async fn page( + &self, + cursor: u64, + limit: usize, + ) -> Result { + use super::background::{OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page}; + use tokio::io::AsyncSeekExt; + let capture = self.output.capture.lock().await; + let truncated = capture.truncated; + let budget = limit + PAGE_CHAR_TRAILING_BYTES; + if capture.file.is_none() { + let bytes = capture.inline.as_bytes(); + let start = usize::try_from(cursor) + .unwrap_or(usize::MAX) + .min(bytes.len()); + let end = start.saturating_add(budget).min(bytes.len()); + return decode_page(&bytes[start..end], cursor, limit, truncated); + } + drop(capture); + let mut file = tokio::fs::File::open(&self.path) + .await + .map_err(|_| OutputPageError::Unavailable)?; + file.seek(io::SeekFrom::Start(cursor)) + .await + .map_err(|_| OutputPageError::Unavailable)?; + let mut bytes = Vec::new(); + file.take(budget as u64) + .read_to_end(&mut bytes) + .await + .map_err(|_| OutputPageError::Unavailable)?; + decode_page(&bytes, cursor, limit, truncated) + } + + async fn completion(&self) -> Arc { + let mut done = self.terminal.clone(); + done.wait_for(Option::is_some) + .await + .expect("command supervisor publishes its terminal") + .as_ref() + .unwrap() + .clone() + } + pub(crate) async fn wait(&self, timeout_ms: Option) -> serde_json::Value { + let done = if let Some(ms) = timeout_ms { + tokio::select! { + biased; + result = self.completion() => result, + _ = tokio::time::sleep(Duration::from_millis(ms)) => { + self.timeout.cancel(); + self.completion().await + } + } + } else { + self.completion().await + }; + let exit = match done.observed { + Ok(Observed::Exited(status)) => Some(status), + _ => None, + }; + let status = match &done.observed { + _ if done.termination_error.is_some() || done.output.failure.is_some() => "failed", + Ok(Observed::Exited(status)) if signal_name(*status).is_some() => "signaled", + Ok(Observed::Exited(_)) => "exited", + Ok(Observed::TimedOut) => "timed_out", + Ok(Observed::Cancelled) => "cancelled", + _ => "failed", + }; + let mut reply = object( + json!({"status":status, "durationMs":done.duration_ms, "outputPath":self.path, + "outputBytes":done.output.output_bytes,"outputTruncated":done.output.truncated, + "preview":done.output.preview,"previewTruncated":done.output.preview_truncated}), + ); + insert_exit(&mut reply, exit); + if exit.is_some_and(|status| !status.success()) + && let Some(note) = self + .isolation + .and_then(|i| i.failure_hint(done.output.shown())) + { + reply.insert("failureNote".into(), note.into()); + } + Value::Object(reply) + } + pub(crate) async fn terminate(&self) -> io::Result<()> { + self.kill.cancel(); + self.completion() + .await + .termination_error + .as_deref() + .map_or(Ok(()), |error| Err(io::Error::other(error.to_owned()))) + } + pub(crate) fn ended(&self) -> bool { + self.terminal.borrow().is_some() + } +} + +pub struct ExecProcess { + host: Arc, + task_id: String, + pub(super) output: Arc, + task: Arc, + settle_on_drop: bool, +} +impl Drop for ExecProcess { + fn drop(&mut self) { + if !self.settle_on_drop { + return; + } + if self.task.ended() { + self.host.settle_command(&self.task_id, &self.task); + } else { + self.task.kill.cancel(); + let task = self.task.clone(); + let owner = self.host.clone(); + let id = self.task_id.clone(); + self.host.command_workers.spawn(async move { + task.completion().await; + owner.settle_command(&id, &task); + }); + } + } +} +impl ExecProcess { + pub(crate) fn retain_task(mut self) -> PathBuf { + self.settle_on_drop = false; + self.task.path.clone() + } + async fn next(&self) -> io::Result { + let mut observed = self.task.observed.clone(); + observed + .wait_for(Option::is_some) + .await + .expect("command supervisor publishes its observation") + .clone() + .unwrap() + .map_err(io::Error::other) + } + async fn close(&self) -> Settled { + self.task.completion().await.output.clone() + } + async fn terminate(&self) -> io::Result<()> { + self.task.terminate().await + } + /// Terminates, reaps and closes a process nobody will own. Preserve the /// failure and partial output if termination could not be confirmed. - pub(super) async fn abandon(mut self) -> Result<(), Box> { + pub(super) async fn abandon(self) -> Result<(), Box> { let terminated = self.terminate().await; let settled = self.close().await; terminated.map_err(|error| Box::new(terminate_failed(&error, &settled))) } fn wall_time_ms(&self) -> u64 { - self.started.elapsed().as_millis() as u64 + self.task.started.elapsed().as_millis() as u64 } /// Adds HostPlatform's note to a failed command's `note` when the command /// was sandboxed and its output shows a typical denial. fn failure_note(&self, note: String, settled: &Settled) -> String { - let isolation = self.isolation.as_ref(); + let isolation = self.task.isolation.as_ref(); match isolation.and_then(|isolation| isolation.failure_hint(settled.shown())) { Some(hint) => format!("{note}\n\n{hint}"), None => note, @@ -2110,7 +2434,7 @@ impl ExecProcess { /// Supervises a background command until it ends or `cancel` fires; the /// tree is released before the result is returned. pub(super) async fn finish_background( - mut self, + self, task_id: &str, cancel: CancellationToken, ) -> (ExecStatus, ToolResult) { @@ -2150,7 +2474,7 @@ impl ExecProcess { format!("exec process wait failed: {error}"), "failed", ), - (Ok(None), _) => ( + (Ok(None | Some(Observed::Cancelled)), _) => ( ExecStatus::Cancelled, "Command cancelled by user.".into(), "cancelled", @@ -2220,36 +2544,6 @@ fn insert_exit(structured: &mut JsonObject, exit: Option) { } } -/// The name of the signal that ended a process, as `exec` reports it. -#[cfg(unix)] -pub fn signal_name(status: ExitStatus) -> Option { - use std::os::unix::process::ExitStatusExt; - let signal = status.signal()?; - let name = match signal { - libc::SIGHUP => "SIGHUP", - libc::SIGINT => "SIGINT", - libc::SIGQUIT => "SIGQUIT", - libc::SIGILL => "SIGILL", - libc::SIGTRAP => "SIGTRAP", - libc::SIGABRT => "SIGABRT", - libc::SIGBUS => "SIGBUS", - libc::SIGFPE => "SIGFPE", - libc::SIGKILL => "SIGKILL", - libc::SIGUSR1 => "SIGUSR1", - libc::SIGSEGV => "SIGSEGV", - libc::SIGUSR2 => "SIGUSR2", - libc::SIGPIPE => "SIGPIPE", - libc::SIGALRM => "SIGALRM", - libc::SIGTERM => "SIGTERM", - _ => return Some(format!("SIG{signal}")), - }; - Some(name.into()) -} -#[cfg(windows)] -pub fn signal_name(_: ExitStatus) -> Option { - None -} - fn exit_failure_summary(status: ExitStatus) -> String { if let Some(code) = status.code() { return format!("Command exited with code {code}."); @@ -2366,7 +2660,7 @@ pub(super) async fn execute( }; let platform = &tools.platform; let cwd = match &input.cwd { - Some(value) => resolve_cwd(value, &tools.cwd, platform), + Some(value) => resolve_cwd(value, &tools.cwd, &tools.execution_home, tools.execution_os), None => tools.cwd.clone(), }; let (spec, shell) = match platform.build_process_spec(&input.command, &cwd).await { @@ -2398,9 +2692,11 @@ pub(super) async fn execute( )); } let cwd_text = cwd.to_string_lossy().into_owned(); - if let Some(refused) = - check_heavy_search(&input.command, &cwd_text, &platform.home.to_string_lossy()) - { + if let Some(refused) = check_heavy_search( + &input.command, + &cwd_text, + &tools.execution_home.to_string_lossy(), + ) { return Ok(refused); } let task_id = format!("exec-{}", uuid::Uuid::new_v4()); @@ -2417,32 +2713,15 @@ pub(super) async fn execute( Some(facts) => facts.0.workspace_roots(&cwd, cancel.clone()).await?, None => vec![tools.cwd.clone()], }; - let (spec, temporary, isolation) = - match platform.prepare_isolated_process(spec, &roots, None).await { - Ok(prepared) => prepared, - Err(error) => return Ok(failed(error.reason, error.code)), - }; - let tree = match platform.spawn(spec) { - Ok(tree) => tree, - Err(error) => { - return Ok(failed( - format!("Failed to spawn process: {error}"), - "exec_invalid_request", - )); - } + let process = match platform + .start_command(&task_id, spec, &roots, &tools.output_dir, effective_timeout) + .await + { + Ok(process) => process, + Err(error) => return Ok(failed(error.reason, error.code)), }; let (result, exit) = run_process( - tools, - branch, - call, - context, - &request, - tree, - temporary, - isolation, - background, - effective_timeout, - cancel, + tools, branch, call, context, &request, process, background, cancel, ) .await?; Ok(ran(result, request.command, exit)) @@ -2462,43 +2741,10 @@ async fn run_process( call: &ToolCall, context: &ToolExecutionContext, request: &Call<'_>, - mut tree: ProcessTree, - temporary: Option, - isolation: Option, + process: ExecProcess, background: bool, - timeout: Option, cancel: CancellationToken, ) -> Result<(ToolResult, Option), HostError> { - tree.hold(temporary); - let output = Arc::new(Output { - capture: Mutex::new(Capture { - path: tools.output_dir.join(format!("{}.log", request.task_id)), - inline: String::new(), - inline_units: 0, - preview: String::new(), - file: None, - file_bytes: 0, - output_bytes: 0, - truncated: false, - failure: None, - }), - failed: CancellationToken::new(), - }); - let stop_pumps = CancellationToken::new(); - let started = Instant::now(); - let pumps = vec![ - tokio::spawn(pump(tree.stdout(), output.clone(), stop_pumps.clone())), - tokio::spawn(pump(tree.stderr(), output.clone(), stop_pumps.clone())), - ]; - let mut process = ExecProcess { - tree, - output, - pumps, - stop_pumps, - started, - deadline: timeout.map(|timeout| started + Duration::from_millis(timeout)), - isolation, - }; if cancel.is_cancelled() { if let Err(result) = process.abandon().await { return Ok((*result, None)); @@ -2545,6 +2791,13 @@ async fn run_process( }; let exit = match observed { Ok(Observed::Exited(status)) => status, + Ok(Observed::Cancelled) => { + let settled = process.close().await; + return Ok(( + ToolResult::error(settled_content(&settled, Some("Command cancelled."))), + None, + )); + } Ok(Observed::OutputFailed) => { if let Err(error) = process.terminate().await { let settled = process.close().await; @@ -2660,13 +2913,13 @@ async fn hand_off( immediate: bool, cancel: &CancellationToken, ) -> Result<(ToolResult, Option), HostError> { - let output_path = match process.ensure_file().await { + let output_path = match process.host.retain_output(&request.task_id).await { Ok(path) => path, Err(error) => { if let Err(result) = process.abandon().await { return Ok((*result, None)); } - return Ok((offload_failed(&error), None)); + return Ok((offload_failed(&error.to_string()), None)); } }; if cancel.is_cancelled() { diff --git a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs index 8ae7975162..64249db367 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs @@ -19,7 +19,7 @@ pub use pending::call_positions; use crate::{ host::{HostError, HostFuture, SessionFiles, ToolDriver, ToolExecutionContext, ToolHost}, - host_platform::HostPlatform, + host_platform::ExecHost, methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, params, reply}, timeline_tree::TreeCommands, tool_registry::ToolConcurrency, @@ -144,7 +144,10 @@ impl DynPlugin for WorkspaceToolsOwner { pub(crate) struct WorkspaceTools { ctx: Ctx, facts: Key, - platform: Arc, + platform: Arc, + exec_definition: ToolDefinition, + execution_home: PathBuf, + execution_os: crate::host_platform::Os, cwd: PathBuf, output_dir: PathBuf, /// SessionStore's output ownership (ADR 013); absent in hosts without @@ -257,7 +260,7 @@ impl WorkspaceTools { impl ToolDriver for WorkspaceTools { fn definitions(&self) -> Vec { let mut definitions = FileTools::definitions(); - definitions.push(exec::definition_for(&self.platform)); + definitions.push(self.exec_definition.clone()); definitions.push(exec::stop_definition()); definitions } @@ -320,7 +323,7 @@ impl ToolDriver for WorkspaceTools { struct WorkspaceToolsPlugin { facts: Key, host: Key, - platform: Key, + platform: Key, session_config: Key, identity: Key, tree: Key, @@ -384,11 +387,13 @@ impl DynPlugin for WorkspaceToolsPlugin { let output_dir = self.config.output_root.join(&identity.session_id); // A configured boundary is the file tools' home too: `~` // resolves against it, never against the platform home. + let info = platform.facts(); + let exec_definition = exec::definition_for(&info); let home = self .config .boundary .as_ref() - .map_or(platform.home.clone(), |boundary| boundary.home.clone()); + .map_or_else(|| info.home.to_owned(), |boundary| boundary.home.clone()); let tools = Arc::new(WorkspaceTools { ctx: ctx.clone(), facts: self.facts.clone(), @@ -404,6 +409,9 @@ impl DynPlugin for WorkspaceToolsPlugin { session_id: identity.session_id.clone(), member: config.collaboration_role == CollaborationRole::Member, cwd, + exec_definition, + execution_home: info.home.to_owned(), + execution_os: info.os, platform, tree, lifecycle: CancellationToken::new(), diff --git a/crates/dim-agent-capabilities/tests/context_flow/compacted_bindings.rs b/crates/dim-agent-capabilities/tests/context_flow/compacted_bindings.rs index b2c86c0575..3f5c3a4db1 100644 --- a/crates/dim-agent-capabilities/tests/context_flow/compacted_bindings.rs +++ b/crates/dim-agent-capabilities/tests/context_flow/compacted_bindings.rs @@ -7,7 +7,7 @@ use dim_agent_capabilities::{ agent_loop::AgentLoop, defaults, history::summary_message, - host_platform::{HostPlatform, ShellStatus}, + host_platform::{ExecHost, ShellStatus}, workspace_tools::{self, WorkspaceToolsConfig}, }; use dim_agent_runtime::testing::chain_events; @@ -173,7 +173,7 @@ impl Files { let dir = std::env::temp_dir().join(format!("dim-compacted-{}", uuid::Uuid::new_v4())); std::fs::create_dir(&dir).unwrap(); let dir = dir.canonicalize().unwrap(); - let mut platform = HostPlatform::current(ShellStatus::Unavailable { + let mut platform = ExecHost::current(ShellStatus::Unavailable { code: "COMPACTED_BINDINGS_TEST", reason: "The file tools run no command here.".into(), }) @@ -217,7 +217,7 @@ impl Files { }, ); let agent = MinimalHost::start_with(&builder, |root, _| { - root.provide_as::(Arc::new(platform))?; + root.provide_as::(Arc::new(platform))?; Ok(()) }) .await diff --git a/crates/dim-agent-capabilities/tests/hooks_flow.rs b/crates/dim-agent-capabilities/tests/hooks_flow.rs index 77e88cfdf4..7890d8ba05 100644 --- a/crates/dim-agent-capabilities/tests/hooks_flow.rs +++ b/crates/dim-agent-capabilities/tests/hooks_flow.rs @@ -11,7 +11,7 @@ use dim_agent_capabilities::{ }, host::*, host_platform::{ - ExecShellRuntime, HostPlatform, OutputEncoding, ShellEdition, ShellSource, ShellStatus, + ExecHost, ExecShellRuntime, OutputEncoding, ShellEdition, ShellSource, ShellStatus, }, methods::{RpcError, SessionMethods}, model_provider::ModelProviderPlugin, @@ -545,7 +545,7 @@ impl Env { std::fs::create_dir_all(dir.join("work")).unwrap(); std::fs::create_dir_all(dir.join("home")).unwrap(); let dir = dir.canonicalize().unwrap(); - let mut platform = HostPlatform::current(ShellStatus::Available(ExecShellRuntime { + let mut platform = ExecHost::current(ShellStatus::Available(ExecShellRuntime { executable_path: "/bin/sh".into(), edition: ShellEdition::Sh, source: ShellSource::Fallback, @@ -653,7 +653,7 @@ impl Env { dim_agent_capabilities::hooks::install(&mut builder); } let agent = MinimalHost::start_with(&builder, |root, _| { - root.provide_as::(Arc::new(platform))?; + root.provide_as::(Arc::new(platform))?; root.provide_as::(Arc::new(SkillSettingsHost(Arc::new( MemorySkillSettings::default(), ))))?; diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 329684350f..8063bceb8a 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -99,7 +99,7 @@ async fn shell_resolution_follows_the_preference_and_never_fails_the_service() { #[tokio::test] async fn spawn_isolates_the_environment_and_terminate_releases_the_tree() { - let platform = HostPlatform::current(ShellStatus::Unavailable { + let platform = ExecHost::current(ShellStatus::Unavailable { code: EXEC_SHELL_UNAVAILABLE, reason: "spawn does not need a shell".into(), }) @@ -192,7 +192,15 @@ async fn unchanged_shell_preferences_reuse_detection_and_edits_recover() { ]) .env(CHILD_HOME, &home) .env("SHELL", &shell) - .env("PATH", &bin) + .env( + "PATH", + std::env::join_paths([ + bin.as_path(), + std::path::Path::new("/usr/bin"), + std::path::Path::new("/bin"), + ]) + .unwrap(), + ) .output() .await .unwrap(); @@ -232,14 +240,15 @@ async fn unchanged_shell_preferences_reuse_detection_and_edits_recover() { HostPlatformConfig { execution: names.key().unwrap(), toolchain: names.key().unwrap(), + command_files: Some((0, "command-output".into())), exec_shell_file: Some((0, "exec-shell.json".into())), - home: None, + home: Some(home.clone()), }, ) .unwrap(), ); (&platform).await.unwrap(); - let platform = root.get::().unwrap(); + let platform = root.get::().unwrap(); assert!(matches!( platform.exec_shell().await, ShellStatus::Unavailable { @@ -250,6 +259,173 @@ async fn unchanged_shell_preferences_reuse_detection_and_edits_recover() { std::os::unix::fs::symlink("/bin/bash", &shell).unwrap(); let selected = platform.exec_shell().await; assert!(matches!(selected, ShellStatus::Available(_))); + let face = root + .get_at(&rutis_bridge::session::host_key("execHost")) + .unwrap(); + let facts = + rutis_bridge::session::settle(face.invoke("info", serde_json::json!([{}]).into()).unwrap()) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(facts, serde_json::to_value(platform.info().await).unwrap()); + assert_eq!(facts["arch"], platform.arch); + assert_eq!(facts["execShell"]["state"], "available"); + assert_eq!(facts["execShell"]["executable"], shell.to_str().unwrap()); + let request = serde_json::json!([{ + "program": "/bin/sh", + "args": ["-c", "printf abc; printf def >&2; exit 7"], + "read": [], + "write": [home], + "timeoutMs": 10000, + "outputLimit": {"stdout": 3, "stderr": 3}, + "services": "none" + }]); + let reply = rutis_bridge::session::settle(face.invoke("confined", request.into()).unwrap()) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(reply["status"], 7); + assert_eq!(reply["stdout"], "YWJj"); + assert_eq!(reply["stderr"], "ZGVm"); + assert_eq!(reply["stdoutTruncated"], false); + assert_eq!(reply["stderrTruncated"], false); + let configured = serde_json::json!([{ + "command": r#"read -r line; printf '%s' "$line"; printf '%s' "$WIRE_ENV" >&2; exit 2"#, + "cwd": home, + "env": {"WIRE_ENV":"test"}, + "stdin":"YWJjCg==", + "timeoutMs":10000, + "limits":{"stdout":3,"stderr":2} + }]); + let reply = + rutis_bridge::session::settle(face.invoke("configured", configured.into()).unwrap()) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(reply["status"], "exited"); + assert_eq!(reply["exitCode"], 2); + assert_eq!(reply["stdout"], "YWJj"); + assert_eq!(reply["stderr"], "dGU="); + assert_eq!(reply["stdoutTruncated"], false); + assert_eq!(reply["stderrTruncated"], true); + let invoke = async |method: &str, request: serde_json::Value| { + let value = face.invoke(method, serde_json::json!([request]).into())?; + rutis_bridge::session::settle(value).await?.json() + }; + let start = serde_json::json!({"taskId":"short-command", "command":"printf retained", "cwd":home, + "workspace":home, "roots":[], "outputDir":home.join("command-output/session")}); + let output = invoke("start", start.clone()).await.unwrap(); + let task = serde_json::json!({"taskId":"short-command"}); + let terminal = invoke("wait", task.clone()).await.unwrap(); + assert_eq!(terminal["status"], "exited"); + assert_eq!(terminal["preview"], "retained"); + assert_eq!(terminal["outputBytes"], 8); + assert_eq!(terminal["outputPath"], output["outputPath"]); + assert!(!std::path::Path::new(output["outputPath"].as_str().unwrap()).exists()); + let page = invoke( + "output", + serde_json::json!({"taskId":"short-command", "limit":3}), + ) + .await + .unwrap(); + assert_eq!( + page, + serde_json::json!({"text":"ret","bytes":3,"nextCursor":3,"truncated":false,"retainedFrom":0}) + ); + assert!(invoke("start", start).await.is_err()); + assert_eq!(invoke("retainOutput", task.clone()).await.unwrap(), output); + assert_eq!( + std::fs::read(output["outputPath"].as_str().unwrap()).unwrap(), + b"retained" + ); + invoke("kill", task.clone()).await.unwrap(); + assert_eq!(invoke("wait", task.clone()).await.unwrap(), terminal); + invoke("settle", task.clone()).await.unwrap(); + assert!(invoke("wait", task).await.is_err()); + let retained = invoke( + "output", + serde_json::json!({"outputPath":output["outputPath"],"cursor":3}), + ) + .await + .unwrap(); + assert_eq!(retained["text"], "ained"); + assert!( + invoke( + "output", + serde_json::json!({"outputPath":home.join("exec-shell.json")}) + ) + .await + .is_err() + ); + let deadline = serde_json::json!({"taskId":"deadline"}); + invoke( + "start", + serde_json::json!({"taskId":"deadline","command":"sleep 5","cwd":home, + "workspace":home,"roots":[],"outputDir":home,"timeoutMs":25}), + ) + .await + .unwrap(); + assert_eq!( + invoke("wait", deadline.clone()).await.unwrap()["status"], + "timed_out" + ); + invoke("settle", deadline).await.unwrap(); + let shell_id = serde_json::json!({"taskId":"interactive"}); + invoke("shell",serde_json::json!({"taskId":"interactive","cwd":home,"workspace":home,"roots":[],"outputDir":platform.exec_root().join("session/branch"),"cols":80,"rows":24})).await.unwrap(); + invoke( + "resize", + serde_json::json!({"taskId":"interactive","cols":100,"rows":32}), + ) + .await + .unwrap(); + invoke( + "write", + serde_json::json!({"taskId":"interactive","data":"ZXhpdCA3Cg=="}), + ) + .await + .unwrap(); + let finished = invoke( + "wait", + serde_json::json!({"taskId":"interactive","timeoutMs":10000}), + ) + .await + .unwrap(); + assert_eq!(finished["exitCode"], 7); + let captured = invoke("output", shell_id.clone()).await.unwrap(); + assert_eq!(captured["retainedFrom"], 0); + invoke("settle", shell_id).await.unwrap(); + let output_root = platform.exec_root(); + let branch_output = output_root.join("session/branch"); + std::fs::create_dir_all(&branch_output).unwrap(); + std::fs::write(branch_output.join("command.log"), "output").unwrap(); + for path in [&output_root, &home, &output_root.join("../bin")] { + let request = serde_json::json!([{"path":path}]); + assert!( + rutis_bridge::session::settle( + face.invoke("removeOutputDirectory", request.into()) + .unwrap() + ) + .await + .is_err() + ); + } + let request = serde_json::json!([{"path":branch_output}]); + for _ in 0..2 { + let reply = rutis_bridge::session::settle( + face.invoke("removeOutputDirectory", request.clone().into()) + .unwrap(), + ) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(reply, serde_json::json!({})); + assert!(!branch_output.exists()); + } + std::fs::remove_file(&shell).unwrap(); let cloned = (*platform).clone(); for status in futures_util::future::join_all([platform.exec_shell(), cloned.exec_shell()]).await @@ -281,13 +457,34 @@ async fn unchanged_shell_preferences_reuse_detection_and_edits_recover() { platform.exec_shell().await, ShellStatus::Available(_) )); - root.shutdown().await.unwrap(); + let request = serde_json::json!([{ + "command": "printf ready > started; exec /bin/sleep 60", + "cwd": home, "timeoutMs": 60000, "limits": {"stdout": 0, "stderr": 0} + }]); + let pending = tokio::spawn(rutis_bridge::session::settle( + face.invoke("configured", request.clone().into()).unwrap(), + )); + tokio::time::timeout(std::time::Duration::from_secs(10), async { + while !home.join("started").exists() { + tokio::task::yield_now().await; + } + root.shutdown().await.unwrap(); + }) + .await + .unwrap(); + let stopped = pending.await.unwrap().unwrap().json().unwrap(); + assert_eq!(stopped["status"], "cancelled"); + assert!( + rutis_bridge::session::settle(face.invoke("configured", request.into()).unwrap()) + .await + .is_err() + ); } /// A start whose stdin carries the payload and then closes it. #[tokio::test] async fn spawn_with_stdin_delivers_the_bytes_and_closes_the_pipe() { - let platform = HostPlatform::current(ShellStatus::Unavailable { + let platform = ExecHost::current(ShellStatus::Unavailable { code: EXEC_SHELL_UNAVAILABLE, reason: "spawn does not need a shell".into(), }) @@ -336,7 +533,7 @@ async fn sandbox_backend_reports_the_bubblewrap_preparation_uses() { .unwrap() .join(format!("dim-backend-{}", uuid::Uuid::new_v4().simple())); std::fs::create_dir_all(&base).unwrap(); - let mut platform = HostPlatform::current(ShellStatus::Unavailable { + let mut platform = ExecHost::current(ShellStatus::Unavailable { code: "test", reason: String::new(), }) @@ -355,8 +552,8 @@ async fn sandbox_backend_reports_the_bubblewrap_preparation_uses() { /// The host-owned helper is always confined where the platform can confine, /// whatever the Process isolation switch says. -fn confined_platform(settings: ExecutionSettings) -> HostPlatform { - HostPlatform::current(ShellStatus::Unavailable { +fn confined_platform(settings: ExecutionSettings) -> ExecHost { + ExecHost::current(ShellStatus::Unavailable { code: "test", reason: String::new(), }) @@ -406,7 +603,7 @@ fn perl() -> Option { } async fn confined( - platform: &HostPlatform, + platform: &ExecHost, script: &str, write: &std::path::Path, timeout: Duration, @@ -1128,8 +1325,8 @@ fn runtime_fixture(base: &std::path::Path, name: &str) -> PathBuf { /// A platform whose shell is `/bin/sh` and whose captured environment is /// `env`, with `toolchains` as the runtimes Dim downloaded. -fn toolchain_platform(pairs: &[(&str, &str)], toolchains: Vec) -> HostPlatform { - let mut platform = HostPlatform::current(ShellStatus::Available(ExecShellRuntime { +fn toolchain_platform(pairs: &[(&str, &str)], toolchains: Vec) -> ExecHost { + let mut platform = ExecHost::current(ShellStatus::Available(ExecShellRuntime { executable_path: "/bin/sh".into(), edition: ShellEdition::Sh, source: ShellSource::Login, diff --git a/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs index fe549dfd19..957be35237 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs @@ -8,8 +8,8 @@ use std::{ffi::OsString, path::PathBuf, time::Duration}; use tokio_util::sync::CancellationToken; /// A platform whose Process isolation switch is off. -fn platform() -> HostPlatform { - HostPlatform::current(ShellStatus::Unavailable { +fn platform() -> ExecHost { + ExecHost::current(ShellStatus::Unavailable { code: "test", reason: String::new(), }) diff --git a/crates/dim-agent-capabilities/tests/permission_flow.rs b/crates/dim-agent-capabilities/tests/permission_flow.rs index 735f102822..3db27f43af 100644 --- a/crates/dim-agent-capabilities/tests/permission_flow.rs +++ b/crates/dim-agent-capabilities/tests/permission_flow.rs @@ -3,7 +3,7 @@ use dim_agent_capabilities::{ approval::{AdmitCall, Approval}, defaults, file_access, host::*, - host_platform::{HostPlatform, ShellStatus}, + host_platform::{ExecHost, ShellStatus}, model_provider::ModelProviderPlugin, permission::{ AdmissionDecision, AdviseTool, CommandRules, Decision, NoCommandRules, Permission, @@ -328,7 +328,7 @@ async fn granted_agent( tools, grants, files, - HostPlatform::current(ShellStatus::Unavailable { + ExecHost::current(ShellStatus::Unavailable { code: "PERMISSION_TEST", reason: "The permission flow starts no process".into(), }) @@ -341,7 +341,7 @@ async fn granted_agent_with( tools: Arc, grants: Arc, files: Arc, - platform: HostPlatform, + platform: ExecHost, associations: Option, ) -> MinimalHost { let mut builder = AgentBuilder::new(AgentConfig::default()); diff --git a/crates/dim-agent-capabilities/tests/permission_flow/worktrees.rs b/crates/dim-agent-capabilities/tests/permission_flow/worktrees.rs index deda653779..8208acec8a 100644 --- a/crates/dim-agent-capabilities/tests/permission_flow/worktrees.rs +++ b/crates/dim-agent-capabilities/tests/permission_flow/worktrees.rs @@ -76,8 +76,8 @@ impl Probes { std::fs::write(&file, format!("#!/bin/sh\nprintf '%s\\n' \"$*\" >> '{}/calls'\nif test -f '{}/pause'; then\n : > '{}/entered'\n while test -f '{}/pause'; do /bin/sleep 0.01; done\nfi\nexec /usr/bin/git \"$@\"\n", self.root.display(), self.root.display(), self.root.display(), self.root.display())).unwrap(); std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o700)).unwrap(); } - fn platform(&self) -> HostPlatform { - let mut platform = HostPlatform::current(ShellStatus::Unavailable { + fn platform(&self) -> ExecHost { + let mut platform = ExecHost::current(ShellStatus::Unavailable { code: "WORKTREE_TEST", reason: "No model shell is used".into(), }) diff --git a/crates/dim-agent-capabilities/tests/workspace_files.rs b/crates/dim-agent-capabilities/tests/workspace_files.rs index aa19c8195d..902c6842ba 100644 --- a/crates/dim-agent-capabilities/tests/workspace_files.rs +++ b/crates/dim-agent-capabilities/tests/workspace_files.rs @@ -2929,7 +2929,7 @@ mod toolhost { defaults, execution_settings::ExecutionSettingsHost, host_platform::{ - ExecShellRuntime, HostPlatform, OutputEncoding, ShellEdition, ShellSource, ShellStatus, + ExecHost, ExecShellRuntime, OutputEncoding, ShellEdition, ShellSource, ShellStatus, }, workspace_tools::{self, FileToolBoundary, WorkspaceToolsConfig}, }; @@ -2944,7 +2944,7 @@ mod toolhost { std::fs::create_dir_all(root.join("home")).unwrap(); let root = root.canonicalize().unwrap(); let workspace = root.join("workspace"); - let mut platform = HostPlatform::current(ShellStatus::Available(ExecShellRuntime { + let mut platform = ExecHost::current(ShellStatus::Available(ExecShellRuntime { executable_path: "/bin/sh".into(), edition: ShellEdition::Sh, source: ShellSource::Fallback, @@ -2968,7 +2968,7 @@ mod toolhost { }, ); let agent = MinimalHost::start_with(&builder, |root, _| { - root.provide_as::(Arc::new(platform))?; + root.provide_as::(Arc::new(platform))?; Ok(()) }) .await diff --git a/crates/dim-app-server/src/exec_shell_settings.rs b/crates/dim-app-server/src/exec_shell_settings.rs index fbeffe40ca..e5e9cb072a 100644 --- a/crates/dim-app-server/src/exec_shell_settings.rs +++ b/crates/dim-app-server/src/exec_shell_settings.rs @@ -1,6 +1,6 @@ use crate::{methods::ManagementMethods, protocol::Empty}; use dim_agent_capabilities::{ - host_platform::{ExecShellSettingsError, HostPlatform}, + host_platform::{ExecHost, ExecShellSettingsError}, methods::{Interruption, MethodCall, MethodDecl, RpcError, params, reply}, }; use dim_agent_runtime::Names; @@ -28,7 +28,7 @@ fn shell_failed(error: ExecShellSettingsError) -> RpcError { } pub(crate) struct ExecShellSettingsPlugin { - platform: Key, + platform: Key, methods: Key, } diff --git a/crates/dim-app-server/src/execution_settings.rs b/crates/dim-app-server/src/execution_settings.rs index 525bd23f88..59a7bacbd8 100644 --- a/crates/dim-app-server/src/execution_settings.rs +++ b/crates/dim-app-server/src/execution_settings.rs @@ -9,7 +9,7 @@ use crate::settings::{Settings, SettingsScope, SourceDeclaration}; use dim_agent_capabilities::execution_settings::{ ExecutionSettingsError, ExecutionSettingsHost, SOURCE, }; -use dim_agent_capabilities::host_platform::{HostPlatform, SandboxBackend}; +use dim_agent_capabilities::host_platform::{ExecHost, SandboxBackend}; use dim_agent_capabilities::methods::{Interruption, MethodCall, MethodDecl, params, reply}; use dim_agent_runtime::{Names, PartRegistry}; use rutis::Ctx; @@ -92,7 +92,7 @@ struct BackendView { /// The read-only management surface HostPlatform's backend availability needs. /// The switches themselves stay `settings.read`/`settings.update`. pub struct ExecutionBackendPlugin { - platform: Key, + platform: Key, methods: Key, } @@ -135,7 +135,7 @@ impl DynPlugin for ExecutionBackendPlugin { match method.as_str() { "host.execution.backend" => { let _: Empty = params(value)?; - let (available, reason) = match platform.sandbox_backend() { + let (available, reason) = match platform.info().await.backend { SandboxBackend::Available => (true, None), SandboxBackend::Unavailable { reason } => (false, Some(reason)), }; diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index 26e44b9b29..daa19d971c 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -993,6 +993,9 @@ pub async fn serve(mut builder: AgentBuilder, mut config: ServerConfig) -> Resul dim_agent_capabilities::host_platform::HostPlatformConfig { execution: names.key()?, toolchain: names.key()?, + command_files: session_files_root.map(|root| { + (root, crate::storage::COMMAND_OUTPUT_DIRECTORY.into()) + }), exec_shell_file: Some((home_root, "exec-shell.json".into())), home: platform_home.clone(), }, @@ -1516,7 +1519,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("fileStorage", "object"), ("grokOAuthService", "secret"), ("historyRenderer", "hot-path"), - ("hostPlatform", "object"), ("loader", "owner-api"), ("loopState", "hot-path"), // Session creation calls it directly; no leaf needs the service. diff --git a/crates/dim-app-server/src/mcp/server.rs b/crates/dim-app-server/src/mcp/server.rs index b5820db650..2806e5553b 100644 --- a/crates/dim-app-server/src/mcp/server.rs +++ b/crates/dim-app-server/src/mcp/server.rs @@ -4,7 +4,7 @@ mod stdio; use super::auth::{Credential, McpAuth, Refusal, credential_key}; use super::config::{BearerAuth, McpServerSettings, RemoteTransport}; -use dim_agent_capabilities::host_platform::HostPlatform; +use dim_agent_capabilities::host_platform::ExecHost; use dim_agent_runtime::StateCell; use dim_agent_types::{ ContentBlock, ImageSource, ImageSourceType, JsonObject, JsonSchema, ToolContent, ToolResult, @@ -590,7 +590,7 @@ pub struct McpServer { /// The host a stdio child takes its `PATH` from: the entry's own, else /// this host's, with the installed runtimes appended. Read optionally, so /// a host without HostPlatform spawns as before. - platform: Option>, + platform: Option>, tool_call_timeout: Option, authorization: Option, state: StateCell, @@ -1413,7 +1413,7 @@ impl Plugin for McpServerPlugin { let state = StateCell::new(McpServerState::Disconnected); let service = Arc::new(McpServer { transport: self.transport.clone(), - platform: ctx.get_at(&Key::::of()), + platform: ctx.get_at(&Key::::of()), tool_call_timeout: self.tool_call_timeout, authorization: self.oauth.clone().map(|(key, server)| Authorization { credential: auth.credential(key), diff --git a/crates/dim-app-server/src/mcp/server/stdio.rs b/crates/dim-app-server/src/mcp/server/stdio.rs index beaea3d37e..eb643a1c82 100644 --- a/crates/dim-app-server/src/mcp/server/stdio.rs +++ b/crates/dim-app-server/src/mcp/server/stdio.rs @@ -1,6 +1,6 @@ //! Server-owned stdio only; client-local processes require a separate bridge. use super::{DIAGNOSTIC_BYTES, McpServerError, Result}; -use dim_agent_capabilities::host_platform::HostPlatform; +use dim_agent_capabilities::host_platform::ExecHost; use futures_util::{SinkExt, StreamExt}; use rmcp::{ RoleClient, @@ -141,7 +141,7 @@ impl Config { /// system and Windows directories, and the parent's `PATH`, with `.exe` /// appended when the name has no extension. A `.cmd` shim such as /// `npx.cmd` is found only by its full name. - fn child_path(&self, platform: Option<&HostPlatform>) -> Option { + fn child_path(&self, platform: Option<&ExecHost>) -> Option { let platform = platform?; let base = self .env @@ -163,7 +163,7 @@ impl Config { pub fn spawn( &self, failure: Arc>>, - platform: Option<&HostPlatform>, + platform: Option<&ExecHost>, ) -> Result { let mut command = Command::new(&self.command); command diff --git a/crates/dim-app-server/src/skills_management.rs b/crates/dim-app-server/src/skills_management.rs index 30cde4c5b5..970fd03f65 100644 --- a/crates/dim-app-server/src/skills_management.rs +++ b/crates/dim-app-server/src/skills_management.rs @@ -17,7 +17,7 @@ use dim_agent_capabilities::skills::{ SkillsCatalogBinding, SkillsError, selection_path, valid_installation_id, }; use dim_agent_capabilities::{ - host_platform::HostPlatform, + host_platform::ExecHost, skill_settings::{ SOURCE, SettingsVersion, SkillInstallSource, SkillInstallation, SkillSettings, SkillSettingsError, SkillSettingsHost, SkillSettingsSnapshot, @@ -596,7 +596,7 @@ fn recorded(source: &SkillInstallSource) -> SourceParams { } pub struct SkillsCatalogPlugin { - platform: Key, + platform: Key, settings: Key, methods: Key, parts: Key, @@ -629,13 +629,13 @@ impl DynPlugin for SkillsCatalogPlugin { let settings = ctx.require_at(&self.settings)?; let methods = ctx.require_at(&self.methods)?; let parts = ctx.require_at(&self.parts)?; - let home = platform.home.clone(); + let home = platform.facts().home.to_owned(); clean_staging(&home); settings.register::(ctx)?; let settings = Arc::new(SkillSettingsHost(Arc::new(SkillStorage { settings }))); let catalog = dim_agent_capabilities::skills::SkillsCatalogPlugin::mount( ctx, - (platform, settings), + (home.clone(), settings), ) .await?; ctx.provide_at(dim_agent_capabilities::skills::owner_key(), catalog.clone())?; diff --git a/crates/dim-app-server/src/storage/files.rs b/crates/dim-app-server/src/storage/files.rs index 748655492f..5707787ccb 100644 --- a/crates/dim-app-server/src/storage/files.rs +++ b/crates/dim-app-server/src/storage/files.rs @@ -16,7 +16,7 @@ use super::{SqliteStorage, sqlite::error}; use dim_agent_capabilities::{ file_storage::{FileStorage, FileStorageError}, host::{SessionFileError, SessionFileErrorCode, SessionFilesService, StoredSessionFile}, - host_platform::HostPlatform, + host_platform::ExecHost, }; use rusqlite::{Connection, TransactionBehavior, params}; use rutis::Ctx; @@ -362,17 +362,14 @@ impl SessionFiles { .ctx .get::() .ok_or_else(|| error("the Session's resource node storage is unavailable"))?; - let host = self.0.ctx.get::(); + let host = self.0.ctx.get::(); for candidate in candidates { if let Some(host) = host .as_ref() .filter(|host| candidate.starts_with(host.exec_root())) { - let path = candidate.clone(); - let host = host.clone(); - tokio::task::spawn_blocking(move || host.remove_exec_directory(&path)) + host.remove_output_directory(candidate) .await - .map_err(error)? .map_err(error)?; continue; } diff --git a/crates/dim-app-server/src/storage/files/tests.rs b/crates/dim-app-server/src/storage/files/tests.rs index a8f44ceb36..dd0582c953 100644 --- a/crates/dim-app-server/src/storage/files/tests.rs +++ b/crates/dim-app-server/src/storage/files/tests.rs @@ -7,7 +7,7 @@ use super::*; use crate::storage::{SessionStore, SqliteTimelineStore}; use dim_agent_capabilities::file_storage::FileStoragePlugin; -use dim_agent_capabilities::host_platform::{HostPlatform, ShellStatus}; +use dim_agent_capabilities::host_platform::{ExecHost, ShellStatus}; use dim_agent_runtime::{SessionConfig, TimelineStore}; use rutis::host::CtxHost; use std::path::PathBuf; @@ -562,7 +562,7 @@ async fn concurrent_deletes_remove_a_shared_output_directory() { #[tokio::test] async fn a_delete_removes_shell_output_of_its_last_owner() { let fixture = Fixture::new().await; - let mut platform = HostPlatform::current(ShellStatus::Unavailable { + let mut platform = ExecHost::current(ShellStatus::Unavailable { code: "DELETE_FLOW", reason: "Deleting output runs no command".into(), }) @@ -570,7 +570,7 @@ async fn a_delete_removes_shell_output_of_its_last_owner() { platform.home = fixture.home.clone(); fixture .root - .provide_as::(Arc::new(platform)) + .provide_as::(Arc::new(platform)) .unwrap(); let store = SessionStore::new(fixture.db.clone(), fixture.root.clone(), 0); fixture.session("source").await; diff --git a/crates/dim-app-server/tests/mcp_session_flow.rs b/crates/dim-app-server/tests/mcp_session_flow.rs index a8302ac1de..ce7add0ad2 100644 --- a/crates/dim-app-server/tests/mcp_session_flow.rs +++ b/crates/dim-app-server/tests/mcp_session_flow.rs @@ -6,7 +6,7 @@ use axum::{ response::{IntoResponse, Response, Sse, sse::Event}, routing::post, }; -use dim_agent_capabilities::host_platform::HostPlatform; +use dim_agent_capabilities::host_platform::ExecHost; #[cfg(unix)] use dim_agent_capabilities::host_platform::ShellStatus; #[cfg(unix)] @@ -575,7 +575,7 @@ impl Env { async fn with_stdio_toolchain(bin: PathBuf, root: PathBuf) -> Self { let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mcp-minimal.cjs"); - let platform = HostPlatform::current(ShellStatus::Unavailable { + let platform = ExecHost::current(ShellStatus::Unavailable { code: "test", reason: "stdio does not need a shell".into(), }) @@ -604,7 +604,7 @@ impl Env { configure: impl FnOnce(&mut AgentBuilder, &Arc), configuration: impl FnOnce(&str, &Path) -> Value, credential_names: BTreeSet, - platform: Option, + platform: Option, ) -> Self { let remote = Remote::new(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); diff --git a/crates/dim-app-server/tests/read_image_flow.rs b/crates/dim-app-server/tests/read_image_flow.rs index 7981ae817d..36f01df027 100644 --- a/crates/dim-app-server/tests/read_image_flow.rs +++ b/crates/dim-app-server/tests/read_image_flow.rs @@ -11,7 +11,7 @@ use dim_agent_capabilities::{ defaults, history::HistoryRenderer, host::*, - host_platform::{HostPlatform, ShellStatus}, + host_platform::{ExecHost, ShellStatus}, workspace_tools::{self, WorkspaceToolsConfig}, }; use dim_agent_runtime::testing::chain_events; @@ -189,7 +189,7 @@ async fn accumulated_user_and_read_images_do_not_block_native_conversation() { let home = tempfile::tempdir().unwrap(); let work = home.path().canonicalize().unwrap(); - let mut platform = HostPlatform::current(ShellStatus::Unavailable { + let mut platform = ExecHost::current(ShellStatus::Unavailable { code: "READ_IMAGE_FLOW", reason: "Reading the fixture runs no command".into(), }) @@ -269,7 +269,7 @@ async fn accumulated_user_and_read_images_do_not_block_native_conversation() { }, ); let agent = MinimalHost::start_with(&builder, |root, _| { - root.provide_as::(Arc::new(platform))?; + root.provide_as::(Arc::new(platform))?; Ok(()) }) .await @@ -492,7 +492,7 @@ async fn an_offloaded_read_result_registers_its_output_path() { ) .unwrap(); - let mut platform = HostPlatform::current(ShellStatus::Unavailable { + let mut platform = ExecHost::current(ShellStatus::Unavailable { code: "OFFLOAD_FLOW", reason: "Reading a fixture runs no command".into(), }) @@ -511,7 +511,7 @@ async fn an_offloaded_read_result_registers_its_output_path() { }, ); let agent = MinimalHost::start_with(&builder, move |root, _| { - root.provide_as::(Arc::new(platform))?; + root.provide_as::(Arc::new(platform))?; root.provide_as::(owner)?; Ok(()) }) diff --git a/crates/dim-app-server/tests/session_files_flow.rs b/crates/dim-app-server/tests/session_files_flow.rs index bc06c65aad..b4bba837de 100644 --- a/crates/dim-app-server/tests/session_files_flow.rs +++ b/crates/dim-app-server/tests/session_files_flow.rs @@ -366,7 +366,7 @@ async fn a_put_without_active_file_storage_reports_node_unavailable() { async fn a_session_reads_its_own_file_without_an_approval_request() { use dim_agent_capabilities::{ defaults, - host_platform::{HostPlatform, ShellStatus}, + host_platform::{ExecHost, ShellStatus}, permission::PermissionState, workspace_tools::WorkspaceToolsConfig, }; @@ -377,7 +377,7 @@ async fn a_session_reads_its_own_file_without_an_approval_request() { let work = home.0.join("work"); std::fs::create_dir(&work).unwrap(); let store = Store::mount(&home, true).await; - let mut platform = HostPlatform::current(ShellStatus::Unavailable { + let mut platform = ExecHost::current(ShellStatus::Unavailable { code: "SESSION_FILES_TEST", reason: "Reading a Session file runs no command".into(), }) @@ -395,7 +395,7 @@ async fn a_session_reads_its_own_file_without_an_approval_request() { }, ); let agent = MinimalHost::start_with(&builder, |root, _| { - root.provide_as::(Arc::new(platform))?; + root.provide_as::(Arc::new(platform))?; Ok(()) }) .await diff --git a/crates/dim-app-server/tests/transport_flow/branches.rs b/crates/dim-app-server/tests/transport_flow/branches.rs index dcbbddde31..8c70b05ea0 100644 --- a/crates/dim-app-server/tests/transport_flow/branches.rs +++ b/crates/dim-app-server/tests/transport_flow/branches.rs @@ -628,9 +628,9 @@ async fn launch_prompt_sources( (server, agent, home) } -fn prompt_platform(home: &std::path::Path) -> dim_agent_capabilities::host_platform::HostPlatform { - use dim_agent_capabilities::host_platform::{HostPlatform, Os, ShellStatus}; - let mut platform = HostPlatform::current(ShellStatus::Unavailable { +fn prompt_platform(home: &std::path::Path) -> dim_agent_capabilities::host_platform::ExecHost { + use dim_agent_capabilities::host_platform::{ExecHost, Os, ShellStatus}; + let mut platform = ExecHost::current(ShellStatus::Unavailable { code: "PROMPT_BRANCH", reason: "the flow runs no command".into(), }) @@ -643,7 +643,7 @@ fn prompt_platform(home: &std::path::Path) -> dim_agent_capabilities::host_platf platform } -struct PromptPlatform(Arc); +struct PromptPlatform(Arc); impl rutis::host::DynPlugin for PromptPlatform { fn name(&self) -> &str { "PromptBranchPlatform" @@ -656,7 +656,7 @@ impl rutis::host::DynPlugin for PromptPlatform { ctx: &'a rutis::Ctx, ) -> rutis::host::BoxFuture<'a, rutis::Result> { Box::pin(async move { - ctx.provide_as::(self.0.clone())?; + ctx.provide_as::(self.0.clone())?; Ok(rutis::host::Effect::Done) }) } diff --git a/crates/dim-app-server/tests/transport_flow/process_typescript.rs b/crates/dim-app-server/tests/transport_flow/process_typescript.rs index 651d0ba8b4..067fd34ae8 100644 --- a/crates/dim-app-server/tests/transport_flow/process_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/process_typescript.rs @@ -1441,7 +1441,7 @@ async fn node_store_preserves_repository_results_and_worktree_removal_exclusion( ..Default::default() }; let protected = server - .service::() + .service::() .unwrap() .exec_root() .join("store-face-protected"); @@ -1620,7 +1620,7 @@ async fn node_store_preserves_repository_results_and_worktree_removal_exclusion( assert_ok(&created); assert!(store.has_records("wire-source").await.unwrap()); let output = server - .service::() + .service::() .unwrap() .exec_root() .join("fixture-owned-output") diff --git a/crates/dim-app-server/tests/transport_flow/skill_references.rs b/crates/dim-app-server/tests/transport_flow/skill_references.rs index cd65b98de9..603504d4ea 100644 --- a/crates/dim-app-server/tests/transport_flow/skill_references.rs +++ b/crates/dim-app-server/tests/transport_flow/skill_references.rs @@ -19,7 +19,7 @@ use std::sync::Mutex; /// Mounts the Skills catalog in the test host, which has no home plugins, /// and keeps it so a test can change enablement. struct CatalogHost { - platform: Arc, + platform: Arc, settings: Arc, parts: Key, catalog: Arc>>>, @@ -34,13 +34,13 @@ impl DynPlugin for CatalogHost { fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { let parts = ctx.require_at(&self.parts)?; - ctx.provide_as::( + ctx.provide_as::( self.platform.clone(), )?; let catalog = skills::SkillsCatalogPlugin::mount( ctx, ( - self.platform.clone(), + self.platform.facts().home.to_owned(), Arc::new(SkillSettingsHost(self.settings.clone())), ), ) @@ -156,7 +156,7 @@ fn build( dim_app_server::collaboration::install(&mut builder); dim_agent_capabilities::prompt_sources::install(&mut builder); skills::install(&mut builder); - let mut platform = dim_agent_capabilities::host_platform::HostPlatform::current( + let mut platform = dim_agent_capabilities::host_platform::ExecHost::current( dim_agent_capabilities::host_platform::ShellStatus::Unavailable { code: "SKILL_REFERENCES", reason: "The flow runs no command".into(), diff --git a/crates/dim-modality/src/engine.rs b/crates/dim-modality/src/engine.rs index 4aa75f4af7..408d61b153 100644 --- a/crates/dim-modality/src/engine.rs +++ b/crates/dim-modality/src/engine.rs @@ -23,7 +23,7 @@ use dim_agent_capabilities::host::{ SelectableModelsHost, }; use dim_agent_capabilities::host_platform::{ - ConfinedError, ConfinedOutput, ConfinedSpec, Confinement, HostPlatform, SystemServices, + ConfinedError, ConfinedOutput, ConfinedSpec, Confinement, ExecHost, SystemServices, }; use dim_agent_capabilities::methods::{Progress, RpcError}; use dim_agent_types::ModelId; @@ -2160,7 +2160,7 @@ impl Shared { } return; } - let Some(platform) = self.ctx.get::() else { + let Some(platform) = self.ctx.get::() else { if !slot.cancel_requested() { self.fail(slot, "unavailable", "The host platform is unavailable") .await; diff --git a/crates/dim-modality/src/lib.rs b/crates/dim-modality/src/lib.rs index 6a4d0365fe..98e8b91430 100644 --- a/crates/dim-modality/src/lib.rs +++ b/crates/dim-modality/src/lib.rs @@ -1087,7 +1087,7 @@ pub(crate) async fn evaluate( global, ctx: ctx.clone(), host_platform: ctx - .get::() + .get::() .is_some(), ocr_helper: ocr_helper.map(|path| path.to_owned()), pp_ocr: match ocr { diff --git a/crates/dimcode/tests/ocr_helper_flow.rs b/crates/dimcode/tests/ocr_helper_flow.rs index 1effae4f16..1b2533103c 100644 --- a/crates/dimcode/tests/ocr_helper_flow.rs +++ b/crates/dimcode/tests/ocr_helper_flow.rs @@ -2,8 +2,7 @@ //! a Modality host task relies on. #![cfg(target_os = "macos")] use dim_agent_capabilities::host_platform::{ - ConfinedError, ConfinedOutput, ConfinedSpec, Confinement, HostPlatform, ShellStatus, - SystemServices, + ConfinedError, ConfinedOutput, ConfinedSpec, Confinement, ExecHost, ShellStatus, SystemServices, }; use serde_json::Value; use std::ffi::OsString; @@ -38,7 +37,7 @@ async fn run( for path in [&work, &tmp, &cache] { std::fs::create_dir_all(path).unwrap(); } - let platform = HostPlatform::current(ShellStatus::Unavailable { + let platform = ExecHost::current(ShellStatus::Unavailable { code: "test", reason: String::new(), }) diff --git a/docs/architecture/rust-agent/generated/app-server/services.json b/docs/architecture/rust-agent/generated/app-server/services.json index e5709a60db..bdd264813a 100644 --- a/docs/architecture/rust-agent/generated/app-server/services.json +++ b/docs/architecture/rust-agent/generated/app-server/services.json @@ -2063,7 +2063,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "status": "Ready" }, @@ -2085,7 +2085,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "provider": 29, "generation": 1 @@ -2111,7 +2111,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "provider": 29, "declared": true, "external": true @@ -2144,7 +2144,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "status": "Ready" }, @@ -2156,7 +2156,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "provider": 29, "generation": 1 @@ -2170,7 +2170,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "provider": 29, "declared": true, "external": true @@ -2191,7 +2191,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "status": "Ready" }, @@ -2203,7 +2203,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "provider": 29, "generation": 1 @@ -2217,7 +2217,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "provider": 29, "declared": true, "external": true @@ -3409,7 +3409,7 @@ "removing": false }, { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "provider": 29, "generation": 1, "removing": false @@ -3762,6 +3762,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#execHost", + "provider": 29, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#executionSettingsHost", "provider": 25, diff --git a/docs/architecture/rust-agent/generated/app-server/services.md b/docs/architecture/rust-agent/generated/app-server/services.md index b51f2577af..ae9f354343 100644 --- a/docs/architecture/rust-agent/generated/app-server/services.md +++ b/docs/architecture/rust-agent/generated/app-server/services.md @@ -171,13 +171,13 @@ flowchart LR p18 -->|"dim_app_server::settings::SettingsService"| p34 p10 -->|"dim_app_server::methods::ManagementMethods"| p33 p18 -->|"dim_app_server::settings::SettingsService"| p33 - p29 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p32 + p29 -->|"dim_agent_capabilities::host_platform::ExecHost"| p32 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p32 p10 -->|"dim_app_server::methods::ManagementMethods"| p32 p18 -->|"dim_app_server::settings::SettingsService"| p32 - p29 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p31 + p29 -->|"dim_agent_capabilities::host_platform::ExecHost"| p31 p10 -->|"dim_app_server::methods::ManagementMethods"| p31 - p29 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p30 + p29 -->|"dim_agent_capabilities::host_platform::ExecHost"| p30 p10 -->|"dim_app_server::methods::ManagementMethods"| p30 p25 -->|"dim_agent_capabilities::execution_settings::ExecutionSettingsHost"| p29 p4 -->|"dim_agent_capabilities::file_storage::FileStorage"| p29 diff --git a/docs/architecture/rust-agent/generated/app-server/services.mmd b/docs/architecture/rust-agent/generated/app-server/services.mmd index 85105c8a0f..7af2ea586f 100644 --- a/docs/architecture/rust-agent/generated/app-server/services.mmd +++ b/docs/architecture/rust-agent/generated/app-server/services.mmd @@ -166,13 +166,13 @@ flowchart LR p18 -->|"dim_app_server::settings::SettingsService"| p34 p10 -->|"dim_app_server::methods::ManagementMethods"| p33 p18 -->|"dim_app_server::settings::SettingsService"| p33 - p29 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p32 + p29 -->|"dim_agent_capabilities::host_platform::ExecHost"| p32 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p32 p10 -->|"dim_app_server::methods::ManagementMethods"| p32 p18 -->|"dim_app_server::settings::SettingsService"| p32 - p29 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p31 + p29 -->|"dim_agent_capabilities::host_platform::ExecHost"| p31 p10 -->|"dim_app_server::methods::ManagementMethods"| p31 - p29 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p30 + p29 -->|"dim_agent_capabilities::host_platform::ExecHost"| p30 p10 -->|"dim_app_server::methods::ManagementMethods"| p30 p25 -->|"dim_agent_capabilities::execution_settings::ExecutionSettingsHost"| p29 p4 -->|"dim_agent_capabilities::file_storage::FileStorage"| p29 diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index d36ab1b4be..c248f9768b 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -19,12 +19,12 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `credentialVariablesHost` | process | root | data | `variables` async | | `eventHub` | process | eventhub | data | `declare` async, `publish` async | | `eventSubscriptions` | process | eventhub | data | `list` sync, `sources` sync, `subscribe` async, `unsubscribe` async | +| `execHost` | process | HostPlatform | data | `configured` async, `confined` async, `info` async, `kill` async, `output` async, `removeOutputDirectory` async, `resize` async, `retainOutput` async, `settle` async, `shell` async, `start` async, `tail` async, `wait` async, `write` async | | `executionSettingsHost` | process | ExecutionSettings | data | `read` async | | `fileStorage` | process | FileStorage | internal(object) | — | | `fsHost` | process | FileStorage | data | `backup` async, `closeRead` async, `createDirectory` async, `list` async, `lock` async, `openRead` async, `readAt` async, `readBytes` async, `remove` async, `replace` async, `stat` async, `unlock` async | | `grokOAuthService` | process | GrokOAuth | internal(secret) | — | | `hooksService` | process | HooksSettings | data | `plugins` async, `refusal` sync, `register` async, `withdraw` async | -| `hostPlatform` | process | HostPlatform | internal(object) | — | | `listenAddresses` | process | Transport | data | `read` async | | `loader` | process | rutis-loader | internal(owner-api) | — | | `localId` | process | root | data | `get` sync | diff --git a/docs/architecture/rust-agent/generated/local/services.json b/docs/architecture/rust-agent/generated/local/services.json index 412c1802e1..f01a49a593 100644 --- a/docs/architecture/rust-agent/generated/local/services.json +++ b/docs/architecture/rust-agent/generated/local/services.json @@ -1806,6 +1806,11 @@ "state": "Active", "generation": 1, "injects": [ + { + "service": "dim_agent_capabilities::host_platform::ExecHost", + "scope": null, + "status": "Ready" + }, { "service": "dim_agent_capabilities::prompt_guide::GuideEntries@session", "scope": null, @@ -1833,6 +1838,12 @@ } ], "resolved": [ + { + "service": "dim_agent_capabilities::host_platform::ExecHost", + "scope": null, + "provider": 5, + "generation": 1 + }, { "service": "dim_agent_capabilities::prompt_guide::GuideEntries@session", "scope": null, @@ -1865,6 +1876,12 @@ } ], "reads": [ + { + "service": "dim_agent_capabilities::host_platform::ExecHost", + "provider": 5, + "declared": true, + "external": true + }, { "service": "dim_agent_capabilities::prompt_guide::GuideEntries@session", "provider": 42, @@ -2231,7 +2248,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "status": "Ready" }, @@ -2248,7 +2265,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "provider": 5, "generation": 1 @@ -2268,7 +2285,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "provider": 5, "declared": true, "external": true @@ -2400,7 +2417,7 @@ "removing": false }, { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "provider": 5, "generation": 1, "removing": false @@ -2538,7 +2555,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "status": "Ready" }, @@ -2570,7 +2587,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "provider": 5, "generation": 1 @@ -2614,7 +2631,7 @@ "external": false }, { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "provider": 5, "declared": true, "external": true @@ -3070,7 +3087,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "status": "Ready" }, @@ -3107,7 +3124,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "provider": 5, "generation": 1 @@ -3151,7 +3168,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "provider": 5, "declared": true, "external": true @@ -3485,7 +3502,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "status": "Ready" }, @@ -3502,7 +3519,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "provider": 5, "generation": 1 @@ -3522,7 +3539,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "provider": 5, "declared": true, "external": true @@ -3718,7 +3735,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "status": "Ready" }, @@ -3746,7 +3763,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "scope": null, "provider": 5, "generation": 1 @@ -3778,7 +3795,7 @@ "external": false }, { - "service": "dim_agent_capabilities::host_platform::HostPlatform", + "service": "dim_agent_capabilities::host_platform::ExecHost", "provider": 5, "declared": true, "external": true diff --git a/docs/architecture/rust-agent/generated/local/services.md b/docs/architecture/rust-agent/generated/local/services.md index 4040fac953..5c012df442 100644 --- a/docs/architecture/rust-agent/generated/local/services.md +++ b/docs/architecture/rust-agent/generated/local/services.md @@ -155,6 +155,7 @@ flowchart LR p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p65 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p65 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p65 + p5 -->|"dim_agent_capabilities::host_platform::ExecHost"| p64 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p64 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p64 p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p64 @@ -164,9 +165,9 @@ flowchart LR p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p63 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p63 p73 -->|"dim_agent_runtime::state::StateCell@main"| p63 - p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p28 + p5 -->|"dim_agent_capabilities::host_platform::ExecHost"| p28 p4 -->|"dim_agent_capabilities::file_storage::FileStorage"| p5 - p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p56 + p5 -->|"dim_agent_capabilities::host_platform::ExecHost"| p56 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p56 p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p56 p19 -->|"dim_agent_capabilities::workspace_tools::mentions::MentionIndex"| p56 @@ -192,7 +193,7 @@ flowchart LR p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p51 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p51 p33 -->|"dim_agent_runtime::scope::SessionLoader@session"| p51 - p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p50 + p5 -->|"dim_agent_capabilities::host_platform::ExecHost"| p50 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p50 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p50 p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p50 @@ -211,7 +212,7 @@ flowchart LR p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p45 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p45 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p45 - p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p44 + p5 -->|"dim_agent_capabilities::host_platform::ExecHost"| p44 p43 -->|"dim_agent_capabilities::prompt_registry::PromptRegistry@session"| p44 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p44 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p43 @@ -221,7 +222,7 @@ flowchart LR p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p39 p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p39 p33 -->|"dim_agent_capabilities::hooks::sources::HookSourcesHost@session"| p38 - p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p38 + p5 -->|"dim_agent_capabilities::host_platform::ExecHost"| p38 p39 -->|"dim_agent_capabilities::input_queue::SubmitChecks@session"| p38 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p38 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p38 diff --git a/docs/architecture/rust-agent/generated/local/services.mmd b/docs/architecture/rust-agent/generated/local/services.mmd index 707defe688..cbfb29c2dc 100644 --- a/docs/architecture/rust-agent/generated/local/services.mmd +++ b/docs/architecture/rust-agent/generated/local/services.mmd @@ -150,6 +150,7 @@ flowchart LR p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p65 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p65 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p65 + p5 -->|"dim_agent_capabilities::host_platform::ExecHost"| p64 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p64 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p64 p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p64 @@ -159,9 +160,9 @@ flowchart LR p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p63 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p63 p73 -->|"dim_agent_runtime::state::StateCell@main"| p63 - p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p28 + p5 -->|"dim_agent_capabilities::host_platform::ExecHost"| p28 p4 -->|"dim_agent_capabilities::file_storage::FileStorage"| p5 - p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p56 + p5 -->|"dim_agent_capabilities::host_platform::ExecHost"| p56 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p56 p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p56 p19 -->|"dim_agent_capabilities::workspace_tools::mentions::MentionIndex"| p56 @@ -187,7 +188,7 @@ flowchart LR p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p51 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p51 p33 -->|"dim_agent_runtime::scope::SessionLoader@session"| p51 - p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p50 + p5 -->|"dim_agent_capabilities::host_platform::ExecHost"| p50 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p50 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p50 p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p50 @@ -206,7 +207,7 @@ flowchart LR p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p45 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p45 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p45 - p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p44 + p5 -->|"dim_agent_capabilities::host_platform::ExecHost"| p44 p43 -->|"dim_agent_capabilities::prompt_registry::PromptRegistry@session"| p44 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p44 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p43 @@ -216,7 +217,7 @@ flowchart LR p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p39 p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p39 p33 -->|"dim_agent_capabilities::hooks::sources::HookSourcesHost@session"| p38 - p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p38 + p5 -->|"dim_agent_capabilities::host_platform::ExecHost"| p38 p39 -->|"dim_agent_capabilities::input_queue::SubmitChecks@session"| p38 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p38 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p38 diff --git a/docs/architecture/rust-agent/plugins/Hooks.md b/docs/architecture/rust-agent/plugins/Hooks.md index e147caa8c6..a4395555e7 100644 --- a/docs/architecture/rust-agent/plugins/Hooks.md +++ b/docs/architecture/rust-agent/plugins/Hooks.md @@ -60,7 +60,7 @@ cancellation token terminates its process tree on close. | Service | Purpose | | --- | --- | | `S:HookSourcesHost` | Read the effective documents of the user, the workspace and the plugins. | -| `P:HostPlatform` | Build each command's process spec, environment and process tree. | +| `P:ExecHost` | Build each command's process spec, environment and process tree. | | `S:SessionConfig` | Pass the working directory, permission and collaboration-role facts to the payload. | | `S:SessionIdentity` | Name the Session in the payload and `DIM_SESSION_ID`. | | `S:SubmitChecks` | Register `hooks`, the `UserPromptSubmit` check the operator-input entries call. | @@ -69,7 +69,7 @@ cancellation token terminates its process tree on close. | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `P:HostPlatform`、`S:HookSourcesHost`、`S:SessionConfig`、`S:SessionIdentity`、`S:SubmitChecks` | +| 注入 | `P:ExecHost`、`S:HookSourcesHost`、`S:SessionConfig`、`S:SessionIdentity`、`S:SubmitChecks` | | 提供 | `S:HooksRuntime` | | 被注入于 | `HooksBranch` | diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index e2dadab46a..a352770063 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -2,7 +2,7 @@ Owner: [host_platform.rs](../../../../crates/dim-agent-capabilities/src/host_platform.rs). Resolves host home/environment and execution shell and supplies process spawning -and tree-supervision primitives to local tools. +and tree-supervision primitives to local tools. The process service [`execHost.info`](../../../design/resource-faces.md#37-info-confined-and-configured) exposes host facts and the current execution shell. Hooks runs configured commands through `execHost.configured`, OCR runs helpers through `confined`, and SessionStore removes released shell output through `removeOutputDirectory`. ## Dependencies @@ -369,6 +369,6 @@ workspace, and the same command with the sandbox off. | --- | --- | | 作用域 | 进程 | | 注入 | `P:ExecutionSettingsHost`、`P:FileStorage`、`P:ToolchainSourceHost` | -| 提供 | `P:HostPlatform` | -| 被注入于 | `HooksSession`、`PromptSources`、`ShellInput`、`SkillsCatalog`、`WorkspaceTools` | +| 提供 | `P:ExecHost` | +| 被注入于 | `BackgroundExec`、`HooksSession`、`PromptSources`、`ShellInput`、`SkillsCatalog`、`WorkspaceTools` | diff --git a/docs/architecture/rust-agent/plugins/PromptSources.md b/docs/architecture/rust-agent/plugins/PromptSources.md index 4cd9b965e2..f3e81bc084 100644 --- a/docs/architecture/rust-agent/plugins/PromptSources.md +++ b/docs/architecture/rust-agent/plugins/PromptSources.md @@ -96,7 +96,7 @@ from branch adoption. | Service | Purpose | | --- | --- | -| `P:HostPlatform` | Home, environment and shell/platform context. | +| `P:ExecHost` | Home, environment and shell/platform context. | | `S:SessionConfig` | Working directory, Session context and the reply language a record carries. | | `S:PromptRegistry` | Register each of its sources by name, until this part unloads. | @@ -165,7 +165,7 @@ was applied (`a_branch_opened_after_the_value_was_applied_holds_one_block`). | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `P:HostPlatform`、`S:PromptRegistry`、`S:SessionConfig` | +| 注入 | `P:ExecHost`、`S:PromptRegistry`、`S:SessionConfig` | | 提供 | `S:SessionLanguage`、`S:dyn HostDispatch#sessionLanguage` | | 被注入于 | `PromptSourcesBranch` | diff --git a/docs/architecture/rust-agent/plugins/ShellInput.md b/docs/architecture/rust-agent/plugins/ShellInput.md index dfb61caf51..b2e1b8eb3c 100644 --- a/docs/architecture/rust-agent/plugins/ShellInput.md +++ b/docs/architecture/rust-agent/plugins/ShellInput.md @@ -11,7 +11,7 @@ working directory, through the Session methods `shell.run`, `shell.stop` and | Service | Purpose | | --- | --- | -| `P:HostPlatform` | Build each command as `exec` does (`build_process_spec`) and spawn its process tree. | +| `P:ExecHost` | Build each command as `exec` does (`build_process_spec`) and spawn its process tree. | | `S:SessionConfig` | The Session working directory. | | `S:GuideEntries` | Register the shell-input marker's guide entry at Session scope, until this plugin unloads. | | `S:TreeCommands` | Check `branchId` at start; write a recorded run's input on that branch. | @@ -147,7 +147,7 @@ for the race flows; production builds have no hook. | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `P:HostPlatform`、`S:GuideEntries`、`S:SessionConfig`、`S:SessionIdentity`、`S:SessionLifecycle`、`S:SessionMethods`、`S:TreeCommands` | +| 注入 | `P:ExecHost`、`S:GuideEntries`、`S:SessionConfig`、`S:SessionIdentity`、`S:SessionLifecycle`、`S:SessionMethods`、`S:TreeCommands` | | 提供 | — | | 被注入于 | — | diff --git a/docs/architecture/rust-agent/plugins/Skills.md b/docs/architecture/rust-agent/plugins/Skills.md index 314565420a..ac55539dda 100644 --- a/docs/architecture/rust-agent/plugins/Skills.md +++ b/docs/architecture/rust-agent/plugins/Skills.md @@ -53,7 +53,7 @@ Caller unload does not automatically remove registered content. | Service | Purpose | | --- | --- | -| `P:HostPlatform` | Resolve the user home root. | +| `P:ExecHost` | Resolve the user home root. | | `P:SkillSettingsHost` | Read and update enablement. | | `P:PartRegistry` | Register the Skills parts, until this plugin unloads. | @@ -141,7 +141,7 @@ settings mutation was durably saved. | 项 | 值 | | --- | --- | | 作用域 | 进程 | -| 注入 | `P:HostPlatform`、`P:PartRegistry`、`P:SkillSettingsHost` | +| 注入 | `P:ExecHost`、`P:PartRegistry`、`P:SkillSettingsHost` | | 提供 | `P:SkillsCatalog`、`P:SkillsCatalog#dim/skills/catalog-owner`、`P:dyn HostDispatch#skillsCatalog` | | 被注入于 | `Skills` | diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index f744aacb50..53f0333f6b 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -95,7 +95,7 @@ enter. | Service | Purpose | | --- | --- | -| `P:HostPlatform` | Home, shell, environment and process supervision. | +| `P:ExecHost` | Home, shell, environment and process supervision. | | `S:TreeCommands` | Resolve the calling branch per call. | | `S:SessionConfig` | cwd and collaboration role. | | `S:SessionIdentity` | Session-specific output directory. | @@ -470,7 +470,7 @@ empty live preview and unavailable historical captures. | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `P:HostPlatform`、`P:MentionIndex`、`S:SessionConfig`、`S:SessionIdentity`、`S:SessionMethods`、`S:TreeCommands` | +| 注入 | `P:ExecHost`、`P:MentionIndex`、`S:SessionConfig`、`S:SessionIdentity`、`S:SessionMethods`、`S:TreeCommands` | | 提供 | `S:ToolHost`、`S:dyn HostDispatch#toolHost` | | 被注入于 | `ToolRegistry` | @@ -572,6 +572,7 @@ releases no lock across a read: the page opens the registered file itself. | Service | Purpose | | --- | --- | +| `P:ExecHost` | Read retained task output and stop a running task. | | `B:Dispatcher` | Replay commands, then consume command ends and interrupts in dispatch order. | | `B:Timeline` | Commit ends/notices, recovered ones included. | | `B:TimelineIdentity` | The branch whose entry this part registers. | @@ -638,7 +639,7 @@ and Session isolation. | 项 | 值 | | --- | --- | | 作用域 | 分支 | -| 注入 | `B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:GuideEntries`、`S:SessionLifecycle` | +| 注入 | `B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`P:ExecHost`、`S:GuideEntries`、`S:SessionLifecycle` | | 提供 | `B:BackgroundExec`、`B:dyn HostDispatch#backgroundExec` | | 被注入于 | — | diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 8f891133b6..c8821dcde2 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -87,14 +87,15 @@ whether a call may run, or consults who is calling. | Method | Mode | Request | Reply | | --- | --- | --- | --- | -| `start` | async | `{taskId, command, cwd, workspace, roots}` | `{outputPath}` | +| `start` | async | `{taskId, command, cwd, workspace, roots, outputDir, timeoutMs?}` | `{outputPath}` | +| `retainOutput` | async | `{taskId}` | `{outputPath}` | | `wait` | async | `{taskId, timeoutMs?}` | terminal record (§3.2) | | `kill` | async | `{taskId}` | `{}` | | `settle` | async | `{taskId}` | `{}` | | `output` | async | `{taskId, cursor?, limit?} \| {outputPath, cursor?, limit?}` | page (§3.4) | | `tail` | async | `{taskId}` | `{text, totalBytes, truncated}` (§3.5) | | `removeOutputDirectory` | async | `{path}` | `{}` (§3.8) | -| `shell` | async | `{taskId, cwd, workspace, roots, cols, rows}` | `{outputPath}` | +| `shell` | async | `{taskId, cwd, workspace, roots, outputDir, cols, rows}` | `{outputPath}` | | `write` | async | `{taskId, data}` | `{}` | | `resize` | async | `{taskId, cols, rows}` | `{}` | | `info` | async | `{}` | host facts (§3.7) | @@ -103,11 +104,11 @@ whether a call may run, or consults who is calling. ### 3.2 `start` and `wait` -`start` accepts only `{taskId, command, cwd, workspace, roots}`. `cwd` is a resolved working +`start` accepts only `{taskId, command, cwd, workspace, roots, outputDir, timeoutMs?}`. `cwd` is a resolved working directory — the control side obtains it from `fsHost.resolve`, which is also what triggers [worktree recognition](#421-session-scoped-recognition-and-association) for a cwd outside the known range; an absent `cwd` is `workspace`. `workspace` is the Session's workspace root and -`roots` the mapped subtree paths from the Session's confirmed worktrees. All are node-absolute. +`roots` the mapped subtree paths from the Session's confirmed worktrees. All are node-absolute. WorkspaceTools passes the Session command-output directory as `outputDir`; ShellSession passes its branch shell output directory. A cwd that does not exist is `cwd_not_found`; the provider never resolves a relative path itself. The provider prepares the boundary with `workspace` plus exactly `roots` and adds no other @@ -118,7 +119,7 @@ to confirm a root: a directory outside the range does not become writable becaus it, because `cwd` sits in it, or because the model asked. The range is the caller's confirmed range, in the same trust position as the workspace list preparation already takes; the switches still decide enforcement, and the model cannot set either (§3.9). It builds the shell, argv and -environment from its current shell preference, spawns, and creates the task's output file. +environment from its current shell preference, spawns, and returns the planned output path. If supplied, `timeoutMs` starts at spawn and terminates the command when it expires, even before a caller waits. Short foreground output stays in memory. Crossing the existing inline limit creates the file. Before a background handoff the caller awaits `retainOutput`; the owner writes the captured bytes and keeps appending to that file. Repeated retention returns the same path. `taskId` is assigned by the caller (the control side allocates `exec-` as it does today); a second `start` with an id the provider still holds is `task_exists` and starts nothing, so a retried call after a lost reply cannot run the command twice. @@ -219,7 +220,7 @@ to the existing `exec_task_unknown` response for this RPC. The terminal preview ### 3.6 Persistent shell -`shell {taskId, cwd, workspace, roots, cols, rows}` creates one persistent PTY shell as a task; +`shell {taskId, cwd, workspace, roots, outputDir, cols, rows}` creates one persistent PTY shell as a task; `write {taskId, data}` sends `data` (base64 bytes) to it, `resize` sets the geometry, `output` reads its captured text, and `kill` ends it. `cwd` and `roots` are resolved and confirmed exactly as for `start` (§3.2); a running shell keeps the roots it started with. `read` is not a separate @@ -239,7 +240,7 @@ settles the command as ended with the task's loss, never as still running. `info {}` answers the provider's host facts as data, because other owners read them today: ```text -{os: "darwin" | "linux" | "win32", +{os: "darwin" | "linux" | "win32", arch: string, home: string, timezone?: string, execRoot: string, platformRoots: [string], backend: {state: "available"} | {state: "unavailable", reason: string}, execShell: {state: "available", executable: string, edition: string, @@ -256,14 +257,14 @@ reads it, and this face does not write it. purpose, never an agent-decided command — and answers its exit status, both streams within the limits, whether the host could confine it, and whether either stream was cut. Its refusals are the ones it has today: `InvalidPath`, `TimedOut`, `OutputLimit`, `Cancelled`, `Spawn`, `Cleanup`. It -reads no setting and grants no network. +reads no setting and grants no network. `outputLimit` gives the stdout and stderr byte limits separately. A successful call returns the numeric exit code (null for a signal) and both streams as base64 bytes. Exceeding either limit returns `OutputLimit`. `configured` runs a **configuration command**: a command that exists because of configuration, not because an agent decided it (a Hooks handler, [Hooks A.6.3](plugins/Hooks.md#a63-process-start-with-an-initial-stdin)). It starts the command through the same shell spec as `start`, writes `stdin` (base64 bytes, if any) to the child's stdin -and closes it, adds `env` entries to the spec environment, and answers the exit status and both -streams within `limits: {stdout, stderr}`. It reads **no** isolation switch and prepares **no** +and closes it, applies `env` entries (null removes the variable), and answers the exit status and both +streams as base64 bytes within `limits: {stdout, stderr}`. It reads **no** isolation switch and prepares **no** sandbox: a configuration command runs outside the agent boundary, exactly as it does today ([ADR 003 D2](../adr/003-approval-scope.md)). It takes no task id, no output file and no background handoff; a cancelled call or `timeoutMs` kills the tree before the call answers. It is diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index df3457e9bd..1efd071fa9 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -758,6 +758,52 @@ export interface TimelineStore { latestSnapshot(request: { sessionId: string; branchId: string; through: number; interpreter: string }): Promise<{ snapshot: TimelineRecoverySnapshot | null }>; } +/** Host facts of the node that executes commands. */ +export interface ExecHost { + shell(request: {taskId: string; cwd: string; workspace: string; roots: string[]; outputDir: string; cols: number; rows: number}): Promise<{outputPath: string}>; + write(request: {taskId: string; data: string}): Promise>; + resize(request: {taskId: string; cols: number; rows: number}): Promise>; + output(request: ({taskId: string} | {outputPath: string}) & {cursor?: number; limit?: number}): Promise<{ + text: string; bytes: number; nextCursor?: number; truncated: boolean; retainedFrom: number; reset?: boolean; + }>; + start(request: {taskId: string; command: string; cwd: string; workspace: string; roots: string[]; outputDir: string; timeoutMs?: number}): Promise<{outputPath: string}>; + wait(request: {taskId: string; timeoutMs?: number}): Promise<{ + status: 'exited' | 'signaled' | 'timed_out' | 'cancelled' | 'failed'; + exitCode?: number; signal?: string; durationMs: number; outputPath: string; + outputBytes: number; outputTruncated: boolean; preview: string; previewTruncated: boolean; failureNote?: string; + }>; + kill(request: {taskId: string}): Promise>; + settle(request: {taskId: string}): Promise>; + retainOutput(request: {taskId: string}): Promise<{outputPath: string}>; + tail(request: {taskId: string}): Promise<{text: string; totalBytes: number; truncated: boolean}>; + configured(request: { + command: string; cwd: string; env?: Record; stdin?: string; + timeoutMs: number; limits: {stdout: number; stderr: number}; + }): Promise<{status: 'exited' | 'signaled' | 'timed_out' | 'cancelled'; exitCode?: number; signal?: string; durationMs: number; stdout: string; stderr: string; stdoutTruncated: boolean; stderrTruncated: boolean}>; + removeOutputDirectory(request: {path: string}): Promise>; + confined(request: { + program: string; args: string[]; read: string[]; write: string[]; + env?: Record; timeoutMs: number; outputLimit: {stdout: number; stderr: number}; + services: 'none' | 'onDeviceRecognition'; + }): Promise<{status: number | null; stdout: string; stderr: string; confined: boolean; stdoutTruncated: boolean; stderrTruncated: boolean}>; + info(request: Record): Promise<{ + os: 'darwin' | 'linux' | 'win32'; + arch: string; + home: string; + timezone?: string; + execRoot: string; + platformRoots: string[]; + backend: { state: 'available' } | { state: 'unavailable'; reason: string }; + execShell: { + state: 'available'; + executable: string; + edition: 'bash' | 'zsh' | 'sh' | 'dash' | 'ksh' | 'git-bash' | 'pwsh' | 'windows-powershell' | 'cmd'; + source: 'explicit' | 'login' | 'fallback' | 'automatic'; + outputEncoding: 'utf8' | 'unknown'; + } | { state: 'unavailable'; code: string; reason: string }; + }>; +} + export type FsEntryName = string | { Unix: number[] } | { Windows: number[] }; /** Directory operations and pinned reads on the filesystem owner; see resource-faces §4.1. */ export interface FsHost { diff --git a/tests/integration/tests/local_execution.rs b/tests/integration/tests/local_execution.rs index 9cab6b9109..6f763fe5d8 100644 --- a/tests/integration/tests/local_execution.rs +++ b/tests/integration/tests/local_execution.rs @@ -11,7 +11,7 @@ use dim_agent_capabilities::{ history::HistoryRenderer, host::*, host_platform::{ - EXEC_SHELL_CONFIG_INVALID, EXEC_SHELL_UNAVAILABLE, ExecShellRuntime, HostPlatform, + EXEC_SHELL_CONFIG_INVALID, EXEC_SHELL_UNAVAILABLE, ExecHost, ExecShellRuntime, HostPlatformConfig, HostPlatformPlugin, OutputEncoding, ShellEdition, ShellSource, ShellStatus, resolve_shell, }, @@ -131,19 +131,19 @@ impl ModelDriver for Script { } /// Provides the process HostPlatform the design lets tests construct. -struct PlatformPlugin(Arc); +struct PlatformPlugin(Arc); impl Plugin for PlatformPlugin { type Deps = (); fn name(&self) -> &str { "TestHostPlatform" } async fn apply(&self, ctx: &Ctx, (): Self::Deps) -> rutis::Result { - ctx.provide_as::(self.0.clone())?; + ctx.provide_as::(self.0.clone())?; Ok(()) } } /// `platform` provided by [`PlatformPlugin`], a row of the harness's host. -fn test_platform(platform: HostPlatform) -> impl FnOnce(&mut AgentBuilder) { +fn test_platform(platform: ExecHost) -> impl FnOnce(&mut AgentBuilder) { let platform = Arc::new(platform); move |builder| { builder.plugin(move |_| Ok(Box::new(PlatformPlugin(platform.clone())))); @@ -161,6 +161,7 @@ fn configured_platform(home: PathBuf) -> impl FnOnce(&mut AgentBuilder) { HostPlatformConfig { execution: names.key()?, toolchain: names.key()?, + command_files: Some((0, "command-output".into())), exec_shell_file: Some((0, "exec-shell.json".into())), home: None, }, @@ -299,11 +300,11 @@ fn scratch(name: &str) -> PathBuf { std::fs::canonicalize(path).unwrap() } -async fn platform(extra: &[(&str, &str)]) -> HostPlatform { +async fn platform(extra: &[(&str, &str)]) -> ExecHost { let mut env: Vec<_> = std::env::vars_os().collect(); env.retain(|(key, _)| key != "SHELL"); env.push(("SHELL".into(), "/bin/bash".into())); - let mut platform = HostPlatform::current(resolve_shell(Ok(None), &env).await) + let mut platform = ExecHost::current(resolve_shell(Ok(None), &env).await) .unwrap() .with_execution_settings(ExecutionSettingsHost::fixed(ExecutionSettings::default())); platform.env.extend( @@ -315,15 +316,15 @@ async fn platform(extra: &[(&str, &str)]) -> HostPlatform { } impl Harness { - async fn new(platform: HostPlatform, hook: Hook) -> Self { + async fn new(platform: ExecHost, hook: Hook) -> Self { Self::with_context(platform, hook, false).await } /// The same assembly with a context model and a strategy bound, so a flow /// test can compact (`local_support/compaction.rs`). - async fn new_compacting(platform: HostPlatform, hook: Hook) -> Self { + async fn new_compacting(platform: ExecHost, hook: Hook) -> Self { Self::with_context(platform, hook, true).await } - async fn with_context(mut platform: HostPlatform, hook: Hook, compacting: bool) -> Self { + async fn with_context(mut platform: ExecHost, hook: Hook, compacting: bool) -> Self { let cwd = scratch("cwd"); platform.home = cwd.clone(); platform.env.retain(|(name, _)| name != "HOME"); @@ -588,7 +589,7 @@ async fn exec_and_external_shell_callers_use_live_shell_preferences() { scratch("cwd"), ) .await; - let platform = harness.root.get::().unwrap(); + let platform = harness.root.get::().unwrap(); let session = harness.session().await; let refusal = platform @@ -629,7 +630,7 @@ async fn exec_and_external_shell_callers_use_live_shell_preferences() { assert!(text(results(&events).last().unwrap()).contains(executable)); assert!(Arc::ptr_eq( &platform, - &harness.root.get::().unwrap() + &harness.root.get::().unwrap() )); } @@ -672,6 +673,8 @@ async fn exec_and_external_shell_callers_use_live_shell_preferences() { async fn foreground_output_is_canonical_and_offloaded_like_ts() { let harness = Harness::new(platform(&[]).await, Hook::None).await; let session = harness.session().await; + let output_dir = harness.output_root.join(session.id()); + std::fs::write(&output_dir, b"blocks creation of command logs").unwrap(); harness .run( &session, @@ -689,6 +692,7 @@ async fn foreground_output_is_canonical_and_offloaded_like_ts() { assert!(text(result).ends_with("\n\nCommand exited with code 3.")); assert!(!text(result).contains('\u{FFFD}')); + std::fs::remove_file(&output_dir).unwrap(); session.idle("main").await.unwrap(); harness .run( @@ -798,7 +802,7 @@ fn exit_drains_output_even_when_offload_is_slow() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn an_unavailable_shell_or_a_missing_execution_port_refuses_the_payload() { - let unavailable = HostPlatform::current(ShellStatus::Unavailable { + let unavailable = ExecHost::current(ShellStatus::Unavailable { code: EXEC_SHELL_UNAVAILABLE, reason: "Selected command shell is unavailable: /opt/zsh".into(), }) @@ -824,7 +828,7 @@ async fn an_unavailable_shell_or_a_missing_execution_port_refuses_the_payload() session.close().await.unwrap(); harness.shutdown().await; - let without_port = HostPlatform::current(ShellStatus::Available(ExecShellRuntime { + let without_port = ExecHost::current(ShellStatus::Available(ExecShellRuntime { executable_path: "/bin/sh".into(), edition: ShellEdition::Sh, source: ShellSource::Fallback, @@ -2854,13 +2858,17 @@ fn group_instance(diagnostics: &RuntimeDiagnostics, scope: &str) -> InstanceId { /// The call another language makes on `name` in `instance`. async fn face_call( ctx: &Ctx, - instance: InstanceId, + instance: impl Into>, name: &str, method: &str, args: Vec, ) -> Value { + let mut key = host_key(name); + if let Some(instance) = instance.into() { + key = key.instance(instance); + } let dispatch = ctx - .get_at::(&host_key(name).instance(instance)) + .get_at::(&key) .unwrap_or_else(|| panic!("{name} is not a face in this instance")); let reply = dispatch .invoke(method, BridgeValue::List(args)) @@ -2871,13 +2879,17 @@ async fn face_call( /// The error the call another language makes on `name` returns. async fn face_error( ctx: &Ctx, - instance: InstanceId, + instance: impl Into>, name: &str, method: &str, args: Vec, ) -> rutis_bridge::session::Error { + let mut key = host_key(name); + if let Some(instance) = instance.into() { + key = key.instance(instance); + } let dispatch = ctx - .get_at::(&host_key(name).instance(instance)) + .get_at::(&key) .unwrap_or_else(|| panic!("{name} is not a face in this instance")); let reply = dispatch .invoke(method, BridgeValue::List(args)) @@ -2889,7 +2901,13 @@ async fn face_error( /// and errors for the task both callers name. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn background_exec_face_answers_as_the_typed_service() { - let harness = Harness::new(platform(&[]).await, Hook::None).await; + let home = scratch("background-face"); + let harness = Harness::with_platform( + configured_platform(home.clone()), + Hook::None, + scratch("cwd"), + ) + .await; let session = harness.session().await; harness .run( @@ -2922,6 +2940,49 @@ async fn background_exec_face_answers_as_the_typed_service() { let ctx = harness.seen.ctx("main"); let instance = group_instance(&session.branch_diagnostics("main").unwrap(), "BranchScope"); + let root = &harness.root; + let retained = face_call( + root, + None, + "execHost", + "retainOutput", + vec![json!({"taskId":task}).into()], + ) + .await; + let path = events + .iter() + .find_map(|event| match &event.kind { + EventKind::ExecStarted(data) if data.task_id == task => Some(&data.output_path), + _ => None, + }) + .unwrap(); + assert_eq!(retained, json!({"outputPath":path})); + assert_eq!(std::fs::read(path).unwrap(), b"face-output"); + let tail = face_call( + root, + None, + "execHost", + "tail", + vec![json!({"taskId":task}).into()], + ) + .await; + assert_eq!( + tail, + json!({"text":"face-output", "totalBytes":11, "truncated":false}) + ); + assert_eq!( + face_error( + root, + None, + "execHost", + "retainOutput", + vec![json!({"taskId":"missing"}).into()] + ) + .await + .code(), + Some("task_unknown") + ); + let typed = background.output(task.clone()).await.unwrap(); let wire = face_call( &ctx, @@ -3153,6 +3214,7 @@ async fn background_exec_face_answers_as_the_typed_service() { )); restored.close().await.unwrap(); harness.shutdown().await; + std::fs::remove_dir_all(home).unwrap(); } /// The text of every tool result of a batch, in call order. diff --git a/tests/integration/tests/local_product.rs b/tests/integration/tests/local_product.rs index ab1af07848..9520d58aca 100644 --- a/tests/integration/tests/local_product.rs +++ b/tests/integration/tests/local_product.rs @@ -11,7 +11,7 @@ use dim_agent_capabilities::{ history::HistoryRenderer, host::*, host_platform::{ - ExecShellRuntime, HostPlatform, OutputEncoding, ShellEdition, ShellSource, ShellStatus, + ExecHost, ExecShellRuntime, OutputEncoding, ShellEdition, ShellSource, ShellStatus, }, model_provider::ModelProviderPlugin, permission::{CommandRules, NoCommandRules, Permission}, @@ -32,7 +32,7 @@ struct Product { } async fn product(dirs: &Dirs) -> Product { - let mut platform = HostPlatform::current(ShellStatus::Available(ExecShellRuntime { + let mut platform = ExecHost::current(ShellStatus::Available(ExecShellRuntime { executable_path: "/bin/sh".into(), edition: ShellEdition::Sh, source: ShellSource::Fallback, @@ -68,7 +68,7 @@ async fn product(dirs: &Dirs) -> Product { ); builder.plugin(|names| Ok(Box::new(SkillsCatalogPlugin::new(names)?))); let agent = MinimalHost::start_with(&builder, |root, _| { - root.provide_as::(Arc::new(platform))?; + root.provide_as::(Arc::new(platform))?; root.provide_as::(Arc::new(SkillSettingsHost(Arc::new( MemorySkillSettings::default(), ))))?; diff --git a/tests/integration/tests/local_support/mod.rs b/tests/integration/tests/local_support/mod.rs index 86af26bf38..50135ea5ee 100644 --- a/tests/integration/tests/local_support/mod.rs +++ b/tests/integration/tests/local_support/mod.rs @@ -12,7 +12,7 @@ use dim_agent_capabilities::{ history::HistoryRenderer, host::*, host_platform::{ - ExecShellRuntime, HostPlatform, Os, OutputEncoding, ShellEdition, ShellSource, ShellStatus, + ExecHost, ExecShellRuntime, Os, OutputEncoding, ShellEdition, ShellSource, ShellStatus, }, model_provider::ModelProviderPlugin, permission::{CommandRules, NoCommandRules}, @@ -95,8 +95,8 @@ pub fn skill_file(name: &str, description: &str, body: &str) -> String { format!("---\nname: {name}\ndescription: {description}\n---\n{body}\n") } -pub fn platform(home: &Path) -> HostPlatform { - let mut platform = HostPlatform::current(ShellStatus::Available(ExecShellRuntime { +pub fn platform(home: &Path) -> ExecHost { + let mut platform = ExecHost::current(ShellStatus::Available(ExecShellRuntime { executable_path: "/bin/zsh".into(), edition: ShellEdition::Zsh, source: ShellSource::Login, @@ -567,7 +567,7 @@ pub async fn env(dirs: &Dirs, options: Options) -> Env { let clients = options.clients.clone(); let execution = options.execution.clone(); let agent = MinimalHost::start_with(&builder, move |root, _| { - root.provide_as::(Arc::new(host))?; + root.provide_as::(Arc::new(host))?; root.provide_as::(Arc::new(SkillSettingsHost(settings)))?; if let Some(clients) = clients { root.provide_as::(Arc::new(SessionClientsHost::new(clients)))?; diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 810e16c3fd..1fe6546c7d 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -10,7 +10,7 @@ use dim_agent_capabilities::{ file_storage::FileStoragePlugin, history::HistoryRenderer, host::*, - host_platform::{HostPlatform, HostPlatformConfig, HostPlatformPlugin, resolve_shell}, + host_platform::{ExecHost, HostPlatformConfig, HostPlatformPlugin, resolve_shell}, model_provider::ModelProviderPlugin, permission::{CommandRules, NoCommandRules}, skill_settings::SkillSettingsHost, @@ -98,19 +98,19 @@ impl ModelDriver for Script { } /// Provides the process HostPlatform the design lets tests construct. -struct PlatformPlugin(Arc); +struct PlatformPlugin(Arc); impl Plugin for PlatformPlugin { type Deps = (); fn name(&self) -> &str { "TestHostPlatform" } async fn apply(&self, ctx: &Ctx, (): Self::Deps) -> rutis::Result { - ctx.provide_as::(self.0.clone())?; + ctx.provide_as::(self.0.clone())?; Ok(()) } } /// `platform` provided by [`PlatformPlugin`], a row of the harness's host. -fn test_platform(platform: HostPlatform) -> impl FnOnce(&mut AgentBuilder) { +fn test_platform(platform: ExecHost) -> impl FnOnce(&mut AgentBuilder) { let platform = Arc::new(platform); move |builder| { builder.plugin(move |_| Ok(Box::new(PlatformPlugin(platform.clone())))); @@ -128,6 +128,7 @@ fn configured_platform(home: PathBuf) -> impl FnOnce(&mut AgentBuilder) { HostPlatformConfig { execution: names.key()?, toolchain: names.key()?, + command_files: Some((0, "command-output".into())), exec_shell_file: Some((0, "exec-shell.json".into())), home: None, }, @@ -148,11 +149,11 @@ fn scratch(name: &str) -> PathBuf { std::fs::canonicalize(path).unwrap() } -async fn platform(extra: &[(&str, &str)]) -> HostPlatform { +async fn platform(extra: &[(&str, &str)]) -> ExecHost { let mut env: Vec<_> = std::env::vars_os().collect(); env.retain(|(key, _)| key != "SHELL"); env.push(("SHELL".into(), "/bin/bash".into())); - let mut platform = HostPlatform::current(resolve_shell(Ok(None), &env).await) + let mut platform = ExecHost::current(resolve_shell(Ok(None), &env).await) .unwrap() .with_execution_settings(ExecutionSettingsHost::fixed(ExecutionSettings::default())); platform.env.extend( @@ -173,15 +174,15 @@ struct Harness { } impl Harness { - async fn new(platform: HostPlatform) -> Self { + async fn new(platform: ExecHost) -> Self { Self::with_context(platform, false).await } /// The same assembly with a context model and a strategy bound, so a flow /// test can compact (`local_support/compaction.rs`). - async fn new_compacting(platform: HostPlatform) -> Self { + async fn new_compacting(platform: ExecHost) -> Self { Self::with_context(platform, true).await } - async fn with_context(mut platform: HostPlatform, compacting: bool) -> Self { + async fn with_context(mut platform: ExecHost, compacting: bool) -> Self { let home = scratch("home"); platform.home = home.clone(); let cwd = scratch("cwd"); diff --git a/tests/integration/tests/prompt_guide.rs b/tests/integration/tests/prompt_guide.rs index 92d2087299..4b801dde47 100644 --- a/tests/integration/tests/prompt_guide.rs +++ b/tests/integration/tests/prompt_guide.rs @@ -10,7 +10,7 @@ use dim_agent_capabilities::{ defaults, history::HistoryRenderer, host::*, - host_platform::HostPlatform, + host_platform::ExecHost, model_provider::ModelProviderPlugin, permission::{CommandRules, NoCommandRules}, prompt_guide::{GuideEntries, GuideEntry, GuideScope}, @@ -92,7 +92,7 @@ fn mock_model_hosts(builder: &mut AgentBuilder) { /// read. async fn platform_host(builder: &AgentBuilder, dirs: &Dirs) -> MinimalHost { MinimalHost::start_with(builder, |root, _| { - root.provide_as::(Arc::new(platform(&dirs.home)))?; + root.provide_as::(Arc::new(platform(&dirs.home)))?; Ok(()) }) .await diff --git a/tests/integration/tests/skills.rs b/tests/integration/tests/skills.rs index b152744dd6..fa1671be0a 100644 --- a/tests/integration/tests/skills.rs +++ b/tests/integration/tests/skills.rs @@ -786,13 +786,13 @@ impl SkillSettings for SlowFirstResponse { #[tokio::test(flavor = "multi_thread")] async fn a_late_update_response_does_not_overwrite_a_newer_setting() { use dim_agent_capabilities::{ - host_platform::HostPlatform, skill_settings::SkillSettingsHost, skills::SkillsCatalogPlugin, + host_platform::ExecHost, skill_settings::SkillSettingsHost, skills::SkillsCatalogPlugin, }; use std::sync::Arc; let dirs = Dirs::new(); let layout = layout(&dirs); let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); - root.provide_as::(Arc::new(platform(&dirs.home))) + root.provide_as::(Arc::new(platform(&dirs.home))) .unwrap(); let settings = Arc::new(SlowFirstResponse { inner: Arc::default(), @@ -1062,13 +1062,13 @@ async fn unavailable_settings_isolate_skills_and_refresh_recovers_existing_sessi #[tokio::test(flavor = "multi_thread")] async fn a_failed_read_back_is_reported_and_recovered_by_the_next_query() { use dim_agent_capabilities::{ - host_platform::HostPlatform, skill_settings::SkillSettingsHost, skills::SkillsCatalogPlugin, + host_platform::ExecHost, skill_settings::SkillSettingsHost, skills::SkillsCatalogPlugin, }; use std::sync::Arc; let dirs = Dirs::new(); let layout = layout(&dirs); let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); - root.provide_as::(Arc::new(platform(&dirs.home))) + root.provide_as::(Arc::new(platform(&dirs.home))) .unwrap(); let settings = Arc::new(FailingReads { inner: Arc::default(), @@ -1871,7 +1871,7 @@ async fn remove_deletes_only_what_the_record_owns() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_new_catalog_restores_installations_from_settings() { - use dim_agent_capabilities::{host_platform::HostPlatform, skill_settings::SkillSettingsHost}; + use dim_agent_capabilities::{host_platform::ExecHost, skill_settings::SkillSettingsHost}; let dirs = Dirs::new(); let source = installation_source(&dirs); @@ -1894,7 +1894,7 @@ async fn a_new_catalog_restores_installations_from_settings() { env.agent.close().await.unwrap(); let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); - root.provide_as::(Arc::new(platform(&dirs.home))) + root.provide_as::(Arc::new(platform(&dirs.home))) .unwrap(); let settings: Arc = settings; root.provide_as::(Arc::new(SkillSettingsHost(settings))) diff --git a/xtask/src/app_server.rs b/xtask/src/app_server.rs index 7cfa75435a..9bf74553cd 100644 --- a/xtask/src/app_server.rs +++ b/xtask/src/app_server.rs @@ -65,6 +65,7 @@ pub struct Overrides { /// endpoint a client connects to. The product path leaves every field empty. #[derive(Clone)] pub struct RunSettings { + pub platform_home: Option, pub overrides: Overrides, pub model_config: Option, pub unix_path: Option, @@ -90,6 +91,7 @@ pub struct RunSettings { impl Default for RunSettings { fn default() -> Self { Self { + platform_home: None, overrides: Overrides::default(), model_config: None, unix_path: None, @@ -173,6 +175,7 @@ pub async fn serve_home( let mut config = ServerConfig { websocket_address: Some(([127, 0, 0, 1], 0).into()), unix_path: run.unix_path.clone(), + platform_home: run.platform_home.clone(), product_home: product.then(|| home.clone()), target_home: Some(if product { home.join("rust") diff --git a/xtask/src/plugins.rs b/xtask/src/plugins.rs index f7ba5ccdf9..a29d808464 100644 --- a/xtask/src/plugins.rs +++ b/xtask/src/plugins.rs @@ -14,7 +14,7 @@ use dim_agent_capabilities::{ SessionFileError, SessionFileErrorCode, SessionFiles, SessionFilesService, StoredSessionFile, }, - host_platform::{HostPlatform, ShellStatus}, + host_platform::{ExecHost, ShellStatus}, model_provider::ModelProviderPlugin, permission::{CommandRules, NoCommandRules}, skill_settings::SkillSettingsHost, @@ -60,7 +60,7 @@ impl DynPlugin for GraphPlatform { fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { let execution = ctx.require_at(&self.execution)?; - let mut platform = HostPlatform::current(ShellStatus::Unavailable { + let mut platform = ExecHost::current(ShellStatus::Unavailable { code: "GRAPH_ONLY", reason: "Graph generation does not execute commands".into(), }) @@ -69,7 +69,7 @@ impl DynPlugin for GraphPlatform { let toolchain = ctx.require_at(&self.toolchain)?; platform = platform.with_toolchain_source((*toolchain).clone()); platform.home = self.home.clone(); - ctx.provide_as::(Arc::new(platform))?; + ctx.provide_as::(Arc::new(platform))?; Ok(Effect::Done) }) } diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index ee6aaf7649..1c57a96820 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -628,8 +628,8 @@ const TEXTS: &[(&str, TextMember)] = &[ pub async fn run() -> Result<()> { let options = Options::parse()?; let report = match (&options.rejudge, options.pool.is_empty()) { - (Some(source), _) => rejudge(&options, source, |_| {}).await?, - (None, false) => pooled(&options, |_| {}).await?, + (Some(source), _) => rejudge(&options, source, None).await?, + (None, false) => pooled(&options, None).await?, (None, true) => evaluate(&options).await?, }; println!("{report}"); @@ -751,11 +751,7 @@ async fn evaluate(options: &Options) -> Result { /// and is not judged again; every other run keeps its own outcome — `stop`, /// `turns`, `error` — and gains the judge's part afresh. The source is never /// written to. -async fn rejudge( - options: &Options, - source: &Path, - observe: impl Fn(&mut AgentBuilder), -) -> Result { +async fn rejudge(options: &Options, source: &Path, platform_home: Option<&Path>) -> Result { let source = std::fs::canonicalize(source) .map_err(|error| format!("--rejudge {}: {error}", source.display()))?; let saved = read_saved_runs(&source)?; @@ -776,7 +772,7 @@ async fn rejudge( plan.push((run, index)); } let cancel = CancellationToken::new(); - let server = served(options, observe).await?; + let server = served(options, platform_home).await?; let outcome = rejudge_with(options, &source, &server, &scenarios, &plan, &cancel).await; server.shutdown(); server.join().await?; @@ -793,7 +789,7 @@ async fn rejudge( /// source's `runs.jsonl` is read as it stands, in the order given; the /// sources are never written to, and nothing is re-judged. A pooled set /// keeps the sources' run numbers, which may repeat between them. -async fn pooled(options: &Options, observe: impl Fn(&mut AgentBuilder)) -> Result { +async fn pooled(options: &Options, platform_home: Option<&Path>) -> Result { let scenarios = read_scenarios(&options.scenarios)?; let mut records = Vec::new(); let mut directories = Vec::new(); @@ -805,7 +801,7 @@ async fn pooled(options: &Options, observe: impl Fn(&mut AgentBuilder)) -> Resul records.extend(read); } let cancel = CancellationToken::new(); - let server = served(options, observe).await?; + let server = served(options, platform_home).await?; let resolved = async { let model = selection(&server, &options.model, &options.out, &cancel).await?; let judge = selection(&server, &options.judge, &options.out, &cancel).await?; @@ -826,7 +822,7 @@ async fn pooled(options: &Options, observe: impl Fn(&mut AgentBuilder)) -> Resul /// The profile a re-judge or a pool resolves the judge in: the model /// configuration under a fresh home beside the output. No Session is created /// and no model turn runs. -async fn served(options: &Options, observe: impl Fn(&mut AgentBuilder)) -> Result { +async fn served(options: &Options, platform_home: Option<&Path>) -> Result { let home = options.out.join("home"); private_directory(&home)?; app_server::serve_home( @@ -835,9 +831,10 @@ async fn served(options: &Options, observe: impl Fn(&mut AgentBuilder)) -> Resul options.out.join("command-output"), RunSettings { model_config: options.model_config.clone(), + platform_home: platform_home.map(Path::to_owned), ..Default::default() }, - observe, + |_| {}, ) .await } @@ -2408,6 +2405,7 @@ async fn child_outcome(params: &ChildParams, preflight: &Arc) -> Child js_runtime: params.js_runtime.clone(), boundary: params.boundary.clone(), plugin_tools: false, + platform_home: None, }; // The scenario's event producers run in the child, whose process // publishes what the run's Session subscribes to (EventHub design A.1). @@ -2471,6 +2469,7 @@ fn native_probe_settings( js_runtime: None, boundary, plugin_tools: false, + platform_home: None, } } @@ -6795,7 +6794,6 @@ mod tests { HostFuture, ModelConnection, ModelDriver, ModelStopReason, ResolveModelConnection, ResolvedModelConnection, }; - use dim_agent_capabilities::host_platform::{HostPlatform, resolve_shell}; use std::sync::{ Mutex, atomic::{AtomicUsize, Ordering}, @@ -9491,7 +9489,7 @@ mod tests { /// The process facts a flow's runs see: the ones this process has, /// with `home` pointed at the fixture's own empty directory, so a run /// never reads the developer's `~/AGENTS.md`, Skills list or ``. - platform: HostPlatform, + platform_home: PathBuf, } impl Fixture { /// `scenario` is the scenario file's content and `workspace` the @@ -9591,23 +9589,13 @@ mod tests { .unwrap(); let platform_home = directory.join("platform-home"); std::fs::create_dir_all(&platform_home).unwrap(); - let env: Vec<_> = std::env::vars_os().collect(); - let shell = resolve_shell(Ok(None), &env).await; - let mut platform = HostPlatform::current(shell) - .unwrap() - .with_execution_settings( - dim_agent_capabilities::execution_settings::ExecutionSettingsHost::fixed( - Default::default(), - ), - ); - platform.home = platform_home; Self { directory, provider, http, models, scenarios, - platform, + platform_home, } } /// [`evaluate`] over this fixture's runs, whose process facts point at @@ -9623,19 +9611,14 @@ mod tests { rejudge( options, options.rejudge.as_deref().expect("a rejudge source"), - |builder| { - builder.process_value(Arc::new(self.platform.clone())); - }, + Some(&self.platform_home), ) .await } /// [`pooled`] over this fixture's provider, with the same process /// facts as [`evaluate`](Self::evaluate). async fn pooled(&self, options: &Options) -> Result { - pooled(options, |builder| { - builder.process_value(Arc::new(self.platform.clone())); - }) - .await + pooled(options, Some(&self.platform_home)).await } /// The options of one run per arm over this fixture, with `out`. fn options(&self, out: PathBuf) -> Options {