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..94aecaf125 100644 --- a/crates/dim-agent-capabilities/examples/host_platform_bubblewrap_spike.rs +++ b/crates/dim-agent-capabilities/examples/host_platform_bubblewrap_spike.rs @@ -145,7 +145,7 @@ mod linux { } async fn run(platform: &HostPlatform, spec: ProcessSpec) -> Result { - let mut tree = platform.spawn(spec)?; + let mut tree = platform.spawn_tree(spec)?; let (mut stdout, mut stderr) = (tree.stdout(), tree.stderr()); let (mut out, mut err) = (Vec::new(), Vec::new()); let (status, _, _) = tokio::time::timeout(LIMIT, async { @@ -315,7 +315,7 @@ mod linux { spec }; let script = "(while :; do printf x >> heartbeat; sleep 0.05; done) > background.log 2>&1 & echo $! > child.pid; echo ready; while test ! -f release; do sleep 0.01; done"; - let mut tree = platform.spawn(prepare(command( + let mut tree = platform.spawn_tree(prepare(command( &workspace, Path::new("/bin/sh"), vec!["-c".into(), script.into()], @@ -518,7 +518,8 @@ mod linux { ); checks.push("host UNIX socket outside grants is inaccessible"); - let mut tree = platform.spawn(isolated(shell("sleep 60 & echo ready; wait"), &readonly))?; + let mut tree = + platform.spawn_tree(isolated(shell("sleep 60 & echo ready; wait"), &readonly))?; let mut line = String::new(); tokio::time::timeout(LIMIT, BufReader::new(tree.stdout()).read_line(&mut line)).await??; assert_eq!(line.trim(), "ready"); 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..9ae2ed1de5 100644 --- a/crates/dim-agent-capabilities/examples/host_platform_isolation_spike.rs +++ b/crates/dim-agent-capabilities/examples/host_platform_isolation_spike.rs @@ -70,7 +70,7 @@ mod macos { } async fn run(platform: &HostPlatform, spec: ProcessSpec) -> Result { - let mut tree = platform.spawn(spec)?; + let mut tree = platform.spawn_tree(spec)?; let (mut stdout, mut stderr) = (tree.stdout(), tree.stderr()); let (mut out, mut err) = (Vec::new(), Vec::new()); let (status, _, _) = tokio::time::timeout(LIMIT, async { @@ -253,7 +253,7 @@ mod macos { assert!(!marker.exists()); checks.push("invalid policy never executes payload"); - let mut tree = platform.spawn(isolated( + let mut tree = platform.spawn_tree(isolated( command( &workspace, "/bin/sh", 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..083938cc03 100644 --- a/crates/dim-agent-capabilities/examples/host_platform_landlock_spike.rs +++ b/crates/dim-agent-capabilities/examples/host_platform_landlock_spike.rs @@ -158,7 +158,7 @@ mod linux { Ok(spec) } async fn run(platform: &HostPlatform, spec: ProcessSpec) -> Result { - let mut tree = platform.spawn(spec)?; + let mut tree = platform.spawn_tree(spec)?; let (mut stdout, mut stderr) = (tree.stdout(), tree.stderr()); let (mut out, mut err) = (Vec::new(), Vec::new()); let (status, _, _) = tokio::time::timeout(LIMIT, async { @@ -277,7 +277,7 @@ mod linux { assert!(!marker.exists()); checks.push("invalid policy does not execute payload"); - let mut tree = platform.spawn(isolated( + let mut tree = platform.spawn_tree(isolated( shell( "sleep 60 & child=$!; printf '%s\\n' \"$child\"; wait \"$child\"", vec![], diff --git a/crates/dim-agent-capabilities/src/exec_stop.rs b/crates/dim-agent-capabilities/src/exec_stop.rs index 217c45f795..f060a5a572 100644 --- a/crates/dim-agent-capabilities/src/exec_stop.rs +++ b/crates/dim-agent-capabilities/src/exec_stop.rs @@ -14,6 +14,7 @@ use std::sync::Arc; pub enum TaskError { Unknown, Closed, + Read, } /// Stops a background task by id. diff --git a/crates/dim-agent-capabilities/src/file_access.rs b/crates/dim-agent-capabilities/src/file_access.rs index c15072e70d..d6e9e02385 100644 --- a/crates/dim-agent-capabilities/src/file_access.rs +++ b/crates/dim-agent-capabilities/src/file_access.rs @@ -624,7 +624,7 @@ impl Worktrees { env.push(("LC_ALL".into(), "C".into())); let mut tree = self .platform - .spawn(ProcessSpec { + .spawn_tree(ProcessSpec { executable: "git".into(), args: vec![ "-C".into(), diff --git a/crates/dim-agent-capabilities/src/hooks/runner.rs b/crates/dim-agent-capabilities/src/hooks/runner.rs index f4e526bc37..0533ebc968 100644 --- a/crates/dim-agent-capabilities/src/hooks/runner.rs +++ b/crates/dim-agent-capabilities/src/hooks/runner.rs @@ -14,11 +14,15 @@ use crate::{ handlers, }, host::{HostError, HostFuture}, - host_platform::{HostPlatform, Os}, + host_platform::{ + HostPlatform, HostPlatformError, Os, OutputLimits, SpawnWithStdinReply, + SpawnWithStdinRequest, SpawnWithStdinStatus, + }, input_queue::{CheckSubmission, SubmitCheckReply, SubmitCheckRequest, SubmitChecks}, permission::{AdmissionDecision, AdviseTool, Permission, ToolAdviceReply, ToolAdviceRequest}, tool_registry::ToolRegistry, }; +use base64::{Engine, engine::general_purpose::STANDARD}; use dim_agent_runtime::{ AgentError, BranchLifecycle, CollaborationRole, Dispatcher, Names, QueryComparison, QueryFilter, QueryOperand, QueryOutput, QueryPage, QueryPick, QuerySelect, QuerySpec, @@ -35,7 +39,6 @@ use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use serde_json::{Value, json}; use std::{ collections::HashMap, - ffi::OsString, future::Future, num::NonZeroU64, path::Path, @@ -43,10 +46,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). @@ -385,90 +385,71 @@ impl HooksRuntime { ) -> HookResult { let command = handler.command(self.platform.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; - } - }; - 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(), - }; + return unloaded_run(handler).result; } - let mut tree = match self.platform.spawn_with_stdin(spec, stdin) { - Ok(tree) => tree, - Err(error) => { - let result = failed(format!("spawn failed: {error}"), &[]); + let env = match self.environment(handler) { + Ok(env) => env, + Err(reason) => { + let result = failed(reason, &[]); 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, - ), - 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 request = SpawnWithStdinRequest { + command: command.into(), + cwd: self.config.cwd.clone(), + env, + stdin: Some(STANDARD.encode(stdin)), + timeout_ms: handler.timeout.as_millis() as u64, + limits: OutputLimits { + stdout: STDOUT_LIMIT, + stderr: STDERR_LIMIT, + }, }; - let result = match end { - End::Cancelled => { - let _ = tree.terminate().await; - failed("cancelled", &[]) + let reply = match self + .platform + .spawn_with_stdin(request, cancelled_by(cancel, gate)) + .await + { + Ok(reply) => reply, + Err(HostPlatformError::Cancelled) if gate.is_some_and(|gate| gate.is_cancelled()) => { + return unloaded_run(handler).result; } - End::TimedOut => { - let _ = tree.terminate().await; - failed( - format!("timed out after {}s", handler.timeout.as_secs()), - &[], - ) + Err(HostPlatformError::Cancelled) => return failed("cancelled", &[]), + Err(error) => { + let result = failed(error.to_string(), &[]); + self.report(handler, &result, started.elapsed()); + return result; } - 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; - } - }; - if overflow { + }; + let stdout = STANDARD.decode(&reply.stdout).unwrap_or_default(); + let stderr = STANDARD.decode(&reply.stderr).unwrap_or_default(); + let result = match reply.status { + SpawnWithStdinStatus::Exited => { + if reply.stdout_truncated { failed("stdout exceeded 64 KiB", &stderr) - } else if status.code() == Some(2) { + } else if reply.exit_code == Some(2) { exit_two(handler.event, &stderr) - } else if status.success() { + } else if reply.exit_code == Some(0) { HookResult::Success { - stdout: String::from_utf8_lossy_owned(bytes), + stdout: String::from_utf8_lossy_owned(stdout), } } else { - failed(format!("exited with {status}"), &stderr) + failed(format!("exited with {}", exit_text(&reply)), &stderr) } } + SpawnWithStdinStatus::Signaled => { + failed(format!("exited with {}", exit_text(&reply)), &stderr) + } + SpawnWithStdinStatus::Cancelled if gate.is_some_and(|gate| gate.is_cancelled()) => { + unloaded_run(handler).result + } + SpawnWithStdinStatus::Cancelled => failed("cancelled", &[]), + SpawnWithStdinStatus::TimedOut => failed( + format!("timed out after {}s", handler.timeout.as_secs()), + &[], + ), }; self.report(handler, &result, started.elapsed()); // The run's result is taken here, in the same poll that hands it to @@ -498,59 +479,72 @@ 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())), - ( - "DIM_SESSION_ID", - OsString::from(self.identity.session_id.clone()), + fn environment( + &self, + handler: &HookHandler, + ) -> Result>, String> { + let mut env: std::collections::BTreeMap<_, _> = MANAGED_ENV + .into_iter() + .map(|key| (key.to_owned(), None)) + .collect(); + let home = match self.sources.0.home() { + Some(home) => Some( + home.to_str() + .ok_or_else(|| "DIMCODE_HOME is not UTF-8".to_owned())? + .to_owned(), ), - ]; - 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())); + None => None, + }; + let plugin_root = match handler.plugin_root.as_ref() { + Some(root) => Some( + root.to_str() + .ok_or_else(|| "DIM_PLUGIN_ROOT is not UTF-8".to_owned())? + .to_owned(), + ), + None => None, + }; + for (key, value) in [ + ("DIM_PROJECT_DIR", Some(self.config.cwd.clone())), + ("DIM_HOOK_EVENT", Some(handler.event.name().to_owned())), + ("DIM_SESSION_ID", Some(self.identity.session_id.clone())), + ("DIMCODE_HOME", home), + ("DIM_PLUGIN_ROOT", plugin_root), + ] { + env.insert(key.to_owned(), value); } - vars + Ok(env) } } -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 +/// Cancels the call when the point's cancel or the unload gate fires. +fn cancelled_by( + cancel: &CancellationToken, + gate: Option<&CancellationToken>, +) -> crate::host::CancelledFn { + let cancel = cancel.clone(); + let gate = gate.cloned(); + std::sync::Arc::new(move || { + let cancel = cancel.clone(); + let gate = gate.clone(); + Box::pin(async move { + match gate { + Some(gate) => tokio::select! { + biased; + _ = cancel.cancelled() => {} + _ = gate.cancelled() => {} + }, + None => cancel.cancelled().await, + } + Ok(()) + }) + }) } -/// 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; - } - } - } +fn exit_text(reply: &SpawnWithStdinReply) -> String { + match (reply.exit_code, &reply.signal) { + (Some(code), _) => format!("exit status: {code}"), + (_, Some(signal)) => format!("signal: {signal}"), + _ => "unknown".to_owned(), } } diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 5a4cd2d430..72ad3b4002 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -7,20 +7,23 @@ use crate::execution_settings::ExecutionSettingsHost; use crate::file_storage::{FileStorage, FileStorageError}; use crate::toolchain::{InstalledToolchain, ToolchainSourceHost}; +use base64::{Engine, engine::general_purpose::STANDARD}; use dim_agent_runtime::Names; use rutis::Ctx; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, ErrorKind, Key, TypeKey}; use std::{ + collections::BTreeMap, ffi::{OsStr, OsString}, io, - path::{Path, PathBuf}, + path::{Component, Path, PathBuf}, process::{ExitStatus, Stdio}, sync::Arc, + time::{Duration, Instant}, }; use tokio::{ - io::{AsyncReadExt, AsyncWriteExt}, + io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, process::{Child, ChildStderr, ChildStdout}, - sync::Mutex, + sync::{Mutex, watch}, }; use tokio_util::sync::CancellationToken; @@ -28,6 +31,14 @@ mod confined; mod exec_shell_settings; #[cfg(unix)] mod isolation; +pub(crate) mod output; +mod task; + +pub(crate) use task::{OutputRecord, TaskKind, TaskRecord, TaskStatus, Terminal}; + +/// Step 1 keeps the old table name as an alias; step 3 removes it with the exec handoff. +#[allow(dead_code, reason = "step 1 compatibility name; removed in step 3")] +pub(crate) type ExecutionTask = TaskKind; pub use confined::{ ConfinedError, ConfinedOutput, ConfinedSpec, ConfinedStream, Confinement, SystemServices, }; @@ -56,10 +67,13 @@ pub(crate) const ISOLATION_SUMMARY: Option<&str> = if cfg!(target_os = "macos") None }; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] pub enum Os { + #[serde(rename = "darwin")] Macos, + #[serde(rename = "linux")] Linux, + #[serde(rename = "win32")] Windows, } impl Os { @@ -80,7 +94,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 +136,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 +148,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 { - pub executable_path: PathBuf, + #[serde(rename = "executable")] + pub executable_path: String, 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 }, @@ -229,6 +249,10 @@ 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, + stopping: Arc>>, shell: Arc>, shell_file: Option<(Arc, usize, PathBuf)>, pub(crate) execution: Option>, @@ -276,7 +300,8 @@ 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 }, @@ -284,6 +309,7 @@ pub enum SandboxBackend { /// What a consumer keeps for a process that /// [`HostPlatform::prepare_isolated_process`] sandboxed. +#[derive(Clone, Copy)] pub(crate) struct Isolation; impl Isolation { @@ -335,6 +361,375 @@ impl Drop for TemporaryDirectory { } } +/// How a wait reply ended, or that it is still running. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum WaitStatus { + Running, + Exited, + Signaled, + TimedOut, + Cancelled, + Failed, +} + +/// A wait reply; terminal when the task ended, `running` when the wait deadline elapsed. +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WaitReply { + pub status: WaitStatus, + #[serde(skip_serializing_if = "Option::is_none")] + pub text: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub exit_code: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub signal: Option, + pub duration_ms: u64, + pub output_path: String, + pub output_bytes: u64, + pub output_truncated: bool, + pub preview: String, + pub preview_truncated: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub failure: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_note: Option, +} + +/// Why a task reached a failed or cancelled terminal record. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum TaskFailure { + OutputWriteFailed { message: String }, + TerminateFailed { message: String }, + JobUnavailable { message: String }, + ShellExited, + ShellReset, + CommandFailed, + UnknownExit, + OwnerUnloaded, +} + +impl std::fmt::Display for TaskFailure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::OutputWriteFailed { message } + | Self::TerminateFailed { message } + | Self::JobUnavailable { message } => f.write_str(message), + Self::ShellExited => f.write_str("shell exited"), + Self::ShellReset => f.write_str("shell reset"), + Self::CommandFailed => f.write_str("command failed"), + Self::UnknownExit => f.write_str("command ended with an unknown exit"), + Self::OwnerUnloaded => f.write_str("execution owner unloaded"), + } + } +} + +/// A page of a task's captured output. +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OutputPageReply { + pub text: String, + pub bytes: u64, + pub total_bytes: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + pub truncated: bool, + pub retained_from: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub reset: Option, +} + +#[derive(Clone, Debug, serde::Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(crate) enum ShellEvent { + Output { cursor: u64, text: String }, + Marker { cursor: u64, line: String }, +} + +impl ShellEvent { + pub(crate) fn cursor(&self) -> u64 { + match self { + Self::Output { cursor, .. } | Self::Marker { cursor, .. } => *cursor, + } + } +} + +/// A request to start a persistent PTY shell on this execution node. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ShellRequest { + pub task_id: String, + pub cwd: String, + pub workspace: String, + pub roots: Vec, + pub output_dir: String, + pub cols: u16, + pub rows: u16, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ShellWrite { + pub task_id: String, + pub data: String, + #[serde(default)] + pub command: Option, + #[serde(default)] + pub job: Option, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ShellJobStart { + pub task_id: String, + pub end_marker: String, + /// Absolute path of the job's log; it must be inside the shell output directory. + pub output_path: String, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ShellCommandStart { + pub task_id: String, + pub start_marker: String, + pub end_marker: String, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ShellResize { + pub task_id: String, + pub cols: u16, + pub rows: u16, +} + +/// Byte limits for a configured command's two streams. +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OutputLimits { + pub stdout: usize, + pub stderr: usize, +} + +/// A request to run one confined helper on this node. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConfinedRequest { + pub program: String, + pub args: Vec, + pub read: Vec, + pub write: Vec, + #[serde(default)] + pub env: BTreeMap, + pub timeout_ms: u64, + pub output_limit: OutputLimits, + pub services: confined::SystemServices, +} + +/// A confined helper's bounded result. Success means it stayed within its +/// limits; an output limit is an error, not a truncated reply. +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConfinedReply { + pub status: Option, + pub stdout: String, + pub stderr: String, + pub confined: bool, +} + +/// A request to compose the PATH a child process gets. `base` is UTF-8; a +/// result that cannot be represented answers `None`. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ChildPathRequest { + pub directories: Vec, + pub base: String, +} + +/// A request to remove a persistent-shell output directory. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RemoveOutputDirectoryRequest { + pub path: String, +} + +/// A request to run one configured command with stdin. `env` is UTF-8; a +/// non-UTF-8 environment belongs to the in-process binding. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SpawnWithStdinRequest { + pub command: String, + pub cwd: String, + pub env: BTreeMap>, + pub stdin: Option, + pub timeout_ms: u64, + pub limits: OutputLimits, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SpawnWithStdinStatus { + Exited, + Signaled, + Cancelled, + TimedOut, +} + +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SpawnWithStdinReply { + pub status: SpawnWithStdinStatus, + #[serde(skip_serializing_if = "Option::is_none")] + pub exit_code: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub signal: Option, + pub duration_ms: u64, + pub stdout: String, + pub stderr: String, + pub stdout_truncated: bool, + pub stderr_truncated: bool, +} + +/// A request to start a command on this execution node. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SpawnRequest { + pub task_id: String, + pub command: String, + pub cwd: String, + pub workspace: String, + pub roots: Vec, + pub output_dir: String, + pub timeout_ms: Option, +} + +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SpawnReply { + pub task_id: String, + pub output_path: String, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TaskRequest { + pub task_id: String, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WaitRequest { + pub task_id: String, + pub timeout_ms: Option, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct OutputRequest { + pub task_id: String, + pub cursor: Option, + pub limit: Option, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct ShellEventRequest { + pub task_id: String, + pub cursor: u64, + pub wait_ms: u64, + pub limit: usize, +} + +pub(crate) struct ShellEventPage { + pub events: Vec, + pub next_cursor: u64, +} + +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OutputPathReply { + pub output_path: String, +} + +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum HostPlatformError { + #[error("invalid request: {0}")] + Invalid(String), + #[error("invalid path {path}: {reason}")] + InvalidPath { path: String, reason: String }, + #[error("the confined helper exceeded its timeout")] + TimedOut, + #[error("the confined helper reached its {stream} limit")] + OutputLimit { stream: ConfinedStream }, + #[error("unknown execution task")] + TaskUnknown, + #[error("execution task already exists")] + TaskExists, + #[error("execution task is still running")] + TaskRunning, + #[error("execution task has ended")] + TaskEnded, + #[error("output unavailable: {0}")] + OutputUnavailable(String), + #[error("cancelled")] + Cancelled, + #[error("execution host closed")] + Closed, + #[error("{0}")] + Io(String), + #[error("isolation configuration is invalid: {0}")] + IsolationConfigInvalid(String), + #[error("isolation is unavailable: {0}")] + IsolationUnavailable(String), + #[error("exec shell configuration is invalid: {0}")] + ExecShellConfigInvalid(String), + #[error("exec shell is unavailable: {0}")] + ExecShellUnavailable(String), + #[error("exec shell does not support this working directory: {0}")] + ExecShellCwdUnsupported(String), + #[error("working directory not found: {0}")] + CwdNotFound(String), + #[error("exec shell path mapping failed: {0}")] + ExecShellPathMappingFailed(String), + #[error("{0}")] + Failed(String), +} + +impl From for HostPlatformError { + fn from(error: crate::workspace_tools::background::OutputPageError) -> Self { + Self::OutputUnavailable(error.to_string()) + } +} + +impl From for HostPlatformError { + fn from(error: crate::workspace_tools::exec::CaptureError) -> Self { + match error { + crate::workspace_tools::exec::CaptureError::Unknown => Self::TaskUnknown, + crate::workspace_tools::exec::CaptureError::Unavailable(reason) => { + Self::OutputUnavailable(reason) + } + } + } +} + +/// The process facts the `hostPlatform.info` operation answers. +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HostInfo { + pub os: Os, + pub arch: String, + pub home: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub timezone: Option, + pub exec_root: String, + pub platform_roots: Vec, + pub backend: SandboxBackend, + pub exec_shell: ShellStatus, +} + +#[rutis::service] impl HostPlatform { /// Facts of the current process with an already resolved shell. pub fn current(shell: ShellStatus) -> io::Result { @@ -357,6 +752,10 @@ impl HostPlatform { status: shell, })), shell_file: None, + commands: Arc::default(), + command_shutdown: CancellationToken::new(), + command_workers: tokio_util::task::TaskTracker::new(), + stopping: Arc::default(), execution: None, toolchain: None, }) @@ -364,6 +763,7 @@ impl HostPlatform { /// Uses `host` for the execution switches at each process preparation. The /// HostPlatform plugin wires it; a platform without switches fails /// preparation instead of running unsandboxed (ADR 011 D1). + #[service(skip)] pub fn with_execution_settings(mut self, host: ExecutionSettingsHost) -> Self { self.execution = Some(Arc::new(host)); self @@ -371,31 +771,11 @@ impl HostPlatform { /// Uses `host` for the installed runtimes at each process start. The /// HostPlatform plugin wires it; a platform without it starts processes /// with the PATH they would have without any runtime. + #[service(skip)] pub fn with_toolchain_source(mut self, host: ToolchainSourceHost) -> Self { self.toolchain = Some(Arc::new(host)); self } - /// Reads the configured exec shell for this invocation without reloading - /// the plugin. Explicitly constructed platforms keep their supplied shell. - pub async fn exec_shell(&self) -> ShellStatus { - let mut resolved = self.shell.lock().await; - if let Some((storage, root, relative)) = &self.shell_file { - let config = read_config(storage, *root, relative).await; - if config != resolved.config - || matches!( - resolved.status, - ShellStatus::Unavailable { - code: EXEC_SHELL_UNAVAILABLE, - .. - } - ) - { - let status = resolve_shell(config.clone(), &self.env).await; - *resolved = ResolvedShell { config, status }; - } - } - resolved.status.clone() - } /// The command for `spec` with a cleared environment; `stdin` is the caller's choice. fn command(spec: &ProcessSpec, stdin: Stdio) -> tokio::process::Command { let mut command = tokio::process::Command::new(&spec.executable); @@ -408,13 +788,207 @@ impl HostPlatform { command } /// Starts `spec` as the root of its own process tree. - pub fn spawn(&self, spec: ProcessSpec) -> io::Result { + #[service(skip)] + pub fn spawn_tree(&self, spec: ProcessSpec) -> io::Result { ProcessTree::spawn(Self::command(&spec, Stdio::null())) } /// [`Self::spawn`] with `stdin` written to the child's standard input, /// which then closes. A child that exits before reading it does not fail /// the start. - pub fn spawn_with_stdin(&self, spec: ProcessSpec, stdin: Vec) -> io::Result { + /// Runs one confined helper and returns its bounded result. + pub async fn spawn_confined( + &self, + request: ConfinedRequest, + cancelled: crate::host::CancelledFn, + ) -> Result { + let cancel = CancellationToken::new(); + let waiter = { + let cancel = cancel.clone(); + tokio::spawn(async move { + let _ = cancelled().await; + cancel.cancel(); + }) + }; + let spec = confined::ConfinedSpec { + executable: request.program.into(), + args: request.args.into_iter().map(Into::into).collect(), + env: request + .env + .into_iter() + .map(|(key, value)| (key.into(), value.into())) + .collect(), + }; + let confinement = confined::Confinement { + read: request.read.into_iter().map(PathBuf::from).collect(), + write: request.write.into_iter().map(PathBuf::from).collect(), + timeout: Duration::from_millis(request.timeout_ms), + stdout_limit: request.output_limit.stdout, + stderr_limit: request.output_limit.stderr, + services: request.services, + }; + let result = self.spawn_confined_process(spec, confinement, cancel).await; + waiter.abort(); + let output = result.map_err(|error| match error { + confined::ConfinedError::InvalidPath { path, reason } => { + HostPlatformError::InvalidPath { + path: path.to_string_lossy().into_owned(), + reason, + } + } + confined::ConfinedError::TimedOut => HostPlatformError::TimedOut, + confined::ConfinedError::OutputLimit { stream } => { + HostPlatformError::OutputLimit { stream } + } + confined::ConfinedError::Cancelled => HostPlatformError::Cancelled, + confined::ConfinedError::Spawn(error) | confined::ConfinedError::Cleanup(error) => { + HostPlatformError::Io(error.to_string()) + } + })?; + Ok(ConfinedReply { + status: output.status.code(), + stdout: STANDARD.encode(output.stdout), + stderr: STANDARD.encode(output.stderr), + confined: output.confined, + }) + } + + /// Composes the PATH a child process gets, as data. The served base is + /// UTF-8; a non-UTF-8 daemon PATH uses [`Self::child_path_process`] in + /// process and is not expressible through this face. + pub fn child_path(&self, request: ChildPathRequest) -> Option { + self.child_path_process(&request.directories, OsStr::new(&request.base)) + .and_then(|path| path.to_str().map(str::to_owned)) + } + + /// Removes a persistent-shell output directory below `execRoot`. + pub async fn remove_output_directory( + &self, + request: RemoveOutputDirectoryRequest, + ) -> Result<(), HostPlatformError> { + let platform = self.clone(); + let path = PathBuf::from(request.path); + tokio::task::spawn_blocking(move || platform.remove_exec_directory(&path)) + .await + .map_err(|error| HostPlatformError::Io(error.to_string()))? + .map_err(|error| { + if error.kind() == io::ErrorKind::InvalidInput { + HostPlatformError::Invalid(error.to_string()) + } else { + HostPlatformError::Io(error.to_string()) + } + }) + } + + /// Runs one configured command with stdin and returns its bounded result. + pub async fn spawn_with_stdin( + &self, + request: SpawnWithStdinRequest, + cancelled: crate::host::CancelledFn, + ) -> Result { + let started = Instant::now(); + let stdin = STANDARD + .decode(request.stdin.unwrap_or_default()) + .map_err(|error| HostPlatformError::Invalid(error.to_string()))?; + let cancel = CancellationToken::new(); + let waiter = { + let cancel = cancel.clone(); + tokio::spawn(async move { + let _ = cancelled().await; + cancel.cancel(); + }) + }; + let command = ConfiguredCommand { + command: request.command, + cwd: PathBuf::from(request.cwd), + env: request + .env + .into_iter() + .map(|(key, value)| (key.into(), value.map(Into::into))) + .collect(), + stdin, + timeout: Duration::from_millis(request.timeout_ms), + stdout_limit: request.limits.stdout, + stderr_limit: request.limits.stderr, + }; + let end = self.configured(command, &cancel, None).await; + waiter.abort(); + let end = end.map_err(|error| match error { + ConfiguredError::Prepare(error) => Self::process_error(error), + ConfiguredError::Unloaded => HostPlatformError::Closed, + ConfiguredError::Spawn(error) => HostPlatformError::Io(error.to_string()), + ConfiguredError::Wait(error, stderr) => { + let reason = format!("wait failed: {error}"); + HostPlatformError::Io(if stderr.is_empty() { + reason + } else { + format!("{reason}: {}", String::from_utf8_lossy(&stderr)) + }) + } + })?; + let duration_ms = started.elapsed().as_millis() as u64; + let (status, exit_code, signal, stdout, stderr, stdout_truncated, stderr_truncated) = + match end { + ConfiguredEnd::Exited { + status, + stdout, + stderr, + stdout_truncated, + stderr_truncated, + } => { + let signal = signal_name(status); + let exit_code = status.code(); + let status = if signal.is_some() { + SpawnWithStdinStatus::Signaled + } else { + SpawnWithStdinStatus::Exited + }; + ( + status, + exit_code, + signal, + stdout, + stderr, + stdout_truncated, + stderr_truncated, + ) + } + ConfiguredEnd::Cancelled => ( + SpawnWithStdinStatus::Cancelled, + None, + None, + Vec::new(), + Vec::new(), + false, + false, + ), + ConfiguredEnd::TimedOut => ( + SpawnWithStdinStatus::TimedOut, + None, + None, + Vec::new(), + Vec::new(), + false, + false, + ), + }; + Ok(SpawnWithStdinReply { + status, + exit_code, + signal, + duration_ms, + stdout: STANDARD.encode(stdout), + stderr: STANDARD.encode(stderr), + stdout_truncated, + stderr_truncated, + }) + } + + #[service(skip)] + pub fn spawn_with_stdin_process( + &self, + spec: ProcessSpec, + stdin: Vec, + ) -> io::Result { let mut tree = ProcessTree::spawn(Self::command(&spec, Stdio::piped()))?; if let Some(mut pipe) = tree.child.stdin.take() { tokio::spawn(async move { @@ -444,8 +1018,46 @@ impl HostPlatform { }) } - /// The sandbox backend a new process would use. Preparation reads the same - /// backend, so this report and the next process start cannot disagree. + #[cfg(windows)] + #[service(skip)] + pub(crate) async fn prepare_isolated_process( + &self, + spec: ProcessSpec, + _workspaces: &[PathBuf], + _output_dir: Option<&Path>, + ) -> Result<(ProcessSpec, Option, Option), ProcessSpecError> + { + if !self.execution_settings().await?.sandbox { + return Ok((spec, None, None)); + } + Err(ProcessSpecError { + code: "isolation_unavailable", + reason: WINDOWS_SANDBOX_UNAVAILABLE.into(), + }) + } + /// Reads the configured exec shell for this invocation without reloading + /// the plugin. Explicitly constructed platforms keep their supplied shell. + pub async fn exec_shell(&self) -> ShellStatus { + let mut resolved = self.shell.lock().await; + if let Some((storage, root, relative)) = &self.shell_file { + let config = read_config(storage, *root, relative).await; + if config != resolved.config + || matches!( + resolved.status, + ShellStatus::Unavailable { + code: EXEC_SHELL_UNAVAILABLE, + .. + } + ) + { + let status = resolve_shell(config.clone(), &self.env).await; + *resolved = ResolvedShell { config, status }; + } + } + resolved.status.clone() + } + + /// The sandbox backend a new process would use. #[cfg(windows)] pub fn sandbox_backend(&self) -> SandboxBackend { SandboxBackend::Unavailable { @@ -453,15 +1065,13 @@ impl HostPlatform { } } - /// The sandbox backend a new process would use. macOS always has - /// `sandbox-exec`. + /// The sandbox backend a new process would use. #[cfg(target_os = "macos")] pub fn sandbox_backend(&self) -> SandboxBackend { SandboxBackend::Available } - /// The sandbox backend a new process would use: the same bubblewrap - /// preparation resolves from the captured `PATH`. + /// The sandbox backend a new process would use. #[cfg(all(unix, not(target_os = "macos")))] pub fn sandbox_backend(&self) -> SandboxBackend { match isolation::bubblewrap(&self.env) { @@ -472,70 +1082,835 @@ impl HostPlatform { } } - #[cfg(windows)] - pub(crate) async fn prepare_isolated_process( - &self, - spec: ProcessSpec, - _workspaces: &[PathBuf], - _output_dir: Option<&Path>, - ) -> Result<(ProcessSpec, Option, Option), ProcessSpecError> - { - if !self.execution_settings().await?.sandbox { - return Ok((spec, None, None)); + fn exec_root_path(&self) -> PathBuf { + let root = self.home.join(".dim").join("exec"); + std::fs::canonicalize(&root).unwrap_or(root) + } + + /// The directory the persistent shell owns: `/.dim/exec`. + pub fn exec_root(&self) -> Result { + self.exec_root_path() + .to_str() + .map(str::to_owned) + .ok_or_else(|| HostPlatformError::Invalid("the exec root path is not UTF-8".into())) + } + /// The process facts a consumer needs, in one call. Resolves the exec + /// shell; in-process callers that need only captured facts read the fields. + pub async fn info(&self) -> Result { + let home = self + .home + .to_str() + .ok_or_else(|| HostPlatformError::Invalid("the user home path is not UTF-8".into()))?; + let exec_root = self.exec_root_path(); + let exec_root = exec_root + .to_str() + .ok_or_else(|| HostPlatformError::Invalid("the exec root path is not UTF-8".into()))?; + let mut platform_roots = Vec::with_capacity(self.platform_roots.len()); + for root in &self.platform_roots { + platform_roots.push( + root.to_str() + .ok_or_else(|| { + HostPlatformError::Invalid("a platform root path is not UTF-8".into()) + })? + .to_owned(), + ); } - Err(ProcessSpecError { - code: "isolation_unavailable", - reason: WINDOWS_SANDBOX_UNAVAILABLE.into(), + Ok(HostInfo { + os: self.os, + arch: self.arch.clone(), + home: home.to_owned(), + timezone: self.timezone.clone(), + exec_root: exec_root.to_owned(), + platform_roots, + backend: self.sandbox_backend(), + exec_shell: self.exec_shell().await, }) } -} - -const RUNTIME_BIN_ENV_KEYS: [&str; 5] = [ - "DIMCODE_CLI_BIN", - "DIMCODE_UV_BIN", - "DIMCODE_PYTHON_BIN", - "DIMCODE_NODE_BIN", - "DIMCODE_BUNDLED_GIT_BIN", -]; -const PLUGIN_BIN_DIRS_ENV: &str = "DIMCODE_PLUGIN_BIN_DIRS"; -impl HostPlatform { - /// 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 - /// must nest. - pub fn installed_toolchains(&self) -> Vec { - let Some(source) = self.toolchain.as_ref() else { - return Vec::new(); - }; - let reply = match source.list() { - Ok(reply) => reply, - Err(error) => { - tracing::warn!(%error, "the installed runtimes cannot cross as data"); - return Vec::new(); + fn process_error(error: ProcessSpecError) -> HostPlatformError { + match error.code { + "task_exists" => HostPlatformError::TaskExists, + "task_ended" => HostPlatformError::TaskEnded, + "cancelled" => HostPlatformError::Cancelled, + "io" => HostPlatformError::Io(error.reason), + "isolation_config_invalid" => HostPlatformError::IsolationConfigInvalid(error.reason), + "isolation_unavailable" => HostPlatformError::IsolationUnavailable(error.reason), + "exec_shell_config_invalid" | EXEC_SHELL_CONFIG_INVALID => { + HostPlatformError::ExecShellConfigInvalid(error.reason) } - }; - reply - .toolchains - .into_iter() - .map(|toolchain| InstalledToolchain { - bin: toolchain.bin.into(), - root: toolchain.root.into(), - }) - .filter(|toolchain| toolchain.bin.starts_with(&toolchain.root)) - .collect() + "exec_shell_unavailable" | EXEC_SHELL_UNAVAILABLE => { + HostPlatformError::ExecShellUnavailable(error.reason) + } + "exec_shell_cwd_unsupported" | "EXEC_SHELL_CWD_UNSUPPORTED" => { + HostPlatformError::ExecShellCwdUnsupported(error.reason) + } + "cwd_not_found" => HostPlatformError::CwdNotFound(error.reason), + "exec_shell_path_mapping_failed" | "EXEC_SHELL_PATH_MAPPING_FAILED" => { + HostPlatformError::ExecShellPathMappingFailed(error.reason) + } + "invalid_request" | "exec_invalid_request" => { + HostPlatformError::Invalid(format!("{}: {}", error.code, error.reason)) + } + _ => HostPlatformError::Failed(format!("{}: {}", error.code, error.reason)), + } } - /// The PATH a child gets: the host's embedding `directories` first, then - /// `base` (the PATH it would get with no installed runtime), then the - /// toolchain bin directories not already in either. `None` when nothing is - /// appended, so the caller leaves the child's PATH as it is. `base` may be - /// a login shell's literal `$PATH`, which is only expanded when the - /// command runs. - pub fn child_path(&self, directories: &[String], base: &OsStr) -> Option { - let windows = self.os == Os::Windows; - let bins: Vec = self - .installed_toolchains() + /// Starts a command on this node and returns the task id and output path. + /// Requires the plugin-built owner. + pub async fn spawn(&self, request: SpawnRequest) -> Result { + if request.task_id.is_empty() + || request.task_id.contains(['/', '\\', '\0', ':']) + || matches!(request.task_id.as_str(), "." | "..") + { + return Err(HostPlatformError::Invalid( + "taskId must be a single filename component".into(), + )); + } + let cwd = PathBuf::from(&request.cwd); + let workspace = PathBuf::from(&request.workspace); + let output_dir = PathBuf::from(&request.output_dir); + let roots: Vec = request.roots.iter().map(PathBuf::from).collect(); + if !cwd.is_absolute() + || !workspace.is_absolute() + || !output_dir.is_absolute() + || roots.iter().any(|root| !root.is_absolute()) + { + return Err(HostPlatformError::Invalid( + "execution paths must be absolute".into(), + )); + } + if !tokio::fs::metadata(&cwd) + .await + .is_ok_and(|metadata| metadata.is_dir()) + { + return Err(HostPlatformError::Invalid( + "working directory not found".into(), + )); + } + let (spec, _) = self + .build_process_spec(&request.command, &cwd) + .await + .map_err(Self::process_error)?; + let output_path = output_dir.join(format!("{}.log", request.task_id)); + self.start_command( + &request.task_id, + spec, + &roots, + &output_dir, + request.timeout_ms, + ) + .await + .map_err(Self::process_error)?; + Ok(SpawnReply { + task_id: request.task_id, + output_path: output_path.to_string_lossy().into_owned(), + }) + } + + /// Waits for a task's terminal record. `timeoutMs` stops the wait and + /// answers `running`; it never kills the task. `cancelled` ends only the + /// wait. Use `kill` to stop the task. + pub async fn wait( + &self, + request: WaitRequest, + cancelled: crate::host::CancelledFn, + ) -> Result { + let task = self + .task(&request.task_id) + .ok_or(HostPlatformError::TaskUnknown)?; + tokio::select! { + biased; + _ = cancelled() => Err(HostPlatformError::Cancelled), + value = task.wait(request.timeout_ms) => Ok(value), + } + } + + /// Kills a task's process tree. + pub async fn kill(&self, request: TaskRequest) -> Result<(), HostPlatformError> { + let task = self + .task(&request.task_id) + .ok_or(HostPlatformError::TaskUnknown)?; + if task.is_terminal() { + return Ok(()); + } + if !task.is_running() { + return Err(HostPlatformError::TaskRunning); + } + match &task.kind { + TaskKind::Command(command) => { + command.kill.cancel(); + let terminal = task.wait(None).await; + match terminal.failure { + Some(TaskFailure::TerminateFailed { message }) => { + Err(HostPlatformError::Failed(message)) + } + _ => Ok(()), + } + } + TaskKind::Shell(shell) => { + shell.terminate(); + let terminal = task.wait(None).await; + match terminal.failure { + Some(TaskFailure::TerminateFailed { message }) => { + Err(HostPlatformError::Failed(message)) + } + _ => Ok(()), + } + } + TaskKind::ShellCommand(command) => { + if !command.shell.is_active(&task) { + return Ok(()); + } + command + .shell + .write(b"\x03") + .await + .map_err(|error| HostPlatformError::Io(error.to_string())) + } + TaskKind::Job(job) => { + if !self.stopping.lock().unwrap().insert(task.id.clone()) { + return Err(HostPlatformError::TaskRunning); + } + let mut pid = job.pid.subscribe(); + let mut current = *pid.borrow_and_update(); + if current.is_none() { + let _ = tokio::time::timeout(Duration::from_secs(2), pid.changed()).await; + current = *pid.borrow_and_update(); + } + if task.is_terminal() { + self.stopping.lock().unwrap().remove(&task.id); + return Ok(()); + } + let Some(pid) = current else { + let record = task.clone(); + let job = job.clone(); + let shutdown = self.command_shutdown.clone(); + let workers = self.command_workers.clone(); + let stopping = self.stopping.clone(); + self.command_workers.spawn(async move { + let mut pid = job.pid.subscribe(); + let mut changed = record.changed.subscribe(); + loop { + if record.is_terminal() { + stopping.lock().unwrap().remove(&record.id); + return; + } + let current = *pid.borrow_and_update(); + if let Some(pid) = current { + if record.is_terminal() { + stopping.lock().unwrap().remove(&record.id); + return; + } + let tree = job_tree(pid); + if kill_job(pid, tree.clone()).await.is_err() { + let shutdown = shutdown.clone(); + let id = record.id.clone(); + let stopping = stopping.clone(); + workers.spawn(async move { + observe_job_release(record, job, pid, shutdown, tree).await; + stopping.lock().unwrap().remove(&id); + }); + return; + } + record.finish(Terminal { + status: TaskStatus::Cancelled, + exit_code: None, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: None, + output: job.output_record().0, + note: None, + }); + stopping.lock().unwrap().remove(&record.id); + return; + } + tokio::select! { + biased; + _ = shutdown.cancelled() => { + stopping.lock().unwrap().remove(&record.id); + return; + } + changed = changed.changed() => { + if changed.is_err() { + stopping.lock().unwrap().remove(&record.id); + return; + } + } + changed = pid.changed() => { + if changed.is_err() { + stopping.lock().unwrap().remove(&record.id); + return; + } + } + } + } + }); + return Err(HostPlatformError::TaskRunning); + }; + let tree = job_tree(pid); + if let Err(error) = kill_job(pid, tree.clone()).await { + let record = task.clone(); + let job = job.clone(); + let shutdown = self.command_shutdown.clone(); + let stopping = self.stopping.clone(); + let id = task.id.clone(); + self.command_workers.spawn(async move { + observe_job_release(record, job, pid, shutdown, tree).await; + stopping.lock().unwrap().remove(&id); + }); + return Err(HostPlatformError::Failed(error.to_string())); + } + task.finish(Terminal { + status: TaskStatus::Cancelled, + exit_code: None, + signal: None, + duration_ms: task.started.elapsed().as_millis() as u64, + failure: None, + output: job.output_record().0, + note: None, + }); + self.stopping.lock().unwrap().remove(&task.id); + Ok(()) + } + } + } + + /// Releases an ended task's record. + pub async fn settle(&self, request: TaskRequest) -> Result<(), HostPlatformError> { + let Some(task) = self.task(&request.task_id) else { + return Ok(()); + }; + if !task.is_terminal() { + return Err(HostPlatformError::TaskRunning); + } + let mut commands = self.commands.lock().unwrap(); + commands.remove(&request.task_id); + if let TaskKind::Shell(shell) = &task.kind { + shell.sweep(task.terminal()); + } + Ok(()) + } + + pub(crate) fn task(&self, id: &str) -> Option> { + self.commands.lock().unwrap().get(id).cloned() + } + + pub(crate) fn shell_task(&self, id: &str) -> Option> { + match &self.task(id)?.kind { + TaskKind::Shell(shell) => Some(shell.clone()), + _ => None, + } + } + + pub(crate) fn shell_command(&self, id: &str) -> Option> { + match &self.task(id)?.kind { + TaskKind::ShellCommand(command) => Some(command.clone()), + _ => None, + } + } + + pub(crate) fn job_marker(&self, id: &str) -> Option { + match &self.task(id)?.kind { + TaskKind::Job(job) => Some(job.end_marker.clone()), + _ => None, + } + } + + pub(crate) fn job_completion( + &self, + id: &str, + ) -> Option<(std::path::PathBuf, std::path::PathBuf)> { + match &self.task(id)?.kind { + TaskKind::Job(job) => job.completion.clone(), + _ => None, + } + } + + /// Starts a persistent PTY shell on this node and returns the task id. + /// Requires the plugin-built owner. + pub async fn shell(&self, request: ShellRequest) -> Result { + if request.task_id.is_empty() + || request.task_id.contains(['/', '\\', '\0', ':']) + || matches!(request.task_id.as_str(), "." | "..") + { + return Err(HostPlatformError::Invalid( + "taskId must be a single filename component".into(), + )); + } + let cwd = PathBuf::from(&request.cwd); + let workspace = PathBuf::from(&request.workspace); + let output_dir = PathBuf::from(&request.output_dir); + let roots: Vec = request.roots.iter().map(PathBuf::from).collect(); + if !cwd.is_absolute() + || !workspace.is_absolute() + || !output_dir.is_absolute() + || roots.iter().any(|root| !root.is_absolute()) + { + return Err(HostPlatformError::Invalid( + "execution paths must be absolute".into(), + )); + } + if !tokio::fs::metadata(&cwd) + .await + .is_ok_and(|metadata| metadata.is_dir()) + { + return Err(HostPlatformError::Invalid( + "working directory not found".into(), + )); + } + tokio::fs::create_dir_all(&output_dir) + .await + .map_err(|error| HostPlatformError::Io(error.to_string()))?; + let (shell, _) = self + .start_shell( + &request.task_id, + &cwd, + &roots, + &output_dir, + PtySize { + cols: request.cols, + rows: request.rows, + }, + ) + .await + .map_err(Self::process_error)?; + Ok(SpawnReply { + task_id: request.task_id, + output_path: shell.output_path().to_string_lossy().into_owned(), + }) + } + + /// Writes bytes to a shell task. + pub async fn write(&self, request: ShellWrite) -> Result<(), HostPlatformError> { + let task = self + .task(&request.task_id) + .ok_or(HostPlatformError::TaskUnknown)?; + if task.is_terminal() { + return Err(HostPlatformError::TaskEnded); + } + let shell = match &task.kind { + TaskKind::Shell(shell) => shell.clone(), + _ => return Err(HostPlatformError::TaskUnknown), + }; + if request.command.is_some() && request.job.is_some() { + return Err(HostPlatformError::Invalid( + "a shell write cannot start a command and a job together".into(), + )); + } + let bytes = STANDARD + .decode(request.data) + .map_err(|error| HostPlatformError::Invalid(error.to_string()))?; + let command = if let Some(start) = request.command { + if !valid_shell_marker(&start.start_marker) || !valid_shell_marker(&start.end_marker) { + return Err(HostPlatformError::Invalid( + "shell command markers must be __DIM_START_<8 hex>_<8 hex>__ and __DIM_END_<8 hex>_<8 hex>__".into(), + )); + } + if start.task_id.is_empty() + || start.task_id.contains(['/', '\\', '\0', ':']) + || matches!(start.task_id.as_str(), "." | "..") + { + return Err(HostPlatformError::Invalid( + "command taskId must be a single filename component".into(), + )); + } + let directory = shell + .output_path() + .parent() + .unwrap_or_else(|| Path::new(".")); + let command_path = directory.join(format!("{}.log", start.task_id)); + if std::fs::symlink_metadata(&command_path).is_ok() { + return Err(HostPlatformError::TaskExists); + } + let command = Arc::new(shell::ShellCommand::new( + shell.clone(), + start.start_marker, + start.end_marker, + command_path, + )); + let record = TaskRecord::new( + start.task_id.clone(), + TaskKind::ShellCommand(command.clone()), + ); + { + let mut commands = self.commands.lock().unwrap(); + if commands.contains_key(&start.task_id) { + return Err(HostPlatformError::TaskExists); + } + commands.insert(start.task_id.clone(), record.clone()); + if !shell.reserve_active_command(&record) { + commands.remove(&start.task_id); + return Err(HostPlatformError::TaskRunning); + } + } + shell.add_child(&record); + Some((start.task_id, record)) + } else { + None + }; + let job = if let Some(start) = request.job { + if !valid_shell_marker(&start.end_marker) || !start.end_marker.starts_with("__DIM_END_") + { + return Err(HostPlatformError::Invalid( + "shell job end marker must be __DIM_END_<8 hex>_<8 hex>__".into(), + )); + } + if start.task_id.is_empty() + || start.task_id.contains(['/', '\\', '\0', ':']) + || matches!(start.task_id.as_str(), "." | "..") + { + return Err(HostPlatformError::Invalid( + "job taskId must be a single filename component".into(), + )); + } + let directory = shell + .output_path() + .parent() + .unwrap_or_else(|| Path::new(".")) + .to_path_buf(); + let output_path = PathBuf::from(&start.output_path); + if output_path.parent().is_none_or(|parent| !parent.is_dir()) { + return Err(HostPlatformError::Invalid( + "job outputPath parent must exist".into(), + )); + } + if output_path.file_stem().and_then(|stem| stem.to_str()) + != Some(start.task_id.as_str()) + { + return Err(HostPlatformError::Invalid( + "job outputPath stem must equal its taskId".into(), + )); + } + if !output_path.is_absolute() + || output_path + .components() + .any(|component| matches!(component, Component::CurDir | Component::ParentDir)) + || !output_path.starts_with(&directory) + { + return Err(HostPlatformError::Invalid( + "job outputPath must be absolute and inside the shell output directory".into(), + )); + } + let completion = shell.pwsh().then(|| { + ( + directory.join(format!("{}.result", start.task_id)), + directory.join(format!("{}.err", start.task_id)), + ) + }); + if std::fs::symlink_metadata(&output_path).is_ok() + || completion.as_ref().is_some_and(|(result, error)| { + std::fs::symlink_metadata(result).is_ok() + || std::fs::symlink_metadata(error).is_ok() + }) + { + return Err(HostPlatformError::TaskExists); + } + let job = Arc::new(shell::ShellJob { + shell: Arc::downgrade(&shell), + pid: watch::channel(None).0, + end_marker: start.end_marker, + output_path, + completion, + }); + let record = TaskRecord::new(start.task_id.clone(), TaskKind::Job(job.clone())); + { + let mut commands = self.commands.lock().unwrap(); + if commands.contains_key(&start.task_id) { + return Err(HostPlatformError::TaskExists); + } + commands.insert(start.task_id.clone(), record.clone()); + } + shell.add_child(&record); + Some((start.task_id, record)) + } else { + None + }; + if let Err(error) = shell.write(&bytes).await { + if let Some((id, _)) = &command { + self.commands.lock().unwrap().remove(id); + } + if let Some((id, _)) = &job { + self.commands.lock().unwrap().remove(id); + } + if command.is_some() { + shell.set_active_command(None); + } + return Err(HostPlatformError::Io(error.to_string())); + } + if let Some((_, record)) = &command { + record.start(); + } + if let Some((_, record)) = &job { + record.start(); + if let Some((result_path, _)) = self.job_completion(&record.id) { + let record = record.clone(); + self.command_workers.spawn(async move { + loop { + if record.is_terminal() { + return; + } + tokio::time::sleep(Duration::from_millis(200)).await; + if record.is_terminal() { + return; + } + let Ok(text) = tokio::fs::read_to_string(&result_path).await else { + continue; + }; + let TaskKind::Job(job) = &record.kind else { + return; + }; + if let Some(code) = shell::completion_code(&text, &job.end_marker) { + record.finish(shell::job_completion_terminal(&record, job, &code)); + return; + } + } + }); + } + } + Ok(()) + } + + /// Resizes a shell task's PTY. + pub async fn resize(&self, request: ShellResize) -> Result<(), HostPlatformError> { + let task = self + .task(&request.task_id) + .ok_or(HostPlatformError::TaskUnknown)?; + if task.is_terminal() { + return Err(HostPlatformError::TaskEnded); + } + let shell = match &task.kind { + TaskKind::Shell(shell) => shell.clone(), + _ => return Err(HostPlatformError::TaskUnknown), + }; + shell + .resize(PtySize { + cols: request.cols, + rows: request.rows, + }) + .await + .map_err(|error| HostPlatformError::Io(error.to_string())) + } + + /// Reads a page of a task's captured output. + pub async fn output( + &self, + request: OutputRequest, + ) -> Result { + let limit = request.limit.unwrap_or(64 * 1024); + if limit == 0 { + return Err(HostPlatformError::Invalid( + "output limit must be positive".into(), + )); + } + let limit = limit.min(4 * 1024 * 1024) as usize; + if let Some(shell) = self.shell_task(&request.task_id) { + return shell + .page(request.cursor, limit) + .map_err(HostPlatformError::from); + } + if let Some(command) = self.shell_command(&request.task_id) { + return command + .page(request.cursor.unwrap_or(0), limit) + .map_err(HostPlatformError::from); + } + if let Some(page) = self + .task(&request.task_id) + .and_then(|task| task.terminal_page(request.cursor.unwrap_or(0), limit)) + { + return Ok(OutputPageReply { + text: page.text, + bytes: page.bytes, + total_bytes: page.total_bytes.max(page.bytes), + next_cursor: page.next_cursor, + truncated: page.truncated, + retained_from: 0, + reset: None, + }); + } + if let Some(task) = self.task(&request.task_id) + && let TaskKind::Job(job) = &task.kind + { + let page = match self + .retained_output_page( + std::path::Path::new(&job.output_path), + request.cursor.unwrap_or(0), + limit, + ) + .await + { + Ok(page) => page, + Err(crate::workspace_tools::background::OutputPageError::Unavailable) => { + return Ok(OutputPageReply { + text: String::new(), + bytes: 0, + total_bytes: 0, + next_cursor: None, + truncated: false, + retained_from: 0, + reset: None, + }); + } + Err(error) => return Err(HostPlatformError::from(error)), + }; + return Ok(OutputPageReply { + text: page.text, + bytes: page.bytes, + total_bytes: page.total_bytes.max(page.bytes), + next_cursor: page.next_cursor, + truncated: false, + retained_from: 0, + reset: None, + }); + } + let task = self.command_task(&request.task_id)?; + let page = task + .page(request.cursor.unwrap_or(0), limit) + .await + .map_err(HostPlatformError::from)?; + Ok(OutputPageReply { + text: page.text, + bytes: page.bytes, + total_bytes: page.total_bytes.max(page.bytes), + next_cursor: page.next_cursor, + truncated: page.truncated, + retained_from: 0, + reset: None, + }) + } + + /// The private ShellSession transport: the lossless owner event page. + /// Not a public data-face operation and never exposed through TypeScript. + pub(crate) async fn shell_events( + &self, + request: ShellEventRequest, + ) -> Result { + let shell = self + .shell_task(&request.task_id) + .ok_or(HostPlatformError::TaskUnknown)?; + let page = shell + .events_page(request.cursor, Some(request.wait_ms), request.limit) + .await; + Ok(ShellEventPage { + events: page.events, + next_cursor: page.next_cursor, + }) + } + + /// Writes the captured output to the task's log file and returns its path. + pub async fn retain_output( + &self, + request: TaskRequest, + ) -> Result { + if let Some(shell) = self.shell_task(&request.task_id) { + return Ok(OutputPathReply { + output_path: shell.output_path().to_string_lossy().into_owned(), + }); + } + if let Some(command) = self.shell_command(&request.task_id) { + return Ok(OutputPathReply { + output_path: command.output_path().to_string_lossy().into_owned(), + }); + } + let output_path = self.retain_output_by_id(&request.task_id).await?; + Ok(OutputPathReply { output_path }) + } + + /// Reads the bounded live tail of a task. + pub async fn tail( + &self, + request: TaskRequest, + ) -> Result { + if let Some(shell) = self.shell_task(&request.task_id) { + return Ok(shell.tail()); + } + if let Some(command) = self.shell_command(&request.task_id) { + return Ok(command.tail()); + } + if let Some(task) = self.task(&request.task_id) + && let TaskKind::Job(job) = &task.kind + { + let (record, _) = job.output_record(); + return Ok(crate::workspace_tools::exec::OutputTail { + text: record.preview, + total_bytes: record.bytes, + truncated: record.truncated, + }); + } + if let Some(terminal) = self.task(&request.task_id).and_then(|task| task.terminal()) { + let text = match &terminal.output.text { + Some(text) => crate::host_platform::output::truncate_preview(text), + None => terminal.output.preview.clone(), + }; + return Ok(crate::workspace_tools::exec::OutputTail { + text, + total_bytes: terminal.output.bytes, + truncated: terminal.output.truncated, + }); + } + self.tail_by_id(&request.task_id).await.map_err(Into::into) + } + /// 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 { + match self.exec_shell().await { + ShellStatus::Available(runtime) => match runtime.edition { + ShellEdition::Bash + | ShellEdition::Zsh + | ShellEdition::Pwsh + | ShellEdition::WindowsPowershell => ShellStatus::Available(runtime), + _ => self.fallback_persistent_shell(), + }, + ShellStatus::Unavailable { .. } => self.fallback_persistent_shell(), + } + } +} + +const RUNTIME_BIN_ENV_KEYS: [&str; 5] = [ + "DIMCODE_CLI_BIN", + "DIMCODE_UV_BIN", + "DIMCODE_PYTHON_BIN", + "DIMCODE_NODE_BIN", + "DIMCODE_BUNDLED_GIT_BIN", +]; +const PLUGIN_BIN_DIRS_ENV: &str = "DIMCODE_PLUGIN_BIN_DIRS"; + +impl HostPlatform { + /// 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 + /// must nest. + pub fn installed_toolchains(&self) -> Vec { + let Some(source) = self.toolchain.as_ref() else { + return Vec::new(); + }; + let reply = match source.list() { + Ok(reply) => reply, + Err(error) => { + tracing::warn!(%error, "the installed runtimes cannot cross as data"); + return Vec::new(); + } + }; + reply + .toolchains + .into_iter() + .map(|toolchain| InstalledToolchain { + bin: toolchain.bin.into(), + root: toolchain.root.into(), + }) + .filter(|toolchain| toolchain.bin.starts_with(&toolchain.root)) + .collect() + } + + /// The PATH a child gets: the host's embedding `directories` first, then + /// `base` (the PATH it would get with no installed runtime), then the + /// toolchain bin directories not already in either. `None` when nothing is + /// appended, so the caller leaves the child's PATH as it is. `base` may be + /// a login shell's literal `$PATH`, which is only expanded when the + /// command runs. + pub fn child_path_process(&self, directories: &[String], base: &OsStr) -> Option { + let windows = self.os == Os::Windows; + let bins: Vec = self + .installed_toolchains() .into_iter() .map(|toolchain| toolchain.bin) .collect(); @@ -585,7 +1960,7 @@ impl HostPlatform { command, &env, self, - &shell.executable_path, + Path::new(&shell.executable_path), shell.edition, cwd, &toolchain, @@ -606,7 +1981,7 @@ impl HostPlatform { }; Ok(( ProcessSpec { - executable: shell.executable_path.clone(), + executable: PathBuf::from(&shell.executable_path), args: args .iter() .map(OsString::from) @@ -875,7 +2250,9 @@ fn git_bash_cygpath(bash: &Path) -> Option { /// Runs a product helper and returns its stdout. async fn capture(platform: &HostPlatform, spec: ProcessSpec) -> Result { - let mut tree = platform.spawn(spec).map_err(|error| error.to_string())?; + let mut tree = platform + .spawn_tree(spec) + .map_err(|error| error.to_string())?; let mut stdout = tree.stdout(); drop(tree.stderr()); let mut bytes = vec![]; @@ -963,7 +2340,7 @@ impl ProcessTree { impl Drop for ProcessTree { fn drop(&mut self) { if !self.terminated && !self.released() { - native::signal(self.pid, libc::SIGKILL); + native::kill_tree(self.pid); } } } @@ -1062,7 +2439,20 @@ impl DynPlugin for HostPlatformPlugin { 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(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_as::(platform)?; Ok(Effect::Done) }) } @@ -1131,17 +2521,17 @@ pub async fn resolve_shell( .map(|(index, source)| (&detected.shells[index], source)), }; match selected { - Some((shell, source)) => ShellStatus::Available(ExecShellRuntime { - executable_path: shell.path.clone(), - edition: shell.edition, + Some((shell, source)) => available_shell( + shell.path.clone(), + shell.edition, source, - output_encoding: match shell.edition { + match shell.edition { ShellEdition::GitBash | ShellEdition::WindowsPowershell | ShellEdition::Cmd => { OutputEncoding::Unknown } _ => OutputEncoding::Utf8, }, - }), + ), None => ShellStatus::Unavailable { code: EXEC_SHELL_UNAVAILABLE, reason: match explicit { @@ -1383,6 +2773,33 @@ mod unix { unsafe { libc::kill(-(pid as libc::pid_t), signal) }; } + /// Kills every descendant that still names `pid` as an ancestor, then the + /// root group. A child that started its own session is not in the root + /// group, so the `/proc` walk is the part that reaches it. + pub fn kill_tree(pid: u32) { + fn children(pid: u32) -> Vec { + let Ok(text) = std::fs::read_to_string(format!("/proc/{pid}/task/{pid}/children")) + else { + return Vec::new(); + }; + text.split_whitespace() + .filter_map(|value| value.parse().ok()) + .collect() + } + let mut pending = children(pid); + let mut seen = Vec::new(); + while let Some(child) = pending.pop() { + if seen.contains(&child) { + continue; + } + seen.push(child); + pending.extend(children(child)); + unsafe { libc::kill(-(child as libc::pid_t), libc::SIGKILL) }; + unsafe { libc::kill(child as libc::pid_t, libc::SIGKILL) }; + } + unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGKILL) }; + } + /// True once the root is reaped and the group has no member left. async fn group_gone(tree: &mut ProcessTree, pid: u32, within: Duration) -> bool { let deadline = tokio::time::Instant::now() + within; @@ -1433,7 +2850,10 @@ mod windows { use super::*; use std::{os::windows::ffi::OsStringExt, time::Duration}; use windows_sys::Win32::{ - Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}, + Foundation::{ + CloseHandle, ERROR_INVALID_PARAMETER, ERROR_NO_MORE_FILES, GetLastError, HANDLE, + INVALID_HANDLE_VALUE, STILL_ACTIVE, + }, System::{ Com::CoTaskMemFree, Diagnostics::ToolHelp::{ @@ -1447,16 +2867,84 @@ mod windows { QueryInformationJobObject, SetInformationJobObject, TerminateJobObject, }, Threading::{ - CREATE_NO_WINDOW, CREATE_SUSPENDED, OpenProcess, OpenThread, PROCESS_SET_QUOTA, - PROCESS_TERMINATE, ResumeThread, THREAD_SUSPEND_RESUME, TerminateProcess, + CREATE_NO_WINDOW, CREATE_SUSPENDED, GetExitCodeProcess, OpenProcess, OpenThread, + PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_QUOTA, PROCESS_TERMINATE, + ResumeThread, THREAD_SUSPEND_RESUME, TerminateProcess, }, }, UI::Shell::{FOLDERID_Profile, SHGetKnownFolderPath}, }; - const SHELL_PROBE_TIMEOUT: Duration = Duration::from_millis(1_500); - const SHELL_PROBE_CONCURRENCY: usize = 4; - const TERMINATE_CONFIRM: Duration = Duration::from_secs(5); + pub fn kill_tree(pid: u32) { + let _ = terminate_tree(pid); + } + + pub fn process_alive(pid: u32) -> bool { + // SAFETY: the process handle is closed below. + unsafe { + let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if process.is_null() { + return GetLastError() != ERROR_INVALID_PARAMETER; + } + let mut code = 0u32; + let ok = GetExitCodeProcess(process, &mut code); + CloseHandle(process); + ok == 0 || code == STILL_ACTIVE as u32 + } + } + + pub fn tree_pids(pid: u32) -> Option> { + // SAFETY: snapshot handle is closed below; entries are sized. + let parents = unsafe { + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if snapshot == INVALID_HANDLE_VALUE { + return None; + } + let mut entry: PROCESSENTRY32W = std::mem::zeroed(); + entry.dwSize = std::mem::size_of::() as u32; + let mut parents = Vec::new(); + if Process32FirstW(snapshot, &mut entry) == 0 { + let error = GetLastError(); + CloseHandle(snapshot); + let _ = error; + return None; + } + loop { + parents.push((entry.th32ProcessID, entry.th32ParentProcessID)); + if Process32NextW(snapshot, &mut entry) == 0 { + if GetLastError() != ERROR_NO_MORE_FILES { + CloseHandle(snapshot); + return None; + } + break; + } + } + CloseHandle(snapshot); + parents + }; + let mut tree = vec![pid]; + let mut index = 0; + while index < tree.len() { + let parent = tree[index]; + tree.extend( + parents + .iter() + .filter(|(child, of)| *of == parent && !tree.contains(child)) + .map(|(child, _)| *child) + .collect::>(), + ); + index += 1; + } + Some(tree) + } + + pub fn tree_alive(pid: u32) -> bool { + tree_pids(pid).is_none_or(|tree| tree.into_iter().any(process_alive)) + } + + const SHELL_PROBE_TIMEOUT: Duration = Duration::from_millis(1_500); + const SHELL_PROBE_CONCURRENCY: usize = 4; + const TERMINATE_CONFIRM: Duration = Duration::from_secs(5); pub fn home(env: &[(OsString, OsString)]) -> io::Result { if let Some(home) = env_var(env, "USERPROFILE").filter(|home| !home.is_empty()) { @@ -2070,7 +3558,7 @@ impl PtyProcessTree { self.terminating = true; #[cfg(unix)] { - native::signal(self.pid, libc::SIGKILL); + native::kill_tree(self.pid); let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2); while tokio::time::Instant::now() < deadline { match self.try_wait()? { @@ -2104,7 +3592,7 @@ impl PtyProcessTree { impl Drop for PtyProcessTree { fn drop(&mut self) { if !self.terminated && !self.released() { - native::signal(self.pid, libc::SIGKILL); + native::kill_tree(self.pid); } } } @@ -2132,31 +3620,93 @@ pub fn terminate_job(pid: u32) -> io::Result<()> { native::terminate_tree(pid) } -pub(crate) async fn stop_job(pid: u32) -> io::Result<()> { - terminate_job(pid)?; - #[cfg(unix)] - { - match wait_job_exit(pid).await { - Err(error) if error.kind() == io::ErrorKind::TimedOut => kill_job(pid).await, - result => result, +async fn observe_job_release( + record: Arc, + job: Arc, + pid: u32, + shutdown: CancellationToken, + tree: Option>, +) { + loop { + if record.is_terminal() { + return; + } + if job_released(pid, tree.as_deref()).await { + record.finish(Terminal { + status: TaskStatus::Cancelled, + exit_code: None, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: Some(TaskFailure::TerminateFailed { + message: "job release was not confirmed at stop; it ended later".into(), + }), + output: job.output_record().0, + note: None, + }); + return; + } + tokio::select! { + _ = shutdown.cancelled() => return, + _ = tokio::time::sleep(Duration::from_millis(200)) => {} } } - #[cfg(windows)] - Ok(()) } /// Kills a background job that outlived its shell and confirms it is gone: /// the process group it leads on POSIX, the process tree under it on /// Windows. -pub async fn kill_job(pid: u32) -> io::Result<()> { +pub async fn kill_job(pid: u32, tree: Option>) -> io::Result<()> { #[cfg(unix)] { - // SAFETY: plain syscall on the addressed group. - unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGKILL) }; + let _ = tree; + native::kill_tree(pid); wait_job_exit(pid).await } #[cfg(windows)] - native::terminate_tree(pid) + { + native::terminate_tree(pid)?; + let Some(tree) = tree else { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "job tree could not be enumerated", + )); + }; + let deadline = tokio::time::Instant::now() + Duration::from_secs(2); + while tree.iter().copied().any(native::process_alive) { + if tokio::time::Instant::now() >= deadline { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "job processes are still alive", + )); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + Ok(()) + } +} + +pub(crate) fn job_tree(pid: u32) -> Option> { + #[cfg(unix)] + { + let _ = pid; + None + } + #[cfg(windows)] + { + native::tree_pids(pid) + } +} + +async fn job_released(pid: u32, tree: Option<&[u32]>) -> bool { + #[cfg(unix)] + { + let _ = tree; + wait_job_exit(pid).await.is_ok() + } + #[cfg(windows)] + { + tree.is_some_and(|tree| tree.iter().copied().all(|pid| !native::process_alive(pid))) + } } #[cfg(unix)] @@ -2180,22 +3730,27 @@ async fn wait_job_exit(pid: u32) -> io::Result<()> { } } -impl HostPlatform { - /// 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 { - match self.exec_shell().await { - ShellStatus::Available(runtime) => match runtime.edition { - ShellEdition::Bash - | ShellEdition::Zsh - | ShellEdition::Pwsh - | ShellEdition::WindowsPowershell => ShellStatus::Available(runtime), - _ => self.fallback_persistent_shell(), - }, - ShellStatus::Unavailable { .. } => self.fallback_persistent_shell(), - } +fn available_shell( + path: PathBuf, + edition: ShellEdition, + source: ShellSource, + output_encoding: OutputEncoding, +) -> ShellStatus { + match path.to_str() { + Some(path) => ShellStatus::Available(ExecShellRuntime { + executable_path: path.to_owned(), + edition, + source, + output_encoding, + }), + None => ShellStatus::Unavailable { + code: EXEC_SHELL_UNAVAILABLE, + reason: "The shell path is not UTF-8".into(), + }, } +} +impl HostPlatform { fn fallback_persistent_shell(&self) -> ShellStatus { if cfg!(windows) { for name in ["pwsh.exe", "powershell.exe"] { @@ -2205,15 +3760,15 @@ impl HostPlatform { } else { ShellEdition::WindowsPowershell }; - return ShellStatus::Available(ExecShellRuntime { - executable_path: path, + return available_shell( + path, edition, - source: ShellSource::Fallback, - output_encoding: match edition { + ShellSource::Fallback, + match edition { ShellEdition::Pwsh => OutputEncoding::Utf8, _ => OutputEncoding::Unknown, }, - }); + ); } } ShellStatus::Unavailable { @@ -2222,12 +3777,12 @@ impl HostPlatform { } } else { if let Some(path) = find_executable("bash") { - return ShellStatus::Available(ExecShellRuntime { - executable_path: path, - edition: ShellEdition::Bash, - source: ShellSource::Fallback, - output_encoding: OutputEncoding::Utf8, - }); + return available_shell( + path, + ShellEdition::Bash, + ShellSource::Fallback, + OutputEncoding::Utf8, + ); } ShellStatus::Unavailable { code: EXEC_SHELL_UNAVAILABLE, @@ -2279,37 +3834,105 @@ impl HostPlatform { }) } - /// The directory the persistent shell owns: `/.dim/exec`. - pub fn exec_root(&self) -> PathBuf { - let root = self.home.join(".dim").join("exec"); - std::fs::canonicalize(&root).unwrap_or(root) - } - /// Removes `path`, one persistent shell output directory below /// [`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<()> { - let root = self.exec_root(); - if path == root || !path.starts_with(&root) { + if !path.is_absolute() + || path + .components() + .any(|component| matches!(component, Component::CurDir | Component::ParentDir)) + { return Err(io::Error::new( io::ErrorKind::InvalidInput, "not a persistent shell output directory", )); } - match std::fs::remove_dir_all(path) { + let root = + std::fs::canonicalize(self.exec_root_path()).unwrap_or_else(|_| self.exec_root_path()); + let target = canonicalize_existing_prefix(path)?; + if target == root || !target.starts_with(&root) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "not a persistent shell output directory", + )); + } + let mut current = root.clone(); + for component in path + .strip_prefix(&root) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "outside the exec root"))? + .components() + { + current.push(component); + match std::fs::symlink_metadata(¤t) { + Ok(metadata) if metadata.file_type().is_symlink() => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "a symlink component is not a persistent shell output directory", + )); + } + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => break, + Err(error) => return Err(error), + } + } + match std::fs::remove_dir_all(&target) { Ok(()) => {} Err(error) if error.kind() == io::ErrorKind::NotFound => {} Err(error) => return Err(error), } #[cfg(unix)] - if let Some(parent) = path.parent() { + if let Some(parent) = target.parent() { std::fs::File::open(parent)?.sync_all()?; } Ok(()) } } +fn valid_shell_marker(marker: &str) -> bool { + let Some(rest) = marker + .strip_prefix("__DIM_START_") + .or_else(|| marker.strip_prefix("__DIM_END_")) + else { + return false; + }; + let Some((first, rest)) = rest.split_once('_') else { + return false; + }; + let Some((second, tail)) = rest.split_once("__") else { + return false; + }; + tail.is_empty() + && first.len() == 8 + && second.len() == 8 + && first.bytes().all(|byte| byte.is_ascii_hexdigit()) + && second.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn canonicalize_existing_prefix(path: &Path) -> io::Result { + let mut missing = Vec::new(); + let mut current = path; + loop { + match std::fs::canonicalize(current) { + Ok(mut base) => { + for part in missing.iter().rev() { + base.push(part); + } + return Ok(base); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => { + let Some(name) = current.file_name() else { + return Err(error); + }; + missing.push(name.to_owned()); + current = current.parent().ok_or(error)?; + } + Err(error) => return Err(error), + } + } +} + fn find_executable(name: &str) -> Option { let path_var = std::env::var_os("PATH")?; for entry in std::env::split_paths(&path_var) { @@ -2321,6 +3944,1357 @@ fn find_executable(name: &str) -> Option { None } +impl HostPlatform { + 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::host_platform::output::OUTPUT_FILE_BYTE_LIMIT; + use crate::workspace_tools::background::{ + OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page, + }; + use std::io::SeekFrom; + use tokio::io::{AsyncReadExt, AsyncSeekExt}; + 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 metadata = file.metadata().await.ok(); + let truncated = metadata + .as_ref() + .is_some_and(|m| m.len() >= OUTPUT_FILE_BYTE_LIMIT); + let mut page = decode_page(&buffer[..read], cursor, limit, truncated)?; + page.total_bytes = metadata.map(|m| m.len()).unwrap_or(0); + Ok(page) + } +} + +/// 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 +} + +pub(crate) mod shell { + use super::output::bounded_preview; + use super::output::{Decoder, head_bytes, tail_bytes}; + use super::{ + ExecShellRuntime, HostPlatform, ProcessSpec, ProcessSpecError, PtyProcessTree, PtySize, + ShellEdition, ShellStatus, + }; + use super::{TaskKind, TaskRecord, terminate_job}; + use crate::workspace_tools::background::{ + OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page, + }; + use std::{ + collections::VecDeque, + io::{self, Read, Write}, + path::{Path, PathBuf}, + sync::{Arc, Mutex, Weak}, + time::{Duration, Instant}, + }; + use tokio::sync::{Mutex as AsyncMutex, Notify, 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, + events: Mutex, + active_command: Mutex>>, + children: Mutex>>, + event_notify: Arc, + kill: CancellationToken, + path: PathBuf, + edition: super::ShellEdition, + } + + pub(crate) struct ShellCommand { + pub(crate) shell: Arc, + start_marker: String, + end_marker: String, + path: PathBuf, + state: Mutex, + } + + struct ShellCommandState { + started: bool, + code: Option, + output: String, + bytes: u64, + omitted: usize, + tail: String, + file: Option, + } + + impl ShellCommand { + pub(crate) fn new( + shell: Arc, + start_marker: String, + end_marker: String, + path: PathBuf, + ) -> Self { + Self { + shell, + start_marker, + end_marker, + path, + state: Mutex::new(ShellCommandState { + started: false, + code: None, + output: String::new(), + bytes: 0, + omitted: 0, + tail: String::new(), + file: None, + }), + } + } + + fn feed(&self, line: &str) -> Option { + let mut state = self.state.lock().unwrap(); + let mut rest = line; + if !state.started { + let position = rest.find(&self.start_marker)?; + state.started = true; + rest = &rest[position + self.start_marker.len()..]; + } + if state.file.is_none() { + let mut options = std::fs::OpenOptions::new(); + options.create_new(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + if let Ok(file) = options.open(&self.path) { + state.file = Some(file); + } + } + let Some(position) = rest.find(&self.end_marker) else { + if last_full_marker(rest).is_some() { + return None; + } + append_command_output( + &mut state, + &crate::shell_session::regularize_output(rest.as_bytes()), + ); + return None; + }; + append_command_output( + &mut state, + &crate::shell_session::regularize_output(&rest.as_bytes()[..position]), + ); + let code = rest[position + self.end_marker.len()..].trim().to_owned(); + state.code = Some(code.clone()); + Some(code) + } + + pub(crate) fn output_path(&self) -> &Path { + &self.path + } + + pub(crate) fn output_record(&self) -> super::OutputRecord { + let state = self.state.lock().unwrap(); + super::OutputRecord { + path: self.path.to_string_lossy().into_owned(), + bytes: state.bytes, + truncated: state.omitted > 0, + text: None, + preview: state.tail.clone(), + preview_truncated: state.omitted > 0, + } + } + + pub(crate) fn tail(&self) -> crate::workspace_tools::exec::OutputTail { + let state = self.state.lock().unwrap(); + crate::workspace_tools::exec::OutputTail { + text: state.tail.clone(), + total_bytes: state.bytes, + truncated: state.omitted > 0, + } + } + + pub(crate) fn page( + &self, + cursor: u64, + limit: usize, + ) -> Result { + let state = self.state.lock().unwrap(); + let bytes = state.output.as_bytes(); + let start = (cursor as usize).min(bytes.len()); + let end = (start + limit + PAGE_CHAR_TRAILING_BYTES).min(bytes.len()); + let page = decode_page(&bytes[start..end], cursor, limit, state.omitted > 0)?; + Ok(super::OutputPageReply { + text: page.text, + bytes: page.bytes, + total_bytes: state.bytes, + next_cursor: page.next_cursor, + truncated: state.omitted > 0, + retained_from: 0, + reset: None, + }) + } + } + + fn append_command_output(state: &mut ShellCommandState, text: &str) { + if text.is_empty() { + return; + } + if let Some(file) = state.file.as_mut() { + use std::io::Write; + let _ = file.write_all(text.as_bytes()); + } + state.bytes += text.len() as u64; + state.tail.push_str(text); + if state.tail.len() > 16_000 { + state.tail = tail_bytes(&state.tail, 16_000).to_owned(); + } + let room = (64 * 1024usize).saturating_sub(state.output.len()); + if text.len() <= room { + state.output.push_str(text); + } else { + let kept = head_bytes(text, room); + state.output.push_str(kept); + state.omitted += text.len() - kept.len(); + } + } + + pub(crate) struct ShellJob { + pub(crate) shell: Weak, + pub(crate) pid: watch::Sender>, + pub(crate) end_marker: String, + pub(crate) output_path: PathBuf, + pub(crate) completion: Option<(PathBuf, PathBuf)>, + } + + impl ShellJob { + pub(crate) fn output_record(&self) -> (super::OutputRecord, Option) { + use std::io::{Read, Seek, SeekFrom}; + let bytes = std::fs::metadata(&self.output_path) + .map(|metadata| metadata.len()) + .unwrap_or(0); + let (text, failure) = std::fs::File::open(&self.output_path).map_or_else( + |error| { + ( + String::new(), + Some(super::TaskFailure::JobUnavailable { + message: error.to_string(), + }), + ) + }, + |mut file| { + let window = 64 * 1024; + if bytes > window { + let _ = file.seek(SeekFrom::End(-(window as i64))); + } + let mut tail = Vec::new(); + let read = file.read_to_end(&mut tail); + let mut decoder = Decoder::default(); + let mut text = decoder.write(&tail); + text.push_str(&decoder.end()); + let failure = read.err().map(|error| super::TaskFailure::JobUnavailable { + message: error.to_string(), + }); + (text, failure) + }, + ); + let (preview, preview_truncated) = bounded_preview(&text, bytes as usize); + ( + super::OutputRecord { + path: self.output_path.to_string_lossy().into_owned(), + bytes, + truncated: false, + text: None, + preview, + preview_truncated, + }, + failure, + ) + } + } + + const EVENT_RETAIN_CHARS: usize = 1024 * 1024; + + fn parse_shell_job(line: &str) -> Option<(String, u32)> { + let (prefix, tail) = last_full_marker(line)?; + if prefix != "__DIM_END_" { + return None; + } + let mut parts = tail.split_whitespace(); + let pid = parts.next()?.parse().ok()?; + let task_id = parts.next()?; + Some((task_id.to_owned(), pid)) + } + + fn shell_event_len(event: &super::ShellEvent) -> usize { + match event { + super::ShellEvent::Output { text, .. } => text.len(), + super::ShellEvent::Marker { line, .. } => line.len(), + } + } + + fn last_full_marker(line: &str) -> Option<(&'static str, &str)> { + let mut found: Option<(usize, (&'static str, &str))> = None; + for (prefix, position) in [ + ("__DIM_START_", line.rfind("__DIM_START_")), + ("__DIM_END_", line.rfind("__DIM_END_")), + ] { + let Some(position) = position else { + continue; + }; + if found.is_some_and(|(other, _)| other > position) { + continue; + } + let rest = &line[position + prefix.len()..]; + let Some((first, rest)) = rest.split_once('_') else { + continue; + }; + let Some((second, tail)) = rest.split_once("__") else { + continue; + }; + if first.len() == 8 + && second.len() == 8 + && first.bytes().all(|byte| byte.is_ascii_hexdigit()) + && second.bytes().all(|byte| byte.is_ascii_hexdigit()) + { + found = Some((position, (prefix, tail))); + } + } + found.map(|(_, marker)| marker) + } + + #[derive(Default)] + struct ShellEvents { + items: VecDeque, + pending: String, + base: u64, + next: u64, + chars: usize, + } + + impl ShellEvents { + fn push(&mut self, text: String) { + self.pending.push_str(&text); + while let Some(newline) = self.pending.find('\n') { + let line: String = self.pending.drain(..=newline).collect(); + let cursor = self.next; + self.next += 1; + self.chars += line.len(); + if last_full_marker(&line).is_some() { + self.items + .push_back(super::ShellEvent::Marker { cursor, line }); + } else { + self.items + .push_back(super::ShellEvent::Output { cursor, text: line }); + } + } + if self.pending.len() > 65536 { + let cursor = self.next; + self.next += 1; + let text = std::mem::take(&mut self.pending); + self.chars += text.len(); + self.items + .push_back(super::ShellEvent::Output { cursor, text }); + } + } + + fn trim(&mut self) { + let mut removed = false; + while self.chars > EVENT_RETAIN_CHARS { + let Some(front) = self.items.pop_front() else { + break; + }; + self.chars = self.chars.saturating_sub(shell_event_len(&front)); + removed = true; + } + if removed { + self.base = self + .items + .front() + .map(super::ShellEvent::cursor) + .unwrap_or(self.next); + } + } + + fn finish(&mut self) { + if self.pending.is_empty() { + return; + } + let cursor = self.next; + self.next += 1; + let text = std::mem::take(&mut self.pending); + self.chars += text.len(); + self.items + .push_back(super::ShellEvent::Output { cursor, text }); + } + + fn page(&mut self, cursor: u64, limit: usize) -> EventPage { + while let Some(front) = self.items.front() { + if front.cursor() >= cursor { + break; + } + if let Some(front) = self.items.pop_front() { + self.chars = self.chars.saturating_sub(shell_event_len(&front)); + self.base = front.cursor() + 1; + } + } + let reset = cursor < self.base; + let mut events = Vec::new(); + let mut used = 0; + for event in self.items.iter().filter(|event| event.cursor() >= cursor) { + let length = shell_event_len(event); + if !events.is_empty() && used + length > limit { + break; + } + used += length; + events.push(event.clone()); + if used >= limit { + break; + } + } + let next_cursor = events + .last() + .map(|event| event.cursor() + 1) + .unwrap_or(cursor.max(self.base)); + EventPage { + events, + next_cursor, + reset, + } + } + } + + pub(crate) struct EventPage { + pub(crate) events: Vec, + pub(crate) next_cursor: u64, + pub(crate) reset: bool, + } + + #[derive(Default)] + struct OutputFilter { + decoder: Decoder, + } + + impl OutputFilter { + fn new() -> Self { + Self { + decoder: Decoder::default(), + } + } + + fn push(&mut self, bytes: &[u8]) -> (String, String) { + let raw = self.decoder.write(bytes); + let display = crate::shell_session::regularize_output(raw.as_bytes()); + (raw, display) + } + + fn finish(&mut self) -> (String, String) { + let raw = self.decoder.end(); + let display = crate::shell_session::regularize_output(raw.as_bytes()); + (raw, display) + } + } + + #[derive(Default)] + struct LineSplitter { + pending: String, + finished: bool, + } + + impl LineSplitter { + fn push(&mut self, chunk: &str) -> Vec { + self.pending.push_str(chunk); + let mut lines = Vec::new(); + while let Some(newline) = self.pending.find('\n') { + lines.push(self.pending.drain(..=newline).collect()); + } + if self.pending.len() > 64 * 1024 { + lines.push(std::mem::take(&mut self.pending)); + } + lines + } + + fn finish(&mut self) -> Option { + if self.finished { + return None; + } + self.finished = true; + (!self.pending.is_empty()).then(|| std::mem::take(&mut self.pending)) + } + } + + fn classify_line( + line: &str, + pump: &Arc, + jobs: &Arc>>>, + ) { + let active = pump.active_command.lock().unwrap().clone(); + if let Some(record) = active.and_then(|weak| weak.upgrade()) + && let TaskKind::ShellCommand(command) = &record.kind + && let Some(code) = command.feed(line) + { + record.finish(shell_command_terminal(&record, command, code)); + pump.clear_active(&record); + } + if let Some((task_id, reported)) = parse_shell_job(line) { + let pid = pump + .pty + .blocking_lock() + .as_ref() + .and_then(|pty| pty.job_pid(reported).ok()); + if let Some(pid) = pid { + let jobs = jobs.lock().unwrap(); + if let Some(record) = jobs.get(&task_id) + && let TaskKind::Job(job) = &record.kind + && job + .shell + .upgrade() + .is_some_and(|shell| Arc::ptr_eq(&shell, pump)) + { + job.pid.send_replace(Some(pid)); + } + } + } + { + let jobs = jobs.lock().unwrap(); + for record in jobs.values() { + if record.is_terminal() { + continue; + } + let TaskKind::Job(job) = &record.kind else { + continue; + }; + if !job + .shell + .upgrade() + .is_some_and(|shell| Arc::ptr_eq(&shell, pump)) + { + continue; + } + if line.contains(&job.end_marker) { + let code = last_full_marker(line) + .map(|(_, tail)| tail.trim().to_owned()) + .filter(|code| !code.is_empty()); + record.finish(job_terminal(record, job, code.as_deref())); + } + } + } + } + + impl HostPlatform { + pub(crate) async fn start_shell( + &self, + id: &str, + cwd: &Path, + roots: &[PathBuf], + directory: &Path, + size: PtySize, + ) -> 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: PathBuf::from(&runtime.executable_path), + 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 (shell, record, mut file) = { + 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(), + }); + } + std::fs::create_dir_all(directory).map_err(|error| ProcessSpecError { + code: "io", + reason: error.to_string(), + })?; + let path = directory.join(format!("{id}.log")); + let mut options = std::fs::OpenOptions::new(); + options.create_new(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let file = options.open(&path).map_err(|error| ProcessSpecError { + code: if error.kind() == io::ErrorKind::AlreadyExists { + "task_exists" + } else { + "io" + }, + reason: error.to_string(), + })?; + let shell = Arc::new(ShellTask { + pty: AsyncMutex::new(None), + capture: Mutex::default(), + events: Mutex::default(), + active_command: Mutex::new(None), + children: Mutex::new(Vec::new()), + event_notify: Arc::new(Notify::new()), + kill: CancellationToken::new(), + path, + edition: runtime.edition, + }); + let record = TaskRecord::new(id.to_owned(), TaskKind::Shell(shell.clone())); + commands.insert(id.to_owned(), record.clone()); + (shell, record, file) + }; + let mut pty = match self.spawn_pty(spec, size) { + Ok(pty) => pty, + Err(error) => { + let _ = std::fs::remove_file(&shell.path); + self.commands.lock().unwrap().remove(id); + return Err(ProcessSpecError { + code: "failed", + reason: error.to_string(), + }); + } + }; + pty.hold(temporary); + let mut reader = pty.take_reader(); + *shell.pty.lock().await = Some(pty); + record.start(); + let jobs = self.commands.clone(); + let shell_record = record.clone(); + let pump = Arc::downgrade(&shell); + let (drained, reader_finished) = tokio::sync::oneshot::channel(); + std::thread::spawn(move || { + let mut bytes = [0; 4096]; + let mut filter = OutputFilter::new(); + let mut written = 0usize; + let mut splitter = LineSplitter::default(); + while let Ok(n) = reader.read(&mut bytes) { + if n == 0 { + break; + } + let Some(pump) = pump.upgrade() else { + break; + }; + let (raw, chunk) = filter.push(&bytes[..n]); + for line in splitter.push(&raw) { + classify_line(&line, &pump, &jobs); + } + let mut capture = pump.capture.lock().unwrap(); + if shell_record.is_terminal() { + 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); + } + let room = (crate::host_platform::output::OUTPUT_FILE_BYTE_LIMIT as usize) + .saturating_sub(written); + if room > 0 { + let take = chunk.len().min(room); + if file.write_all(&chunk.as_bytes()[..take]).is_ok() { + written += take; + } + } + drop(capture); + { + let mut events = pump.events.lock().unwrap(); + events.trim(); + if !shell_record.is_terminal() { + events.push(chunk); + } + } + pump.event_notify.notify_waiters(); + } + let (raw_tail, tail) = filter.finish(); + if !raw_tail.is_empty() { + for line in splitter.push(&raw_tail) { + if let Some(pump) = pump.upgrade() { + classify_line(&line, &pump, &jobs); + } + } + } + if !tail.is_empty() + && let Some(pump) = pump.upgrade() + { + let mut capture = pump.capture.lock().unwrap(); + capture.total += tail.len() as u64; + capture.text.push_str(&tail); + if capture.text.len() > RETAINED { + let dropped = + capture.text.len() - tail_bytes(&capture.text, RETAINED).len(); + capture.text.drain(..dropped); + } + let room = (crate::host_platform::output::OUTPUT_FILE_BYTE_LIMIT as usize) + .saturating_sub(written); + if room > 0 { + let take = tail.len().min(room); + let _ = file.write_all(&tail.as_bytes()[..take]); + } + drop(capture); + let mut events = pump.events.lock().unwrap(); + events.trim(); + events.push(tail); + } + if let Some(pump) = pump.upgrade() { + if let Some(line) = splitter.finish() { + classify_line(&line, &pump, &jobs); + } + pump.events.lock().unwrap().finish(); + } + let _ = drained.send(()); + }); + let worker = shell.clone(); + let worker_record = record.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.kill.cancelled()=>Some("cancelled"), + _=shutdown.cancelled()=>Some("unloaded"), + }; + 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::host_platform::output::EXIT_STDIO_GRACE, + reader_finished, + ) + .await; + let terminal = + shell_terminal(&worker_record, worker.output_record(), exit, status, error); + worker_record.finish(terminal); + }); + Ok((shell, runtime)) + } + } + + impl ShellTask { + pub(crate) fn output_path(&self) -> &Path { + &self.path + } + + pub(crate) fn pwsh(&self) -> bool { + matches!( + self.edition, + super::ShellEdition::Pwsh | super::ShellEdition::WindowsPowershell + ) + } + + pub(crate) fn reserve_active_command(&self, command: &Arc) -> bool { + let mut active = self.active_command.lock().unwrap(); + if active + .as_ref() + .and_then(Weak::upgrade) + .is_some_and(|current| !current.is_terminal()) + { + return false; + } + *active = Some(Arc::downgrade(command)); + true + } + + pub(crate) fn set_active_command(&self, command: Option>) { + *self.active_command.lock().unwrap() = command.map(|command| Arc::downgrade(&command)); + } + + pub(crate) fn is_active(&self, record: &Arc) -> bool { + self.active_command + .lock() + .unwrap() + .as_ref() + .and_then(Weak::upgrade) + .is_some_and(|current| Arc::ptr_eq(¤t, record)) + } + + pub(crate) fn clear_active(&self, record: &super::TaskRecord) { + let mut active = self.active_command.lock().unwrap(); + if active + .as_ref() + .and_then(Weak::upgrade) + .is_some_and(|current| std::ptr::eq(Arc::as_ptr(¤t), record)) + { + *active = None; + } + } + + pub(crate) fn add_child(&self, record: &Arc) { + self.children.lock().unwrap().push(Arc::downgrade(record)); + } + + pub(crate) fn children_list(&self) -> Vec> { + self.children + .lock() + .unwrap() + .iter() + .filter_map(Weak::upgrade) + .collect() + } + + pub(crate) fn sweep(&self, shell_terminal: Option>) { + let failure = match &shell_terminal { + Some(terminal) + if matches!(&terminal.failure, Some(super::TaskFailure::OwnerUnloaded)) => + { + super::TaskFailure::OwnerUnloaded + } + Some(terminal) if terminal.status == super::TaskStatus::Cancelled => { + super::TaskFailure::ShellReset + } + _ => super::TaskFailure::ShellExited, + }; + let note = shell_terminal + .as_ref() + .map( + |terminal| match (terminal.signal.as_deref(), terminal.exit_code) { + (Some(signal), _) => format!("[shell killed by signal: {signal}]"), + (_, Some(code)) => format!("[shell exited: code {code}]"), + _ => "[shell exited]".to_owned(), + }, + ) + .unwrap_or_else(|| "[shell exited]".to_owned()); + for record in self.children_list() { + if record.is_terminal() { + continue; + } + let output = match &record.kind { + super::TaskKind::ShellCommand(command) => command.output_record(), + super::TaskKind::Job(job) => { + if let Some(pid) = *job.pid.borrow() { + let _ = terminate_job(pid); + } + job.output_record().0 + } + _ => super::OutputRecord::default(), + }; + record.finish(super::Terminal { + status: super::TaskStatus::Failed, + exit_code: None, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: Some(failure.clone()), + output, + note: Some(note.clone()), + }); + } + self.active_command.lock().unwrap().take(); + } + + pub(crate) fn terminate(&self) { + self.kill.cancel(); + } + + pub(crate) fn output_record(&self) -> super::OutputRecord { + let capture = self.capture.lock().unwrap(); + let (preview, preview_truncated) = + bounded_preview(&capture.text, capture.total as usize); + super::OutputRecord { + path: self.path.to_string_lossy().into_owned(), + bytes: capture.total, + truncated: capture.total > capture.text.len() as u64, + text: None, + preview, + preview_truncated, + } + } + + pub(crate) async fn events_page( + &self, + cursor: u64, + wait_ms: Option, + limit: usize, + ) -> EventPage { + let wait = wait_ms.unwrap_or(0); + let deadline = Instant::now() + Duration::from_millis(wait.min(86_400_000)); + loop { + let page = { + let mut events = self.events.lock().unwrap(); + let page = events.page(cursor, limit); + drop(events); + page + }; + if !page.events.is_empty() || page.reset || wait == 0 || Instant::now() >= deadline + { + return page; + } + let remaining = deadline.saturating_duration_since(Instant::now()); + tokio::select! { + _ = self.event_notify.notified() => {} + _ = tokio::time::sleep(remaining) => {} + } + } + } + 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 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(super::OutputPageReply { + text: String::new(), + bytes: 0, + total_bytes: capture.total, + next_cursor: None, + truncated: true, + retained_from: first, + reset: Some(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 page = decode_page( + &capture.text.as_bytes()[start..end], + cursor, + limit, + first != 0, + )?; + Ok(super::OutputPageReply { + text: page.text, + bytes: page.bytes, + total_bytes: capture.total, + next_cursor: page.next_cursor, + truncated: page.truncated, + retained_from: first, + reset: None, + }) + } + pub(crate) fn tail(&self) -> crate::workspace_tools::exec::OutputTail { + let capture = self.capture.lock().unwrap(); + let (text, truncated) = bounded_preview(&capture.text, capture.total as usize); + crate::workspace_tools::exec::OutputTail { + text, + total_bytes: capture.total, + truncated, + } + } + } + + fn shell_command_terminal( + record: &super::TaskRecord, + command: &ShellCommand, + code: String, + ) -> super::Terminal { + let (status, failure) = match code.as_str() { + "0" => (super::TaskStatus::Exited, None), + "failed" => ( + super::TaskStatus::Failed, + Some(super::TaskFailure::CommandFailed), + ), + other => match other.parse::() { + Ok(_) => ( + super::TaskStatus::Failed, + Some(super::TaskFailure::CommandFailed), + ), + Err(_) => ( + super::TaskStatus::Failed, + Some(super::TaskFailure::UnknownExit), + ), + }, + }; + super::Terminal { + status, + exit_code: code.parse().ok(), + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure, + output: command.output_record(), + note: None, + } + } + + pub(crate) fn completion_code(text: &str, marker: &str) -> Option { + text.lines().find_map(|line| { + line.split_once(marker) + .map(|(_, rest)| rest.trim().to_owned()) + .filter(|rest| !rest.is_empty()) + }) + } + + pub(crate) fn job_completion_terminal( + record: &super::TaskRecord, + job: &ShellJob, + code: &str, + ) -> super::Terminal { + let (output, read_failure) = job.output_record(); + let (status, exit_code, failure) = match code { + "failed" => ( + super::TaskStatus::Failed, + None, + Some(super::TaskFailure::CommandFailed), + ), + "unknown" => ( + super::TaskStatus::Failed, + None, + Some(super::TaskFailure::UnknownExit), + ), + code => match code.parse::() { + Ok(0) => (super::TaskStatus::Exited, Some(0), None), + Ok(code) => ( + super::TaskStatus::Failed, + Some(code), + Some(super::TaskFailure::CommandFailed), + ), + Err(_) => ( + super::TaskStatus::Failed, + None, + Some(super::TaskFailure::UnknownExit), + ), + }, + }; + super::Terminal { + status, + exit_code, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: read_failure.or(failure), + output, + note: None, + } + } + + fn job_terminal( + record: &super::TaskRecord, + job: &ShellJob, + code: Option<&str>, + ) -> super::Terminal { + let (output, read_failure) = job.output_record(); + let (status, exit_code, failure) = match code { + Some("0") => (super::TaskStatus::Exited, Some(0), None), + Some(code) => match code.parse::() { + Ok(code) => ( + super::TaskStatus::Failed, + Some(code), + Some(super::TaskFailure::CommandFailed), + ), + Err(_) => ( + super::TaskStatus::Failed, + None, + Some(super::TaskFailure::UnknownExit), + ), + }, + None => (super::TaskStatus::Exited, None, None), + }; + super::Terminal { + status, + exit_code, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: read_failure.or(failure), + output, + note: None, + } + } + + fn shell_terminal( + record: &super::TaskRecord, + output: super::OutputRecord, + exit: Option, + status: &str, + error: Option, + ) -> super::Terminal { + let status_text = status; + let status = match status_text { + "exited" => super::TaskStatus::Exited, + "signaled" => super::TaskStatus::Signaled, + "timed_out" => super::TaskStatus::TimedOut, + "cancelled" => super::TaskStatus::Cancelled, + "unloaded" => super::TaskStatus::Cancelled, + _ => super::TaskStatus::Failed, + }; + let (exit_code, signal) = match exit.as_ref() { + Some(exit) => ( + Some(exit.exit_code() as i32), + exit.signal().map(str::to_owned), + ), + None => (None, None), + }; + let failure = match status { + super::TaskStatus::Cancelled if status_text == "unloaded" => { + Some(super::TaskFailure::OwnerUnloaded) + } + super::TaskStatus::Failed => { + error + .as_ref() + .map(|message| super::TaskFailure::TerminateFailed { + message: message.clone(), + }) + } + _ => None, + }; + super::Terminal { + status, + exit_code, + signal, + duration_ms: record.started.elapsed().as_millis() as u64, + failure, + output, + note: error, + } + } + + #[cfg(test)] + mod shell_marker_tests { + use super::last_full_marker; + + #[test] + fn an_echoed_marker_is_not_a_full_marker() { + let echo = "printf '%s%s' '__DIM_START_aaaabbbb_' 'ccccdddd__';"; + assert!(last_full_marker(echo).is_none()); + } + + #[test] + fn a_full_marker_is_recognized_after_the_echo() { + let line = "__DIM_START_aaaabbbb_ccccdddd__"; + assert_eq!(last_full_marker(line), Some(("__DIM_START_", ""))); + let line = "__DIM_END_aaaabbbb_ccccdddd__7\n"; + assert_eq!(last_full_marker(line), Some(("__DIM_END_", "7\n"))); + } + + #[test] + fn the_init_line_reports_its_last_marker() { + let line = "__DIM_START_aaaabbbb_ccccdddd____DIM_END_eeeeffff_00001111__0\n"; + assert_eq!(last_full_marker(line), Some(("__DIM_END_", "0\n"))); + } + } +} + +pub(crate) 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(crate) enum ConfiguredEnd { + Exited { + status: ExitStatus, + stdout: Vec, + stderr: Vec, + stdout_truncated: bool, + stderr_truncated: bool, + }, + Cancelled, + TimedOut, +} + +#[derive(Debug)] +pub(crate) enum ConfiguredError { + Prepare(ProcessSpecError), + Unloaded, + Spawn(std::io::Error), + Wait(std::io::Error, Vec), +} + +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 HostPlatform { + pub(crate) 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_process(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; + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -2372,7 +5346,7 @@ mod tests { ); let base = joined(&["/base/a", "/base/b"]); let composed = platform - .child_path(&["/host/bin".into()], OsStr::new(&base)) + .child_path_process(&["/host/bin".into()], OsStr::new(&base)) .unwrap(); assert_eq!( composed.to_str().unwrap(), @@ -2393,7 +5367,7 @@ mod tests { Some(vec![toolchain("/base/a"), toolchain("/runtimes/node/bin")]), ); let base = joined(&["/base/a", "/base/b"]); - let composed = platform.child_path(&[], OsStr::new(&base)).unwrap(); + let composed = platform.child_path_process(&[], OsStr::new(&base)).unwrap(); assert_eq!( composed.to_str().unwrap(), joined(&["/base/a", "/base/b", "/runtimes/node/bin"]) @@ -2401,21 +5375,47 @@ mod tests { let base = joined(&["/base", "/runtimes/node/bin"]); let installed = host_with(&[], Some(vec![toolchain("/runtimes/node/bin")])); assert!( - installed.child_path(&[], OsStr::new(&base)).is_none(), + installed + .child_path_process(&[], OsStr::new(&base)) + .is_none(), "a runtime already on the PATH changes nothing" ); } + #[test] + fn a_child_path_without_an_addition_answers_none() { + let platform = host_with(&[], None); + assert!( + platform + .child_path(ChildPathRequest { + directories: Vec::new(), + base: joined(&["/base"]), + }) + .is_none() + ); + } + + #[cfg(unix)] + #[test] + fn the_native_child_path_preserves_a_non_utf8_base() { + use std::os::unix::ffi::OsStrExt; + let platform = host_with(&[], Some(vec![toolchain("/runtimes/node/bin")])); + let base = OsStr::from_bytes(b"/base/\xff"); + let composed = platform.child_path_process(&[], base).unwrap(); + assert_eq!(&composed.as_bytes()[..base.len()], base.as_bytes()); + assert!(composed.as_bytes().ends_with(b"/runtimes/node/bin")); + } + #[test] fn a_platform_without_the_port_leaves_the_path_as_it_is() { assert!( host_with(&[], None) - .child_path(&[], OsStr::new("/base")) + .child_path_process(&[], OsStr::new("/base")) .is_none() ); assert!( host_with(&[], Some(vec![])) - .child_path(&[], OsStr::new("/base")) + .child_path_process(&[], OsStr::new("/base")) .is_none() ); } @@ -2513,7 +5513,7 @@ mod tests { std::fs::canonicalize(&path).unwrap_or(path) }) .collect(); - let mut tree = platform.spawn(spec).unwrap(); + let mut tree = platform.spawn_tree(spec).unwrap(); tree.hold(temporary); let mut stdout = tree.stdout(); let mut stderr = tree.stderr(); diff --git a/crates/dim-agent-capabilities/src/host_platform/confined.rs b/crates/dim-agent-capabilities/src/host_platform/confined.rs index 5c8564529a..6f23d4ed42 100644 --- a/crates/dim-agent-capabilities/src/host_platform/confined.rs +++ b/crates/dim-agent-capabilities/src/host_platform/confined.rs @@ -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`]; @@ -73,7 +74,8 @@ pub struct ConfinedOutput { } /// The output stream that reached its limit. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "snake_case")] pub enum ConfinedStream { Stdout, Stderr, @@ -176,7 +178,7 @@ impl HostPlatform { /// must not rely on the directory being quiescent on macOS or unconfined /// Linux: a process that left the group may still write to the `write` /// directories after `Ok`. - pub async fn spawn_confined( + pub async fn spawn_confined_process( &self, spec: ConfinedSpec, confinement: Confinement, @@ -186,7 +188,7 @@ impl HostPlatform { if cancel.is_cancelled() { return Err(ConfinedError::Cancelled); } - let mut tree = self.spawn(process).map_err(ConfinedError::Spawn)?; + let mut tree = self.spawn_tree(process).map_err(ConfinedError::Spawn)?; let stdout = tree.stdout(); let stderr = tree.stderr(); let outcome = { diff --git a/crates/dim-agent-capabilities/src/host_platform/output.rs b/crates/dim-agent-capabilities/src/host_platform/output.rs new file mode 100644 index 0000000000..77a9a802a9 --- /dev/null +++ b/crates/dim-agent-capabilities/src/host_platform/output.rs @@ -0,0 +1,216 @@ +//! Canonical command output rules shared by exec, the persistent shell and ShellInput: +//! one UTF-8 decoder, one sanitizer, one preview truncation and one pipe pump. + +use std::{ + sync::Arc, + time::{Duration, Instant}, +}; + +use tokio::io::AsyncReadExt; +use tokio_util::sync::CancellationToken; + +pub const OUTPUT_PREVIEW_MAX_LINES: usize = 2_000; +pub const OUTPUT_PREVIEW_MAX_BYTES: usize = 50 * 1024; +pub const PREVIEW_BUFFER_HEADROOM_BYTES: usize = OUTPUT_PREVIEW_MAX_BYTES * 2; +pub const OUTPUT_FILE_BYTE_LIMIT: u64 = 64 * 1024 * 1024; +pub const EXIT_STDIO_GRACE: Duration = Duration::from_millis(100); + +/// Incremental canonical UTF-8 decoding of one stream (ADR 018): invalid and +/// truncated bytes become `<0xNN>`, never U+FFFD. +#[derive(Default)] +pub struct Decoder { + pending: Vec, +} +impl Decoder { + pub fn write(&mut self, chunk: &[u8]) -> String { + let mut input = std::mem::take(&mut self.pending); + input.extend_from_slice(chunk); + self.decode(&input, false) + } + pub fn end(&mut self) -> String { + let input = std::mem::take(&mut self.pending); + self.decode(&input, true) + } + fn decode(&mut self, input: &[u8], last: bool) -> String { + let mut output = String::new(); + let mut offset = 0; + while offset < input.len() { + let first = input[offset]; + if first <= 0x7f { + output.push(first as char); + offset += 1; + continue; + } + let length = match first { + 0xc2..=0xdf => 2, + 0xe0..=0xef => 3, + 0xf0..=0xf4 => 4, + _ => 0, + }; + if length == 0 { + output.push_str(&escape_byte(first)); + offset += 1; + continue; + } + if offset + length > input.len() { + if !last { + self.pending = input[offset..].to_vec(); + break; + } + output.push_str(&escape_byte(first)); + offset += 1; + continue; + } + match std::str::from_utf8(&input[offset..offset + length]) { + Ok(text) => { + output.push_str(text); + offset += length; + } + Err(_) => { + output.push_str(&escape_byte(first)); + offset += 1; + } + } + } + output + } +} + +fn escape_byte(byte: u8) -> String { + format!("<0x{byte:02X}>") +} + +/// Removes control characters except `\t\n\r`, and U+FFF9–U+FFFB. +pub fn sanitize(text: &str) -> String { + text.chars() + .filter(|&ch| { + !(matches!(ch, '\u{0}'..='\u{8}' | '\u{b}' | '\u{c}' | '\u{e}'..='\u{1f}') + || matches!(ch, '\u{7f}'..='\u{9f}' | '\u{fff9}'..='\u{fffb}')) + }) + .collect() +} + +/// The head of `text` within `max` UTF-8 bytes, on a character boundary. +pub(crate) fn head_bytes(text: &str, max: usize) -> &str { + if text.len() <= max { + return text; + } + let mut end = max; + while !text.is_char_boundary(end) { + end -= 1; + } + &text[..end] +} + +/// The tail of `text` within `max` UTF-8 bytes, on a character boundary. +pub fn tail_bytes(text: &str, max: usize) -> &str { + if text.len() <= max { + return text; + } + let mut start = text.len() - max; + while !text.is_char_boundary(start) { + start += 1; + } + &text[start..] +} + +/// TS `truncatePreview`: the last 2000 lines within 50 KiB. +pub fn truncate_preview(text: &str) -> String { + let sanitized = sanitize(text); + if sanitized.is_empty() { + return sanitized; + } + let lines: Vec<&str> = sanitized.split('\n').collect(); + let tail = &lines[lines.len().saturating_sub(OUTPUT_PREVIEW_MAX_LINES)..]; + let joined = tail.join("\n"); + if joined.len() <= OUTPUT_PREVIEW_MAX_BYTES { + return joined; + } + if tail.len() == 1 || (tail.len() == 2 && tail[1].is_empty()) { + let suffix = if tail.len() == 2 { "\n" } else { "" }; + return format!( + "{}{suffix}", + tail_bytes(tail[0], OUTPUT_PREVIEW_MAX_BYTES - suffix.len()) + ); + } + let (mut low, mut high) = (0, tail.len() - 1); + while low < high { + let middle = (low + high) / 2; + if tail[middle..].join("\n").len() <= OUTPUT_PREVIEW_MAX_BYTES { + high = middle; + } else { + low = middle + 1; + } + } + let joined = tail[low..].join("\n"); + tail_bytes(&joined, OUTPUT_PREVIEW_MAX_BYTES).to_owned() +} + +/// exec's preview bounds — the sanitized tail within 2,000 lines and 50 KiB — +/// and whether they left anything out: bytes outside the captured `preview` +/// buffer, or a sanitized tail the rule cut. +pub fn bounded_preview(preview: &str, decoded: usize) -> (String, bool) { + let text = truncate_preview(preview); + let truncated = decoded > preview.len() || text.len() < sanitize(preview).len(); + (text, truncated) +} + +/// Appends `text` to the bounded output tail that [`truncate_preview`] reads: +/// past twice the preview budget, only the last part from a line start stays. +pub fn capture_preview(preview: &mut String, text: &str) { + preview.push_str(text); + if preview.len() > PREVIEW_BUFFER_HEADROOM_BYTES { + let keep = tail_bytes(preview, PREVIEW_BUFFER_HEADROOM_BYTES); + let keep = keep + .find('\n') + .filter(|index| index + 1 < keep.len()) + .map_or(keep, |index| &keep[index + 1..]); + *preview = keep.to_owned(); + } +} + +/// Where [`pump`] delivers the decoded text of a pipe, in read order. +pub trait OutputSink: Send + Sync { + fn push(&self, text: &str) -> impl Future + Send; +} + +/// Reads one pipe through its own [`Decoder`] until EOF, a read error, or +/// [`EXIT_STDIO_GRACE`] of reading after `stop` (the root exited) fires. +pub async fn pump( + mut pipe: impl tokio::io::AsyncRead + Unpin, + output: Arc, + stop: CancellationToken, +) { + let mut decoder = Decoder::default(); + let mut buffer = vec![0; 16 * 1024]; + let mut drain_budget = EXIT_STDIO_GRACE; + loop { + let draining = stop.is_cancelled(); + let started = Instant::now(); + let read = if draining { + if drain_budget.is_zero() { + break; + } + match tokio::time::timeout(drain_budget, pipe.read(&mut buffer)).await { + Ok(read) => read, + Err(_) => break, + } + } else { + tokio::select! { + read = pipe.read(&mut buffer) => read, + _ = stop.cancelled() => continue, + } + }; + match read { + Ok(0) | Err(_) => break, + Ok(count) => { + let text = decoder.write(&buffer[..count]); + if draining { + drain_budget = drain_budget.saturating_sub(started.elapsed()); + } + output.push(&text).await; + } + } + } + output.push(&decoder.end()).await; +} diff --git a/crates/dim-agent-capabilities/src/host_platform/task.rs b/crates/dim-agent-capabilities/src/host_platform/task.rs new file mode 100644 index 0000000000..da3ba2aab9 --- /dev/null +++ b/crates/dim-agent-capabilities/src/host_platform/task.rs @@ -0,0 +1,214 @@ +//! One task table entry for every host process: the common state machine, the +//! terminal record and the per-kind payload. Payloads own their resources; the +//! record owns the one terminal watch. + +use std::{ + sync::{Arc, Mutex}, + time::Instant, +}; + +use tokio::sync::watch; + +use super::{TaskFailure, WaitReply, WaitStatus, shell}; +use crate::workspace_tools::background::{OutputPage, PAGE_CHAR_TRAILING_BYTES, decode_page}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum TaskStatus { + Exited, + Signaled, + TimedOut, + Cancelled, + Failed, +} + +impl TaskStatus { + fn wait_status(self) -> WaitStatus { + match self { + Self::Exited => WaitStatus::Exited, + Self::Signaled => WaitStatus::Signaled, + Self::TimedOut => WaitStatus::TimedOut, + Self::Cancelled => WaitStatus::Cancelled, + Self::Failed => WaitStatus::Failed, + } + } +} + +#[derive(Clone, Debug, Default)] +pub(crate) struct OutputRecord { + pub(crate) path: String, + pub(crate) bytes: u64, + pub(crate) truncated: bool, + pub(crate) text: Option, + pub(crate) preview: String, + pub(crate) preview_truncated: bool, +} + +pub(crate) struct Terminal { + pub(crate) status: TaskStatus, + pub(crate) exit_code: Option, + pub(crate) signal: Option, + pub(crate) duration_ms: u64, + pub(crate) failure: Option, + pub(crate) output: OutputRecord, + pub(crate) note: Option, +} + +pub(crate) enum TaskState { + Reserved, + Running, + Terminal(Arc), +} + +pub(crate) enum TaskKind { + Command(Arc), + ShellCommand(Arc), + Job(Arc), + Shell(Arc), +} + +pub(crate) struct TaskRecord { + pub(crate) id: String, + pub(crate) started: Instant, + pub(crate) state: Mutex, + pub(crate) changed: watch::Sender>>, + pub(crate) kind: TaskKind, +} + +impl TaskRecord { + pub(crate) fn new(id: String, kind: TaskKind) -> Arc { + Arc::new(Self { + id, + started: Instant::now(), + state: Mutex::new(TaskState::Reserved), + changed: watch::channel(None).0, + kind, + }) + } + + pub(crate) fn start(&self) -> bool { + let mut state = self.state.lock().unwrap(); + if matches!(*state, TaskState::Reserved) { + *state = TaskState::Running; + true + } else { + false + } + } + + pub(crate) fn finish(&self, terminal: Terminal) { + let mut state = self.state.lock().unwrap(); + if matches!(*state, TaskState::Terminal(_)) { + return; + } + let terminal = Arc::new(terminal); + *state = TaskState::Terminal(terminal.clone()); + drop(state); + self.changed.send_replace(Some(terminal)); + self.after_terminal(); + } + + pub(crate) fn terminal(&self) -> Option> { + match &*self.state.lock().unwrap() { + TaskState::Terminal(terminal) => Some(terminal.clone()), + _ => None, + } + } + + pub(crate) fn is_terminal(&self) -> bool { + matches!(*self.state.lock().unwrap(), TaskState::Terminal(_)) + } + + pub(crate) fn is_running(&self) -> bool { + matches!(*self.state.lock().unwrap(), TaskState::Running) + } + + fn after_terminal(&self) { + match &self.kind { + TaskKind::ShellCommand(command) => command.shell.clear_active(self), + TaskKind::Shell(shell) => shell.sweep(self.terminal()), + TaskKind::Command(_) | TaskKind::Job(_) => {} + } + } + + pub(crate) fn terminal_page(&self, cursor: u64, limit: usize) -> Option { + let terminal = self.terminal()?; + let text = terminal.output.text.as_ref()?; + let bytes = text.as_bytes(); + let start = usize::try_from(cursor) + .unwrap_or(usize::MAX) + .min(bytes.len()); + let end = start + .saturating_add(limit + PAGE_CHAR_TRAILING_BYTES) + .min(bytes.len()); + let mut page = + decode_page(&bytes[start..end], cursor, limit, terminal.output.truncated).ok()?; + page.total_bytes = terminal.output.bytes; + Some(page) + } + + pub(crate) async fn output_snapshot(&self) -> OutputRecord { + match &self.kind { + TaskKind::Command(command) => command.output_record().await, + TaskKind::ShellCommand(command) => command.output_record(), + TaskKind::Job(job) => job.output_record().0, + TaskKind::Shell(shell) => shell.output_record(), + } + } + + pub(crate) async fn wait(&self, timeout: Option) -> WaitReply { + let mut changed = self.changed.subscribe(); + let deadline = timeout.map(|ms| Instant::now() + std::time::Duration::from_millis(ms)); + loop { + let notified = changed.changed(); + if let Some(terminal) = self.terminal() { + return self.reply(Some(terminal)).await; + } + let Some(deadline) = deadline else { + let _ = notified.await; + continue; + }; + let now = Instant::now(); + if now >= deadline { + return self.reply(None).await; + } + let _ = tokio::time::timeout(deadline.saturating_duration_since(now), notified).await; + } + } + + async fn reply(&self, terminal: Option>) -> WaitReply { + let output = match &terminal { + Some(terminal) => terminal.output.clone(), + None => self.output_snapshot().await, + }; + let (status, exit_code, signal, duration_ms, failure_note) = match &terminal { + Some(terminal) => ( + terminal.status.wait_status(), + terminal.exit_code, + terminal.signal.clone(), + terminal.duration_ms, + terminal.note.clone(), + ), + None => ( + WaitStatus::Running, + None, + None, + self.started.elapsed().as_millis() as u64, + None, + ), + }; + WaitReply { + status, + text: output.text, + exit_code, + signal, + duration_ms, + output_path: output.path, + output_bytes: output.bytes, + output_truncated: output.truncated, + preview: output.preview, + preview_truncated: output.preview_truncated, + failure: terminal.and_then(|terminal| terminal.failure.clone()), + failure_note, + } + } +} diff --git a/crates/dim-agent-capabilities/src/lib.rs b/crates/dim-agent-capabilities/src/lib.rs index 588447991e..b07b480373 100644 --- a/crates/dim-agent-capabilities/src/lib.rs +++ b/crates/dim-agent-capabilities/src/lib.rs @@ -124,6 +124,7 @@ fn register_names_in(catalog: &mut dim_agent_runtime::names::ServiceCatalog) { register::(catalog, branch); catalog.register_shared_instance("branchLine", BRANCH_GROUP); register::(catalog, None); + catalog.register_shared("hostPlatform"); register::(catalog, None); register::(catalog, None); catalog.register_shared("fsHost"); diff --git a/crates/dim-agent-capabilities/src/prompt_sources.rs b/crates/dim-agent-capabilities/src/prompt_sources.rs index 57e0c8f7a7..e9549f0101 100644 --- a/crates/dim-agent-capabilities/src/prompt_sources.rs +++ b/crates/dim-agent-capabilities/src/prompt_sources.rs @@ -277,7 +277,7 @@ fn environment( Some(custom) => custom(shell), None => built_in.to_owned(), }; - entries.push(xml_tag("shell", &executable_path.to_string_lossy())); + entries.push(xml_tag("shell", executable_path)); entries.push(xml_tag("shell_edition", edition)); entries.push(xml_tag("shell_guidance", &guidance)); entries.push(xml_tag( diff --git a/crates/dim-agent-capabilities/src/shell_input.rs b/crates/dim-agent-capabilities/src/shell_input.rs index 848504363b..ba3f4a62be 100644 --- a/crates/dim-agent-capabilities/src/shell_input.rs +++ b/crates/dim-agent-capabilities/src/shell_input.rs @@ -11,15 +11,16 @@ //! Session (`SessionLifecycle::take_hold`), so an idle unload never ends it. use crate::{ context_block::{element, raw, text}, + host_platform::output::{ + OutputSink, bounded_preview, capture_preview, pump, sanitize, tail_bytes, + }, + host_platform::signal_name, host_platform::{HostPlatform, ProcessTree}, 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, - }, }; use dim_agent_runtime::{ AgentBuilder, Names, SessionConfig, SessionHold, SessionIdentity, SessionLifecycle, @@ -261,7 +262,7 @@ impl ShellInput { })); } let hold = self.lifecycle.take_hold().ok_or_else(RpcError::closed)?; - let tree = self.platform.spawn(spec).map_err(|error| { + let tree = self.platform.spawn_tree(spec).map_err(|error| { refused("spawn_failed", format!("Failed to spawn process: {error}")) })?; let info = RunInfo { diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index fb15e58f7e..b3dfdf9602 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -15,10 +15,13 @@ use crate::{ exec_stop::{ExecStop, TaskError}, host::{HostError, SessionFiles}, host_platform::{ - HostPlatform, PtyProcessTree, PtySize, ShellEdition, ShellStatus, kill_job, stop_job, + HostPlatform, HostPlatformError, OutputRequest, ShellCommandStart, ShellEdition, + ShellEvent, ShellEventRequest, ShellJobStart, ShellRequest, ShellStatus, ShellWrite, + TaskRequest, WaitReply, WaitRequest, WaitStatus, }, }; -use dim_agent_runtime::{Dispatcher, Names, Timeline}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use dim_agent_runtime::{Dispatcher, Names, SessionLifecycle, Timeline}; use dim_agent_types::{ EventKind, ExecEndedData, ExecStartedData, ExecStatus, JsonObject, ToolContent, ToolEffect, ToolResult, @@ -28,7 +31,6 @@ use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use serde_json::json; use std::{ collections::{HashMap, VecDeque}, - io::Write as _, path::{Path, PathBuf}, sync::Arc, time::Duration, @@ -48,22 +50,6 @@ const MAX_TIMEOUT_MS: u64 = 3_600_000; const DESCRIPTION_CHARS: usize = 200; const INIT_TIMEOUT: Duration = Duration::from_secs(10); const STOP_WAIT: Duration = Duration::from_secs(2); -const PID_WAIT: Duration = Duration::from_secs(2); -const PWSH_FILE_POLL: Duration = Duration::from_millis(200); -const SHELL_EXIT_POLL: Duration = Duration::from_millis(100); - -/// Hex digits in each half of a marker; `marker_pair` splits a uuid into -/// four of these runs. -const MARKER_HEX: usize = 8; -/// The longest exit token `marker_code` accepts. -const MARKER_TOKEN_LIMIT: usize = 12; -/// The marker a wrapper writes: `__DIM_START_` or `__DIM_END_`, two -/// `MARKER_HEX` runs, a separator and the closing `__`. -const MARKER_LIMIT: usize = "__DIM_START_".len() + 2 * MARKER_HEX + 1 + 2; -/// The longest line a marker can occupy: the marker, the exit token -/// `posix_command`, `posix_background` and `pwsh_command` append to it, and -/// the trailing newline. -const MARKER_LINE_LIMIT: usize = MARKER_LIMIT + MARKER_TOKEN_LIMIT + 1; /// Configuration for the shell session. #[derive(Clone)] @@ -97,171 +83,24 @@ struct QueuedCommand { done: oneshot::Sender>, } -/// One command's output, owned from the moment its line is written. -/// -/// The PTY stream is shared by every command, so a command cannot recover -/// its output from a common buffer: another command's burst can push the -/// start marker out of it before the marker is looked for. Each command -/// holds its own capture instead, fed every chunk while it holds the shell, -/// and finds its own start marker in that stream. -struct Capture { - start_marker: String, - end_marker: String, - /// Bytes seen before the start marker, trimmed to the tail that could - /// still be a start marker split across chunks. The shell echoes the - /// wrapper line, and the marker is written in two quoted halves, so no - /// full marker appears there. - ahead: String, - /// Set once the start marker arrived. - started: bool, - /// The earliest `OUTPUT_LIMIT` bytes of the output. - output: String, - /// Bytes dropped after `output` filled. - omitted: usize, - /// Bytes after the start marker not yet settled: the end marker line may - /// be complete or partial there. - pending: String, - /// The end marker's exit token once its line is complete. - code: Option, - /// Where settled bytes also go: the task log once the call occupies. - file: Option, - /// How much of `output` a waiting caller has already been given. - delivered: usize, -} - -impl Capture { - fn new(start_marker: String, end_marker: String) -> Self { - Self { - start_marker, - end_marker, - ahead: String::new(), - started: false, - output: String::new(), - omitted: 0, - pending: String::new(), - code: None, - file: None, - delivered: 0, - } - } - - /// Takes one chunk of the stream. Nothing is settled here: a - /// background job's completion marker has to leave the chunk first. - fn append(&mut self, text: &str) { - if self.started { - self.pending.push_str(text); - return; - } - self.ahead.push_str(text); - let Some(pos) = self.ahead.find(&self.start_marker) else { - let keep = self.start_marker.len() - 1; - self.ahead = tail_bytes(&self.ahead, keep).to_owned(); - return; - }; - let rest = self.ahead[pos + self.start_marker.len()..].to_owned(); - self.ahead.clear(); - self.started = true; - self.pending.push_str(&rest); - } - - /// Removes a completion marker line of another command. - fn strip(&mut self, marker: &str) { - strip_marker(&mut self.ahead, marker); - strip_marker(&mut self.pending, marker); - } - - /// Settles everything that cannot be part of the end marker. Once the - /// end marker line is complete, its token is `code` and the line itself - /// is dropped: it is not output. - fn drain(&mut self) { - if !self.started || self.code.is_some() { - return; - } - if let Some(code) = marker_code(&self.pending, &self.end_marker) { - let end = self.pending.find(&self.end_marker).expect("marker present"); - self.settle(end); - self.pending.clear(); - self.code = Some(code); - return; - } - self.settle(marker_hold(&self.pending)); - } - - /// Settles `pending[..upto]`: the task log gets every byte, while - /// `output` keeps the earliest `OUTPUT_LIMIT` bytes for the result and - /// counts the rest as omitted. - fn settle(&mut self, upto: usize) { - let text: String = self.pending.drain(..upto).collect(); - if let Some(file) = self.file.as_mut() { - let _ = file.write_all(text.as_bytes()); - } - let room = OUTPUT_LIMIT.saturating_sub(self.output.len()); - let mut end = room.min(text.len()); - while !text.is_char_boundary(end) { - end -= 1; - } - self.output.push_str(&text[..end]); - self.omitted += text.len() - end; - } - - /// Makes the task log receive everything settled from now on, starting - /// with the output already held and the bytes already dropped. The file - /// stays open for the task's life: the burst arrives in thousands of - /// chunks, and opening it once per chunk costs more than the read that - /// produced them. - fn bind(&mut self, path: &Path) { - let Ok(mut file) = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(path) - else { - return; - }; - let _ = file.write_all(self.output.as_bytes()); - if let Some(omitted) = self.omitted() { - let mut note = String::new(); - if !self.output.is_empty() && !self.output.ends_with('\n') { - note.push('\n'); - } - note.push_str(&format!("[Output truncated: {omitted} bytes omitted]\n")); - let _ = file.write_all(note.as_bytes()); - } - self.file = Some(file); - } - - fn omitted(&self) -> Option { - (self.omitted > 0).then_some(self.omitted) - } -} - /// The foreground call that outlived its timeout; the shell is occupied /// until its end marker arrives. struct OccupyingTask { task_id: String, output_path: PathBuf, + delivered: usize, ended: Arc, -} - -enum BackgroundKind { - /// A shell job; completion marker arrives over the PTY stream. - Posix, - /// A detached child; completion marker arrives in the result file. - Pwsh { - result_path: PathBuf, - error_path: PathBuf, - }, + _hold: Option, } struct BackgroundTask { task_id: String, output_path: PathBuf, - end_marker: String, - pid: std::io::Result, - kind: BackgroundKind, + _hold: Option, } struct Inner { - pty: Option, + shell: Option, /// Counts spawned shells; a consumer loop serves only its own shell. generation: u64, dialect: ShellDialect, @@ -271,8 +110,6 @@ struct Inner { /// Raw stream tail, for the markers of commands that own no capture: /// initialization, background jobs and their pids. retained: String, - /// The command holding the shell; its capture is fed every chunk. - capture: Option, occupying: Option, background: HashMap, /// Note for the call that was running when the shell exited. @@ -284,20 +121,12 @@ struct Inner { occupy_exit: Option, } -enum Liveness { - Alive, - Dead(Option), - /// A newer shell owns the session state. - Replaced, -} - /// A terminal produced by the reader and its waiting caller. struct Settlement { data: ExecEndedData, ended: Option>, } -/// The persistent shell of one branch. pub struct ShellSession { facts: Option<(Ctx, Key)>, inner: tokio::sync::Mutex, @@ -314,6 +143,8 @@ pub struct ShellSession { /// native storage, where shell output has no owner. owner: Option>, session_id: String, + session_lifecycle: Option>, + recovery: Option>, tasks: Arc>, } @@ -330,14 +161,13 @@ impl ShellSession { Self { facts: None, inner: tokio::sync::Mutex::new(Inner { - pty: None, + shell: None, generation: 0, dialect: ShellDialect::Posix, shell_exe: None, queue: VecDeque::new(), queue_running: false, retained: String::new(), - capture: None, occupying: None, background: HashMap::new(), shell_exit: None, @@ -352,6 +182,8 @@ impl ShellSession { dispatcher, owner, session_id, + session_lifecycle: None, + recovery: None, tasks: Arc::new(tokio::sync::Mutex::new(TaskTracker::new())), } } @@ -452,16 +284,31 @@ impl ShellSession { self: &Arc, queued: &QueuedCommand, ) -> Option> { - let notify = { + let (notify, task_id, output_path) = { let inner = self.inner.lock().await; - inner.occupying.as_ref().map(|task| task.ended.clone())? + let task = inner.occupying.as_ref()?; + ( + task.ended.clone(), + task.task_id.clone(), + task.output_path.clone(), + ) }; - let deadline = tokio::time::Instant::now() + Duration::from_millis(queued.timeout_ms); + let notified = notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + let deadline = + tokio::time::Instant::now() + Duration::from_millis(queued.timeout_ms.min(86_400_000)); let ended = tokio::select! { - _ = notify.notified() => true, + _ = queued.cancel.cancelled() => { + return Some(Err("command cancelled while waiting for the shell".into())); + } + _ = self.lifecycle.cancelled() => { + return Some(Err("shell session closed while waiting for the shell".into())); + } + _ = &mut notified => true, _ = tokio::time::sleep_until(deadline) => false, }; - let mut inner = self.inner.lock().await; + let inner = self.inner.lock().await; if ended || inner.occupying.is_none() { let tail = inner.occupy_tail.clone().unwrap_or_default(); let exit = inner.occupy_exit.clone().unwrap_or_default(); @@ -479,28 +326,76 @@ impl ShellSession { text.push_str("The command was not executed: the shell was occupied. Resend it now."); return Some(Ok(ToolResult::text(text))); } + let delivered = inner.occupying.as_ref().expect("checked above").delivered; + drop(inner); + let page = self + .host + .output(OutputRequest { + task_id: task_id.clone(), + cursor: Some(delivered as u64), + limit: Some(OUTPUT_LIMIT as u64), + }) + .await + .ok(); let mut text = String::new(); - if let Some(capture) = inner.capture.as_mut() { - let delivered = capture.delivered.min(capture.output.len()); - let fresh = capture.output[delivered..].to_owned(); - capture.delivered = capture.output.len(); - if !fresh.is_empty() { - text.push_str(&fresh); - if !fresh.ends_with('\n') { + if let Some(page) = page { + if !page.text.is_empty() { + text.push_str(&page.text); + if !page.text.ends_with('\n') { text.push('\n'); } } + let mut inner = self.inner.lock().await; + if let Some(task) = inner + .occupying + .as_mut() + .filter(|task| task.task_id == task_id) + { + task.delivered = + page.next_cursor + .unwrap_or(task.delivered as u64 + page.bytes) as usize; + } } - let task = inner.occupying.as_mut().expect("checked above"); text.push_str(&format!( "Task {} still occupies the shell. The command was not executed; resend it after the task ends.\nTask ID: {}\nOutput: {}", - task.task_id, - task.task_id, - task.output_path.display() + task_id, + task_id, + output_path.display() )); Some(Ok(ToolResult::text(text))) } + async fn write_shell(&self, bytes: &[u8]) -> Result<(), HostError> { + let inner = self.inner.lock().await; + let Some(task_id) = inner.shell.clone() else { + return Err(HostError::failed("Shell is not running")); + }; + self.host + .write(ShellWrite { + task_id, + data: STANDARD.encode(bytes), + command: None, + job: None, + }) + .await + .map_err(|error| HostError::failed(format!("Shell write failed: {error}"))) + } + + async fn stop_shell(&self, task_id: &str) { + let _ = self + .host + .kill(TaskRequest { + task_id: task_id.to_owned(), + }) + .await; + let _ = self + .host + .settle(TaskRequest { + task_id: task_id.to_owned(), + }) + .await; + } + /// Spawns the shell on first use or after a death. Returns the reset /// note when this spawn replaces a dead shell. async fn ensure_shell(self: &Arc) -> Result, HostError> { @@ -512,7 +407,7 @@ impl ShellSession { if self.lifecycle.is_cancelled() { return Err(HostError::Cancelled("shell session closed".into())); } - if inner.pty.is_some() { + if inner.shell.is_some() { return Ok(None); } inner.generation @@ -524,39 +419,6 @@ impl ShellSession { let inner = self.inner.lock().await; inner.had_reset.then(|| "[shell was reset]".to_owned()) }; - let shell = self.host.persistent_shell().await; - let (exe, dialect) = match shell { - ShellStatus::Available(runtime) => { - 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,86 +428,159 @@ impl ShellSession { } None => vec![self.config.cwd.clone()], }; - let (spec, temporary, _) = self + let runtime = match self.host.persistent_shell().await { + ShellStatus::Available(shell) => shell, + ShellStatus::Unavailable { code, reason } => { + return Err(HostError::failed(format!("{code}: {reason}"))); + } + }; + let id = format!("shell-{}", uuid::Uuid::new_v4()); + let cwd = self + .config + .cwd + .to_str() + .ok_or_else(|| HostError::failed("the shell cwd is not UTF-8"))? + .to_owned(); + let output_dir = self + .config + .output_dir + .to_str() + .ok_or_else(|| HostError::failed("the shell output directory is not UTF-8"))? + .to_owned(); + let roots = roots + .iter() + .map(|root| { + root.to_str() + .map(str::to_owned) + .ok_or_else(|| HostError::failed("a shell workspace root is not UTF-8")) + }) + .collect::, _>>()?; + let reply = self .host - .prepare_isolated_process(spec, &roots, Some(&self.config.output_dir)) + .shell(ShellRequest { + task_id: id.clone(), + cwd: cwd.clone(), + workspace: cwd, + roots, + output_dir, + cols: 500, + rows: 50, + }) .await - .map_err(|error| HostError::failed(format!("{}: {}", error.code, error.reason)))?; - let mut pty = self - .host - .spawn_pty( - spec, - PtySize { - cols: 500, - rows: 50, - }, - ) - .map_err(|e| HostError::failed(e.to_string()))?; - pty.hold(temporary); - let reader = pty.take_reader(); + .map_err(|error| HostError::failed(error.to_string()))?; + let task_id = reply.task_id.clone(); + if let Err(error) = self + .register_output(std::path::Path::new(&reply.output_path)) + .await + { + let _ = self + .host + .kill(TaskRequest { + task_id: task_id.clone(), + }) + .await; + let _ = self + .host + .wait( + WaitRequest { + task_id: task_id.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + let _ = self + .host + .settle(TaskRequest { + task_id: task_id.clone(), + }) + .await; + let _ = std::fs::remove_file(&reply.output_path); + return Err(HostError::failed(error)); + } + let dialect = match runtime.edition { + ShellEdition::Pwsh | ShellEdition::WindowsPowershell => ShellDialect::Pwsh, + _ => ShellDialect::Posix, + }; + let exe = runtime.executable_path; + let task_id = reply.task_id; let generation = { let mut inner = self.inner.lock().await; if self.lifecycle.is_cancelled() { - let _ = pty.terminate().await; + drop(inner); + self.stop_shell(&task_id).await; return Err(HostError::Cancelled("shell session closed".into())); } inner.generation += 1; - inner.shell_exe = Some(exe); + inner.shell_exe = Some(PathBuf::from(exe)); inner.dialect = dialect; inner.shell_exit = None; inner.had_reset = false; inner.occupy_tail = None; inner.occupy_exit = None; - inner.pty = Some(pty); + inner.shell = Some(task_id.clone()); 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(); { let tasks = self.tasks.lock().await; tasks.spawn(async move { - let mut poll = tokio::time::interval(SHELL_EXIT_POLL); - let mut reading = true; + let mut event_cursor = 0u64; + let wait_cancel = lifecycle.clone(); + let cancelled: crate::host::CancelledFn = std::sync::Arc::new(move || { + let cancel = wait_cancel.clone(); + Box::pin(async move { + cancel.cancelled().await; + Ok(()) + }) + }); + let wait = this.host.wait( + WaitRequest { + task_id: task_id.clone(), + timeout_ms: None, + }, + cancelled, + ); + tokio::pin!(wait); loop { tokio::select! { biased; _ = lifecycle.cancelled() => break, - chunk = rx.recv(), if reading => match chunk { - Some(Some(bytes)) => { - this.handle_output(®ularize_output(&bytes)).await; - } - _ => { - reading = false; + page = this.host.shell_events(ShellEventRequest { + task_id: task_id.clone(), + cursor: event_cursor, + wait_ms: 100, + limit: 64 * 1024, + }) => match page { + Ok(page) => { + for event in page.events { + this.handle_event(event).await; + } + event_cursor = page.next_cursor; } + Err(_) => break, }, - _ = poll.tick() => match this.liveness(generation).await { - Liveness::Alive => {} - Liveness::Replaced => break, - Liveness::Dead(status) => { - while let Ok(Some(bytes)) = rx.try_recv() { - this.handle_output(®ularize_output(&bytes)).await; + result = &mut wait => { + let end = result.ok(); + loop { + let page = this.host.shell_events(ShellEventRequest { + task_id: task_id.clone(), + cursor: event_cursor, + wait_ms: 0, + limit: 64 * 1024, + }).await; + let Ok(page) = page else { break }; + if page.events.is_empty() { + break; } - this.handle_shell_exit(generation, status).await; - break; + for event in page.events { + this.handle_event(event).await; + } + event_cursor = page.next_cursor; } + this.handle_shell_exit(generation, end).await; + break; }, } } @@ -701,17 +636,19 @@ impl ShellSession { if inner.retained.contains(&end_marker) { return Ok(()); } - if inner.pty.is_none() { + if inner.shell.is_none() { return Err("shell exited during initialization".into()); } } if tokio::time::Instant::now() >= deadline { let mut inner = self.inner.lock().await; - if let Some(mut pty) = inner.pty.take() { - let _ = pty.terminate().await; - } + let task_id = inner.shell.take(); let captured = inner.retained.clone(); inner.had_reset = true; + drop(inner); + if let Some(task_id) = task_id { + self.stop_shell(&task_id).await; + } return Err(format!( "shell did not initialize; captured output: {captured}" )); @@ -720,167 +657,167 @@ impl ShellSession { } } - /// Starts a command: installs its capture and writes the wrapped line - /// under the same lock, so no chunk of its own output can arrive before - /// the capture that owns it exists. + /// Writes a wrapped command and starts its owner-side capture. async fn start_command( - self: &Arc, - capture: Capture, + &self, + command_id: &str, + start_marker: &str, + end_marker: &str, wrapped: &str, ) -> Result<(), HostError> { - let mut inner = self.inner.lock().await; - let line = format!("{wrapped}\n"); - let Some(pty) = inner.pty.as_mut() else { + let inner = self.inner.lock().await; + let Some(task_id) = inner.shell.clone() else { return Err(HostError::failed("Shell is not running")); }; - pty.write(line.as_bytes()) + let line = format!("{wrapped}\n"); + self.host + .write(ShellWrite { + task_id, + data: STANDARD.encode(line.as_bytes()), + command: Some(ShellCommandStart { + task_id: command_id.to_owned(), + start_marker: start_marker.to_owned(), + end_marker: end_marker.to_owned(), + }), + job: None, + }) + .await .map_err(|e| HostError::failed(format!("Shell write failed: {e}")))?; - inner.capture = Some(capture); Ok(()) } - /// Consumes PTY output: folds it into the retained buffer and the - /// command's capture, settles background tasks whose completion marker - /// arrived (removing the marker from every buffer), and advances the - /// occupying task. A background marker is looked for only in the tail - /// this chunk can have completed, so the scan stays as small as the - /// chunk however far `retained` has grown. - async fn handle_output(self: &Arc, text: &str) { - let mut settled: Vec = Vec::new(); - { - let mut inner = self.inner.lock().await; - inner.retained.push_str(text); - if let Some(capture) = inner.capture.as_mut() { - capture.append(text); - } - let tail = tail_bytes(&inner.retained, text.len() + MARKER_LINE_LIMIT); - let matched: Vec<(String, String)> = inner - .background - .values() - .filter(|task| matches!(task.kind, BackgroundKind::Posix)) - .filter_map(|task| { - marker_code(tail, &task.end_marker).map(|code| (task.task_id.clone(), code)) - }) - .collect(); - for (task_id, code) in matched { - let Some(task) = inner.background.remove(&task_id) else { - continue; - }; - strip_marker(&mut inner.retained, &task.end_marker); - if let Some(capture) = inner.capture.as_mut() { - capture.strip(&task.end_marker); - } - let preview = file_tail(&task.output_path, OUTPUT_LIMIT); - let data = ExecEndedData { - task_id: task.task_id.clone(), - status: exit_status(&code), - result: ended_result(&task.task_id, &task.output_path, &preview, &code), - }; - settled.push(Settlement { data, ended: None }); - } - if inner.retained.len() > RETAINED_BUFFER_TRIM { - inner.retained = tail_bytes(&inner.retained, RETAINED_BUFFER_LIMIT).to_owned(); - } - if let Some(capture) = inner.capture.as_mut() { - capture.drain(); - } - settled.extend(advance_occupying(&mut inner)); - } - for settlement in settled { - self.settle(settlement.data); - if let Some(notify) = settlement.ended { - notify.notify_waiters(); - } + /// Consumes PTY output: folds it into the retained buffer and strips a + /// registered job's end marker. Terminal facts come from the host watcher. + async fn handle_event(self: &Arc, event: ShellEvent) { + match event { + ShellEvent::Output { text, .. } => self.handle_output(&text).await, + ShellEvent::Marker { line, .. } => self.handle_output(&line).await, } } - /// Whether the shell of `generation` still runs. A shell the session - /// terminated itself (its PTY taken) counts as dead. - async fn liveness(&self, generation: u64) -> Liveness { + async fn handle_output(self: &Arc, text: &str) { let mut inner = self.inner.lock().await; - if inner.generation != generation { - return Liveness::Replaced; + inner.retained.push_str(text); + let markers: Vec = inner + .background + .values() + .filter_map(|task| self.host.job_marker(&task.task_id)) + .collect(); + for marker in markers { + strip_marker(&mut inner.retained, &marker); } - 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), - }, + if inner.retained.len() > RETAINED_BUFFER_TRIM { + inner.retained = tail_bytes(&inner.retained, RETAINED_BUFFER_LIMIT).to_owned(); } } - /// The shell of `generation` died: note the exit, settle the occupying - /// task and the POSIX background jobs as failed, and mark the reset for - /// the next call. - async fn handle_shell_exit( - self: &Arc, - generation: u64, - status: Option, - ) { + /// The shell of `generation` died: note the exit, settle each child from + /// the owner terminal when it is available (falling back to the reset + /// result only when the owner has no terminal), and mark the reset. + async fn handle_shell_exit(self: &Arc, generation: u64, end: Option) { let mut settled: Vec = Vec::new(); - let mut orphans: Vec = Vec::new(); + let mut orphans: Vec<(String, PathBuf)> = Vec::new(); + let mut cleanup_unconfirmed = false; + #[allow( + unused_assignments, + reason = "the early generation return leaves the initial value unread" + )] + let mut shell_task = None; { let mut inner = self.inner.lock().await; if inner.generation != generation { return; } - if inner.pty.take().is_some() { - let note = match status { - Some(status) => match status.signal() { - Some(signal) => format!("[shell killed by signal: {signal}]"), - None => format!("[shell exited: code {}]", status.exit_code()), + let task_id = inner.shell.take(); + shell_task = task_id.clone(); + if task_id.is_some() { + let note = match end { + Some(reply) => match (reply.signal.as_deref(), reply.exit_code) { + (Some(signal), _) => format!("[shell killed by signal: {signal}]"), + (_, Some(code)) => format!("[shell exited: code {code}]"), + _ => "[shell exited]".to_owned(), }, None => "[shell exited]".to_owned(), }; inner.shell_exit = Some(note); } inner.had_reset = true; - if let Some(occ) = inner.occupying.take() { - if let Some(mut capture) = inner.capture.take() { - capture.settle(capture.pending.len()); - inner.occupy_tail = Some(capture.output); - } - let preview = file_tail(&occ.output_path, OUTPUT_LIMIT); - let data = ExecEndedData { - task_id: occ.task_id.clone(), - status: ExecStatus::Failed, - result: reset_result(&occ.task_id, &occ.output_path, &preview), - }; - inner.occupy_exit = None; - settled.push(Settlement { - data, - ended: Some(occ.ended), - }); - } if inner.dialect == ShellDialect::Posix { - orphans = inner.background.drain().map(|(_, task)| task).collect(); + orphans = inner + .background + .iter() + .map(|(id, task)| (id.clone(), task.output_path.clone())) + .collect(); } } - for task in orphans { - let killed = match task.pid { - Ok(pid) => kill_job(pid).await, - Err(error) => Err(error), - }; - let preview = file_tail(&task.output_path, OUTPUT_LIMIT); - let mut result = reset_result(&task.task_id, &task.output_path, &preview); + for (task_id, output_path) in orphans { + let killed = self + .host + .kill(TaskRequest { + task_id: task_id.clone(), + }) + .await + .map_err(|error| std::io::Error::other(error.to_string())); + let reply = self + .host + .wait( + WaitRequest { + task_id: task_id.clone(), + timeout_ms: Some(2_000), + }, + never_cancelled(), + ) + .await + .ok(); + if reply + .as_ref() + .is_none_or(|reply| reply.status == WaitStatus::Running) + { + cleanup_unconfirmed = true; + continue; + } + let removed = self + .inner + .lock() + .await + .background + .remove(&task_id) + .is_some(); + if !removed { + continue; + } + let reply = reply.expect("checked above"); + if killed.is_ok() { + let _ = self + .host + .settle(TaskRequest { + task_id: task_id.clone(), + }) + .await; + } + let mut data = ended_from_reply(&task_id, &reply, &output_path); if let Err(error) = killed { - if let ToolContent::Text(text) = &mut result.content { + cleanup_unconfirmed = true; + if let ToolContent::Text(text) = &mut data.result.content { text.push_str(&format!("\nJob could not be terminated: {error}")); } - if let Some(fields) = result.structured_content.as_mut() { + if let Some(fields) = data.result.structured_content.as_mut() { fields.insert("code".into(), "exec_terminate_failed".into()); } } - settled.push(Settlement { - data: ExecEndedData { - task_id: task.task_id.clone(), - status: ExecStatus::Failed, - result, - }, - ended: None, - }); + settled.push(Settlement { data, ended: None }); + } + if let Some(task_id) = shell_task { + if cleanup_unconfirmed { + let _ = self + .host + .kill(TaskRequest { + task_id: task_id.clone(), + }) + .await; + } else { + self.stop_shell(&task_id).await; + } } for settlement in settled { self.settle(settlement.data); @@ -894,9 +831,8 @@ impl ShellSession { let _ = self.timeline.append(EventKind::ExecEnded(data).into()); } - /// One foreground call: install its capture, send the wrapped command, - /// poll the capture for its end marker, convert to an occupying task on - /// timeout. + /// One foreground call: start its owner-side capture, wait for the + /// terminal record, and convert a timeout into an occupying task. async fn run_foreground( self: &Arc, command: &str, @@ -915,122 +851,233 @@ impl ShellSession { ShellDialect::Posix => posix_command(command, &start, &end), ShellDialect::Pwsh => pwsh_command(command, &start, &end), }; - let capture = Capture::new(start_marker, end_marker); - self.start_command(capture, &wrapped) + let command_id = format!("exec-{}", uuid::Uuid::new_v4().simple()); + let output_path = self.config.output_dir.join(format!("{command_id}.log")); + self.register_output(&output_path).await?; + self.start_command(&command_id, &start_marker, &end_marker, &wrapped) .await .map_err(|e| e.to_string())?; - let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout_ms); - loop { - { - let mut inner = self.inner.lock().await; - if inner.pty.is_none() { - let note = inner - .shell_exit - .clone() - .unwrap_or_else(|| "[shell exited]".into()); - let mut text = String::new(); - if let Some(mut capture) = inner.capture.take() { - capture.settle(capture.pending.len()); - push_output(&mut text, &capture.output); - if let Some(omitted) = capture.omitted() { - text.push_str(&format!( - "\n[Output truncated: {omitted} bytes omitted]" - )); - } - } - text.push_str(¬e); - let mut result = ToolResult::text(text); - result.is_error = Some(true); - return Ok(ran(result, command, None)); - } - if let Some(code) = inner - .capture - .as_ref() - .and_then(|capture| capture.code.clone()) + let cancel_token = cancel.clone(); + let cancelled: crate::host::CancelledFn = Arc::new(move || { + let cancel = cancel_token.clone(); + Box::pin(async move { + cancel.cancelled().await; + Ok(()) + }) + }); + match self + .host + .wait( + WaitRequest { + task_id: command_id.clone(), + timeout_ms: Some(timeout_ms), + }, + cancelled, + ) + .await + { + Ok(reply) if reply.status != WaitStatus::Running => { + if reply.status == WaitStatus::Failed + && reply.exit_code.is_none() + && reply.signal.is_none() { - let capture = inner.capture.take().expect("capture present"); - let mut text = String::new(); - push_output(&mut text, &capture.output); - text.push_str(&exit_line(&code)); - if let Some(omitted) = capture.omitted() { - text.push_str(&format!("\n[Output truncated: {omitted} bytes omitted]")); + let note = match reply.failure_note.clone() { + Some(note) => Some(note), + None => { + let shell_id = self.inner.lock().await.shell.clone(); + let terminal = shell_id + .as_ref() + .and_then(|id| self.host.task(id)) + .and_then(|record| record.terminal()); + terminal + .map(|terminal| shell_exit_note(&terminal)) + .or_else(|| { + self.inner + .try_lock() + .ok() + .and_then(|inner| inner.shell_exit.clone()) + }) + } + }; + if let Some(note) = note { + let mut result = ToolResult::text(note); + result.is_error = Some(true); + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.clone(), + }) + .await; + return Ok(ran(result, command, None)); } - let mut result = ToolResult::text(text); - result.is_error = (code != "0").then_some(true); - return Ok(ran(result, command, code.parse().ok())); } + let text = self.command_result_text(&command_id, &reply).await; + let mut result = ToolResult::text(text); + result.is_error = (reply.exit_code != Some(0)).then_some(true); + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.clone(), + }) + .await; + Ok(ran(result, command, reply.exit_code)) } - if tokio::time::Instant::now() >= deadline { + Ok(_) => { if self.config.member { - return self - .interrupt() + self.interrupt(&command_id) .await - .map(|result| ran(result, command, None)); - } - return self - .occupy_current(command, context) - .await - .map(|result| ran(result, command, None)); - } - tokio::select! { - _ = cancel.cancelled() => { - return self - .interrupt() + .map(|result| ran(result, command, None)) + } else { + self.occupy_current(command, &command_id, &output_path, context) .await - .map(|result| ran(result, command, None)); + .map(|result| ran(result, command, None)) } - _ = tokio::time::sleep(Duration::from_millis(10)) => {} + } + Err(HostPlatformError::Cancelled) => self + .interrupt(&command_id) + .await + .map(|result| ran(result, command, None)), + Err(_) => { + let note = self + .inner + .lock() + .await + .shell_exit + .clone() + .unwrap_or_else(|| "[shell exited]".into()); + let mut result = ToolResult::text(note); + result.is_error = Some(true); + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.clone(), + }) + .await; + Ok(ran(result, command, None)) } } } - /// Turn stop and member timeout: Ctrl+C, bounded marker wait; without - /// the marker the shell tree is terminated and the session resets. - async fn interrupt(self: &Arc) -> Result { + async fn command_result_text(&self, command_id: &str, reply: &WaitReply) -> String { + let mut text = String::new(); + if let Ok(page) = self + .host + .output(OutputRequest { + task_id: command_id.to_owned(), + cursor: None, + limit: Some(OUTPUT_LIMIT as u64), + }) + .await { - let mut inner = self.inner.lock().await; - if let Some(pty) = inner.pty.as_mut() { - let _ = pty.write(b"\x03"); + push_output(&mut text, &page.text); + } + if let Some(signal) = &reply.signal { + text.push_str(&format!("[Command terminated by signal {signal}]")); + } else { + text.push_str(&exit_line( + &reply + .exit_code + .map(|code| code.to_string()) + .unwrap_or_else(|| "unknown".into()), + )); + } + if reply.output_truncated { + text.push_str(&format!( + "\n[Output truncated: {} bytes omitted]", + reply + .output_bytes + .saturating_sub((OUTPUT_LIMIT as u64).min(reply.output_bytes)) + )); + } + text + } + + /// Turn stop and member timeout: Ctrl+C, bounded wait; without the + /// terminal record the shell tree is terminated and the session resets. + async fn interrupt(self: &Arc, command_id: &str) -> Result { + { + let inner = self.inner.lock().await; + if inner.shell.is_some() { + drop(inner); + let _ = self.write_shell(b"\x03").await; } } let deadline = tokio::time::Instant::now() + STOP_WAIT; + let never = CancellationToken::new(); + let cancelled: crate::host::CancelledFn = Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }); loop { + if self.inner.lock().await.shell.is_none() { + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.to_owned(), + }) + .await; + return Ok(ToolResult::error( + "[Command interrupted; the shell exited and will be reset]", + )); + } + match self + .host + .wait( + WaitRequest { + task_id: command_id.to_owned(), + timeout_ms: Some(10), + }, + cancelled.clone(), + ) + .await { - let mut inner = self.inner.lock().await; - if inner.pty.is_none() { - inner.capture = None; - return Ok(ToolResult::error( - "[Command interrupted; the shell exited and will be reset]", - )); - } - if inner - .capture - .as_ref() - .is_some_and(|capture| capture.code.is_some()) - { - let capture = inner.capture.take().expect("capture present"); + Ok(reply) if reply.status != WaitStatus::Running => { let mut text = String::new(); - push_output(&mut text, &capture.output); - text.push_str("[Command interrupted]"); - if let Some(omitted) = capture.omitted() { - text.push_str(&format!("\n[Output truncated: {omitted} bytes omitted]")); + if let Ok(page) = self + .host + .output(OutputRequest { + task_id: command_id.to_owned(), + cursor: None, + limit: Some(OUTPUT_LIMIT as u64), + }) + .await + { + push_output(&mut text, &page.text); } + text.push_str("[Command interrupted]"); + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.to_owned(), + }) + .await; return Ok(ToolResult::error(text)); } + Ok(_) => {} + Err(_) => {} } if tokio::time::Instant::now() >= deadline { let mut inner = self.inner.lock().await; - inner.capture = None; - if let Some(mut pty) = inner.pty.take() { - let _ = pty.terminate().await; - } + let task_id = inner.shell.take(); inner.shell_exit = Some("[shell was terminated]".into()); inner.had_reset = true; + drop(inner); + if let Some(task_id) = task_id { + self.stop_shell(&task_id).await; + } + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.to_owned(), + }) + .await; return Ok(ToolResult::error( "[Command interrupted; the shell was terminated and reset]", )); } - tokio::time::sleep(Duration::from_millis(10)).await; } } @@ -1055,19 +1102,49 @@ impl ShellSession { } /// Registers the running command as the occupying task and reports it. - /// The capture becomes the task's output as it stands: a start marker - /// that arrives later is still dropped, and a settled end marker still - /// settles the task. async fn occupy_current( self: &Arc, command: &str, + command_id: &str, + output_path: &Path, context: &CallContext, ) -> Result { - let task_id = format!("exec-{}", uuid::Uuid::new_v4().simple()); - let output_path = self.config.output_dir.join(format!("{task_id}.log")); - self.register_output(&output_path).await?; let description = describe(command); - let (preview, omitted, settled) = { + let never = CancellationToken::new(); + let cancelled: crate::host::CancelledFn = Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }); + let reply = self + .host + .wait( + WaitRequest { + task_id: command_id.to_owned(), + timeout_ms: Some(0), + }, + cancelled, + ) + .await + .ok(); + let page = self + .host + .output(OutputRequest { + task_id: command_id.to_owned(), + cursor: None, + limit: Some(OUTPUT_LIMIT as u64), + }) + .await + .ok(); + let preview = page + .as_ref() + .map(|page| page.text.clone()) + .unwrap_or_default(); + let omitted = reply.as_ref().is_some_and(|reply| reply.output_truncated) + || page.as_ref().is_some_and(|page| page.truncated); + { let mut inner = self.inner.lock().await; if self.lifecycle.is_cancelled() { return Err("shell session closed".into()); @@ -1078,47 +1155,108 @@ impl ShellSession { turn_id: context.turn_id.clone(), request_id: context.request_id.clone(), call_id: context.call_id.clone(), - task_id: task_id.clone(), - description: description.clone(), + task_id: command_id.to_owned(), + description, title: None, output_path: output_path.to_string_lossy().into_owned(), }) .into(), ) .map_err(|error| error.to_string())?; - let (preview, omitted) = match inner.capture.as_mut() { - Some(capture) => { - capture.bind(&output_path); - capture.delivered = capture.output.len(); - (capture.output.clone(), capture.omitted()) - } - None => (String::new(), None), - }; + let hold = self + .session_lifecycle + .as_ref() + .and_then(|lifecycle| lifecycle.take_hold()); inner.occupy_tail = None; inner.occupy_exit = None; inner.occupying = Some(OccupyingTask { - task_id: task_id.clone(), - output_path: output_path.clone(), + task_id: command_id.to_owned(), + output_path: output_path.to_path_buf(), + delivered: preview.len(), ended: Arc::new(Notify::new()), + _hold: hold, }); - (preview, omitted, advance_occupying(&mut inner)) - }; - if let Some(settled) = settled { - self.settle(settled.data); } + let ended = { + let inner = self.inner.lock().await; + inner + .occupying + .as_ref() + .expect("just installed") + .ended + .clone() + }; + let this = self.clone(); + let id = command_id.to_owned(); + let path = output_path.to_path_buf(); + let tasks = self.tasks.lock().await; + tasks.spawn(async move { + let reply = this + .host + .wait( + WaitRequest { + task_id: id.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + let (result, status, preview, exit) = match reply { + Ok(reply) => { + let code = wait_code(&reply); + ( + ended_result(&id, &path, &reply.preview, &code), + exit_status(&code), + reply.preview.clone(), + exit_line(&code), + ) + } + Err(_) => ( + reset_result(&id, &path, ""), + ExecStatus::Failed, + String::new(), + "[Task failed: shell was reset]".to_owned(), + ), + }; + let published = { + let mut inner = this.inner.lock().await; + if inner + .occupying + .as_ref() + .is_some_and(|task| task.task_id == id) + { + inner.occupy_tail = Some(preview); + inner.occupy_exit = Some(exit); + inner.occupying = None; + true + } else { + false + } + }; + if !published { + return; + } + this.settle(ExecEndedData { + task_id: id.clone(), + status, + result, + }); + let _ = this.host.settle(TaskRequest { task_id: id }).await; + ended.notify_waiters(); + }); let mut text = String::new(); push_output(&mut text, &preview); - if let Some(omitted) = omitted { - text.push_str(&format!("[Output truncated: {omitted} bytes omitted]\n")); + if omitted { + text.push_str("[Output truncated]\n"); } text.push_str(&format!( - "Command is still running and occupies the shell.\nTask ID: {task_id}\nOutput: {}", + "Command is still running and occupies the shell.\nTask ID: {command_id}\nOutput: {}", output_path.display() )); let mut result = ToolResult::text(text); result.structured_content = Some(structured(json!({ "type": "started", - "taskId": task_id, + "taskId": command_id, "outputPath": output_path.to_string_lossy(), }))); Ok(result) @@ -1132,6 +1270,10 @@ impl ShellSession { ) -> Result { let task_id = format!("exec-{}", uuid::Uuid::new_v4().simple()); let output_path = self.config.output_dir.join(format!("{task_id}.log")); + let output_path_text = output_path + .to_str() + .ok_or_else(|| "the job output path is not UTF-8".to_owned())? + .to_owned(); self.register_output(&output_path).await?; let completion = marker_pair().1; let pid_marker = marker_pair().1; @@ -1140,10 +1282,10 @@ impl ShellSession { let inner = self.inner.lock().await; inner.dialect }; - let (wrapped, kind) = match dialect { + let (wrapped, pwsh_paths) = match dialect { ShellDialect::Posix => ( posix_background(command, &output_path, &completion, &pid_marker), - BackgroundKind::Posix, + None, ), ShellDialect::Pwsh => { let shell = { @@ -1163,20 +1305,10 @@ impl ShellSession { &completion, &pid_marker, ), - BackgroundKind::Pwsh { - result_path: result_path.clone(), - error_path: error_path.clone(), - }, + Some((result_path, error_path)), ) } }; - let pwsh_paths = match &kind { - BackgroundKind::Pwsh { - result_path, - error_path, - } => Some((result_path.clone(), error_path.clone())), - BackgroundKind::Posix => None, - }; { let mut inner = self.inner.lock().await; if self.lifecycle.is_cancelled() { @@ -1191,23 +1323,35 @@ impl ShellSession { task_id: task_id.clone(), description: description.clone(), title: None, - output_path: output_path.to_string_lossy().into_owned(), + output_path: output_path_text.clone(), }) .into(), ) .map_err(|error| error.to_string())?; + let hold = self + .session_lifecycle + .as_ref() + .and_then(|lifecycle| lifecycle.take_hold()); inner.background.insert( task_id.clone(), BackgroundTask { task_id: task_id.clone(), output_path: output_path.clone(), - end_marker: completion.full(), - pid: Err(std::io::Error::other("the job pid was not reported")), - kind, + _hold: hold, }, ); } - if let Err(error) = self.write_line(&wrapped).await { + if let Err(error) = self + .write_line_job( + &wrapped, + ShellJobStart { + task_id: task_id.clone(), + end_marker: completion.full(), + output_path: output_path_text, + }, + ) + .await + { let task = self.inner.lock().await.background.remove(&task_id); if task.is_some() { self.settle(ExecEndedData { @@ -1218,77 +1362,46 @@ impl ShellSession { } return Err(error.to_string()); } - let pid_marker_full = pid_marker.full(); - let deadline = tokio::time::Instant::now() + PID_WAIT; - while tokio::time::Instant::now() < deadline { - let found = { - let inner = self.inner.lock().await; - marker_code(&inner.retained, &pid_marker_full) - }; - if let Some(code) = found { - let mut inner = self.inner.lock().await; - let Inner { - 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) - }); + let error_path = pwsh_paths.as_ref().map(|(_, error)| error.clone()); + let this = self.clone(); + let host = self.host.clone(); + let watched = task_id.clone(); + let watched_output = output_path.clone(); + self.tasks.lock().await.spawn(async move { + let reply = host + .wait( + WaitRequest { + task_id: watched.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + if let Ok(reply) = reply { + if this + .inner + .lock() + .await + .background + .remove(&watched) + .is_none() + { + return; } - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - if let Some((result_path, error_path)) = pwsh_paths { - let this = self.clone(); - let lifecycle = self.lifecycle.clone(); - let marker = completion.full(); - let watched = task_id.clone(); - let output_path = output_path.clone(); - let tasks = self.tasks.lock().await; - tasks.spawn(async move { - loop { - tokio::select! { - _ = lifecycle.cancelled() => return, - _ = tokio::time::sleep(PWSH_FILE_POLL) => {} - } - let finished = { - let inner = this.inner.lock().await; - match inner.background.get(&watched) { - None => return, - Some(_) => std::fs::read_to_string(&result_path) - .ok() - .and_then(|text| marker_code(&text, &marker)), - } - }; - if let Some(code) = finished { - let task_id = watched.clone(); - let mut inner = this.inner.lock().await; - inner.background.remove(&task_id); - drop(inner); - let preview = file_tail(&output_path, OUTPUT_LIMIT); - let mut result = ended_result(&task_id, &output_path, &preview, &code); - if let ToolContent::Text(text) = &mut result.content { - text.push_str(&format!("\nStandard error: {}", error_path.display())); - } - let data = ExecEndedData { - task_id: task_id.clone(), - status: exit_status(&code), - result, - }; - this.settle(data); - return; - } + let _ = host + .settle(TaskRequest { + task_id: watched.clone(), + }) + .await; + let mut data = ended_from_reply(&watched, &reply, &watched_output); + if let Some(error_path) = &error_path + && let ToolContent::Text(text) = &mut data.result.content + { + text.push_str(&format!("\nStandard error: {}", error_path.display())); } - }); - } + this.settle(data); + } + }); let mut result = ToolResult::text(format!( "Background command started.\nTask ID: {task_id}\nOutput: {}", output_path.display() @@ -1302,7 +1415,7 @@ impl ShellSession { } /// Stops a task by id. - pub async fn stop(&self, task_id: &str) -> Result { + pub async fn stop(self: &Arc, task_id: &str) -> Result { let occupying = { let mut inner = self.inner.lock().await; if inner @@ -1317,49 +1430,64 @@ impl ShellSession { }; if let Some(occ) = occupying { { - let mut inner = self.inner.lock().await; - if let Some(capture) = inner.capture.as_mut() { - capture.settle(capture.pending.len()); - } - if let Some(pty) = inner.pty.as_mut() { - let _ = pty.write(b"\x03"); - } - } - let deadline = tokio::time::Instant::now() + STOP_WAIT; - let mut found = false; - loop { - let state = { - let inner = self.inner.lock().await; - ( - inner.pty.is_none(), - inner - .capture - .as_ref() - .is_some_and(|capture| capture.code.is_some()), - ) - }; - if state.0 || state.1 { - found = state.1; - break; - } - if tokio::time::Instant::now() >= deadline { - break; + let inner = self.inner.lock().await; + if inner.shell.is_some() { + drop(inner); + let _ = self.write_shell(b"\x03").await; } - tokio::time::sleep(Duration::from_millis(10)).await; } + let never = CancellationToken::new(); + let cancelled: crate::host::CancelledFn = Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }); + let reply = self + .host + .wait( + WaitRequest { + task_id: task_id.to_owned(), + timeout_ms: Some(STOP_WAIT.as_millis() as u64), + }, + cancelled, + ) + .await + .ok(); + let found = reply + .as_ref() + .is_some_and(|reply| reply.status != WaitStatus::Running); + let page = self + .host + .output(OutputRequest { + task_id: task_id.to_owned(), + cursor: None, + limit: Some(OUTPUT_LIMIT as u64), + }) + .await + .ok(); + let preview = page.map(|page| page.text).unwrap_or_default(); { let mut inner = self.inner.lock().await; - if let Some(capture) = inner.capture.take() { - inner.occupy_tail = Some(capture.output); - } + inner.occupy_tail = Some(preview); + inner.occupy_exit = None; if !found { - if let Some(mut pty) = inner.pty.take() { - let _ = pty.terminate().await; - } + let shell = inner.shell.take(); inner.shell_exit = Some("[shell was terminated]".into()); inner.had_reset = true; + drop(inner); + if let Some(shell) = shell { + self.stop_shell(&shell).await; + } } } + let _ = self + .host + .settle(TaskRequest { + task_id: task_id.to_owned(), + }) + .await; let data = ExecEndedData { task_id: task_id.to_owned(), status: ExecStatus::Cancelled, @@ -1374,16 +1502,89 @@ impl ShellSession { inner.background.remove(task_id) }; if let Some(task) = task { - let terminated = match task.pid { - Ok(pid) => stop_job(pid).await, - Err(error) => Err(error), - }; - let data = match terminated { - Ok(()) => ExecEndedData { - task_id: task_id.to_owned(), + let killed = self + .host + .kill(TaskRequest { + task_id: task.task_id.clone(), + }) + .await; + if matches!(killed, Err(HostPlatformError::TaskRunning)) { + let task_id = task.task_id.clone(); + let output_path = task.output_path.clone(); + self.inner + .lock() + .await + .background + .insert(task_id.clone(), task); + let this = self.clone(); + let host = self.host.clone(); + let watched = task_id.clone(); + self.tasks.lock().await.spawn(async move { + let reply = host + .wait( + WaitRequest { + task_id: watched.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + if let Ok(reply) = reply { + if this + .inner + .lock() + .await + .background + .remove(&watched) + .is_none() + { + return; + } + let _ = host + .settle(TaskRequest { + task_id: watched.clone(), + }) + .await; + this.settle(ended_from_reply(&watched, &reply, &output_path)); + } + }); + return Ok(ExecEndedData { + task_id, status: ExecStatus::Cancelled, - result: ToolResult::text("Background command stopped."), - }, + result: ToolResult::text( + "Background command stop requested; it will end after it starts.", + ), + }); + } + let kill_failed = killed.is_err(); + let data = match killed { + Ok(()) => { + let reply = self + .host + .wait( + WaitRequest { + task_id: task.task_id.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .ok(); + let _ = self + .host + .settle(TaskRequest { + task_id: task.task_id.clone(), + }) + .await; + reply.map_or_else( + || ExecEndedData { + task_id: task_id.to_owned(), + status: ExecStatus::Cancelled, + result: ToolResult::text("Background command stopped."), + }, + |reply| ended_from_reply(task_id, &reply, &task.output_path), + ) + } Err(error) => { let mut result = ToolResult::error(format!( "Background command could not be terminated: {error}\nOutput: {}", @@ -1401,6 +1602,47 @@ impl ShellSession { } } }; + if kill_failed { + let watched = task.task_id.clone(); + let output_path = task.output_path.clone(); + self.inner + .lock() + .await + .background + .insert(watched.clone(), task); + let this = self.clone(); + let host = self.host.clone(); + self.tasks.lock().await.spawn(async move { + let reply = host + .wait( + WaitRequest { + task_id: watched.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + if let Ok(reply) = reply { + if this + .inner + .lock() + .await + .background + .remove(&watched) + .is_none() + { + return; + } + let _ = host + .settle(TaskRequest { + task_id: watched.clone(), + }) + .await; + this.settle(ended_from_reply(&watched, &reply, &output_path)); + } + }); + return Ok(data); + } self.settle(data.clone()); return Ok(data); } @@ -1408,12 +1650,23 @@ impl ShellSession { } async fn write_line(&self, line: &str) -> Result<(), HostError> { - let mut inner = self.inner.lock().await; - let Some(pty) = inner.pty.as_mut() else { + self.write_shell(format!("{line}\n").as_bytes()).await + } + + async fn write_line_job(&self, line: &str, job: ShellJobStart) -> Result<(), HostError> { + let inner = self.inner.lock().await; + let Some(task_id) = inner.shell.clone() else { return Err(HostError::failed("Shell is not running")); }; - pty.write(format!("{line}\n").as_bytes()) - .map_err(|e| HostError::failed(format!("Shell write failed: {e}"))) + self.host + .write(ShellWrite { + task_id, + data: STANDARD.encode(format!("{line}\n").as_bytes()), + command: None, + job: Some(job), + }) + .await + .map_err(|error| HostError::failed(format!("Shell write failed: {error}"))) } } @@ -1422,31 +1675,26 @@ impl ExecStop for ShellSession { self: Arc, task_id: String, ) -> BoxFuture<'static, Result> { - Box::pin(async move { ShellSession::stop(&self, &task_id).await }) + Box::pin(async move { + match ShellSession::stop(&self, &task_id).await { + Err(TaskError::Unknown) => match &self.recovery { + Some(recovery) => recovery.stop(task_id).await.map_err(|error| match error { + crate::workspace_tools::background::TaskError::Closed => TaskError::Closed, + crate::workspace_tools::background::TaskError::Unknown => { + TaskError::Unknown + } + crate::workspace_tools::background::TaskError::Read(_) => TaskError::Read, + }), + None => Err(TaskError::Unknown), + }, + other => other, + } + }) } } /// Settles the occupying task once its capture saw a complete end marker /// line, taking the capture with it. -fn advance_occupying(inner: &mut Inner) -> Option { - let code = inner.capture.as_ref()?.code.clone()?; - let occ = inner.occupying.take()?; - let capture = inner.capture.take(); - let preview = file_tail(&occ.output_path, OUTPUT_LIMIT); - if let Some(capture) = &capture { - inner.occupy_tail = Some(capture.output.clone()); - } - inner.occupy_exit = Some(exit_line(&code)); - Some(Settlement { - data: ExecEndedData { - task_id: occ.task_id.clone(), - status: exit_status(&code), - result: ended_result(&occ.task_id, &occ.output_path, &preview, &code), - }, - ended: Some(occ.ended), - }) -} - /// The plugin. pub struct ShellSessionPlugin { recovery: Key, @@ -1458,6 +1706,7 @@ pub struct ShellSessionPlugin { host: Key, lifecycle: Key, session_config: Key, + session_lifecycle: Key, identity: Key, config: Option, } @@ -1482,6 +1731,7 @@ impl ShellSessionPlugin { host: names.key()?, lifecycle: names.key()?, session_config: names.key()?, + session_lifecycle: names.key()?, identity: names.key()?, config: None, }) @@ -1500,6 +1750,7 @@ impl DynPlugin for ShellSessionPlugin { self.host.erase(), self.lifecycle.erase(), self.session_config.erase(), + self.session_lifecycle.erase(), self.identity.erase(), ] } @@ -1508,7 +1759,9 @@ impl DynPlugin for ShellSessionPlugin { let timeline = ctx.require_at(&self.timeline)?; let dispatcher = ctx.require_at(&self.dispatcher)?; let host = ctx.require_at(&self.host)?; + let recovery = ctx.require_at(&self.recovery)?; let config = ctx.require_at(&self.session_config)?; + let session_lifecycle = ctx.require_at(&self.session_lifecycle)?; let identity = ctx.require_at(&self.identity)?; let owner = ctx.get::(); let mut session = ShellSession::new( @@ -1529,18 +1782,22 @@ impl DynPlugin for ShellSessionPlugin { identity.session_id.clone(), ); session.facts = Some((ctx.clone(), self.facts.clone())); + session.recovery = Some(recovery); + session.session_lifecycle = Some(session_lifecycle); let session = Arc::new(session); let service = session.clone(); ctx.effect(move || async move { service.lifecycle.cancel(); { let mut inner = service.inner.lock().await; - if let Some(mut pty) = inner.pty.take() { - let _ = pty.terminate().await; - } + let task_id = inner.shell.take(); for queued in inner.queue.drain(..) { let _ = queued.done.send(Err("shell session closed".into())); } + drop(inner); + if let Some(task_id) = task_id { + service.stop_shell(&task_id).await; + } } let tasks = service.tasks.lock().await.clone(); tasks.close(); @@ -1567,13 +1824,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. @@ -1612,39 +1862,79 @@ fn push_output(text: &mut String, output: &str) { } } -fn file_tail(path: &Path, limit: usize) -> String { - std::fs::read(path) - .map(|bytes| tail_bytes(&String::from_utf8_lossy(&bytes), limit).to_owned()) - .unwrap_or_default() -} - -/// The token on the line of the last `marker` once that line is complete: -/// exit digits, pwsh `failed`, or a job pid. A malformed token reads as -/// `unknown`. -fn marker_code(text: &str, marker: &str) -> Option { - let rest = &text[text.rfind(marker)? + marker.len()..]; - let token = rest[..rest.find('\n')?].trim(); - let valid = !token.is_empty() - && token.len() <= 12 - && token.chars().all(|ch| ch.is_ascii_alphanumeric()); - Some(if valid { token } else { "unknown" }.to_owned()) -} - fn exit_status(code: &str) -> ExecStatus { match code { "0" => ExecStatus::Completed, + "cancelled" => ExecStatus::Cancelled, _ => ExecStatus::Failed, } } +fn wait_code(reply: &WaitReply) -> String { + if reply.status == WaitStatus::Cancelled { + "cancelled".to_owned() + } else { + reply + .exit_code + .map(|code| code.to_string()) + .or_else(|| reply.signal.clone()) + .unwrap_or_else(|| "failed".to_owned()) + } +} + +fn never_cancelled() -> crate::host::CancelledFn { + let never = CancellationToken::new(); + std::sync::Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }) +} + fn exit_line(code: &str) -> String { match code { "failed" => "[Command failed]".to_owned(), + "cancelled" => "[Command cancelled]".to_owned(), "unknown" => "[Command finished with unknown exit code]".to_owned(), code => format!("[Command finished with exit code {code}]"), } } +fn ended_from_reply(task_id: &str, reply: &WaitReply, output_path: &Path) -> ExecEndedData { + let code = wait_code(reply); + let mut result = if matches!( + reply.failure, + Some( + crate::host_platform::TaskFailure::ShellReset + | crate::host_platform::TaskFailure::ShellExited + ) + ) { + reset_result(task_id, output_path, &reply.preview) + } else { + ended_result(task_id, output_path, &reply.preview, &code) + }; + if let Some(failure) = &reply.failure + && let ToolContent::Text(text) = &mut result.content + { + text.push('\n'); + text.push_str(&failure.to_string()); + } + let status = match reply.status { + WaitStatus::Exited if reply.exit_code == Some(0) && reply.failure.is_none() => { + ExecStatus::Completed + } + WaitStatus::Cancelled => ExecStatus::Cancelled, + _ => ExecStatus::Failed, + }; + ExecEndedData { + task_id: task_id.to_owned(), + status, + result, + } +} + fn ended_result(task_id: &str, output_path: &Path, preview: &str, code: &str) -> ToolResult { let status = exit_status(code); let label = match status { @@ -1668,6 +1958,14 @@ fn ended_result(task_id: &str, output_path: &Path, preview: &str, code: &str) -> result } +fn shell_exit_note(terminal: &crate::host_platform::Terminal) -> String { + match (terminal.signal.as_deref(), terminal.exit_code) { + (Some(signal), _) => format!("[shell killed by signal: {signal}]"), + (_, Some(code)) => format!("[shell exited: code {code}]"), + _ => "[shell exited]".to_owned(), + } +} + /// A shell death settles open tasks as failed with a reset note. fn reset_result(task_id: &str, output_path: &Path, preview: &str) -> ToolResult { let mut text = preview.to_owned(); @@ -1696,40 +1994,34 @@ fn strip_marker(text: &mut String, marker: &str) { } } -/// Where the pending tail that may still become a marker starts. -/// -/// A tail is held only while it is still short enough to become one, so -/// output that merely starts with `__DIM_` cannot keep the rest of an -/// arbitrarily long line out of the log. -fn marker_hold(text: &str) -> usize { - const PREFIX: &str = "__DIM_"; - if let Some(pos) = text.rfind(PREFIX) - && !text[pos..].contains('\n') - { - return if text.len() - pos <= MARKER_LINE_LIMIT { - pos - } else { - text.len() - }; - } - (1..PREFIX.len()) - .rev() - .find(|len| text.ends_with(&PREFIX[..*len])) - .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(); while let Some(ch) = chars.next() { if ch == '\x1b' { - while let Some(&next) = chars.peek() { - if next.is_ascii_alphabetic() || next == '[' { + match chars.peek().copied() { + Some('[') => { chars.next(); - break; + for next in chars.by_ref() { + if next.is_ascii_alphabetic() { + break; + } + } } - chars.next(); + Some(']') => { + chars.next(); + for next in chars.by_ref() { + if next == '\x07' { + break; + } + } + } + Some('(' | ')' | '*' | '+' | '-' | '.' | '/') => { + chars.next(); + chars.next(); + } + _ => {} } } else if ch == '\r' { if chars.peek() == Some(&'\n') { @@ -1829,14 +2121,19 @@ fn posix_background( completion: &MarkerPair, pid: &MarkerPair, ) -> String { + let task_id = output_path + .file_stem() + .and_then(|name| name.to_str()) + .unwrap_or_default(); format!( - "{{ {{ eval $'{}'; }} > '{}' 2>&1; printf '%s%s%d\\n' '{}' '{}' \"$?\"; }} & disown\nprintf '%s%s%d\\n' '{}' '{}' \"$!\"", + "{{ {{ eval $'{}'; }} > '{}' 2>&1; printf '%s%s%d\\n' '{}' '{}' \"$?\"; }} & disown\nprintf '%s%s%d %s\\n' '{}' '{}' \"$!\" '{}'", posix_escape(command), output_path.display(), completion.first(), completion.second(), pid.first(), pid.second(), + task_id, ) } @@ -1864,6 +2161,10 @@ fn pwsh_background( completion: &MarkerPair, pid: &MarkerPair, ) -> String { + let task_id = output_path + .file_stem() + .and_then(|name| name.to_str()) + .unwrap_or_default(); let encoded = base64_encode(command); let mut out = String::new(); out.push_str("$__dim_p = Start-Process -FilePath '"); @@ -1889,7 +2190,9 @@ fn pwsh_background( out.push_str(pid.first()); out.push_str("' + '"); out.push_str(pid.second()); - out.push_str("' + $__dim_p.Id)"); + out.push_str("' + $__dim_p.Id + ' ' + '"); + out.push_str(task_id); + out.push_str("')"); out } @@ -1897,155 +2200,3 @@ fn base64_encode(data: &str) -> String { use base64::Engine; base64::engine::general_purpose::STANDARD.encode(data.as_bytes()) } - -#[cfg(test)] -mod tests { - use super::*; - - const START: &str = "__DIM_START_aaaabbbb_ccccdddd__"; - const END: &str = "__DIM_END_eeeeffff_00001111__"; - - fn capture() -> Capture { - Capture::new(START.into(), END.into()) - } - - /// Feeds a chunk and settles it the way the reader does. - fn feed(capture: &mut Capture, text: &str) { - capture.append(text); - capture.drain(); - } - - #[test] - fn a_start_marker_split_across_chunks_is_found_and_the_echo_dropped() { - let mut capture = capture(); - feed( - &mut capture, - "$ printf '%s%s' '__DIM_START_aaaabbbb_' 'ccccdddd__'; eval\n", - ); - feed(&mut capture, "echo hi\nhi\n"); - // The marker arrives in two chunks; neither half carries it alone. - feed(&mut capture, "__DIM_START_aaaabbbb_"); - feed(&mut capture, "ccccdddd__"); - feed(&mut capture, "line one\nline two\n"); - feed(&mut capture, &format!("{END}0\n")); - assert_eq!(capture.code.as_deref(), Some("0")); - assert_eq!(capture.output, "line one\nline two\n"); - assert_eq!(capture.omitted(), None); - } - - #[test] - fn a_start_marker_and_echo_after_conversion_stay_out_of_the_result() { - let mut capture = capture(); - feed( - &mut capture, - "$ printf '%s%s' '__DIM_START_aaaabbbb_' 'ccccdddd__'\n", - ); - feed(&mut capture, START); - feed(&mut capture, "output\n"); - feed(&mut capture, &format!("{END}3\n")); - assert_eq!(capture.code.as_deref(), Some("3")); - assert_eq!(capture.output, "output\n"); - assert!(!capture.output.contains("__DIM_")); - } - - #[test] - fn a_capture_converted_after_the_limit_reports_the_omission_and_keeps_the_rest() { - let mut capture = capture(); - feed(&mut capture, START); - let burst = "y".repeat(OUTPUT_LIMIT * 2); - feed(&mut capture, &burst); - let path = std::env::temp_dir().join(format!("capture-bind-{}", uuid::Uuid::new_v4())); - capture.bind(&path); - feed(&mut capture, "after\n"); - feed(&mut capture, &format!("{END}0\n")); - assert_eq!(capture.code.as_deref(), Some("0")); - let file = std::fs::read_to_string(&path).unwrap(); - let _ = std::fs::remove_file(&path); - assert!( - file.starts_with(&burst[..100]), - "the earliest bytes are kept" - ); - assert!( - file.contains(&format!( - "[Output truncated: {} bytes omitted]", - OUTPUT_LIMIT - )), - "{file}" - ); - assert!(file.ends_with("after\n"), "{}", &file[file.len() - 40..]); - assert!(!file.contains("__DIM_")); - } - - #[test] - fn an_end_marker_arriving_after_the_output_passed_the_limit_still_settles() { - let mut capture = capture(); - feed(&mut capture, START); - feed(&mut capture, &"x".repeat(OUTPUT_LIMIT * 2)); - assert!(capture.code.is_none()); - feed(&mut capture, &format!("\n{END}0\n")); - assert_eq!(capture.code.as_deref(), Some("0")); - assert_eq!(capture.output.len(), OUTPUT_LIMIT); - assert_eq!(capture.omitted(), Some(OUTPUT_LIMIT + 1)); - } - - #[test] - fn a_burst_past_the_limit_keeps_the_earliest_bytes() { - let mut capture = capture(); - feed(&mut capture, START); - let mut expected = String::new(); - for index in 0..5000 { - let line = format!("{index}\n"); - expected.push_str(&line); - feed(&mut capture, &line); - } - feed(&mut capture, &format!("{END}0\n")); - assert_eq!(capture.code.as_deref(), Some("0")); - assert!(expected.starts_with(&capture.output), "the earliest bytes"); - assert_eq!( - capture.omitted(), - Some(expected.len() - capture.output.len()), - "every byte past the limit is reported" - ); - } - - #[test] - fn a_long_line_starting_with_the_marker_prefix_is_settled_not_held() { - let mut capture = capture(); - feed(&mut capture, START); - let path = std::env::temp_dir().join(format!("capture-hold-{}", uuid::Uuid::new_v4())); - capture.bind(&path); - - feed(&mut capture, "__DIM_"); - let body = "a".repeat(1024 * 1024); - let mut settled = String::from("__DIM_"); - for chunk in body.as_bytes().chunks(4096) { - let text = std::str::from_utf8(chunk).unwrap(); - settled.push_str(text); - feed(&mut capture, text); - assert!( - capture.pending.len() <= MARKER_LINE_LIMIT, - "a line that can no longer become a marker is held: {} bytes", - capture.pending.len() - ); - } - assert!(capture.code.is_none()); - feed(&mut capture, "\n"); - feed(&mut capture, &format!("{END}0\n")); - assert_eq!(capture.code.as_deref(), Some("0")); - - let file = std::fs::read_to_string(&path).unwrap(); - let _ = std::fs::remove_file(&path); - let expected = format!("{settled}\n"); - assert!( - file.starts_with(&expected[..MARKER_LINE_LIMIT]), - "the log starts with the line's first bytes" - ); - assert!( - file.ends_with(&expected), - "the log holds the whole line: {} bytes", - file.len() - ); - assert_eq!(capture.output.len(), OUTPUT_LIMIT); - assert_eq!(capture.omitted(), Some(expected.len() - OUTPUT_LIMIT)); - } -} diff --git a/crates/dim-agent-capabilities/src/workspace_tools/background.rs b/crates/dim-agent-capabilities/src/workspace_tools/background.rs index ba5e487c04..cdf572eb03 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/background.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/background.rs @@ -5,9 +5,13 @@ //! 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::{background_result, recovered_result, sanitize}; use crate::{ context_block, + host_platform::{ + HostPlatform, HostPlatformError, OutputRequest, TaskFailure, TaskRequest, WaitReply, + WaitRequest, WaitStatus, + }, prompt_guide::{GuideEntries, GuideEntry, GuideScope}, }; use dim_agent_runtime::{ @@ -20,13 +24,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 { @@ -35,6 +35,8 @@ pub struct StartRequest { pub call_id: String, /// Proposed id; a `before` hook may rewrite it, the final one is returned. pub task_id: String, + /// The owner's task id; `task_id` is the branch-visible id a hook may rewrite. + pub host_task_id: String, pub description: String, pub title: Option, pub output_path: String, @@ -46,8 +48,6 @@ pub enum StartError { Closing, /// `exec/started` was not written. Timeline(AgentError), - /// Rejected handover could not confirm process-tree termination. - Termination(Box), } #[derive(Debug, Clone, thiserror::Error, serde::Serialize)] @@ -120,6 +120,8 @@ pub struct OutputPage { /// `cursor + bytes`. `text` can be shorter because sanitization drops /// control characters. pub bytes: u64, + /// The total bytes in the source capture or file. + pub total_bytes: u64, /// Present when the read found at least `limit` bytes, so the client may /// continue immediately; always `cursor + bytes`. Absent on a shorter or /// empty page, which does not mean the file ended: the client advances by @@ -130,17 +132,78 @@ 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, + total_bytes: 0, + 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, cancel: CancellationToken, - output: Option>, + /// The owner's task id while this process owns the task; absent for a + /// task rebuilt from the Timeline after an unload. + host_task_id: Option, /// The task's registered output file (`exec/started.output_path`): what /// the paged read answers from, in every state of the task. output_path: String, + /// The terminal preview, stored once the owner ends so a read during the + /// `exec/ended` commit serves the final bytes. + final_preview: Option, /// The dispatched `exec/ended`, once its wake decision is done. ended: watch::Sender>, } @@ -148,19 +211,118 @@ impl Task { fn new( description: String, cancel: CancellationToken, - output: Option>, + host_task_id: Option, output_path: String, ) -> Self { Self { description, cancel, - output, + host_task_id, output_path, + final_preview: None, ended: watch::Sender::new(None), } } } +fn missing_reply(output_path: &str) -> WaitReply { + WaitReply { + status: WaitStatus::Failed, + text: None, + exit_code: None, + signal: None, + duration_ms: 0, + output_path: output_path.to_owned(), + output_bytes: 0, + output_truncated: false, + preview: String::new(), + preview_truncated: false, + failure: Some(TaskFailure::OwnerUnloaded), + failure_note: None, + } +} + +async fn wait_owner( + platform: &HostPlatform, + host_task_id: &str, + cancel: &CancellationToken, +) -> Option { + let waited = platform + .wait( + WaitRequest { + task_id: host_task_id.to_owned(), + timeout_ms: None, + }, + cancelled_fn(cancel), + ) + .await; + match waited { + Ok(reply) => Some(reply), + Err(HostPlatformError::Cancelled) => { + let _ = platform + .kill(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; + platform + .wait( + WaitRequest { + task_id: host_task_id.to_owned(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .ok() + } + Err(_) => None, + } +} + +async fn stop_owner(platform: &HostPlatform, host_task_id: &str) { + let _ = platform + .kill(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; + let _ = platform + .wait( + WaitRequest { + task_id: host_task_id.to_owned(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + let _ = platform + .settle(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; +} + +fn cancelled_fn(token: &CancellationToken) -> crate::host::CancelledFn { + let token = token.clone(); + std::sync::Arc::new(move || { + let token = token.clone(); + Box::pin(async move { + token.cancelled().await; + Ok(()) + }) + }) +} + +fn never_cancelled() -> crate::host::CancelledFn { + let token = CancellationToken::new(); + std::sync::Arc::new(move || { + let token = token.clone(); + Box::pin(async move { + token.cancelled().await; + Ok(()) + }) + }) +} + #[derive(Default)] struct State { /// Rejects new starts. @@ -170,6 +332,7 @@ struct State { } pub struct BackgroundExec { + platform: Arc, timeline: Arc, from: Option, /// Gives each task its Session hold. @@ -189,11 +352,7 @@ impl BackgroundExec { /// Starting needs the live process, so it is the exec tool's own /// operation; the `backgroundExec` face serves the task id afterwards. #[service(skip)] - pub async fn start( - self: &Arc, - request: StartRequest, - process: ExecProcess, - ) -> Result { + pub async fn start(self: &Arc, request: StartRequest) -> Result { #[cfg(feature = "testing")] testing::pause(&request.output_path).await; let _handover = self.tasks.token(); @@ -203,11 +362,12 @@ impl BackgroundExec { self.session.take_hold() }; let Some(hold) = hold else { - process.abandon().await.map_err(StartError::Termination)?; + stop_owner(&self.platform, &request.host_task_id).await; return Err(StartError::Closing); }; let cancel = self.lifecycle.child_token(); let description = request.description.clone(); + let host_task_id = request.host_task_id.clone(); let mut registered = None; let committed = self.timeline.append_registered( EventKind::ExecStarted(ExecStartedData { @@ -233,7 +393,7 @@ impl BackgroundExec { Task::new( description.clone(), cancel.clone(), - Some(process.output.clone()), + Some(host_task_id.clone()), data.output_path.clone(), ), ); @@ -247,7 +407,7 @@ impl BackgroundExec { if let Some(task_id) = registered { self.state.lock().unwrap().tasks.remove(&task_id); } - process.abandon().await.map_err(StartError::Termination)?; + stop_owner(&self.platform, &host_task_id).await; return Err(if self.state.lock().unwrap().closing { StartError::Closing } else { @@ -259,12 +419,24 @@ impl BackgroundExec { unreachable!("exec/started kind is preserved") }; let task_id = data.task_id.clone(); + let output_path = data.output_path.clone(); let owner = self.clone(); + let platform = self.platform.clone(); let supervised = task_id.clone(); let parent = dim_agent_runtime::core::current_parent_call_id(); self.tasks.spawn(async move { let run = async { - let (status, result) = process.finish_background(&supervised, cancel).await; + let reply = wait_owner(&platform, &host_task_id, &cancel).await; + if let Some(reply) = &reply { + let mut state = owner.state.lock().unwrap(); + if let Some(task) = state.tasks.get_mut(&supervised) { + task.final_preview = Some(reply.preview.clone()); + } + } + let (status, result) = match reply { + Some(reply) => background_result(&supervised, &reply), + None => background_result(&supervised, &missing_reply(&output_path)), + }; let mut ended = owner.timeline.append( EventKind::ExecEnded(ExecEndedData { task_id: supervised.clone(), @@ -273,6 +445,11 @@ impl BackgroundExec { }) .into(), ); + let _ = platform + .settle(TaskRequest { + task_id: host_task_id, + }) + .await; drop(hold); if let Ok(event) = &ended { let mut publication = owner.timeline.watch(); @@ -291,7 +468,7 @@ impl BackgroundExec { tracing::warn!(%error, task_id = supervised, "exec/ended was not written"); state.tasks.remove(&supervised); } else if let Some(task) = state.tasks.get_mut(&supervised) { - task.output = None; + task.host_task_id = None; } }; if let Some(parent) = parent { @@ -306,18 +483,54 @@ impl BackgroundExec { /// Reads the live capture without reconstructing a resource from history: /// what `backgroundExec.output` answers. pub async fn output(&self, task_id: String) -> Result { - let output = { + let (host_task_id, _) = { let state = self.state.lock().unwrap(); if state.closed { return Err(TaskError::Closed); } - state - .tasks - .get(&task_id) - .and_then(|task| task.output.clone()) - .ok_or(TaskError::Unknown)? + let task = state.tasks.get(&task_id).ok_or(TaskError::Unknown)?; + if let Some(preview) = &task.final_preview + && task.host_task_id.is_some() + { + return Ok(preview.clone()); + } + (task.host_task_id.clone(), task.output_path.clone()) }; - Ok(output.preview().await) + let Some(host_task_id) = host_task_id else { + return Err(TaskError::Unknown); + }; + match self + .platform + .tail(TaskRequest { + task_id: host_task_id.clone(), + }) + .await + { + Ok(tail) => Ok(tail.text), + Err(HostPlatformError::TaskUnknown | HostPlatformError::OutputUnavailable(_)) => { + let done = self + .state + .lock() + .unwrap() + .tasks + .get(&task_id) + .and_then(|task| task.ended.borrow().clone()); + Ok(done + .and_then(|done| { + done.result + .structured_content + .as_ref()? + .get("preview")? + .as_str() + .map(str::to_owned) + }) + .unwrap_or_default()) + } + Err(error) => Err(TaskError::Read(AgentError::fault( + "BackgroundExec", + error.to_string(), + ))), + } } /// Reads one page of the task's registered output file, by byte offset: @@ -336,12 +549,10 @@ impl BackgroundExec { self.page(&task_id, cursor, limit).await } - /// The paged read behind [`Self::output_page`]. - /// - /// The file is the read's only source, so a running task, an ended task - /// and a task rebuilt after an unload answer alike; the live capture and - /// the result preview are not consulted. The file is append-only, so a - /// cursor the method handed out always names a byte that never changes. + /// The paged read behind [`Self::output_page`]. A live owner serves it + /// from the task record; a recovered task reads the registered file. The + /// file is append-only, so a cursor the method handed out always names a + /// byte that never changes. async fn page( &self, task_id: &str, @@ -353,15 +564,12 @@ impl BackgroundExec { if state.closed { return Err(OutputPageError::Closed); } - state.tasks.get(task_id).map(|task| { - ( - task.output_path.clone(), - task.ended.borrow().clone(), - task.output.clone(), - ) - }) + state + .tasks + .get(task_id) + .map(|task| (task.host_task_id.clone(), task.output_path.clone())) }; - let (output_path, ended, live) = match current { + let (host_task_id, output_path) = match current { Some(current) => current, None => { let start = self @@ -369,95 +577,44 @@ impl BackgroundExec { .await .map_err(OutputPageError::Read)? .ok_or(OutputPageError::Unknown)?; - let ended = self - .terminal(task_id, self.timeline.committed()) - .await - .map_err(OutputPageError::Read)?; if self.state.lock().unwrap().closed { return Err(OutputPageError::Closed); } - (start.output_path, ended, None) + (None, start.output_path) } }; - 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; + if let Some(host_task_id) = host_task_id { + match self + .platform + .output(OutputRequest { + task_id: host_task_id, + cursor: Some(cursor), + limit: Some(limit as u64), + }) + .await + { + Ok(page) => { + return Ok(OutputPage { + text: page.text, + bytes: page.bytes, + total_bytes: page.total_bytes.max(page.bytes), + next_cursor: page.next_cursor, + truncated: page.truncated, + }); + } + Err(HostPlatformError::TaskUnknown | HostPlatformError::OutputUnavailable(_)) => {} + Err(HostPlatformError::Closed) => return Err(OutputPageError::Closed), + Err(error) => { + return Err(OutputPageError::Read(AgentError::fault( + "BackgroundExec", + error.to_string(), + ))); + } } } - // 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 - .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, - }) + self.platform + .retained_output_page(std::path::Path::new(&output_path), cursor, limit) + .await } /// Waits until the task ends, or `timeout_ms` elapses: what @@ -963,20 +1120,12 @@ pub(crate) fn wakes(data: &ExecEndedData) -> bool { data.status != ExecStatus::Cancelled } -/// The `outputTruncated` flag an `exec/ended` result carries. -fn output_truncated(result: &ToolResult) -> Option { - result - .structured_content - .as_ref() - .and_then(|fields| fields.get("outputTruncated")) - .and_then(serde_json::Value::as_bool) -} - /// ``: work the model started has finished, failed or /// been cancelled. 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 +1136,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 +1152,7 @@ impl DynPlugin for BackgroundExecPlugin { } fn injects(&self) -> Vec { vec![ + self.platform.erase(), self.timeline.erase(), self.dispatcher.erase(), self.session.erase(), @@ -1061,6 +1212,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..c766275f45 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -10,8 +10,10 @@ 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, + HostPlatform, HostPlatformError, ISOLATION_SUMMARY, Isolation, Os, OutputRecord, + ProcessSpec, ProcessSpecError, ProcessTree, ShellEdition, ShellKind, ShellStatus, + SpawnReply, SpawnRequest, TaskFailure, TaskKind, TaskRecord, TaskRequest, TaskStatus, + Terminal, WaitReply, WaitRequest, WaitStatus, signal_name, }, tool_registry::definition, }; @@ -22,13 +24,18 @@ use serde_json::{Value, json}; use std::{ io, path::{Component, Path, PathBuf}, - process::ExitStatus, sync::Arc, time::Duration, }; -use tokio::{io::AsyncReadExt, sync::Mutex, task::JoinHandle, time::Instant}; +use tokio::{io::AsyncReadExt, sync::Mutex, task::JoinHandle}; use tokio_util::sync::CancellationToken; +use crate::host_platform::output::head_bytes; +pub use crate::host_platform::output::{ + Decoder, EXIT_STDIO_GRACE, OUTPUT_FILE_BYTE_LIMIT, OutputSink, bounded_preview, + capture_preview, pump, sanitize, tail_bytes, truncate_preview, +}; + /// Default foreground wait before a command moves to the background. const DEFAULT_WAIT_TIME: Duration = Duration::from_millis(30_000); const DEFAULT_EXEC_TIMEOUT_MS: u64 = 300_000; @@ -36,17 +43,9 @@ const MIN_EXEC_TIMEOUT_MS: u64 = 1_000; const MAX_EXEC_TIMEOUT_MS: u64 = 3_600_000; /// Foreground output stays inline until this UTF-16 length is exceeded. const INLINE_OUTPUT_CHAR_LIMIT: usize = 30_000; -const OUTPUT_PREVIEW_MAX_LINES: usize = 2_000; -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; -/// 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::HostPlatform) -> ToolDefinition { let mut env_line = format!( "Environment: {}/{}", platform.os.node_platform(), @@ -139,26 +138,6 @@ pub(super) async fn stop( } } -/// The process tree could not be confirmed gone; dropping it kills what is -/// left, but the caller must not take the command as stopped. Like the -/// background result, it keeps the output captured so far, including the -/// reference to an output file already written. -fn terminate_failed(error: &io::Error, settled: &Settled) -> ToolResult { - let mut structured = object(json!({ - "code": "exec_terminate_failed", - "outputBytes": settled.output_bytes, - "outputTruncated": settled.truncated, - })); - if let Some(path) = &settled.output_path { - structured.insert("outputPath".into(), path.clone().into()); - } - let note = format!("Command could not be terminated: {error}"); - ToolResult { - structured_content: Some(structured), - ..ToolResult::error(settled_content(settled, Some(¬e))) - } -} - fn failed(message: impl Into, code: &str) -> ToolResult { ToolResult { structured_content: Some(object(json!({ "code": code }))), @@ -168,11 +147,11 @@ fn failed(message: impl Into, code: &str) -> ToolResult { /// Declares the command a started call ran (session boundary A.6): the exit /// status the result observed, or none. -fn ran(mut result: ToolResult, command: &str, exit: Option) -> ToolResult { +fn ran(mut result: ToolResult, command: &str, exit: Option) -> ToolResult { result.effects = Some(vec![ToolEffect::CommandRun { command: command.to_owned(), - exit_code: exit.and_then(|status| status.code()), - signal: exit.and_then(signal_name), + exit_code: exit.as_ref().and_then(|status| status.code), + signal: exit.and_then(|status| status.signal), }]); result } @@ -1630,15 +1609,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) @@ -1680,147 +1659,6 @@ fn correct_windows_path(value: &str) -> String { value.to_owned() } -/// Incremental canonical UTF-8 decoding of one stream (ADR 018): invalid and -/// truncated bytes become `<0xNN>`, never U+FFFD. -#[derive(Default)] -pub struct Decoder { - pending: Vec, -} -impl Decoder { - pub fn write(&mut self, chunk: &[u8]) -> String { - let mut input = std::mem::take(&mut self.pending); - input.extend_from_slice(chunk); - self.decode(&input, false) - } - pub fn end(&mut self) -> String { - let input = std::mem::take(&mut self.pending); - self.decode(&input, true) - } - fn decode(&mut self, input: &[u8], last: bool) -> String { - let mut output = String::new(); - let mut offset = 0; - while offset < input.len() { - let first = input[offset]; - if first <= 0x7f { - output.push(first as char); - offset += 1; - continue; - } - let length = match first { - 0xc2..=0xdf => 2, - 0xe0..=0xef => 3, - 0xf0..=0xf4 => 4, - _ => 0, - }; - if length == 0 { - output.push_str(&escape_byte(first)); - offset += 1; - continue; - } - if offset + length > input.len() { - if !last { - self.pending = input[offset..].to_vec(); - break; - } - output.push_str(&escape_byte(first)); - offset += 1; - continue; - } - match std::str::from_utf8(&input[offset..offset + length]) { - Ok(text) => { - output.push_str(text); - offset += length; - } - Err(_) => { - output.push_str(&escape_byte(first)); - offset += 1; - } - } - } - output - } -} - -fn escape_byte(byte: u8) -> String { - format!("<0x{byte:02X}>") -} - -/// Removes control characters except `\t\n\r`, and U+FFF9–U+FFFB. -pub fn sanitize(text: &str) -> String { - text.chars() - .filter(|&ch| { - !(matches!(ch, '\u{0}'..='\u{8}' | '\u{b}' | '\u{c}' | '\u{e}'..='\u{1f}') - || matches!(ch, '\u{7f}'..='\u{9f}' | '\u{fff9}'..='\u{fffb}')) - }) - .collect() -} - -/// The tail of `text` within `max` UTF-8 bytes, on a character boundary. -pub fn tail_bytes(text: &str, max: usize) -> &str { - if text.len() <= max { - return text; - } - let mut start = text.len() - max; - while !text.is_char_boundary(start) { - start += 1; - } - &text[start..] -} - -/// The head of `text` within `max` UTF-8 bytes, on a character boundary. -fn head_bytes(text: &str, max: usize) -> &str { - if text.len() <= max { - return text; - } - let mut end = max; - while !text.is_char_boundary(end) { - end -= 1; - } - &text[..end] -} - -/// TS `truncatePreview`: the last 2000 lines within 50 KiB. -pub fn truncate_preview(text: &str) -> String { - let sanitized = sanitize(text); - if sanitized.is_empty() { - return sanitized; - } - let lines: Vec<&str> = sanitized.split('\n').collect(); - let tail = &lines[lines.len().saturating_sub(OUTPUT_PREVIEW_MAX_LINES)..]; - let joined = tail.join("\n"); - if joined.len() <= OUTPUT_PREVIEW_MAX_BYTES { - return joined; - } - if tail.len() == 1 || (tail.len() == 2 && tail[1].is_empty()) { - let suffix = if tail.len() == 2 { "\n" } else { "" }; - return format!( - "{}{suffix}", - tail_bytes(tail[0], OUTPUT_PREVIEW_MAX_BYTES - suffix.len()) - ); - } - let (mut low, mut high) = (0, tail.len() - 1); - while low < high { - let middle = (low + high) / 2; - if tail[middle..].join("\n").len() <= OUTPUT_PREVIEW_MAX_BYTES { - high = middle; - } else { - low = middle + 1; - } - } - let joined = tail[low..].join("\n"); - tail_bytes(&joined, OUTPUT_PREVIEW_MAX_BYTES).to_owned() -} - -/// exec's preview bounds — the sanitized tail within 2,000 lines and 50 KiB — -/// and whether they left anything out: bytes outside the captured `preview` -/// buffer, or a sanitized tail the rule cut. ShellInput's command record and a -/// background task's final result both read this one rule. -pub fn bounded_preview(preview: &str, decoded: usize) -> (String, bool) { - let text = truncate_preview(preview); - let truncated = decoded > preview.len() || text.len() < sanitize(preview).len(); - (text, truncated) -} - /// Merged canonical output of one command, inline until it outgrows the /// budget, then in the output file (TS `ExecOutputCapture`). struct Capture { @@ -1832,7 +1670,7 @@ struct Capture { file_bytes: u64, output_bytes: u64, truncated: bool, - failure: Option, + failure: Option, } impl Capture { async fn process(&mut self, text: &str) -> io::Result<()> { @@ -1865,6 +1703,7 @@ impl Capture { options.mode(0o600); let mut file = options.open(&self.path).await?; tokio::io::AsyncWriteExt::write_all(&mut file, initial.as_bytes()).await?; + file.sync_all().await?; self.file_bytes = initial.len() as u64; if initial.len() < self.inline.len() { self.truncated = true; @@ -1901,39 +1740,175 @@ impl Capture { } } -/// Appends `text` to the bounded output tail that [`truncate_preview`] reads: -/// past twice the preview budget, only the last part from a line start stays. -pub fn capture_preview(preview: &mut String, text: &str) { - preview.push_str(text); - if preview.len() > PREVIEW_BUFFER_HEADROOM_BYTES { - let keep = tail_bytes(preview, PREVIEW_BUFFER_HEADROOM_BYTES); - let keep = keep - .find('\n') - .filter(|index| index + 1 < keep.len()) - .map_or(keep, |index| &keep[index + 1..]); - *preview = keep.to_owned(); - } -} - -/// Where [`pump`] delivers the decoded text of a pipe, in read order. -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 { - pub(super) async fn preview(&self) -> String { - truncate_preview(&self.capture.lock().await.preview) + async fn ensure_file(&self) -> Result { + let mut capture = self.capture.lock().await; + if let Some(failure) = &capture.failure { + return Err(failure.to_string()); + } + match capture.create_file().await { + Ok(()) => Ok(capture.path.to_string_lossy().into_owned()), + Err(error) => { + let error = error.to_string(); + capture.failure = Some(TaskFailure::OutputWriteFailed { + message: error.clone(), + }); + Err(error) + } + } } - /// Whether the capture stopped appending at `OUTPUT_FILE_BYTE_LIMIT`. - pub(super) async fn truncated(&self) -> bool { - 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 HostPlatform { + pub(crate) async fn start_command( + &self, + task_id: &str, + spec: ProcessSpec, + roots: &[PathBuf], + output_dir: &Path, + timeout: Option, + ) -> Result<(), ProcessSpecError> { + if tokio::fs::create_dir_all(output_dir).await.is_err() { + return Err(ProcessSpecError { + code: "invalid_request", + reason: "output directory is not usable".into(), + }); + } + if std::fs::symlink_metadata(output_dir.join(format!("{task_id}.log"))).is_ok() { + return Err(ProcessSpecError { + code: "task_exists", + reason: "Execution task already exists".into(), + }); + } + let (spec, temporary, isolation) = self.prepare_isolated_process(spec, roots, None).await?; + let path = output_dir.join(format!("{task_id}.log")); + let output = Arc::new(Output { + capture: Mutex::new(Capture { + path: path.clone(), + 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 task = Arc::new(CommandTask { + output: output.clone(), + path, + isolation, + kill: CancellationToken::new(), + }); + let record = TaskRecord::new(task_id.to_owned(), TaskKind::Command(task.clone())); + { + 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(), + }); + } + commands.insert(task_id.to_owned(), record.clone()); + } + let mut tree = match self.spawn_tree(spec) { + Ok(tree) => tree, + Err(error) => { + let output = task.output_record().await; + record.finish(crate::host_platform::Terminal { + status: crate::host_platform::TaskStatus::Failed, + exit_code: None, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: Some(crate::host_platform::TaskFailure::CommandFailed), + output, + note: None, + }); + self.commands.lock().unwrap().remove(task_id); + return Err(ProcessSpecError { + code: "exec_invalid_request", + reason: format!("Failed to spawn process: {error}"), + }); + } + }; + tree.hold(temporary); + let stop_pumps = CancellationToken::new(); + let pumps = vec![ + tokio::spawn(pump(tree.stdout(), output.clone(), stop_pumps.clone())), + tokio::spawn(pump(tree.stderr(), output.clone(), stop_pumps.clone())), + ]; + let running = RunningCommand { + tree, + stop_pumps, + pumps, + output: output.clone(), + }; + let worker = task.clone(); + let supervised = record.clone(); + let shutdown = self.command_shutdown.clone(); + record.start(); + self.command_workers.spawn(async move { + running + .supervise(supervised, &worker, timeout, shutdown) + .await; + }); + Ok(()) + } + + pub(crate) fn command_task(&self, task_id: &str) -> Result, CaptureError> { + match &self.task(task_id).ok_or(CaptureError::Unknown)?.kind { + TaskKind::Command(task) => Ok(task.clone()), + _ => Err(CaptureError::Unknown), + } + } + + pub async fn retain_output_by_id(&self, task_id: &str) -> Result { + self.command_task(task_id)? + .output + .ensure_file() + .await + .map_err(CaptureError::Unavailable) + } + pub async fn tail_by_id(&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() { @@ -1945,61 +1920,37 @@ impl OutputSink for Output { return; } if let Err(error) = capture.process(text).await { - capture.failure = Some(error.to_string()); + capture.failure = Some(TaskFailure::OutputWriteFailed { + message: error.to_string(), + }); self.failed.cancel(); } } } -/// Reads one pipe through its own [`Decoder`] until EOF, a read error, or -/// [`EXIT_STDIO_GRACE`] of reading after `stop` (the root exited) fires. -pub async fn pump( - mut pipe: impl tokio::io::AsyncRead + Unpin, - output: Arc, - stop: CancellationToken, -) { - let mut decoder = Decoder::default(); - let mut buffer = vec![0; 16 * 1024]; - let mut drain_budget = EXIT_STDIO_GRACE; - loop { - let draining = stop.is_cancelled(); - let started = Instant::now(); - let read = if draining { - if drain_budget.is_zero() { - break; - } - match tokio::time::timeout(drain_budget, pipe.read(&mut buffer)).await { - Ok(read) => read, - Err(_) => break, - } - } else { - tokio::select! { - read = pipe.read(&mut buffer) => read, - _ = stop.cancelled() => continue, - } - }; - match read { - Ok(0) | Err(_) => break, - Ok(count) => { - let text = decoder.write(&buffer[..count]); - if draining { - drain_budget = drain_budget.saturating_sub(started.elapsed()); - } - output.push(&text).await; - } - } +/// What ended the wait for a running command. +#[derive(Clone, Debug)] +pub(super) struct CommandExit { + pub(super) code: Option, + pub(super) signal: Option, +} +impl CommandExit { + pub(super) fn success(&self) -> bool { + self.signal.is_none() && self.code == Some(0) } - output.push(&decoder.end()).await; } -/// What ended the wait for a running command. +#[derive(Clone)] pub(super) enum Observed { - Exited(ExitStatus), + Cancelled, + OwnerUnloaded, + Exited(CommandExit), TimedOut, OutputFailed, } /// Summary of a settled command's output. +#[derive(Clone)] struct Settled { output_path: Option, output_bytes: u64, @@ -2008,7 +1959,7 @@ struct Settled { /// The preview bounds left output out of `preview`. preview_truncated: bool, inline: String, - failure: Option, + failure: Option, } impl Settled { /// The output text that the result shows. @@ -2020,58 +1971,81 @@ 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 { - tree: ProcessTree, +pub(crate) struct CommandTask { pub(super) output: Arc, + pub(super) path: PathBuf, + pub(super) isolation: Option, + pub(crate) kill: CancellationToken, +} + +struct RunningCommand { + tree: ProcessTree, + 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, + record: Arc, + task: &CommandTask, + timeout: Option, + shutdown: CancellationToken, + ) { + let deadline = timeout.map(|ms| record.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(|status| { + let code = status.code(); + Observed::Exited(CommandExit { code, signal: signal_name(status) }) + }) + .map_err(|error| error.to_string()), + _ = async { tokio::time::sleep_until(deadline.expect("guarded").into()).await }, if deadline.is_some() => 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::OwnerUnloaded), + }; + 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); + record.finish(command_terminal( + &record, + observed, + termination_error, + output, + task, + )); } + /// Starts the bounded pipe drain and waits for output writes to finish. async fn close(&mut self) -> Settled { - self.stop_pumps.cancel(); - futures_util::future::join_all(std::mem::take(&mut self.pumps)).await; + let mut pumps = std::mem::take(&mut self.pumps); + let mut drained = Box::pin(futures_util::future::join_all(pumps.iter_mut())); + tokio::select! { + _ = &mut drained => {} + _ = tokio::time::sleep(EXIT_STDIO_GRACE) => { + self.stop_pumps.cancel(); + drained.await; + } + } let mut capture = self.output.capture.lock().await; if let Some(file) = capture.file.as_mut() && let Err(error) = tokio::io::AsyncWriteExt::flush(file).await && capture.failure.is_none() { - capture.failure = Some(error.to_string()); + capture.failure = Some(TaskFailure::OutputWriteFailed { + message: error.to_string(), + }); } let (preview, preview_truncated) = bounded_preview( &capture.preview, @@ -2087,174 +2061,239 @@ impl ExecProcess { failure: capture.failure.clone(), } } - /// 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> { - 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 - } - /// 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(); - match isolation.and_then(|isolation| isolation.failure_hint(settled.shown())) { - Some(hint) => format!("{note}\n\n{hint}"), - None => note, +} + +fn command_terminal( + record: &TaskRecord, + observed: Result, + termination_error: Option, + output: Settled, + task: &CommandTask, +) -> Terminal { + let (mut status, exit_code, signal, failed_exit) = match &observed { + Ok(Observed::Exited(exit)) => ( + if exit.signal.is_some() { + TaskStatus::Signaled + } else { + TaskStatus::Exited + }, + exit.code, + exit.signal.clone(), + !exit.success(), + ), + Ok(Observed::TimedOut) => (TaskStatus::TimedOut, None, None, false), + Ok(Observed::Cancelled) => (TaskStatus::Cancelled, None, None, false), + Ok(Observed::OwnerUnloaded) => (TaskStatus::Cancelled, None, None, false), + Ok(Observed::OutputFailed) | Err(_) => (TaskStatus::Failed, None, None, false), + }; + if termination_error.is_some() || output.failure.is_some() { + status = TaskStatus::Failed; + } + let note = failed_exit + .then(|| { + task.isolation + .as_ref() + .and_then(|isolation| isolation.failure_hint(output.shown())) + }) + .flatten(); + let failure = if matches!(observed, Ok(Observed::OwnerUnloaded)) { + Some(TaskFailure::OwnerUnloaded) + } else { + match &observed { + Err(message) if termination_error.is_none() && output.failure.is_none() => { + Some(TaskFailure::TerminateFailed { + message: message.clone(), + }) + } + _ => termination_error + .map(|message| TaskFailure::TerminateFailed { message }) + .or_else(|| output.failure.clone()), } + }; + let output = OutputRecord { + path: task.path.to_string_lossy().into_owned(), + bytes: output.output_bytes, + truncated: output.truncated, + text: output.output_path.is_none().then(|| output.inline.clone()), + preview: output.preview.clone(), + preview_truncated: output.preview_truncated, + }; + Terminal { + status, + exit_code, + signal, + duration_ms: record.started.elapsed().as_millis() as u64, + failure, + output, + note, } +} - /// 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, - task_id: &str, - cancel: CancellationToken, - ) -> (ExecStatus, ToolResult) { - let observed = tokio::select! { - biased; - observed = self.next() => observed.map(Some), - _ = cancel.cancelled() => Ok(None), - }; - let mut unterminated = None; - let exit = match &observed { - Ok(Some(Observed::Exited(status))) => Some(*status), - _ => { - if let Err(error) = self.terminate().await { - tracing::warn!(%error, task_id, "background exec termination failed"); - unterminated = Some(error); +impl CommandTask { + pub(crate) async fn output_record(&self) -> OutputRecord { + let capture = self.output.capture.lock().await; + let preview = truncate_preview(&capture.preview); + OutputRecord { + path: self.path.to_string_lossy().into_owned(), + bytes: capture.output_bytes, + truncated: capture.truncated, + text: capture.file.is_none().then(|| capture.inline.clone()), + preview: preview.clone(), + preview_truncated: preview.len() < capture.preview.len(), + } + } + + 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 total_bytes = capture.output_bytes; + 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()); + let mut page = decode_page(&bytes[start..end], cursor, limit, truncated)?; + page.total_bytes = total_bytes; + return Ok(page); + } + 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)?; + let mut page = decode_page(&bytes, cursor, limit, truncated)?; + page.total_bytes = total_bytes; + Ok(page) + } +} + +fn settled_from_reply(reply: &WaitReply) -> (Settled, Option) { + let settled = Settled { + output_path: reply + .text + .is_none() + .then(|| reply.output_path.clone()) + .filter(|path| std::path::Path::new(path).exists()), + output_bytes: reply.output_bytes, + truncated: reply.output_truncated, + preview: reply.preview.clone(), + preview_truncated: reply.preview_truncated, + inline: reply.text.clone().unwrap_or_default(), + failure: reply.failure.clone(), + }; + let exit = + matches!(reply.status, WaitStatus::Exited | WaitStatus::Signaled).then(|| CommandExit { + code: reply.exit_code, + signal: reply.signal.clone(), + }); + (settled, exit) +} + +pub(super) fn background_result(task_id: &str, reply: &WaitReply) -> (ExecStatus, ToolResult) { + let (settled, exit) = settled_from_reply(reply); + let (status, summary, name) = match reply.status { + WaitStatus::Cancelled => ( + ExecStatus::Cancelled, + "Command cancelled by user.".to_owned(), + "cancelled", + ), + WaitStatus::TimedOut => ( + ExecStatus::Failed, + "Command timed out.".to_owned(), + "timed_out", + ), + _ if settled.failure.is_some() => { + let failure = settled.failure.as_ref().expect("guarded"); + let summary = match failure { + TaskFailure::OutputWriteFailed { message } => { + format!("exec output offload failed: {message}") } - None - } - }; - let settled = self.close().await; - let (status, summary, name) = match (&observed, exit) { - _ if let Some(error) = &unterminated => ( - ExecStatus::Failed, - format!("Command could not be terminated: {error}"), - "failed", - ), - _ if settled.failure.is_some() => ( - ExecStatus::Failed, - format!( - "exec output offload failed: {}", - settled.failure.as_deref().unwrap_or_default() - ), - "failed", - ), - (Err(error), _) => ( - ExecStatus::Failed, - format!("exec process wait failed: {error}"), - "failed", - ), - (Ok(None), _) => ( - ExecStatus::Cancelled, - "Command cancelled by user.".into(), - "cancelled", - ), - (Ok(Some(Observed::TimedOut)), _) => { - (ExecStatus::Failed, "Command timed out.".into(), "timed_out") - } - (_, Some(status)) if status.success() => ( + _ => failure.to_string(), + }; + (ExecStatus::Failed, summary, "failed") + } + WaitStatus::Exited | WaitStatus::Signaled => match &exit { + Some(exit) if exit.success() => ( ExecStatus::Completed, - "Command completed.".into(), + "Command completed.".to_owned(), "completed", ), - (_, Some(status)) => (ExecStatus::Failed, exit_failure_summary(status), "failed"), - (_, None) => ( + Some(exit) => (ExecStatus::Failed, exit_failure_summary(exit), "failed"), + None => ( ExecStatus::Failed, - "Command failed without an exit code.".into(), + "Command failed without an exit code.".to_owned(), "failed", ), - }; - let note = match exit { - Some(status) if !status.success() && settled.failure.is_none() => { - self.failure_note(summary.clone(), &settled) - } - _ => summary.clone(), - }; - let mut structured = object(json!({ - "type": "finished", - "status": name, - "taskId": task_id, - "outputBytes": settled.output_bytes, - "outputTruncated": settled.truncated, - "preview": settled.preview.clone(), - "previewTruncated": settled.preview_truncated, - "timedOut": name == "timed_out", - "summary": summary, - })); - if let Some(path) = &settled.output_path { - structured.insert("outputPath".into(), path.clone().into()); - } - insert_exit(&mut structured, exit); - let content = match &settled.output_path { - Some(path) => file_backed_content( - path, - settled.output_bytes, - settled.truncated, - &settled.preview, - Some(¬e), + }, + WaitStatus::Failed | WaitStatus::Running => ( + ExecStatus::Failed, + reply.failure.as_ref().map_or_else( + || "Command failed without an exit code.".to_owned(), + ToString::to_string, ), - None => note, - }; - let result = ToolResult { - structured_content: Some(structured), - is_error: (status != ExecStatus::Completed).then_some(true), - ..ToolResult::text(content) - }; - (status, result) + "failed", + ), + }; + let note = match (&settled.failure, &exit) { + (None, Some(exit)) if !exit.success() => reply + .failure_note + .clone() + .unwrap_or_else(|| summary.clone()), + _ => summary.clone(), + }; + let mut structured = object(json!({ + "type": "finished", + "status": name, + "taskId": task_id, + "outputBytes": settled.output_bytes, + "outputTruncated": settled.truncated, + "preview": settled.preview.clone(), + "previewTruncated": settled.preview_truncated, + "timedOut": name == "timed_out", + "summary": summary, + })); + if let Some(path) = &settled.output_path { + structured.insert("outputPath".into(), path.clone().into()); } + insert_exit(&mut structured, exit.as_ref()); + let result = ToolResult { + structured_content: Some(structured), + is_error: (status != ExecStatus::Completed).then_some(true), + ..ToolResult::text(settled_content(&settled, Some(¬e))) + }; + (status, result) } -fn insert_exit(structured: &mut JsonObject, exit: Option) { +fn insert_exit(structured: &mut JsonObject, exit: Option<&CommandExit>) { let Some(status) = exit else { return }; - if let Some(code) = status.code() { + if let Some(code) = status.code { structured.insert("exitCode".into(), code.into()); } - if let Some(signal) = signal_name(status) { - structured.insert("signal".into(), signal.into()); - } -} - -/// 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 + if let Some(signal) = &status.signal { + structured.insert("signal".into(), signal.clone().into()); + } } -fn exit_failure_summary(status: ExitStatus) -> String { - if let Some(code) = status.code() { +fn exit_failure_summary(status: &CommandExit) -> String { + if let Some(code) = status.code { return format!("Command exited with code {code}."); } - match signal_name(status) { + match &status.signal { Some(signal) => format!("Command terminated by signal {signal}."), None => "Command failed without an exit code.".into(), } @@ -2291,6 +2330,19 @@ fn append_note(content: &str, note: Option<&str>) -> String { } } +fn settled_content(settled: &Settled, note: Option<&str>) -> String { + match &settled.output_path { + Some(path) => file_backed_content( + path, + settled.output_bytes, + settled.truncated, + &settled.preview, + note, + ), + None => append_note(&settled.inline, note), + } +} + fn running_content(reason: &str, task_id: &str, output_path: &str, preview: &str) -> String { [ reason, @@ -2366,26 +2418,19 @@ 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.platform.home, tools.platform.os), None => tools.cwd.clone(), }; - let (spec, shell) = match platform.build_process_spec(&input.command, &cwd).await { - Ok(built) => built, - Err(error) - if matches!( - error.code, - EXEC_SHELL_CONFIG_INVALID | EXEC_SHELL_UNAVAILABLE - ) => - { + let shell = match platform.exec_shell().await { + ShellStatus::Available(shell) => shell, + ShellStatus::Unavailable { code, reason } => { return Ok(failed( format!( - "exec shell is unavailable ({}): {} Fix exec-shell.json and retry.", - error.code, error.reason + "exec shell is unavailable ({code}): {reason} Fix exec-shell.json and retry." ), "exec_shell_unavailable", )); } - Err(error) => return Ok(failed(error.reason, error.code)), }; if let Some(marker) = background_marker(&input.command, shell.edition) { let (line, column) = marker.position(&input.command); @@ -2398,16 +2443,18 @@ 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.platform.home.to_string_lossy(), + ) { return Ok(refused); } - let task_id = format!("exec-{}", uuid::Uuid::new_v4()); + let host_task_id = format!("exec-{}", uuid::Uuid::new_v4()); let background = input.run_in_background && !tools.member; let effective_timeout = (!(input.disable_timeout && background)).then_some(input.timeout_ms); let request = Call { - task_id: task_id.clone(), + task_id: host_task_id.clone(), command: &input.command, title: input.title.as_deref(), cwd: cwd_text, @@ -2417,32 +2464,26 @@ 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 spawn = match platform + .spawn(SpawnRequest { + task_id: host_task_id, + command: input.command.clone(), + cwd: request.cwd.clone(), + workspace: tools.cwd.to_string_lossy().into_owned(), + roots: roots + .iter() + .map(|root| root.to_string_lossy().into_owned()) + .collect(), + output_dir: tools.output_dir.to_string_lossy().into_owned(), + timeout_ms: effective_timeout, + }) + .await + { + Ok(spawn) => spawn, + Err(error) => return Ok(spawn_failed(error)), }; let (result, exit) = run_process( - tools, - branch, - call, - context, - &request, - tree, - temporary, - isolation, - background, - effective_timeout, - cancel, + tools, branch, call, context, &request, spawn, background, cancel, ) .await?; Ok(ran(result, request.command, exit)) @@ -2462,168 +2503,142 @@ async fn run_process( call: &ToolCall, context: &ToolExecutionContext, request: &Call<'_>, - mut tree: ProcessTree, - temporary: Option, - isolation: Option, + spawn: SpawnReply, 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)); - } - return Ok((cancelled_result(), None)); - } +) -> Result<(ToolResult, Option), HostError> { + let platform = &tools.platform; + let host_task_id = spawn.task_id; + let output_path = spawn.output_path; if background { - return hand_off(branch, call, context, request, process, true, &cancel).await; + return hand_off( + platform, + branch, + call, + context, + request, + &host_task_id, + &output_path, + None, + true, + &cancel, + ) + .await; } - - let handoff = async { - if tools.member { - std::future::pending::<()>().await - } else { - tokio::time::sleep(DEFAULT_WAIT_TIME).await - } - }; - let observed = tokio::select! { - biased; - observed = process.next() => Some(observed), - _ = cancel.cancelled() => { - if let Err(error) = process.terminate().await { - let settled = process.close().await; - return Ok((terminate_failed(&error, &settled), None)); - } - let settled = process.close().await; - if let Some(failure) = &settled.failure { - return Ok((offload_failed(failure), None)); - } - return Ok(( - ToolResult::error(settled_content(&settled, Some("Command cancelled."))), - None, - )); - } - _ = handoff => None, - }; - let wall = process.wall_time_ms(); - let observed = match observed { - Some(observed) => Some(observed), - None => futures_util::FutureExt::now_or_never(process.next()), - }; - let Some(observed) = observed else { - return hand_off(branch, call, context, request, process, false, &cancel).await; - }; - let exit = match observed { - Ok(Observed::Exited(status)) => status, - Ok(Observed::OutputFailed) => { - if let Err(error) = process.terminate().await { - let settled = process.close().await; - return Ok((terminate_failed(&error, &settled), None)); - } - let settled = process.close().await; - return Ok(( - offload_failed(settled.failure.as_deref().unwrap_or_default()), - None, - )); + let timeout = (!tools.member).then_some(DEFAULT_WAIT_TIME.as_millis() as u64); + let waited = platform + .wait( + WaitRequest { + task_id: host_task_id.clone(), + timeout_ms: timeout, + }, + cancelled_fn(&cancel), + ) + .await; + let reply = match waited { + Ok(reply) if reply.status == WaitStatus::Running => { + return hand_off( + platform, + branch, + call, + context, + request, + &host_task_id, + &output_path, + Some(reply), + false, + &cancel, + ) + .await; } - Ok(Observed::TimedOut) => { - if let Err(error) = process.terminate().await { - let settled = process.close().await; - return Ok((terminate_failed(&error, &settled), None)); - } - let settled = process.close().await; - if let Some(failure) = &settled.failure { - return Ok((offload_failed(failure), None)); - } - let mut fields = json!({ - "type": "finished", - "status": "timed_out", - "outputBytes": settled.output_bytes, - "outputTruncated": settled.truncated, - "wallTimeMs": wall, - "timeoutMs": request.timeout_ms, - "timedOut": true, - }); - if let Some(path) = &settled.output_path { - fields["outputPath"] = path.clone().into(); - } - return Ok(( - ToolResult { - structured_content: Some(request.structured(fields)), - ..ToolResult::error(settled_content(&settled, Some("Command timed out."))) - }, - None, - )); + Ok(reply) => reply, + Err(HostPlatformError::Cancelled) => { + return cancel_foreground(platform, &host_task_id).await; } Err(error) => { - if let Err(error) = process.terminate().await { - let settled = process.close().await; - return Ok((terminate_failed(&error, &settled), None)); - } - process.close().await; + stop_and_settle(platform, &host_task_id).await; return Ok(( - failed( - format!("Failed to wait for process: {error}"), - "exec_wait_failed", - ), + failed(format!("exec wait failed: {error}"), "exec_wait_failed"), None, )); } }; - let settled = process.close().await; - if let Some(failure) = &settled.failure { - return Ok((offload_failed(failure), None)); + finish_foreground(platform, request, &host_task_id, reply).await +} + +async fn finish_foreground( + platform: &HostPlatform, + request: &Call<'_>, + host_task_id: &str, + reply: WaitReply, +) -> Result<(ToolResult, Option), HostError> { + let (settled, exit) = settled_from_reply(&reply); + let _ = platform + .settle(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; + let completed = reply.status == WaitStatus::Exited + && exit.as_ref().is_some_and(CommandExit::success) + && settled.failure.is_none(); + if let Some(TaskFailure::OutputWriteFailed { message }) = &settled.failure { + let note = format!("exec output offload failed: {message}"); + let mut result = failed(note.clone(), "exec_output_offload_failed"); + result.content = ToolContent::Text(settled_content(&settled, Some(¬e))); + return Ok((result, None)); + } + if reply.status == WaitStatus::Cancelled { + return Ok(( + ToolResult::error(settled_content(&settled, Some("Command cancelled."))), + None, + )); + } + if reply.status == WaitStatus::TimedOut { + let mut fields = json!({ + "type": "finished", + "status": "timed_out", + "outputBytes": settled.output_bytes, + "outputTruncated": settled.truncated, + "wallTimeMs": reply.duration_ms, + "timeoutMs": request.timeout_ms, + "timedOut": true, + }); + if let Some(path) = &settled.output_path { + fields["outputPath"] = path.clone().into(); + } + return Ok(( + ToolResult { + structured_content: Some(request.structured(fields)), + ..ToolResult::error(settled_content(&settled, Some("Command timed out."))) + }, + None, + )); } - let completed = exit.success(); let note = (!completed).then(|| { - let note = match exit.code() { - Some(code) => format!("Command exited with code {code}."), - None => exit_failure_summary(exit), + let base = match &exit { + Some(exit) => exit_failure_summary(exit), + None => settled.failure.as_ref().map_or_else( + || "Command failed without an exit code.".to_owned(), + ToString::to_string, + ), }; - process.failure_note(note, &settled) + match &reply.failure_note { + Some(hint) => format!("{base}\n\n{hint}"), + None => base, + } }); let mut fields = object(json!({ "type": "finished", "status": if completed { "completed" } else { "failed" }, "outputBytes": settled.output_bytes, "outputTruncated": settled.truncated, - "wallTimeMs": wall, + "wallTimeMs": reply.duration_ms, "timeoutMs": request.timeout_ms, })); if let Some(path) = &settled.output_path { fields.insert("outputPath".into(), path.clone().into()); } - insert_exit(&mut fields, Some(exit)); + insert_exit(&mut fields, exit.as_ref()); Ok(( ToolResult { content: ToolContent::Text(settled_content(&settled, note.as_deref())), @@ -2631,81 +2646,108 @@ async fn run_process( structured_content: Some(request.structured(Value::Object(fields))), ..ToolResult::default() }, - Some(exit), + exit, )) } -fn settled_content(settled: &Settled, note: Option<&str>) -> String { - match &settled.output_path { - Some(path) => file_backed_content( - path, - settled.output_bytes, - settled.truncated, - &settled.preview, - note, +async fn cancel_foreground( + platform: &HostPlatform, + host_task_id: &str, +) -> Result<(ToolResult, Option), HostError> { + let killed = platform + .kill(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; + let reply = platform + .wait( + WaitRequest { + task_id: host_task_id.to_owned(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .ok(); + let result = match (killed, reply) { + (Err(error), _) => failed( + format!("Command could not be terminated: {error}"), + "exec_terminate_failed", ), - None => append_note(&settled.inline, note), - } + (_, Some(reply)) => { + let (settled, _) = settled_from_reply(&reply); + ToolResult::error(settled_content(&settled, Some("Command cancelled."))) + } + (_, None) => cancelled_result(), + }; + let _ = platform + .settle(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; + Ok((result, None)) } /// Moves a running command to this branch's BackgroundExec; `immediate` /// for `runInBackground`, otherwise after the foreground wait. Its answer /// observed no exit: the call saw that the command started and nothing more. +#[expect( + clippy::too_many_arguments, + reason = "one parameter per input a handoff carries" +)] async fn hand_off( + platform: &HostPlatform, branch: &Branch, call: &ToolCall, context: &ToolExecutionContext, request: &Call<'_>, - process: ExecProcess, + host_task_id: &str, + output_path: &str, + reply: Option, immediate: bool, cancel: &CancellationToken, -) -> Result<(ToolResult, Option), HostError> { - let output_path = match process.ensure_file().await { - Ok(path) => path, +) -> Result<(ToolResult, Option), HostError> { + let retained = match platform + .retain_output(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await + { + Ok(path) => path.output_path, Err(error) => { - if let Err(result) = process.abandon().await { - return Ok((*result, None)); - } - return Ok((offload_failed(&error), None)); + stop_and_settle(platform, host_task_id).await; + return Ok((offload_failed(&error.to_string()), None)); } }; if cancel.is_cancelled() { - if let Err(result) = process.abandon().await { - return Ok((*result, None)); - } + stop_and_settle(platform, host_task_id).await; return Ok((cancelled_result(), None)); } let background = match branch.service::() { Ok(background) => background, Err(error) => { - if let Err(result) = process.abandon().await { - return Ok((*result, None)); - } + stop_and_settle(platform, host_task_id).await; return Ok((start_failed(&error.to_string()), None)); } }; - let preview = process.output.preview().await; - let wall = if immediate { 0 } else { process.wall_time_ms() }; let started = background - .start( - StartRequest { - turn_id: context.turn_id.clone(), - request_id: context.request_id.clone(), - call_id: call.id.clone(), - task_id: request.task_id.clone(), - description: request - .command - .lines() - .next() - .unwrap_or_default() - .chars() - .take(DESCRIPTION_CHARS) - .collect(), - title: request.title.map(String::from), - output_path: output_path.clone(), - }, - process, - ) + .start(StartRequest { + turn_id: context.turn_id.clone(), + request_id: context.request_id.clone(), + call_id: call.id.clone(), + task_id: request.task_id.clone(), + host_task_id: host_task_id.to_owned(), + description: request + .command + .lines() + .next() + .unwrap_or_default() + .chars() + .take(DESCRIPTION_CHARS) + .collect(), + title: request.title.map(String::from), + output_path: retained.clone(), + }) .await; let task_id = match started { Ok(task_id) => task_id, @@ -2715,14 +2757,24 @@ async fn hand_off( Err(StartError::Timeline(error)) => { return Ok((start_failed(&error.to_string()), None)); } - Err(StartError::Termination(result)) => { - return Ok((*result, None)); - } }; + let preview = match platform + .tail(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await + { + Ok(tail) => tail.text, + Err(_) => reply + .as_ref() + .map(|reply| reply.preview.clone()) + .unwrap_or_default(), + }; + let wall = reply.as_ref().map(|reply| reply.duration_ms).unwrap_or(0); let mut structured = request.structured(json!({ "type": "running", "status": "running", - "outputPath": output_path, + "outputPath": retained, "wallTimeMs": wall, "timeoutMs": request.timeout_ms, "notification": "completion-will-be-sent", @@ -2741,12 +2793,71 @@ async fn hand_off( Ok(( ToolResult { structured_content: Some(structured), - ..ToolResult::text(running_content(&reason, &task_id, &output_path, &preview)) + ..ToolResult::text(running_content(&reason, &task_id, output_path, &preview)) }, None, )) } +fn cancelled_fn(token: &CancellationToken) -> crate::host::CancelledFn { + let token = token.clone(); + std::sync::Arc::new(move || { + let token = token.clone(); + Box::pin(async move { + token.cancelled().await; + Ok(()) + }) + }) +} + +fn never_cancelled() -> crate::host::CancelledFn { + let token = CancellationToken::new(); + std::sync::Arc::new(move || { + let token = token.clone(); + Box::pin(async move { + token.cancelled().await; + Ok(()) + }) + }) +} + +async fn stop_and_settle(platform: &HostPlatform, host_task_id: &str) { + let _ = platform + .kill(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; + let _ = platform + .wait( + WaitRequest { + task_id: host_task_id.to_owned(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + let _ = platform + .settle(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; +} + +fn spawn_failed(error: HostPlatformError) -> ToolResult { + let (code, message) = match error { + HostPlatformError::ExecShellConfigInvalid(reason) + | HostPlatformError::ExecShellUnavailable(reason) => ("exec_shell_unavailable", reason), + HostPlatformError::IsolationConfigInvalid(reason) => ("isolation_config_invalid", reason), + HostPlatformError::IsolationUnavailable(reason) => ("isolation_unavailable", reason), + HostPlatformError::Invalid(reason) => ("exec_invalid_request", reason), + HostPlatformError::TaskExists => { + ("task_exists", "Execution task already exists".to_owned()) + } + HostPlatformError::Cancelled => ("cancelled", "Tool execution cancelled.".to_owned()), + other => ("exec_invalid_request", other.to_string()), + }; + failed(message, code) +} fn start_failed(reason: &str) -> ToolResult { failed( format!( @@ -2756,39 +2867,6 @@ fn start_failed(reason: &str) -> ToolResult { ) } -#[cfg(test)] -#[test] -fn termination_failure_keeps_captured_output() { - for output_path in [None, Some("/outputs/exec-partial.log".into())] { - let settled = Settled { - output_path, - output_bytes: 37, - truncated: false, - preview: "partial stdout before termination".into(), - preview_truncated: false, - inline: "partial stdout before termination".into(), - failure: None, - }; - let result = terminate_failed(&io::Error::other("tree still alive"), &settled); - let ToolContent::Text(content) = &result.content else { - panic!("exec returns text"); - }; - assert!(content.contains("Command could not be terminated: tree still alive")); - assert!(content.contains("partial stdout before termination")); - assert_eq!(result.is_error, Some(true)); - let fields = result.structured_content.unwrap(); - assert_eq!(fields["code"], "exec_terminate_failed"); - assert_eq!(fields["outputBytes"], 37); - assert_eq!(fields["outputTruncated"], false); - if let Some(path) = &settled.output_path { - assert!(content.contains(path)); - assert_eq!(fields["outputPath"], path.as_str()); - } else { - assert!(!fields.contains_key("outputPath")); - } - } -} - /// An `&` that every POSIX edition reads as a background marker. #[cfg(test)] const ALWAYS_REFUSED: &[&str] = &[ diff --git a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs index 8ae7975162..a0ac1fe108 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs @@ -240,6 +240,9 @@ impl WorkspaceTools { return Ok(()); }; let path = PathBuf::from(path); + if !path.exists() { + return Ok(()); + } if !path.starts_with(&self.output_dir) { return Err(HostError::failed(format!( "Output path {} is outside the Session's output directory", diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 329684350f..a595fade76 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1,4 +1,5 @@ //! HostPlatform acceptance on Unix (`docs/architecture/rust-agent/plugins/HostPlatform.md`). +use base64::Engine; use dim_agent_capabilities::execution_settings::{ExecutionSettings, ExecutionSettingsHost}; use dim_agent_capabilities::host_platform::*; use dim_agent_capabilities::toolchain::{InstalledToolchain, ToolchainSourceHost}; @@ -97,6 +98,10 @@ async fn shell_resolution_follows_the_preference_and_never_fails_the_service() { )); } +fn path_string(path: impl AsRef) -> String { + path.as_ref().to_string_lossy().into_owned() +} + #[tokio::test] async fn spawn_isolates_the_environment_and_terminate_releases_the_tree() { let platform = HostPlatform::current(ShellStatus::Unavailable { @@ -107,7 +112,7 @@ async fn spawn_isolates_the_environment_and_terminate_releases_the_tree() { let cwd = std::env::temp_dir(); let mut tree = platform - .spawn(ProcessSpec { + .spawn_tree(ProcessSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "env; cat".into()], cwd: cwd.clone(), @@ -122,7 +127,7 @@ async fn spawn_isolates_the_environment_and_terminate_releases_the_tree() { let spawn_tree = || { platform - .spawn(ProcessSpec { + .spawn_tree(ProcessSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "sleep 100 & echo $!; wait".into()], cwd: cwd.clone(), @@ -154,7 +159,7 @@ async fn spawn_isolates_the_environment_and_terminate_releases_the_tree() { assert!( platform - .spawn(ProcessSpec { + .spawn_tree(ProcessSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "true".into()], cwd: cwd.join("dim-missing-cwd-for-spawn"), @@ -295,7 +300,7 @@ async fn spawn_with_stdin_delivers_the_bytes_and_closes_the_pipe() { let cwd = std::env::temp_dir(); let payload = br#"{"hook_event_name":"Stop"}"#.to_vec(); let mut tree = platform - .spawn_with_stdin( + .spawn_with_stdin_process( ProcessSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "cat; echo done".into()], @@ -311,7 +316,7 @@ async fn spawn_with_stdin_delivers_the_bytes_and_closes_the_pipe() { assert_eq!(output, "{\"hook_event_name\":\"Stop\"}done\n"); let mut tree = platform - .spawn_with_stdin( + .spawn_with_stdin_process( ProcessSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "echo ok".into()], @@ -412,7 +417,7 @@ async fn confined( timeout: Duration, ) -> Result { platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.into()], @@ -466,7 +471,7 @@ async fn a_confined_helper_reads_its_grants_and_writes_only_its_directory() { let has_home = std::env::var_os("HOME").is_some(); let mut control = platform - .spawn(ProcessSpec { + .spawn_tree(ProcessSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.clone().into()], cwd: write.clone(), @@ -490,7 +495,7 @@ async fn a_confined_helper_reads_its_grants_and_writes_only_its_directory() { std::fs::remove_file(read.join("escape.txt")).unwrap(); let output = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.into()], @@ -541,7 +546,7 @@ async fn a_confined_helper_reads_its_grants_and_writes_only_its_directory() { "if exec 3<>/dev/tcp/127.0.0.1/{port} 2>/dev/null; then echo tcp=yes; else echo tcp=no; fi\n" ); let mut control = platform - .spawn(ProcessSpec { + .spawn_tree(ProcessSpec { executable: bash.clone(), args: vec!["-c".into(), probe.clone().into()], cwd: write.clone(), @@ -560,7 +565,7 @@ async fn a_confined_helper_reads_its_grants_and_writes_only_its_directory() { "the unconfined control did not reach the listener: {control_output}" ); let output = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: bash, args: vec!["-c".into(), probe.into()], @@ -623,7 +628,7 @@ async fn a_confined_helper_stdout_cap_kills_the_tree() { ); let platform = confined_platform(switch_off()); let result = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.into()], @@ -669,7 +674,7 @@ async fn a_confined_helper_cancel_kills_the_tree() { let platform = confined_platform(switch_off()); let cancel = CancellationToken::new(); let (result, (pid, cancelled_at)) = tokio::join!( - platform.spawn_confined( + platform.spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.into()], @@ -742,7 +747,7 @@ async fn a_confined_helper_refuses_relative_and_missing_paths() { ]; for confinement in cases { let result = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "true".into()], @@ -772,7 +777,7 @@ async fn a_host_without_bubblewrap_runs_the_confined_helper_unconfined() { let mut platform = confined_platform(switch_off()); platform.env = env(&[("PATH", bin.to_str().unwrap())]); let output = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "echo artifact > artifact.txt".into()], @@ -825,7 +830,7 @@ async fn the_isolation_switch_does_not_change_a_confined_helper() { "if exec 3<>/dev/tcp/127.0.0.1/{port} 2>/dev/null; then echo tcp=yes; else echo tcp=no; fi\n" ); let output = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: bash, args: vec!["-c".into(), script.into()], @@ -994,7 +999,7 @@ async fn a_confined_helper_stderr_cap_kills_the_tree() { ); let platform = confined_platform(switch_off()); let result = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.into()], @@ -1050,7 +1055,7 @@ async fn a_confined_helper_gets_the_allowlist_plus_its_own_environment() { quote(&mktemp) ); let output = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.into()], @@ -1156,7 +1161,7 @@ async fn an_exec_resolves_a_command_only_the_toolchain_source_provides() { .build_process_spec("command -v fixturetool", &base) .await .unwrap(); - let mut tree = platform.spawn(spec).unwrap(); + let mut tree = platform.spawn_tree(spec).unwrap(); let mut output = String::new(); tree.stdout().read_to_string(&mut output).await.unwrap(); assert!(tree.wait().await.unwrap().success()); @@ -1172,7 +1177,7 @@ async fn an_exec_resolves_a_command_only_the_toolchain_source_provides() { .build_process_spec("command -v fixturetool", &base) .await .unwrap(); - let mut tree = platform.spawn(spec).unwrap(); + let mut tree = platform.spawn_tree(spec).unwrap(); let mut output = String::new(); tree.stdout().read_to_string(&mut output).await.unwrap(); assert!(tree.wait().await.unwrap().success()); @@ -1183,3 +1188,1157 @@ async fn an_exec_resolves_a_command_only_the_toolchain_source_provides() { ); std::fs::remove_dir_all(base).unwrap(); } + +fn never_cancelled() -> dim_agent_capabilities::host::CancelledFn { + let never = CancellationToken::new(); + std::sync::Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }) +} + +#[tokio::test] +async fn the_host_platform_service_answers_info() { + let platform = HostPlatform::current(ShellStatus::Unavailable { + code: "TEST", + reason: "no shell".into(), + }) + .unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + root.provide_as::(std::sync::Arc::new(platform.clone())) + .unwrap(); + let face = root + .get_at::(&rutis_bridge::session::host_key( + "hostPlatform", + )) + .expect("hostPlatform is served"); + let reply = + rutis_bridge::session::settle(face.invoke("info", serde_json::json!([]).into()).unwrap()) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!( + reply, + serde_json::to_value(platform.info().await.unwrap()).unwrap() + ); +} + +#[test] +fn public_output_has_no_event_fields() { + assert!( + serde_json::from_value::(serde_json::json!({ + "taskId": "task", + "eventCursor": 0 + })) + .is_err() + ); + let reply = serde_json::to_value(OutputPageReply { + text: "done".into(), + bytes: 4, + total_bytes: 4, + next_cursor: None, + truncated: false, + retained_from: 0, + reset: None, + }) + .unwrap(); + assert!(reply.get("events").is_none()); + assert!(reply.get("nextEventCursor").is_none()); + assert!(reply.get("eventRetainedFrom").is_none()); + assert!(reply.get("state").is_none()); +} + +#[test] +fn task_failure_serializes_with_its_code() { + assert_eq!( + serde_json::to_value(TaskFailure::OutputWriteFailed { + message: "disk full".into() + }) + .unwrap(), + serde_json::json!({"code": "output_write_failed", "message": "disk full"}) + ); + assert_eq!( + serde_json::to_value(TaskFailure::ShellExited).unwrap(), + serde_json::json!({"code": "shell_exited"}) + ); +} + +#[tokio::test] +async fn the_host_platform_service_starts_and_waits_for_a_command() { + let dir = std::env::temp_dir().join(unique("dim-host-service")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + let face = root + .get_at::(&rutis_bridge::session::host_key( + "hostPlatform", + )) + .unwrap(); + let invoke = |method: &'static str, request: serde_json::Value| { + let face = face.clone(); + async move { + rutis_bridge::session::settle( + face.invoke(method, serde_json::json!([request]).into()) + .unwrap(), + ) + .await? + .json() + } + }; + let path = dir.to_string_lossy().into_owned(); + let spawn = invoke( + "spawn", + serde_json::json!({ + "taskId": "service-task", + "command": "printf hi", + "cwd": path, + "workspace": path, + "roots": [], + "outputDir": path, + "timeoutMs": 10000 + }), + ) + .await + .unwrap(); + assert_eq!(spawn["taskId"], "service-task"); + let terminal = serde_json::to_value( + platform + .wait( + WaitRequest { + task_id: "service-task".into(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .unwrap(), + ) + .unwrap(); + assert_eq!(terminal["status"], "exited"); + assert_eq!(terminal["text"], "hi"); + assert!(terminal.get("failure").is_none()); + assert_eq!(terminal["preview"], "hi"); + assert_eq!(terminal["outputPath"], spawn["outputPath"]); + let page = invoke( + "output", + serde_json::json!({"taskId": "service-task", "limit": 16}), + ) + .await + .unwrap(); + assert_eq!(page["text"], "hi"); + invoke("settle", serde_json::json!({"taskId": "service-task"})) + .await + .unwrap(); + let missing = platform + .wait( + WaitRequest { + task_id: "service-task".into(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .unwrap_err(); + assert!(matches!(missing, HostPlatformError::TaskUnknown)); + + platform + .spawn(SpawnRequest { + task_id: "long-task".into(), + command: "seq 1 2500".into(), + cwd: path.clone(), + workspace: path.clone(), + roots: Vec::new(), + output_dir: path.clone(), + timeout_ms: Some(10_000), + }) + .await + .unwrap(); + let long = platform + .wait( + WaitRequest { + task_id: "long-task".into(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(long.status, WaitStatus::Exited); + let text = long.text.expect("an inline task keeps its complete text"); + assert_eq!(text.lines().count(), 2_500); + assert!(long.preview.lines().count() <= 2_000); + assert!(long.preview.lines().count() < text.lines().count()); + let retained = platform + .retain_output(TaskRequest { + task_id: "long-task".into(), + }) + .await + .unwrap(); + let file = std::fs::read_to_string(&retained.output_path).unwrap(); + assert_eq!(file, text); + let page = platform + .output(OutputRequest { + task_id: "long-task".into(), + cursor: None, + limit: Some(64 * 1024), + }) + .await + .unwrap(); + assert_eq!(page.text, text); + platform + .settle(TaskRequest { + task_id: "long-task".into(), + }) + .await + .unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[tokio::test] +async fn the_host_platform_service_serves_a_shell() { + let dir = std::env::temp_dir().join(unique("dim-host-shell")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + let face = root + .get_at::(&rutis_bridge::session::host_key( + "hostPlatform", + )) + .unwrap(); + let invoke = |method: &'static str, request: serde_json::Value| { + let face = face.clone(); + async move { + rutis_bridge::session::settle( + face.invoke(method, serde_json::json!([request]).into()) + .unwrap(), + ) + .await? + .json() + } + }; + let path = dir.to_string_lossy().into_owned(); + invoke( + "shell", + serde_json::json!({ + "taskId": "service-shell", + "cwd": path, + "workspace": path, + "roots": [], + "outputDir": path, + "cols": 80, + "rows": 24 + }), + ) + .await + .unwrap(); + invoke( + "write", + serde_json::json!({"taskId": "service-shell", "data": "cHJpbnRmIGhpOyBleGl0IDcK"}), + ) + .await + .unwrap(); + let terminal = platform + .wait( + WaitRequest { + task_id: "service-shell".into(), + timeout_ms: Some(10000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(terminal.status, WaitStatus::Exited); + assert_eq!(terminal.exit_code, Some(7)); + assert!(terminal.preview.contains("hi")); + assert!(std::path::Path::new(&terminal.output_path).exists()); + assert!( + std::fs::read_to_string(&terminal.output_path) + .unwrap() + .contains("hi") + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&terminal.output_path) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + } + let page = invoke( + "output", + serde_json::json!({"taskId": "service-shell", "limit": 4096}), + ) + .await + .unwrap(); + assert!(page["text"].as_str().unwrap().contains("hi")); + assert!(matches!( + platform + .write(ShellWrite { + task_id: "service-shell".into(), + data: String::new(), + command: None, + job: None, + }) + .await, + Err(HostPlatformError::TaskEnded) + )); + invoke("settle", serde_json::json!({"taskId": "service-shell"})) + .await + .unwrap(); + platform + .settle(TaskRequest { + task_id: "service-shell".into(), + }) + .await + .unwrap(); + assert!(std::path::Path::new(&terminal.output_path).exists()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[tokio::test] +async fn the_host_platform_service_runs_a_command_with_stdin() { + let dir = std::env::temp_dir().join(unique("dim-host-stdin")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + let never = CancellationToken::new(); + let cancelled: dim_agent_capabilities::host::CancelledFn = std::sync::Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }); + let reply = platform + .spawn_with_stdin( + SpawnWithStdinRequest { + command: "cat".into(), + cwd: path_string(&dir), + env: Default::default(), + stdin: Some("aGk=".into()), + timeout_ms: 10000, + limits: OutputLimits { + stdout: 64 * 1024, + stderr: 64 * 1024, + }, + }, + cancelled, + ) + .await + .unwrap(); + assert_eq!(reply.status, SpawnWithStdinStatus::Exited); + assert_eq!(reply.exit_code, Some(0)); + assert_eq!(reply.stdout, "aGk="); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[tokio::test] +async fn the_host_platform_service_runs_a_confined_helper() { + let dir = std::env::temp_dir().join(unique("dim-host-confined")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + let never = CancellationToken::new(); + let cancelled: dim_agent_capabilities::host::CancelledFn = std::sync::Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }); + let reply = platform + .spawn_confined( + ConfinedRequest { + program: "/bin/sh".into(), + args: vec!["-c".into(), "printf hi; printf err >&2".into()], + read: vec![], + write: vec![path_string(&dir)], + env: Default::default(), + timeout_ms: 10000, + output_limit: OutputLimits { + stdout: 64 * 1024, + stderr: 64 * 1024, + }, + services: dim_agent_capabilities::host_platform::SystemServices::None, + }, + cancelled, + ) + .await + .unwrap(); + assert_eq!(reply.status, Some(0)); + assert_eq!(reply.stdout, "aGk="); + assert_eq!(reply.stderr, "ZXJy"); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[tokio::test] +async fn the_host_platform_service_removes_output_and_composes_a_path() { + let dir = std::env::temp_dir().join(unique("dim-host-remove")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + let output = dir.join(".dim/exec/session/branch"); + std::fs::create_dir_all(&output).unwrap(); + std::fs::write(output.join("command.log"), b"output").unwrap(); + platform + .remove_output_directory(RemoveOutputDirectoryRequest { + path: path_string(&output), + }) + .await + .unwrap(); + assert!(!output.exists()); + let bin = dir.join("runtimes/bin"); + std::fs::create_dir_all(&bin).unwrap(); + let with_toolchain = toolchain_platform( + &[("PATH", "/bin")], + vec![InstalledToolchain { + bin, + root: dir.join("runtimes"), + }], + ); + let path = with_toolchain + .child_path(ChildPathRequest { + directories: vec!["/opt/dim".into()], + base: "/bin".into(), + }) + .unwrap(); + assert!(path.contains("/opt/dim")); + assert!(path.contains("/bin")); + let refused = platform + .remove_output_directory(RemoveOutputDirectoryRequest { + path: path_string(dir.join(".dim/exec")), + }) + .await + .unwrap_err(); + assert!(matches!(refused, HostPlatformError::Invalid(_))); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[tokio::test] +async fn a_wait_timeout_leaves_the_command_running() { + let dir = std::env::temp_dir().join(unique("dim-host-wait-timeout")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + let path = dir.to_string_lossy().into_owned(); + let spawn: serde_json::Value = serde_json::to_value( + platform + .spawn(SpawnRequest { + task_id: "wait-timeout".into(), + command: "sleep 0.3".into(), + cwd: path_string(&dir), + workspace: path_string(&dir), + roots: Vec::new(), + output_dir: path_string(&dir), + timeout_ms: None, + }) + .await + .unwrap(), + ) + .unwrap(); + assert_eq!(spawn["taskId"], "wait-timeout"); + let first = platform + .wait( + WaitRequest { + task_id: "wait-timeout".into(), + timeout_ms: Some(10), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(first.status, WaitStatus::Running); + let second = platform + .wait( + WaitRequest { + task_id: "wait-timeout".into(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(second.status, WaitStatus::Exited); + platform + .settle(TaskRequest { + task_id: "wait-timeout".into(), + }) + .await + .unwrap(); + let _ = path; + std::fs::remove_dir_all(dir).unwrap(); +} + +#[tokio::test] +async fn output_removal_refuses_traversal_and_links() { + let dir = std::env::temp_dir().join(unique("dim-host-remove-safety")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + let exec_root = dir.join(".dim/exec"); + let outside = dir.join("outside"); + std::fs::create_dir_all(exec_root.join("session/branch")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("keep"), b"keep").unwrap(); + let traversal = exec_root.join("session/branch/../../outside"); + let error = platform + .remove_output_directory(RemoveOutputDirectoryRequest { + path: path_string(traversal), + }) + .await + .unwrap_err(); + assert!(matches!(error, HostPlatformError::Invalid(_))); + assert!(outside.join("keep").exists()); + let root_error = platform + .remove_output_directory(RemoveOutputDirectoryRequest { + path: path_string(&exec_root), + }) + .await + .unwrap_err(); + assert!(matches!(root_error, HostPlatformError::Invalid(_))); + #[cfg(unix)] + { + let link = exec_root.join("session/link"); + std::os::unix::fs::symlink(&outside, &link).unwrap(); + let link_error = platform + .remove_output_directory(RemoveOutputDirectoryRequest { + path: path_string(link), + }) + .await + .unwrap_err(); + assert!(matches!(link_error, HostPlatformError::Invalid(_))); + assert!(outside.join("keep").exists()); + let real = exec_root.join("session/real"); + std::fs::create_dir_all(real.join("child")).unwrap(); + let alias = exec_root.join("session/alias"); + std::os::unix::fs::symlink(&real, &alias).unwrap(); + let component = platform + .remove_output_directory(RemoveOutputDirectoryRequest { + path: path_string(alias.join("child")), + }) + .await + .unwrap_err(); + assert!(matches!(component, HostPlatformError::Invalid(_))); + assert!(real.join("child").exists()); + } + platform + .remove_output_directory(RemoveOutputDirectoryRequest { + path: path_string(exec_root.join("session/absent")), + }) + .await + .unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[tokio::test] +async fn a_shell_burst_completes_without_a_private_subscriber() { + let dir = std::env::temp_dir().join(unique("dim-host-burst")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + platform + .shell(ShellRequest { + task_id: "burst-shell".into(), + cwd: path_string(&dir), + workspace: path_string(&dir), + roots: Vec::new(), + output_dir: path_string(&dir), + cols: 80, + rows: 24, + }) + .await + .unwrap(); + let token = format!("BURST-{}", uuid::Uuid::new_v4().simple()); + std::fs::write(dir.join("burst-token"), &token).unwrap(); + let burst = format!( + "printf '%s%s\\n' '__DIM_START_aaaabbbb_' 'ccccdddd__'; seq 1 400000; printf 'OUTPUT-'; cat '{}'; printf '\\n'; printf '%s%s%d\\n' '__DIM_END_eeeefaff_' '00001111__' 0", + dir.join("burst-token").display() + ) + "\n"; + platform + .write(ShellWrite { + task_id: "burst-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(burst.as_bytes()), + command: Some(ShellCommandStart { + task_id: "burst-command".into(), + start_marker: "__DIM_START_aaaabbbb_ccccdddd__".into(), + end_marker: "__DIM_END_eeeefaff_00001111__".into(), + }), + job: None, + }) + .await + .unwrap(); + let mut seen = false; + let mut last = String::new(); + for _ in 0..2000 { + let page = platform + .output(OutputRequest { + task_id: "burst-shell".into(), + cursor: None, + limit: Some(64 * 1024), + }) + .await + .unwrap(); + last = page.text; + if last.contains(&token) { + seen = true; + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!( + seen, + "the shell output never reached the public page: {last:?}" + ); + let terminal = platform + .wait( + WaitRequest { + task_id: "burst-command".into(), + timeout_ms: Some(30_000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(terminal.status, WaitStatus::Exited); + platform + .settle(TaskRequest { + task_id: "burst-command".into(), + }) + .await + .unwrap(); + platform + .kill(TaskRequest { + task_id: "burst-shell".into(), + }) + .await + .unwrap(); + platform + .settle(TaskRequest { + task_id: "burst-shell".into(), + }) + .await + .unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[tokio::test] +async fn a_shell_command_capture_is_owned_by_the_host() { + let dir = std::env::temp_dir().join(unique("dim-host-command-capture")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + platform + .shell(ShellRequest { + task_id: "capture-shell".into(), + cwd: path_string(&dir), + workspace: path_string(&dir), + roots: Vec::new(), + output_dir: path_string(&dir), + cols: 80, + rows: 24, + }) + .await + .unwrap(); + platform + .write(ShellWrite { + task_id: "capture-shell".into(), + data: "cHJpbnRmICclcyVzXG4nICdfX0RJTV9TVEFSVF9hYWFhYmJiYl8nICdjY2NjZGRkZF9fJzsgcHJpbnRmICclcyVzJWRcbicgJ19fRElNX0VORF8xMTExMjIyMl8nICczMzMzNDQ0NF9fJyAwOyBwcmludGYgaGk7IHByaW50ZiAnJXMlcyVkXG4nICdfX0RJTV9FTkRfZWVlZWZmZmZfJyAnMDAwMDExMTFfXycgMAo=".into(), + command: Some(ShellCommandStart { + task_id: "owner-command".into(), + start_marker: "__DIM_START_aaaabbbb_ccccdddd__".into(), + end_marker: "__DIM_END_eeeeffff_00001111__".into(), + }), + job: None, + }) + .await + .unwrap(); + let finished = platform + .wait( + WaitRequest { + task_id: "owner-command".into(), + timeout_ms: Some(10_000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(finished.status, WaitStatus::Exited); + let page = platform + .output(OutputRequest { + task_id: "owner-command".into(), + cursor: None, + limit: Some(4096), + }) + .await + .unwrap(); + assert!(page.text.contains("hi"), "{:?}", page.text); + assert!(!page.text.contains("11112222"), "{:?}", page.text); + let tail = platform + .tail(TaskRequest { + task_id: "owner-command".into(), + }) + .await + .unwrap(); + assert!(tail.text.contains("hi"), "{:?}", tail.text); + let retained = platform + .retain_output(TaskRequest { + task_id: "owner-command".into(), + }) + .await + .unwrap(); + assert!(retained.output_path.ends_with(".log")); + platform + .settle(TaskRequest { + task_id: "owner-command".into(), + }) + .await + .unwrap(); + let failing = "printf '%s%s' '__DIM_START_aaaabbbb_' 'ccccdddd__'; false; printf '%s%s%d\\n' '__DIM_END_eeeeffff_' '00001111__' 3\n"; + platform + .write(ShellWrite { + task_id: "capture-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(failing.as_bytes()), + command: Some(ShellCommandStart { + task_id: "failing-command".into(), + start_marker: "__DIM_START_aaaabbbb_ccccdddd__".into(), + end_marker: "__DIM_END_eeeeffff_00001111__".into(), + }), + job: None, + }) + .await + .unwrap(); + let failed = platform + .wait( + WaitRequest { + task_id: "failing-command".into(), + timeout_ms: Some(10_000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(failed.status, WaitStatus::Failed); + assert_eq!(failed.exit_code, Some(3)); + assert_eq!(failed.failure, Some(TaskFailure::CommandFailed)); + assert_eq!(failed.text, None); + platform + .settle(TaskRequest { + task_id: "failing-command".into(), + }) + .await + .unwrap(); + let capped = "printf '%s%s' '__DIM_START_22223333_' '44445555__'; head -c 65533 /dev/zero | tr '\\0' a; printf '\\n\\303\\251\\n'; printf '%s%s%d\\n' '__DIM_END_66667777_' '88889999__' 0\n"; + platform + .write(ShellWrite { + task_id: "capture-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(capped.as_bytes()), + command: Some(ShellCommandStart { + task_id: "capped-command".into(), + start_marker: "__DIM_START_22223333_44445555__".into(), + end_marker: "__DIM_END_66667777_88889999__".into(), + }), + job: None, + }) + .await + .unwrap(); + let capped_end = platform + .wait( + WaitRequest { + task_id: "capped-command".into(), + timeout_ms: Some(10_000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(capped_end.status, WaitStatus::Exited); + let inside = platform + .output(OutputRequest { + task_id: "capped-command".into(), + cursor: Some(65_535), + limit: Some(16), + }) + .await + .unwrap(); + assert!(inside.text.is_empty(), "{:?}", inside.text); + assert_eq!(inside.bytes, 0); + assert_eq!(inside.total_bytes, capped_end.output_bytes); + assert!(inside.next_cursor.is_none()); + let whole = platform + .output(OutputRequest { + task_id: "capped-command".into(), + cursor: Some(65_534), + limit: Some(16), + }) + .await + .unwrap(); + assert_eq!(whole.text, "é"); + assert_eq!(whole.total_bytes, capped_end.output_bytes); + assert_eq!(whole.bytes, 2); + platform + .settle(TaskRequest { + task_id: "capped-command".into(), + }) + .await + .unwrap(); + let long = "printf '%s%s\\n' '__DIM_START_aaaabbbb_' 'ccccdddd__'; sleep 30\n"; + platform + .write(ShellWrite { + task_id: "capture-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(long.as_bytes()), + command: Some(ShellCommandStart { + task_id: "long-command".into(), + start_marker: "__DIM_START_aaaabbbb_ccccdddd__".into(), + end_marker: "__DIM_END_eeeefaff_00001111__".into(), + }), + job: None, + }) + .await + .unwrap(); + let second = platform + .write(ShellWrite { + task_id: "capture-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(b"echo second\n"), + command: Some(ShellCommandStart { + task_id: "second-command".into(), + start_marker: "__DIM_START_11112222_33334444__".into(), + end_marker: "__DIM_END_55556666_77778888__".into(), + }), + job: None, + }) + .await; + assert!(matches!(second, Err(HostPlatformError::TaskRunning))); + let retained = platform + .retain_output(TaskRequest { + task_id: "capture-shell".into(), + }) + .await + .unwrap(); + platform + .kill(TaskRequest { + task_id: "capture-shell".into(), + }) + .await + .unwrap(); + platform + .settle(TaskRequest { + task_id: "capture-shell".into(), + }) + .await + .unwrap(); + assert!(std::path::Path::new(&retained.output_path).exists()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[tokio::test] +async fn a_job_write_terminalizes_and_reads_its_output() { + let dir = std::env::temp_dir().join(unique("dim-host-job")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + platform + .shell(ShellRequest { + task_id: "job-shell".into(), + cwd: path_string(&dir), + workspace: path_string(&dir), + roots: Vec::new(), + output_dir: path_string(&dir), + cols: 80, + rows: 24, + }) + .await + .unwrap(); + let missing_parent = dir.join("missing").join("job-2.log"); + let invalid = platform + .write(ShellWrite { + task_id: "job-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(b"printf 'x'\n"), + command: None, + job: Some(ShellJobStart { + task_id: "job-2".into(), + end_marker: "__DIM_END_aaaabbbb_ccccdddd__".into(), + output_path: missing_parent.to_string_lossy().into_owned(), + }), + }) + .await; + assert!(matches!(invalid, Err(HostPlatformError::Invalid(_)))); + let output_path = dir.join("job-1.log"); + let line = format!( + "printf '\\033'; printf '\\033['; printf '\\033[2~'; printf '\\033]0;t\\033\\\\'; printf 'job-output\\n' > '{}'; printf '%s%s%d\\n' '__DIM_END_aaaabbbb_' 'ccccdddd__' 0\n", + output_path.display() + ); + platform + .write(ShellWrite { + task_id: "job-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(line.as_bytes()), + command: None, + job: Some(ShellJobStart { + task_id: "job-1".into(), + end_marker: "__DIM_END_aaaabbbb_ccccdddd__".into(), + output_path: output_path.to_string_lossy().into_owned(), + }), + }) + .await + .unwrap(); + let reply = platform + .wait( + WaitRequest { + task_id: "job-1".into(), + timeout_ms: Some(5_000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(reply.status, WaitStatus::Exited, "job reply: {reply:?}"); + assert_eq!(reply.exit_code, Some(0)); + let page = platform + .output(OutputRequest { + task_id: "job-1".into(), + cursor: None, + limit: Some(16 * 1024), + }) + .await + .unwrap(); + assert!(page.text.contains("job-output"), "{}", page.text); + platform + .settle(TaskRequest { + task_id: "job-1".into(), + }) + .await + .unwrap(); + let reused = platform + .write(ShellWrite { + task_id: "job-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(b"printf 'again'\n"), + command: None, + job: Some(ShellJobStart { + task_id: "job-1".into(), + end_marker: "__DIM_END_aaaabbbb_ccccdddd__".into(), + output_path: output_path.to_string_lossy().into_owned(), + }), + }) + .await; + assert!(matches!(reused, Err(HostPlatformError::TaskExists))); + platform + .kill(TaskRequest { + task_id: "job-shell".into(), + }) + .await + .unwrap(); + platform + .settle(TaskRequest { + task_id: "job-shell".into(), + }) + .await + .unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} 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..fae63168b1 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs @@ -2,6 +2,7 @@ //! (`docs/architecture/rust-agent/plugins/HostPlatform.md`). The platform has //! no confinement backend, so the timeout, output caps and cancellation apply //! and the result reports `confined: false`. +use base64::Engine; use dim_agent_capabilities::execution_settings::{ExecutionSettings, ExecutionSettingsHost}; use dim_agent_capabilities::host_platform::*; use std::{ffi::OsString, path::PathBuf, time::Duration}; @@ -17,69 +18,97 @@ fn platform() -> HostPlatform { .with_execution_settings(ExecutionSettingsHost::fixed(ExecutionSettings::default())) } -fn command(script: &str) -> ConfinedSpec { +fn request( + script: &str, + timeout: Duration, + stdout_limit: usize, + write: &std::path::Path, +) -> ConfinedRequest { let executable = std::env::var_os("ComSpec") .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from(r"C:\Windows\System32\cmd.exe")); - ConfinedSpec { - executable, + ConfinedRequest { + program: executable.to_str().expect("ComSpec is UTF-8").to_owned(), args: ["/d", "/s", "/v:off", "/c", script] .into_iter() .map(OsString::from) + .map(|arg| arg.to_str().expect("argument is UTF-8").to_owned()) .collect(), - env: vec![], + read: Vec::new(), + write: vec![write.to_str().expect("temporary path is UTF-8").to_owned()], + env: Default::default(), + timeout_ms: timeout.as_millis() as u64, + output_limit: OutputLimits { + stdout: stdout_limit, + stderr: 1024, + }, + services: SystemServices::None, } } +fn cancelled(token: &CancellationToken) -> dim_agent_capabilities::host::CancelledFn { + let token = token.clone(); + std::sync::Arc::new(move || { + let token = token.clone(); + Box::pin(async move { + token.cancelled().await; + Ok(()) + }) + }) +} + #[tokio::test] async fn a_helper_without_a_backend_reports_no_confinement_and_keeps_every_limit() { let write = std::env::temp_dir().join(format!("dim-confined-{}", std::process::id())); std::fs::create_dir_all(&write).unwrap(); - let confinement = |timeout: Duration| Confinement { - read: vec![], - write: vec![write.clone()], - timeout, - stdout_limit: 1024, - stderr_limit: 1024, - services: SystemServices::None, - }; + let platform = platform(); - let ok = platform() + let ok = platform .spawn_confined( - command("echo ok"), - confinement(Duration::from_secs(30)), - CancellationToken::new(), + request("echo ok", Duration::from_secs(30), 1024, &write), + cancelled(&CancellationToken::new()), ) .await .unwrap(); - assert!(ok.status.success()); + assert_eq!(ok.status, Some(0)); assert!(!ok.confined, "Windows cannot confine a host-owned helper"); - assert_eq!(String::from_utf8_lossy(&ok.stdout).trim(), "ok"); + let stdout = base64::engine::general_purpose::STANDARD + .decode(&ok.stdout) + .unwrap(); + assert_eq!(String::from_utf8_lossy(&stdout).trim(), "ok"); - let timed = platform() + let timed = platform .spawn_confined( - command("ping -n 61 127.0.0.1 >nul"), - confinement(Duration::from_millis(300)), - CancellationToken::new(), + request( + "ping -n 61 127.0.0.1 >nul", + Duration::from_millis(300), + 1024, + &write, + ), + cancelled(&CancellationToken::new()), ) .await; assert!( - matches!(timed, Err(ConfinedError::TimedOut)), + matches!(timed, Err(HostPlatformError::TimedOut)), "{:?}", timed.err() ); - let flooded = platform() + let flooded = platform .spawn_confined( - command("for /L %i in (1,1,100000) do @echo 01234567890123456789"), - confinement(Duration::from_secs(30)), - CancellationToken::new(), + request( + "for /L %i in (1,1,100000) do @echo 01234567890123456789", + Duration::from_secs(30), + 1024, + &write, + ), + cancelled(&CancellationToken::new()), ) .await; assert!( matches!( flooded, - Err(ConfinedError::OutputLimit { + Err(HostPlatformError::OutputLimit { stream: ConfinedStream::Stdout }) ), @@ -88,22 +117,26 @@ async fn a_helper_without_a_backend_reports_no_confinement_and_keeps_every_limit ); let cancel = CancellationToken::new(); - let cancel_platform = platform(); - let (cancelled, ()) = tokio::join!( - cancel_platform.spawn_confined( - command("ping -n 61 127.0.0.1 >nul"), - confinement(Duration::from_secs(30)), - cancel.clone(), + let cancel_task = async { + tokio::time::sleep(Duration::from_millis(200)).await; + cancel.cancel(); + }; + let (result, ()) = tokio::join!( + platform.spawn_confined( + request( + "ping -n 61 127.0.0.1 >nul", + Duration::from_secs(30), + 1024, + &write, + ), + cancelled(&cancel), ), - async { - tokio::time::sleep(Duration::from_millis(200)).await; - cancel.cancel(); - }, + cancel_task, ); assert!( - matches!(cancelled, Err(ConfinedError::Cancelled)), + matches!(result, Err(HostPlatformError::Cancelled)), "{:?}", - cancelled.err() + result.err() ); std::fs::remove_dir_all(&write).unwrap(); } diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 12eb3af853..867cc94d07 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -697,6 +697,10 @@ impl Session { pub fn service(&self, branch: &str) -> Result> { self.published(branch)?.service::() } + /// Reads a capability service when the loaded profile provides it. + pub fn service_opt(&self, branch: &str) -> Result>> { + self.published(branch)?.service_opt::() + } /// Observes publication progress without exposing Timeline mutation. pub fn publication(&self, branch: &str) -> Result { Ok(self.published(branch)?.publication()) diff --git a/crates/dim-agent-runtime/src/branch.rs b/crates/dim-agent-runtime/src/branch.rs index a188a590fa..bf7e6ac1a1 100644 --- a/crates/dim-agent-runtime/src/branch.rs +++ b/crates/dim-agent-runtime/src/branch.rs @@ -147,6 +147,9 @@ impl Branch { pub fn service(&self) -> Result> { self.0.public::() } + pub fn service_opt(&self) -> Result>> { + self.0.public_opt::() + } /// The branch scope and the capabilities it installed. pub fn diagnostics(&self) -> rutis::host::diagnostics::RuntimeDiagnostics { self.0.diagnostics() diff --git a/crates/dim-agent-runtime/src/timeline_context.rs b/crates/dim-agent-runtime/src/timeline_context.rs index 40223f0ec6..10e95895c0 100644 --- a/crates/dim-agent-runtime/src/timeline_context.rs +++ b/crates/dim-agent-runtime/src/timeline_context.rs @@ -317,6 +317,10 @@ impl TimelineContext { crate::names::in_group::(&self.catalog, crate::BRANCH_GROUP)?; self.port::(std::any::type_name::()) } + pub(crate) fn public_opt(&self) -> Result>> { + crate::names::in_group::(&self.catalog, crate::BRANCH_GROUP)?; + Ok(self.ctx.get_at::(&self.scope.key::())) + } pub(crate) fn port(&self, name: &str) -> Result> { self.ctx .get_at::(&self.scope.key::()) diff --git a/crates/dim-app-server/src/connection.rs b/crates/dim-app-server/src/connection.rs index 6959298b0b..cccd28dcc7 100644 --- a/crates/dim-app-server/src/connection.rs +++ b/crates/dim-app-server/src/connection.rs @@ -7,6 +7,7 @@ use crate::{ skills_management::skills_error, }; use dim_agent_capabilities::{ + exec_stop::{self, ExecStop}, host::{ModelPortError, ModelSelectionRequest}, methods::{Accepted, CallSite, CallerConnection, Callers, NotifyError, RpcError}, permission::{Permission, PermissionState, PermissionUpdateError}, @@ -1628,19 +1629,35 @@ impl Connection { if p.task_id.is_empty() { return Err(RpcError::invalid("taskId must not be empty")); } - let result = session - .service::(&p.branch_id)? - .stop(p.task_id) - .await - .map_err(|error| match error { - TaskError::Unknown => RpcError::app( + let result = if let Some(stop) = + session.service_opt::(&p.branch_id)? + { + stop.stop(p.task_id).await.map_err(|error| match error { + exec_stop::TaskError::Unknown => RpcError::app( -32000, "exec_task_unknown", "Command is not a task of this branch", ), - TaskError::Closed => RpcError::reloading(), - TaskError::Read(error) => error.into(), - })?; + exec_stop::TaskError::Closed => RpcError::reloading(), + exec_stop::TaskError::Read => { + RpcError::app(-32603, "exec_task_read", "Task facts could not be read") + } + })? + } else { + session + .service::(&p.branch_id)? + .stop(p.task_id) + .await + .map_err(|error| match error { + TaskError::Unknown => RpcError::app( + -32000, + "exec_task_unknown", + "Command is not a task of this branch", + ), + TaskError::Closed => RpcError::reloading(), + TaskError::Read(error) => error.into(), + })? + }; Reply::ExecEnded(result) } Call::SessionSkills(p) => { diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index a86735a06f..16576b75cf 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1685,7 +1685,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/stdio.rs b/crates/dim-app-server/src/mcp/server/stdio.rs index beaea3d37e..4b14de00e4 100644 --- a/crates/dim-app-server/src/mcp/server/stdio.rs +++ b/crates/dim-app-server/src/mcp/server/stdio.rs @@ -157,7 +157,7 @@ impl Config { .map(|(_, value)| value.clone()) }) .unwrap_or_default(); - platform.child_path(&[], &base) + platform.child_path_process(&[], &base) } pub fn spawn( diff --git a/crates/dim-app-server/src/storage/files.rs b/crates/dim-app-server/src/storage/files.rs index 748655492f..1fc56d3211 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::{HostPlatform, HostPlatformError, RemoveOutputDirectoryRequest}, }; use rusqlite::{Connection, TransactionBehavior, params}; use rutis::Ctx; @@ -364,17 +364,17 @@ impl SessionFiles { .ok_or_else(|| error("the Session's resource node storage is unavailable"))?; 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)) + if let Some(host) = host.as_ref() { + match host + .remove_output_directory(RemoveOutputDirectoryRequest { + path: candidate.to_string_lossy().into_owned(), + }) .await - .map_err(error)? - .map_err(error)?; - continue; + { + Ok(()) => continue, + Err(HostPlatformError::Invalid(_) | HostPlatformError::InvalidPath { .. }) => {} + Err(failure) => return Err(error(failure.to_string())), + } } let relative = candidate .strip_prefix(storage.root_path(self.0.root).map_err(error)?) diff --git a/crates/dim-app-server/tests/transport_flow/exec_shell_settings.rs b/crates/dim-app-server/tests/transport_flow/exec_shell_settings.rs index 3db046740e..f6b85e9d8f 100644 --- a/crates/dim-app-server/tests/transport_flow/exec_shell_settings.rs +++ b/crates/dim-app-server/tests/transport_flow/exec_shell_settings.rs @@ -55,10 +55,7 @@ async fn execution_shell_settings_are_revisioned_and_used_by_the_host() { let dim_agent_capabilities::host_platform::ShellStatus::Available(shell) = resolution else { panic!("saved preference must be executable by HostPlatform"); }; - assert_eq!( - shell.executable_path.to_string_lossy(), - executable.as_str().unwrap() - ); + assert_eq!(shell.executable_path.as_str(), executable.as_str().unwrap()); for invalid in [ json!({"expectedRevision":saved["result"]["revision"],"executablePath":"/missing/dim-test-shell"}), json!({"expectedRevision":saved["result"]["revision"],"executablePath":null}), 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 e4276e57b1..633d1dc703 100644 --- a/crates/dim-app-server/tests/transport_flow/process_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/process_typescript.rs @@ -1440,11 +1440,12 @@ async fn node_store_preserves_repository_results_and_worktree_removal_exclusion( cwd: workspace.to_string_lossy().into_owned(), ..Default::default() }; - let protected = server + let exec_root = server .service::() .unwrap() .exec_root() - .join("store-face-protected"); + .unwrap(); + let protected = PathBuf::from(exec_root).join("store-face-protected"); std::fs::create_dir_all(&protected).unwrap(); let marker = protected.join("keep"); std::fs::write(&marker, "untouched").unwrap(); @@ -1619,10 +1620,12 @@ async fn node_store_preserves_repository_results_and_worktree_removal_exclusion( }})).await; assert_ok(&created); assert!(store.has_records("wire-source").await.unwrap()); - let output = server + let exec_root = server .service::() .unwrap() .exec_root() + .unwrap(); + let output = PathBuf::from(exec_root) .join("fixture-owned-output") .join("stdout"); std::fs::create_dir_all(output.parent().unwrap()).unwrap(); diff --git a/crates/dim-app-server/tests/transport_flow/shell_input.rs b/crates/dim-app-server/tests/transport_flow/shell_input.rs index 3c4f9d6f02..d6da9c2df1 100644 --- a/crates/dim-app-server/tests/transport_flow/shell_input.rs +++ b/crates/dim-app-server/tests/transport_flow/shell_input.rs @@ -461,7 +461,7 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { assert_ok(&empty); assert_eq!( empty["result"], - json!({"text":"","bytes":0,"truncated":false}) + json!({"text":"","bytes":0,"totalBytes":0,"truncated":false}) ); std::fs::write(shell.work.join("go1"), b"go").unwrap(); let first = tokio::time::timeout(Duration::from_secs(5), async { @@ -476,14 +476,15 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { }) .await .unwrap(); - assert_eq!( - first["result"], - json!({"text":"alpha\n","bytes":6,"truncated":false}) - ); + assert_eq!(first["result"]["text"], "alpha\n"); + assert_eq!(first["result"]["bytes"], 6); + assert!(first["result"]["totalBytes"].as_u64().unwrap() >= 6); + assert_eq!(first["result"]["truncated"], false); // A cursor already handed out rereads the same bytes. let reread = exec_output_page(&mut shell, ¶ms, 0, 64).await; assert_ok(&reread); - assert_eq!(reread["result"], first["result"]); + assert_eq!(reread["result"]["text"], first["result"]["text"]); + assert_eq!(reread["result"]["bytes"], first["result"]["bytes"]); // A page can meet the file ending inside a character, which a read sees // when it catches a write in progress; completed writes end on a // boundary, so write the first byte of a two-byte character directly to @@ -503,10 +504,10 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { drop(file); let partial = exec_output_page(&mut shell, ¶ms, 0, 64).await; assert_ok(&partial); - assert_eq!( - partial["result"], - json!({"text":"alpha\n","bytes":6,"truncated":false}) - ); + assert_eq!(partial["result"]["text"], "alpha\n"); + assert_eq!(partial["result"]["bytes"], 6); + assert!(partial["result"]["totalBytes"].as_u64().unwrap() >= 6); + assert_eq!(partial["result"]["truncated"], false); let next = partial["result"]["bytes"].as_u64().unwrap(); let mut file = std::fs::OpenOptions::new() .append(true) @@ -518,7 +519,7 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { assert_ok(&completed); assert_eq!( completed["result"], - json!({"text":"é","bytes":2,"truncated":false}) + json!({"text":"é","bytes":2,"totalBytes":6,"truncated":false}) ); std::fs::write(shell.work.join("go2"), b"go").unwrap(); // A short page carries no next cursor; the walk advances by `cursor + @@ -540,7 +541,7 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { assert_ok(&beta); assert_eq!( beta["result"], - json!({"text":"beta\n","bytes":6,"truncated":false}) + json!({"text":"beta\n","bytes":6,"totalBytes":12,"truncated":false}) ); std::fs::write(shell.work.join("go3"), b"go").unwrap(); tokio::time::timeout(Duration::from_secs(5), async { @@ -602,7 +603,7 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { assert_ok(&finished); assert_eq!( finished["result"], - json!({"text":"alpha\nbeta\ngamma\n","bytes":18,"truncated":false}) + json!({"text":"alpha\nbeta\ngamma\n","bytes":18,"totalBytes":18,"truncated":false}) ); // Concatenated pages equal the file, minus the control character the // preview rule strips. @@ -648,7 +649,7 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { assert_ok(&restored); assert_eq!( restored["result"], - json!({"text":"alpha\nbeta\ngamma\n","bytes":18,"truncated":false}) + json!({"text":"alpha\nbeta\ngamma\n","bytes":18,"totalBytes":18,"truncated":false}) ); let stopped = shell.client.rpc("session.exec.stop", params.clone()).await; assert_ok(&stopped); @@ -721,13 +722,13 @@ async fn background_exec_output_page_clamps_scopes_and_errors() { assert_ok(&first); assert_eq!( first["result"], - json!({"text":"012345678","bytes":9,"nextCursor":9,"truncated":false}) + json!({"text":"012345678","bytes":9,"totalBytes":13,"nextCursor":9,"truncated":false}) ); let second = exec_output_page(&mut shell, ¶ms, 9, 10).await; assert_ok(&second); assert_eq!( second["result"], - json!({"text":"éX\n","bytes":4,"truncated":false}) + json!({"text":"éX\n","bytes":4,"totalBytes":13,"truncated":false}) ); assert!(!first["result"]["text"].as_str().unwrap().contains('é')); assert!(second["result"]["text"].as_str().unwrap().starts_with('é')); @@ -736,7 +737,7 @@ async fn background_exec_output_page_clamps_scopes_and_errors() { assert_ok(&whole); assert_eq!( whole["result"], - json!({"text":"012345678éX\n","bytes":13,"truncated":false}) + json!({"text":"012345678éX\n","bytes":13,"totalBytes":13,"truncated":false}) ); // A budget that cuts the very first character serves it whole: the page // still consumes it and the cursor moves, even at `limit: 1`. @@ -744,7 +745,7 @@ async fn background_exec_output_page_clamps_scopes_and_errors() { assert_ok(&cut); assert_eq!( cut["result"], - json!({"text":"é","bytes":2,"nextCursor":11,"truncated":false}) + json!({"text":"é","bytes":2,"totalBytes":13,"nextCursor":11,"truncated":false}) ); // Walking the whole file at `limit: 1` by `cursor + bytes` terminates and // reassembles it. @@ -768,7 +769,7 @@ async fn background_exec_output_page_clamps_scopes_and_errors() { assert_ok(&inside); assert_eq!( inside["result"], - json!({"text":"","bytes":0,"truncated":false}) + json!({"text":"","bytes":0,"totalBytes":13,"truncated":false}) ); for invalid in [ json!({"sessionId":shell.sid,"branchId":"main","taskId":task,"limit":0}), @@ -897,7 +898,7 @@ async fn background_exec_output_page_clamps_scopes_and_errors() { assert_ok(&face_page); assert_eq!( face_page["result"], - json!({"text":"😀","bytes":4,"nextCursor":4,"truncated":false}) + json!({"text":"😀","bytes":4,"totalBytes":5,"nextCursor":4,"truncated":false}) ); // A removed registered file is the page method's own error. std::fs::remove_file( diff --git a/crates/dim-modality/src/engine.rs b/crates/dim-modality/src/engine.rs index 43a0ddf670..7e853ed2a9 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, + ConfinedReply, ConfinedRequest, HostPlatform, HostPlatformError, OutputLimits, SystemServices, }; use dim_agent_capabilities::methods::{Progress, RpcError}; use dim_agent_types::ModelId; @@ -2276,22 +2276,84 @@ impl Shared { OsString::from("--output-mode"), OsString::from(params.output_mode.as_str()), ]); - let spec = ConfinedSpec { - executable, - args, - env, + let strings = (|| -> Result<_, String> { + let program = executable + .to_str() + .ok_or_else(|| "The OCR helper path is not UTF-8".to_owned())? + .to_owned(); + let args = args + .iter() + .map(|arg| { + arg.to_str() + .map(str::to_owned) + .ok_or_else(|| "An OCR helper argument is not UTF-8".to_owned()) + }) + .collect::, _>>()?; + let read = read + .into_iter() + .map(|path| { + path.to_str() + .map(str::to_owned) + .ok_or_else(|| "An OCR read path is not UTF-8".to_owned()) + }) + .collect::, _>>()?; + let write = write + .into_iter() + .map(|path| { + path.to_str() + .map(str::to_owned) + .ok_or_else(|| "An OCR write path is not UTF-8".to_owned()) + }) + .collect::, _>>()?; + let env = env + .into_iter() + .map(|(key, value)| { + Ok(( + key.to_str() + .ok_or_else(|| "An OCR environment key is not UTF-8".to_owned())? + .to_owned(), + value + .to_str() + .ok_or_else(|| "An OCR environment value is not UTF-8".to_owned())? + .to_owned(), + )) + }) + .collect::, String>>()?; + Ok((program, args, read, write, env)) + })(); + let (program, args, read, write, env) = match strings { + Ok(strings) => strings, + Err(reason) => { + if !slot.cancel_requested() { + self.fail_host(slot, "executor_error", reason).await; + } + return; + } }; - let confinement = Confinement { + let request = ConfinedRequest { + program, + args, read, write, - timeout: OCR_TIMEOUT, - stdout_limit: OCR_STDOUT_LIMIT, - stderr_limit: OCR_STDERR_LIMIT, + env: env.into_iter().collect(), + timeout_ms: OCR_TIMEOUT.as_millis() as u64, + output_limit: OutputLimits { + stdout: OCR_STDOUT_LIMIT, + stderr: OCR_STDERR_LIMIT, + }, services, }; - let outcome = platform - .spawn_confined(spec, confinement, slot.cancel.child_token()) - .await; + let cancelled: dim_agent_capabilities::host::CancelledFn = { + let cancel = slot.cancel.child_token(); + std::sync::Arc::new(move || { + let cancel = cancel.clone(); + Box::pin(async move { + cancel.cancelled().await; + Ok(()) + }) + }) + }; + let outcome = platform.spawn_confined(request, cancelled).await; if slot.cancel_requested() { // The helper was killed: nothing it wrote is published (A.2.1). let _ = task::remove_work(&self.files, &record.task_id).await; @@ -2302,7 +2364,7 @@ impl Shared { self.record_confined(slot, output.confined).await; output } - Err(ConfinedError::Cancelled) => { + Err(HostPlatformError::Cancelled) => { let _ = task::remove_work(&self.files, &record.task_id).await; return; } @@ -2310,15 +2372,15 @@ impl Shared { // A path the description names that no longer exists is the // copy becoming unreadable, not a request error (A.2.1). let (code, message) = match &error { - ConfinedError::InvalidPath { path, .. } - if plugin_target && path != &input.path => + HostPlatformError::InvalidPath { path, .. } + if plugin_target && Path::new(path) != input.path => { ( "executor_error", - format!("The OCR helper's copy is unreadable: {path:?}"), + format!("The OCR helper's copy is unreadable: {path}"), ) } - _ => (confinement_code(&error), error.to_string()), + _ => (platform_error_code(&error), error.to_string()), }; self.fail_host(slot, code, message).await; return; @@ -2354,9 +2416,11 @@ impl Shared { /// Maps one finished helper call to a terminal outcome (decision 7): /// exit 0 publishes the artifacts, exit 2 carries a typed code, anything /// else is `executor_error` with the tail of standard error. - async fn settle_host(self: &Arc, slot: &Arc, output: ConfinedOutput) { - let stdout = String::from_utf8_lossy(&output.stdout); - match output.status.code() { + async fn settle_host(self: &Arc, slot: &Arc, output: ConfinedReply) { + let stdout = STANDARD.decode(&output.stdout).unwrap_or_default(); + let stderr = STANDARD.decode(&output.stderr).unwrap_or_default(); + let stdout = String::from_utf8_lossy(&stdout); + match output.status { Some(0) => { let ok = serde_json::from_str::(stdout.trim()) .is_ok_and(|payload| payload.ok); @@ -2366,7 +2430,7 @@ impl Shared { "executor_error", format!( "The OCR helper printed no success line{}", - stderr_tail(&output.stderr) + stderr_tail(&stderr) ), ) .await; @@ -2403,7 +2467,7 @@ impl Shared { self.fail_host( slot, "executor_error", - format!("The OCR helper failed{}", stderr_tail(&output.stderr)), + format!("The OCR helper failed{}", stderr_tail(&stderr)), ) .await; } @@ -2827,9 +2891,17 @@ impl Shared { /// The record error code of a confinement failure (decision 7): a path the /// call cannot resolve is the caller's input, everything else the executor. -fn confinement_code(error: &ConfinedError) -> &'static str { +fn platform_error_code(error: &HostPlatformError) -> &'static str { + match error { + HostPlatformError::Invalid(_) | HostPlatformError::InvalidPath { .. } => "invalid_input", + _ => "executor_error", + } +} + +#[cfg(test)] +fn confinement_code(error: &dim_agent_capabilities::host_platform::ConfinedError) -> &'static str { match error { - ConfinedError::InvalidPath { .. } => "invalid_input", + dim_agent_capabilities::host_platform::ConfinedError::InvalidPath { .. } => "invalid_input", _ => "executor_error", } } diff --git a/crates/dimcode/tests/ocr_helper_flow.rs b/crates/dimcode/tests/ocr_helper_flow.rs index 1effae4f16..736123d3c3 100644 --- a/crates/dimcode/tests/ocr_helper_flow.rs +++ b/crates/dimcode/tests/ocr_helper_flow.rs @@ -54,7 +54,7 @@ async fn run( ]; args.extend(extra_args.iter().copied().map(OsString::from)); platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: PathBuf::from(env!("CARGO_BIN_EXE_dimcode")), args, diff --git a/docs/INDEX.md b/docs/INDEX.md index 3cf28f3b78..4b51d47fb5 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -14,7 +14,8 @@ This index is navigation. Delivery status lives in issues, not here. - [模型请求重试与任务续接方案](design/research/model-retry-recovery.md)(中文,#1210):请求重试的可见性、独立恢复能力的边界及所有者合同需求 - [服务面:跨语言形状的策略、盘点与第一批改造](design/service-faces.md)(中文,Draft) - [插件远程化:可行性与落地路径](design/research/remote-plugins.md)(中文,研究稿):rutis 链路能跨什么、HostPlatform/exec/基础工具/存储各自能不能远程化、推荐拓扑与分阶段 -- [Resource and store data faces](design/resource-faces.md) (Draft): `execHost`, `fsHost` and `store` as the only public contracts for processes, files and Session state (#1295, #1296, #1297, #1298) +- [HostPlatform 任务所有者重构](design/research/1295-host-platform-task-owner.md)(English research draft):#1295 的单一 task record、状态机、输出/错误契约、事件流删除与迁移步骤 +- [Resource and store services](design/resource-faces.md) (Draft): `hostPlatform`, `fsHost` and `store` service methods as the public contracts for processes, files and Session state (#1295, #1296, #1297, #1298); no separate face object - [Watch:任务观察与 side branch](design/research/side-eval.md)(中文,设计提案):Watch 与 Pursuit 的用户边界、分支切点、订阅与 prompt 的组合、管理与关注、采样开销 - [Overall design for undesigned features](design/overview.md)([中文](zh/design/overview.md)) - [Plugin designs index](design/plugins/README.md)([中文](zh/design/plugins/README.md)) diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 4ffb192260..d1a35c6930 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -12,9 +12,45 @@ and tree-supervision primitives to local tools. | `P:ToolchainSourceHost` | The downloaded runtimes installed under the plan in effect, each with the bin directory appended to a started child's `PATH` and the archive directory granted to a confined one. Required; an assembly that installs no runtimes provides `ToolchainSourceHost::fixed(vec![])`. | | `P:FileStorage` | Read the configured exec shell; enabled only when `exec_shell_file` is configured. | + +## Data face + +`hostPlatform` is a process-scope data face. Its public methods are `info`, `execShell`, +`persistentShell`, `sandboxBackend`, `execRoot`, the command task operations `spawn`, `wait`, +`kill`, `settle`, `output`, `retainOutput` and `tail`, the persistent shell operations `shell`, +`write` and `resize`, and `spawnWithStdin`, `spawnConfined`, `removeOutputDirectory` and +`childPath`. `spawn_tree`, `spawn_with_stdin_process`, `spawn_pty`, `build_process_spec` and +`child_path_process` remain `#[service(skip)]`: they carry process handles and cannot cross. + +A task id is reserved by the owner before a command or background job starts. `spawn` and the job +part of `shell.write` answer `task_exists` for an id already in the table or an existing output +log, and `invalid` for a missing output parent or an output path outside the shell directory. `wait` reports the terminal record and never removes it; a +timeout stops the wait and answers `running`. `settle` releases only an ended task or an exited +shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a stop is pending answers `task_running`. Command and job logs stay under the output directory the caller gives the owner; the +persistent shell defaults to `execRoot`. Logs are registered by the branch when the model is +given their path. +`removeOutputDirectory` accepts only a persistent-shell output directory below the canonical +`execRoot` and refuses traversal and symlink components. + +`output` serves a text page. Public reads are terminal records plus `output`, `tail`, `wait` and +`retainOutput`; there is no public event cursor or shell state. The owner line queue is private to +`ShellSession`. A shell command capture is read by its command id and records the bounded output, +tail and task log. `wait`, `kill`, `output` and `tail` address shell command and job ids as well +as exec tasks. A shell command ends from its marker; shell exit sweeps its command and job +children. A terminal shell answers `write`/`resize` with `task_ended`, and `settle` is +idempotent. A shell `outputPath` is registered before the reply and survives settle until +`removeOutputDirectory` or Session deletion; `retainOutput` is idempotent. `ShellJobStart.outputPath` +is an absolute path inside the shell output directory and its file stem equals the task id; `childPath` takes UTF-8 data, while the +native `child_path_process` accepts an `OsStr` base without replacement. The command/task and shell settlement rules are in +[resource faces §3.2](../../../design/resource-faces.md#32-settlement-and-retained-task-records). + ## Events and lifetime -No Timeline events or plugin background tasks. `apply` captures the process +No Timeline events. Every task kind — exec command, shell command, shell job and persistent +shell — is one record in the owner's table: the record holds the state and the single terminal +watch, and its per-kind payload holds the process, PTY, capture or pid. The owner keeps command +supervisors, pipe pumps, the shell reader and the +shell worker until kill, settle or owner shutdown; `apply` captures the process environment, reads the initial shell snapshot, retains the configured FileStorage source and requires the execution-settings port. `exec_shell()` rereads that source on every invocation. @@ -120,9 +156,10 @@ switches: declarations are read once, while each process start reads them. For a persistent shell, background PIDs enter through the existing PTY marker. `PtyProcessTree::job_pid` uses portable-pty's foreground-group handle and -Linux's namespace/session metadata to resolve the native host identity once. ShellSession stores -the typed PID or the I/O failure and uses it directly on stop or shell exit. A bounded native -stop waits for release before the cancelled terminal fact; the public signal helper is unchanged. +Linux's namespace/session metadata to resolve the native host identity once. `ShellJob.pid` +stores the typed PID in the owner record; `ShellSession` keeps only the task id and calls +`host.kill` by id. A bounded native stop waits for release before the cancelled terminal fact; +the public signal helper is unchanged. A running shell keeps the boundary it started with; changing the switches applies to the next process. macOS permits only the needed terminal ioctl commands. diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index e762f59831..cfb5a3e8d7 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -102,7 +102,9 @@ Its absence retains the original workspace boundary and does not gate loading. No direct Dispatcher subscription. Tool results return to ToolExecutor; background exec transfers ownership to BackgroundExec, which commits ends and -wakes. Per-call lookups obtain FileReads/BackgroundExec on the caller's branch. +wakes. BackgroundExec keeps the branch task id, the owner task id and the +registered path; it holds no live process or capture. Its live reads, stop and +settle call the HostPlatform task operations. Per-call lookups obtain FileReads/BackgroundExec on the caller's branch. Generation cancellation rejects new calls and stops accepted calls; cleanup waits for tracked calls, including handoff. File mutations stage complete bytes and retain coordinator admission through I/O/publication. Foreground commands @@ -135,8 +137,10 @@ the foreground or after the background handoff, appends HostPlatform's failure note to the result text when the shown output matches; stops, timeouts and offload failures get none. Codes and structured content are unchanged. -`exec_stop {taskId}` stops a detached command owned by the calling branch through -BackgroundExec. It waits for cleanup and returns the committed terminal +`exec_stop {taskId}` stops a detached command owned by the calling branch. The +App Server resolves the branch's `dyn ExecStop` when the profile provides it (ShellSession in the +minimal profile) and otherwise uses BackgroundExec; both map `unknown`/`closed`/`read` to the same +RPC errors. It waits for cleanup and returns the committed terminal `{task_id, status, result}` in the model-readable content. An already-ended task keeps its result. Only `cancelled` confirms cancellation; `failed` remains an error, including when the process tree could not be released. An unknown task fails @@ -686,6 +690,7 @@ releases no lock across a read: the page opens the registered file itself. | `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. | +| `P:HostPlatform` | Read retained task output and stop a running task. | | `S:GuideEntries` | Register the exec notification's entry for this branch, until this part unloads. | | `S:SessionLifecycle` | `hold()`: each running task holds the Session, so an idle unload waits for it. | diff --git a/docs/design/background-task-output.md b/docs/design/background-task-output.md index a4af157573..ac4c214b54 100644 --- a/docs/design/background-task-output.md +++ b/docs/design/background-task-output.md @@ -14,7 +14,7 @@ The `/tasks` panel on `rust-tui` lists background commands and stops one through `session.exec.stop`. It cannot display a command's output while the command runs. The UI is not on `main`; its current implementation is tracked in #264. -The output already exists. Before transferring a command, `ExecProcess` creates +The output already exists. Before transferring a command, the owner's command capture creates its output file; the pipe pumps keep updating that file and its bounded preview. `exec/started` carries the task identity and output path, and `exec/ended` carries the final result. The command's owner is diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index ce4052095c..feb58ef254 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -7,12 +7,12 @@ directly. The rutis binding dispatches its data arguments and returns its result | Dependency | Caller and contract | | --- | --- | -| `hostPlatform` | Exec and Shell use the task and PTY operations in [execHost §3](../resource-faces.md#3-exechost). Hooks calls configured(request); OCR calls confined(request). Both return the result of that call. Process handles remain with the platform. | +| `hostPlatform` | The process service exposes its own data methods: `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, and the task operations `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`/`spawnWithStdin`/`spawnConfined`/`removeOutputDirectory`/`childPath`. `spawn` returns a task id; the process and output file stay with the owner. `spawn_tree`, `spawn_with_stdin_process`, `spawn_pty`, `build_process_spec` and `child_path_process` stay `#[service(skip)]`. Process handles remain with the service that owns them. | | `fileStorage`, `mentionIndex` | File tools and workspace completion use [fsHost §4](../resource-faces.md#4-fshost), including mentions. Storage clients use the owner's file and lease operations. An opened reader uses openRead/readAt/closeRead. | | `sessionStore` | Session repository, metadata, attachments, Timeline and worktree associations use store, store.readMetadata/setTitle, sessionFiles, timelineStore and store.associateWorktree respectively. Session construction binds the existing Session-scoped timelineStore. Path import and fileId reads use the [Session files contract](../appserver/session-files.md). | | `pluginFiles` | Scheduler uses pluginFiles.open(). EventHub retains a caller-managed scope through settlement of admitted publishes across row restarts. Both use scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | | `settingsService` | Declared sources use settings.register/read/update/projects. PluginManager uses the owner-write form for CAS edits and applies its existing writeOnly redaction. SettingsMethods retains the local client-write path. [Settings contract](../appserver/settings-service.md#42-service-settings-owner-path). | -| Permission, PromptSources, Skills catalog/management and execution/shell Settings → resource owners | Use the node facts and file operations in the [resource caller matrix](../resource-faces.md#6-provider-binding-and-the-owners-that-use-each-operation), including execHost.info and fsHost resolution and reads. | +| Permission, PromptSources, Skills catalog/management and execution/shell Settings → resource owners | Use the node facts and file operations in the [resource caller matrix](../resource-faces.md#6-provider-binding-and-the-owners-that-use-each-operation), including `hostPlatform.info` and fsHost resolution and reads. | ## Additional public bindings diff --git a/docs/design/host-platform-isolation.md b/docs/design/host-platform-isolation.md index f71a8267a2..4839822ef0 100644 --- a/docs/design/host-platform-isolation.md +++ b/docs/design/host-platform-isolation.md @@ -255,7 +255,7 @@ preparation; the model's cwd and command cannot select or expand the grant. A si output directory and the rest of the home receive no implicit access, apart from git's configuration on macOS. -Existing output paths keep their owners. WorkspaceTools' `ExecProcess` pumps child output into its +Existing output paths keep their owners. The owner's command capture pumps child output into its host-owned output sink; an occupying ShellSession command appends its captured PTY text from `OccupyingTask::commit`; explicit POSIX background jobs open their log inside `posix_background` and the host reads it for previews. That log is written inside the grant above, so a sandboxed shell can diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md new file mode 100644 index 0000000000..aab98b04f0 --- /dev/null +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -0,0 +1,362 @@ +# #1295 clean redesign: one task owner, one record, one splitter +Status: design and implementation record for #1295 from `984f6b59d1`; the earlier +`af6752a2e9` patch stack is only the local `backup/pr-2002-af675` reference. The contract +lands in `docs/design/resource-faces.md` §3; other pages link to it. +## 0. Decision +1. `HostPlatform` owns all four task kinds: exec command, persistent-shell command, shell + job, persistent shell. One `TaskRecord` with an immutable `TaskKind` payload makes + per-kind state unrepresentable elsewhere. `ShellSession` owns policy; the tool owners + hold task ids. +2. One terminal watch, one splitter, one `OutputPage`, one `HostPlatformError`, one typed + `TaskFailure`. Every added field has a consumer and a test. +3. The public shell event stream is deleted, approved by the user/PR owner (§3.2); + terminal records plus `output`/`tail`/`wait`/`retainOutput` replace it. +4. Service methods take `&self`; no `mounted` weak, no `arc()`, no test-only path. +5. Paths are UTF-8 `String`; errors are typed enums whose tags are the codes. +6. Seven migration steps; no step waits for a product approval. `session.exec.stop` is + routed in this PR through the branch stop owner, without adding a `ShellSession` + dependency to `BackgroundExec`. +## 1. Ownership and state +`HostPlatform` owns every process/PTY/task and its terminal, timeout, isolation marker and +log. `ShellSession` owns queue/timeout/occupancy/markers/facts; `WorkspaceTools`/ +`BackgroundExec` own the branch id, result and registered path. The branch writes the +facts; the owner writes none. `ShellInput` is unchanged. +### 1.2 One record, per-kind payload +```text +reserve(id, log) process started / wrapper written / PTY spawned + ▼ ▼ + Reserved ────────── start failure: remove ──► Running ──────────► Terminal(term) + └─ kill / timeout / exit / sweep +``` + +```rust +struct TaskRecord { id: String, started: Instant, + state: Mutex, // Reserved | Running | Terminal(Arc) + changed: watch::Sender>>, kind: TaskKind } +enum TaskKind { Command(CommandTask), ShellCommand(ShellCommand), Job(JobTask), Shell(ShellTask) } +struct Terminal { status: TaskStatus, exit_code: Option, signal: Option, + duration_ms: u64, failure: Option, output: OutputRecord, note: Option } +``` + +`CommandTask`: tree, capture, isolation, timeout. `ShellCommand`: `Arc`, markers, +capture. `JobTask`: `Arc`, markers, paths, pid, stop. `ShellTask`: PTY, reader, +display, log, `Weak` active/children. Only `ShellTask` has an active slot, only +`Command`/`ShellCommand` have inline text, only `Job` has a pid; shell holds `Weak`, child +holds `Arc`, so no cycle. The owner's active slot is authoritative for `kill`: `ShellSession.occupying` +is a client-side projection and never changes which record `kill` may interrupt; when they +disagree, the owner wins and the session drops the stale occupancy. `finish(terminal)` returns if already terminal, stores the `Arc` +in `state` and `changed` (wakes all), then clears active/sweeps; only `LogRecord.retained` +and the terminal mode remain. The `Terminal` (including its `OutputRecord`) is +immutable; `retainOutput` never mutates it (see §2.2). +### 1.3 Settlement +`settle(taskId)` is the only release. Terminal → remove; Reserved/Running → +`task_running`; absent or already settled → `Ok`. `kill` never releases. `kill` +on a `Reserved` record answers `task_running` and does not cancel the start; `kill` on a +terminal record is a no-op. + +| Action | Exec command | Shell command | Job | Shell | +| --- | --- | --- | --- | --- | +| `kill` running | cancel + terminate; await release; `cancelled` or `failed{terminate_failed}` | ETX only if active; terminal from marker or sweep | signal pid; pending stop until release; `cancelled` on release, `failed{shell_exited}`/`failed{shell_reset}`/`failed{owner_unloaded}` on sweep; missing pid answers `task_running` and keeps a pid watcher | terminate PTY; `cancelled` or `failed{terminate_failed}`; sweep | +| `kill` terminal / settle | no-op / after result | no-op / after result | no-op / after fact | no-op / removes the shell record | +| shell exit | n/a | `failed{shell_exited}` with partial output | `failed{shell_exited}` with file read | `exited`/`signaled`/`cancelled` | +| timeout / unload | `spawn.timeout` → `timed_out`; `wait` never kills; unload `cancelled{owner_unloaded}` | deadline is `kill`; unload same | no timeout; unload same after sweep | no timeout; unload same | + +A shell's terminal marks every child terminal; `settle(shellId)` removes only the shell +record. A job whose release is unconfirmed stays Running until release or the shell's sweep. `settle` keeps registered logs; the shell log exposed by the `shell` +reply is registered and kept until `removeOutputDirectory` or Session deletion; only the +internal init log is removed on release. +### 1.4 Interrupt, pid, pwsh, Windows +`kill(commandId)` checks the shell active slot and non-terminal under its lock, then writes +ETX; Reserved answers `task_running`, and a terminal, superseded or repeated interrupt is a +no-op. A shell command's terminal comes from its end marker; a shell exit sweeps it; a 2 s +expiry kills the shell. A job pid arrives through a `watch>`; `kill` +subscribes before reading the pid and waits for it. The pid is accepted only when its job id +is registered and the record belongs to the same shell. A pid after terminal is ignored; a +kill before it keeps a pid watcher and answers `task_running` after 2 s; a late pid is +killed and released before the terminal. pwsh completion +writes its marker to the owner-derived `.result`, watched for 200 ms. Windows uses the existing PTY/job +code; a stopped job is `cancelled`. +### 1.5 Wake and binding +`wait` subscribes to `changed` before reading state, so a terminal in the window is seen. +The task methods are `&self`; no `spawn_in`, no `Arc` receiver, no `Weak`. The +table, worker tracker and shutdown token are `Arc`/cloneable fields created by +`HostPlatform::current`; a test that builds it spawns the same way. +## 2. Data contract +### 2.1 Operations +| Method | Request | Reply | +| --- | --- | --- | +| `info` / `execShell` / `persistentShell` / `sandboxBackend` / `execRoot` | `{}` | facts; `execRoot` is `String`; non-UTF-8 is `invalid` | +| `spawn` / `shell` / `write` | `SpawnRequest` / `ShellRequest` / `ShellWrite` | `SpawnReply` / `SpawnReply` / `{}` | +| `resize` / `kill` / `settle` / `retainOutput` / `wait` | existing / `TaskRequest` / `WaitRequest` | `{}` / `OutputPathReply` / `WaitReply` | +| `output` / `tail` | `OutputRequest {taskId, cursor?, limit?}` / `TaskRequest` | `OutputPage` / `OutputTail` | +| `spawnWithStdin` / `spawnConfined` / `removeOutputDirectory` / `childPath` | existing / UTF-8 base | existing; `childPath` `None` = nothing to append | + +`ShellWrite` is `{taskId, data, command?: {taskId, startMarker, endMarker}, job?: +{taskId, endMarker, outputPath}}`; the optional start declares the task the +written bytes begin. A job's `outputPath` must be absolute, inside the shell output directory, +with an existing parent, and its file stem must equal `taskId`. The event API is deleted (§3.2). +### 2.2 Task snapshot +| Field | Exec command | Shell command | Job | Shell | +| --- | --- | --- | --- | --- | +| `text` | complete output when the snapshot is inline; absent when the log is the source | absent | absent | absent | +| `outputPath` | data-face snapshot path; a model result exposes it only when the file exists | file | wrapper file | shell log; exposed path is registered | +| `outputBytes` / `outputTruncated` | produced; log cap, false with no file | produced; log cap | file length; false (uncapped) | produced; log cap | +| `preview`/`previewTruncated` | `bounded_preview` tail | same | bounded tail read | same | +| `failure` | `TaskFailure` | `TaskFailure` | `TaskFailure` | `TaskFailure` | +| `status` | running/exited/signaled/timed_out/cancelled/failed | running/exited/failed | running/exited/failed/cancelled | running/exited/signaled/cancelled/failed | +| `exitCode`/`signal` | when exited/signaled | numeric token; no signal | numeric token; no signal | when exited/signaled | +| `durationMs` / `failureNote` | `now - started` while running, `terminal_at - started` when terminal; isolation hint | same; absent | same; absent | same; absent | + +* `text` present means the current snapshot is inline and `output` serves it; absent means + the log is the source. A terminal snapshot is immutable. A model-facing result includes + `outputPath` only when the file exists and is registered; the data-face `wait` may report + the planned path for introspection, but that path is not handed to the model. `retainOutput` on a Running inline task creates the log and switches the + capture to file mode; on a Terminal inline task it only creates a side copy, so the + snapshot and `output` stay inline and the returned path is for a caller that wants it. + +| Snapshot | `wait` | `output` | `retainOutput` | +| --- | --- | --- | --- | +| Running, inline | running + `text` | text | create log, switch to file; later snapshots are file-backed | +| Terminal, inline | terminal + `text` | text | side copy; snapshot and reads unchanged | +| File-backed | terminal/ running + path + preview | file | existing path | +* `OutputWriteFailed{message}` is the log error and forces `status: failed`, keeping + `exitCode` if the process exited; a job read error is `JobUnavailable{message}`. A + running snapshot has no failure/exit/signal/note. `tail`/`output` read a job file with a + bounded seek/read; nothing loads it whole. A shell token is data: `0` → + `exited{0}`, another numeric → `failed{code}` with `CommandFailed`, `failed` → + `CommandFailed`, other/empty → `UnknownExit`. +### 2.3 Output page +`OutputPage = {text, bytes, totalBytes, nextCursor?, truncated, retainedFrom, reset}`. + +| Case | `bytes` | `totalBytes` | `nextCursor` | `retainedFrom`/`reset` | +| --- | --- | --- | --- | --- | +| inline at EOF / cursor past end | length or 0 | text length | absent | 0/false | +| file/shell full page | ≥ `limit`, ≤ `limit+3` | total | `cursor + bytes` | 0/false (file); absolute (shell) | +| file/shell short page | bytes read | total | absent | 0/false (file); absolute (shell) | +| cursor inside a UTF-8 char | 0 or the whole first char | total | absent | unchanged | +| shell cursor below `retainedFrom` | 0 | total | absent | `retainedFrom`, `reset: true` | + +`bytes` is consumed; `nextCursor` is present iff the source read reached `limit` and +`bytes > 0`; a page never splits a character; `truncated` is the source log cap. +### 2.4 Errors and failure kinds +`HostPlatformError`: `invalid`, `invalid_path`, `timed_out`, `output_limit`, `task_unknown`, `task_exists`, +`task_running`, `task_ended`, `output_unavailable`, `cancelled`, `closed`, `io`, +`isolation_config_invalid`, `isolation_unavailable`, `exec_shell_config_invalid`, +`exec_shell_unavailable`, `exec_shell_cwd_unsupported`, `cwd_not_found`, +`exec_shell_path_mapping_failed`, `failed`. One typed enum, one variant per code; the wire +tag is the code, so `xtask types` generates it. `ProcessSpecError{code,reason}` maps by an +exhaustive match; a new code fails to compile until classified. `spawnWithStdin`/ +`spawnConfined` keep `InvalidPath` as `invalid_path`; `ConfinedError::TimedOut` and +`OutputLimit { stream }` keep `timed_out` and `output_limit` with the stream field; exec maps `Invalid`/the exec-shell +errors to its own codes. + +`TaskFailure` is a typed enum, used identically by `Terminal.failure` and +`WaitReply.failure`: + +```rust +#[derive(Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum TaskFailure { + OutputWriteFailed { message: String }, // {"code":"output_write_failed","message":"..."} + TerminateFailed { message: String }, // {"code":"terminate_failed","message":"..."} + JobUnavailable { message: String }, // {"code":"job_unavailable","message":"..."} + ShellExited, ShellReset, CommandFailed, UnknownExit, OwnerUnloaded, +} +``` + +`xtask types` exposes it as `TaskFailure`, a discriminated union on `code`; +`WaitReply.failure?: TaskFailure | null`. Only the three OS/read errors carry a message; a +`cancelled` record may carry `TerminateFailed`/`OwnerUnloaded`. +## 3. Shell output +### 3.1 Splitter and classification +The PTY reader is the only reader. It applies `regularize_output` once, appends the chunk +to the display capture, and feeds one splitter: + +```rust +struct LineSplitter { pending: String, finished: bool } +fn push(&mut self, chunk: &str) -> Vec; // complete lines; a >64 KiB partial line is + // flushed as one chunk so memory is bounded +fn finish(&mut self) -> Option; // the remaining tail, once +``` + +`finish` is called exactly once at PTY EOF; its line is classified too, so a marker without +a newline lands. Classification: active command start → begin capture; active command end +→ token, terminal; registered job pid/completion → resolve once; otherwise command output +and display output. Markers are validated at `write`: `__DIM_START_<8 hex>_<8 hex>__` / +`__DIM_END_<8 hex>_<8 hex>__`, non-empty, one per line, token 1–12 ASCII alphanumerics. A +marker inside other text is not one; the wrapper splits its literal so the echo does not +match. A caller that prints its own marker ends its own capture; it is not a secret. +`output(shellId)` reads the last 64 KiB of regularized text; `retainedFrom` is the absolute +start of that 64 KiB window, not the start of the 1 MiB display capture. A cursor below the +window is reset to `retainedFrom`; `tail` previews it; no other reader touches the PTY. The worker orders the shell terminal: after the process exits it waits for the reader +(bounded by `EXIT_STDIO_GRACE`), the reader calls `finish`, then the shell terminal sweeps +children. The final unterminated line is in the command capture, its log and the display +capture exactly once. +### 3.2 Approved compatibility: event API removal +The user/PR owner approved for this PR: delete `output(eventCursor)`, the `OutputPage` +event fields, `ShellEvent`, `ShellState`, `OutputRequest.waitMs/eventCursor` and +`ackEventCursor`. No in-repo consumer exists; generated TypeScript drops the fields; the +alpha plugin API break is accepted for #1295. Replacement: terminal records plus `wait`, +`output`, `tail`, `retainOutput`; the owner reader is the only lossless consumer. There is no +public fallback queue and no ack cursor. The owner keeps a crate-private line queue only for +`ShellSession`; it is an implementation detail, not a public contract. +## 4. Flows +### 4.1 ShellSession: state and exact owner calls +Stored: `shell: Option`, `generation`, `dialect`, `shell_exe`, `queue`, +`queue_running`, `occupying: Option<{task_id, output_path, delivered}>`, +`background: HashMap`, `shell_exit`, `had_reset`. +A `write`/`resize` `task_ended` means the shell is terminal → step 7. + +1. **Init.** `shell(...)` → id/path; store, bump generation; spawn the shell watcher + `wait(shellId, None, lifecycle)` → step 7. `write(shellId, data, start=Command{initId})`; + one `wait(initId, INIT_TIMEOUT)`; terminal → `settle(initId)`, remove its internal log; + failure → `kill(shellId)`, `wait`, `settle`, clear shell, fail the first call. +2. **First foreground.** `write(shellId, data, start=Command{commandId})` → id/path; + register the path. One `wait(commandId, timeout_ms, cancel)` — the same one-wait policy + as exec's 30 s foreground wait, no poll loop. Terminal → 4; `cancelled` → 5; `running` + → 3; `task_unknown` → 7. +3. **Occupancy.** Append `exec/started`; on failure `kill`, `wait`, `settle`, clear + occupying, return the fact failure — no phantom fact. Set occupying; watcher + `wait(commandId, None)`; terminal → 4, append `exec/ended`, settle, clear, notify. + Return "still running" with the preview `output(commandId, 0, 16 KiB)`. The next call's + `occupied_wait` waits on the notify or its deadline; if still occupied it reads + `output(occ.taskId, delivered, 16 KiB)` and does not execute the new command. +4. **Result.** `output(commandId, 0, 16 KiB)`; exit line from `WaitReply`; omitted = + `outputBytes - bytes` when `bytes < outputBytes`; `is_error` = status not `exited{0}`; + settle after the text is materialized. +5. **Interrupt.** `kill(commandId)` (ETX only if active); `wait(commandId, Some(2 s))`; + terminal → 4 with the interrupted note; still running → kill the shell, wait for child + watchers, settle; the sweep writes `failed{shell_reset}`. +6. **Background.** `write(shellId, data, start=Job{...})`; register; append `exec/started` + (on failure kill/settle, no fact); watcher `wait(jobId, None)`; terminal → result, + append `exec/ended`, settle, remove. A stop kills and waits; `task_running` keeps the + watcher and returns a stop-requested result; a kill error keeps the watcher too; the + owner terminal fact follows. +7. **Shell exit.** The watcher gets the terminal; ignore an older generation. Set + `shell=None`, `had_reset=true`, `shell_exit=note(status)`; the sweep has terminaled the + children and their watchers write facts. Wait for child watchers (separate tracker), + then `settle(shellId)`; the next call respawns and prepends the note. +8. **Reads.** `session.exec.output` → `tail(hostTaskId)`; `outputPage` → `output(hostTaskId, + cursor, limit)`; a gone record reads the registered file; the shell display read is + `output(shellId, ...)`/`tail(shellId)`. A `wait` timeout is `running`, no kill; settle + only terminal; a repeated settle is `Ok`. +### 4.2 Exec: start, wait, handoff, stop +```text +exec: read execShell() for the edition; keep & and heavy-search refusals +spawn → {taskId, outputPath}; wait(taskId, 30s, cancel) + terminal → result → settle; cancelled → kill/wait → result; + running → retainOutput → BackgroundExec.start(hostTaskId, taskId, path) → watcher + (watcher: stop → kill/wait/exec-ended; terminal → result/exec-ended/settle) +``` + +One result builder: `text` → inline content + note; file → `Output saved to:`, bytes, +truncation line, note, `preview`; `failure` → its code/message (`OutputWriteFailed` keeps +partial output); `status` → `completed` only for `exited{0}` without failure. Preserved: +inline below 30,000 UTF-16 units is complete (including `seq 1 5000`); above it the full +file; offload failure keeps partial output; `StartRequest` carries `task_id` (branch, +hook-rewritable) and `host_task_id`. Facts: `WorkspaceTools`/`BackgroundExec` and +`ShellSession` append `exec/started` after the owner accepted the start (on failure the task +is killed/settled, no phantom start) and `exec/ended` after the terminal and before settle; +the owner writes none; recovery reads them as today and never restarts a process. +## 5. Boundaries +### 5.1 Paths, logs, registration +Data-face paths are UTF-8 `String`, absolute unless stated; no `to_string_lossy` on a +request or reply. A non-UTF-8 owner path makes `info`/`execRoot` answer `invalid`; a +non-UTF-8 shell path is `exec_shell_unavailable`. In-process producers use `to_str()` and +fail their own call; SessionStore removes a non-UTF-8 candidate with FileStorage. Log is +`{outputDir}/{taskId}.log`; files are created 0600 in the output directory the caller provides. Exec log is lazy at the inline threshold or +`retainOutput`; `symlink_metadata` rejects any entry (dangling included) as `task_exists`. +Shell command/shell/job logs are `create_new`; a failed PTY start removes the log; a job +completion file is checked for absence. `retainOutput` is idempotent: exec creates the file +and switches to file mode; shell marks the PTY log retained until `removeOutputDirectory`. +Registration is the branch's: `ToolDriver` registers an `outputPath` only when the model +result carries it and the file exists; it never registers a planned exec path. `ShellSession` +registers the shell `outputPath` before the `shell` reply leaves and the `write` reply path +after start. Command logs are registered; the init log is internal and is not. +### 5.2 Markers, pid, state +Shape/validation/scope: §3.1; `write` rejects a malformed/empty marker with `invalid`. The +pid line is `__DIM_END_...__ `, scoped to its shell and a registered id; a job +without a pid cannot be signaled immediately: 2 s, `task_running`, then a late pid is +killed and released before the terminal. `ShellState`/`ready` is deleted: readiness is the init terminal. +### 5.3 MCP child PATH: final rule +```rust +// native, in-process, not served +fn child_path_process(&self, directories: &[String], base: &OsStr) -> Option +// None = nothing to append; Some = composed. An OsStr base is ordinary data. +``` +| Case | Native | Served `childPath` | MCP caller | +| --- | --- | --- | --- | +| no platform / no addition | n/a / `None` | n/a / `None` | `None`; leave PATH | +| composition | `Some(OsString)` | `Some(String)` | set PATH | +| non-UTF-8 daemon base | accepted as `OsStr` | not expressible | native binding; no error | + +A non-UTF-8 daemon PATH is not an error: on Unix it is legal data and receives the runtime +directories; on Windows `OsString` is UTF-16. The served face cannot receive one, so no +silent loss remains; this is the same owner operation, not a second implementation. +### 5.4 `removeOutputDirectory` and docs +The request path is UTF-8. Reject `.`/`..` and any symlink component between canonical +`execRoot` and the target (`invalid_path`); canonicalize the target when it exists, or its +parent when absent, and require a strict descendant of the canonical root (equal is +`invalid_path`); remove; absent is `Ok`; other I/O is `io`. A path outside `execRoot` is +`invalid_path` (SessionStore falls back to FileStorage). + +`resource-faces.md` §3 owns the contract; `HostPlatform.md` owns the shape and links; +`WorkspaceTools.md` owns exec/BackgroundExec and links; `service-faces.md` §3.4 lists +operations and attributes the PTY to `ShellSession`; npm declarations regenerate. +## 6. Verification +| Case | Evidence | +| --- | --- | +| shell command page, UTF-8 cut, retained log, second command, kill | `host_platform_flow::a_shell_command_capture_is_owned_by_the_host` | +| shell terminal, `TaskEnded`, idempotent settle | `host_platform_flow::the_host_platform_service_serves_a_shell` | +| public shell text burst without an event cursor | `host_platform_flow::a_shell_burst_completes_without_a_private_subscriber` | +| shell exit sweeps commands/jobs; stop after a pid | `minimal_execution::shell_exit_settles_tasks`, `shell_exit_kills_background_jobs`, `stop_background_task` | +| inline exec behavior | `local_execution::foreground_output_is_canonical_and_offloaded_like_ts` | +| page accounting and restored tasks | `transport_flow/shell_input::background_exec_output_pages_running_finished_and_restored_tasks` | +| Windows confined outcomes | `host_platform_windows_flow` | +| docs/types | `xtask check`, `types`, `graph` | + +Existing flows stay (`host_platform_flow`, `local_execution`, `minimal_execution`, +`transport_flow/shell_input`). Full commands and counts are in the PR body, so this table +does not claim a test that is not in the tree. +## 7. Migration +### 7.1 Buildable steps + +| # | Parent | Commit | Files | Compile boundary | Gate | +| --- | --- | --- | --- | --- | --- | +| 1 | `984f6b59d1` | `refactor(host-platform): one task record and per-kind payload` | `host_platform.rs` (+ private `task`), new `output.rs`, `exec.rs` (capture/command move), `shell_session.rs` (payloads, no policy), `shell_input.rs` imports, `HostPlatform.md` | `TaskRecord`/`TaskKind` for all four; `ExecProcess`, `ExecutionTask`, event fields and public shapes still exist; `ShellSession` still reads `output(eventCursor)`. If the four payload moves do not compile together, split 1a/1b; do not claim one commit. | `host_platform_flow`, `local_execution` foreground/background, `minimal_execution` shell, clippy | +| 2 | step 1 | `refactor(host-platform): one snapshot, typed errors and failures` | `host_platform.rs`, `exec.rs`, `shell_session.rs`, `background.rs`, `hooks/runner.rs`, `modality/engine.rs`, npm, docs | §2.2–2.4; `ExecProcess` still exists and reads the snapshot; event fields still exist; all matches updated; `TaskFailure` replaces `outputFailure`; `retainOutput` switches a Running capture to file mode and only side-copies a Terminal one (never mutates a terminal snapshot) | `host_platform_flow`, `local_execution`, `minimal_execution`, `hooks_flow`, `ocr_helper_flow`, `mcp_session_flow`, `process_typescript` | +| 3 | step 2 | `refactor(exec): run commands as owner task ids` | `exec.rs`, `background.rs`, `workspace_tools/mod.rs`, `local_execution.rs`, `WorkspaceTools.md` | `ExecProcess`, `CommandTask` and `ExecutionTask` deleted; one `TaskRecord` table; `BackgroundExec` holds ids, live reads via `tail`/`output` | `local_execution` handoff/stop/recovery, `transport_flow/shell_input` | +| 4 | step 3 | `refactor(host-platform): splitter, shell settlement, event API removal` | `host_platform.rs`, `shell_session.rs`, `minimal_execution.rs`, `npm/*`, `HostPlatform.md`, `resource-faces.md` | Owner splitter; markers/pwsh/sweep; `write`/`resize` on a dead shell answer `task_ended`; `ShellSession` has no marker scan/retained/event loop; event API deleted | `minimal_execution` shell, `host_platform_flow` burst/display + dead-shell write, `xtask types` | +| 5 | step 4 | `fix(host-platform): one boundary policy` | `host_platform.rs`, `exec.rs`, `shell_session.rs`, `stdio.rs`, `storage/files.rs`, `hooks/runner.rs`, `modality/engine.rs`, flow tests | UTF-8 paths; log reservation/cleanup/retention; strict removal; typed MCP PATH | `host_platform_flow`, `host_platform_windows_flow`, `mcp_session_flow`, `ocr_helper_flow` | +| 6 | step 5 | `fix(app-server): route session.exec.stop through the branch stop owner` | `connection.rs`, `transport_flow/shell_input.rs`, `minimal_execution.rs` | Minimal's `ShellSession` already provides `dyn ExecStop`; `session.exec.stop` uses it when present, otherwise the local profile keeps `BackgroundExec`. `BackgroundExec` gains no `ShellSession` dependency; a future profile with both task kinds must provide one stop dispatcher in its assembly. | live shell command/job stop through `session.exec.stop`; normal exec stop unchanged; `product_protocol` | +| 7 | step 6 | `docs(host-platform): one owner contract` | `resource-faces.md`, `HostPlatform.md`, `WorkspaceTools.md`, `service-faces.md`, `resource-owner-operations.md`, `ShellInput.md`, `npm/plugin.d.ts`, generated | One rule per page; identical operation lists; PTY attribution; registration split | `xtask check`, `graph`, `types`; `node --test scripts/*.test.mjs` | + +### 7.2 Patch mapping +| Change | Keep | Rewrite | +| --- | --- | --- | +| Job reads, acks, exec ids | jobs readable by id; retention explicit; exec uses `spawn`/`wait`/`kill`/`settle` | job records in the one table; `wait`/`output`/`tail`/`retainOutput`; terminal record replaces `ExecProcess`; `hostTaskId`; no rebuilt `ExitStatus` | +| Stream | no marker may be lost; display never backpressures | owner is the only line consumer; queue/cursor/ack deleted; one text capture is the display read | + +### 7.3 Scope and follow-up +`task_ended` is in this PR: step 2 adds it, step 4 makes `write`/`resize` return it, and +`write_to_a_terminated_shell_answers_task_ended` gates it; no `connection.rs` change for +that case. `session.exec.stop` is step 6: the minimal `ShellSession` `ExecStop` provider +serves shell tasks; the local profile keeps `BackgroundExec`. `BackgroundExec` gains no +`ShellSession` dependency; `ShellSession`'s existing recovery dependency on `BackgroundExec` +stays. +## 8. Rule check +| Rule | Application | +| --- | --- | +| §1 dependence / ownership; ADR 002 D1 | HostPlatform owns processes/PTYs/tasks; ShellSession policy; WorkspaceTools semantics; BackgroundExec facts. No new capability. | +| Timeline facts; rules 1–4, 9 | No fact added/moved; producers unchanged; owner writes none. | +| One owner/record/watch/splitter/page/error enum | Four records → one with per-kind payload, three notifiers → one watch, two page types → one, folded messages → one `HostPlatformError` and one `TaskFailure`. | +| Data face, no live handle, no duplicate owner | Public methods are serde data; native handles stay native; exec/BackgroundExec hold ids and paths; the owner is the only marker interpreter and terminal writer. `session.exec.stop` selects the branch stop provider; `BackgroundExec` gains no `ShellSession` dependency. | +| Rule 3 / rule 7 / test rule / ADR 002 D4 | Reader is a blocking thread, supervisors/waiters are tasks, terminal transition never awaits under a lock; reuses `pump`/`Decoder`/`bounded_preview`, `sessionFiles`, `Timeline`, `SessionLifecycle`; boundary tests are face flows; switches read per prepare, shell preference per spawn. | + +Exceptions: `kill` on a shell command requests an interrupt and the marker or sweep decides +the terminal (the stop producer still writes `cancelled`); `wait` timeout is a read; +`child_path_process` takes `OsStr` in-process. + +Ablation: the added fields are values consumers were reconstructing (inline text, failure +kind, duration, exit/signal, started path), the page's `totalBytes`/`retainedFrom`/`reset`, +and `task_ended`; each has a consumer and a test. diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index e5dd257f13..d85a031886 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -1,6 +1,6 @@ -# Resource and store data faces +# Resource and store services -Status: Draft. Issues: [#1295](https://github.com/arcships/dim/issues/1295) (`execHost`), +Status: Draft. Issues: [#1295](https://github.com/arcships/dim/issues/1295) (`hostPlatform` service methods), [#1296](https://github.com/arcships/dim/issues/1296) (leaf identity and lifecycle), [#1297](https://github.com/arcships/dim/issues/1297) (`fsHost`), [#1298](https://github.com/arcships/dim/issues/1298) (`store`); parent @@ -9,13 +9,17 @@ Background: [remote plugins §3–§4](research/remote-plugins.md). This is a design, not an implementation record. Every operation below is a target shape. +A "data face" below means a service's public operation set: the service itself, served by name, +not a separate object. Business code writes no `HostDispatch`; `#[rutis::service]` generates it, +and a service is served in the scope where it is provided. + ## 1. Scope -Resource and state operations use these public data faces: +Resource and state operations use these public services: | Face | Operations | Provided by | Issue | | --- | --- | --- | --- | -| `execHost` | `start`, `wait`, `kill`, `settle`, `output`, `tail`, `removeOutputDirectory`, `shell`, `write`, `resize`, `info`, `confined`, `configured` | the process owner | #1295 | +| `hostPlatform` | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail`, `shell`, `write`, `resize`, `spawnWithStdin`, `spawnConfined`, `removeOutputDirectory`, `childPath` | the process owner | #1295 | | `fsHost` | tool family: `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions`; storage family: `stat`, `readBytes`, `openRead`, `readAt`, `closeRead`, `lock`, `unlock`, `backup`, `createDirectory`, `replace`, `list`, `remove` | the file-operations owner | #1297 | | `store` | Session-row repository operations (§5.2) | the process state owner | #1298 | | `timelineStore` | Timeline operations and completion notifications (§5.1) | the Session state owner | #1298 | @@ -24,7 +28,7 @@ Resource and state operations use these public data faces: ```text control node resource leaf (mounted per #1296) WorkspaceTools ── fsHost ─── data ──────► file operations on node files - exec, ShellSession ── execHost ─ data ──────► processes, PTY, output files + exec, ShellSession ── existing services ───► processes, PTY, output files settings, auth, Hooks ── fsHost ─── data ──────► the same face, answered locally Permission and Approval never asked, never decides Session repository ── store ───────────────► the state owner, locally @@ -32,9 +36,9 @@ Resource and state operations use these public data faces: Worktree associations ── store ──────────────► the same state owner, locally ``` -**A face is a shape; the mount is a deployment.** `execHost` and `fsHost` are provided by the -daemon that holds the process, the file or the session's own configuration — the control node's -own plugins, or a resource leaf mounted per +**A service is the shape; the mount is a deployment.** `hostPlatform` and `fsHost` are provided by +the daemon that holds the process, the file or the session's own configuration — the control +node's own plugins, or a resource leaf mounted per [#1296](https://github.com/arcships/dim/issues/1296). `store` and `timelineStore` are provided where the Session state is, always in the daemon that owns that Session ([#1298](https://github.com/arcships/dim/issues/1298)); it is the same face whether the rows live in @@ -43,7 +47,8 @@ classification on the name. The public contract and migration rules are in [service faces](service-faces.md) §2. For these resource faces, §6 maps `hostPlatform`, `fileStorage`, `sqliteStorage` and `timelineStore` -to their public operations and Rust bindings. +to their public operations and Rust bindings. A service's public methods are its contract; there +is no separate face object and no `execHost` name. What stays on the control side, in every case: Session and branch scope, admission (`Approval`, and `Permission` with the [ADR 014](../adr/014-file-access-facts.md) table), the @@ -51,11 +56,11 @@ What stays on the control side, in every case: Session and branch scope, admissi the worktree Session view, and the recorded tool result. No face asks the user anything, decides whether a call may run, or consults who is calling. -## 2. Rules for these faces +## 2. Rules for these services -1. **One face per service.** The operations are the public contract; a Rust typed client is a - binding over the same operations and owns no second business logic. There is no owner trait - beside the face. +1. **One service, one contract.** The operations are the service's public methods; a Rust typed + client is a binding over the same methods and owns no second business logic. There is no owner + trait beside the service. 2. **One call per operation.** `read`, `write`, `edit`, `glob`, `grep` and `mentions` are one call each; a traversal is one call, not one call per file. 3. **Paths are node paths.** A request carries a node-absolute resolved path; a reply returns @@ -63,8 +68,8 @@ whether a call may run, or consults who is calling. exception: **`fsHost.resolve` is the resolution entry point**, so it accepts the path as the model gave it — relative to the `cwd` the caller passes, starting with `~`, containing `..`, following symlinks — because only the node can resolve it. `cwd`, `workspace` and the - confirmed roots it is given are node-absolute. Every other operation, `execHost.start` and - `shell` included, takes a path a `resolve` reply or the caller's own record already returned. + confirmed roots it is given are node-absolute. Every other operation, the task and shell + operations included, takes a path a `resolve` reply or the caller's own record already returned. Returned paths are stable for history: the same file always resolves to the same path. 4. **Ids are values.** A task, read or lease id is a string the provider issues or the caller assigns; ids carry no authority. @@ -74,270 +79,102 @@ whether a call may run, or consults who is calling. (`content`, `structuredContent`, `isError`, `effects`) and keeps the codes it uses today. A call that could not be served is `{code, message}`; the control side returns that code and message as the tool result unchanged, so the two vocabularies stay one. -7. **Cancellation is a call.** The caller drops the call or sends the bridge's cancel. Cancelling - a read of an outcome changes nothing; cancelling a process is `kill`. +7. **Cancellation is a call.** The caller drops the call or sends the bridge's cancel; a service + method that needs it takes the existing `cancelled: CancelledFn` parameter (`toolHost.execute` + is the shape), not a separate `cancel` operation. Cancelling a read of an outcome changes + nothing; cancelling a process is `kill`. 8. **No per-service authorization.** Authorization is `Approval` and `Permission` over agent - actions, and connection trust is #1296's. A face carries no credential, preset or grant. + actions, and connection trust is #1296's. A service carries no credential, preset or grant. 9. **Names are camelCase.** Request, reply and error members are camelCase, as the rest of the migration's wire types are. -## 3. `execHost` - -### 3.1 Methods +## 3. Process and task services -| Method | Mode | Request | Reply | -| --- | --- | --- | --- | -| `start` | async | `{taskId, command, cwd, workspace, roots}` | `{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}` | -| `write` | async | `{taskId, data}` | `{}` | -| `resize` | async | `{taskId, cols, rows}` | `{}` | -| `info` | async | `{}` | host facts (§3.7) | -| `confined` | async | `{program, args, read, write, env?, timeoutMs, outputLimit, services}` | `{status, stdout, stderr, confined, stdoutTruncated, stderrTruncated}` | -| `configured` | async | `{command, cwd, env?, stdin?, timeoutMs, limits}` | `{status, exitCode?, signal?, durationMs, stdout, stderr, stdoutTruncated, stderrTruncated}` | - -### 3.2 `start` and `wait` - -`start` accepts only `{taskId, command, cwd, workspace, roots}`. `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. -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 -writable root of its own, apart from the output and temporary directories its contract already -grants. `roots` holds the additional roots recognition confirmed; the workspace is always part of -the writable range and cannot be narrowed or replaced by leaving it out. The provider has no way -to confirm a root: a directory outside the range does not become writable because a command names -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. -`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. - -`start` has no switch input. A request that still carries `sandbox`, `network` or any other -boundary switch is `invalid`: the switch is not the caller's to send -([ADR 003 D1](../adr/003-approval-scope.md), [process isolation](host-platform-isolation.md)). -`roots` is not a switch: it is the workspace range the Session already confirmed, and it grants -nothing the file facts do not already grant. - -`wait` returns the terminal record once the process tree has ended: +There is no separate `execHost` face. A public service is its own contract: `#[rutis::service]` +serves its public `&self` methods in the scope where it is provided, and `xtask types` generates +the TypeScript declarations. A leaf mounts a part copy in the host's instance, so a process, +Session or branch service crosses a leaf without a second face +([research/remote-plugins §4.2](research/remote-plugins.md#42-叶子插件级远程化的单位)). -```text -{status: "exited" | "signaled" | "timed_out" | "cancelled" | "failed", - exitCode?: number, signal?: string, durationMs: number, - outputPath: string, outputBytes: number, outputTruncated: bool, - preview: string, previewTruncated: bool, - failureNote?: string} -``` +The process operations are split by their owners: -- `preview` is the bounded sanitized tail the exec rules already define (the last 2,000 lines - within 50 KiB); `outputPath` is the append-only file on the node; `outputTruncated` is the - 64 MiB cap. -- `failureNote` is the isolation owner's note, present only when a sandboxed command failed and - its shown output matches a typical denial. Producing it is the provider's; appending it to the - result text is the control side's. -- `timeoutMs` bounds the call's wait, not the process's obligation: reaching it kills the tree and - answers `status: "timed_out"`. The control side computes the effective timeout from its own - policy and passes it; a `wait` cancelled by the caller ends only the call, and the caller sends - `kill` if it wants the process gone. -- `wait` is repeatable and stays readable until the task is settled (§3.8). Without `timeoutMs` the - call waits for the end; the control side passes one whenever its policy has one. - -### 3.3 `kill` - -`kill {taskId}` terminates the task's process tree with the existing tree-kill and answers `{}`. -An ended but unsettled task is a no-op that still answers `{}`; an id the provider does not hold is -`task_unknown` and kills nothing. `exec_stop` stays a control-side tool: it calls `kill`, then -`wait`, then `settle`, and words its own `{task_id, status, result}`. `kill` answering -`task_unknown` means the task was already settled, so `exec_stop` answers from the branch's own -task record — `exec_task_unknown` only when the branch has no record either. - -### 3.4 `output` - -`output` reads captured output by byte cursor. A request supplies exactly one of `taskId` and -`outputPath`. Both forms answer -`{text, bytes, nextCursor?, truncated, retainedFrom, reset?}`. `limit` rejects `0` (`invalid`), -defaults to 1 MiB and clamps to 4 MiB. `text` is sanitized exactly like the preview; `bytes` is -the captured bytes this page consumed; `nextCursor` is present when the page was full and equals -`cursor + bytes`; `bytes == 0` means caught up, so the caller retries the same cursor. A page -never splits a character. For a command, the capture is the append-only output file: the file -never changes behind a cursor, `retainedFrom` is `0`, and `truncated` is the 64 MiB cap. These are -the rules of [background command output](background-task-output.md); this face adds no second page -rule, only the fields below, which a bounded capture needs. - -- `{taskId, cursor?, limit?}` selects a task held by the provider. This serves the PTY capture - and command output while the task record is held. -- `{outputPath, cursor?, limit?}` pages a command's file independently of the task record. - For `session.exec.output.page`, the control side resolves the task in the requested Session - and branch and takes the path from that branch's `exec/started`. This route serves ended and - rebuilt tasks, including after settlement or provider restart. The provider opens only files - within its command-output root and checks containment when opening. The control side uses - the terminal fact's `outputTruncated` when present. On the path-only read, the provider uses - the file-size-at-cap rule for recovered tasks. The public RPC continues to take a task id. - -**The retained start is data, not an error.** `retainedFrom` is the earliest cursor the provider -can still serve. A bounded capture grows at its end and drops at its start, so `retainedFrom` only -ever increases. - -- An omitted `cursor` means `retainedFrom`, not byte zero. Asking for `{taskId}` is the reset - request: it answers from the oldest byte the provider still holds. -- A `cursor` below `retainedFrom` is not a failure: the reply is - `{text: "", bytes: 0, retainedFrom, reset: true}` and carries **no** `nextCursor`. The - continuation is `retainedFrom`: `reset` overrides the `bytes == 0` rule above, which otherwise - means "retry the same cursor". A client that checks `reset` first never loops. -- The bytes between an old cursor and `retainedFrom` are gone on purpose; the reply never - reconstructs them. A command's append-only output file has no such gap; only a bounded shell - capture drops text. -- The capture may advance again between two calls. `retainedFrom` in each reply is the truth for - that reply; a caller whose next cursor is below the new `retainedFrom` takes the reset page and - continues from there. It must not cache `retainedFrom`, and a cursor the provider handed out is - never revised in place, only overtaken by the start. -- A lost reply is retried at the same cursor. Pages are reads of an append-only file or of an - absolute capture offset, so a repeated read returns the same bytes or the reset page; nothing is - consumed by reading, and no read changes the task. - -### 3.5 `tail` - -`tail {taskId}` answers the live tail a task shows while it runs: -`{text, totalBytes, truncated}`. `text` is the last 2,000 lines within 50 KiB of the capture, -sanitized like the preview; `totalBytes` is how many bytes the capture holds so far, so a client -can tell growth from a stall; `truncated` is the same flag the terminal record carries. It is a -read of the live capture, not a page: the control side's `session.exec.output` uses it, and a -client that needs the whole output pages `output` from `retainedFrom`. Once the live capture is -released, a held task answers `output_unavailable`. The control side maps that and `task_unknown` -to the existing `exec_task_unknown` response for this RPC. The terminal preview comes from -`exec/ended` under the [background output contract](background-task-output.md#2-client-method). - -### 3.6 Persistent shell - -`shell {taskId, cwd, workspace, roots, 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 -operation: one page operation with one cursor rule serves both a command's output file and the -shell's capture, and a second name for the same operation would be a duplicate. The shell's -capture is bounded (64 KiB today), so its `retainedFrom` advances as it drops the oldest text and -the reset page of §3.4 is how a caller catches up. - -The command protocol that runs on top of the shell — marker pairs, occupancy, the queue and the -foreground timeout — is not part of this face. It stays with the shell's consumer, which uses -`write`/`resize`/`output` and pages, never streams (§9). A marker that never arrives is not proof -that a command still runs: on a lost link the provider ends the task (§3.8), so the consumer -settles the command as ended with the task's loss, never as still running. - -### 3.7 `info`, `confined` and `configured` - -`info {}` answers the provider's host facts as data, because other owners read them today: +| Service | Scope | Public operations | Owner document | +| --- | --- | --- | --- | +| `hostPlatform` | process | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail`, `shell`, `write`, `resize`, `spawnWithStdin`, `spawnConfined`, `removeOutputDirectory`, `childPath` | [HostPlatform](../architecture/rust-agent/plugins/HostPlatform.md) | +| `toolHost` | session | `execute` | [tool contributions §2.1](../architecture/rust-agent/tool-contributions.md#21-宿主工具的-toolhost-数据面) | +| `backgroundExec` | branch | `output`, `outputPage`, `wait`, `stop` | [WorkspaceTools data face](../architecture/rust-agent/plugins/WorkspaceTools.md#data-face) | +| `sessionMethods.shell` / `ShellSession` | session, branch | the shell operations | [ShellInput](../architecture/rust-agent/plugins/ShellInput.md) | + +`hostPlatform`'s handle methods (`spawn_tree`, `spawn_with_stdin_process`, `spawn_pty`, +`build_process_spec`, `child_path_process`) stay `#[service(skip)]`; they carry process handles and +cannot cross. The service serves the command task operations on `hostPlatform`: `spawn` returns a task id and +the process/output state stays with the owner; `wait`, `kill`, `settle`, `output`, `retainOutput` +and `tail` work by that id. `WorkspaceTools` and `backgroundExec` use the task id; the branch keeps +the task record and the facts. `shell`/`write`/`resize` are served by the same owner; the owner +records the command capture and `ShellSession` keeps only queue, timeout and occupancy policy. `spawnWithStdin` and `spawnConfined` are the existing methods +Hooks and OCR call, now with data requests and replies. `removeOutputDirectory` and `childPath` +are the existing cleanup and PATH helpers, now data methods; SessionStore and MCP call them. The +served `childPath` composes from UTF-8 data; a non-UTF-8 daemon PATH is accepted by the native +`child_path_process` as `OsStr` and is not expressible through the face, so no replacement +characters are written. The +in-process cores stay as the shared implementation, not a second public operation. + +The command process, output file, PTY and command capture are owned by `HostPlatform`; the branch +keeps the task record and writes the facts. `shell` writes its bounded capture to `outputPath`, so the path is +real for both task and file reads. `ShellSession` creates the command id and marker pair, sends them +with `write`, and keeps only the queue, timeout and occupancy policy; foreground output, the exit +code and the task log are read back by command id through `output`, `wait` and `settle`. The owner +keeps its line queue private: public reads are terminal records plus `output`, `tail`, `wait` and +`retainOutput`; no public event cursor or shell state exists. Background shell jobs are registered in the owner under +the branch task id; the control side never sees a host pid. `wait` takes the existing cancellation callback; a timeout stops the wait and answers `running`, +and neither a timeout nor a cancelled call kills the task. A command's own `spawn.timeoutMs` still +terminates it at that deadline; stopping a task is an explicit `kill`. `spawnConfined` success means the helper stayed within its limits; an output limit is an +error, so its reply carries no truncation flags. Cancellation is the existing +`cancelled: CancelledFn` parameter (`toolHost.execute` is the shape); it is not a separate +`cancel` operation and carries no `callId`. + +### 3.1 `hostPlatform.info` + +`info()` answers the process facts consumers read today: ```text -{os: "darwin" | "linux" | "win32", - home: string, timezone?: string, execRoot: string, platformRoots: [string], +{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, - source: string, outputEncoding: "utf8" | "unknown"} + source: string, outputEncoding: string} | {state: "unavailable", code: string, reason: string}} ``` -`backend` is the decision preparation would use; `execShell` is the current resolved shell -preference, which the environment prompt source reads on every load. The exec-shell preference is -otherwise a Settings document whose public contract is `host.exec_shell.get`/`update`; `start` -reads it, and this face does not write it. - -`confined` starts a host-owned helper under its own boundary — a program a plugin runs for its own -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. - -`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** -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 -not an agent-reachable operation: no tool maps to it. - -### 3.8 Ownership, disconnect, settlement and cancellation - -- The provider owns the process, the PTY, the temporary directory and the output file. The branch - owns the task record and the facts: `exec/started` after `start` returns the id and output path, - `exec/ended` when the terminal record is in, and the wake notice. A background handoff moves the - control-side task record only; the process never moves. -- **A start that cannot be recorded kills its process.** If appending `exec/started` fails, or the - call is cancelled after `start` returned, the control side calls `kill` and waits for the tree to - end before returning the tool error: no process outlives an unrecorded start. A start whose - reply never arrived is not retried — the branch has no record of it, and the id stays held until - the connection ends, so a retry cannot run the command twice. -- **Settlement.** The provider holds a task record from `start` until `settle`. `start` and - `shell` refuse every id still held, live or terminal (`task_exists`). After recording the - terminal fact, the control side can call `settle` to release the task record and its runtime - resources. Calls by task id then answer `task_unknown` until the id is reused. A new task - creates a fresh output file. Settlement, including on disconnect, preserves output files. - The control side can still page the registered command output by path (§3.4). -- **Output directory removal.** SessionStore applies the last-owner rule and orders durable - directory removal before the row commit under the - [Session deletion contract](appserver/session-deletion-and-fork.md#32-sequence). It calls - `execHost.removeOutputDirectory {path}` for persistent-shell output. The provider validates - that the directory is strictly below its `execRoot`, removes it and makes removal durable - before replying, as required by [ADR 013 D4](../adr/013-command-output-ownership.md#d4-fork-delete-and-growth). - An absent directory counts as removed. SessionStore uses `fsHost.remove` for command-output - directories in the FileStorage root. -- When the link drops, the node's own host ends the processes it started - ([overview §6.3](overview.md#63-multiple-nodes)), and settlement is the connection's end. A - reconnect provides the services again and reloads nothing: the Session keeps running. -- A control-side task that was waiting on a dropped link settles once, as failed with - `node_unavailable`, and is never restarted; the command may have run. -- Cancelling an `exec` call kills the task before the call returns; a cancelled `wait` only ends - the call. A provider that closes, or that unloads the face, kills its tasks before it stops - serving; a node whose App Server dies leaves only the backend's parent-death handling. -- #1296 fixes the leaf's lifecycle and states the disconnect rule for owned processes. This - document depends on that rule; it does not define reconnect or mount semantics. - -### 3.9 Settings and the boundary - -The provider reads its own `sandbox` and `network` switches through its `ExecutionSettings` part -at every `start` and `shell`, uses its own exec-shell preference and captured `PATH`, and prepares -the process with its own platform roots and temporary directory. A running task keeps the boundary -it started with. A missing or unreadable switch source is `isolation_config_invalid`; sandbox on -without a backend is `isolation_unavailable`; both refuse the payload before it runs, exactly as -[process isolation](host-platform-isolation.md#failure) states, and nothing falls back to a weaker -boundary. `configured` and `confined` read no switch: the first runs outside the boundary by -design, the second under its own. - -The consumer sends no switch, reads none, and cannot widen a boundary through `cwd`, `workspace`, -`roots` or `command`: `roots` is the range the Session confirmed through the file facts, and the -provider adds nothing to it. Its tool declaration line stays what it is; it describes the -switches, not their value. On a remote node the switches are the node user's; a local management -client reads and writes them through the node's own management methods, not through this face. - -### 3.10 Errors - -| Code | When | -| --- | --- | -| `node_unavailable` | The provider is not connected. Only this call fails | -| `invalid` | Malformed request or an output path outside the operation's root | -| `task_exists` | `start` or `shell` with an id the provider still holds | -| `task_unknown` | An id the provider does not hold: never issued, or settled | -| `cwd_not_found` | The resolved `cwd` does not exist | -| `exec_shell_unavailable` | The shell preference cannot be resolved (with its own reason) | -| `isolation_unavailable` | The sandbox is on and the host has no backend | -| `isolation_config_invalid` | The switches cannot be read | -| `spawn_failed` | The process could not start | -| `output_unavailable` | The selected output file is missing or unreadable, or `tail` has no live capture for a held task | -| `remove_failed` | Removing a persistent-shell output directory or making the removal durable failed | -| `cancelled` | The call was cancelled before it changed anything | +`execShell` is the existing `ShellStatus` shape; `backend` is `SandboxBackend`; `execRoot` is +the platform's execution root. `execShell`, `sandboxBackend` and `execRoot` remain available as +individual methods for a caller that needs one fact; `info` is the one call for a caller that +needs several. + +### 3.2 Settlement and retained task records + +A task id is reserved by the owner before the command or job starts. `spawn` and the `job` part of +`shell.write` reject an id already in the live table with `task_exists`; a completed command keeps +its output log, so reusing its id is refused until the log is removed. `spawn` also refuses an +unusable output directory before the process starts. + +`wait` reports the terminal record but never removes it; a timeout answers `running` and only +stops waiting. The caller decides when the record is no longer needed and calls `settle`. `settle` +accepts only a terminal task or a shell that exited; a running command, shell or background job +answers `task_running`; settling an already released id is `Ok`. `kill` is the explicit stop; a second kill while a stop is pending answers `task_running`; when +it ends a background job the owner marks that job ended so it can be settled. `wait`, `kill`, +`output` and `tail` address shell command and job ids as well as exec commands, and `output` for a +job performs a bounded seek/read of its log. A terminal shell answers `write`/`resize` with +`task_ended`. A caller that never settles keeps the record and its log until the owner unloads. + +Command and job output logs live below the output directory the caller gives the owner; the +persistent shell defaults to `execRoot`. The branch registers the logs it gives the model (foreground, +occupying, background and shell); Session deletion removes the registered candidates. A shell log +is registered before the `shell` reply exposes it and is kept until `removeOutputDirectory` or +Session deletion; settling the shell does not delete it. The init log is internal and is removed +when its command is released. `retainOutput` is idempotent. `removeOutputDirectory` accepts only a +UTF-8 path that is a persistent-shell output directory strictly below the canonical `execRoot`; +`.`/`..` and every symlink component are refused, an absent target is `Ok`. ## 4. `fsHost` @@ -586,7 +423,7 @@ grant, and tool approval still follows the preset `sessionFiles.put` uses `createDirectory` and `replace` with `permissions: "privateReadOnly"` to store the file on the resource node. It returns a node path and owns the rows under the [Session-file contract](appserver/session-files.md#31-on-disk). Command output stays on the node -and is read through `execHost.output` and `execHost.tail` (§3.4–§3.5). +and is read through the branch's `backgroundExec.output` / `backgroundExec.outputPage`. ### 4.7 Errors @@ -843,37 +680,37 @@ original path argument and ownership exclusion. | Old name | Face | What the name is now | | --- | --- | --- | -| `hostPlatform` | `execHost` | The provider and its Rust binding: `ProcessTree`, `PtyProcessTree`, temporary directories and shell preparation are its internals, reached through the operations | +| `hostPlatform` | `hostPlatform` | The process service and its Rust binding; its public data methods serve `info`, the command task operations, the persistent shell, the configured/confined helpers, removal and child path (the list is in §3). `ProcessTree`, `PtyProcessTree`, temporary directories, shell preparation and the `_process` cores are internals (`#[service(skip)]`) | | `fileStorage` | `fsHost` | The provider and its binding: roots, leases, generations and one validated path component per open are its internals | | `sqliteStorage` | `sqliteStorage.storageReport({})` | SQLite file, WAL and reclaimable bytes ([native storage](appserver/native-storage-format.md)). Session repository operations belong to `store`. | | `timelineStore` | `timelineStore` | Session-scoped Timeline operations; the `TimelineStore` trait is its native binding | For the owners below, Rust callers use a thin binding over the operations — a direct in-process call rather than JSON — and none of them publishes a second API: there is no owner -trait beside the face, no object type another module constructs, and no method set that the face -does not have. A consumer that needs something the face does not offer needs a new operation on -the face, not a new accessor beside it. +trait beside the service, no object type another module constructs, and no method set that the +service does not have. A consumer that needs something the service does not offer needs a new +operation on the service, not a new accessor beside it. The owners that read node files or start node processes, and the operations they use: | Owner | Operations | | --- | --- | | WorkspaceTools file tools | `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions` | -| SessionStore Session files and command output | `createDirectory`, `replace`, `list`, `remove`, `execHost.removeOutputDirectory` | +| SessionStore Session files and command output | `createDirectory`, `replace`, `list`, `remove`; shell output removal stays the Rust `remove_output_directory` call | | Settings sources and their CAS writes | `readBytes`, `stat`, `lock`, `readBytes {leaseId}`, `replace {leaseId}`, `unlock` | | MCP auth store, managed OAuth and OAuth token stores | `readBytes`, `lock`, `readBytes {leaseId}`, `backup`, `replace {leaseId}`, `unlock` | | Hooks project file (`.dimcode/hooks.json`) | `stat`, `readBytes` | -| PromptSources (environment, project and user rule files) | `execHost.info` (`os`, `home`, `timezone`, `execShell`), `stat`, `readBytes` | +| PromptSources (environment, project and user rule files) | `hostPlatform.info` (`os`, `home`, `timezone`, `execShell`), `stat`, `readBytes` | | UI extension resources | `stat`, `openRead`, `readAt`, `closeRead` | | Migration ledger and snapshots | `createDirectory`, `list`, `remove` | -| Hooks configuration commands | `execHost.configured` | +| Hooks configuration commands | Hooks' own process start (Rust); `hostPlatform.configured` only if a foreign caller needs it | | Worktree association | `store.associateWorktree` | ## 7. Rule check | Rule | Application | | --- | --- | -| §1, ADR 002 D1 | Each face belongs to the part that owns the resource or the state; consumers stay in their own scope. No new Capability on the control side | +| §1, ADR 002 D1 | Each service belongs to the part that owns the resource or the state; consumers stay in their own scope. No new Capability on the control side | | §4 rule 1 | Command events are not added. A background command's fact is still `exec/started`/`exec/ended` on its branch, written by its owner | | §4 rule 2 | A handoff keeps its fact on the branch and its process with the provider; nothing is handed to a second owner | | §4 rule 3 | No before callback and no commit-time I/O. `timelineStore.append` is the one operation allowed inside the caller's commit lock because it queues without I/O and does not wait; completion arrives through `commits`, after the commit and outside every lock. Every other face operation is outside the lock | @@ -884,11 +721,11 @@ The owners that read node files or start node processes, and the operations they | §4 rule 8 | The faces add no Timeline, Dispatcher or event-format change. One runtime requirement is unmet: [#861](https://github.com/arcships/dim/issues/861), per-call resolution of a Session's process-scope service by its resource node. It is the dim runtime's, solved with rutis's current capability; no requirement is raised to rutis ([overview §6.3](overview.md#63-multiple-nodes), [principles §4 rule 8](../architecture/rust-agent/principles.md)) | | §4 rule 9 | No new Timeline fact: `exec/started` and `exec/ended` already exist, and the faces write none | | ADR 002 D2 | No wiring plugin: each face is its provider's own service | -| ADR 002 D3 | Dependencies follow scope: `execHost` and `fsHost` are process names a leaf can provide; `store` is provided where the Session state is | +| ADR 002 D3 | Dependencies follow scope: `hostPlatform` and `fsHost` are process names a leaf can provide; the task and shell services stay in their Session/branch scope | | ADR 002 D4 | Business configuration is read at use time: the switches at each `start`, the shell preference at each spawn and each environment prompt, the engine at open | | ADR 002 D5 | §3–§5 are the language-neutral contract; the Rust bindings implement them | | ADR 003 D1, D2, D5 | No boundary switch in a call; a preset, approval or replay confers none; `configured` runs because of configuration, outside the agent boundary, as hooks already do | -| ADR 009 | Permission decides; `execHost`'s provider enforces | +| ADR 009 | Permission decides; `hostPlatform`'s provider enforces | | ADR 010, ADR 011 | The switches stay the host user's settings, read and enforced by the provider | | ADR 012, ADR 013 | Grants and Session-file ownership stay control-side records; paths are the node's | | ADR 014 | The four facts keep their sources: resolution, workspace, system and the worktree probe are the node's, the row facts the control node's. `resolve` never publishes an expansion; the Session part publishes only after the store acknowledged the association and the candidate passed the recheck (§4.2.2) | @@ -918,8 +755,8 @@ No other requirement is raised: ## 9. Open decisions -1. **Naming and instance per leaf.** Process-scope names are global, so `execHost` and `fsHost` - need one instance per leaf: `execHost.` or a host-side route. +1. **Naming and instance per leaf.** Process-scope names are global, so `hostPlatform` and + `fsHost` need one instance per leaf: `hostPlatform.` or a host-side route. [#1296](https://github.com/arcships/dim/issues/1296) decides; this document assumes only that a Session's calls reach one provider. 2. **Disconnect policy.** The node ends the processes it started, per overview §6.3. #1296 states @@ -928,10 +765,10 @@ No other requirement is raised: 3. **`owned` on the control side.** The fact is a row lookup, so it is answered by `sessionFiles` with the node's resolved path rather than on the node. If review wants it computed with the other three, the rows would have to move, which is #1298's kind of decision. -4. **Where the persistent-shell protocol runs.** `write`/`resize`/`output` are enough for a - control-side marker and occupancy protocol that pages its output; running the protocol on the - node would make it `start`/`wait` instead. #1295 decides when it wires PTY, after foreground - and background. +4. **Where the persistent-shell protocol runs.** The owner records the command capture and + markers; the control side keeps the queue, timeout and occupancy policy and reads the command + by id. The owner line queue is private to `ShellSession`, not a public contract. #1295 wires the + PTY and the foreground/occupancy path. 5. **Result text ownership.** File operations return their tool result from the provider because the text is the file operation's own (line numbers, previews, image blocks). A command returns records, and the control side composes the tool result, because the task identity, the @@ -941,19 +778,19 @@ No other requirement is raised: to the same state owner (#1298); the naming split changes neither placement nor ordering. 7. **Root identity form.** The Session passes the opaque `rootIdentity` back to the provider. The provider owns its platform form and comparison. -8. **Retained task records.** Settlement is explicit (§3.8). If a long-lived local provider wants a +8. **Retained task records.** Settlement is explicit (§3.2). If a long-lived local provider wants a bound instead, it must give the control side time to record the terminal fact and refuse a - repeated `start` until expiry. Registered file retention follows Session ownership (§3.8). + repeated `start` until expiry. Registered file retention follows Session ownership (§3.2). ## 10. Ablation -The faces are operations over data with ids, not adapters: `start`/`wait`/`kill`/`output`/`tail` -reuse the existing process tree, capture, page rule and fault vocabulary; `shell`/`write`/`resize` -are the PTY primitives the shell already has; `info`, `confined` and `configured` are the reads -and starts the platform already performs, including the configuration command Hooks runs. -`removeOutputDirectory` carries the existing HostPlatform cleanup across the face. Paging by a -registered output path reuses `output` after the provider releases its task record. -`fsHost` adds no primitive file API and no per-file traversal: its storage family is the reads and +The removed `execHost` face added no operation of its own. Each operation lives on the service +that already owns it: `hostPlatform.info` (and its `execShell`/`sandboxBackend`/`execRoot` +methods) reads the platform facts the process owner already has; `toolHost.execute` and +`backgroundExec.output`/`outputPage`/`wait`/`stop` are the existing tool and task operations; +`sessionMethods.shell` keeps the PTY primitives the shell already has. No process or PTY state +moves between services, and no handle crosses. `fsHost` adds no primitive file API and no +per-file traversal: its storage family is the reads and leases the node's storage already offers, needed because a path's facts and its bytes cannot be read on a machine that does not hold the file; `resolve` is where resolution and the worktree probe belong. `store` publishes the repository operations the state owner already has; diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index f2640bfe20..678339f473 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -123,7 +123,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou | 名字 | 现在的对象 | 目标操作 | | --- | --- | --- | -| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 数据面 `execHost`:`start`/`wait`/`kill`/`settle`/`output`/`tail`/`removeOutputDirectory`/`shell`/`write`/`resize`/`info`/`confined`/`configured`([resource and store data faces](resource-faces.md) §3,#1295);`hostPlatform` 是提供方和它的 Rust binding | +| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 服务自身的方法就是公开操作:`info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`、`spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`、`shell`/`write`/`resize`、`spawnWithStdin`/`spawnConfined`/`removeOutputDirectory`/`childPath`;`spawn_tree`/`spawn_with_stdin_process`/`spawn_pty`/`build_process_spec`/`child_path_process` 保持 `#[service(skip)]`。不建 `execHost`([resource and store services](resource-faces.md) §3,#1295) | | `fileStorage` | `FilePath`、根与代次 | 数据面 `fsHost`:工具部分 `resolve`/`read`/`write`/`edit`/`glob`/`grep`/`mentions`,存储部分 `stat`/`readBytes`/`openRead`/`readAt`/`closeRead`/`lock`/`unlock`/`backup`/`createDirectory`/`replace`/`list`/`remove`(§4,#1297);`fileStorage` 是提供方和 binding | | `sqliteStorage` | 连接与事务 | Session 行走 `store`;原生 Agent、Provider 和 Settings 的记录操作直接调用 `sqliteStorage`,连接与事务由 SQLite 插件持有。`sqliteStorage.storageReport({})` 返回 SQLite 文件和 WAL 的容量指标([存储契约](appserver/native-storage-format.md)) | | `timelineStore` | 连接与批次 | Session 作用域的 `timelineStore` 数据面(resource-faces §9 允许与仓储族分名):`createSession`/`sessionConfig`/`releaseSession`/`rollbackSession`/`append`(同步受理)/`commits`、`closeCommits`(按分支序的完成通知)/`head`/`branches`/`readPage`/`readSegments`/`query`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`;`TimelineStore` trait 是 binding(#1298) | @@ -153,14 +153,14 @@ Proposed target operations: [Resource and repository operations](contracts/resou | 名字 | 数据面 | 所有者把什么留在内部 | | --- | --- | --- | | `mcpSession` | `state()`、`refresh()`、`widget(published)`、`call(server, tool, arguments)` | 连接代次、已发布工具、发现与重连 | -| `backgroundExec` | `output(taskId)`、`outputPage(taskId, cursor, limit)`、`wait(taskId, timeoutMs)`、`stop(taskId)` | 任务表、活进程、输出采集与唤醒 | +| `backgroundExec` | `output(taskId)`、`outputPage(taskId, cursor, limit)`、`wait(taskId, timeoutMs)`、`stop(taskId)` | 任务表、task id/路径、事实与唤醒;不持有活进程或采集 | 形状与错误由所有者文档定义:[MCP Apps](appserver/mcp-apps.md#44-the-mcpsession-data-face)(`mcpSession`)和 [WorkspaceTools](../architecture/rust-agent/plugins/WorkspaceTools.md#data-face)(`backgroundExec`)。 -`backgroundExec.start` 需要活的进程对象,仍是 `exec` 工具的操作,不在数据面上;`backgroundExec.stop` 是 kill。 +`backgroundExec.start` 需要活的进程对象,仍是 `exec` 工具的操作,不在数据面上;`BackgroundExec` 只保存 branch task id、host task id 和 output path,实时读取走 `hostPlatform.tail`/`output`。`backgroundExec.stop` 是 kill。持久 PTY 由 `HostPlatform` 拥有,`ShellSession` 持有策略;公共 PTY 操作只有 `shell`/`write`/`resize`。 这些名字在 catalog 里是 `data`,Rust 类型仍由部件在同一实例按类型键读取。 -`hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:数据面就是公开契约,`execHost`、`fsHost`、`store`、`timelineStore` 的操作就是它们的接口,旧名字是提供方和它的 Rust binding,调用方在进程内直接调这组操作,不再有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store data faces](resource-faces.md) §6)。 +`hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:服务本身就是公开契约;一个 service 的公开方法就是它的接口,没有单独的 face 对象,也没有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform` 的公开方法包括 `info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`,以及命令任务和持久 shell 的操作(见 §3.4);`toolHost`、`backgroundExec`、`sessionMethods.shell` 通过该数据面调用它们。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store services](resource-faces.md) §6)。 ### 3.5 热路径与顺序:待操作化 diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 2e128453aa..506d28a64c 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -142,6 +142,375 @@ export interface ToolHost { execute(call: { id: string; name: string; input: { [key: string]: unknown } }, caller: ToolExecutionContext, cancelled: () => void | Promise): Promise } +/** Byte limits for a configured command's two streams. */ +export type OutputLimits = { + stdout: number | bigint + stderr: number | bigint +} + +/** + * The system services a host-owned helper may reach beyond its files. The + * set is closed: every rule a variant adds is recorded in + * `docs/architecture/rust-agent/plugins/HostPlatform.md` with the denial it + * answers. + */ +export type SystemServices = + | /** No system service: the helper reads the system baseline, its own executable and [`Confinement::read`], and writes [`Confinement::write`]; everything else is denied. */ "none" + | /** On-device text recognition: Apple Vision, the Apple Neural Engine and the GPU, and the sandbox extension that hands the framework's cache to the neural-engine compiler service. */ "onDeviceRecognition" + +/** A request to run one confined helper on this node. */ +export type ConfinedRequest = { + program: string + args: string[] + read: string[] + write: string[] + env?: Record + timeoutMs: number | bigint + outputLimit: OutputLimits + services: SystemServices +} + +/** + * A confined helper's bounded result. Success means it stayed within its + * limits; an output limit is an error, not a truncated reply. + */ +export type ConfinedReply = { + status?: number | null + stdout: string + stderr: string + confined: boolean +} + +/** The output stream that reached its limit. */ +export type ConfinedStream = "stdout" | "stderr" + +export type HostPlatformError = + | { invalid: string } + | { invalid_path: { path: string; reason: string } } + | "timed_out" + | { output_limit: { stream: ConfinedStream } } + | "task_unknown" + | "task_exists" + | "task_running" + | "task_ended" + | { output_unavailable: string } + | "cancelled" + | "closed" + | { io: string } + | { isolation_config_invalid: string } + | { isolation_unavailable: string } + | { exec_shell_config_invalid: string } + | { exec_shell_unavailable: string } + | { exec_shell_cwd_unsupported: string } + | { cwd_not_found: string } + | { exec_shell_path_mapping_failed: string } + | { failed: string } + +/** + * A request to compose the PATH a child process gets. `base` is UTF-8; a + * result that cannot be represented answers `None`. + */ +export type ChildPathRequest = { + directories: string[] + base: string +} + +/** A request to remove a persistent-shell output directory. */ +export type RemoveOutputDirectoryRequest = { + path: string +} + +/** + * A request to run one configured command with stdin. `env` is UTF-8; a + * non-UTF-8 environment belongs to the in-process binding. + */ +export type SpawnWithStdinRequest = { + command: string + cwd: string + env: Record + stdin?: string | null + timeoutMs: number | bigint + limits: OutputLimits +} + +export type SpawnWithStdinStatus = "exited" | "signaled" | "cancelled" | "timed_out" + +export type SpawnWithStdinReply = { + status: SpawnWithStdinStatus + exitCode?: number | null + signal?: string | null + durationMs: number | bigint + stdout: string + stderr: string + stdoutTruncated: boolean + stderrTruncated: boolean +} + +export type ShellEdition = "bash" | "zsh" | "sh" | "dash" | "ksh" | "git-bash" | "pwsh" | "windows-powershell" | "cmd" + +export type ShellSource = + | /** The executable path configured in `exec-shell.json`. */ "explicit" + | /** A supported login shell (macOS / Linux). */ "login" + | /** The POSIX fallback chain after an unsupported or missing login shell. */ "fallback" + | /** The Windows automatic order `pwsh -> Windows PowerShell -> cmd`. */ "automatic" + +export type OutputEncoding = "utf8" | "unknown" + +export type ExecShellRuntime = { + executable: string + edition: ShellEdition + source: ShellSource + outputEncoding: OutputEncoding +} + +export type ShellStatus = + | { state: "available" } & ExecShellRuntime + | { state: "unavailable"; code: string; reason: string } + +/** + * 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. + */ +export type SandboxBackend = { state: "available" } | { state: "unavailable"; reason: string } + +export type Os = "darwin" | "linux" | "win32" + +/** The process facts the `hostPlatform.info` operation answers. */ +export type HostInfo = { + os: Os + arch: string + home: string + timezone?: string | null + execRoot: string + platformRoots: string[] + backend: SandboxBackend + execShell: ShellStatus +} + +/** A request to start a command on this execution node. */ +export type SpawnRequest = { + taskId: string + command: string + cwd: string + workspace: string + roots: string[] + outputDir: string + timeoutMs?: number | bigint | null +} + +export type SpawnReply = { + taskId: string + outputPath: string +} + +export type WaitRequest = { + taskId: string + timeoutMs?: number | bigint | null +} + +/** How a wait reply ended, or that it is still running. */ +export type WaitStatus = "running" | "exited" | "signaled" | "timed_out" | "cancelled" | "failed" + +/** Why a task reached a failed or cancelled terminal record. */ +export type TaskFailure = + | { code: "output_write_failed"; message: string } + | { code: "terminate_failed"; message: string } + | { code: "job_unavailable"; message: string } + | { code: "shell_exited" } + | { code: "shell_reset" } + | { code: "command_failed" } + | { code: "unknown_exit" } + | { code: "owner_unloaded" } + +/** A wait reply; terminal when the task ended, `running` when the wait deadline elapsed. */ +export type WaitReply = { + status: WaitStatus + text?: string | null + exitCode?: number | null + signal?: string | null + durationMs: number | bigint + outputPath: string + outputBytes: number | bigint + outputTruncated: boolean + preview: string + previewTruncated: boolean + failure?: TaskFailure | null + failureNote?: string | null +} + +export type TaskRequest = { + taskId: string +} + +/** A request to start a persistent PTY shell on this execution node. */ +export type ShellRequest = { + taskId: string + cwd: string + workspace: string + roots: string[] + outputDir: string + cols: number + rows: number +} + +export type ShellCommandStart = { + taskId: string + startMarker: string + endMarker: string +} + +export type ShellJobStart = { + taskId: string + endMarker: string + /** Absolute path of the job's log; it must be inside the shell output directory. */ + outputPath: string +} + +export type ShellWrite = { + taskId: string + data: string + command?: ShellCommandStart | null + job?: ShellJobStart | null +} + +export type ShellResize = { + taskId: string + cols: number + rows: number +} + +export type OutputRequest = { + taskId: string + cursor?: number | bigint | null + limit?: number | bigint | null +} + +/** A page of a task's captured output. */ +export type OutputPageReply = { + text: string + bytes: number | bigint + totalBytes: number | bigint + nextCursor?: number | bigint | null + truncated: boolean + retainedFrom: number | bigint + reset?: boolean | null +} + +export type OutputPathReply = { + outputPath: string +} + +export type OutputTail = { + text: string + totalBytes: number | bigint + truncated: boolean +} + +/** Process facts and the source of the exec shell preference. */ +export interface HostPlatform { + /** + * [`Self::spawn`] with `stdin` written to the child's standard input, + * which then closes. A child that exits before reading it does not fail + * the start. + * Runs one confined helper and returns its bounded result. + * @throws {HostPlatformErrorThrown} + */ + spawnConfined(request: ConfinedRequest, cancelled: () => void | Promise): Promise + /** + * Composes the PATH a child process gets, as data. The served base is + * UTF-8; a non-UTF-8 daemon PATH uses [`Self::child_path_process`] in + * process and is not expressible through this face. + */ + childPath(request: ChildPathRequest): Promise + /** + * Removes a persistent-shell output directory below `execRoot`. + * @throws {HostPlatformErrorThrown} + */ + removeOutputDirectory(request: RemoveOutputDirectoryRequest): Promise + /** + * Runs one configured command with stdin and returns its bounded result. + * @throws {HostPlatformErrorThrown} + */ + spawnWithStdin(request: SpawnWithStdinRequest, cancelled: () => void | Promise): Promise + /** + * Reads the configured exec shell for this invocation without reloading + * the plugin. Explicitly constructed platforms keep their supplied shell. + */ + execShell(): Promise + /** The sandbox backend a new process would use. */ + sandboxBackend(): Promise + /** + * The directory the persistent shell owns: `/.dim/exec`. + * @throws {HostPlatformErrorThrown} + */ + execRoot(): Promise + /** + * The process facts a consumer needs, in one call. Resolves the exec + * shell; in-process callers that need only captured facts read the fields. + * @throws {HostPlatformErrorThrown} + */ + info(): Promise + /** + * Starts a command on this node and returns the task id and output path. + * Requires the plugin-built owner. + * @throws {HostPlatformErrorThrown} + */ + spawn(request: SpawnRequest): Promise + /** + * Waits for a task's terminal record. `timeoutMs` stops the wait and + * answers `running`; it never kills the task. `cancelled` ends only the + * wait. Use `kill` to stop the task. + * @throws {HostPlatformErrorThrown} + */ + wait(request: WaitRequest, cancelled: () => void | Promise): Promise + /** + * Kills a task's process tree. + * @throws {HostPlatformErrorThrown} + */ + kill(request: TaskRequest): Promise + /** + * Releases an ended task's record. + * @throws {HostPlatformErrorThrown} + */ + settle(request: TaskRequest): Promise + /** + * Starts a persistent PTY shell on this node and returns the task id. + * Requires the plugin-built owner. + * @throws {HostPlatformErrorThrown} + */ + shell(request: ShellRequest): Promise + /** + * Writes bytes to a shell task. + * @throws {HostPlatformErrorThrown} + */ + write(request: ShellWrite): Promise + /** + * Resizes a shell task's PTY. + * @throws {HostPlatformErrorThrown} + */ + resize(request: ShellResize): Promise + /** + * Reads a page of a task's captured output. + * @throws {HostPlatformErrorThrown} + */ + output(request: OutputRequest): Promise + /** + * Writes the captured output to the task's log file and returns its path. + * @throws {HostPlatformErrorThrown} + */ + retainOutput(request: TaskRequest): Promise + /** + * Reads the bounded live tail of a task. + * @throws {HostPlatformErrorThrown} + */ + tail(request: TaskRequest): Promise + /** + * Resolves the persistent shell: bash, zsh, pwsh, or Windows PowerShell. + * Other shells fall back per the platform rules. + */ + persistentShell(): Promise +} + export type ImageSourceType = "base64" | "url" | "file" export type ImageSource = { @@ -737,6 +1106,8 @@ export type OutputPage = { * control characters. */ bytes: number | bigint + /** The total bytes in the source capture or file. */ + totalBytes: number | bigint /** * Present when the read found at least `limit` bytes, so the client may * continue immediately; always `cursor + bytes`. Absent on a shorter or @@ -1380,6 +1751,9 @@ export type ErrorThrown = RustError<"Error", string, undefined> /** What a method returning `Err(HostError)` throws. */ export type HostErrorThrown = RustError<"HostError", "Failed" | "Cancelled", undefined> +/** What a method returning `Err(HostPlatformError)` throws. */ +export type HostPlatformErrorThrown = RustError<"HostPlatformError", "invalid" | "invalid_path" | "timed_out" | "output_limit" | "task_unknown" | "task_exists" | "task_running" | "task_ended" | "output_unavailable" | "cancelled" | "closed" | "io" | "isolation_config_invalid" | "isolation_unavailable" | "exec_shell_config_invalid" | "exec_shell_unavailable" | "exec_shell_cwd_unsupported" | "cwd_not_found" | "exec_shell_path_mapping_failed" | "failed", HostPlatformError> + /** What a method returning `Err(ListenAddressesError)` throws. */ export type ListenAddressesErrorThrown = RustError<"ListenAddressesError", "invalid_path", ListenAddressesError> @@ -1426,6 +1800,7 @@ export interface Services { worktreeAssociations: WorktreeAssociations credentialVariablesHost: CredentialVariablesHost toolHost: ToolHost + hostPlatform: HostPlatform inputQueue: InputQueue reservedMethods: ReservedMethods permission: Permission diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 18fafd15be..6ec5b5c954 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -261,6 +261,12 @@ export type BranchEvent = Omit & { export type { AgentErrorThrown, BranchLifecycle, Dispatcher, PartRegistry, PartScope, ProcessActivity, Services, SessionFault, SessionIdentity, SessionLifecycle, TimelineIdentity, TreeCommands, PermissionState, SessionPermissions, SessionsErrorThrown, + HostPlatform, HostInfo, ShellStatus, SandboxBackend, ExecShellRuntime, Os, ShellEdition, + ShellSource, OutputEncoding, OutputPage, OutputTail, OutputPathReply, + SpawnRequest, SpawnReply, WaitRequest, WaitReply, TaskRequest, OutputRequest, HostPlatformError, + ShellRequest, ShellWrite, ShellCommandStart, ShellJobStart, ShellResize, OutputLimits, + SpawnWithStdinRequest, SpawnWithStdinReply, ConfinedRequest, ConfinedReply, ChildPathRequest, + RemoveOutputDirectoryRequest, WorkflowFiles, WorkflowFileEntry, WorkflowRoot, WorkflowFilesErrorThrown, UiResources, PublishFile, ResourceRef, ResourceErrorThrown, } from './branch-services.js'; diff --git a/tests/integration/tests/local_execution.rs b/tests/integration/tests/local_execution.rs index 9cab6b9109..273c986cb3 100644 --- a/tests/integration/tests/local_execution.rs +++ b/tests/integration/tests/local_execution.rs @@ -612,7 +612,7 @@ async fn exec_and_external_shell_callers_use_live_shell_preferences() { .unwrap(); assert_eq!(spec.executable, PathBuf::from(executable)); assert_eq!(shell.executable_path, spec.executable); - let mut process = platform.spawn(spec).unwrap(); + let mut process = platform.spawn_tree(spec).unwrap(); let mut output = Vec::new(); process.stdout().read_to_end(&mut output).await.unwrap(); assert!(process.wait().await.unwrap().success()); diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index b9972d8348..dda4863af3 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -978,11 +978,14 @@ async fn stop_background_task() { let pid = pid_in(&pid_file).await; let stop = session - .service::("main") - .unwrap(); - let ended = stop.stop(task_id.clone()).await.unwrap(); + .service_opt::("main") + .unwrap() + .expect("the minimal profile provides the branch stop owner"); + let ended = stop.clone().stop(task_id.clone()).await.unwrap(); assert_eq!(ended.status, ExecStatus::Cancelled); assert!(gone(&pid).await); + let repeated = stop.stop(task_id).await.unwrap(); + assert_eq!(repeated.status, ExecStatus::Cancelled); session.close().await.unwrap(); harness.shutdown().await; }