Skip to main content

merry_runtime/
process_background_tool.rs

1//! Model tools for processes retained by `run_process` with `background: true`.
2
3use crate::{
4    BackgroundProcessControl, BackgroundProcessId, BackgroundProcessLookupError,
5    BackgroundProcessOutput, BackgroundProcessStop, BackgroundProcessSummary,
6    ProcessCommandToolError, RegisteredTool, ToolActionKind, ToolExecutionContext,
7    ToolExecutionOutcome, ToolExecutor, ToolExecutorFuture,
8};
9use merry_core::{ErrorInfo, PendingToolCall};
10use merry_tools_macros::tool;
11use schemars::JsonSchema;
12use serde::Deserialize;
13use std::sync::Arc;
14
15const INVALID_ARGUMENTS: &str = "background_process_invalid_arguments";
16const NOT_FOUND: &str = "background_process_not_found";
17
18#[tool(
19    crate = "crate",
20    name = "read_background_process",
21    description = "Read a background process retained by run_process. Omit process_id to list id, state, and command. Provide the id from that result to read later stdout and stderr."
22)]
23#[derive(Debug, Deserialize, JsonSchema)]
24#[serde(deny_unknown_fields)]
25struct ReadBackgroundProcessInput {
26    #[schemars(
27        description = "Id reported by a background run_process result. Omit it to list retained processes."
28    )]
29    #[serde(default)]
30    process_id: Option<String>,
31}
32
33#[tool(
34    crate = "crate",
35    name = "stop_background_process",
36    description = "Stop one background process group by the id from a background run_process result. A process that has already exited or been killed reports that state."
37)]
38#[derive(Debug, Deserialize, JsonSchema)]
39#[serde(deny_unknown_fields)]
40struct StopBackgroundProcessInput {
41    #[schemars(
42        description = "Id reported by a background run_process result.",
43        length(min = 1, max = 64)
44    )]
45    process_id: String,
46}
47
48/// Registers the read-only background process tool.
49pub fn read_background_process_tool(
50    control: Arc<dyn BackgroundProcessControl>,
51) -> Result<RegisteredTool, ProcessCommandToolError> {
52    let spec =
53        ReadBackgroundProcessInput::tool_spec().map_err(|error| ProcessCommandToolError::Core {
54            source: error.into(),
55        })?;
56    Ok(
57        RegisteredTool::read_only(spec, Arc::new(ReadBackgroundProcessExecutor { control }))
58            .with_parallel_safe_execution(),
59    )
60}
61
62/// Registers the tool that stops one retained background process group.
63pub fn stop_background_process_tool(
64    control: Arc<dyn BackgroundProcessControl>,
65) -> Result<RegisteredTool, ProcessCommandToolError> {
66    let spec =
67        StopBackgroundProcessInput::tool_spec().map_err(|error| ProcessCommandToolError::Core {
68            source: error.into(),
69        })?;
70    Ok(RegisteredTool::new(
71        spec,
72        Arc::new(StopBackgroundProcessExecutor { control }),
73        ToolActionKind::RuntimeControl,
74    )
75    .with_parallel_safe_execution())
76}
77
78struct ReadBackgroundProcessExecutor {
79    control: Arc<dyn BackgroundProcessControl>,
80}
81
82impl ToolExecutor for ReadBackgroundProcessExecutor {
83    fn execute<'a>(
84        &'a self,
85        call: PendingToolCall,
86        _context: ToolExecutionContext,
87    ) -> ToolExecutorFuture<'a> {
88        Box::pin(async move {
89            let input = match call
90                .arguments()
91                .deserialize_as::<ReadBackgroundProcessInput>()
92            {
93                Ok(input) => input,
94                Err(error) => return Ok(invalid_arguments(error.to_string())),
95            };
96            let Some(process_id) = input
97                .process_id
98                .as_deref()
99                .map(str::trim)
100                .filter(|id| !id.is_empty())
101            else {
102                return Ok(ToolExecutionOutcome::succeeded_text(format_list(
103                    &self.control.list(),
104                )));
105            };
106            let id = match BackgroundProcessId::new(process_id) {
107                Ok(id) => id,
108                Err(message) => return Ok(invalid_arguments(message)),
109            };
110            match self.control.read(&id) {
111                Ok(output) => Ok(ToolExecutionOutcome::succeeded_text(format_output(&output))),
112                Err(error) => Ok(not_found(&error)),
113            }
114        })
115    }
116}
117
118struct StopBackgroundProcessExecutor {
119    control: Arc<dyn BackgroundProcessControl>,
120}
121
122impl ToolExecutor for StopBackgroundProcessExecutor {
123    fn execute<'a>(
124        &'a self,
125        call: PendingToolCall,
126        _context: ToolExecutionContext,
127    ) -> ToolExecutorFuture<'a> {
128        Box::pin(async move {
129            let input = match call
130                .arguments()
131                .deserialize_as::<StopBackgroundProcessInput>()
132            {
133                Ok(input) => input,
134                Err(error) => return Ok(invalid_arguments(error.to_string())),
135            };
136            let id = match BackgroundProcessId::new(input.process_id.trim()) {
137                Ok(id) => id,
138                Err(message) => return Ok(invalid_arguments(message)),
139            };
140            match self.control.stop(&id) {
141                Ok(stopped) => Ok(ToolExecutionOutcome::succeeded_text(format_stop(&stopped))),
142                Err(error) => Ok(not_found(&error)),
143            }
144        })
145    }
146}
147
148fn format_list(processes: &[BackgroundProcessSummary]) -> String {
149    if processes.is_empty() {
150        return "No background processes.".to_owned();
151    }
152    processes
153        .iter()
154        .map(|process| match process.display_name() {
155            Some(name) => format!(
156                "{} ({name}) {} {}",
157                process.id(),
158                process.state().label(),
159                process.command()
160            ),
161            None => format!(
162                "{} {} {}",
163                process.id(),
164                process.state().label(),
165                process.command()
166            ),
167        })
168        .collect::<Vec<_>>()
169        .join("\n")
170}
171
172fn format_output(output: &BackgroundProcessOutput) -> String {
173    let summary = output.summary();
174    let stdout_label = stream_label("stdout", output.stdout_truncated());
175    let stderr_label = stream_label("stderr", output.stderr_truncated());
176    format!(
177        "{} {}\ncommand: {}\n{stdout_label}:\n{}\n{stderr_label}:\n{}",
178        summary.id(),
179        summary.state().label(),
180        summary.command(),
181        output.stdout(),
182        output.stderr()
183    )
184}
185
186fn format_stop(stopped: &BackgroundProcessStop) -> String {
187    let summary = stopped.summary();
188    if stopped.changed() {
189        format!("{} killed", summary.id())
190    } else {
191        format!("{} already {}", summary.id(), summary.state().label())
192    }
193}
194
195fn stream_label(name: &str, truncated: bool) -> String {
196    if truncated {
197        format!("{name} (truncated)")
198    } else {
199        name.to_owned()
200    }
201}
202
203fn invalid_arguments(message: String) -> ToolExecutionOutcome {
204    failed_outcome(INVALID_ARGUMENTS, message)
205}
206
207fn not_found(error: &BackgroundProcessLookupError) -> ToolExecutionOutcome {
208    failed_outcome(NOT_FOUND, error.message())
209}
210
211fn failed_outcome(code: &str, message: String) -> ToolExecutionOutcome {
212    ToolExecutionOutcome::failed_text(
213        message.clone(),
214        ErrorInfo::new(code, &message).expect("background process diagnostic is valid"),
215    )
216}
217
218#[cfg(test)]
219mod tests {
220    use super::{ReadBackgroundProcessExecutor, StopBackgroundProcessExecutor, format_list};
221    use crate::{
222        BackgroundProcessControl, BackgroundProcessId, BackgroundProcessLookupError,
223        BackgroundProcessOutput, BackgroundProcessState, BackgroundProcessStop,
224        BackgroundProcessSummary, ToolExecutionContext, ToolExecutor,
225    };
226    use merry_core::{PendingToolCall, ToolCallArguments, ToolCallId, ToolName};
227    use serde_json::json;
228    use std::sync::{Arc, Mutex};
229
230    struct FakeControl {
231        processes: Mutex<Vec<BackgroundProcessSummary>>,
232    }
233
234    impl FakeControl {
235        fn running() -> Self {
236            Self {
237                processes: Mutex::new(vec![BackgroundProcessSummary::new(
238                    BackgroundProcessId::new("bg-1").expect("id"),
239                    "sleep 30",
240                    None,
241                    BackgroundProcessState::Running { pid: 42 },
242                )]),
243            }
244        }
245    }
246
247    impl BackgroundProcessControl for FakeControl {
248        fn list(&self) -> Vec<BackgroundProcessSummary> {
249            self.processes.lock().expect("process list").clone()
250        }
251
252        fn read(
253            &self,
254            id: &BackgroundProcessId,
255        ) -> Result<BackgroundProcessOutput, BackgroundProcessLookupError> {
256            let processes = self.list();
257            let summary = processes
258                .iter()
259                .find(|process| process.id() == id)
260                .cloned()
261                .ok_or_else(|| {
262                    BackgroundProcessLookupError::new(
263                        id.clone(),
264                        processes
265                            .iter()
266                            .map(|process| process.id().clone())
267                            .collect(),
268                    )
269                })?;
270            Ok(BackgroundProcessOutput::new(
271                summary, "ready\n", "", false, false,
272            ))
273        }
274
275        fn stop(
276            &self,
277            id: &BackgroundProcessId,
278        ) -> Result<BackgroundProcessStop, BackgroundProcessLookupError> {
279            let mut processes = self.processes.lock().expect("process list");
280            let Some(process) = processes.iter_mut().find(|process| process.id() == id) else {
281                let known = processes
282                    .iter()
283                    .map(|process| process.id().clone())
284                    .collect();
285                return Err(BackgroundProcessLookupError::new(id.clone(), known));
286            };
287            let changed = matches!(process.state(), BackgroundProcessState::Running { .. });
288            if changed {
289                let id = process.id().clone();
290                let command = process.command().to_owned();
291                let cwd = process.cwd().map(str::to_owned);
292                *process =
293                    BackgroundProcessSummary::new(id, command, cwd, BackgroundProcessState::Killed);
294            }
295            Ok(BackgroundProcessStop::new(process.clone(), changed))
296        }
297    }
298
299    fn call(name: &str, arguments: serde_json::Value) -> PendingToolCall {
300        PendingToolCall::new(
301            ToolCallId::new("call-background").expect("call id"),
302            ToolName::new(name).expect("tool name"),
303            ToolCallArguments::try_from(arguments).expect("arguments"),
304        )
305    }
306
307    fn text(outcome: &crate::ToolExecutionOutcome) -> String {
308        outcome.content().as_str().to_owned()
309    }
310
311    #[tokio::test]
312    async fn read_lists_when_the_id_is_omitted_and_returns_output_for_an_id() {
313        let control = Arc::new(FakeControl::running());
314        let executor = ReadBackgroundProcessExecutor {
315            control: control.clone(),
316        };
317        let listed = executor
318            .execute(
319                call("read_background_process", json!({})),
320                ToolExecutionContext::default(),
321            )
322            .await
323            .expect("list");
324        assert_eq!(text(&listed), format_list(&control.list()));
325        assert!(text(&listed).contains("bg-1 running pid 42 sleep 30"));
326
327        let read = executor
328            .execute(
329                call("read_background_process", json!({"process_id": "bg-1"})),
330                ToolExecutionContext::default(),
331            )
332            .await
333            .expect("read");
334        let body = text(&read);
335        assert!(body.contains("bg-1 running pid 42"));
336        assert!(body.contains("stdout:\nready\n"));
337    }
338
339    #[tokio::test]
340    async fn stop_kills_a_running_process_and_names_an_unknown_id() {
341        let executor = StopBackgroundProcessExecutor {
342            control: Arc::new(FakeControl::running()),
343        };
344        let stopped = executor
345            .execute(
346                call("stop_background_process", json!({"process_id": "bg-1"})),
347                ToolExecutionContext::default(),
348            )
349            .await
350            .expect("stop");
351        assert_eq!(text(&stopped), "bg-1 killed");
352
353        let missing = executor
354            .execute(
355                call("stop_background_process", json!({"process_id": "bg-9"})),
356                ToolExecutionContext::default(),
357            )
358            .await
359            .expect("missing id is a tool result");
360        assert!(text(&missing).contains("No background process `bg-9`"));
361        assert!(text(&missing).contains("bg-1"));
362    }
363
364    #[test]
365    fn empty_list_says_nothing_is_retained() {
366        assert_eq!(format_list(&[]), "No background processes.");
367    }
368}