Skip to main content

merry_runtime/process/
contracts.rs

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
12/// Maximum accepted byte length for one argv item in a process intent.
13pub const MAX_PROCESS_ARG_BYTES: usize = 4096;
14/// Maximum accepted number of argv items in a process intent.
15pub const MAX_PROCESS_ARGV_ITEMS: usize = 256;
16/// Maximum accepted byte length for a workspace-relative process cwd.
17pub const MAX_PROCESS_CWD_BYTES: usize = 4096;
18/// Maximum accepted byte length for inline stdin text.
19pub const MAX_PROCESS_STDIN_TEXT_BYTES: usize = 64 * 1024;
20/// Maximum accepted captured byte limit per process output stream.
21pub const MAX_PROCESS_OUTPUT_LIMIT_BYTES: usize = 1024 * 1024;
22/// Default foreground wait timeout in seconds before handing off to background.
23pub const DEFAULT_PROCESS_WAIT_TIMEOUT_SECS: u64 = 120;
24/// Maximum accepted foreground wait timeout in seconds for one `run_process` call.
25pub const MAX_PROCESS_WAIT_TIMEOUT_SECS: u64 = 3600;
26
27/// Minimal process environment override policy for SP1.
28///
29/// This describes environment changes requested by the tool call. It does not
30/// decide whether the selected process runner inherits its own current
31/// environment; that is part of the runner/sandbox boundary chosen by the
32/// runtime builder.
33#[non_exhaustive]
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum ProcessEnvPolicy {
37    /// No tool-requested environment overrides.
38    #[default]
39    Empty,
40    /// Test-only stand-in for a future non-empty environment policy.
41    #[cfg(test)]
42    NonEmptyForTest,
43}
44
45impl ProcessEnvPolicy {
46    /// Creates the no environment override policy.
47    #[must_use]
48    pub const fn empty() -> Self {
49        Self::Empty
50    }
51}
52
53/// Explicit admission for the process runner used by the local workspace lane.
54///
55/// This value is intentionally small and declarative. It records that the
56/// caller has selected Merry's local-workspace process profile and accepted
57/// the process risk for that profile; it is not proof that any process is
58/// actually confined. A host adapter may materialize this profile with a
59/// platform-native mechanism, or report that isolation is unavailable. Runtime
60/// code treats it as construction-time admission for the configured process
61/// runner boundary;
62/// argv classification remains a risk signal rather than an executable
63/// allowlist.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct AcceptedLocalWorkspaceProcessAdmission {
66    sandbox_profile: LocalWorkspaceProcessSandboxProfile,
67    permission_profile_id: ProcessPermissionProfileId,
68}
69
70impl AcceptedLocalWorkspaceProcessAdmission {
71    /// Creates admission for the local workspace process profile.
72    ///
73    /// Calling this explicitly accepts validated process intents for the
74    /// declared profile. The selected runner still enforces filesystem,
75    /// network, and host-integration capabilities.
76    #[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    /// Creates admission for the explicit unrestricted host process profile.
85    ///
86    /// The runtime still records and audits the process action, but the host
87    /// process backend does not add an operating-system sandbox in this mode.
88    /// Review policy remains a separate runtime setting; host admission does
89    /// not imply fully trusted execution.
90    #[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    /// Returns the declared sandbox profile for this admission.
109    #[must_use]
110    pub const fn sandbox_profile(self) -> LocalWorkspaceProcessSandboxProfile {
111        self.sandbox_profile
112    }
113
114    /// Returns the permission profile admitted by this construction-time grant.
115    #[must_use]
116    pub const fn permission_profile_id(self) -> ProcessPermissionProfileId {
117        self.permission_profile_id
118    }
119}
120
121/// Declared sandbox/profile associated with local workspace process admission.
122#[non_exhaustive]
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum LocalWorkspaceProcessSandboxProfile {
125    /// Local workspace process profile.
126    LocalWorkspace,
127    /// Explicit unrestricted host process profile.
128    Host,
129}
130
131impl LocalWorkspaceProcessSandboxProfile {
132    /// Returns the stable profile label used in process composition identity.
133    #[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/// Stable identifier for a runtime-owned process permission profile.
143///
144/// Permission profiles describe filesystem, network, and side-effect
145/// capability. They are separate from concrete command classification and from
146/// model-visible tool profiles.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
148pub struct ProcessPermissionProfileId(&'static str);
149
150impl ProcessPermissionProfileId {
151    /// Read-only process lane for bounded inspection commands.
152    pub const READ_ONLY: Self = Self("process.read_only");
153    /// Local workspace process lane.
154    pub const LOCAL_WORKSPACE: Self = Self("process.local_workspace");
155    /// Local workspace process lane accepted for the unrestricted host profile.
156    pub const LOCAL_WORKSPACE_HOST: Self = Self("process.local_workspace.host");
157    /// Read-only shell wrapper lane for plain command sequences under a real shell runner.
158    pub const SHELL_READ_ONLY: Self = Self("process.shell.read_only");
159    /// Process lane admitted by an explicit permission request review.
160    pub const APPROVED_PERMISSION_REQUEST: Self = Self("process.permission_request.approved");
161
162    /// Returns the stable profile identifier string.
163    #[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
203/// Boxed process runner future used for object-safe runtime process boundaries.
204///
205/// The runner boundary is runtime-owned and provider-neutral. It accepts only a
206/// validated [`ProcessActionIntent`] and a cancellation-aware context.
207pub type ProcessRunnerFuture<'a> = Pin<Box<dyn Future<Output = ProcessRunnerResult> + Send + 'a>>;
208
209/// Result returned by a runtime-owned process runner.
210pub type ProcessRunnerResult = Result<ProcessRunnerOutput, ProcessRunnerError>;
211
212/// Live incremental output chunk emitted while a process action is running.
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct ProcessOutputChunk {
215    /// Tool call that owns the running process.
216    pub call_id: merry_core::ToolCallId,
217    /// Which output pipe produced the chunk.
218    pub stream: merry_core::ToolOutputStream,
219    /// Lossy UTF-8 text chunk.
220    pub delta: String,
221}
222
223/// Non-blocking sink for forwarding bounded live process output chunks to UI observers.
224#[derive(Debug, Clone)]
225pub struct ProcessOutputSink {
226    call_id: merry_core::ToolCallId,
227    sender: tokio::sync::mpsc::Sender<ProcessOutputChunk>,
228}
229
230impl ProcessOutputSink {
231    /// Creates a live output sink bound to one active tool call.
232    #[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    /// Emits a bounded chunk without ever blocking the process reader task.
241    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/// Context passed to a process runner.
257#[derive(Debug, Clone)]
258pub struct ProcessRunnerContext {
259    cancellation_token: CancellationToken,
260    output_sink: Option<ProcessOutputSink>,
261}
262
263impl ProcessRunnerContext {
264    /// Creates a process runner context with the provided cancellation token.
265    #[must_use]
266    pub fn new(cancellation_token: CancellationToken) -> Self {
267        Self {
268            cancellation_token,
269            output_sink: None,
270        }
271    }
272
273    /// Attaches a non-blocking live output sink for streaming stdout/stderr progress.
274    #[must_use]
275    pub fn with_output_sink(mut self, sink: ProcessOutputSink) -> Self {
276        self.output_sink = Some(sink);
277        self
278    }
279
280    /// Returns the cancellation token for this process action.
281    #[must_use]
282    pub fn cancellation_token(&self) -> &CancellationToken {
283        &self.cancellation_token
284    }
285
286    /// Returns the optional live output sink for streaming stdout/stderr progress.
287    #[must_use]
288    pub fn output_sink(&self) -> Option<&ProcessOutputSink> {
289        self.output_sink.as_ref()
290    }
291}
292
293/// Object-safe runtime process runner boundary.
294///
295/// Implementations for SP2 are fakes or adapters supplied by tests and higher
296/// layers. This trait must not imply shell execution, raw shell parsing, or
297/// provider-specific behavior.
298pub trait ProcessRunner: Send + Sync {
299    /// Runs a validated process intent and returns provider-neutral output.
300    fn run<'a>(
301        &'a self,
302        intent: ProcessActionIntent,
303        context: ProcessRunnerContext,
304    ) -> ProcessRunnerFuture<'a>;
305
306    /// Returns the session board that retains this runner's background processes.
307    ///
308    /// Runners that do not keep processes after `run` returns leave this empty.
309    fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
310        None
311    }
312}
313
314/// Factory for runners created from approved permission requests.
315///
316/// Implementations translate a runtime-approved request into the concrete
317/// process backend/profile for that exact action. Adapters consume read-only
318/// session snapshots; runtime owns retention and capability lifetimes through
319/// `SessionPermissionedProcessRunnerFactory`. An adapter never records grants
320/// or grants authority beyond the runtime-approved request.
321pub trait PermissionedProcessRunnerFactory: Send + Sync {
322    /// Validates the request against the backend's hard capability policy.
323    ///
324    /// Backends that do not have additional policy constraints may keep the
325    /// default only when they can enforce every capability in the request
326    /// through their existing runner. A backend that cannot materialize a
327    /// requested path or network grant must reject it. A validation failure
328    /// must happen before any reviewer or process side effect is started.
329    fn validate_request(&self, _request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
330        Ok(())
331    }
332
333    /// Returns whether the backend already enforces every capability in the
334    /// request for the current process session.
335    ///
336    /// This query covers capability state only; it does not authorize the
337    /// requested action. Implementations must return `false` for capabilities
338    /// that are action-scoped, such as network access, or when the backend
339    /// cannot prove that the requested access is covered.
340    fn request_capabilities_are_satisfied(
341        &self,
342        _request: &PermissionRequest,
343    ) -> Result<bool, ProcessRunnerError> {
344        Ok(false)
345    }
346
347    /// Prepares one validated action and its normalized path evidence without
348    /// changing permission state. Adapters can share a single filesystem view
349    /// across validation and materialization. The default retains no paths.
350    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    /// Creates the process runner for one approved permission request, without
362    /// mutating session state. Runtime handles retention after successful preparation.
363    fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner>;
364}
365
366/// Compatibility factory that always returns the same runner.
367#[derive(Clone)]
368pub struct StaticPermissionedProcessRunnerFactory {
369    runner: Arc<dyn ProcessRunner>,
370}
371
372impl StaticPermissionedProcessRunnerFactory {
373    /// Creates a static runner factory.
374    #[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/// Provider-neutral, typed intent for a local process action.
409///
410/// The argv vector is intentionally open and does not enumerate allowed
411/// commands. This value is proposal evidence only in SP1; it is not an
412/// executor and must not be treated as authorization to spawn a process.
413#[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    /// Creates a validated process action intent.
433    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    /// Keeps the process after the tool returns when `background` is true.
463    ///
464    /// The default waits until the process exits or reaches its wait timeout.
465    /// A retained background process stays until stopped or the owning session ends.
466    #[must_use]
467    pub fn with_background(mut self, background: bool) -> Self {
468        self.background = background;
469        self
470    }
471
472    /// Sets an optional foreground wait timeout in seconds (`1..=MAX_PROCESS_WAIT_TIMEOUT_SECS`).
473    ///
474    /// When a foreground command is still running after this timeout, the runner
475    /// does not kill it; it retains the process in the background and returns
476    /// its id and partial output so the calling LLM can decide how to proceed.
477    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    /// Attaches an optional short human-readable label for a retained process.
486    #[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    /// Returns a compact deterministic summary of the process intent.
500    #[must_use]
501    pub fn summary(&self) -> &str {
502        &self.summary
503    }
504
505    /// Returns the exact argv vector.
506    #[must_use]
507    pub fn argv(&self) -> &[String] {
508        &self.argv
509    }
510
511    /// Returns the workspace-relative cwd, or `None` for the workspace root.
512    #[must_use]
513    pub fn cwd(&self) -> Option<&str> {
514        self.cwd.as_deref()
515    }
516
517    /// Returns the typed environment policy.
518    #[must_use]
519    pub const fn env_policy(&self) -> ProcessEnvPolicy {
520        self.env_policy
521    }
522
523    /// Returns optional inline stdin text.
524    #[must_use]
525    pub fn stdin_text(&self) -> Option<&str> {
526        self.stdin_text.as_deref()
527    }
528
529    /// Returns whether the runner should retain the process after the tool returns.
530    #[must_use]
531    pub const fn background(&self) -> bool {
532        self.background
533    }
534
535    /// Returns the explicit foreground wait timeout override in seconds, if set.
536    #[must_use]
537    pub const fn timeout_secs(&self) -> Option<u64> {
538        self.timeout_secs
539    }
540
541    /// Returns the effective foreground wait timeout in seconds.
542    #[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    /// Returns the optional human-readable display name for this process.
551    #[must_use]
552    pub fn display_name(&self) -> Option<&str> {
553        self.display_name.as_deref()
554    }
555
556    /// Returns the stdout capture limit in bytes.
557    #[must_use]
558    pub const fn stdout_limit_bytes(&self) -> usize {
559        self.stdout_limit_bytes
560    }
561
562    /// Returns the stderr capture limit in bytes.
563    #[must_use]
564    pub const fn stderr_limit_bytes(&self) -> usize {
565        self.stderr_limit_bytes
566    }
567}
568
569/// Bounded output returned by a process runner.
570///
571/// Process output is an opaque byte stream. The runner keeps the exact bounded
572/// bytes and a loss-tolerant UTF-8 view separately so binary tools cannot turn a
573/// successful process into an infrastructure error merely by writing invalid
574/// UTF-8. Internal execution audit evidence stores byte counts and truncation
575/// flags, not these payloads.
576#[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    /// Creates validated process runner output for a previously validated intent.
594    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    /// Creates output from exact bounded process bytes.
613    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    /// Records the pid of a process that is still running.
649    #[must_use]
650    pub fn with_running_pid(mut self, pid: u32) -> Self {
651        self.running_pid = Some(pid);
652        self
653    }
654
655    /// Records the id of a process retained after this call returns.
656    #[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    /// Records that a foreground wait elapsed after `secs` seconds without killing
663    /// the still-running process, handing it off to the background supervisor.
664    #[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    /// Returns the provider-neutral completion status.
671    #[must_use]
672    pub const fn status(&self) -> ProcessExitStatus {
673        self.status
674    }
675
676    /// Returns bounded stdout payload for the result artifact.
677    #[must_use]
678    pub fn stdout_text(&self) -> &str {
679        &self.stdout_text
680    }
681
682    /// Returns the exact bounded stdout bytes.
683    #[must_use]
684    pub fn stdout_data(&self) -> &[u8] {
685        &self.stdout_data
686    }
687
688    /// Returns whether stdout was valid UTF-8 without replacement.
689    #[must_use]
690    pub fn stdout_is_utf8(&self) -> bool {
691        std::str::from_utf8(&self.stdout_data).is_ok()
692    }
693
694    /// Returns captured stdout byte count.
695    #[must_use]
696    pub const fn stdout_bytes(&self) -> usize {
697        self.stdout_bytes
698    }
699
700    /// Returns whether stdout capture was truncated.
701    #[must_use]
702    pub const fn stdout_truncated(&self) -> bool {
703        self.stdout_truncated
704    }
705
706    /// Returns bounded stderr payload for the result artifact.
707    #[must_use]
708    pub fn stderr_text(&self) -> &str {
709        &self.stderr_text
710    }
711
712    /// Returns the exact bounded stderr bytes.
713    #[must_use]
714    pub fn stderr_data(&self) -> &[u8] {
715        &self.stderr_data
716    }
717
718    /// Returns whether stderr was valid UTF-8 without replacement.
719    #[must_use]
720    pub fn stderr_is_utf8(&self) -> bool {
721        std::str::from_utf8(&self.stderr_data).is_ok()
722    }
723
724    /// Returns captured stderr byte count.
725    #[must_use]
726    pub const fn stderr_bytes(&self) -> usize {
727        self.stderr_bytes
728    }
729
730    /// Returns whether stderr capture was truncated.
731    #[must_use]
732    pub const fn stderr_truncated(&self) -> bool {
733        self.stderr_truncated
734    }
735
736    /// Returns the pid when the process is still running.
737    #[must_use]
738    pub const fn running_pid(&self) -> Option<u32> {
739        self.running_pid
740    }
741
742    /// Returns the id of a process retained after this call returns.
743    #[must_use]
744    pub fn background_process_id(&self) -> Option<&BackgroundProcessId> {
745        self.background_process_id.as_ref()
746    }
747
748    /// Returns the foreground wait timeout in seconds when the call handed off a
749    /// still-running command to the background without killing it.
750    #[must_use]
751    pub const fn wait_timed_out_secs(&self) -> Option<u64> {
752        self.wait_timed_out_secs
753    }
754
755    /// Returns whether the process output represents successful completion.
756    ///
757    /// A process that is still running counts as success so the turn can continue.
758    #[must_use]
759    pub const fn ok(&self) -> bool {
760        matches!(
761            self.status,
762            ProcessExitStatus::Exited(0) | ProcessExitStatus::Running
763        )
764    }
765
766    /// Builds payload-free internal execution evidence for the given intent.
767    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/// Provider-neutral process completion status.
785#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
786#[serde(rename_all = "snake_case")]
787pub enum ProcessExitStatus {
788    /// The process exited with an integer code.
789    Exited(i32),
790    /// The process was cancelled before normal completion.
791    Cancelled,
792    /// The process could not be started by the future process executor.
793    FailedToStart,
794    /// The process runner reported a domain failure before normal completion.
795    DomainFailed,
796    /// The process was still running when the tool returned.
797    ///
798    /// The runner keeps it until the owning session ends.
799    Running,
800}
801
802impl ProcessExitStatus {
803    /// Returns the exit code when the process reached normal exit.
804    #[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/// Infrastructure errors returned by a process runner.
814#[derive(Debug, Clone, PartialEq, Eq, Error)]
815pub enum ProcessRunnerError {
816    /// Process runner was cancelled cooperatively before producing output.
817    #[error("process runner cancelled")]
818    Cancelled,
819
820    /// The runner infrastructure failed before producing durable output.
821    #[error("process runner infrastructure error: {message}")]
822    Infrastructure {
823        /// Actionable infrastructure failure detail.
824        message: String,
825    },
826}
827
828impl ProcessRunnerError {
829    /// Creates an infrastructure process runner error.
830    #[must_use]
831    pub fn infrastructure(message: impl Into<String>) -> Self {
832        Self::Infrastructure {
833            message: message.into(),
834        }
835    }
836}
837
838/// Provider-neutral evidence recorded after a process action executes.
839///
840/// This stores bounded metadata only: the validated intent identity, completion
841/// status, captured byte counts, and truncation flags. It contains no provider
842/// wire data and no stdout/stderr payload.
843#[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    /// Creates validated process execution evidence for a previously proposed intent.
859    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    /// Returns the compact process intent summary.
885    #[must_use]
886    pub fn intent_summary(&self) -> &str {
887        &self.intent_summary
888    }
889
890    /// Returns the exact argv copied from the validated intent.
891    #[must_use]
892    pub fn argv(&self) -> &[String] {
893        &self.argv
894    }
895
896    /// Returns the workspace-relative cwd copied from the validated intent.
897    #[must_use]
898    pub fn cwd(&self) -> Option<&str> {
899        self.cwd.as_deref()
900    }
901
902    /// Returns the permission profile used for this process execution.
903    #[must_use]
904    pub const fn permission_profile_id(&self) -> ProcessPermissionProfileId {
905        self.permission_profile_id
906    }
907
908    /// Returns the provider-neutral completion status.
909    #[must_use]
910    pub const fn status(&self) -> ProcessExitStatus {
911        self.status
912    }
913
914    /// Returns the exit code when the process reached normal exit.
915    #[must_use]
916    pub const fn exit_code(&self) -> Option<i32> {
917        self.status.exit_code()
918    }
919
920    /// Returns captured stdout byte count.
921    #[must_use]
922    pub const fn stdout_bytes(&self) -> usize {
923        self.stdout_bytes
924    }
925
926    /// Returns whether stdout capture was truncated.
927    #[must_use]
928    pub const fn stdout_truncated(&self) -> bool {
929        self.stdout_truncated
930    }
931
932    /// Returns captured stderr byte count.
933    #[must_use]
934    pub const fn stderr_bytes(&self) -> usize {
935        self.stderr_bytes
936    }
937
938    /// Returns whether stderr capture was truncated.
939    #[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}