Skip to main content

merry_process/
lib.rs

1//! Host-process adapters for Merry's provider-neutral process contract.
2//!
3//! [`merry_runtime`] owns process intent, admission, permission requests, and
4//! execution evidence. This crate owns the host-facing runner selection and
5//! binds the runners used by one runtime owner to one [`ProcessSession`]. A
6//! platform can replace the concrete backend without changing coding
7//! composition or runtime call sites.
8
9mod backend;
10mod baseline;
11mod browser_spawner;
12mod callback_runner;
13#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
14mod confinement;
15#[cfg(not(all(feature = "sandbox", any(target_os = "linux", target_os = "macos"))))]
16#[path = "confinement/unsupported.rs"]
17mod confinement;
18mod gpg;
19mod host_path;
20mod host_resources;
21mod process_runner;
22
23pub use backend::{
24    LiveProcessBackend, LocalProcessBackend, PreparedLiveReplace, SessionGrantClearPolicy,
25    UnrestrictedPermissionedProcessRunnerFactory,
26};
27pub use baseline::{default_development_path_rules, default_development_path_rules_with_env};
28pub use browser_spawner::BrowserProcessSpawner;
29pub use callback_runner::{
30    CallbackBackgroundSupervisor, CallbackProcessExecutor, CallbackProcessOutput,
31    CallbackProcessRequest, CallbackProcessResponder, CallbackProcessRunner,
32    CallbackProcessTerminalStatus,
33};
34#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
35pub use confinement::BrowserSandboxProfile;
36pub use confinement::{probe_workspace_sandbox, sandbox_helper_main, sandbox_helper_requested};
37pub use gpg::GpgAgentSockets;
38pub use host_path::resolve_host_path;
39pub use host_resources::{HostPathKind, HostPathMetadata, ssh_known_hosts};
40
41pub use process_runner::{
42    DEFAULT_REMOVED_ENV_PREFIX, ProcessEnvIsolation, ProcessSessionPermissions, TokioProcessRunner,
43    action_process_path,
44};
45
46#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
47pub use process_runner::{
48    WorkspaceProcessEnvironment, WorkspaceProcessRunner, WorkspaceProcessRunnerFactory,
49};
50
51use merry_core::{CapabilityPolicy, HostPathPolicy};
52use merry_runtime::{
53    AcceptedLocalWorkspaceProcessAdmission, HostIntegration, PathAccess, PathAccessRule,
54    PathAccessRuleSource, PermissionedProcessRunnerFactory, ProcessRunner, ProcessRunnerError,
55    ProcessSessionPermissionView,
56};
57use std::{
58    ffi::OsString,
59    path::{Path, PathBuf},
60    sync::Arc,
61};
62use thiserror::Error;
63
64/// Semantic process backend behavior requested by an application surface.
65///
66/// The selected behavior is intentionally independent of the operating system.
67/// A platform backend may implement [`Isolated`](Self::Isolated) with its
68/// native mechanism or report that the behavior is unavailable; callers do not
69/// need to name Landlock, seccomp, or another concrete mechanism.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum ProcessBackendMode {
72    /// Run actions in the host process environment, subject to runtime policy.
73    Host,
74    /// Request the platform's isolated local-process behavior.
75    Isolated,
76}
77
78/// Errors raised while selecting or constructing a host-process backend.
79///
80/// Execution failures remain [`merry_runtime::ProcessRunnerError`]. This error
81/// belongs to the adapter layer because it also represents a platform backend
82/// that is not available for the requested semantic mode.
83#[derive(Debug, Error, Clone, PartialEq, Eq)]
84pub enum ProcessBackendError {
85    /// The concrete runner rejected its configuration.
86    #[error("process backend configuration failed: {source}")]
87    Runner {
88        /// The runner configuration failure.
89        #[source]
90        source: ProcessRunnerError,
91    },
92    /// The requested isolated behavior has no implementation on this target.
93    #[error(
94        "isolated local process backend is unavailable on target operating system `{target_os}`"
95    )]
96    UnsupportedIsolation {
97        /// Rust's target-operating-system identifier.
98        target_os: &'static str,
99    },
100}
101
102impl From<ProcessRunnerError> for ProcessBackendError {
103    fn from(source: ProcessRunnerError) -> Self {
104        Self::Runner { source }
105    }
106}
107
108/// One process execution boundary used by a runtime instance.
109///
110/// The admission and both runner capabilities are kept together so callers
111/// cannot accidentally pair a runner with a permission factory from another
112/// backend configuration. Child runtimes obtain their process session through
113/// [`ProcessBackend::new_session`] or [`ProcessBackend::new_session_with`],
114/// whose backend controls session isolation.
115#[derive(Clone)]
116pub struct ProcessSession {
117    admission: AcceptedLocalWorkspaceProcessAdmission,
118    runner: Arc<dyn ProcessRunner>,
119    permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
120    permission_view: Option<ProcessSessionPermissionView>,
121    session_permissions: Option<ProcessSessionPermissions>,
122    static_path_rules: Vec<PathAccessRule>,
123    workspace_writable: bool,
124    network_policy: CapabilityPolicy,
125    allowed_domains: Vec<String>,
126    browser_allow_local: bool,
127    live_policy: Option<merry_runtime::LivePolicyHandle>,
128    live_env_isolation: Option<Arc<std::sync::RwLock<ProcessEnvIsolation>>>,
129    env_isolation: ProcessEnvIsolation,
130}
131
132impl ProcessSession {
133    /// Creates a session from an explicit, trusted adapter boundary.
134    ///
135    /// Production callers should select [`LocalProcessBackend::new`] so the
136    /// admission, runner, and reviewed-action factory are produced by one
137    /// backend implementation. This constructor exists for adapters and
138    /// deterministic fixtures that already own all three components.
139    #[must_use]
140    pub fn from_parts(
141        admission: AcceptedLocalWorkspaceProcessAdmission,
142        runner: Arc<dyn ProcessRunner>,
143        permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
144    ) -> Self {
145        Self {
146            admission,
147            runner,
148            permissioned_factory,
149            permission_view: None,
150            session_permissions: None,
151            static_path_rules: Vec::new(),
152            workspace_writable: true,
153            network_policy: CapabilityPolicy::Ask,
154            allowed_domains: Vec::new(),
155            browser_allow_local: true,
156            live_policy: None,
157            live_env_isolation: None,
158            env_isolation: ProcessEnvIsolation::default(),
159        }
160    }
161
162    /// Attaches a read-only view of this session's retained permissions so child
163    /// runtimes may inherit already-approved ordinary capabilities without
164    /// mutating the parent session.
165    #[must_use]
166    pub fn with_permission_view(mut self, view: ProcessSessionPermissionView) -> Self {
167        self.permission_view = Some(view);
168        self
169    }
170
171    /// Attaches the shared session-scoped capability store owned by this session.
172    #[must_use]
173    pub fn with_session_permissions(mut self, permissions: ProcessSessionPermissions) -> Self {
174        self.permission_view = Some(permissions.view());
175        self.session_permissions = Some(permissions);
176        self
177    }
178
179    /// Attaches the static path rules and workspace writability backing this
180    /// session so in-process workspace tools share the same access policy.
181    #[must_use]
182    pub fn with_access_policy_inputs(
183        mut self,
184        static_path_rules: Vec<PathAccessRule>,
185        workspace_writable: bool,
186    ) -> Self {
187        self.static_path_rules = static_path_rules;
188        self.workspace_writable = workspace_writable;
189        self
190    }
191
192    /// Attaches static outbound network and browser-local policy inputs backing
193    /// this session so in-process web/browser tools share the same rules.
194    #[must_use]
195    pub fn with_network_policy_inputs(
196        mut self,
197        network_policy: CapabilityPolicy,
198        allowed_domains: Vec<String>,
199        browser_allow_local: bool,
200    ) -> Self {
201        self.network_policy = network_policy;
202        self.allowed_domains = allowed_domains;
203        self.browser_allow_local = browser_allow_local;
204        self
205    }
206
207    /// Attaches a unified single-lock [`merry_runtime::LivePolicyHandle`] shared
208    /// with a [`LiveProcessBackend`] so mid-session sandbox, path, protected-path,
209    /// and network changes update file tools, web/browser tools, and child
210    /// sessions atomically.
211    #[must_use]
212    pub fn with_live_policy(mut self, policy: merry_runtime::LivePolicyHandle) -> Self {
213        self.live_policy = Some(policy);
214        self
215    }
216
217    /// Attaches a live environment-isolation handle shared with a
218    /// [`LiveProcessBackend`] so browser spawns always observe the latest
219    /// isolated environment configuration.
220    #[must_use]
221    pub fn with_live_env_isolation(
222        mut self,
223        env_isolation: Arc<std::sync::RwLock<ProcessEnvIsolation>>,
224    ) -> Self {
225        self.live_env_isolation = Some(env_isolation);
226        self
227    }
228
229    /// Attaches the environment isolation policy stripped from browser and
230    /// child processes spawned under this session.
231    #[must_use]
232    pub fn with_env_isolation(mut self, env_isolation: ProcessEnvIsolation) -> Self {
233        self.env_isolation = env_isolation;
234        self
235    }
236
237    /// Returns whether writes inside the workspace are allowed by this session.
238    #[must_use]
239    pub const fn workspace_writable(&self) -> bool {
240        self.workspace_writable
241    }
242
243    /// Returns whether this session is backed by a live-swappable
244    /// [`merry_runtime::LivePolicyHandle`] (from [`LiveProcessBackend`]).
245    #[must_use]
246    pub fn has_live_policy(&self) -> bool {
247        self.live_policy.is_some()
248    }
249
250    /// Returns the static environment isolation configured on this session.
251    #[must_use]
252    pub fn env_isolation(&self) -> &ProcessEnvIsolation {
253        &self.env_isolation
254    }
255
256    /// Returns the runtime admission selected for this process boundary.
257    #[must_use]
258    pub const fn admission(&self) -> AcceptedLocalWorkspaceProcessAdmission {
259        self.admission
260    }
261
262    /// Returns the runner for ordinary process actions.
263    #[must_use]
264    pub fn runner(&self) -> Arc<dyn ProcessRunner> {
265        Arc::clone(&self.runner)
266    }
267
268    /// Returns the factory for reviewed process actions.
269    #[must_use]
270    pub fn permissioned_factory(&self) -> Arc<dyn PermissionedProcessRunnerFactory> {
271        Arc::clone(&self.permissioned_factory)
272    }
273
274    /// Returns a read-only view of capabilities retained by this session, when
275    /// backed by a session-scoped permission store.
276    #[must_use]
277    pub fn permission_view(&self) -> Option<ProcessSessionPermissionView> {
278        self.permission_view.clone()
279    }
280
281    /// Returns the shared session-scoped capability store, when backed by one.
282    #[must_use]
283    pub fn session_permissions(&self) -> Option<ProcessSessionPermissions> {
284        self.session_permissions.clone()
285    }
286
287    /// Builds a unified [`merry_runtime::WorkspaceAccessPolicy`] sharing this
288    /// session's static rules and live session-scoped grants.
289    #[must_use]
290    pub fn workspace_access_policy(
291        &self,
292        workspace_root: &Path,
293        workspace_writable: bool,
294    ) -> merry_runtime::WorkspaceAccessPolicy {
295        let mut policy = merry_runtime::WorkspaceAccessPolicy::new(
296            workspace_root,
297            self.workspace_writable && workspace_writable,
298        )
299        .with_static_rules(self.static_path_rules.iter().cloned());
300        if let Some(view) = self.permission_view.clone() {
301            policy = policy.with_session_permissions(view);
302        }
303        policy
304    }
305
306    /// Returns the unified single-lock [`merry_runtime::LivePolicyHandle`]
307    /// backing this session, synthesizing a static handle if this session was
308    /// not produced by [`LiveProcessBackend`].
309    #[must_use]
310    pub fn live_policy_handle(
311        &self,
312        workspace_root: &Path,
313        workspace_writable: bool,
314    ) -> merry_runtime::LivePolicyHandle {
315        if let Some(live) = &self.live_policy {
316            return live.clone();
317        }
318        let restricted = self.admission.sandbox_profile()
319            != merry_runtime::LocalWorkspaceProcessSandboxProfile::Host;
320        let workspace_access = restricted.then(|| {
321            merry_runtime::WorkspaceAccessPolicy::new(
322                workspace_root,
323                self.workspace_writable && workspace_writable,
324            )
325            .with_static_rules(self.static_path_rules.iter().cloned())
326        });
327        let baseline = merry_runtime::LivePolicyBaseline::new(
328            restricted,
329            workspace_access,
330            self.product_private_paths(),
331            self.network_access_policy(),
332        );
333        let mut handle = merry_runtime::LivePolicyHandle::new(baseline);
334        if let Some(view) = self.permission_view.clone() {
335            handle = handle.with_session_permissions(view);
336        }
337        handle
338    }
339
340    /// Builds a unified [`merry_runtime::NetworkAccessPolicy`] sharing this
341    /// session's configured `network` policy, `browser.allow_local`, workspace
342    /// `allowed_domains`, and live session-scoped domain/network grants.
343    #[must_use]
344    pub fn network_access_policy(&self) -> merry_runtime::NetworkAccessPolicy {
345        let mut policy =
346            merry_runtime::NetworkAccessPolicy::new(self.network_policy, self.browser_allow_local)
347                .with_allowed_domains(&self.allowed_domains);
348        if let Some(view) = self.permission_view.clone() {
349            policy = policy.with_session_permissions(view);
350        }
351        policy
352    }
353
354    /// Returns Merry built-in `ProductPrivate` paths (such as `providers/` and
355    /// `MERRY_API_KEY_FILE`) configured on this session.
356    #[must_use]
357    pub fn product_private_paths(&self) -> Vec<PathBuf> {
358        merry_runtime::extract_product_private_paths(&self.static_path_rules)
359    }
360
361    /// Creates a desktop headless browser spawner bound to this session's live
362    /// policy handle and environment isolation policy.
363    #[must_use]
364    pub fn browser_spawner(&self, workspace_root: impl Into<PathBuf>) -> BrowserProcessSpawner {
365        let workspace_root = workspace_root.into();
366        let live_policy = self.live_policy_handle(&workspace_root, self.workspace_writable);
367        let live_env = self
368            .live_env_isolation
369            .clone()
370            .unwrap_or_else(|| Arc::new(std::sync::RwLock::new(self.env_isolation.clone())));
371        BrowserProcessSpawner::new(live_policy, workspace_root, live_env)
372    }
373}
374
375/// Request options for deriving a scoped [`ProcessSession`] from a [`ProcessBackend`].
376#[derive(Debug, Clone)]
377pub struct ProcessSessionRequest {
378    pub(crate) workspace_root: Option<PathBuf>,
379    pub(crate) workspace_writable: bool,
380    pub(crate) inherited_permissions: Option<ProcessSessionPermissionView>,
381    pub(crate) extra_path_rules: Vec<PathAccessRule>,
382}
383
384impl Default for ProcessSessionRequest {
385    fn default() -> Self {
386        Self {
387            workspace_root: None,
388            workspace_writable: true,
389            inherited_permissions: None,
390            extra_path_rules: Vec::new(),
391        }
392    }
393}
394
395impl ProcessSessionRequest {
396    /// Creates a default session request inheriting the backend's workspace root
397    /// and writability.
398    #[must_use]
399    pub fn new() -> Self {
400        Self::default()
401    }
402
403    /// Overrides the workspace root directory for the new session (for example,
404    /// an isolated git worktree).
405    #[must_use]
406    pub fn with_workspace_root(mut self, workspace_root: impl Into<PathBuf>) -> Self {
407        self.workspace_root = Some(workspace_root.into());
408        self
409    }
410
411    /// Keeps the workspace readable and not writable for isolated actions in
412    /// this session.
413    #[must_use]
414    pub fn read_only_workspace(mut self) -> Self {
415        self.workspace_writable = false;
416        self
417    }
418
419    /// Sets whether isolated actions in this session may write inside the
420    /// workspace root.
421    ///
422    /// A request cannot widen a backend that was already configured read-only.
423    #[must_use]
424    pub fn with_workspace_writable(mut self, writable: bool) -> Self {
425        self.workspace_writable = writable;
426        self
427    }
428
429    /// Seeds the new session with a read-only snapshot of an existing session's
430    /// approved ordinary capabilities.
431    #[must_use]
432    pub fn with_inherited_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
433        self.inherited_permissions = Some(view);
434        self
435    }
436
437    /// Appends additional filesystem rules for the new session.
438    #[must_use]
439    pub fn with_extra_path_rules(
440        mut self,
441        rules: impl IntoIterator<Item = PathAccessRule>,
442    ) -> Self {
443        self.extra_path_rules = rules.into_iter().collect();
444        self
445    }
446
447    /// Returns the optional workspace root override.
448    #[must_use]
449    pub fn workspace_root(&self) -> Option<&Path> {
450        self.workspace_root.as_deref()
451    }
452
453    /// Returns whether the caller requested workspace writability.
454    #[must_use]
455    pub const fn workspace_writable(&self) -> bool {
456        self.workspace_writable
457    }
458
459    /// Returns the optional inherited permission view.
460    #[must_use]
461    pub fn inherited_permissions(&self) -> Option<&ProcessSessionPermissionView> {
462        self.inherited_permissions.as_ref()
463    }
464
465    /// Returns any extra filesystem access rules attached to this request.
466    #[must_use]
467    pub fn extra_path_rules(&self) -> &[PathAccessRule] {
468        &self.extra_path_rules
469    }
470}
471
472/// Stable host-process backend boundary consumed by coding composition.
473///
474/// The trait deliberately says nothing about how a platform enforces the
475/// selected behavior. Linux confines each action with Landlock and seccomp.
476/// Other targets report that isolation is unavailable instead of silently
477/// running on the host.
478pub trait ProcessBackend: Send + Sync {
479    /// Creates the process session for one runtime owner.
480    ///
481    /// Each call returns a session with the backend's configured admission and
482    /// runner capabilities. Backends may use a fresh session-scoped capability
483    /// store for every call, which keeps parent and child runtime state isolated.
484    fn new_session(&self) -> ProcessSession;
485
486    /// Creates a process session configured with scoped request options.
487    ///
488    /// The default implementation delegates to [`Self::new_session`] for custom
489    /// test or adapter backends that do not vary session parameters.
490    ///
491    /// # Errors
492    ///
493    /// Returns a [`ProcessBackendError`] when the requested workspace root,
494    /// sandbox rules, or inherited permissions cannot be validated.
495    fn new_session_with(
496        &self,
497        _request: ProcessSessionRequest,
498    ) -> Result<ProcessSession, ProcessBackendError> {
499        Ok(self.new_session())
500    }
501}
502
503/// Inputs shared by local process backend implementations.
504#[derive(Debug, Clone)]
505pub struct ProcessBackendOptions {
506    /// Trusted filesystem rules installed for isolated actions.
507    pub(crate) path_rules: Vec<PathAccessRule>,
508    /// Three-state policy for outbound network capability (`deny`, `ask`, `allow`).
509    pub(crate) network_policy: CapabilityPolicy,
510    /// Workspace-persisted exact external hostnames allowed for web/browser tools.
511    pub(crate) allowed_domains: Vec<String>,
512    /// Whether explicit local loopback/data browser targets are allowed without review.
513    pub(crate) browser_allow_local: bool,
514    /// When false, the workspace itself is readable and not writable.
515    pub(crate) workspace_writable: bool,
516    /// Host integrations pre-authorized (`allow`) by the embedding application.
517    pub(crate) host_integrations: Vec<HostIntegration>,
518    /// Host integrations hard-blocked (`deny`) by the embedding application.
519    pub(crate) denied_host_integrations: Vec<HostIntegration>,
520    pub(crate) gpg_agent_sockets: Option<GpgAgentSockets>,
521    /// Environment assignments validated and applied by the host backend.
522    pub(crate) environment_overrides: Vec<(OsString, OsString)>,
523    /// Environment variable isolation policy stripped from every child process.
524    pub(crate) env_isolation: ProcessEnvIsolation,
525}
526
527impl Default for ProcessBackendOptions {
528    fn default() -> Self {
529        Self {
530            path_rules: Vec::new(),
531            network_policy: CapabilityPolicy::Ask,
532            allowed_domains: Vec::new(),
533            browser_allow_local: true,
534            workspace_writable: true,
535            host_integrations: Vec::new(),
536            denied_host_integrations: Vec::new(),
537            gpg_agent_sockets: None,
538            environment_overrides: Vec::new(),
539            env_isolation: ProcessEnvIsolation::default(),
540        }
541    }
542}
543
544impl ProcessBackendOptions {
545    /// Creates default options without preauthorized process capabilities.
546    #[must_use]
547    pub fn new() -> Self {
548        Self::default()
549    }
550
551    /// Sets trusted filesystem rules installed for isolated actions.
552    #[must_use]
553    pub fn with_path_rules(mut self, path_rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
554        self.path_rules = path_rules.into_iter().collect();
555        self
556    }
557
558    /// Appends filesystem rules installed for isolated actions.
559    #[must_use]
560    pub fn extend_path_rules(
561        mut self,
562        path_rules: impl IntoIterator<Item = PathAccessRule>,
563    ) -> Self {
564        self.path_rules.extend(path_rules);
565        self
566    }
567
568    /// Appends the default local development toolchain and cache baseline rules.
569    #[must_use]
570    pub fn with_default_development_baseline(self, home: &Path) -> Self {
571        self.extend_path_rules(default_development_path_rules(home))
572    }
573
574    /// Appends Merry's product path rules from the shared [`HostPathPolicy`]
575    /// contract (writable config/skills, writable durable memory, read-only
576    /// state/history, and denied private credentials).
577    #[must_use]
578    pub fn with_host_path_policy(mut self, policy: &HostPathPolicy) -> Self {
579        for path in policy.product_writable_config() {
580            self.path_rules.push(PathAccessRule::new(
581                path.clone(),
582                PathAccess::ReadWrite,
583                PathAccessRuleSource::ProductConfig,
584            ));
585        }
586        if let Some(memory_root) = policy.durable_memory_root() {
587            self.path_rules.push(PathAccessRule::new(
588                memory_root.to_path_buf(),
589                PathAccess::ReadWrite,
590                PathAccessRuleSource::DurableMemory,
591            ));
592        }
593        for path in policy.product_readonly() {
594            self.path_rules.push(PathAccessRule::new(
595                path.clone(),
596                PathAccess::ReadOnly,
597                PathAccessRuleSource::ProductReadOnly,
598            ));
599        }
600        for path in policy.denied() {
601            self.path_rules.push(PathAccessRule::new(
602                path.clone(),
603                PathAccess::Deny,
604                PathAccessRuleSource::ProductPrivate,
605            ));
606        }
607        self
608    }
609
610    /// Sets the three-state network policy (`deny`, `ask`, or `allow`).
611    #[must_use]
612    pub fn with_network_policy(mut self, policy: CapabilityPolicy) -> Self {
613        self.network_policy = policy;
614        self
615    }
616
617    /// Sets workspace-persisted exact allowed domains for web/browser tools.
618    #[must_use]
619    pub fn with_allowed_domains<I, S>(mut self, domains: I) -> Self
620    where
621        I: IntoIterator<Item = S>,
622        S: Into<String>,
623    {
624        self.allowed_domains = domains.into_iter().map(Into::into).collect();
625        self
626    }
627
628    /// Sets whether explicit local browser targets (`localhost`, `127.0.0.1`,
629    /// `::1`, `data:text/html`) are permitted without permission review.
630    #[must_use]
631    pub fn with_browser_allow_local(mut self, allow_local: bool) -> Self {
632        self.browser_allow_local = allow_local;
633        self
634    }
635
636    /// Sets whether isolated process sessions may request network capability.
637    ///
638    /// `true` maps to [`CapabilityPolicy::Ask`]; `false` maps to
639    /// [`CapabilityPolicy::Deny`]. Use [`Self::with_network_policy`] to
640    /// pre-authorize network via [`CapabilityPolicy::Allow`].
641    #[must_use]
642    pub fn with_network_requests_allowed(mut self, allowed: bool) -> Self {
643        self.network_policy = if allowed {
644            CapabilityPolicy::Ask
645        } else {
646            CapabilityPolicy::Deny
647        };
648        self
649    }
650
651    /// Keeps the workspace readable and not writable for isolated actions.
652    ///
653    /// Baseline paths such as `/tmp` stay writable. Host execution ignores this.
654    #[must_use]
655    pub fn read_only_workspace(mut self) -> Self {
656        self.workspace_writable = false;
657        self
658    }
659
660    /// Sets host integrations pre-authorized (`allow`) by the embedding application.
661    #[must_use]
662    pub fn with_host_integrations(
663        mut self,
664        host_integrations: impl IntoIterator<Item = HostIntegration>,
665    ) -> Self {
666        self.host_integrations = host_integrations.into_iter().collect();
667        self.denied_host_integrations
668            .retain(|denied| !self.host_integrations.contains(denied));
669        self
670    }
671
672    /// Sets host integrations hard-denied (`deny`) by the embedding application.
673    #[must_use]
674    pub fn with_denied_host_integrations(
675        mut self,
676        denied: impl IntoIterator<Item = HostIntegration>,
677    ) -> Self {
678        self.denied_host_integrations = denied.into_iter().collect();
679        self.host_integrations
680            .retain(|allowed| !self.denied_host_integrations.contains(allowed));
681        self
682    }
683
684    /// Sets the three-state policy for one host integration (`deny`, `ask`, `allow`).
685    #[must_use]
686    pub fn with_host_integration_policy(
687        mut self,
688        integration: HostIntegration,
689        policy: CapabilityPolicy,
690    ) -> Self {
691        self.host_integrations.retain(|item| *item != integration);
692        self.denied_host_integrations
693            .retain(|item| *item != integration);
694        match policy {
695            CapabilityPolicy::Allow => self.host_integrations.push(integration),
696            CapabilityPolicy::Deny => self.denied_host_integrations.push(integration),
697            CapabilityPolicy::Ask => {}
698        }
699        self
700    }
701
702    /// Installs explicitly discovered native and auxiliary GnuPG socket paths.
703    #[must_use]
704    pub fn with_gpg_agent_sockets(mut self, sockets: GpgAgentSockets) -> Self {
705        self.gpg_agent_sockets = Some(sockets);
706        self
707    }
708
709    /// Sets environment assignments that the backend validates before applying.
710    #[must_use]
711    pub fn with_environment_overrides(
712        mut self,
713        environment_overrides: impl IntoIterator<Item = (OsString, OsString)>,
714    ) -> Self {
715        self.environment_overrides = environment_overrides.into_iter().collect();
716        self
717    }
718
719    /// Replaces the environment-variable isolation policy enforced across
720    /// both isolated and host process runners.
721    #[must_use]
722    pub fn with_env_isolation(mut self, env_isolation: ProcessEnvIsolation) -> Self {
723        self.env_isolation = env_isolation;
724        self
725    }
726
727    /// Returns the trusted filesystem rules installed for isolated actions.
728    #[must_use]
729    pub fn path_rules(&self) -> &[PathAccessRule] {
730        &self.path_rules
731    }
732
733    /// Returns the configured three-state network policy.
734    #[must_use]
735    pub const fn network_policy(&self) -> CapabilityPolicy {
736        self.network_policy
737    }
738
739    /// Returns workspace-persisted allowed domains for web/browser tools.
740    #[must_use]
741    pub fn allowed_domains(&self) -> &[String] {
742        &self.allowed_domains
743    }
744
745    /// Returns whether local browser targets are allowed without review.
746    #[must_use]
747    pub const fn browser_allow_local(&self) -> bool {
748        self.browser_allow_local
749    }
750
751    /// Returns whether isolated sessions allow network requests (`ask` or `allow`).
752    #[must_use]
753    pub const fn network_requests_allowed(&self) -> bool {
754        self.network_policy.allows_requests()
755    }
756
757    /// Returns host integrations already approved by the embedding application.
758    #[must_use]
759    pub fn host_integrations(&self) -> &[HostIntegration] {
760        &self.host_integrations
761    }
762
763    /// Returns host integrations hard-denied by the embedding application.
764    #[must_use]
765    pub fn denied_host_integrations(&self) -> &[HostIntegration] {
766        &self.denied_host_integrations
767    }
768
769    /// Returns the validated environment assignments applied by the backend.
770    #[must_use]
771    pub fn environment_overrides(&self) -> &[(OsString, OsString)] {
772        &self.environment_overrides
773    }
774}
775
776#[cfg(test)]
777mod tests;