1use super::validation::{
2 ProcessActionError, summarize_intent, validate_argv, validate_captured_bytes, validate_cwd,
3 validate_output_limit, validate_stdin_text, validate_timeout_secs,
4};
5use super::{BackgroundProcessControl, BackgroundProcessId};
6use crate::{PermissionRequest, RequestedCapability};
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8use std::{fmt, future::Future, pin::Pin, sync::Arc};
9use thiserror::Error;
10use tokio_util::sync::CancellationToken;
11
12pub const MAX_PROCESS_ARG_BYTES: usize = 4096;
14pub const MAX_PROCESS_ARGV_ITEMS: usize = 256;
16pub const MAX_PROCESS_CWD_BYTES: usize = 4096;
18pub const MAX_PROCESS_STDIN_TEXT_BYTES: usize = 64 * 1024;
20pub const MAX_PROCESS_OUTPUT_LIMIT_BYTES: usize = 1024 * 1024;
22pub const DEFAULT_PROCESS_WAIT_TIMEOUT_SECS: u64 = 120;
24pub const MAX_PROCESS_WAIT_TIMEOUT_SECS: u64 = 3600;
26
27#[non_exhaustive]
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum ProcessEnvPolicy {
37 #[default]
39 Empty,
40 #[cfg(test)]
42 NonEmptyForTest,
43}
44
45impl ProcessEnvPolicy {
46 #[must_use]
48 pub const fn empty() -> Self {
49 Self::Empty
50 }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct AcceptedLocalWorkspaceProcessAdmission {
66 sandbox_profile: LocalWorkspaceProcessSandboxProfile,
67 permission_profile_id: ProcessPermissionProfileId,
68}
69
70impl AcceptedLocalWorkspaceProcessAdmission {
71 #[must_use]
77 pub const fn accept_local_workspace() -> Self {
78 Self {
79 sandbox_profile: LocalWorkspaceProcessSandboxProfile::LocalWorkspace,
80 permission_profile_id: ProcessPermissionProfileId::LOCAL_WORKSPACE,
81 }
82 }
83
84 #[must_use]
91 pub const fn accept_host() -> Self {
92 Self {
93 sandbox_profile: LocalWorkspaceProcessSandboxProfile::Host,
94 permission_profile_id: ProcessPermissionProfileId::LOCAL_WORKSPACE_HOST,
95 }
96 }
97
98 #[cfg(test)]
99 pub(crate) const fn for_test_permission_profile_id(
100 permission_profile_id: ProcessPermissionProfileId,
101 ) -> Self {
102 Self {
103 sandbox_profile: LocalWorkspaceProcessSandboxProfile::LocalWorkspace,
104 permission_profile_id,
105 }
106 }
107
108 #[must_use]
110 pub const fn sandbox_profile(self) -> LocalWorkspaceProcessSandboxProfile {
111 self.sandbox_profile
112 }
113
114 #[must_use]
116 pub const fn permission_profile_id(self) -> ProcessPermissionProfileId {
117 self.permission_profile_id
118 }
119}
120
121#[non_exhaustive]
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum LocalWorkspaceProcessSandboxProfile {
125 LocalWorkspace,
127 Host,
129}
130
131impl LocalWorkspaceProcessSandboxProfile {
132 #[must_use]
134 pub const fn as_str(self) -> &'static str {
135 match self {
136 Self::LocalWorkspace => "local-workspace",
137 Self::Host => "host",
138 }
139 }
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
148pub struct ProcessPermissionProfileId(&'static str);
149
150impl ProcessPermissionProfileId {
151 pub const READ_ONLY: Self = Self("process.read_only");
153 pub const LOCAL_WORKSPACE: Self = Self("process.local_workspace");
155 pub const LOCAL_WORKSPACE_HOST: Self = Self("process.local_workspace.host");
157 pub const SHELL_READ_ONLY: Self = Self("process.shell.read_only");
159 pub const APPROVED_PERMISSION_REQUEST: Self = Self("process.permission_request.approved");
161
162 #[must_use]
164 pub const fn as_str(self) -> &'static str {
165 self.0
166 }
167}
168
169impl Serialize for ProcessPermissionProfileId {
170 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
171 where
172 S: Serializer,
173 {
174 serializer.serialize_str((*self).as_str())
175 }
176}
177
178impl<'de> Deserialize<'de> for ProcessPermissionProfileId {
179 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
180 where
181 D: Deserializer<'de>,
182 {
183 let value = String::deserialize(deserializer)?;
184 match value.as_str() {
185 "process.read_only" => Ok(Self::READ_ONLY),
186 "process.local_workspace" => Ok(Self::LOCAL_WORKSPACE),
187 "process.local_workspace.host" => Ok(Self::LOCAL_WORKSPACE_HOST),
188 "process.shell.read_only" => Ok(Self::SHELL_READ_ONLY),
189 "process.permission_request.approved" => Ok(Self::APPROVED_PERMISSION_REQUEST),
190 _ => Err(serde::de::Error::custom(format!(
191 "unsupported process permission profile id `{value}`"
192 ))),
193 }
194 }
195}
196
197impl fmt::Display for ProcessPermissionProfileId {
198 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
199 formatter.write_str(self.as_str())
200 }
201}
202
203pub type ProcessRunnerFuture<'a> = Pin<Box<dyn Future<Output = ProcessRunnerResult> + Send + 'a>>;
208
209pub type ProcessRunnerResult = Result<ProcessRunnerOutput, ProcessRunnerError>;
211
212#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct ProcessOutputChunk {
215 pub call_id: merry_core::ToolCallId,
217 pub stream: merry_core::ToolOutputStream,
219 pub delta: String,
221}
222
223#[derive(Debug, Clone)]
225pub struct ProcessOutputSink {
226 call_id: merry_core::ToolCallId,
227 sender: tokio::sync::mpsc::Sender<ProcessOutputChunk>,
228}
229
230impl ProcessOutputSink {
231 #[must_use]
233 pub fn new(
234 call_id: merry_core::ToolCallId,
235 sender: tokio::sync::mpsc::Sender<ProcessOutputChunk>,
236 ) -> Self {
237 Self { call_id, sender }
238 }
239
240 pub fn emit(&self, stream: merry_core::ToolOutputStream, bytes: &[u8]) {
242 if bytes.is_empty() {
243 return;
244 }
245 const MAX_LIVE_CHUNK_BYTES: usize = 4096;
246 let slice = &bytes[..bytes.len().min(MAX_LIVE_CHUNK_BYTES)];
247 let delta = String::from_utf8_lossy(slice).into_owned();
248 let _ = self.sender.try_send(ProcessOutputChunk {
249 call_id: self.call_id.clone(),
250 stream,
251 delta,
252 });
253 }
254}
255
256#[derive(Debug, Clone)]
258pub struct ProcessRunnerContext {
259 cancellation_token: CancellationToken,
260 output_sink: Option<ProcessOutputSink>,
261}
262
263impl ProcessRunnerContext {
264 #[must_use]
266 pub fn new(cancellation_token: CancellationToken) -> Self {
267 Self {
268 cancellation_token,
269 output_sink: None,
270 }
271 }
272
273 #[must_use]
275 pub fn with_output_sink(mut self, sink: ProcessOutputSink) -> Self {
276 self.output_sink = Some(sink);
277 self
278 }
279
280 #[must_use]
282 pub fn cancellation_token(&self) -> &CancellationToken {
283 &self.cancellation_token
284 }
285
286 #[must_use]
288 pub fn output_sink(&self) -> Option<&ProcessOutputSink> {
289 self.output_sink.as_ref()
290 }
291}
292
293pub trait ProcessRunner: Send + Sync {
299 fn run<'a>(
301 &'a self,
302 intent: ProcessActionIntent,
303 context: ProcessRunnerContext,
304 ) -> ProcessRunnerFuture<'a>;
305
306 fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
310 None
311 }
312}
313
314pub trait PermissionedProcessRunnerFactory: Send + Sync {
322 fn validate_request(&self, _request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
330 Ok(())
331 }
332
333 fn request_capabilities_are_satisfied(
341 &self,
342 _request: &PermissionRequest,
343 ) -> Result<bool, ProcessRunnerError> {
344 Ok(false)
345 }
346
347 fn prepare_approved_request(
351 &self,
352 request: &PermissionRequest,
353 ) -> Result<super::PreparedProcessPermission, ProcessRunnerError> {
354 self.validate_request(request)?;
355 Ok(super::PreparedProcessPermission::new(
356 self.runner_for(request),
357 Vec::new(),
358 ))
359 }
360
361 fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner>;
364}
365
366#[derive(Clone)]
368pub struct StaticPermissionedProcessRunnerFactory {
369 runner: Arc<dyn ProcessRunner>,
370}
371
372impl StaticPermissionedProcessRunnerFactory {
373 #[must_use]
375 pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
376 Self { runner }
377 }
378}
379
380impl PermissionedProcessRunnerFactory for StaticPermissionedProcessRunnerFactory {
381 fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
382 if request
383 .requested()
384 .iter()
385 .any(|capability| matches!(capability, RequestedCapability::Path(_)))
386 {
387 return Err(ProcessRunnerError::infrastructure(
388 "static permissioned process runner cannot enforce requested path capabilities",
389 ));
390 }
391 if request
392 .requested()
393 .iter()
394 .any(|capability| matches!(capability, RequestedCapability::HostIntegration(_)))
395 {
396 return Err(ProcessRunnerError::infrastructure(
397 "static permissioned process runner cannot enforce requested host integrations",
398 ));
399 }
400 Ok(())
401 }
402
403 fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
404 Arc::clone(&self.runner)
405 }
406}
407
408#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
414#[serde(deny_unknown_fields)]
415pub struct ProcessActionIntent {
416 summary: String,
417 argv: Vec<String>,
418 cwd: Option<String>,
419 env_policy: ProcessEnvPolicy,
420 stdin_text: Option<String>,
421 stdout_limit_bytes: usize,
422 stderr_limit_bytes: usize,
423 #[serde(default)]
424 background: bool,
425 #[serde(default, skip_serializing_if = "Option::is_none")]
426 timeout_secs: Option<u64>,
427 #[serde(default, skip_serializing_if = "Option::is_none")]
428 display_name: Option<String>,
429}
430
431impl ProcessActionIntent {
432 pub fn new(
434 argv: Vec<String>,
435 cwd: Option<String>,
436 env_policy: ProcessEnvPolicy,
437 stdin_text: Option<String>,
438 stdout_limit_bytes: usize,
439 stderr_limit_bytes: usize,
440 ) -> Result<Self, ProcessActionError> {
441 validate_argv(&argv)?;
442 let cwd = validate_cwd(cwd)?;
443 validate_stdin_text(stdin_text.as_deref())?;
444 validate_output_limit("stdout_limit_bytes", stdout_limit_bytes)?;
445 validate_output_limit("stderr_limit_bytes", stderr_limit_bytes)?;
446 let summary = summarize_intent(&argv, cwd.as_deref());
447
448 Ok(Self {
449 summary,
450 argv,
451 cwd,
452 env_policy,
453 stdin_text,
454 stdout_limit_bytes,
455 stderr_limit_bytes,
456 background: false,
457 timeout_secs: None,
458 display_name: None,
459 })
460 }
461
462 #[must_use]
467 pub fn with_background(mut self, background: bool) -> Self {
468 self.background = background;
469 self
470 }
471
472 pub fn with_timeout_secs(
478 mut self,
479 timeout_secs: Option<u64>,
480 ) -> Result<Self, ProcessActionError> {
481 self.timeout_secs = validate_timeout_secs(timeout_secs)?;
482 Ok(self)
483 }
484
485 #[must_use]
487 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
488 self.display_name = display_name.and_then(|value| {
489 let normalized = value.split_whitespace().collect::<Vec<_>>().join(" ");
490 if normalized.is_empty() {
491 None
492 } else {
493 Some(normalized.chars().take(80).collect())
494 }
495 });
496 self
497 }
498
499 #[must_use]
501 pub fn summary(&self) -> &str {
502 &self.summary
503 }
504
505 #[must_use]
507 pub fn argv(&self) -> &[String] {
508 &self.argv
509 }
510
511 #[must_use]
513 pub fn cwd(&self) -> Option<&str> {
514 self.cwd.as_deref()
515 }
516
517 #[must_use]
519 pub const fn env_policy(&self) -> ProcessEnvPolicy {
520 self.env_policy
521 }
522
523 #[must_use]
525 pub fn stdin_text(&self) -> Option<&str> {
526 self.stdin_text.as_deref()
527 }
528
529 #[must_use]
531 pub const fn background(&self) -> bool {
532 self.background
533 }
534
535 #[must_use]
537 pub const fn timeout_secs(&self) -> Option<u64> {
538 self.timeout_secs
539 }
540
541 #[must_use]
543 pub const fn effective_wait_timeout_secs(&self) -> u64 {
544 match self.timeout_secs {
545 Some(secs) => secs,
546 None => DEFAULT_PROCESS_WAIT_TIMEOUT_SECS,
547 }
548 }
549
550 #[must_use]
552 pub fn display_name(&self) -> Option<&str> {
553 self.display_name.as_deref()
554 }
555
556 #[must_use]
558 pub const fn stdout_limit_bytes(&self) -> usize {
559 self.stdout_limit_bytes
560 }
561
562 #[must_use]
564 pub const fn stderr_limit_bytes(&self) -> usize {
565 self.stderr_limit_bytes
566 }
567}
568
569#[derive(Debug, Clone, PartialEq, Eq)]
577pub struct ProcessRunnerOutput {
578 status: ProcessExitStatus,
579 stdout_data: Vec<u8>,
580 stdout_text: String,
581 stdout_bytes: usize,
582 stdout_truncated: bool,
583 stderr_data: Vec<u8>,
584 stderr_text: String,
585 stderr_bytes: usize,
586 stderr_truncated: bool,
587 running_pid: Option<u32>,
588 background_process_id: Option<BackgroundProcessId>,
589 wait_timed_out_secs: Option<u64>,
590}
591
592impl ProcessRunnerOutput {
593 pub fn new(
595 intent: &ProcessActionIntent,
596 status: ProcessExitStatus,
597 stdout_text: impl Into<String>,
598 stdout_truncated: bool,
599 stderr_text: impl Into<String>,
600 stderr_truncated: bool,
601 ) -> Result<Self, ProcessActionError> {
602 Self::from_bytes(
603 intent,
604 status,
605 stdout_text.into().into_bytes(),
606 stdout_truncated,
607 stderr_text.into().into_bytes(),
608 stderr_truncated,
609 )
610 }
611
612 pub fn from_bytes(
614 intent: &ProcessActionIntent,
615 status: ProcessExitStatus,
616 stdout_data: Vec<u8>,
617 stdout_truncated: bool,
618 stderr_data: Vec<u8>,
619 stderr_truncated: bool,
620 ) -> Result<Self, ProcessActionError> {
621 validate_captured_bytes(
622 "stdout_bytes",
623 stdout_data.len(),
624 intent.stdout_limit_bytes(),
625 )?;
626 validate_captured_bytes(
627 "stderr_bytes",
628 stderr_data.len(),
629 intent.stderr_limit_bytes(),
630 )?;
631
632 Ok(Self {
633 status,
634 stdout_text: String::from_utf8_lossy(&stdout_data).into_owned(),
635 stdout_bytes: stdout_data.len(),
636 stdout_data,
637 stdout_truncated,
638 stderr_text: String::from_utf8_lossy(&stderr_data).into_owned(),
639 stderr_bytes: stderr_data.len(),
640 stderr_data,
641 stderr_truncated,
642 running_pid: None,
643 background_process_id: None,
644 wait_timed_out_secs: None,
645 })
646 }
647
648 #[must_use]
650 pub fn with_running_pid(mut self, pid: u32) -> Self {
651 self.running_pid = Some(pid);
652 self
653 }
654
655 #[must_use]
657 pub fn with_background_process_id(mut self, id: BackgroundProcessId) -> Self {
658 self.background_process_id = Some(id);
659 self
660 }
661
662 #[must_use]
665 pub fn with_wait_timed_out_secs(mut self, secs: u64) -> Self {
666 self.wait_timed_out_secs = Some(secs);
667 self
668 }
669
670 #[must_use]
672 pub const fn status(&self) -> ProcessExitStatus {
673 self.status
674 }
675
676 #[must_use]
678 pub fn stdout_text(&self) -> &str {
679 &self.stdout_text
680 }
681
682 #[must_use]
684 pub fn stdout_data(&self) -> &[u8] {
685 &self.stdout_data
686 }
687
688 #[must_use]
690 pub fn stdout_is_utf8(&self) -> bool {
691 std::str::from_utf8(&self.stdout_data).is_ok()
692 }
693
694 #[must_use]
696 pub const fn stdout_bytes(&self) -> usize {
697 self.stdout_bytes
698 }
699
700 #[must_use]
702 pub const fn stdout_truncated(&self) -> bool {
703 self.stdout_truncated
704 }
705
706 #[must_use]
708 pub fn stderr_text(&self) -> &str {
709 &self.stderr_text
710 }
711
712 #[must_use]
714 pub fn stderr_data(&self) -> &[u8] {
715 &self.stderr_data
716 }
717
718 #[must_use]
720 pub fn stderr_is_utf8(&self) -> bool {
721 std::str::from_utf8(&self.stderr_data).is_ok()
722 }
723
724 #[must_use]
726 pub const fn stderr_bytes(&self) -> usize {
727 self.stderr_bytes
728 }
729
730 #[must_use]
732 pub const fn stderr_truncated(&self) -> bool {
733 self.stderr_truncated
734 }
735
736 #[must_use]
738 pub const fn running_pid(&self) -> Option<u32> {
739 self.running_pid
740 }
741
742 #[must_use]
744 pub fn background_process_id(&self) -> Option<&BackgroundProcessId> {
745 self.background_process_id.as_ref()
746 }
747
748 #[must_use]
751 pub const fn wait_timed_out_secs(&self) -> Option<u64> {
752 self.wait_timed_out_secs
753 }
754
755 #[must_use]
759 pub const fn ok(&self) -> bool {
760 matches!(
761 self.status,
762 ProcessExitStatus::Exited(0) | ProcessExitStatus::Running
763 )
764 }
765
766 pub fn execution_evidence(
768 &self,
769 intent: &ProcessActionIntent,
770 permission_profile_id: ProcessPermissionProfileId,
771 ) -> Result<ProcessExecutionEvidence, ProcessActionError> {
772 ProcessExecutionEvidence::new(
773 intent,
774 permission_profile_id,
775 self.status,
776 self.stdout_bytes,
777 self.stdout_truncated,
778 self.stderr_bytes,
779 self.stderr_truncated,
780 )
781 }
782}
783
784#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
786#[serde(rename_all = "snake_case")]
787pub enum ProcessExitStatus {
788 Exited(i32),
790 Cancelled,
792 FailedToStart,
794 DomainFailed,
796 Running,
800}
801
802impl ProcessExitStatus {
803 #[must_use]
805 pub const fn exit_code(self) -> Option<i32> {
806 match self {
807 Self::Exited(code) => Some(code),
808 Self::Cancelled | Self::FailedToStart | Self::DomainFailed | Self::Running => None,
809 }
810 }
811}
812
813#[derive(Debug, Clone, PartialEq, Eq, Error)]
815pub enum ProcessRunnerError {
816 #[error("process runner cancelled")]
818 Cancelled,
819
820 #[error("process runner infrastructure error: {message}")]
822 Infrastructure {
823 message: String,
825 },
826}
827
828impl ProcessRunnerError {
829 #[must_use]
831 pub fn infrastructure(message: impl Into<String>) -> Self {
832 Self::Infrastructure {
833 message: message.into(),
834 }
835 }
836}
837
838#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
844#[serde(deny_unknown_fields)]
845pub struct ProcessExecutionEvidence {
846 intent_summary: String,
847 argv: Vec<String>,
848 cwd: Option<String>,
849 permission_profile_id: ProcessPermissionProfileId,
850 status: ProcessExitStatus,
851 stdout_bytes: usize,
852 stdout_truncated: bool,
853 stderr_bytes: usize,
854 stderr_truncated: bool,
855}
856
857impl ProcessExecutionEvidence {
858 pub fn new(
860 intent: &ProcessActionIntent,
861 permission_profile_id: ProcessPermissionProfileId,
862 status: ProcessExitStatus,
863 stdout_bytes: usize,
864 stdout_truncated: bool,
865 stderr_bytes: usize,
866 stderr_truncated: bool,
867 ) -> Result<Self, ProcessActionError> {
868 validate_captured_bytes("stdout_bytes", stdout_bytes, intent.stdout_limit_bytes())?;
869 validate_captured_bytes("stderr_bytes", stderr_bytes, intent.stderr_limit_bytes())?;
870
871 Ok(Self {
872 intent_summary: intent.summary().to_owned(),
873 argv: intent.argv().to_vec(),
874 cwd: intent.cwd().map(str::to_owned),
875 permission_profile_id,
876 status,
877 stdout_bytes,
878 stdout_truncated,
879 stderr_bytes,
880 stderr_truncated,
881 })
882 }
883
884 #[must_use]
886 pub fn intent_summary(&self) -> &str {
887 &self.intent_summary
888 }
889
890 #[must_use]
892 pub fn argv(&self) -> &[String] {
893 &self.argv
894 }
895
896 #[must_use]
898 pub fn cwd(&self) -> Option<&str> {
899 self.cwd.as_deref()
900 }
901
902 #[must_use]
904 pub const fn permission_profile_id(&self) -> ProcessPermissionProfileId {
905 self.permission_profile_id
906 }
907
908 #[must_use]
910 pub const fn status(&self) -> ProcessExitStatus {
911 self.status
912 }
913
914 #[must_use]
916 pub const fn exit_code(&self) -> Option<i32> {
917 self.status.exit_code()
918 }
919
920 #[must_use]
922 pub const fn stdout_bytes(&self) -> usize {
923 self.stdout_bytes
924 }
925
926 #[must_use]
928 pub const fn stdout_truncated(&self) -> bool {
929 self.stdout_truncated
930 }
931
932 #[must_use]
934 pub const fn stderr_bytes(&self) -> usize {
935 self.stderr_bytes
936 }
937
938 #[must_use]
940 pub const fn stderr_truncated(&self) -> bool {
941 self.stderr_truncated
942 }
943
944 pub(crate) fn matches_intent(&self, intent: &ProcessActionIntent) -> bool {
945 self.intent_summary == intent.summary()
946 && self.argv == intent.argv()
947 && self.cwd.as_deref() == intent.cwd()
948 && self.stdout_bytes <= intent.stdout_limit_bytes()
949 && self.stderr_bytes <= intent.stderr_limit_bytes()
950 }
951}