Skip to main content

merry_runtime/process/
background.rs

1//! Session-scoped handles for processes that outlive one `run_process` call.
2//!
3//! The process backend owns the live child. This module is the typed view the
4//! runtime, the model tools, and `/tasks` share.
5
6use std::fmt;
7
8/// Identifier returned to the model when a background process is retained.
9#[derive(Debug, Clone, PartialEq, Eq, Hash)]
10pub struct BackgroundProcessId(String);
11
12impl BackgroundProcessId {
13    /// Accepts one model-supplied id.
14    pub fn new(value: impl Into<String>) -> Result<Self, String> {
15        let value = value.into();
16        let valid = !value.is_empty()
17            && value.len() <= 64
18            && value
19                .chars()
20                .all(|character| character.is_ascii_alphanumeric() || character == '-');
21        if !valid {
22            return Err(
23                "background process id must be 1-64 ASCII letters, digits, or hyphens".to_owned(),
24            );
25        }
26        Ok(Self(value))
27    }
28
29    /// Borrows the id text.
30    #[must_use]
31    pub fn as_str(&self) -> &str {
32        &self.0
33    }
34}
35
36impl fmt::Display for BackgroundProcessId {
37    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38        formatter.write_str(&self.0)
39    }
40}
41
42/// Lifecycle of one retained background process.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum BackgroundProcessState {
45    /// The process group is still running.
46    Running {
47        /// Operating-system pid of the retained process.
48        pid: u32,
49    },
50    /// The process exited on its own.
51    Exited {
52        /// Exit code, or `-1` when the platform did not report one.
53        code: i32,
54    },
55    /// `stop_background_process` or session teardown killed the process group.
56    Killed,
57}
58
59impl BackgroundProcessState {
60    /// Returns the short status used in tool results and `/tasks`.
61    #[must_use]
62    pub fn label(&self) -> String {
63        match self {
64            Self::Running { pid } => format!("running pid {pid}"),
65            Self::Exited { code } => format!("exited {code}"),
66            Self::Killed => "killed".to_owned(),
67        }
68    }
69}
70
71/// Compact row for a retained background process.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct BackgroundProcessSummary {
74    id: BackgroundProcessId,
75    display_name: Option<String>,
76    command: String,
77    cwd: Option<String>,
78    state: BackgroundProcessState,
79}
80
81impl BackgroundProcessSummary {
82    /// Creates one list row.
83    #[must_use]
84    pub fn new(
85        id: BackgroundProcessId,
86        command: impl Into<String>,
87        cwd: Option<String>,
88        state: BackgroundProcessState,
89    ) -> Self {
90        Self {
91            id,
92            display_name: None,
93            command: command.into(),
94            cwd,
95            state,
96        }
97    }
98
99    /// Attaches an optional short human-readable display name.
100    #[must_use]
101    pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
102        self.display_name = display_name
103            .map(|value| value.trim().to_owned())
104            .filter(|value| !value.is_empty());
105        self
106    }
107
108    /// Returns the process id.
109    #[must_use]
110    pub fn id(&self) -> &BackgroundProcessId {
111        &self.id
112    }
113
114    /// Returns the optional human-readable display name.
115    #[must_use]
116    pub fn display_name(&self) -> Option<&str> {
117        self.display_name.as_deref()
118    }
119
120    /// Returns the preferred human-facing label (`display_name` when present,
121    /// otherwise the process id).
122    #[must_use]
123    pub fn display_label(&self) -> &str {
124        self.display_name.as_deref().unwrap_or(self.id.as_str())
125    }
126
127    /// Returns the command text shown to the model.
128    #[must_use]
129    pub fn command(&self) -> &str {
130        &self.command
131    }
132
133    /// Returns the workspace-relative cwd, when the call set one.
134    #[must_use]
135    pub fn cwd(&self) -> Option<&str> {
136        self.cwd.as_deref()
137    }
138
139    /// Returns the current lifecycle state.
140    #[must_use]
141    pub fn state(&self) -> &BackgroundProcessState {
142        &self.state
143    }
144}
145
146/// Captured output for one retained background process.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct BackgroundProcessOutput {
149    summary: BackgroundProcessSummary,
150    stdout: String,
151    stderr: String,
152    stdout_truncated: bool,
153    stderr_truncated: bool,
154}
155
156impl BackgroundProcessOutput {
157    /// Creates a read result from the retained capture.
158    #[must_use]
159    pub fn new(
160        summary: BackgroundProcessSummary,
161        stdout: impl Into<String>,
162        stderr: impl Into<String>,
163        stdout_truncated: bool,
164        stderr_truncated: bool,
165    ) -> Self {
166        Self {
167            summary,
168            stdout: stdout.into(),
169            stderr: stderr.into(),
170            stdout_truncated,
171            stderr_truncated,
172        }
173    }
174
175    /// Returns the process row.
176    #[must_use]
177    pub fn summary(&self) -> &BackgroundProcessSummary {
178        &self.summary
179    }
180
181    /// Returns captured stdout since the process started, bounded by the original call.
182    #[must_use]
183    pub fn stdout(&self) -> &str {
184        &self.stdout
185    }
186
187    /// Returns captured stderr since the process started, bounded by the original call.
188    #[must_use]
189    pub fn stderr(&self) -> &str {
190        &self.stderr
191    }
192
193    /// Returns whether stdout capture hit its limit.
194    #[must_use]
195    pub const fn stdout_truncated(&self) -> bool {
196        self.stdout_truncated
197    }
198
199    /// Returns whether stderr capture hit its limit.
200    #[must_use]
201    pub const fn stderr_truncated(&self) -> bool {
202        self.stderr_truncated
203    }
204}
205
206/// Result of asking a retained process to stop.
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct BackgroundProcessStop {
209    summary: BackgroundProcessSummary,
210    changed: bool,
211}
212
213impl BackgroundProcessStop {
214    /// Creates a stop result.
215    ///
216    /// `changed` is true only when this call moved a running process to killed.
217    #[must_use]
218    pub fn new(summary: BackgroundProcessSummary, changed: bool) -> Self {
219        Self { summary, changed }
220    }
221
222    /// Returns the process row after the stop attempt.
223    #[must_use]
224    pub fn summary(&self) -> &BackgroundProcessSummary {
225        &self.summary
226    }
227
228    /// Returns whether this call killed a process that was still running.
229    #[must_use]
230    pub const fn changed(&self) -> bool {
231        self.changed
232    }
233}
234
235/// A model-supplied id did not match a retained process.
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct BackgroundProcessLookupError {
238    id: BackgroundProcessId,
239    known: Vec<BackgroundProcessId>,
240}
241
242impl BackgroundProcessLookupError {
243    /// Creates a lookup miss that names the id and the ids still retained.
244    #[must_use]
245    pub fn new(id: BackgroundProcessId, known: Vec<BackgroundProcessId>) -> Self {
246        Self { id, known }
247    }
248
249    /// Returns the text the model should see.
250    #[must_use]
251    pub fn message(&self) -> String {
252        if self.known.is_empty() {
253            format!(
254                "No background process `{}`. No background processes are retained.",
255                self.id
256            )
257        } else {
258            let known = self
259                .known
260                .iter()
261                .map(BackgroundProcessId::as_str)
262                .collect::<Vec<_>>()
263                .join(", ");
264            format!("No background process `{}`. Known: {known}.", self.id)
265        }
266    }
267}
268
269/// Session-owned control surface for retained background processes.
270///
271/// Implementations live with the process backend that holds the child.
272pub trait BackgroundProcessControl: Send + Sync {
273    /// Lists retained processes, refreshing exit state first.
274    fn list(&self) -> Vec<BackgroundProcessSummary>;
275
276    /// Returns one process and the output captured since it started.
277    fn read(
278        &self,
279        id: &BackgroundProcessId,
280    ) -> Result<BackgroundProcessOutput, BackgroundProcessLookupError>;
281
282    /// Kills one retained process group.
283    ///
284    /// A process that has already exited or been killed returns that state
285    /// with `changed == false`.
286    fn stop(
287        &self,
288        id: &BackgroundProcessId,
289    ) -> Result<BackgroundProcessStop, BackgroundProcessLookupError>;
290}