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)]
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 prepare_approved_request(
354 &self,
355 request: &PermissionRequest,
356 ) -> Result<super::PreparedProcessPermission, ProcessRunnerError> {
357 self.validate_request(request)?;
358 Ok(super::PreparedProcessPermission::new(
359 self.runner_for(request),
360 Vec::new(),
361 ))
362 }
363
364 fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner>;
367}
368
369#[derive(Clone)]
371pub struct StaticPermissionedProcessRunnerFactory {
372 runner: Arc<dyn ProcessRunner>,
373}
374
375impl StaticPermissionedProcessRunnerFactory {
376 #[must_use]
378 pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
379 Self { runner }
380 }
381}
382
383impl PermissionedProcessRunnerFactory for StaticPermissionedProcessRunnerFactory {
384 fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
385 if request
386 .requested()
387 .iter()
388 .any(|capability| matches!(capability, RequestedCapability::Path(_)))
389 {
390 return Err(ProcessRunnerError::infrastructure(
391 "static permissioned process runner cannot enforce requested path capabilities",
392 ));
393 }
394 if request
395 .requested()
396 .iter()
397 .any(|capability| matches!(capability, RequestedCapability::HostIntegration(_)))
398 {
399 return Err(ProcessRunnerError::infrastructure(
400 "static permissioned process runner cannot enforce requested host integrations",
401 ));
402 }
403 Ok(())
404 }
405
406 fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
407 Arc::clone(&self.runner)
408 }
409}
410
411#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
417#[serde(deny_unknown_fields)]
418pub struct ProcessActionIntent {
419 summary: String,
420 argv: Vec<String>,
421 cwd: Option<String>,
422 env_policy: ProcessEnvPolicy,
423 stdin_text: Option<String>,
424 stdout_limit_bytes: usize,
425 stderr_limit_bytes: usize,
426 #[serde(default)]
427 background: bool,
428 #[serde(default, skip_serializing_if = "Option::is_none")]
429 timeout_secs: Option<u64>,
430 #[serde(default, skip_serializing_if = "Option::is_none")]
431 display_name: Option<String>,
432}
433
434impl ProcessActionIntent {
435 pub fn new(
437 argv: Vec<String>,
438 cwd: Option<String>,
439 env_policy: ProcessEnvPolicy,
440 stdin_text: Option<String>,
441 stdout_limit_bytes: usize,
442 stderr_limit_bytes: usize,
443 ) -> Result<Self, ProcessActionError> {
444 validate_argv(&argv)?;
445 let cwd = validate_cwd(cwd)?;
446 validate_stdin_text(stdin_text.as_deref())?;
447 validate_output_limit("stdout_limit_bytes", stdout_limit_bytes)?;
448 validate_output_limit("stderr_limit_bytes", stderr_limit_bytes)?;
449 let summary = summarize_intent(&argv, cwd.as_deref());
450
451 Ok(Self {
452 summary,
453 argv,
454 cwd,
455 env_policy,
456 stdin_text,
457 stdout_limit_bytes,
458 stderr_limit_bytes,
459 background: false,
460 timeout_secs: None,
461 display_name: None,
462 })
463 }
464
465 #[must_use]
470 pub fn with_background(mut self, background: bool) -> Self {
471 self.background = background;
472 self
473 }
474
475 pub fn with_timeout_secs(
481 mut self,
482 timeout_secs: Option<u64>,
483 ) -> Result<Self, ProcessActionError> {
484 self.timeout_secs = validate_timeout_secs(timeout_secs)?;
485 Ok(self)
486 }
487
488 #[must_use]
490 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
491 self.display_name = display_name.and_then(|value| {
492 let normalized = value.split_whitespace().collect::<Vec<_>>().join(" ");
493 if normalized.is_empty() {
494 None
495 } else {
496 Some(normalized.chars().take(80).collect())
497 }
498 });
499 self
500 }
501
502 #[must_use]
504 pub fn summary(&self) -> &str {
505 &self.summary
506 }
507
508 #[must_use]
510 pub fn argv(&self) -> &[String] {
511 &self.argv
512 }
513
514 #[must_use]
516 pub fn cwd(&self) -> Option<&str> {
517 self.cwd.as_deref()
518 }
519
520 #[must_use]
522 pub const fn env_policy(&self) -> ProcessEnvPolicy {
523 self.env_policy
524 }
525
526 #[must_use]
528 pub fn stdin_text(&self) -> Option<&str> {
529 self.stdin_text.as_deref()
530 }
531
532 #[must_use]
534 pub const fn background(&self) -> bool {
535 self.background
536 }
537
538 #[must_use]
540 pub const fn timeout_secs(&self) -> Option<u64> {
541 self.timeout_secs
542 }
543
544 #[must_use]
546 pub const fn effective_wait_timeout_secs(&self) -> u64 {
547 match self.timeout_secs {
548 Some(secs) => secs,
549 None => DEFAULT_PROCESS_WAIT_TIMEOUT_SECS,
550 }
551 }
552
553 #[must_use]
555 pub fn display_name(&self) -> Option<&str> {
556 self.display_name.as_deref()
557 }
558
559 #[must_use]
561 pub const fn stdout_limit_bytes(&self) -> usize {
562 self.stdout_limit_bytes
563 }
564
565 #[must_use]
567 pub const fn stderr_limit_bytes(&self) -> usize {
568 self.stderr_limit_bytes
569 }
570}
571
572#[derive(Debug, Clone, PartialEq, Eq)]
580pub struct ProcessRunnerOutput {
581 status: ProcessExitStatus,
582 stdout_data: Vec<u8>,
583 stdout_text: String,
584 stdout_bytes: usize,
585 stdout_truncated: bool,
586 stderr_data: Vec<u8>,
587 stderr_text: String,
588 stderr_bytes: usize,
589 stderr_truncated: bool,
590 running_pid: Option<u32>,
591 background_process_id: Option<BackgroundProcessId>,
592 wait_timed_out_secs: Option<u64>,
593}
594
595impl ProcessRunnerOutput {
596 pub fn new(
598 intent: &ProcessActionIntent,
599 status: ProcessExitStatus,
600 stdout_text: impl Into<String>,
601 stdout_truncated: bool,
602 stderr_text: impl Into<String>,
603 stderr_truncated: bool,
604 ) -> Result<Self, ProcessActionError> {
605 Self::from_bytes(
606 intent,
607 status,
608 stdout_text.into().into_bytes(),
609 stdout_truncated,
610 stderr_text.into().into_bytes(),
611 stderr_truncated,
612 )
613 }
614
615 pub fn from_bytes(
617 intent: &ProcessActionIntent,
618 status: ProcessExitStatus,
619 stdout_data: Vec<u8>,
620 stdout_truncated: bool,
621 stderr_data: Vec<u8>,
622 stderr_truncated: bool,
623 ) -> Result<Self, ProcessActionError> {
624 validate_captured_bytes(
625 "stdout_bytes",
626 stdout_data.len(),
627 intent.stdout_limit_bytes(),
628 )?;
629 validate_captured_bytes(
630 "stderr_bytes",
631 stderr_data.len(),
632 intent.stderr_limit_bytes(),
633 )?;
634
635 Ok(Self {
636 status,
637 stdout_text: String::from_utf8_lossy(&stdout_data).into_owned(),
638 stdout_bytes: stdout_data.len(),
639 stdout_data,
640 stdout_truncated,
641 stderr_text: String::from_utf8_lossy(&stderr_data).into_owned(),
642 stderr_bytes: stderr_data.len(),
643 stderr_data,
644 stderr_truncated,
645 running_pid: None,
646 background_process_id: None,
647 wait_timed_out_secs: None,
648 })
649 }
650
651 #[must_use]
653 pub fn with_running_pid(mut self, pid: u32) -> Self {
654 self.running_pid = Some(pid);
655 self
656 }
657
658 #[must_use]
660 pub fn with_background_process_id(mut self, id: BackgroundProcessId) -> Self {
661 self.background_process_id = Some(id);
662 self
663 }
664
665 #[must_use]
668 pub fn with_wait_timed_out_secs(mut self, secs: u64) -> Self {
669 self.wait_timed_out_secs = Some(secs);
670 self
671 }
672
673 #[must_use]
675 pub const fn status(&self) -> ProcessExitStatus {
676 self.status
677 }
678
679 #[must_use]
681 pub fn stdout_text(&self) -> &str {
682 &self.stdout_text
683 }
684
685 #[must_use]
687 pub fn stdout_data(&self) -> &[u8] {
688 &self.stdout_data
689 }
690
691 #[must_use]
693 pub fn stdout_is_utf8(&self) -> bool {
694 std::str::from_utf8(&self.stdout_data).is_ok()
695 }
696
697 #[must_use]
699 pub const fn stdout_bytes(&self) -> usize {
700 self.stdout_bytes
701 }
702
703 #[must_use]
705 pub const fn stdout_truncated(&self) -> bool {
706 self.stdout_truncated
707 }
708
709 #[must_use]
711 pub fn stderr_text(&self) -> &str {
712 &self.stderr_text
713 }
714
715 #[must_use]
717 pub fn stderr_data(&self) -> &[u8] {
718 &self.stderr_data
719 }
720
721 #[must_use]
723 pub fn stderr_is_utf8(&self) -> bool {
724 std::str::from_utf8(&self.stderr_data).is_ok()
725 }
726
727 #[must_use]
729 pub const fn stderr_bytes(&self) -> usize {
730 self.stderr_bytes
731 }
732
733 #[must_use]
735 pub const fn stderr_truncated(&self) -> bool {
736 self.stderr_truncated
737 }
738
739 #[must_use]
741 pub const fn running_pid(&self) -> Option<u32> {
742 self.running_pid
743 }
744
745 #[must_use]
747 pub fn background_process_id(&self) -> Option<&BackgroundProcessId> {
748 self.background_process_id.as_ref()
749 }
750
751 #[must_use]
754 pub const fn wait_timed_out_secs(&self) -> Option<u64> {
755 self.wait_timed_out_secs
756 }
757
758 #[must_use]
762 pub const fn ok(&self) -> bool {
763 matches!(
764 self.status,
765 ProcessExitStatus::Exited(0) | ProcessExitStatus::Running
766 )
767 }
768
769 pub fn execution_evidence(
771 &self,
772 intent: &ProcessActionIntent,
773 permission_profile_id: ProcessPermissionProfileId,
774 ) -> Result<ProcessExecutionEvidence, ProcessActionError> {
775 ProcessExecutionEvidence::new(
776 intent,
777 permission_profile_id,
778 self.status,
779 self.stdout_bytes,
780 self.stdout_truncated,
781 self.stderr_bytes,
782 self.stderr_truncated,
783 )
784 }
785}
786
787#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
789#[serde(rename_all = "snake_case")]
790pub enum ProcessExitStatus {
791 Exited(i32),
793 Cancelled,
795 FailedToStart,
797 DomainFailed,
799 Running,
803}
804
805impl ProcessExitStatus {
806 #[must_use]
808 pub const fn exit_code(self) -> Option<i32> {
809 match self {
810 Self::Exited(code) => Some(code),
811 Self::Cancelled | Self::FailedToStart | Self::DomainFailed | Self::Running => None,
812 }
813 }
814}
815
816#[derive(Debug, Clone, PartialEq, Eq, Error)]
818pub enum ProcessRunnerError {
819 #[error("process runner cancelled")]
821 Cancelled,
822
823 #[error("process runner infrastructure error: {message}")]
825 Infrastructure {
826 message: String,
828 },
829}
830
831impl ProcessRunnerError {
832 #[must_use]
834 pub fn infrastructure(message: impl Into<String>) -> Self {
835 Self::Infrastructure {
836 message: message.into(),
837 }
838 }
839}
840
841#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
847#[serde(deny_unknown_fields)]
848pub struct ProcessExecutionEvidence {
849 intent_summary: String,
850 argv: Vec<String>,
851 cwd: Option<String>,
852 permission_profile_id: ProcessPermissionProfileId,
853 status: ProcessExitStatus,
854 stdout_bytes: usize,
855 stdout_truncated: bool,
856 stderr_bytes: usize,
857 stderr_truncated: bool,
858}
859
860impl ProcessExecutionEvidence {
861 pub fn new(
863 intent: &ProcessActionIntent,
864 permission_profile_id: ProcessPermissionProfileId,
865 status: ProcessExitStatus,
866 stdout_bytes: usize,
867 stdout_truncated: bool,
868 stderr_bytes: usize,
869 stderr_truncated: bool,
870 ) -> Result<Self, ProcessActionError> {
871 validate_captured_bytes("stdout_bytes", stdout_bytes, intent.stdout_limit_bytes())?;
872 validate_captured_bytes("stderr_bytes", stderr_bytes, intent.stderr_limit_bytes())?;
873
874 Ok(Self {
875 intent_summary: intent.summary().to_owned(),
876 argv: intent.argv().to_vec(),
877 cwd: intent.cwd().map(str::to_owned),
878 permission_profile_id,
879 status,
880 stdout_bytes,
881 stdout_truncated,
882 stderr_bytes,
883 stderr_truncated,
884 })
885 }
886
887 #[must_use]
889 pub fn intent_summary(&self) -> &str {
890 &self.intent_summary
891 }
892
893 #[must_use]
895 pub fn argv(&self) -> &[String] {
896 &self.argv
897 }
898
899 #[must_use]
901 pub fn cwd(&self) -> Option<&str> {
902 self.cwd.as_deref()
903 }
904
905 #[must_use]
907 pub const fn permission_profile_id(&self) -> ProcessPermissionProfileId {
908 self.permission_profile_id
909 }
910
911 #[must_use]
913 pub const fn status(&self) -> ProcessExitStatus {
914 self.status
915 }
916
917 #[must_use]
919 pub const fn exit_code(&self) -> Option<i32> {
920 self.status.exit_code()
921 }
922
923 #[must_use]
925 pub const fn stdout_bytes(&self) -> usize {
926 self.stdout_bytes
927 }
928
929 #[must_use]
931 pub const fn stdout_truncated(&self) -> bool {
932 self.stdout_truncated
933 }
934
935 #[must_use]
937 pub const fn stderr_bytes(&self) -> usize {
938 self.stderr_bytes
939 }
940
941 #[must_use]
943 pub const fn stderr_truncated(&self) -> bool {
944 self.stderr_truncated
945 }
946
947 pub(crate) fn matches_intent(&self, intent: &ProcessActionIntent) -> bool {
948 self.intent_summary == intent.summary()
949 && self.argv == intent.argv()
950 && self.cwd.as_deref() == intent.cwd()
951 && self.stdout_bytes <= intent.stdout_limit_bytes()
952 && self.stderr_bytes <= intent.stderr_limit_bytes()
953 }
954}