use super::validation::{
ProcessActionError, summarize_intent, validate_argv, validate_captured_bytes, validate_cwd,
validate_output_limit, validate_stdin_text, validate_timeout_secs,
};
use super::{BackgroundProcessControl, BackgroundProcessId};
use crate::{PermissionRequest, RequestedCapability};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{fmt, future::Future, pin::Pin, sync::Arc};
use thiserror::Error;
use tokio_util::sync::CancellationToken;
pub const MAX_PROCESS_ARG_BYTES: usize = 64 * 1024;
pub const MAX_PROCESS_ARGV_ITEMS: usize = 256;
pub const MAX_PROCESS_CWD_BYTES: usize = 4096;
pub const MAX_PROCESS_STDIN_TEXT_BYTES: usize = 64 * 1024;
pub const MAX_PROCESS_OUTPUT_LIMIT_BYTES: usize = 1024 * 1024;
pub const DEFAULT_PROCESS_WAIT_TIMEOUT_SECS: u64 = 120;
pub const MAX_PROCESS_WAIT_TIMEOUT_SECS: u64 = 3600;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProcessEnvPolicy {
#[default]
Empty,
#[cfg(test)]
NonEmptyForTest,
}
impl ProcessEnvPolicy {
#[must_use]
pub const fn empty() -> Self {
Self::Empty
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AcceptedLocalWorkspaceProcessAdmission {
sandbox_profile: LocalWorkspaceProcessSandboxProfile,
permission_profile_id: ProcessPermissionProfileId,
}
impl AcceptedLocalWorkspaceProcessAdmission {
#[must_use]
pub const fn accept_local_workspace() -> Self {
Self {
sandbox_profile: LocalWorkspaceProcessSandboxProfile::LocalWorkspace,
permission_profile_id: ProcessPermissionProfileId::LOCAL_WORKSPACE,
}
}
#[must_use]
pub const fn accept_host() -> Self {
Self {
sandbox_profile: LocalWorkspaceProcessSandboxProfile::Host,
permission_profile_id: ProcessPermissionProfileId::LOCAL_WORKSPACE_HOST,
}
}
#[cfg(test)]
pub(crate) const fn for_test_permission_profile_id(
permission_profile_id: ProcessPermissionProfileId,
) -> Self {
Self {
sandbox_profile: LocalWorkspaceProcessSandboxProfile::LocalWorkspace,
permission_profile_id,
}
}
#[must_use]
pub const fn sandbox_profile(self) -> LocalWorkspaceProcessSandboxProfile {
self.sandbox_profile
}
#[must_use]
pub const fn permission_profile_id(self) -> ProcessPermissionProfileId {
self.permission_profile_id
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LocalWorkspaceProcessSandboxProfile {
LocalWorkspace,
Host,
}
impl LocalWorkspaceProcessSandboxProfile {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::LocalWorkspace => "local-workspace",
Self::Host => "host",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ProcessPermissionProfileId(&'static str);
impl ProcessPermissionProfileId {
pub const READ_ONLY: Self = Self("process.read_only");
pub const LOCAL_WORKSPACE: Self = Self("process.local_workspace");
pub const LOCAL_WORKSPACE_HOST: Self = Self("process.local_workspace.host");
pub const SHELL_READ_ONLY: Self = Self("process.shell.read_only");
pub const APPROVED_PERMISSION_REQUEST: Self = Self("process.permission_request.approved");
#[must_use]
pub const fn as_str(self) -> &'static str {
self.0
}
}
impl Serialize for ProcessPermissionProfileId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str((*self).as_str())
}
}
impl<'de> Deserialize<'de> for ProcessPermissionProfileId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
match value.as_str() {
"process.read_only" => Ok(Self::READ_ONLY),
"process.local_workspace" => Ok(Self::LOCAL_WORKSPACE),
"process.local_workspace.host" => Ok(Self::LOCAL_WORKSPACE_HOST),
"process.shell.read_only" => Ok(Self::SHELL_READ_ONLY),
"process.permission_request.approved" => Ok(Self::APPROVED_PERMISSION_REQUEST),
_ => Err(serde::de::Error::custom(format!(
"unsupported process permission profile id `{value}`"
))),
}
}
}
impl fmt::Display for ProcessPermissionProfileId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
pub type ProcessRunnerFuture<'a> = Pin<Box<dyn Future<Output = ProcessRunnerResult> + Send + 'a>>;
pub type ProcessRunnerResult = Result<ProcessRunnerOutput, ProcessRunnerError>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcessOutputChunk {
pub call_id: merry_core::ToolCallId,
pub stream: merry_core::ToolOutputStream,
pub delta: String,
}
#[derive(Debug, Clone)]
pub struct ProcessOutputSink {
call_id: merry_core::ToolCallId,
sender: tokio::sync::mpsc::Sender<ProcessOutputChunk>,
}
impl ProcessOutputSink {
#[must_use]
pub fn new(
call_id: merry_core::ToolCallId,
sender: tokio::sync::mpsc::Sender<ProcessOutputChunk>,
) -> Self {
Self { call_id, sender }
}
pub fn emit(&self, stream: merry_core::ToolOutputStream, bytes: &[u8]) {
if bytes.is_empty() {
return;
}
const MAX_LIVE_CHUNK_BYTES: usize = 4096;
let slice = &bytes[..bytes.len().min(MAX_LIVE_CHUNK_BYTES)];
let delta = String::from_utf8_lossy(slice).into_owned();
let _ = self.sender.try_send(ProcessOutputChunk {
call_id: self.call_id.clone(),
stream,
delta,
});
}
}
#[derive(Debug, Clone, Default)]
pub struct ProcessRunnerContext {
cancellation_token: CancellationToken,
output_sink: Option<ProcessOutputSink>,
}
impl ProcessRunnerContext {
#[must_use]
pub fn new(cancellation_token: CancellationToken) -> Self {
Self {
cancellation_token,
output_sink: None,
}
}
#[must_use]
pub fn with_output_sink(mut self, sink: ProcessOutputSink) -> Self {
self.output_sink = Some(sink);
self
}
#[must_use]
pub fn cancellation_token(&self) -> &CancellationToken {
&self.cancellation_token
}
#[must_use]
pub fn output_sink(&self) -> Option<&ProcessOutputSink> {
self.output_sink.as_ref()
}
}
pub trait ProcessRunner: Send + Sync {
fn run<'a>(
&'a self,
intent: ProcessActionIntent,
context: ProcessRunnerContext,
) -> ProcessRunnerFuture<'a>;
fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
None
}
}
pub trait PermissionedProcessRunnerFactory: Send + Sync {
fn validate_request(&self, _request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
Ok(())
}
fn request_capabilities_are_satisfied(
&self,
_request: &PermissionRequest,
) -> Result<bool, ProcessRunnerError> {
Ok(false)
}
fn targets_protected_metadata(&self, _request: &PermissionRequest) -> bool {
false
}
fn prepare_approved_request(
&self,
request: &PermissionRequest,
) -> Result<super::PreparedProcessPermission, ProcessRunnerError> {
self.validate_request(request)?;
Ok(super::PreparedProcessPermission::new(
self.runner_for(request),
Vec::new(),
))
}
fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner>;
fn runner_for_decision(
&self,
request: &PermissionRequest,
_scope: merry_core::ApprovalScope,
) -> Arc<dyn ProcessRunner> {
self.runner_for(request)
}
}
#[derive(Clone)]
pub struct StaticPermissionedProcessRunnerFactory {
runner: Arc<dyn ProcessRunner>,
}
impl StaticPermissionedProcessRunnerFactory {
#[must_use]
pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
Self { runner }
}
}
impl PermissionedProcessRunnerFactory for StaticPermissionedProcessRunnerFactory {
fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
if request
.requested()
.iter()
.any(|capability| matches!(capability, RequestedCapability::Path(_)))
{
return Err(ProcessRunnerError::infrastructure(
"static permissioned process runner cannot enforce requested path capabilities",
));
}
if request
.requested()
.iter()
.any(|capability| matches!(capability, RequestedCapability::HostIntegration(_)))
{
return Err(ProcessRunnerError::infrastructure(
"static permissioned process runner cannot enforce requested host integrations",
));
}
Ok(())
}
fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
Arc::clone(&self.runner)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProcessActionIntent {
summary: String,
argv: Vec<String>,
cwd: Option<String>,
env_policy: ProcessEnvPolicy,
stdin_text: Option<String>,
stdout_limit_bytes: usize,
stderr_limit_bytes: usize,
#[serde(default)]
background: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
timeout_secs: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
display_name: Option<String>,
}
impl ProcessActionIntent {
pub fn new(
argv: Vec<String>,
cwd: Option<String>,
env_policy: ProcessEnvPolicy,
stdin_text: Option<String>,
stdout_limit_bytes: usize,
stderr_limit_bytes: usize,
) -> Result<Self, ProcessActionError> {
validate_argv(&argv)?;
let cwd = validate_cwd(cwd)?;
validate_stdin_text(stdin_text.as_deref())?;
validate_output_limit("stdout_limit_bytes", stdout_limit_bytes)?;
validate_output_limit("stderr_limit_bytes", stderr_limit_bytes)?;
let summary = summarize_intent(&argv, cwd.as_deref());
Ok(Self {
summary,
argv,
cwd,
env_policy,
stdin_text,
stdout_limit_bytes,
stderr_limit_bytes,
background: false,
timeout_secs: None,
display_name: None,
})
}
#[must_use]
pub fn with_background(mut self, background: bool) -> Self {
self.background = background;
self
}
pub fn with_timeout_secs(
mut self,
timeout_secs: Option<u64>,
) -> Result<Self, ProcessActionError> {
self.timeout_secs = validate_timeout_secs(timeout_secs)?;
Ok(self)
}
#[must_use]
pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
self.display_name = display_name.and_then(|value| {
let normalized = value.split_whitespace().collect::<Vec<_>>().join(" ");
if normalized.is_empty() {
None
} else {
Some(normalized.chars().take(80).collect())
}
});
self
}
#[must_use]
pub fn summary(&self) -> &str {
&self.summary
}
#[must_use]
pub fn argv(&self) -> &[String] {
&self.argv
}
#[must_use]
pub fn cwd(&self) -> Option<&str> {
self.cwd.as_deref()
}
#[must_use]
pub const fn env_policy(&self) -> ProcessEnvPolicy {
self.env_policy
}
#[must_use]
pub fn stdin_text(&self) -> Option<&str> {
self.stdin_text.as_deref()
}
#[must_use]
pub const fn background(&self) -> bool {
self.background
}
#[must_use]
pub const fn timeout_secs(&self) -> Option<u64> {
self.timeout_secs
}
#[must_use]
pub const fn effective_wait_timeout_secs(&self) -> u64 {
match self.timeout_secs {
Some(secs) => secs,
None => DEFAULT_PROCESS_WAIT_TIMEOUT_SECS,
}
}
#[must_use]
pub fn display_name(&self) -> Option<&str> {
self.display_name.as_deref()
}
#[must_use]
pub const fn stdout_limit_bytes(&self) -> usize {
self.stdout_limit_bytes
}
#[must_use]
pub const fn stderr_limit_bytes(&self) -> usize {
self.stderr_limit_bytes
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcessRunnerOutput {
status: ProcessExitStatus,
stdout_data: Vec<u8>,
stdout_text: String,
stdout_bytes: usize,
stdout_truncated: bool,
stderr_data: Vec<u8>,
stderr_text: String,
stderr_bytes: usize,
stderr_truncated: bool,
running_pid: Option<u32>,
background_process_id: Option<BackgroundProcessId>,
wait_timed_out_secs: Option<u64>,
}
impl ProcessRunnerOutput {
pub fn new(
intent: &ProcessActionIntent,
status: ProcessExitStatus,
stdout_text: impl Into<String>,
stdout_truncated: bool,
stderr_text: impl Into<String>,
stderr_truncated: bool,
) -> Result<Self, ProcessActionError> {
Self::from_bytes(
intent,
status,
stdout_text.into().into_bytes(),
stdout_truncated,
stderr_text.into().into_bytes(),
stderr_truncated,
)
}
pub fn from_bytes(
intent: &ProcessActionIntent,
status: ProcessExitStatus,
stdout_data: Vec<u8>,
stdout_truncated: bool,
stderr_data: Vec<u8>,
stderr_truncated: bool,
) -> Result<Self, ProcessActionError> {
validate_captured_bytes(
"stdout_bytes",
stdout_data.len(),
intent.stdout_limit_bytes(),
)?;
validate_captured_bytes(
"stderr_bytes",
stderr_data.len(),
intent.stderr_limit_bytes(),
)?;
Ok(Self {
status,
stdout_text: String::from_utf8_lossy(&stdout_data).into_owned(),
stdout_bytes: stdout_data.len(),
stdout_data,
stdout_truncated,
stderr_text: String::from_utf8_lossy(&stderr_data).into_owned(),
stderr_bytes: stderr_data.len(),
stderr_data,
stderr_truncated,
running_pid: None,
background_process_id: None,
wait_timed_out_secs: None,
})
}
#[must_use]
pub fn with_running_pid(mut self, pid: u32) -> Self {
self.running_pid = Some(pid);
self
}
#[must_use]
pub fn with_background_process_id(mut self, id: BackgroundProcessId) -> Self {
self.background_process_id = Some(id);
self
}
#[must_use]
pub fn with_wait_timed_out_secs(mut self, secs: u64) -> Self {
self.wait_timed_out_secs = Some(secs);
self
}
#[must_use]
pub const fn status(&self) -> ProcessExitStatus {
self.status
}
#[must_use]
pub fn stdout_text(&self) -> &str {
&self.stdout_text
}
#[must_use]
pub fn stdout_data(&self) -> &[u8] {
&self.stdout_data
}
#[must_use]
pub fn stdout_is_utf8(&self) -> bool {
std::str::from_utf8(&self.stdout_data).is_ok()
}
#[must_use]
pub const fn stdout_bytes(&self) -> usize {
self.stdout_bytes
}
#[must_use]
pub const fn stdout_truncated(&self) -> bool {
self.stdout_truncated
}
#[must_use]
pub fn stderr_text(&self) -> &str {
&self.stderr_text
}
#[must_use]
pub fn stderr_data(&self) -> &[u8] {
&self.stderr_data
}
#[must_use]
pub fn stderr_is_utf8(&self) -> bool {
std::str::from_utf8(&self.stderr_data).is_ok()
}
#[must_use]
pub const fn stderr_bytes(&self) -> usize {
self.stderr_bytes
}
#[must_use]
pub const fn stderr_truncated(&self) -> bool {
self.stderr_truncated
}
#[must_use]
pub const fn running_pid(&self) -> Option<u32> {
self.running_pid
}
#[must_use]
pub fn background_process_id(&self) -> Option<&BackgroundProcessId> {
self.background_process_id.as_ref()
}
#[must_use]
pub const fn wait_timed_out_secs(&self) -> Option<u64> {
self.wait_timed_out_secs
}
#[must_use]
pub const fn ok(&self) -> bool {
matches!(
self.status,
ProcessExitStatus::Exited(0) | ProcessExitStatus::Running
)
}
pub fn execution_evidence(
&self,
intent: &ProcessActionIntent,
permission_profile_id: ProcessPermissionProfileId,
) -> Result<ProcessExecutionEvidence, ProcessActionError> {
ProcessExecutionEvidence::new(
intent,
permission_profile_id,
self.status,
self.stdout_bytes,
self.stdout_truncated,
self.stderr_bytes,
self.stderr_truncated,
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProcessExitStatus {
Exited(i32),
Cancelled,
FailedToStart,
DomainFailed,
Running,
}
impl ProcessExitStatus {
#[must_use]
pub const fn exit_code(self) -> Option<i32> {
match self {
Self::Exited(code) => Some(code),
Self::Cancelled | Self::FailedToStart | Self::DomainFailed | Self::Running => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum ProcessRunnerError {
#[error("process runner cancelled")]
Cancelled,
#[error("process runner infrastructure error: {message}")]
Infrastructure {
message: String,
},
}
impl ProcessRunnerError {
#[must_use]
pub fn infrastructure(message: impl Into<String>) -> Self {
Self::Infrastructure {
message: message.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProcessExecutionEvidence {
intent_summary: String,
argv: Vec<String>,
cwd: Option<String>,
permission_profile_id: ProcessPermissionProfileId,
status: ProcessExitStatus,
stdout_bytes: usize,
stdout_truncated: bool,
stderr_bytes: usize,
stderr_truncated: bool,
}
impl ProcessExecutionEvidence {
pub fn new(
intent: &ProcessActionIntent,
permission_profile_id: ProcessPermissionProfileId,
status: ProcessExitStatus,
stdout_bytes: usize,
stdout_truncated: bool,
stderr_bytes: usize,
stderr_truncated: bool,
) -> Result<Self, ProcessActionError> {
validate_captured_bytes("stdout_bytes", stdout_bytes, intent.stdout_limit_bytes())?;
validate_captured_bytes("stderr_bytes", stderr_bytes, intent.stderr_limit_bytes())?;
Ok(Self {
intent_summary: intent.summary().to_owned(),
argv: intent.argv().to_vec(),
cwd: intent.cwd().map(str::to_owned),
permission_profile_id,
status,
stdout_bytes,
stdout_truncated,
stderr_bytes,
stderr_truncated,
})
}
#[must_use]
pub fn intent_summary(&self) -> &str {
&self.intent_summary
}
#[must_use]
pub fn argv(&self) -> &[String] {
&self.argv
}
#[must_use]
pub fn cwd(&self) -> Option<&str> {
self.cwd.as_deref()
}
#[must_use]
pub const fn permission_profile_id(&self) -> ProcessPermissionProfileId {
self.permission_profile_id
}
#[must_use]
pub const fn status(&self) -> ProcessExitStatus {
self.status
}
#[must_use]
pub const fn exit_code(&self) -> Option<i32> {
self.status.exit_code()
}
#[must_use]
pub const fn stdout_bytes(&self) -> usize {
self.stdout_bytes
}
#[must_use]
pub const fn stdout_truncated(&self) -> bool {
self.stdout_truncated
}
#[must_use]
pub const fn stderr_bytes(&self) -> usize {
self.stderr_bytes
}
#[must_use]
pub const fn stderr_truncated(&self) -> bool {
self.stderr_truncated
}
pub(crate) fn matches_intent(&self, intent: &ProcessActionIntent) -> bool {
self.intent_summary == intent.summary()
&& self.argv == intent.argv()
&& self.cwd.as_deref() == intent.cwd()
&& self.stdout_bytes <= intent.stdout_limit_bytes()
&& self.stderr_bytes <= intent.stderr_limit_bytes()
}
}