diff --git a/crates/dim-agent-capabilities/src/exec_stop.rs b/crates/dim-agent-capabilities/src/exec_stop.rs deleted file mode 100644 index f060a5a572..0000000000 --- a/crates/dim-agent-capabilities/src/exec_stop.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! The unified background-task stop port. -//! -//! ShellSession provides `dyn ExecStop` for stopping the minimal profile's -//! shell tasks. It depends on BackgroundExec for recovery; -//! live PTY cancellation remains owned by ShellSession. The local profile -//! uses BackgroundExec's own service and face for native-process stops. - -use dim_agent_types::ExecEndedData; -use rutis::host::BoxFuture; -use std::sync::Arc; - -/// Stop-path errors. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TaskError { - Unknown, - Closed, - Read, -} - -/// Stops a background task by id. -pub trait ExecStop: Send + Sync + 'static { - fn stop( - self: Arc, - task_id: String, - ) -> BoxFuture<'static, Result>; -} diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index a2d288f9c0..98da28eff4 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -47,6 +47,12 @@ pub use exec_shell_settings::{ExecShellSettings, ExecShellSettingsError, ShellCh pub const EXEC_SHELL_CONFIG_INVALID: &str = "EXEC_SHELL_CONFIG_INVALID"; pub const EXEC_SHELL_UNAVAILABLE: &str = "EXEC_SHELL_UNAVAILABLE"; +/// How long a shell command's interrupt may take to record its terminal before +/// the shell is terminated. Some shells print the end marker after the +/// interrupt and the command ends with its interrupted status; one still +/// running after this window cannot end inside the live shell. +const SHELL_COMMAND_STOP_WAIT_MS: u64 = 2_000; + #[cfg(windows)] const WINDOWS_SANDBOX_UNAVAILABLE: &str = "The sandbox has no backend on Windows; select Off in /settings > Process isolation"; @@ -440,21 +446,6 @@ pub struct OutputPageReply { 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)] @@ -632,20 +623,6 @@ pub struct OutputRequest { 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 { @@ -1265,7 +1242,24 @@ impl HostPlatform { .shell .write(b"\x03") .await - .map_err(|error| HostPlatformError::Io(error.to_string())) + .map_err(|error| HostPlatformError::Io(error.to_string()))?; + if task.wait(Some(SHELL_COMMAND_STOP_WAIT_MS)).await.status != WaitStatus::Running { + return Ok(()); + } + // A command still running after the interrupt did not end + // inside the live shell (some shells abort the whole wrapper + // line, so no end marker can print). The command runs in the + // terminal's foreground process group, which a shell that + // aborts the line leaves running; signal it before terminating + // the shell, whose sweep records the command's terminal. + command.shell.kill_foreground_group().await; + command.shell.terminate(); + if task.wait(Some(SHELL_COMMAND_STOP_WAIT_MS)).await.status == WaitStatus::Running { + return Err(HostPlatformError::Failed( + "the shell did not confirm the command's end".into(), + )); + } + Ok(()) } TaskKind::Job(job) => { if !self.stopping.lock().unwrap().insert(task.id.clone()) { @@ -1409,13 +1403,6 @@ impl HostPlatform { } } - 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, @@ -1778,24 +1765,6 @@ impl HostPlatform { }) } - /// 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, @@ -3558,6 +3527,9 @@ impl PtyProcessTree { self.terminating = true; #[cfg(unix)] { + // The command an interactive shell is running leads the + // terminal's foreground group, outside the shell's own. + let foreground = self.kill_foreground_group(); native::kill_tree(self.pid); let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2); while tokio::time::Instant::now() < deadline { @@ -3566,6 +3538,9 @@ impl PtyProcessTree { None => tokio::time::sleep(std::time::Duration::from_millis(20)).await, } } + if let Some(leader) = foreground { + let _ = wait_group_gone(leader).await; + } } #[cfg(windows)] { @@ -3582,6 +3557,25 @@ impl PtyProcessTree { } Ok(()) } + /// Signals the terminal's foreground process group, where an interactive + /// shell runs the command it is executing, and answers its leader when that + /// group is not the shell's own. + pub(crate) fn kill_foreground_group(&self) -> Option { + #[cfg(unix)] + { + let leader = self.master.process_group_leader()?; + if leader as u32 == self.pid { + return None; + } + // SAFETY: plain syscall on the addressed group. + unsafe { libc::kill(-leader, libc::SIGKILL) }; + Some(leader as u32) + } + #[cfg(not(unix))] + { + None + } + } /// The root exited on its own and was reaped: its descendants stay. fn released(&self) -> bool { self.reaped && !self.terminating @@ -3592,6 +3586,7 @@ impl PtyProcessTree { impl Drop for PtyProcessTree { fn drop(&mut self) { if !self.terminated && !self.released() { + self.kill_foreground_group(); native::kill_tree(self.pid); } } @@ -3605,19 +3600,21 @@ impl Drop for PtyProcessTree { } } -/// Terminates a background job by its root pid: the process group it leads -/// on POSIX, the process tree under it on Windows. -pub fn terminate_job(pid: u32) -> io::Result<()> { - #[cfg(unix)] - { - // SAFETY: plain syscall on the addressed group. - if unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGTERM) } != 0 { - return Err(io::Error::last_os_error()); +#[cfg(unix)] +async fn wait_group_gone(leader: u32) -> bool { + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + // SAFETY: signal 0 only probes the addressed group. + if unsafe { libc::kill(-(leader as libc::pid_t), 0) } != 0 + && io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) + { + return true; } - Ok(()) + if tokio::time::Instant::now() >= deadline { + return false; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; } - #[cfg(windows)] - native::terminate_tree(pid) } async fn observe_job_release( @@ -3652,9 +3649,8 @@ async fn observe_job_release( } } -/// 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. +/// Kills a background job 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, tree: Option>) -> io::Result<()> { #[cfg(unix)] { @@ -4024,18 +4020,17 @@ pub(crate) mod shell { ExecShellRuntime, HostPlatform, ProcessSpec, ProcessSpecError, PtyProcessTree, PtySize, ShellEdition, ShellStatus, }; - use super::{TaskKind, TaskRecord, terminate_job}; + use super::{TaskKind, TaskRecord, job_tree, kill_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}, + time::Duration, }; - use tokio::sync::{Mutex as AsyncMutex, Notify, watch}; + use tokio::sync::{Mutex as AsyncMutex, watch}; use tokio_util::sync::CancellationToken; const RETAINED: usize = 64 * 1024; @@ -4049,10 +4044,8 @@ pub(crate) mod shell { 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, @@ -4263,8 +4256,6 @@ pub(crate) mod shell { } } - 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_" { @@ -4276,13 +4267,6 @@ pub(crate) mod shell { 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 [ @@ -4313,113 +4297,6 @@ pub(crate) mod shell { 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, @@ -4608,10 +4485,8 @@ pub(crate) mod shell { 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, @@ -4675,14 +4550,6 @@ pub(crate) mod shell { } } 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() { @@ -4710,15 +4577,11 @@ pub(crate) mod shell { 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(); + if let Some(pump) = pump.upgrade() + && let Some(line) = splitter.finish() + { + classify_line(&line, &pump, &jobs); } let _ = drained.send(()); }); @@ -4764,6 +4627,20 @@ pub(crate) mod shell { reader_finished, ) .await; + // A job outlives its shell only until it is released: confirm + // that before the shell's terminal sweeps it to its own. + for child in worker.children_list() { + if child.is_terminal() { + continue; + } + let pid = match &child.kind { + TaskKind::Job(job) => *job.pid.borrow(), + _ => None, + }; + if let Some(pid) = pid { + let _ = kill_job(pid, job_tree(pid)).await; + } + } let terminal = shell_terminal(&worker_record, worker.output_record(), exit, status, error); worker_record.finish(terminal); @@ -4864,7 +4741,7 @@ pub(crate) mod shell { super::TaskKind::ShellCommand(command) => command.output_record(), super::TaskKind::Job(job) => { if let Some(pid) = *job.pid.borrow() { - let _ = terminate_job(pid); + super::native::kill_tree(pid); } job.output_record().0 } @@ -4887,6 +4764,19 @@ pub(crate) mod shell { self.kill.cancel(); } + pub(crate) async fn kill_foreground_group(&self) -> bool { + let leader = { + let pty = self.pty.lock().await; + pty.as_ref().and_then(|pty| pty.kill_foreground_group()) + }; + #[cfg(unix)] + if let Some(leader) = leader { + return super::wait_group_gone(leader).await; + } + let _ = leader; + true + } + pub(crate) fn output_record(&self) -> super::OutputRecord { let capture = self.capture.lock().unwrap(); let (preview, preview_truncated) = @@ -4901,32 +4791,6 @@ pub(crate) mod shell { } } - 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() diff --git a/crates/dim-agent-capabilities/src/lib.rs b/crates/dim-agent-capabilities/src/lib.rs index b07b480373..c64eabcc4f 100644 --- a/crates/dim-agent-capabilities/src/lib.rs +++ b/crates/dim-agent-capabilities/src/lib.rs @@ -12,7 +12,6 @@ pub mod context_preparation; mod context_usage; pub mod defaults; pub mod environment_clients; -pub mod exec_stop; pub mod execution_settings; pub mod file_access; pub mod file_storage; @@ -119,7 +118,6 @@ fn register_names_in(catalog: &mut dim_agent_runtime::names::ServiceCatalog) { register::(catalog, branch); register::(catalog, branch); register::(catalog, branch); - register::(catalog, branch); register::(catalog, branch); register::(catalog, branch); catalog.register_shared_instance("branchLine", BRANCH_GROUP); @@ -146,7 +144,6 @@ impl PublicService for input_queue::SubmitChecks {} impl PublicService for permission::Permission {} impl PublicService for workspace_tools::background::BackgroundExec {} impl PublicService for shell_session::ShellSession {} -impl PublicService for dyn exec_stop::ExecStop {} impl PublicService for workspace_tools::file_reads::FileReads {} impl PublicService for timeline_tree::BranchLine {} impl PublicService for timeline_tree::TreeCommands {} diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index b3dfdf9602..b4823a38a2 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -1,54 +1,44 @@ //! Persistent shell execution capability: one long-lived PTY shell per branch. //! //! Every command runs in the same interactive shell, wrapped with runtime -//! marker pairs: the -//! command text carries the fragments only, so echoes cannot forge a full -//! marker. A dedicated OS thread owns the blocking PTY reader and forwards -//! chunks to an async consumer through a channel; no lock is held across a -//! blocking read. Commands are serialized through a queue; a foreground -//! timeout converts the call into an occupying task, and explicit -//! background jobs report completion through their own markers, ending in -//! `exec/ended`. BackgroundExec consumes terminals and owns their notices and recovery. - -use crate::workspace_tools::background::BackgroundExec; +//! marker pairs: the command text carries the fragments only, so echoes cannot +//! forge a full marker. HostPlatform owns the PTY, reads it, parses the markers +//! and records each command's and job's terminal. This part owns the queue and a +//! foreground timeout moves the running command to BackgroundExec; explicit +//! background jobs go there too. BackgroundExec publishes every shell task's +//! terminal, its completion notice and its recovery. + +use crate::workspace_tools::background::{BackgroundExec, StartError, StartRequest, WaitError}; use crate::{ - exec_stop::{ExecStop, TaskError}, host::{HostError, SessionFiles}, host_platform::{ HostPlatform, HostPlatformError, OutputRequest, ShellCommandStart, ShellEdition, - ShellEvent, ShellEventRequest, ShellJobStart, ShellRequest, ShellStatus, ShellWrite, - TaskRequest, WaitReply, WaitRequest, WaitStatus, + ShellJobStart, ShellRequest, ShellStatus, ShellWrite, TaskRequest, WaitReply, WaitRequest, + WaitStatus, }, }; 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, -}; +use dim_agent_runtime::Names; +use dim_agent_types::{ExecEndedData, JsonObject, ToolContent, ToolEffect, ToolResult}; use rutis::Ctx; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use serde_json::json; use std::{ - collections::{HashMap, VecDeque}, + collections::VecDeque, path::{Path, PathBuf}, sync::Arc, time::Duration, }; -use tokio::sync::{Notify, oneshot}; +use tokio::sync::oneshot; use tokio_util::{sync::CancellationToken, task::TaskTracker}; -const RETAINED_BUFFER_LIMIT: usize = 64 * 1024; -/// The size `retained` must pass before it is cut back to -/// `RETAINED_BUFFER_LIMIT`. A burst arrives in thousands of small chunks, so -/// trimming at the limit itself would re-copy the buffer once per chunk; the -/// slack makes the cut amortized while the buffer stays bounded by twice the -/// limit, which is far above the longest marker line it must hold. -const RETAINED_BUFFER_TRIM: usize = 2 * RETAINED_BUFFER_LIMIT; const OUTPUT_LIMIT: usize = 16_000; const MAX_TIMEOUT_MS: u64 = 3_600_000; const DESCRIPTION_CHARS: usize = 200; const INIT_TIMEOUT: Duration = Duration::from_secs(10); +/// How long one init wrapper may take before another copy is written: a +/// startup consumer can eat the first one. +const INIT_RETRY: Duration = Duration::from_secs(1); const STOP_WAIT: Duration = Duration::from_secs(2); /// Configuration for the shell session. @@ -83,48 +73,30 @@ struct QueuedCommand { done: oneshot::Sender>, } -/// The foreground call that outlived its timeout; the shell is occupied -/// until its end marker arrives. +/// The foreground call that outlived its timeout; the shell stays occupied +/// until its terminal record arrives. struct OccupyingTask { + /// The branch-visible id BackgroundExec answers. task_id: String, + /// The owner's task id the command's output is read by. + host_task_id: String, output_path: PathBuf, delivered: usize, - ended: Arc, - _hold: Option, -} - -struct BackgroundTask { - task_id: String, - output_path: PathBuf, - _hold: Option, } struct Inner { shell: Option, - /// Counts spawned shells; a consumer loop serves only its own shell. + /// Counts spawned shells; an exit waiter serves only its own shell. generation: u64, dialect: ShellDialect, shell_exe: Option, queue: VecDeque, queue_running: bool, - /// Raw stream tail, for the markers of commands that own no capture: - /// initialization, background jobs and their pids. - retained: String, occupying: Option, - background: HashMap, /// Note for the call that was running when the shell exited. shell_exit: Option, /// The next call after a shell death reports the reset. had_reset: bool, - /// Final snapshot of the last occupying task, for occupied-period waits. - occupy_tail: Option, - occupy_exit: Option, -} - -/// A terminal produced by the reader and its waiting caller. -struct Settlement { - data: ExecEndedData, - ended: Option>, } pub struct ShellSession { @@ -133,30 +105,24 @@ pub struct ShellSession { config: ShellSessionConfig, lifecycle: CancellationToken, host: Arc, - timeline: Arc, - #[expect( - dead_code, - reason = "stored at composition; no shell path dispatches through it" - )] - dispatcher: Arc, /// SessionStore's output ownership (ADR 013); absent in hosts without /// native storage, where shell output has no owner. owner: Option>, session_id: String, - session_lifecycle: Option>, - recovery: Option>, + /// Owns every shell task's terminal, notice and recovery. + background: Arc, tasks: Arc>, } impl ShellSession { - /// The branch must mount BackgroundExec to recover exec facts and publish completion notices. + /// The branch must mount BackgroundExec: it owns every shell task's + /// terminal, completion notice and recovery. pub fn new( config: ShellSessionConfig, host: Arc, - timeline: Arc, - dispatcher: Arc, owner: Option>, session_id: String, + background: Arc, ) -> Self { Self { facts: None, @@ -167,23 +133,16 @@ impl ShellSession { shell_exe: None, queue: VecDeque::new(), queue_running: false, - retained: String::new(), occupying: None, - background: HashMap::new(), shell_exit: None, had_reset: false, - occupy_tail: None, - occupy_exit: None, }), config, lifecycle: CancellationToken::new(), host, - timeline, - dispatcher, owner, session_id, - session_lifecycle: None, - recovery: None, + background, tasks: Arc::new(tokio::sync::Mutex::new(TaskTracker::new())), } } @@ -278,91 +237,109 @@ impl ShellSession { Ok(result) } - /// While the shell is occupied: wait for the occupying task, then report - /// new output; the caller's command was never sent. + /// While the shell is occupied: wait for the occupying task's terminal, + /// then report its output; the caller's command was never sent. A task the + /// owner already recorded as terminal no longer occupies the shell, so the + /// caller's command runs. async fn occupied_wait( self: &Arc, queued: &QueuedCommand, ) -> Option> { - let (notify, task_id, output_path) = { + let (task_id, host_task_id, output_path, delivered) = { let inner = self.inner.lock().await; let task = inner.occupying.as_ref()?; ( - task.ended.clone(), task.task_id.clone(), + task.host_task_id.clone(), task.output_path.clone(), + task.delivered, ) }; - 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! { + match self.background.wait(task_id.clone(), 0).await { + Ok(_) => { + self.clear_occupancy(&task_id).await; + return None; + } + Err(WaitError::Timeout) => {} + Err(error) => return Some(Err(occupancy_error(&task_id, error))), + } + let wait = self + .background + .wait(task_id.clone(), queued.timeout_ms.min(86_400_000)); + tokio::pin!(wait); + let outcome = tokio::select! { _ = 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, + outcome = &mut wait => outcome, }; - 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(); - let mut text = String::new(); - if !tail.is_empty() { - text.push_str(&tail); - if !tail.ends_with('\n') { + match outcome { + Ok(ended) => { + self.clear_occupancy(&task_id).await; + let mut text = ended_text(&ended); + if !text.is_empty() && !text.ends_with('\n') { text.push('\n'); } + text.push_str( + "The command was not executed: the shell was occupied. Resend it now.", + ); + Some(Ok(ToolResult::text(text))) } - if !exit.is_empty() { - text.push_str(&exit); - text.push('\n'); - } - 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(page) = page { - if !page.text.is_empty() { - text.push_str(&page.text); - if !page.text.ends_with('\n') { - text.push('\n'); + Err(WaitError::Timeout) => { + let page = self + .host + .output(OutputRequest { + task_id: host_task_id, + cursor: Some(delivered as u64), + limit: Some(OUTPUT_LIMIT as u64), + }) + .await + .ok(); + let mut text = String::new(); + 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; + } } + text.push_str(&format!( + "Task {} still occupies the shell. The command was not executed; resend it after the task ends.\nTask ID: {}\nOutput: {}", + task_id, + task_id, + output_path.display() + )); + Some(Ok(ToolResult::text(text))) } - 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; - } + Err(error) => Some(Err(occupancy_error(&task_id, error))), + } + } + + /// Drops the occupancy mark of a task whose terminal the owner recorded. + async fn clear_occupancy(&self, task_id: &str) { + let mut inner = self.inner.lock().await; + if inner + .occupying + .as_ref() + .is_some_and(|task| task.task_id == task_id) + { + inner.occupying = None; } - text.push_str(&format!( - "Task {} still occupies the shell. The command was not executed; resend it after the task ends.\nTask ID: {}\nOutput: {}", - task_id, - task_id, - output_path.display() - )); - Some(Ok(ToolResult::text(text))) } async fn write_shell(&self, bytes: &[u8]) -> Result<(), HostError> { @@ -407,7 +384,12 @@ impl ShellSession { if self.lifecycle.is_cancelled() { return Err(HostError::Cancelled("shell session closed".into())); } - if inner.shell.is_some() { + let alive = inner.shell.as_ref().is_some_and(|id| { + self.host + .task(id) + .is_some_and(|record| !record.is_terminal()) + }); + if alive { return Ok(None); } inner.generation @@ -516,74 +498,25 @@ impl ShellSession { inner.dialect = dialect; inner.shell_exit = None; inner.had_reset = false; - inner.occupy_tail = None; - inner.occupy_exit = None; inner.shell = Some(task_id.clone()); inner.generation }; let this = self.clone(); - let lifecycle = self.lifecycle.clone(); { let tasks = self.tasks.lock().await; tasks.spawn(async move { - 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, - 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, - }, - 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; - } - for event in page.events { - this.handle_event(event).await; - } - event_cursor = page.next_cursor; - } - this.handle_shell_exit(generation, end).await; - break; + let end = this + .host + .wait( + WaitRequest { + task_id, + timeout_ms: None, }, - } - } + cancelled_fn(&this.lifecycle), + ) + .await + .ok(); + this.handle_shell_exit(generation, end).await; }); } let exe_name = { @@ -615,45 +548,88 @@ impl ShellSession { Ok(reset_note) } - /// Sends the init command and waits for its markers; a timeout - /// terminates the shell and fails the call. + /// Writes the init wrapper until one copy's start marker and then its end + /// marker reach the shell's tail; a timeout terminates the shell and fails + /// the call. + /// + /// A shell can spend its first input on a startup consumer — zsh's newuser + /// wizard, for example — instead of the shell prompt, so the wrapper is + /// written again until one copy runs. Each copy carries its own markers, and + /// every copy is watched until the deadline, so an end marker from another + /// copy cannot complete one and a slow copy still counts; the typed line + /// carries the fragments separately, so its echo cannot satisfy the check. async fn send_initial(self: &Arc, command: &str) -> Result<(), String> { - let (start, end) = marker_pair(); let dialect = { let inner = self.inner.lock().await; inner.dialect }; - let wrapped = match dialect { - ShellDialect::Posix => posix_command(command, &start, &end), - ShellDialect::Pwsh => pwsh_command(command, &start, &end), - }; - self.write_line(&wrapped).await.map_err(|e| e.to_string())?; - let end_marker = end.full(); let deadline = tokio::time::Instant::now() + INIT_TIMEOUT; + let mut write_at = tokio::time::Instant::now(); + // Every written copy keeps its markers until the deadline: a copy + // slower than the retry interval still completes the initialization. + let mut copies: Vec<(String, String)> = Vec::new(); loop { - { + let task_id = { let inner = self.inner.lock().await; - if inner.retained.contains(&end_marker) { - return Ok(()); - } - if inner.shell.is_none() { - return Err("shell exited during initialization".into()); + inner.shell.clone() + }; + let Some(task_id) = task_id else { + return Err("shell exited during initialization".into()); + }; + let tail = self + .host + .tail(TaskRequest { + task_id: task_id.clone(), + }) + .await; + if let Ok(tail) = &tail { + for (start_marker, end_marker) in &copies { + if init_complete(&tail.text, start_marker, end_marker) { + return Ok(()); + } } } + let started = match &tail { + Ok(tail) => copies.iter().any(|(start, _)| tail.text.contains(start)), + Err(_) => false, + }; + let now = tokio::time::Instant::now(); + // A started copy is left to finish: another would only queue behind it. + if now >= write_at && !started { + let (start, end) = marker_pair(); + let wrapped = match dialect { + ShellDialect::Posix => posix_command(command, &start, &end), + ShellDialect::Pwsh => pwsh_command(command, &start, &end), + }; + self.write_shell(format!("{wrapped}\n").as_bytes()) + .await + .map_err(|error| error.to_string())?; + copies.push((start.full(), end.full())); + write_at = now + INIT_RETRY; + } + if let Err(_) = &tail + && self + .host + .task(&task_id) + .is_none_or(|record| record.is_terminal()) + { + return Err("shell exited during initialization".into()); + } if tokio::time::Instant::now() >= deadline { - let mut inner = self.inner.lock().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 { + let captured = tail.map(|tail| tail.text).unwrap_or_default(); + let taken = { + let mut inner = self.inner.lock().await; + inner.had_reset = true; + inner.shell.take() + }; + if let Some(task_id) = taken { self.stop_shell(&task_id).await; } return Err(format!( "shell did not initialize; captured output: {captured}" )); } - tokio::time::sleep(Duration::from_millis(10)).await; + tokio::time::sleep(Duration::from_millis(50)).await; } } @@ -686,151 +662,32 @@ impl ShellSession { Ok(()) } - /// 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, - } - } - - async fn handle_output(self: &Arc, text: &str) { - let mut inner = self.inner.lock().await; - 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); - } - 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 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. + /// The shell of `generation` died: note the exit, drop the occupying mark + /// and release the owner's shell record. The owner has already swept every + /// command and job child to its terminal, so BackgroundExec publishes their + /// results and this part only waits for a new shell. async fn handle_shell_exit(self: &Arc, generation: u64, end: Option) { - let mut settled: 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 shell_task = { let mut inner = self.inner.lock().await; if inner.generation != generation { return; } 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.shell_exit = Some(end.as_ref().map_or_else( + || "[shell exited]".to_owned(), + |reply| shell_exit_note(reply.signal.as_deref(), reply.exit_code), + )); } inner.had_reset = true; - if inner.dialect == ShellDialect::Posix { - orphans = inner - .background - .iter() - .map(|(id, task)| (id.clone(), task.output_path.clone())) - .collect(); - } - } - 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 { - 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) = data.result.structured_content.as_mut() { - fields.insert("code".into(), "exec_terminate_failed".into()); - } - } - settled.push(Settlement { data, ended: None }); - } + inner.occupying = None; + task_id + }; 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); - if let Some(notify) = settlement.ended { - notify.notify_waiters(); - } + self.stop_shell(&task_id).await; } } - fn settle(&self, data: ExecEndedData) { - let _ = self.timeline.append(EventKind::ExecEnded(data).into()); - } - /// 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( @@ -884,19 +741,19 @@ impl ShellSession { let note = match reply.failure_note.clone() { Some(note) => Some(note), None => { - let shell_id = self.inner.lock().await.shell.clone(); + let (shell_id, shell_exit) = { + let inner = self.inner.lock().await; + (inner.shell.clone(), inner.shell_exit.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()) + .map(|terminal| { + shell_exit_note(terminal.signal.as_deref(), terminal.exit_code) }) + .or(shell_exit) } }; if let Some(note) = note { @@ -1101,7 +958,9 @@ impl ShellSession { .map_err(|failure| failure.to_string()) } - /// Registers the running command as the occupying task and reports it. + /// Hands the command that outlived its timeout to BackgroundExec and + /// reports it. BackgroundExec registers the task, publishes its terminal + /// and settles it; this part only keeps the occupancy for the queue. async fn occupy_current( self: &Arc, command: &str, @@ -1109,26 +968,9 @@ impl ShellSession { output_path: &Path, context: &CallContext, ) -> Result { - let description = describe(command); - 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(); + if self.lifecycle.is_cancelled() { + return Err("shell session closed".into()); + } let page = self .host .output(OutputRequest { @@ -1142,121 +984,46 @@ impl ShellSession { .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 omitted = page.as_ref().is_some_and(|page| page.truncated); + let started = self + .background + .start(StartRequest { + turn_id: context.turn_id.clone(), + request_id: context.request_id.clone(), + call_id: context.call_id.clone(), + task_id: command_id.to_owned(), + host_task_id: command_id.to_owned(), + description: describe(command), + title: None, + output_path: output_path.to_string_lossy().into_owned(), + }) + .await + .map_err(|error| match error { + StartError::Closing => "shell session closed".to_owned(), + StartError::Timeline(error) => error.to_string(), + })?; { let mut inner = self.inner.lock().await; - if self.lifecycle.is_cancelled() { - return Err("shell session closed".into()); - } - self.timeline - .append( - EventKind::ExecStarted(ExecStartedData { - turn_id: context.turn_id.clone(), - request_id: context.request_id.clone(), - call_id: context.call_id.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 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: command_id.to_owned(), + task_id: started.clone(), + host_task_id: command_id.to_owned(), output_path: output_path.to_path_buf(), delivered: preview.len(), - ended: Arc::new(Notify::new()), - _hold: hold, }); } - 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 omitted { text.push_str("[Output truncated]\n"); } text.push_str(&format!( - "Command is still running and occupies the shell.\nTask ID: {command_id}\nOutput: {}", + "Command is still running and occupies the shell.\nTask ID: {started}\nOutput: {}", output_path.display() )); let mut result = ToolResult::text(text); result.structured_content = Some(structured(json!({ "type": "started", - "taskId": command_id, + "taskId": started, "outputPath": output_path.to_string_lossy(), }))); Ok(result) @@ -1309,350 +1076,49 @@ impl ShellSession { ) } }; - { - let mut inner = self.inner.lock().await; - if self.lifecycle.is_cancelled() { - return Err("shell session closed".into()); - } - self.timeline - .append( - EventKind::ExecStarted(ExecStartedData { - 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(), - title: None, - 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(), - _hold: hold, - }, - ); - } - if let Err(error) = self - .write_line_job( - &wrapped, - ShellJobStart { - task_id: task_id.clone(), - end_marker: completion.full(), - output_path: output_path_text, - }, - ) + self.write_line_job( + &wrapped, + ShellJobStart { + task_id: task_id.clone(), + end_marker: completion.full(), + output_path: output_path_text.clone(), + }, + ) + .await + .map_err(|error| error.to_string())?; + let started = self + .background + .start(StartRequest { + turn_id: context.turn_id.clone(), + request_id: context.request_id.clone(), + call_id: context.call_id.clone(), + task_id: task_id.clone(), + host_task_id: task_id, + description, + title: None, + output_path: output_path_text, + }) .await - { - let task = self.inner.lock().await.background.remove(&task_id); - if task.is_some() { - self.settle(ExecEndedData { - task_id: task_id.clone(), - status: ExecStatus::Failed, - result: ToolResult::error(error.to_string()), - }); - } - return Err(error.to_string()); - } - 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; - } - 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: {}", + .map_err(|error| match error { + StartError::Closing => "shell session closed".to_owned(), + StartError::Timeline(error) => error.to_string(), + })?; + let mut text = format!( + "Background command started.\nTask ID: {started}\nOutput: {}", output_path.display() - )); + ); + if let Some((_, error_path)) = &pwsh_paths { + text.push_str(&format!("\nStandard error: {}", error_path.display())); + } + let mut result = ToolResult::text(text); result.structured_content = Some(structured(json!({ "type": "started", - "taskId": task_id, + "taskId": started, "outputPath": output_path.to_string_lossy(), }))); Ok(ran(result, command, None)) } - /// Stops a task by id. - pub async fn stop(self: &Arc, task_id: &str) -> Result { - let occupying = { - let mut inner = self.inner.lock().await; - if inner - .occupying - .as_ref() - .is_some_and(|task| task.task_id == task_id) - { - inner.occupying.take() - } else { - None - } - }; - if let Some(occ) = occupying { - { - let inner = self.inner.lock().await; - if inner.shell.is_some() { - drop(inner); - let _ = self.write_shell(b"\x03").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; - inner.occupy_tail = Some(preview); - inner.occupy_exit = None; - if !found { - 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, - result: ToolResult::text("Command interrupted."), - }; - self.settle(data.clone()); - occ.ended.notify_waiters(); - return Ok(data); - } - let task = { - let mut inner = self.inner.lock().await; - inner.background.remove(task_id) - }; - if let Some(task) = task { - 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 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: {}", - task.output_path.display() - )); - result.structured_content = Some(structured(json!({ - "code": "exec_terminate_failed", - "taskId": task_id, - "outputPath": task.output_path.to_string_lossy(), - }))); - ExecEndedData { - task_id: task_id.to_owned(), - status: ExecStatus::Failed, - result, - } - } - }; - 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); - } - Err(TaskError::Unknown) - } - - async fn write_line(&self, line: &str) -> Result<(), HostError> { - 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 { @@ -1670,43 +1136,14 @@ impl ShellSession { } } -impl ExecStop for ShellSession { - fn stop( - self: Arc, - task_id: String, - ) -> BoxFuture<'static, Result> { - 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. /// The plugin. pub struct ShellSessionPlugin { - recovery: Key, + background: Key, facts: Key, session: Key, - stop: Key, - timeline: Key, - dispatcher: Key, host: Key, lifecycle: Key, session_config: Key, - session_lifecycle: Key, identity: Key, config: Option, } @@ -1722,16 +1159,12 @@ impl ShellSessionPlugin { /// Derive execution settings from the owning Session. pub fn session(names: &Names<'_>) -> rutis::Result { Ok(Self { - recovery: names.key()?, + background: names.key()?, facts: names.key()?, session: names.key()?, - stop: names.key()?, - timeline: names.key()?, - dispatcher: names.key()?, host: names.key()?, lifecycle: names.key()?, session_config: names.key()?, - session_lifecycle: names.key()?, identity: names.key()?, config: None, }) @@ -1744,24 +1177,18 @@ impl DynPlugin for ShellSessionPlugin { } fn injects(&self) -> Vec { vec![ - self.recovery.erase(), - self.timeline.erase(), - self.dispatcher.erase(), + self.background.erase(), self.host.erase(), self.lifecycle.erase(), self.session_config.erase(), - self.session_lifecycle.erase(), self.identity.erase(), ] } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { - 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 background = ctx.require_at(&self.background)?; 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( @@ -1776,14 +1203,11 @@ impl DynPlugin for ShellSessionPlugin { .join(&identity.branch_id), }), host, - timeline, - dispatcher, owner, identity.session_id.clone(), + background, ); 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 { @@ -1804,26 +1228,21 @@ impl DynPlugin for ShellSessionPlugin { tasks.wait().await; let generation = service.inner.lock().await.generation; service.handle_shell_exit(generation, None).await; - let remaining = service - .inner - .lock() - .await - .background - .keys() - .cloned() - .collect::>(); - for task in remaining { - let _ = ShellSession::stop(&service, &task).await; - } Ok(()) })?; - ctx.provide_at(self.session.clone(), session.clone())?; - ctx.provide_at::(self.stop.clone(), session)?; + ctx.provide_at(self.session.clone(), session)?; Ok(Effect::Done) }) } } +/// Whether `tail` holds `start` and `end` after it. An end marker a consumer +/// printed for an earlier copy, or by itself, does not complete a copy. +fn init_complete(tail: &str, start: &str, end: &str) -> bool { + tail.find(start) + .is_some_and(|at| tail[at + start.len()..].contains(end)) +} + /// 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. @@ -1862,24 +1281,15 @@ fn push_output(text: &mut String, output: &str) { } } -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 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 { @@ -1902,98 +1312,40 @@ fn exit_line(code: &str) -> String { } } -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, +/// The model-readable text of a terminal record. +fn ended_text(data: &ExecEndedData) -> String { + match &data.result.content { + ToolContent::Text(text) => text.clone(), + ToolContent::Blocks(blocks) => blocks + .iter() + .filter_map(|block| match block { + dim_agent_types::ContentBlock::Text { text } => Some(text.as_str()), + dim_agent_types::ContentBlock::Image { .. } => None, + }) + .collect::>() + .join("\n"), } } -fn ended_result(task_id: &str, output_path: &Path, preview: &str, code: &str) -> ToolResult { - let status = exit_status(code); - let label = match status { - ExecStatus::Completed => "completed", - ExecStatus::Failed => "failed", - ExecStatus::Cancelled => "cancelled", - }; - let mut text = preview.to_owned(); - if !text.is_empty() && !text.ends_with('\n') { - text.push('\n'); +fn occupancy_error(task_id: &str, error: WaitError) -> String { + match error { + WaitError::Unknown => { + format!("task {task_id} still occupies the shell but has no task facts") + } + WaitError::Closed => "shell session closed while waiting for the shell".to_owned(), + WaitError::Timeout => format!("task {task_id} still occupies the shell"), + WaitError::Read(error) => error.to_string(), } - text.push_str(&exit_line(code)); - let mut result = ToolResult::text(text); - result.is_error = (status == ExecStatus::Failed).then_some(true); - result.structured_content = Some(structured(json!({ - "type": "finished", - "status": label, - "taskId": task_id, - "outputPath": output_path.to_string_lossy(), - }))); - result } -fn shell_exit_note(terminal: &crate::host_platform::Terminal) -> String { - match (terminal.signal.as_deref(), terminal.exit_code) { +fn shell_exit_note(signal: Option<&str>, exit_code: Option) -> String { + match (signal, 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(); - if !text.is_empty() && !text.ends_with('\n') { - text.push('\n'); - } - text.push_str("[Task failed: shell was reset]"); - let mut result = ToolResult::text(text); - result.is_error = Some(true); - result.structured_content = Some(structured(json!({ - "type": "finished", - "status": "failed", - "taskId": task_id, - "outputPath": output_path.to_string_lossy(), - }))); - result -} - -/// Removes a completion marker line from a capture. -fn strip_marker(text: &mut String, marker: &str) { - if let Some(pos) = text.find(marker) { - let end = text[pos..] - .find('\n') - .map_or(text.len(), |offset| pos + offset + 1); - text.replace_range(pos..end, ""); - } -} - pub(crate) fn regularize_output(bytes: &[u8]) -> String { let text = String::from_utf8_lossy(bytes); let mut out = String::new(); @@ -2045,17 +1397,6 @@ pub(crate) fn regularize_output(bytes: &[u8]) -> String { out } -fn tail_bytes(s: &str, limit: usize) -> &str { - if s.len() <= limit { - return s; - } - let mut start = s.len() - limit; - while !s.is_char_boundary(start) { - start += 1; - } - &s[start..] -} - struct MarkerPair { first: String, second: String, @@ -2200,3 +1541,22 @@ fn base64_encode(data: &str) -> String { use base64::Engine; base64::engine::general_purpose::STANDARD.encode(data.as_bytes()) } + +#[cfg(test)] +mod tests { + use super::init_complete; + + #[test] + fn an_init_copy_completes_only_after_its_own_start_marker() { + let start = "__DIM_START_aaaaaaaa_bbbbbbbb__"; + let end = "__DIM_END_cccccccc_dddddddd__"; + assert!(init_complete( + &format!("noise\n{start}\ninit output\n{end}\n"), + start, + end + )); + assert!(!init_complete(&format!("{end}\n{start}\n"), start, end)); + assert!(!init_complete(&format!("echo {end}\n"), start, end)); + assert!(!init_complete(&format!("{start}\n"), start, end)); + } +} diff --git a/crates/dim-agent-capabilities/src/workspace_tools/background.rs b/crates/dim-agent-capabilities/src/workspace_tools/background.rs index cdf572eb03..8ce67bdc56 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/background.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/background.rs @@ -62,6 +62,10 @@ pub enum TaskError { /// This instance was unloaded. #[error("BackgroundExec is closed")] Closed, + /// The stop is pending: the owner has not confirmed the task's release, so + /// the task is still running and its terminal will follow. + #[error("the task is still running; the stop is pending")] + Running, } /// Why one paged read of a task's registered output file answered nothing. @@ -188,6 +192,11 @@ pub(crate) fn decode_page( }) } +/// How long `stop` waits for a terminal before it answers the pending stop: the +/// owner confirms the release first, and a terminal that cannot be confirmed +/// stays pending instead of blocking the caller. +const STOP_REPLY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + /// 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. pub(crate) const PAGE_CHAR_TRAILING_BYTES: usize = 3; @@ -206,6 +215,8 @@ struct Task { final_preview: Option, /// The dispatched `exec/ended`, once its wake decision is done. ended: watch::Sender>, + /// Set when the owner answered the stop as unconfirmed; the terminal follows. + pending_stop: watch::Sender, } impl Task { fn new( @@ -221,6 +232,7 @@ impl Task { output_path, final_preview: None, ended: watch::Sender::new(None), + pending_stop: watch::Sender::new(false), } } } @@ -246,6 +258,7 @@ async fn wait_owner( platform: &HostPlatform, host_task_id: &str, cancel: &CancellationToken, + pending: Option<&watch::Sender>, ) -> Option { let waited = platform .wait( @@ -259,11 +272,19 @@ async fn wait_owner( match waited { Ok(reply) => Some(reply), Err(HostPlatformError::Cancelled) => { - let _ = platform + let killed = platform .kill(TaskRequest { task_id: host_task_id.to_owned(), }) .await; + match killed { + Ok(()) | Err(HostPlatformError::TaskUnknown | HostPlatformError::TaskEnded) => {} + Err(_) => { + if let Some(pending) = pending { + pending.send_replace(true); + } + } + } platform .wait( WaitRequest { @@ -424,9 +445,10 @@ impl BackgroundExec { let platform = self.platform.clone(); let supervised = task_id.clone(); let parent = dim_agent_runtime::core::current_parent_call_id(); + let pending = self.pending_stop(&supervised); self.tasks.spawn(async move { let run = async { - let reply = wait_owner(&platform, &host_task_id, &cancel).await; + let reply = wait_owner(&platform, &host_task_id, &cancel, pending.as_ref()).await; if let Some(reply) = &reply { let mut state = owner.state.lock().unwrap(); if let Some(task) = state.tasks.get_mut(&supervised) { @@ -667,9 +689,22 @@ impl BackgroundExec { } } - /// Stops a task: cancels it while running, so it ends `cancelled` and - /// does not wake. Returns once its `exec/ended` is dispatched; a task that - /// already ended keeps its result and its wake. + fn pending_stop(&self, task_id: &str) -> Option> { + self.state + .lock() + .unwrap() + .tasks + .get(task_id) + .map(|task| task.pending_stop.clone()) + } + + /// Stops a task and answers the owner's terminal: a native command or a + /// background job ends `cancelled` and does not wake, while a shell command + /// is interrupted and ends with the interrupted line's own status, so it + /// wakes. Returns once its `exec/ended` is dispatched; a task that already + /// ended keeps its result and its wake. When the owner has not confirmed the + /// release, answers `running`: the task keeps its record and hold, and its + /// terminal follows. pub async fn stop(&self, task_id: String) -> Result { let current = { let mut state = self.state.lock().unwrap(); @@ -680,10 +715,10 @@ impl BackgroundExec { if task.ended.borrow().is_none() { task.cancel.cancel(); } - task.ended.subscribe() + (task.ended.subscribe(), task.pending_stop.subscribe()) }) }; - let Some(mut ended) = current else { + let Some((mut ended, mut pending)) = current else { if self .started(&task_id, self.timeline.committed()) .await @@ -706,11 +741,25 @@ impl BackgroundExec { )) }); }; - ended - .wait_for(Option::is_some) - .await - .map(|done| done.clone().expect("waited for Some")) - .map_err(|_| TaskError::Closed) + if let Some(done) = ended.borrow().clone() { + return Ok(done); + } + if *pending.borrow() { + return Err(TaskError::Running); + } + let waited = tokio::time::timeout(STOP_REPLY_TIMEOUT, async { + tokio::select! { + result = ended.wait_for(Option::is_some) => result + .map(|done| done.clone().expect("waited for Some")) + .map_err(|_| TaskError::Closed), + _ = pending.wait_for(|pending| *pending) => Err(TaskError::Running), + } + }) + .await; + match waited { + Ok(result) => result, + Err(_) => Err(TaskError::Running), + } } fn consume( diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index c766275f45..71e7e7aee0 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -135,6 +135,10 @@ pub(super) async fn stop( Err(super::background::TaskError::Closed) => Err(HostError::Cancelled( dim_agent_runtime::CAPABILITY_RELOADING.into(), )), + Err(super::background::TaskError::Running) => Ok(failed( + "The stop was requested; the command is still running because the owner has not confirmed its release. It is not stopped yet, and its result will follow.", + "exec_task_running", + )), } } @@ -2196,11 +2200,13 @@ fn settled_from_reply(reply: &WaitReply) -> (Settled, Option) { 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(), - }); + // The owner records a known exit even when the terminal is `failed` (a + // shell command that ended with a non-zero status, for example), so the + // exit travels with the fields, not with the wait status. + let exit = (reply.exit_code.is_some() || reply.signal.is_some()).then(|| CommandExit { + code: reply.exit_code, + signal: reply.signal.clone(), + }); (settled, exit) } @@ -2219,10 +2225,13 @@ pub(super) fn background_result(task_id: &str, reply: &WaitReply) -> (ExecStatus ), _ if settled.failure.is_some() => { let failure = settled.failure.as_ref().expect("guarded"); - let summary = match failure { - TaskFailure::OutputWriteFailed { message } => { + let summary = match (failure, &exit) { + (TaskFailure::OutputWriteFailed { message }, _) => { format!("exec output offload failed: {message}") } + (TaskFailure::CommandFailed | TaskFailure::UnknownExit, Some(exit)) => { + exit_failure_summary(exit) + } _ => failure.to_string(), }; (ExecStatus::Failed, summary, "failed") diff --git a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs index a0ac1fe108..00fae5e484 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs @@ -575,6 +575,11 @@ impl DynPlugin for WorkspaceToolsPlugin { ), background::TaskError::Closed => RpcError::reloading(), background::TaskError::Read(error) => error.into(), + background::TaskError::Running => RpcError::app( + -32000, + "exec_task_running", + "The task is still running", + ), })?; Ok(serde_json::json!({"text":text})) }) diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index cc2af05114..76408232c5 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -2384,3 +2384,118 @@ async fn a_job_write_terminalizes_and_reads_its_output() { .unwrap(); std::fs::remove_dir_all(dir).unwrap(); } + +/// A job whose pid never arrives answers a bounded `task_running` and keeps its +/// record running; the shell's sweep writes its terminal. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_job_without_a_pid_stays_running_until_the_shell_sweep() { + let dir = std::env::temp_dir().join(unique("dim-host-job-pid")); + 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: "pid-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 output_path = dir.join("job-1.log"); + platform + .write(ShellWrite { + task_id: "pid-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(b"sleep 30\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 + .unwrap(); + + let started = std::time::Instant::now(); + let killed = platform + .kill(TaskRequest { + task_id: "job-1".into(), + }) + .await; + assert!( + matches!(killed, Err(HostPlatformError::TaskRunning)), + "{killed:?}" + ); + assert!( + started.elapsed() >= std::time::Duration::from_millis(1_800), + "the stop must be bounded by the pid wait: {:?}", + started.elapsed() + ); + let reply = platform + .wait( + WaitRequest { + task_id: "job-1".into(), + timeout_ms: Some(0), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(reply.status, WaitStatus::Running, "{reply:?}"); + + platform + .kill(TaskRequest { + task_id: "pid-shell".into(), + }) + .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::Failed, "{reply:?}"); + assert!( + matches!( + reply.failure, + Some(TaskFailure::ShellExited | TaskFailure::ShellReset) + ), + "{reply:?}" + ); + platform + .settle(TaskRequest { + task_id: "pid-shell".into(), + }) + .await + .unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index e4f0f2bdb4..26edd54103 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -741,10 +741,6 @@ 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 99b49ad2b7..0a5f478472 100644 --- a/crates/dim-agent-runtime/src/branch.rs +++ b/crates/dim-agent-runtime/src/branch.rs @@ -152,9 +152,6 @@ 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 178a2c564c..2a36fe209c 100644 --- a/crates/dim-agent-runtime/src/timeline_context.rs +++ b/crates/dim-agent-runtime/src/timeline_context.rs @@ -328,10 +328,6 @@ 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 cccd28dcc7..f9c7a5dea6 100644 --- a/crates/dim-app-server/src/connection.rs +++ b/crates/dim-app-server/src/connection.rs @@ -7,7 +7,6 @@ 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}, @@ -1629,35 +1628,26 @@ impl Connection { if p.task_id.is_empty() { return Err(RpcError::invalid("taskId must not be empty")); } - 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( + let result = 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", ), - exec_stop::TaskError::Closed => RpcError::reloading(), - exec_stop::TaskError::Read => { + TaskError::Closed => RpcError::reloading(), + 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(), - })? - }; + TaskError::Running => RpcError::app( + -32000, + "exec_task_running", + "The stop was requested; the command is still running and its release is not confirmed", + ), + })?; Reply::ExecEnded(result) } Call::SessionSkills(p) => { diff --git a/docs/architecture/rust-agent/capability-event-inventory.md b/docs/architecture/rust-agent/capability-event-inventory.md index 70bf6beef0..a81990f892 100644 --- a/docs/architecture/rust-agent/capability-event-inventory.md +++ b/docs/architecture/rust-agent/capability-event-inventory.md @@ -34,7 +34,7 @@ | TreeTimeline | 执行分支创建、结束命令及结算 | branch/create、branch/end、turn/end;branch 结果事实 | [实现](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) / [说明](plugins/TimelineTree.md) | | WaitBranch | 当前回合内的等待通知与单次等待 | input/message、turn/start、turn/end;不直接写事实 | [实现](../../../crates/dim-agent-capabilities/src/wait.rs) / [说明](plugins/Wait.md) | | HooksBranch | 按已消费事实运行 Hooks,采用有效输出 | input/message;读取 input、turn、approval、tool 等触发事实 | [实现](../../../crates/dim-agent-capabilities/src/hooks/runner.rs) / [说明](plugins/Hooks.md) | -| ShellSession | 持续 shell 执行、后台任务和完成通知 | exec/*、input/message;读取中断与回合事实 | [实现](../../../crates/dim-agent-capabilities/src/shell_session.rs) | +| ShellSession | 持续 shell 执行与命令队列,把后台任务和前台超时转后台的命令交给 BackgroundExec | 不直接写 Timeline 事实;命令终态由 BackgroundExec 发布 | [实现](../../../crates/dim-agent-capabilities/src/shell_session.rs) | ## 核心 Timeline 事件(50 个具体 key) @@ -56,8 +56,8 @@ | `approval/respond` | 对审批请求的决定 | Approval 响应入口 | Approval、HooksBranch、协作审批 | | `approval/cancelled` | 审批请求取消结算 | Approval | Approval 恢复、HooksBranch、协作审批 | | `permission/changed` | 分支权限策略变更 | Permission | Permission | -| `exec/started` | 后台执行已开始 | BackgroundExec、ShellSession | 各执行所有者恢复、GoalBranch、执行历史 | -| `exec/ended` | 后台执行终态 | BackgroundExec、ShellSession | 各执行所有者、GoalBranch;另由生产方发布唤醒输入 | +| `exec/started` | 后台执行已开始 | BackgroundExec | 各执行所有者恢复、GoalBranch、执行历史 | +| `exec/ended` | 后台执行终态 | BackgroundExec | 各执行所有者、GoalBranch;另由生产方发布唤醒输入 | | `turn/start` | 回合开始 | Loop | WaitBranch、Prompt、InputQueue、执行与协作部件 | | `turn/end` | 回合结束及结果 | Loop | WaitBranch、InputQueue、GoalBranch、HooksBranch、执行与协作部件 | | `prompt/changed` | 提示词快照已采用 | Prompt 经 ConfigurationPublisher | Prompt、ContextUsage/配置恢复 | diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index d1a35c6930..50a32f76c3 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -26,7 +26,9 @@ A task id is reserved by the owner before a command or background job starts. `s 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 +shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. A job with no pid answers `task_running` after two seconds and keeps a pid watcher, and a +kill that fails keeps the watcher too: the job record stays running, and its terminal comes from +the confirmed release or from the shell's sweep. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal. Some shells print the end marker after the interrupt, so the command's terminal is the interrupted line's own exit status — which can be success when the line continues past the interrupted command — and `kill` returns from that wait; a command still running after two seconds cannot end inside the live shell, so `kill` signals the terminal's foreground process group — where an interactive shell runs the command, outside the shell's own group — and terminates the shell, whose terminal sweeps the command as a reset. Terminating a shell — this stop, a shell kill or a Session close — releases that foreground group the same way before the shell's terminal sweeps its children. 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 @@ -37,7 +39,12 @@ given their path. `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 +children. Before a shell writes its terminal, it attempts to release each live job whose pid is +known: SIGKILL to the job's group and, where the platform can enumerate them, its descendants, then +a wait of up to two seconds. The sweep keeps a SIGKILL backstop. This is best effort: `kill_job`'s +result is dropped, so a failed kill is not reported, and a descendant that left the job's group or +session can outlive the job's terminal. 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 @@ -157,11 +164,21 @@ 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. `ShellJob.pid` -stores the typed PID in the owner record; `ShellSession` keeps only the task id and calls +stores the typed PID in the owner record; the calling task owner 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. +A persistent shell's first command is the init wrapper, and the shell may spend its first +input on a startup consumer instead — zsh's newuser module runs a wizard when the user has no +startup files. `ShellSession` writes that wrapper again until a copy's own start marker and then +its end marker reached the shell's tail, and it watches every written copy until the init +deadline, so neither a startup consumer nor a shell slower than the retry interval can lose the +initialization. Each copy carries its own marker pair, and a copy counts only when its own start +marker precedes its end marker: an end marker a consumer emitted for another copy or by itself +does not count. A copy that started is not replaced, because another would only queue behind it. +The wrapper uses the same marker fragments as every command, so its echoed text cannot pass for +the marker. ## Command construction diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index cfb5a3e8d7..cec34a8250 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -138,13 +138,14 @@ 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. 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 +App Server calls the branch's `BackgroundExec` in every profile; the operation maps +`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 -without stopping any command. Detached exec results name this operation and +including when the process tree could not be released. When the owner has not +confirmed the release, the operation answers `running` — an explicit pending stop: +the task stays running, keeps its cleanup and Session hold, and its terminal +follows. An unknown task fails without stopping any command. Detached exec results name this operation and distinguish their Task ID from Collaboration's Agent and Session identities. ```text @@ -520,7 +521,7 @@ stopped." The other tools' refusal codes (`invalid_input`, `not_regular_file`, `is_directory`, `file_modified_since_read`, `text_binding_required`, `permission_denied`, `write_error`, `exec_invalid_request`, -`exec_task_unknown`, `exec_terminate_failed`, `exec_wait_failed`, +`exec_task_unknown`, `exec_task_running`, `exec_terminate_failed`, `exec_wait_failed`, `exec_output_offload_failed`) reach clients and persistence in `structuredContent`; `ToolResult.content` carries the sentence the model reads, and HistoryRenderer renders the content alone, so no code reaches the model. A @@ -645,10 +646,12 @@ a filesystem lock, permission grant or cross-process compare-and-swap. ## BackgroundExec Owner: [workspace_tools/background.rs](../../../../crates/dim-agent-capabilities/src/workspace_tools/background.rs). -Owns commands transferred from foreground execution, their terminal records and -bounded completion notices on the calling branch. It also settles abandoned exec -facts and posts completion notices for ShellSession; that producer retains its live -PTY and stop port. See [Shell exec recovery](../../../design/shell-exec-recovery.md) +Owns every task it registers — a detached `exec` command, a persistent shell's +background job and a shell command that outlived its foreground wait — with their +terminal records and bounded completion notices on the calling branch. It also +settles abandoned exec facts. `ShellSession` hands its tasks to `start` and keeps +its queue and occupancy; the owner records every shell task's terminal and is the +one stop entry for both task kinds. See [Shell exec recovery](../../../design/shell-exec-recovery.md) for the profile and generation handoff. `start` carries an optional task `title` into `exec/started` alongside the unchanged command-derived `description`. `session.exec.pending` returns that same title in each `PendingExec` item. The fact and inventory field are optional strings: missing values deserialize as absent and absent values are omitted on serialization. Existing persisted facts and inventories without a title remain readable. Persistence uses [native format v48](../../../design/appserver/native-storage-format.md#v48-task-titles), a marker-only, one-way upgrade that makes older strict readers reject the store at startup; ShellInput's command facts have no supplied title. This adds no state owner or service face and changes neither execution nor cancellation. The existing `toolHost`, `treeCommands` and `backgroundExec` faces retain their operations. @@ -671,12 +674,19 @@ the typed `BackgroundExec` serves it and stays the Rust binding. clamps to 4 MiB, `bytes` is what the page consumed, and the next cursor is `cursor + bytes`; `nextCursor` is present only for a full page. `wait` answers an ended task at once and otherwise waits for its dispatch until `timeoutMs` elapses. -For a running task, `timeoutMs = 0` answers `timeout`. `stop` is kill: it cancels -a running task so it ends `cancelled` -and does not wake, and answers an already ended task's record without changing -its wake. Cancellation is the caller dropping the call: a dropped `outputPage` +For a running task, `timeoutMs = 0` answers `timeout`. `stop` is kill: it stops +a running task and answers the owner's terminal, or `running` when the owner has +not confirmed the release (the task keeps its record and cleanup, and the terminal +follows); an already ended task keeps its record and wake. The terminal decides the wake: `cancelled` stays silent and +every other status posts the completion notice. A command that started as a +native process and a persistent shell's background job both end `cancelled`, so +neither wakes. A shell command is interrupted in its persistent shell; its +terminal is the interrupted wrapper line's own status, so an interrupted command +followed by `|| true` ends `completed`, and a line the shell aborts ends with the +owner's shell reset. A stopped shell command does wake. Cancellation is the caller dropping the call: a dropped `outputPage` drops the read and a dropped `wait` releases the watch. `start` needs the live -process, so it is the `exec` tool's own operation and is not on the face. +process, so it is the caller's own operation — the `exec` tool and `ShellSession` — +and is not on the face. Historical `outputPage`, `wait` and `stop` calls use the owner's bounded task-fact reads, without rebuilding a historical task cache. `wait` returns a historical terminal record without waiting for execution; `timeoutMs` governs the completion wait for a live task. Failed reads or inconsistent required facts answer `read`, not `unknown`. Dropping a historical call cancels its read. diff --git a/docs/design/agent-tool-modes.md b/docs/design/agent-tool-modes.md index eb32053ea4..7e7d0b3d53 100644 --- a/docs/design/agent-tool-modes.md +++ b/docs/design/agent-tool-modes.md @@ -305,14 +305,12 @@ product), and mounting `ShellTools` instead of `WorkspaceTools` for shell Sessio the client methods that part registers (`session.files` mention search, command-output paging), so a shell Session would lose client features that have nothing to do with its tools. -Stopping a task is a separate route. Today `session.exec.stop` resolves the branch's -`BackgroundExec` and stops a native process; a live persistent-shell command belongs to -`ShellSession`, which provides the branch's `dyn ExecStop`. With `execute` in the product, both -kinds exist in one Session: - -- The stop route resolves the live owner first: the branch's `ExecStop` for a live shell task, then - `BackgroundExec` for a native process. A task neither owns is read from shared history for its - terminal result; history never answers for a live task. +Stopping a task is a separate route. `session.exec.stop` resolves the branch's +`BackgroundExec` and stops the task. A live persistent-shell command is handed to the same owner +when its call converts, so both kinds exist in one Session: + +- The stop route calls `BackgroundExec` for every task kind. A task it does not own is read from + shared history for its terminal result; history never answers for a live task. - Both parts stay mounted when the mode changes, so a task started in `shell` or `codemode` can still be stopped after the Session switches to `normal`. - `session.stop` remains the turn's stop and stops no background task. @@ -475,8 +473,8 @@ force (the `effective` value) and shows the named refusal otherwise. `set`/`resume` are refused while `shell` is in force; a chosen `shell` that runs `normal` (no `execute`) neither pauses nor refuses; after leaving, the operator resumes the goal. - Flow: stop a shell task with `session.exec.stop` after switching the Session to `normal`; the - route resolves the live `ExecStop` before `BackgroundExec`, and neither answers for a live task - from history. The minimal-execution profile's Session runs `shell` and keeps `execute`. + route calls `BackgroundExec`, and history never answers for a live task. The + minimal-execution profile's Session runs `shell` and keeps `execute`. - Clients: a web component test for the composer menu and the remembered choice, and one tmux TUI case for the row and the picker. - No event type or envelope changes. The stored configuration gains an optional field that old diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index aab98b04f0..2b162e0900 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -340,10 +340,11 @@ does not claim a test that is not in the tree. ### 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. +that case. `session.exec.stop` is step 6: it calls the branch stop owner. `BackgroundExec` gains no +`ShellSession` dependency; `ShellSession`'s dependency on `BackgroundExec` stays. +[#2032](https://github.com/arcships/dim/issues/2032) board A replaced the two-provider route this +record describes: shell tasks are registered with `BackgroundExec`, and `BackgroundExec.stop` is the +only stop entry ([WorkspaceTools §BackgroundExec](../../architecture/rust-agent/plugins/WorkspaceTools.md#backgroundexec)). ## 8. Rule check | Rule | Application | | --- | --- | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 678339f473..0024c36f8b 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -157,7 +157,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou 形状与错误由所有者文档定义:[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` 只保存 branch task id、host task id 和 output path,实时读取走 `hostPlatform.tail`/`output`。`backgroundExec.stop` 是 kill。持久 PTY 由 `HostPlatform` 拥有,`ShellSession` 持有策略;公共 PTY 操作只有 `shell`/`write`/`resize`。 +`backgroundExec.start` 需要活的进程对象,仍是调用方自己的操作——`exec` 工具和 `ShellSession`——不在数据面上;`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` 不按对象分类保留:服务本身就是公开契约;一个 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)。 diff --git a/docs/design/shell-exec-recovery.md b/docs/design/shell-exec-recovery.md index 349f86c8ac..f41fa42e89 100644 --- a/docs/design/shell-exec-recovery.md +++ b/docs/design/shell-exec-recovery.md @@ -1,25 +1,26 @@ # Shell exec recovery -ShellSession owns its branch's PTY, command queue, foreground-to-background handoff and process cleanup. -It writes the existing `exec/started` and `exec/ended` facts. BackgroundExec owns recovery and completion -notices for that shared exec protocol; its [query, fork boundary and notice contract](../architecture/rust-agent/plugins/WorkspaceTools.md#backgroundexec) +ShellSession owns its branch's persistent shell, command queue and foreground-to-background handoff. +It does not write exec facts: a background job and a foreground command that outlives its wait are +handed to BackgroundExec, which registers the task, publishes its terminal and settles it. +BackgroundExec owns recovery and completion notices for that shared exec protocol; its +[query, fork boundary and notice contract](../architecture/rust-agent/plugins/WorkspaceTools.md#backgroundexec) applies to facts from either execution producer. Event types do not have an exclusive writer. ## Assembly and handoff The minimal-execution profile mounts BackgroundExec alongside ShellSession. ShellSession declares a -load-order dependency on `backgroundExec`: recovery finishes before a new shell can accept commands, -and a reload of the recovery owner first unloads its shell dependent. ShellSession releases its old -processes and writes their terminal facts before BackgroundExec is removed. A ShellSession-only reload -does not restart the recovery owner or mistake another producer's live work for abandoned history. +required dependency on `backgroundExec`: recovery finishes before a new shell can accept commands, +and a reload of the recovery owner first unloads its shell dependent. A ShellSession-only reload does +not restart the recovery owner or mistake another producer's live work for abandoned history. The local-execution profile already provides BackgroundExec, so a host adding ShellSession there reuses it. -ShellSession appends terminals but does not append wake inputs. The Dispatcher delivers terminals to -BackgroundExec, which applies the existing status and branch-closing rules and writes the tagged notice. -For a terminal without a native BackgroundExec task, it reads that task's description from its exact -`exec/started` fact; it does not build a second task table or take ownership of a live PTY. -The existing ShellSession stop port continues to stop its own live tasks. BackgroundExec's live capture -and native-process stop operations are not a new PTY control interface. +ShellSession hands a task to BackgroundExec only after HostPlatform accepted the command or job; on +handoff failure BackgroundExec terminates and settles the owner task. HostPlatform records every +shell task's terminal from its markers and sweeps a dead shell's commands and jobs to their +expected terminals. BackgroundExec then writes the one `exec/ended` per task and posts the wake +input; nobody synthesizes a result or publishes one because a wait timed out. The only stop entry is +`BackgroundExec.stop`; there is no separate shell stop port. ## Recovery cases @@ -37,11 +38,11 @@ Publication, failure handling and retry on the next generation remain the owner' ## Rule check -Both branch parts are Capabilities under principles §1. ShellSession owns I/O and terminal production; -BackgroundExec owns recovery/notification decisions for the exec protocol. This changes the profile's -assembly and removes a duplicate notification writer, not the meaning of an exec event. +Both branch parts are Capabilities under principles §1. ShellSession owns I/O policy and the command +queue; BackgroundExec owns registration, terminal facts, recovery and notification for every task it +registers. This changes who registers a shell task, not the meaning of an exec event. -- Principles §4 rules 1, 2 and 7: the terminal is the handoff; neither part mutates the other's state. +- Principles §4 rules 1, 2 and 7: the owner terminal is the handoff; neither part mutates the other's state. - Rule 3: no before callback. - Rules 4 and 8: existing Timeline queries, Dispatcher and dependency lifecycle; no mechanism change. - Rule 5: existing separate terminal/notice commits remain valid, including recovery of that gap. @@ -60,4 +61,6 @@ The minimal-execution flow restores disposable storage containing an unfinished completed end and a cancelled end. It checks failed settlement, preservation of the existing result, notice eligibility, each notice's stored command description and no duplicates on another restoration. These are committed-prefix recovery cases, not a claim that the test killed a real host process. Live background and occupying-command flows also check the completion notice. -Stop and shell-exit flows check terminal outcomes; the close flow checks one terminal per admitted task. +A shell-exit flow checks the terminal the owner records and that the swept job's process is gone; the +close flow checks one terminal per admitted task, and a recovery restart checks that the live shell +task settles before recovery inspects history. diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 3c4c521e6b..e03ce36b8c 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1092,6 +1092,7 @@ export type TaskError = | /** Required task facts could not be read. */ { read: [] } | /** No matching task or live output on this branch. */ "unknown" | /** This instance was unloaded. */ "closed" + | /** The stop is pending: the owner has not confirmed the task's release, so the task is still running and its terminal will follow. */ "running" /** * One page of a task's registered output file, as @@ -1164,9 +1165,13 @@ export interface BackgroundExec { */ wait(taskId: string, timeoutMs: number | bigint): Promise /** - * Stops a task: cancels it while running, so it ends `cancelled` and - * does not wake. Returns once its `exec/ended` is dispatched; a task that - * already ended keeps its result and its wake. + * Stops a task and answers the owner's terminal: a native command or a + * background job ends `cancelled` and does not wake, while a shell command + * is interrupted and ends with the interrupted line's own status, so it + * wakes. Returns once its `exec/ended` is dispatched; a task that already + * ended keeps its result and its wake. When the owner has not confirmed the + * release, answers `running`: the task keeps its record and hold, and its + * terminal follows. * @throws {TaskErrorThrown} */ stop(taskId: string): Promise @@ -1825,7 +1830,7 @@ export type SessionInstanceErrorThrown = RustError<"SessionInstanceError", "Crea export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "no_session" | "session_closing" | "session_reloading" | "session_unavailable" | "no_line" | "not_data_face" | "method_not_routable" | "wrong_scope" | "routed" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> /** What a method returning `Err(TaskError)` throws. */ -export type TaskErrorThrown = RustError<"TaskError", "read" | "unknown" | "closed", TaskError> +export type TaskErrorThrown = RustError<"TaskError", "read" | "unknown" | "closed" | "running", TaskError> /** What a method returning `Err(WaitCallError)` throws. */ export type WaitCallErrorThrown = RustError<"WaitCallError", "AlreadyWaiting" | "Reloading", undefined> diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index a6a8129f63..83b6571a8c 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -10,7 +10,10 @@ use dim_agent_capabilities::{ file_storage::FileStoragePlugin, history::HistoryRenderer, host::*, - host_platform::{HostPlatform, HostPlatformConfig, HostPlatformPlugin, resolve_shell}, + host_platform::{ + ExecShellRuntime, HostPlatform, HostPlatformConfig, HostPlatformPlugin, OutputEncoding, + ShellEdition, ShellSource, ShellStatus, resolve_shell, + }, model_provider::ModelProviderPlugin, permission::{CommandRules, NoCommandRules}, skill_settings::SkillSettingsHost, @@ -20,7 +23,7 @@ use dim_agent_runtime::testing::MinimalHost; use dim_agent_runtime::testing::{branch_events, chain_events}; use dim_agent_runtime::*; use dim_agent_types::*; -use process_support::{gone, pid_in}; +use process_support::{alive, gone, pid_in}; use rutis::host::CtxHost; use rutis::{Ctx, Plugin}; use serde_json::{Value, json}; @@ -655,7 +658,12 @@ async fn new_persistent_shells_and_environment_refresh_use_current_preferences() .await; session.idle("main").await.unwrap(); let events = local_events(&session).await; - assert!(text(results(&events).last().unwrap()).contains(&format!("selected={alternate}"))); + let call_results = results(&events); + let selected = text(call_results.last().unwrap()); + assert!( + selected.contains(&format!("selected={alternate}")), + "expected selected={alternate}: {selected}" + ); let environment = events .iter() .rev() @@ -874,6 +882,131 @@ async fn timeout_occupies_shell_and_wakes() { harness.shutdown().await; } +/// An ended command no longer occupies the shell: the next call runs its +/// command instead of asking for a resend. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_call_after_the_occupying_command_ends_runs() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + harness + .run( + &session, + &[( + "execute", + json!({"command": "sleep 0.4 && echo occupied", "timeoutMs": 100}), + )], + ) + .await; + let events = until(&session, "occupying admission", |events| { + count(events, "exec/started") == 1 && tool_results(events) == 1 + }) + .await; + assert!( + text(&results(&events)[0]).contains("occupies the shell"), + "{}", + text(&results(&events)[0]) + ); + until(&session, "occupying wake", |events| { + !notifications(events).is_empty() + }) + .await; + harness + .run(&session, &[("execute", json!({"command": "echo next"}))]) + .await; + let events = until(&session, "next result", |events| tool_results(events) == 2).await; + let result = &results(&events)[1]; + assert!(text(result).contains("next"), "{}", text(result)); + session.close().await.unwrap(); + harness.shutdown().await; +} + +/// A command that moves to the background keeps the exit status it ended with. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_handed_off_command_keeps_its_exit_code() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + harness + .run( + &session, + &[( + "execute", + json!({"command": "sleep 0.3; sh -c 'exit 7'", "timeoutMs": 100}), + )], + ) + .await; + let events = until(&session, "occupying admission", |events| { + count(events, "exec/started") == 1 && tool_results(events) == 1 + }) + .await; + let task_id = task_of(&results(&events)[0]); + let events = until(&session, "exec ended", |events| ended(events).len() == 1).await; + let (_, end) = &ended(&events)[0]; + assert_eq!(end.task_id, task_id); + assert_eq!(end.status, ExecStatus::Failed); + let fields = end.result.structured_content.as_ref().unwrap(); + assert_eq!(fields.get("exitCode").and_then(Value::as_i64), Some(7)); + assert_eq!( + fields.get("summary").and_then(Value::as_str), + Some("Command exited with code 7.") + ); + assert!( + text(&end.result).contains("Command exited with code 7."), + "{}", + text(&end.result) + ); + session.close().await.unwrap(); + harness.shutdown().await; +} + +/// A detached shell job keeps the exit status it ended with. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_detached_job_keeps_its_exit_code() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + harness + .run( + &session, + &[( + "execute", + json!({"command": "sh -c 'exit 7'", "runInBackground": true}), + )], + ) + .await; + let events = until(&session, "exec started", |events| tool_results(events) == 1).await; + let task_id = task_of(&results(&events)[0]); + let events = until(&session, "exec ended", |events| ended(events).len() == 1).await; + let (_, end) = &ended(&events)[0]; + assert_eq!(end.task_id, task_id); + assert_eq!(end.status, ExecStatus::Failed); + let fields = end.result.structured_content.as_ref().unwrap(); + assert_eq!(fields.get("exitCode").and_then(Value::as_i64), Some(7)); + assert_eq!( + fields.get("summary").and_then(Value::as_str), + Some("Command exited with code 7.") + ); + assert!( + text(&end.result).contains("Command exited with code 7."), + "{}", + text(&end.result) + ); + + let stop = session + .service::("main") + .unwrap(); + let stopped = stop.stop(task_id.clone()).await.unwrap(); + let stopped_fields = stopped.result.structured_content.as_ref().unwrap(); + assert_eq!( + stopped_fields.get("exitCode").and_then(Value::as_i64), + Some(7) + ); + assert_eq!( + stopped_fields.get("summary").and_then(Value::as_str), + Some("Command exited with code 7.") + ); + session.close().await.unwrap(); + harness.shutdown().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn stop_background_task() { let harness = Harness::new(platform(&[]).await).await; @@ -896,10 +1029,9 @@ async fn stop_background_task() { let pid = pid_in(&pid_file).await; let stop = session - .service_opt::("main") - .unwrap() - .expect("the minimal profile provides the branch stop owner"); - let ended = stop.clone().stop(task_id.clone()).await.unwrap(); + .service::("main") + .unwrap(); + let ended = stop.stop(task_id.clone()).await.unwrap(); assert_eq!(ended.status, ExecStatus::Cancelled); assert!(gone(&pid).await); let repeated = stop.stop(task_id).await.unwrap(); @@ -908,6 +1040,234 @@ async fn stop_background_task() { harness.shutdown().await; } +/// Stopping a command that converted to the background returns a terminal and +/// leaves the shell usable. A shell may abort the wrapper line on the interrupt, +/// in which case the owner terminates the shell and the command ends as a reset; +/// a shell that prints the end marker ends it with the interrupted status. For +/// this command both are a failed terminal. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn stop_an_occupying_command_returns_and_the_shell_keeps_working() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + harness + .run( + &session, + &[("execute", json!({"command": "sleep 60", "timeoutMs": 100}))], + ) + .await; + let events = until(&session, "occupying admission", |events| { + count(events, "exec/started") == 1 && tool_results(events) == 1 + }) + .await; + let task_id = task_of(&results(&events)[0]); + + let stop = session + .service::("main") + .unwrap(); + let ended = tokio::time::timeout(Duration::from_secs(10), stop.stop(task_id.clone())) + .await + .expect("the stop returns once the owner confirms the terminal") + .unwrap(); + assert_eq!(ended.task_id, task_id); + assert_eq!(ended.status, ExecStatus::Failed); + + harness + .run( + &session, + &[("execute", json!({"command": "echo after-stop"}))], + ) + .await; + let events = until(&session, "next result", |events| tool_results(events) == 2).await; + let result = &results(&events)[1]; + assert!(text(result).contains("after-stop"), "{}", text(result)); + session.close().await.unwrap(); + harness.shutdown().await; +} + +/// A command that ignores the interrupt is released by the owner. The command +/// runs in the terminal's foreground process group, not the shell's, and macOS +/// has no `/proc` tree to walk, so the owner signals that group itself before +/// it terminates the shell. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn stopping_a_command_that_ignores_the_interrupt_leaves_no_process() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + let pid_file = harness.cwd.join("stubborn.pid"); + harness + .run( + &session, + &[( + "execute", + json!({ + "command": format!( + "sh -c 'echo $$ > {}; trap \"\" INT TERM HUP; while true; do sleep 1; done'", + pid_file.display() + ), + "timeoutMs": 100 + }), + )], + ) + .await; + let events = until(&session, "occupying admission", |events| { + count(events, "exec/started") == 1 && tool_results(events) == 1 + }) + .await; + let task_id = task_of(&results(&events)[0]); + let pid = pid_in(&pid_file).await; + + let stop = session + .service::("main") + .unwrap(); + let ended = tokio::time::timeout(Duration::from_secs(10), stop.stop(task_id.clone())) + .await + .expect("the stop returns once the owner confirms the terminal") + .unwrap(); + assert_eq!(ended.task_id, task_id); + assert_eq!(ended.status, ExecStatus::Failed); + let path = if cfg!(target_os = "macos") { + " the foreground-group signal did not release it" + } else { + "" + }; + assert!(gone(&pid).await, "process {pid} survived the stop;{path}"); + session.close().await.unwrap(); + harness.shutdown().await; +} + +/// A shell slower than the init retry still initializes: every written copy is +/// watched until the deadline, not only the newest. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_slow_shell_still_initializes() { + let Some(platform) = zsh_platform() else { + return; + }; + let harness = Harness::new(platform).await; + std::fs::write(harness.cwd.join(".zshrc"), "preexec() { sleep 1.5; }\n").unwrap(); + let session = harness.session().await; + harness + .run( + &session, + &[("execute", json!({"command": "printf 'ready'"}))], + ) + .await; + let events = until(&session, "result", |events| tool_results(events) == 1).await; + let call_results = results(&events); + let result = text(&call_results[0]); + assert!(result.contains("ready"), "{result}"); + session.close().await.unwrap(); + harness.shutdown().await; +} + +/// Closing a Session releases the command its shell is running, not only +/// stopping a task. macOS has no `/proc` tree to walk, so the shell's +/// termination signals the terminal's foreground process group. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn closing_a_session_releases_an_occupying_command() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + let pid_file = harness.cwd.join("closing.pid"); + harness + .run( + &session, + &[( + "execute", + json!({ + "command": format!( + "sh -c 'echo $$ > {}; trap \"\" INT TERM HUP; while true; do sleep 1; done'", + pid_file.display() + ), + "timeoutMs": 100 + }), + )], + ) + .await; + let events = until(&session, "occupying admission", |events| { + count(events, "exec/started") == 1 && tool_results(events) == 1 + }) + .await; + let task_id = task_of(&results(&events)[0]); + let pid = pid_in(&pid_file).await; + + session.close().await.unwrap(); + let events = local_events(&session).await; + let (_, end) = ended(&events) + .into_iter() + .find(|(_, data)| data.task_id == task_id) + .expect("closing publishes the occupying task's terminal"); + assert_eq!(end.status, ExecStatus::Failed); + let path = if cfg!(target_os = "macos") { + " the foreground-group signal did not release it" + } else { + "" + }; + assert!( + gone(&pid).await, + "process {pid} survived the Session close;{path}" + ); + harness.shutdown().await; +} + +/// A startup consumer cannot skip the initialization. The `.zshrc` lives in the +/// shell's home, consumes the wrapper line up to the boundary before the final +/// `printf`, and leaves the shell to run that `printf`: the end marker alone +/// reaches the tail while the init never ran. `/bin/zsh` absent skips the case. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_startup_consumer_cannot_skip_the_init() { + let Some(platform) = zsh_platform() else { + return; + }; + let harness = Harness::new(platform).await; + // The harness makes its cwd the shell's HOME. + std::fs::write( + harness.cwd.join(".zshrc"), + r#"HISTFILE=/tmp/dim-consumer-history +__dim_buf= +while true; do + read -k 1 __dim_ch || break + __dim_buf+=$__dim_ch + if [[ $__dim_buf == *"eval $'"* && $__dim_buf == *"'; " ]]; then + break + fi +done +"#, + ) + .unwrap(); + let session = harness.session().await; + harness + .run( + &session, + &[( + "execute", + json!({"command": "printf 'histfile=%s' \"${HISTFILE-unset}\""}), + )], + ) + .await; + let events = until(&session, "result", |events| tool_results(events) == 1).await; + let call_results = results(&events); + let result = text(&call_results[0]); + assert!(result.contains("histfile=unset"), "{result}"); + session.close().await.unwrap(); + harness.shutdown().await; +} + +fn zsh_platform() -> Option { + let zsh = "/bin/zsh"; + if !Path::new(zsh).is_file() { + return None; + } + let runtime = ExecShellRuntime { + executable_path: zsh.into(), + edition: ShellEdition::Zsh, + source: ShellSource::Fallback, + output_encoding: OutputEncoding::Utf8, + }; + Some( + HostPlatform::current(ShellStatus::Available(runtime)) + .unwrap() + .with_execution_settings(ExecutionSettingsHost::fixed(ExecutionSettings::default())), + ) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn shell_exit_settles_tasks() { let harness = Harness::new(platform(&[]).await).await; @@ -1167,7 +1527,7 @@ async fn a_call_that_converts_before_its_output_writes_only_the_command_output() &session, &[( "execute", - json!({"command": "echo first; echo second", "timeoutMs": 0}), + json!({"command": "sleep 0.1; echo first; echo second", "timeoutMs": 0}), )], ) .await; @@ -1213,13 +1573,69 @@ async fn shell_exit_kills_background_jobs() { assert_eq!(end.task_id, task_id); assert_eq!(end.status, ExecStatus::Failed); assert!( - text(&end.result).contains("shell was reset"), + text(&end.result).contains("shell exited"), "{}", text(&end.result) ); assert!( gone(&pid).await, - "background process {pid} survived the shell reset: result={:?}, process={:?}", + "background process {pid} survived the shell exit: result={:?}, process={:?}", + end.result, + std::process::Command::new("ps") + .args(["-o", "pid=,ppid=,pgid=,stat=,comm=", "-p", &pid]) + .output() + .map(|output| ( + output.status, + String::from_utf8_lossy(&output.stdout).into_owned(), + String::from_utf8_lossy(&output.stderr).into_owned(), + )) + ); + session.close().await.unwrap(); + harness.shutdown().await; +} + +/// A job that ignores SIGTERM is gone before its terminal is published: the +/// shell confirms each job's release while it ends, instead of a single +/// unconfirmed signal from the terminal sweep. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_term_ignoring_job_is_gone_before_its_terminal() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + let pid_file = harness.cwd.join("ignoring.pid"); + harness + .run( + &session, + &[( + "execute", + json!({ + "command": format!( + "sh -c 'trap \"\" TERM; echo $$ > {}; sleep 60'", + pid_file.display() + ), + "runInBackground": true + }), + )], + ) + .await; + let events = until(&session, "start", |events| tool_results(events) == 1).await; + let task_id = task_of(&results(&events)[0]); + let pid = pid_in(&pid_file).await; + + harness + .run(&session, &[("execute", json!({"command": "exit 7"}))]) + .await; + let events = until(&session, "job settled", |events| ended(events).len() == 1).await; + let (_, end) = &ended(&events)[0]; + assert_eq!(end.task_id, task_id); + assert_eq!(end.status, ExecStatus::Failed); + assert!( + !alive(&pid), + "process {pid} was alive when its terminal was published: result={:?}", + end.result + ); + assert!( + gone(&pid).await, + "background process {pid} survived the shell exit: result={:?}, process={:?}", end.result, std::process::Command::new("ps") .args(["-o", "pid=,ppid=,pgid=,stat=,comm=", "-p", &pid]) @@ -1492,10 +1908,12 @@ async fn restarting_exec_recovery_settles_the_live_shell_before_rebuilding() { ended(events).len() == 1 && notifications(events).len() == 1 }) .await; + assert_eq!(ended(&after)[0].1.status, ExecStatus::Failed); assert_eq!(count(&after, "exec/started"), 1); assert!( - text(&ended(&after)[0].1.result).contains("shell was reset"), - "the live shell must settle before recovery inspects history" + text(&ended(&after)[0].1.result).contains("shell reset"), + "the live shell must settle before recovery inspects history: {}", + text(&ended(&after)[0].1.result) ); { let ready = tokio::time::timeout( diff --git a/xtask/access-layer.json b/xtask/access-layer.json index c397d34865..0e1879d54e 100644 --- a/xtask/access-layer.json +++ b/xtask/access-layer.json @@ -520,11 +520,6 @@ "file": "crates/dim-agent-runtime/src/agent.rs", "item": "Session::service" }, - { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::service_opt" - }, { "kind": "session-forwarding", "file": "crates/dim-agent-runtime/src/agent.rs",