1use merry_core::ToolOutputStream;
10use merry_runtime::{
11 BackgroundProcessControl, BackgroundProcessId, BackgroundProcessLookupError,
12 BackgroundProcessOutput, BackgroundProcessState, BackgroundProcessStop,
13 BackgroundProcessSummary, ProcessActionIntent, ProcessExitStatus, ProcessOutputSink,
14 ProcessRunner, ProcessRunnerContext, ProcessRunnerError, ProcessRunnerFuture,
15 ProcessRunnerOutput,
16};
17use std::{
18 sync::{
19 Arc, Mutex,
20 atomic::{AtomicU64, Ordering},
21 },
22 time::Duration,
23};
24use tokio::sync::Notify;
25
26const BACKGROUND_SETTLE: Duration = Duration::from_secs(1);
28
29#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct CallbackProcessRequest {
32 pub request_id: String,
34 pub summary: String,
36 pub argv: Vec<String>,
38 pub cwd: Option<String>,
40 pub stdin_text: Option<String>,
42 pub stdout_limit_bytes: u64,
44 pub stderr_limit_bytes: u64,
46 pub display_name: Option<String>,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum CallbackProcessTerminalStatus {
57 Exited {
59 code: i32,
61 },
62 Cancelled,
64 FailedToStart,
66 DomainFailed,
68}
69
70impl From<CallbackProcessTerminalStatus> for ProcessExitStatus {
71 fn from(status: CallbackProcessTerminalStatus) -> Self {
72 match status {
73 CallbackProcessTerminalStatus::Exited { code } => Self::Exited(code),
74 CallbackProcessTerminalStatus::Cancelled => Self::Cancelled,
75 CallbackProcessTerminalStatus::FailedToStart => Self::FailedToStart,
76 CallbackProcessTerminalStatus::DomainFailed => Self::DomainFailed,
77 }
78 }
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct CallbackProcessOutput {
88 pub status: CallbackProcessTerminalStatus,
90 pub stdout: Vec<u8>,
92 pub stdout_truncated: bool,
94 pub stderr: Vec<u8>,
96 pub stderr_truncated: bool,
98}
99
100pub trait CallbackProcessExecutor: Send + Sync {
102 fn start(&self, request: CallbackProcessRequest, responder: CallbackProcessResponder);
106
107 fn cancel(&self, request_id: String);
110}
111
112#[derive(Debug, Clone)]
113struct BoundedCapture {
114 bytes: Vec<u8>,
115 limit: usize,
116 truncated: bool,
117}
118
119impl BoundedCapture {
120 fn new(limit: usize) -> Self {
121 Self {
122 bytes: Vec::new(),
123 limit,
124 truncated: false,
125 }
126 }
127
128 fn append(&mut self, chunk: &[u8]) {
129 if chunk.is_empty() {
130 return;
131 }
132 let remaining = self.limit.saturating_sub(self.bytes.len());
133 if remaining == 0 {
134 self.truncated = true;
135 return;
136 }
137 if chunk.len() > remaining {
138 self.bytes.extend_from_slice(&chunk[..remaining]);
139 self.truncated = true;
140 } else {
141 self.bytes.extend_from_slice(chunk);
142 }
143 }
144
145 fn apply_final(&mut self, final_bytes: Vec<u8>, host_truncated: bool) {
146 if !final_bytes.is_empty() {
147 self.bytes.clear();
148 self.truncated = host_truncated;
149 self.append(&final_bytes);
150 } else if host_truncated {
151 self.truncated = true;
152 }
153 }
154}
155
156struct SlotState {
157 stdout: BoundedCapture,
158 stderr: BoundedCapture,
159 live_sink: Option<ProcessOutputSink>,
160 terminal: Option<Result<CallbackProcessTerminalStatus, ProcessRunnerError>>,
161 killed_by_supervisor: bool,
162}
163
164struct ExecutionSlot {
165 request_id: String,
166 state: Mutex<SlotState>,
167 completed: Notify,
168}
169
170impl ExecutionSlot {
171 fn new(
172 request_id: String,
173 stdout_limit: usize,
174 stderr_limit: usize,
175 live_sink: Option<ProcessOutputSink>,
176 ) -> Self {
177 Self {
178 request_id,
179 state: Mutex::new(SlotState {
180 stdout: BoundedCapture::new(stdout_limit),
181 stderr: BoundedCapture::new(stderr_limit),
182 live_sink,
183 terminal: None,
184 killed_by_supervisor: false,
185 }),
186 completed: Notify::new(),
187 }
188 }
189
190 fn emit_output(&self, stream: ToolOutputStream, bytes: &[u8]) {
191 if bytes.is_empty() {
192 return;
193 }
194 let sink = {
195 let mut guard = self
196 .state
197 .lock()
198 .unwrap_or_else(|poison| poison.into_inner());
199 if guard.terminal.is_some() {
200 return;
201 }
202 match stream {
203 ToolOutputStream::Stdout => guard.stdout.append(bytes),
204 ToolOutputStream::Stderr => guard.stderr.append(bytes),
205 }
206 guard.live_sink.clone()
207 };
208 if let Some(sink) = sink {
209 sink.emit(stream, bytes);
210 }
211 }
212
213 fn settle_output(&self, output: CallbackProcessOutput) {
214 let mut guard = self
215 .state
216 .lock()
217 .unwrap_or_else(|poison| poison.into_inner());
218 if guard.terminal.is_some() {
219 return;
220 }
221 guard
222 .stdout
223 .apply_final(output.stdout, output.stdout_truncated);
224 guard
225 .stderr
226 .apply_final(output.stderr, output.stderr_truncated);
227 guard.live_sink = None;
228 guard.terminal = Some(Ok(output.status));
229 drop(guard);
230 self.completed.notify_waiters();
231 }
232
233 fn settle_error(&self, error: ProcessRunnerError) {
234 let mut guard = self
235 .state
236 .lock()
237 .unwrap_or_else(|poison| poison.into_inner());
238 if guard.terminal.is_some() {
239 return;
240 }
241 guard.live_sink = None;
242 guard.terminal = Some(Err(error));
243 drop(guard);
244 self.completed.notify_waiters();
245 }
246
247 async fn wait_until_settled(&self) {
248 loop {
249 let notified = self.completed.notified();
250 tokio::pin!(notified);
251 notified.as_mut().enable();
252 if self
253 .state
254 .lock()
255 .unwrap_or_else(|poison| poison.into_inner())
256 .terminal
257 .is_some()
258 {
259 return;
260 }
261 notified.await;
262 }
263 }
264
265 fn snapshot_terminal(&self) -> Option<Result<ProcessRunnerOutputParts, ProcessRunnerError>> {
266 let guard = self
267 .state
268 .lock()
269 .unwrap_or_else(|poison| poison.into_inner());
270 let terminal = guard.terminal.as_ref()?;
271 match terminal {
272 Ok(status) => Some(Ok(ProcessRunnerOutputParts {
273 status: ProcessExitStatus::from(*status),
274 stdout: guard.stdout.bytes.clone(),
275 stdout_truncated: guard.stdout.truncated,
276 stderr: guard.stderr.bytes.clone(),
277 stderr_truncated: guard.stderr.truncated,
278 })),
279 Err(error) => Some(Err(error.clone())),
280 }
281 }
282
283 fn snapshot_running_capture(&self) -> (Vec<u8>, bool, Vec<u8>, bool) {
284 let guard = self
285 .state
286 .lock()
287 .unwrap_or_else(|poison| poison.into_inner());
288 (
289 guard.stdout.bytes.clone(),
290 guard.stdout.truncated,
291 guard.stderr.bytes.clone(),
292 guard.stderr.truncated,
293 )
294 }
295
296 fn background_state(&self) -> BackgroundProcessState {
297 let guard = self
298 .state
299 .lock()
300 .unwrap_or_else(|poison| poison.into_inner());
301 if guard.killed_by_supervisor {
302 return BackgroundProcessState::Killed;
303 }
304 match guard.terminal.as_ref() {
305 None => BackgroundProcessState::Running { pid: 0 },
306 Some(Ok(CallbackProcessTerminalStatus::Exited { code })) => {
307 BackgroundProcessState::Exited { code: *code }
308 }
309 Some(Ok(CallbackProcessTerminalStatus::Cancelled)) => BackgroundProcessState::Killed,
310 Some(Ok(
311 CallbackProcessTerminalStatus::FailedToStart
312 | CallbackProcessTerminalStatus::DomainFailed,
313 ))
314 | Some(Err(_)) => BackgroundProcessState::Exited { code: -1 },
315 }
316 }
317
318 fn mark_killed_if_running(&self) -> bool {
319 let mut guard = self
320 .state
321 .lock()
322 .unwrap_or_else(|poison| poison.into_inner());
323 if guard.killed_by_supervisor || guard.terminal.is_some() {
324 return false;
325 }
326 guard.killed_by_supervisor = true;
327 guard.live_sink = None;
328 guard.terminal = Some(Ok(CallbackProcessTerminalStatus::Cancelled));
329 drop(guard);
330 self.completed.notify_waiters();
331 true
332 }
333}
334
335struct ProcessRunnerOutputParts {
336 status: ProcessExitStatus,
337 stdout: Vec<u8>,
338 stdout_truncated: bool,
339 stderr: Vec<u8>,
340 stderr_truncated: bool,
341}
342
343pub struct CallbackProcessResponder {
348 slot: Arc<ExecutionSlot>,
349}
350
351impl CallbackProcessResponder {
352 fn new(slot: Arc<ExecutionSlot>) -> Self {
353 Self { slot }
354 }
355
356 pub fn emit_output(&self, stream: ToolOutputStream, bytes: &[u8]) {
358 self.slot.emit_output(stream, bytes);
359 }
360
361 pub fn complete(&self, output: CallbackProcessOutput) {
363 self.slot.settle_output(output);
364 }
365
366 pub fn fail(&self, message: impl Into<String>) {
368 self.slot
369 .settle_error(ProcessRunnerError::infrastructure(message.into()));
370 }
371
372 pub fn cancel(&self) {
374 self.slot.settle_error(ProcessRunnerError::Cancelled);
375 }
376}
377
378impl Drop for CallbackProcessResponder {
379 fn drop(&mut self) {
380 self.slot.settle_error(ProcessRunnerError::infrastructure(
381 "host process runner dropped responder without completing",
382 ));
383 }
384}
385
386struct RetainedCallbackProcess {
387 id: BackgroundProcessId,
388 display_name: Option<String>,
389 command: String,
390 cwd: Option<String>,
391 slot: Arc<ExecutionSlot>,
392}
393
394impl RetainedCallbackProcess {
395 fn summary(&self) -> BackgroundProcessSummary {
396 BackgroundProcessSummary::new(
397 self.id.clone(),
398 self.command.clone(),
399 self.cwd.clone(),
400 self.slot.background_state(),
401 )
402 .with_display_name(self.display_name.clone())
403 }
404}
405
406struct CallbackBackgroundSupervisorInner {
407 executor: Arc<dyn CallbackProcessExecutor>,
408 next_id: AtomicU64,
409 processes: Mutex<Vec<RetainedCallbackProcess>>,
410}
411
412impl Drop for CallbackBackgroundSupervisorInner {
413 fn drop(&mut self) {
414 let processes = std::mem::take(
415 self.processes
416 .get_mut()
417 .unwrap_or_else(|poison| poison.into_inner()),
418 );
419 for process in processes {
420 if process.slot.mark_killed_if_running() {
421 self.executor.cancel(process.slot.request_id.clone());
422 }
423 }
424 }
425}
426
427#[derive(Clone)]
429pub struct CallbackBackgroundSupervisor {
430 inner: Arc<CallbackBackgroundSupervisorInner>,
431}
432
433impl CallbackBackgroundSupervisor {
434 fn new(executor: Arc<dyn CallbackProcessExecutor>) -> Self {
435 Self {
436 inner: Arc::new(CallbackBackgroundSupervisorInner {
437 executor,
438 next_id: AtomicU64::new(0),
439 processes: Mutex::new(Vec::new()),
440 }),
441 }
442 }
443
444 fn retain(
445 &self,
446 intent: &ProcessActionIntent,
447 explicit_background: bool,
448 slot: Arc<ExecutionSlot>,
449 ) -> BackgroundProcessId {
450 let number = self.inner.next_id.fetch_add(1, Ordering::Relaxed) + 1;
451 let prefix = if explicit_background { "bg" } else { "proc" };
452 let id = BackgroundProcessId::new(format!("{prefix}-{number}"))
453 .expect("minted host background process id is valid");
454 let entry = RetainedCallbackProcess {
455 id: id.clone(),
456 display_name: intent.display_name().map(str::to_owned),
457 command: intent.summary().to_owned(),
458 cwd: intent.cwd().map(str::to_owned),
459 slot,
460 };
461 let mut processes = self
462 .inner
463 .processes
464 .lock()
465 .unwrap_or_else(|poison| poison.into_inner());
466 processes.push(entry);
467 id
468 }
469}
470
471impl BackgroundProcessControl for CallbackBackgroundSupervisor {
472 fn list(&self) -> Vec<BackgroundProcessSummary> {
473 let processes = self
474 .inner
475 .processes
476 .lock()
477 .unwrap_or_else(|poison| poison.into_inner());
478 processes
479 .iter()
480 .map(RetainedCallbackProcess::summary)
481 .collect()
482 }
483
484 fn read(
485 &self,
486 id: &BackgroundProcessId,
487 ) -> Result<BackgroundProcessOutput, BackgroundProcessLookupError> {
488 let processes = self
489 .inner
490 .processes
491 .lock()
492 .unwrap_or_else(|poison| poison.into_inner());
493 let Some(process) = processes.iter().find(|item| item.id == *id) else {
494 let known = processes.iter().map(|item| item.id.clone()).collect();
495 return Err(BackgroundProcessLookupError::new(id.clone(), known));
496 };
497 let summary = process.summary();
498 let (stdout, stdout_truncated, stderr, stderr_truncated) =
499 process.slot.snapshot_running_capture();
500 Ok(BackgroundProcessOutput::new(
501 summary,
502 String::from_utf8_lossy(&stdout),
503 String::from_utf8_lossy(&stderr),
504 stdout_truncated,
505 stderr_truncated,
506 ))
507 }
508
509 fn stop(
510 &self,
511 id: &BackgroundProcessId,
512 ) -> Result<BackgroundProcessStop, BackgroundProcessLookupError> {
513 let (summary, cancel_request_id) = {
514 let processes = self
515 .inner
516 .processes
517 .lock()
518 .unwrap_or_else(|poison| poison.into_inner());
519 let Some(process) = processes.iter().find(|item| item.id == *id) else {
520 let known = processes.iter().map(|item| item.id.clone()).collect();
521 return Err(BackgroundProcessLookupError::new(id.clone(), known));
522 };
523 let changed = process.slot.mark_killed_if_running();
524 let cancel_id = changed.then(|| process.slot.request_id.clone());
525 (process.summary(), cancel_id)
526 };
527 let changed = cancel_request_id.is_some();
528 if let Some(request_id) = cancel_request_id {
529 self.inner.executor.cancel(request_id);
530 }
531 Ok(BackgroundProcessStop::new(summary, changed))
532 }
533}
534
535pub struct CallbackProcessRunner {
538 executor: Arc<dyn CallbackProcessExecutor>,
539 supervisor: Arc<CallbackBackgroundSupervisor>,
540 next_request_id: AtomicU64,
541}
542
543impl CallbackProcessRunner {
544 #[must_use]
547 pub fn new(executor: Arc<dyn CallbackProcessExecutor>) -> Self {
548 let supervisor = Arc::new(CallbackBackgroundSupervisor::new(Arc::clone(&executor)));
549 Self {
550 executor,
551 supervisor,
552 next_request_id: AtomicU64::new(0),
553 }
554 }
555
556 fn mint_request_id(&self) -> String {
557 let seq = self.next_request_id.fetch_add(1, Ordering::Relaxed) + 1;
558 format!("host-proc-{seq}")
559 }
560}
561
562struct ForegroundCancelGuard {
563 executor: Arc<dyn CallbackProcessExecutor>,
564 slot: Arc<ExecutionSlot>,
565 armed: bool,
566}
567
568impl ForegroundCancelGuard {
569 fn new(executor: Arc<dyn CallbackProcessExecutor>, slot: Arc<ExecutionSlot>) -> Self {
570 Self {
571 executor,
572 slot,
573 armed: true,
574 }
575 }
576
577 fn disarm(&mut self) {
578 self.armed = false;
579 }
580}
581
582impl Drop for ForegroundCancelGuard {
583 fn drop(&mut self) {
584 if self.armed && self.slot.mark_killed_if_running() {
585 self.executor.cancel(self.slot.request_id.clone());
586 }
587 }
588}
589
590impl ProcessRunner for CallbackProcessRunner {
591 fn run<'a>(
592 &'a self,
593 intent: ProcessActionIntent,
594 context: ProcessRunnerContext,
595 ) -> ProcessRunnerFuture<'a> {
596 Box::pin(async move {
597 let request_id = self.mint_request_id();
598 let slot = Arc::new(ExecutionSlot::new(
599 request_id.clone(),
600 intent.stdout_limit_bytes(),
601 intent.stderr_limit_bytes(),
602 context.output_sink().cloned(),
603 ));
604 let request = CallbackProcessRequest {
605 request_id: request_id.clone(),
606 summary: intent.summary().to_owned(),
607 argv: intent.argv().to_vec(),
608 cwd: intent.cwd().map(str::to_owned),
609 stdin_text: intent.stdin_text().map(str::to_owned),
610 stdout_limit_bytes: u64::try_from(intent.stdout_limit_bytes()).unwrap_or(u64::MAX),
611 stderr_limit_bytes: u64::try_from(intent.stderr_limit_bytes()).unwrap_or(u64::MAX),
612 display_name: intent.display_name().map(str::to_owned),
613 };
614 let responder = CallbackProcessResponder::new(Arc::clone(&slot));
615 self.executor.start(request, responder);
616 let mut cancel_guard =
617 ForegroundCancelGuard::new(Arc::clone(&self.executor), Arc::clone(&slot));
618
619 let explicit_background = intent.background();
620 let wait_timeout_secs =
621 (!explicit_background).then(|| intent.effective_wait_timeout_secs());
622 let wait_window = match wait_timeout_secs {
623 Some(secs) => Duration::from_secs(secs),
624 None => BACKGROUND_SETTLE,
625 };
626
627 let timed_out = tokio::select! {
628 biased;
629 _ = context.cancellation_token().cancelled() => {
630 cancel_guard.disarm();
631 if slot.mark_killed_if_running() {
632 self.executor.cancel(request_id);
633 }
634 return Err(ProcessRunnerError::Cancelled);
635 }
636 _ = slot.wait_until_settled() => false,
637 _ = tokio::time::sleep(wait_window) => true,
638 };
639
640 if !timed_out {
641 cancel_guard.disarm();
642 let parts = slot.snapshot_terminal().unwrap_or_else(|| {
643 Err(ProcessRunnerError::infrastructure(
644 "host process execution settled without terminal state",
645 ))
646 })?;
647 return ProcessRunnerOutput::from_bytes(
648 &intent,
649 parts.status,
650 parts.stdout,
651 parts.stdout_truncated,
652 parts.stderr,
653 parts.stderr_truncated,
654 )
655 .map_err(|err| ProcessRunnerError::infrastructure(err.to_string()));
656 }
657
658 let bg_id = self
661 .supervisor
662 .retain(&intent, explicit_background, Arc::clone(&slot));
663 cancel_guard.disarm();
664 let (stdout, stdout_truncated, stderr, stderr_truncated) =
665 slot.snapshot_running_capture();
666 let mut output = ProcessRunnerOutput::from_bytes(
667 &intent,
668 ProcessExitStatus::Running,
669 stdout,
670 stdout_truncated,
671 stderr,
672 stderr_truncated,
673 )
674 .map_err(|err| ProcessRunnerError::infrastructure(err.to_string()))?
675 .with_background_process_id(bg_id);
676 if let Some(secs) = wait_timeout_secs {
677 output = output.with_wait_timed_out_secs(secs);
678 }
679 Ok(output)
680 })
681 }
682
683 fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
684 Some(Arc::clone(&self.supervisor) as Arc<dyn BackgroundProcessControl>)
685 }
686}
687
688#[cfg(test)]
689#[path = "callback_runner_tests.rs"]
690mod tests;