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 = 64 * 1024;
17pub const MAX_PROCESS_ARGV_ITEMS: usize = 256;
19pub const MAX_PROCESS_CWD_BYTES: usize = 4096;
21pub const MAX_PROCESS_STDIN_TEXT_BYTES: usize = 64 * 1024;
23pub const MAX_PROCESS_OUTPUT_LIMIT_BYTES: usize = 1024 * 1024;
25pub const DEFAULT_PROCESS_WAIT_TIMEOUT_SECS: u64 = 120;
27pub const MAX_PROCESS_WAIT_TIMEOUT_SECS: u64 = 3600;
29
30#[non_exhaustive]
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39pub enum ProcessEnvPolicy {
40 #[default]
42 Empty,
43 #[cfg(test)]
45 NonEmptyForTest,
46}
47
48impl ProcessEnvPolicy {
49 #[must_use]
51 pub const fn empty() -> Self {
52 Self::Empty
53 }
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub struct AcceptedLocalWorkspaceProcessAdmission {
69 sandbox_profile: LocalWorkspaceProcessSandboxProfile,
70 permission_profile_id: ProcessPermissionProfileId,
71}
72
73impl AcceptedLocalWorkspaceProcessAdmission {
74 #[must_use]
80 pub const fn accept_local_workspace() -> Self {
81 Self {
82 sandbox_profile: LocalWorkspaceProcessSandboxProfile::LocalWorkspace,
83 permission_profile_id: ProcessPermissionProfileId::LOCAL_WORKSPACE,
84 }
85 }
86
87 #[must_use]
94 pub const fn accept_host() -> Self {
95 Self {
96 sandbox_profile: LocalWorkspaceProcessSandboxProfile::Host,
97 permission_profile_id: ProcessPermissionProfileId::LOCAL_WORKSPACE_HOST,
98 }
99 }
100
101 #[cfg(test)]
102 pub(crate) const fn for_test_permission_profile_id(
103 permission_profile_id: ProcessPermissionProfileId,
104 ) -> Self {
105 Self {
106 sandbox_profile: LocalWorkspaceProcessSandboxProfile::LocalWorkspace,
107 permission_profile_id,
108 }
109 }
110
111 #[must_use]
113 pub const fn sandbox_profile(self) -> LocalWorkspaceProcessSandboxProfile {
114 self.sandbox_profile
115 }
116
117 #[must_use]
119 pub const fn permission_profile_id(self) -> ProcessPermissionProfileId {
120 self.permission_profile_id
121 }
122}
123
124#[non_exhaustive]
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum LocalWorkspaceProcessSandboxProfile {
128 LocalWorkspace,
130 Host,
132}
133
134impl LocalWorkspaceProcessSandboxProfile {
135 #[must_use]
137 pub const fn as_str(self) -> &'static str {
138 match self {
139 Self::LocalWorkspace => "local-workspace",
140 Self::Host => "host",
141 }
142 }
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
151pub struct ProcessPermissionProfileId(&'static str);
152
153impl ProcessPermissionProfileId {
154 pub const READ_ONLY: Self = Self("process.read_only");
156 pub const LOCAL_WORKSPACE: Self = Self("process.local_workspace");
158 pub const LOCAL_WORKSPACE_HOST: Self = Self("process.local_workspace.host");
160 pub const SHELL_READ_ONLY: Self = Self("process.shell.read_only");
162 pub const APPROVED_PERMISSION_REQUEST: Self = Self("process.permission_request.approved");
164
165 #[must_use]
167 pub const fn as_str(self) -> &'static str {
168 self.0
169 }
170}
171
172impl Serialize for ProcessPermissionProfileId {
173 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
174 where
175 S: Serializer,
176 {
177 serializer.serialize_str((*self).as_str())
178 }
179}
180
181impl<'de> Deserialize<'de> for ProcessPermissionProfileId {
182 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
183 where
184 D: Deserializer<'de>,
185 {
186 let value = String::deserialize(deserializer)?;
187 match value.as_str() {
188 "process.read_only" => Ok(Self::READ_ONLY),
189 "process.local_workspace" => Ok(Self::LOCAL_WORKSPACE),
190 "process.local_workspace.host" => Ok(Self::LOCAL_WORKSPACE_HOST),
191 "process.shell.read_only" => Ok(Self::SHELL_READ_ONLY),
192 "process.permission_request.approved" => Ok(Self::APPROVED_PERMISSION_REQUEST),
193 _ => Err(serde::de::Error::custom(format!(
194 "unsupported process permission profile id `{value}`"
195 ))),
196 }
197 }
198}
199
200impl fmt::Display for ProcessPermissionProfileId {
201 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
202 formatter.write_str(self.as_str())
203 }
204}
205
206pub type ProcessRunnerFuture<'a> = Pin<Box<dyn Future<Output = ProcessRunnerResult> + Send + 'a>>;
211
212pub type ProcessRunnerResult = Result<ProcessRunnerOutput, ProcessRunnerError>;
214
215#[derive(Debug, Clone, PartialEq, Eq)]
217pub struct ProcessOutputChunk {
218 pub call_id: merry_core::ToolCallId,
220 pub stream: merry_core::ToolOutputStream,
222 pub delta: String,
224}
225
226#[derive(Debug, Clone)]
228pub struct ProcessOutputSink {
229 call_id: merry_core::ToolCallId,
230 sender: tokio::sync::mpsc::Sender<ProcessOutputChunk>,
231}
232
233impl ProcessOutputSink {
234 #[must_use]
236 pub fn new(
237 call_id: merry_core::ToolCallId,
238 sender: tokio::sync::mpsc::Sender<ProcessOutputChunk>,
239 ) -> Self {
240 Self { call_id, sender }
241 }
242
243 pub fn emit(&self, stream: merry_core::ToolOutputStream, bytes: &[u8]) {
245 if bytes.is_empty() {
246 return;
247 }
248 const MAX_LIVE_CHUNK_BYTES: usize = 4096;
249 let slice = &bytes[..bytes.len().min(MAX_LIVE_CHUNK_BYTES)];
250 let delta = String::from_utf8_lossy(slice).into_owned();
251 let _ = self.sender.try_send(ProcessOutputChunk {
252 call_id: self.call_id.clone(),
253 stream,
254 delta,
255 });
256 }
257}
258
259#[derive(Debug, Clone, Default)]
261pub struct ProcessRunnerContext {
262 cancellation_token: CancellationToken,
263 output_sink: Option<ProcessOutputSink>,
264}
265
266impl ProcessRunnerContext {
267 #[must_use]
269 pub fn new(cancellation_token: CancellationToken) -> Self {
270 Self {
271 cancellation_token,
272 output_sink: None,
273 }
274 }
275
276 #[must_use]
278 pub fn with_output_sink(mut self, sink: ProcessOutputSink) -> Self {
279 self.output_sink = Some(sink);
280 self
281 }
282
283 #[must_use]
285 pub fn cancellation_token(&self) -> &CancellationToken {
286 &self.cancellation_token
287 }
288
289 #[must_use]
291 pub fn output_sink(&self) -> Option<&ProcessOutputSink> {
292 self.output_sink.as_ref()
293 }
294}
295
296pub trait ProcessRunner: Send + Sync {
302 fn run<'a>(
304 &'a self,
305 intent: ProcessActionIntent,
306 context: ProcessRunnerContext,
307 ) -> ProcessRunnerFuture<'a>;
308
309 fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
313 None
314 }
315}
316
317pub trait PermissionedProcessRunnerFactory: Send + Sync {
325 fn validate_request(&self, _request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
333 Ok(())
334 }
335
336 fn request_capabilities_are_satisfied(
344 &self,
345 _request: &PermissionRequest,
346 ) -> Result<bool, ProcessRunnerError> {
347 Ok(false)
348 }
349
350 fn targets_protected_metadata(&self, _request: &PermissionRequest) -> bool {
355 false
356 }
357
358 fn prepare_approved_request(
362 &self,
363 request: &PermissionRequest,
364 ) -> Result<super::PreparedProcessPermission, ProcessRunnerError> {
365 self.validate_request(request)?;
366 Ok(super::PreparedProcessPermission::new(
367 self.runner_for(request),
368 Vec::new(),
369 ))
370 }
371
372 fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner>;
375
376 fn runner_for_decision(
383 &self,
384 request: &PermissionRequest,
385 _scope: merry_core::ApprovalScope,
386 ) -> Arc<dyn ProcessRunner> {
387 self.runner_for(request)
388 }
389}
390
391#[derive(Clone)]
393pub struct StaticPermissionedProcessRunnerFactory {
394 runner: Arc<dyn ProcessRunner>,
395}
396
397impl StaticPermissionedProcessRunnerFactory {
398 #[must_use]
400 pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
401 Self { runner }
402 }
403}
404
405impl PermissionedProcessRunnerFactory for StaticPermissionedProcessRunnerFactory {
406 fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
407 if request
408 .requested()
409 .iter()
410 .any(|capability| matches!(capability, RequestedCapability::Path(_)))
411 {
412 return Err(ProcessRunnerError::infrastructure(
413 "static permissioned process runner cannot enforce requested path capabilities",
414 ));
415 }
416 if request
417 .requested()
418 .iter()
419 .any(|capability| matches!(capability, RequestedCapability::HostIntegration(_)))
420 {
421 return Err(ProcessRunnerError::infrastructure(
422 "static permissioned process runner cannot enforce requested host integrations",
423 ));
424 }
425 Ok(())
426 }
427
428 fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
429 Arc::clone(&self.runner)
430 }
431}
432
433#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
439#[serde(deny_unknown_fields)]
440pub struct ProcessActionIntent {
441 summary: String,
442 argv: Vec<String>,
443 cwd: Option<String>,
444 env_policy: ProcessEnvPolicy,
445 stdin_text: Option<String>,
446 stdout_limit_bytes: usize,
447 stderr_limit_bytes: usize,
448 #[serde(default)]
449 background: bool,
450 #[serde(default, skip_serializing_if = "Option::is_none")]
451 timeout_secs: Option<u64>,
452 #[serde(default, skip_serializing_if = "Option::is_none")]
453 display_name: Option<String>,
454}
455
456impl ProcessActionIntent {
457 pub fn new(
459 argv: Vec<String>,
460 cwd: Option<String>,
461 env_policy: ProcessEnvPolicy,
462 stdin_text: Option<String>,
463 stdout_limit_bytes: usize,
464 stderr_limit_bytes: usize,
465 ) -> Result<Self, ProcessActionError> {
466 validate_argv(&argv)?;
467 let cwd = validate_cwd(cwd)?;
468 validate_stdin_text(stdin_text.as_deref())?;
469 validate_output_limit("stdout_limit_bytes", stdout_limit_bytes)?;
470 validate_output_limit("stderr_limit_bytes", stderr_limit_bytes)?;
471 let summary = summarize_intent(&argv, cwd.as_deref());
472
473 Ok(Self {
474 summary,
475 argv,
476 cwd,
477 env_policy,
478 stdin_text,
479 stdout_limit_bytes,
480 stderr_limit_bytes,
481 background: false,
482 timeout_secs: None,
483 display_name: None,
484 })
485 }
486
487 #[must_use]
492 pub fn with_background(mut self, background: bool) -> Self {
493 self.background = background;
494 self
495 }
496
497 pub fn with_timeout_secs(
503 mut self,
504 timeout_secs: Option<u64>,
505 ) -> Result<Self, ProcessActionError> {
506 self.timeout_secs = validate_timeout_secs(timeout_secs)?;
507 Ok(self)
508 }
509
510 #[must_use]
512 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
513 self.display_name = display_name.and_then(|value| {
514 let normalized = value.split_whitespace().collect::<Vec<_>>().join(" ");
515 if normalized.is_empty() {
516 None
517 } else {
518 Some(normalized.chars().take(80).collect())
519 }
520 });
521 self
522 }
523
524 #[must_use]
526 pub fn summary(&self) -> &str {
527 &self.summary
528 }
529
530 #[must_use]
532 pub fn argv(&self) -> &[String] {
533 &self.argv
534 }
535
536 #[must_use]
538 pub fn cwd(&self) -> Option<&str> {
539 self.cwd.as_deref()
540 }
541
542 #[must_use]
544 pub const fn env_policy(&self) -> ProcessEnvPolicy {
545 self.env_policy
546 }
547
548 #[must_use]
550 pub fn stdin_text(&self) -> Option<&str> {
551 self.stdin_text.as_deref()
552 }
553
554 #[must_use]
556 pub const fn background(&self) -> bool {
557 self.background
558 }
559
560 #[must_use]
562 pub const fn timeout_secs(&self) -> Option<u64> {
563 self.timeout_secs
564 }
565
566 #[must_use]
568 pub const fn effective_wait_timeout_secs(&self) -> u64 {
569 match self.timeout_secs {
570 Some(secs) => secs,
571 None => DEFAULT_PROCESS_WAIT_TIMEOUT_SECS,
572 }
573 }
574
575 #[must_use]
577 pub fn display_name(&self) -> Option<&str> {
578 self.display_name.as_deref()
579 }
580
581 #[must_use]
583 pub const fn stdout_limit_bytes(&self) -> usize {
584 self.stdout_limit_bytes
585 }
586
587 #[must_use]
589 pub const fn stderr_limit_bytes(&self) -> usize {
590 self.stderr_limit_bytes
591 }
592}
593
594#[derive(Debug, Clone, PartialEq, Eq)]
602pub struct ProcessRunnerOutput {
603 status: ProcessExitStatus,
604 stdout_data: Vec<u8>,
605 stdout_text: String,
606 stdout_bytes: usize,
607 stdout_truncated: bool,
608 stderr_data: Vec<u8>,
609 stderr_text: String,
610 stderr_bytes: usize,
611 stderr_truncated: bool,
612 running_pid: Option<u32>,
613 background_process_id: Option<BackgroundProcessId>,
614 wait_timed_out_secs: Option<u64>,
615}
616
617impl ProcessRunnerOutput {
618 pub fn new(
620 intent: &ProcessActionIntent,
621 status: ProcessExitStatus,
622 stdout_text: impl Into<String>,
623 stdout_truncated: bool,
624 stderr_text: impl Into<String>,
625 stderr_truncated: bool,
626 ) -> Result<Self, ProcessActionError> {
627 Self::from_bytes(
628 intent,
629 status,
630 stdout_text.into().into_bytes(),
631 stdout_truncated,
632 stderr_text.into().into_bytes(),
633 stderr_truncated,
634 )
635 }
636
637 pub fn from_bytes(
639 intent: &ProcessActionIntent,
640 status: ProcessExitStatus,
641 stdout_data: Vec<u8>,
642 stdout_truncated: bool,
643 stderr_data: Vec<u8>,
644 stderr_truncated: bool,
645 ) -> Result<Self, ProcessActionError> {
646 validate_captured_bytes(
647 "stdout_bytes",
648 stdout_data.len(),
649 intent.stdout_limit_bytes(),
650 )?;
651 validate_captured_bytes(
652 "stderr_bytes",
653 stderr_data.len(),
654 intent.stderr_limit_bytes(),
655 )?;
656
657 Ok(Self {
658 status,
659 stdout_text: String::from_utf8_lossy(&stdout_data).into_owned(),
660 stdout_bytes: stdout_data.len(),
661 stdout_data,
662 stdout_truncated,
663 stderr_text: String::from_utf8_lossy(&stderr_data).into_owned(),
664 stderr_bytes: stderr_data.len(),
665 stderr_data,
666 stderr_truncated,
667 running_pid: None,
668 background_process_id: None,
669 wait_timed_out_secs: None,
670 })
671 }
672
673 #[must_use]
675 pub fn with_running_pid(mut self, pid: u32) -> Self {
676 self.running_pid = Some(pid);
677 self
678 }
679
680 #[must_use]
682 pub fn with_background_process_id(mut self, id: BackgroundProcessId) -> Self {
683 self.background_process_id = Some(id);
684 self
685 }
686
687 #[must_use]
690 pub fn with_wait_timed_out_secs(mut self, secs: u64) -> Self {
691 self.wait_timed_out_secs = Some(secs);
692 self
693 }
694
695 #[must_use]
697 pub const fn status(&self) -> ProcessExitStatus {
698 self.status
699 }
700
701 #[must_use]
703 pub fn stdout_text(&self) -> &str {
704 &self.stdout_text
705 }
706
707 #[must_use]
709 pub fn stdout_data(&self) -> &[u8] {
710 &self.stdout_data
711 }
712
713 #[must_use]
715 pub fn stdout_is_utf8(&self) -> bool {
716 std::str::from_utf8(&self.stdout_data).is_ok()
717 }
718
719 #[must_use]
721 pub const fn stdout_bytes(&self) -> usize {
722 self.stdout_bytes
723 }
724
725 #[must_use]
727 pub const fn stdout_truncated(&self) -> bool {
728 self.stdout_truncated
729 }
730
731 #[must_use]
733 pub fn stderr_text(&self) -> &str {
734 &self.stderr_text
735 }
736
737 #[must_use]
739 pub fn stderr_data(&self) -> &[u8] {
740 &self.stderr_data
741 }
742
743 #[must_use]
745 pub fn stderr_is_utf8(&self) -> bool {
746 std::str::from_utf8(&self.stderr_data).is_ok()
747 }
748
749 #[must_use]
751 pub const fn stderr_bytes(&self) -> usize {
752 self.stderr_bytes
753 }
754
755 #[must_use]
757 pub const fn stderr_truncated(&self) -> bool {
758 self.stderr_truncated
759 }
760
761 #[must_use]
763 pub const fn running_pid(&self) -> Option<u32> {
764 self.running_pid
765 }
766
767 #[must_use]
769 pub fn background_process_id(&self) -> Option<&BackgroundProcessId> {
770 self.background_process_id.as_ref()
771 }
772
773 #[must_use]
776 pub const fn wait_timed_out_secs(&self) -> Option<u64> {
777 self.wait_timed_out_secs
778 }
779
780 #[must_use]
784 pub const fn ok(&self) -> bool {
785 matches!(
786 self.status,
787 ProcessExitStatus::Exited(0) | ProcessExitStatus::Running
788 )
789 }
790
791 pub fn execution_evidence(
793 &self,
794 intent: &ProcessActionIntent,
795 permission_profile_id: ProcessPermissionProfileId,
796 ) -> Result<ProcessExecutionEvidence, ProcessActionError> {
797 ProcessExecutionEvidence::new(
798 intent,
799 permission_profile_id,
800 self.status,
801 self.stdout_bytes,
802 self.stdout_truncated,
803 self.stderr_bytes,
804 self.stderr_truncated,
805 )
806 }
807}
808
809#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
811#[serde(rename_all = "snake_case")]
812pub enum ProcessExitStatus {
813 Exited(i32),
815 Cancelled,
817 FailedToStart,
819 DomainFailed,
821 Running,
825}
826
827impl ProcessExitStatus {
828 #[must_use]
830 pub const fn exit_code(self) -> Option<i32> {
831 match self {
832 Self::Exited(code) => Some(code),
833 Self::Cancelled | Self::FailedToStart | Self::DomainFailed | Self::Running => None,
834 }
835 }
836}
837
838#[derive(Debug, Clone, PartialEq, Eq, Error)]
840pub enum ProcessRunnerError {
841 #[error("process runner cancelled")]
843 Cancelled,
844
845 #[error("process runner infrastructure error: {message}")]
847 Infrastructure {
848 message: String,
850 },
851}
852
853impl ProcessRunnerError {
854 #[must_use]
856 pub fn infrastructure(message: impl Into<String>) -> Self {
857 Self::Infrastructure {
858 message: message.into(),
859 }
860 }
861}
862
863#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
869#[serde(deny_unknown_fields)]
870pub struct ProcessExecutionEvidence {
871 intent_summary: String,
872 argv: Vec<String>,
873 cwd: Option<String>,
874 permission_profile_id: ProcessPermissionProfileId,
875 status: ProcessExitStatus,
876 stdout_bytes: usize,
877 stdout_truncated: bool,
878 stderr_bytes: usize,
879 stderr_truncated: bool,
880}
881
882impl ProcessExecutionEvidence {
883 pub fn new(
885 intent: &ProcessActionIntent,
886 permission_profile_id: ProcessPermissionProfileId,
887 status: ProcessExitStatus,
888 stdout_bytes: usize,
889 stdout_truncated: bool,
890 stderr_bytes: usize,
891 stderr_truncated: bool,
892 ) -> Result<Self, ProcessActionError> {
893 validate_captured_bytes("stdout_bytes", stdout_bytes, intent.stdout_limit_bytes())?;
894 validate_captured_bytes("stderr_bytes", stderr_bytes, intent.stderr_limit_bytes())?;
895
896 Ok(Self {
897 intent_summary: intent.summary().to_owned(),
898 argv: intent.argv().to_vec(),
899 cwd: intent.cwd().map(str::to_owned),
900 permission_profile_id,
901 status,
902 stdout_bytes,
903 stdout_truncated,
904 stderr_bytes,
905 stderr_truncated,
906 })
907 }
908
909 #[must_use]
911 pub fn intent_summary(&self) -> &str {
912 &self.intent_summary
913 }
914
915 #[must_use]
917 pub fn argv(&self) -> &[String] {
918 &self.argv
919 }
920
921 #[must_use]
923 pub fn cwd(&self) -> Option<&str> {
924 self.cwd.as_deref()
925 }
926
927 #[must_use]
929 pub const fn permission_profile_id(&self) -> ProcessPermissionProfileId {
930 self.permission_profile_id
931 }
932
933 #[must_use]
935 pub const fn status(&self) -> ProcessExitStatus {
936 self.status
937 }
938
939 #[must_use]
941 pub const fn exit_code(&self) -> Option<i32> {
942 self.status.exit_code()
943 }
944
945 #[must_use]
947 pub const fn stdout_bytes(&self) -> usize {
948 self.stdout_bytes
949 }
950
951 #[must_use]
953 pub const fn stdout_truncated(&self) -> bool {
954 self.stdout_truncated
955 }
956
957 #[must_use]
959 pub const fn stderr_bytes(&self) -> usize {
960 self.stderr_bytes
961 }
962
963 #[must_use]
965 pub const fn stderr_truncated(&self) -> bool {
966 self.stderr_truncated
967 }
968
969 pub(crate) fn matches_intent(&self, intent: &ProcessActionIntent) -> bool {
970 self.intent_summary == intent.summary()
971 && self.argv == intent.argv()
972 && self.cwd.as_deref() == intent.cwd()
973 && self.stdout_bytes <= intent.stdout_limit_bytes()
974 && self.stderr_bytes <= intent.stderr_limit_bytes()
975 }
976}