Skip to main content

merry_runtime/
process_tool.rs

1//! Runtime-owned process command tool registration helper.
2//!
3//! This module exposes a small provider-neutral tool that turns a model
4//! supplied shell command into [`crate::ProcessActionIntent`] proposal
5//! evidence. It never spawns a process itself; execution remains owned by the
6//! runtime process policy and injected [`crate::ProcessRunner`] lanes.
7
8use crate::{
9    ActionProposal, ActionProposalEvidence, MAX_PROCESS_ARG_BYTES, MAX_PROCESS_WAIT_TIMEOUT_SECS,
10    ProcessActionIntent, ProcessEnvPolicy, RegisteredTool, ToolActionKind, ToolActionPreflight,
11    ToolActionProposalFuture, ToolExecutionContext, ToolExecutionError, ToolExecutionOutcome,
12    ToolExecutor, ToolExecutorFuture,
13    permission::{
14        RequestedCapabilitiesInput, permission_reason_schema_for_schemars,
15        process_cwd_schema_for_schemars, requested_capabilities_schema_for_schemars,
16    },
17    process::shell_command_argv,
18    tool_input::deserialize_non_empty_process_command,
19};
20use merry_core::{CoreError, ErrorInfo, PendingToolCall, ToolName};
21use merry_tools_macros::tool;
22use schemars::JsonSchema;
23use serde::Deserialize;
24use serde_json::json;
25use std::sync::Arc;
26use thiserror::Error;
27
28const DEFAULT_PROCESS_TOOL_STDOUT_LIMIT_BYTES: usize = 64 * 1024;
29const DEFAULT_PROCESS_TOOL_STDERR_LIMIT_BYTES: usize = 64 * 1024;
30
31#[tool(
32    crate = "crate",
33    name = "run_process",
34    description = "Run a validated shell command through the runtime process policy."
35)]
36#[derive(Debug, JsonSchema)]
37struct ProcessCommandInput {
38    #[schemars(
39        description = "Shell command to execute. Newline and tab are allowed; other control characters are rejected. JSON strings must escape embedded control characters.",
40        length(min = 1, max = MAX_PROCESS_ARG_BYTES)
41    )]
42    command: String,
43    #[schemars(
44        schema_with = "process_cwd_schema_for_schemars",
45        description = "Optional workspace-relative working directory. Omit it, use \".\", or use null for the current workspace directory; an empty string is accepted as the same root default for compatibility."
46    )]
47    #[serde(default)]
48    cwd: String,
49    #[schemars(
50        schema_with = "permission_reason_schema_for_schemars",
51        description = "Optional short explanation of why the current task needs the requested capability. Use it only together with permissions."
52    )]
53    #[serde(default)]
54    reason: Option<String>,
55    #[schemars(schema_with = "requested_capabilities_schema_for_schemars")]
56    #[serde(default)]
57    permissions: Option<RequestedCapabilitiesInput>,
58    #[schemars(
59        description = "When true, return once the command is still running, include its id, and keep it until stop_background_process or this session ends. Use it for a GUI or a server. The default waits until the command exits or hits timeout_secs. Do not background the command in the shell instead."
60    )]
61    #[serde(default)]
62    background: bool,
63    #[schemars(
64        description = "Optional foreground wait timeout in seconds (1..=3600, default 120). Set this higher for intentionally slow finite commands (such as full builds, test suites, or large downloads). If the command is still running when this timeout elapses, it is NOT killed; Merry retains it in the background and returns its id and partial output so you can observe progress with read_background_process or terminate it with stop_background_process. Ignored when background is true.",
65        range(min = 1, max = MAX_PROCESS_WAIT_TIMEOUT_SECS)
66    )]
67    #[serde(default)]
68    timeout_secs: Option<u64>,
69    #[schemars(
70        description = "Optional short human-readable display name for a backgrounded process (recommended when background is true, e.g. \"web api server\" or \"dev watcher\"). If omitted and a foreground command hands off on timeout, Merry derives a short fallback label."
71    )]
72    #[serde(default)]
73    display_name: Option<String>,
74}
75
76#[derive(Debug, Deserialize)]
77#[serde(deny_unknown_fields)]
78struct ProcessCommandInputWire {
79    #[serde(deserialize_with = "deserialize_non_empty_process_command")]
80    command: String,
81    #[serde(default)]
82    cwd: Option<String>,
83    #[serde(default)]
84    reason: Option<String>,
85    #[serde(default)]
86    permissions: Option<RequestedCapabilitiesInput>,
87    #[serde(default)]
88    background: bool,
89    #[serde(default)]
90    timeout_secs: Option<u64>,
91    #[serde(default)]
92    display_name: Option<String>,
93}
94
95impl<'de> Deserialize<'de> for ProcessCommandInput {
96    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
97    where
98        D: serde::Deserializer<'de>,
99    {
100        let input = ProcessCommandInputWire::deserialize(deserializer)?;
101        Ok(Self {
102            command: input.command,
103            cwd: input.cwd.unwrap_or_default(),
104            reason: input.reason,
105            permissions: input.permissions,
106            background: input.background,
107            timeout_secs: input.timeout_secs,
108            display_name: input.display_name,
109        })
110    }
111}
112
113/// Errors raised while constructing the runtime-owned process command tool.
114#[derive(Debug, Error)]
115pub enum ProcessCommandToolError {
116    /// A Merry core protocol value rejected the tool definition.
117    #[error(transparent)]
118    Core {
119        /// Source core validation error.
120        #[from]
121        source: CoreError,
122    },
123}
124
125/// Creates a registered process command tool for runtime agent loops.
126///
127/// The provider-visible tool accepts a JSON object with a shell `command`,
128/// nullable workspace-relative `cwd`, and optional capabilities to request
129/// before execution. The returned registered tool is a `CommandExec` action
130/// with proposal evidence enabled, so admitted execution goes through runtime
131/// process policy and an injected [`crate::ProcessRunner`].
132pub fn process_command_tool(
133    name: ToolName,
134    description: &str,
135) -> Result<RegisteredTool, ProcessCommandToolError> {
136    let spec =
137        ProcessCommandInput::tool_spec_with(name.as_str(), description).map_err(|error| {
138            ProcessCommandToolError::Core {
139                source: error.into(),
140            }
141        })?;
142    Ok(RegisteredTool::new(
143        spec,
144        Arc::new(ProcessCommandToolExecutor),
145        ToolActionKind::CommandExec,
146    )
147    .with_action_proposal()
148    .with_parallel_safe_execution())
149}
150
151pub(crate) fn process_call_requests_permission(call: &PendingToolCall) -> bool {
152    let arguments = call.arguments().as_object();
153    arguments
154        .get("permissions")
155        .is_some_and(|permissions| !permissions.is_null())
156        || arguments
157            .get("reason")
158            .is_some_and(|reason| !reason.is_null())
159}
160
161#[derive(Debug)]
162struct ProcessCommandToolExecutor;
163
164impl ToolExecutor for ProcessCommandToolExecutor {
165    fn propose<'a>(
166        &'a self,
167        call: PendingToolCall,
168        _context: ToolExecutionContext,
169    ) -> ToolActionProposalFuture<'a> {
170        Box::pin(async move {
171            let intent = match process_intent_from_call(&call) {
172                Ok(intent) => intent,
173                Err(error) => {
174                    tracing::debug!(
175                        tool_call_id = call.id().as_str(),
176                        tool_name = call.name().as_str(),
177                        diagnostic_code = PROCESS_COMMAND_INVALID_ARGUMENTS_CODE,
178                        "process command tool proposal rejected invalid arguments"
179                    );
180                    return Ok(ToolActionPreflight::Outcome(invalid_arguments_outcome(
181                        call.name().as_str(),
182                        error,
183                    )));
184                }
185            };
186            let cwd_label = if intent.cwd().is_some() {
187                "workspace-relative process"
188            } else {
189                "workspace-root process"
190            };
191            let proposal = ActionProposal::new(
192                &call,
193                ToolActionKind::CommandExec,
194                "process command",
195                cwd_label,
196                "Run the validated shell command through the platform process wrapper using an empty environment".to_owned(),
197                ActionProposalEvidence::ProcessAction(intent),
198            )
199            .map_err(|error| ToolExecutionError::infrastructure(error.to_string()))?;
200
201            Ok(ToolActionPreflight::Proposal(proposal))
202        })
203    }
204
205    fn execute<'a>(
206        &'a self,
207        call: PendingToolCall,
208        _context: ToolExecutionContext,
209    ) -> ToolExecutorFuture<'a> {
210        Box::pin(async move {
211            if let Err(error) = process_intent_from_call(&call) {
212                return Ok(invalid_arguments_outcome(call.name().as_str(), error));
213            }
214            Err(ToolExecutionError::infrastructure(
215                "process command tool must be executed through runtime process policy",
216            ))
217        })
218    }
219}
220
221fn process_intent_from_call(
222    call: &PendingToolCall,
223) -> Result<ProcessActionIntent, InvalidProcessCommandArguments> {
224    let input = call
225        .arguments()
226        .deserialize_as::<ProcessCommandInput>()
227        .map_err(|error| InvalidProcessCommandArguments::new(error.to_string()))?;
228    let _ = (&input.reason, &input.permissions);
229    let argv = shell_command_argv(&input.command);
230    let cwd = (!input.cwd.is_empty()).then_some(input.cwd);
231
232    ProcessActionIntent::new(
233        argv,
234        cwd,
235        ProcessEnvPolicy::empty(),
236        None,
237        DEFAULT_PROCESS_TOOL_STDOUT_LIMIT_BYTES,
238        DEFAULT_PROCESS_TOOL_STDERR_LIMIT_BYTES,
239    )
240    .and_then(|intent| {
241        intent
242            .with_background(input.background)
243            .with_display_name(input.display_name)
244            .with_timeout_secs(input.timeout_secs)
245    })
246    .map_err(|error| InvalidProcessCommandArguments::new(error.to_string()))
247}
248
249#[derive(Debug, Clone, PartialEq, Eq)]
250struct InvalidProcessCommandArguments {
251    message: String,
252}
253
254impl InvalidProcessCommandArguments {
255    fn new(message: impl Into<String>) -> Self {
256        Self {
257            message: message.into(),
258        }
259    }
260
261    fn message(&self) -> &str {
262        &self.message
263    }
264}
265
266const PROCESS_COMMAND_INVALID_ARGUMENTS_CODE: &str = "process_command_invalid_arguments";
267
268fn invalid_arguments_outcome(
269    tool_name: &str,
270    error: InvalidProcessCommandArguments,
271) -> ToolExecutionOutcome {
272    let payload = json!({
273        "ok": false,
274        "tool": tool_name,
275        "error": {
276            "code": PROCESS_COMMAND_INVALID_ARGUMENTS_CODE,
277            "message": error.message(),
278        },
279        "recovery": {
280            "command_contract": "Provide command as one non-empty shell command string. Newline and tab are allowed; other control characters are rejected. Escape control characters for the surrounding JSON string.",
281            "cwd_contract": "cwd, when provided, must be non-empty, workspace-relative, and must not contain control characters. For the workspace root, omit cwd or use \".\".",
282        },
283        "guidance": {
284            "kind": "invalid_process_arguments",
285            "message": "Fix the process tool arguments before retrying. Use command as one JSON string, and set cwd to null or a workspace-relative directory such as \".\".",
286        }
287    });
288    ToolExecutionOutcome::failed_json(
289        payload.to_string(),
290        ErrorInfo::new(PROCESS_COMMAND_INVALID_ARGUMENTS_CODE, error.message())
291            .expect("static process command diagnostic code is valid"),
292    )
293}
294
295#[cfg(test)]
296mod tests {
297    use super::{
298        PROCESS_COMMAND_INVALID_ARGUMENTS_CODE, ProcessCommandToolExecutor,
299        process_call_requests_permission, process_intent_from_call,
300    };
301    use crate::{
302        ActionProposalEvidence, ToolActionPreflight, ToolExecutionContext, ToolExecutor,
303        process::shell_command_argv,
304    };
305    use merry_core::{PendingToolCall, ToolCallArguments, ToolCallId, ToolName};
306    use serde_json::{Value, json};
307
308    fn pending_call(arguments: serde_json::Value) -> PendingToolCall {
309        PendingToolCall::new(
310            ToolCallId::new("call-process").expect("valid tool call id"),
311            ToolName::new("run_process").expect("valid tool name"),
312            ToolCallArguments::try_from(arguments).expect("valid tool call arguments"),
313        )
314    }
315
316    #[test]
317    fn process_intent_from_call_parses_command_and_cwd() {
318        let call = pending_call(json!({
319            "command": "rustc --version",
320            "cwd": "crates/merry-runtime"
321        }));
322
323        let intent = process_intent_from_call(&call).expect("process intent should parse");
324
325        assert_eq!(intent.argv(), shell_command_argv("rustc --version"));
326        assert_eq!(intent.cwd(), Some("crates/merry-runtime"));
327        assert!(intent.stdin_text().is_none());
328        assert!(!intent.background());
329    }
330
331    #[test]
332    fn process_intent_from_call_opts_into_background() {
333        let call = pending_call(json!({
334            "command": "sleep 30",
335            "background": true
336        }));
337
338        let intent = process_intent_from_call(&call).expect("process intent should parse");
339
340        assert!(intent.background());
341    }
342
343    #[test]
344    fn process_intent_from_call_parses_and_validates_timeout_secs() {
345        let default_call = pending_call(json!({ "command": "cargo check" }));
346        let default_intent = process_intent_from_call(&default_call).expect("default parses");
347        assert_eq!(default_intent.timeout_secs(), None);
348        assert_eq!(
349            default_intent.effective_wait_timeout_secs(),
350            crate::DEFAULT_PROCESS_WAIT_TIMEOUT_SECS
351        );
352
353        let custom_call = pending_call(json!({
354            "command": "cargo test --workspace",
355            "timeout_secs": 300
356        }));
357        let custom_intent = process_intent_from_call(&custom_call).expect("custom timeout parses");
358        assert_eq!(custom_intent.timeout_secs(), Some(300));
359        assert_eq!(custom_intent.effective_wait_timeout_secs(), 300);
360
361        let zero_call = pending_call(json!({
362            "command": "cargo check",
363            "timeout_secs": 0
364        }));
365        let zero_err = process_intent_from_call(&zero_call).expect_err("zero timeout must fail");
366        assert!(zero_err.message().contains("greater than zero"));
367
368        let huge_call = pending_call(json!({
369            "command": "cargo check",
370            "timeout_secs": crate::MAX_PROCESS_WAIT_TIMEOUT_SECS + 1
371        }));
372        let huge_err = process_intent_from_call(&huge_call).expect_err("oversized timeout fails");
373        assert!(huge_err.message().contains("maximum allowed wait timeout"));
374    }
375
376    #[test]
377    fn process_command_tool_schema_is_provider_compatible() {
378        let tool = super::process_command_tool(
379            ToolName::new("run_process").expect("valid tool name"),
380            "Run a process.",
381        )
382        .expect("process command tool should build");
383        let schema = serde_json::to_value(tool.spec().input_schema().as_schema())
384            .expect("schema should serialize");
385        crate::schema_contract::assert_provider_input_schema_fields_have_descriptions(tool.spec());
386
387        assert!(
388            schema["properties"]["cwd"]["description"]
389                .as_str()
390                .expect("cwd description should be text")
391                .contains("Omit it")
392        );
393        assert!(
394            schema["properties"]["cwd"]["description"]
395                .as_str()
396                .expect("cwd description should be text")
397                .contains("current workspace directory")
398        );
399        let cwd_string_schema = schema["properties"]["cwd"]["anyOf"]
400            .as_array()
401            .expect("cwd should have nullable branches")
402            .iter()
403            .find(|branch| branch["type"] == "string")
404            .expect("cwd should have a string branch");
405        assert_eq!(cwd_string_schema["minLength"], 1);
406        assert_eq!(cwd_string_schema["maxLength"], crate::MAX_PROCESS_CWD_BYTES);
407        assert!(
408            !schema["properties"]["command"]["description"]
409                .as_str()
410                .unwrap_or_default()
411                .is_empty()
412        );
413        assert_eq!(schema["properties"]["command"]["minLength"], 1);
414        assert_eq!(
415            schema["properties"]["command"]["maxLength"],
416            crate::MAX_PROCESS_ARG_BYTES
417        );
418        assert_eq!(schema["required"], json!(["command"]));
419        assert!(
420            schema["properties"]["background"]["description"]
421                .as_str()
422                .is_some_and(|description| description.contains("still running"))
423        );
424        assert!(
425            schema["properties"]["permissions"]["description"]
426                .as_str()
427                .is_some_and(|description| description.contains("exact action"))
428        );
429        assert!(schema["properties"]["reason"]["description"].is_string());
430    }
431
432    #[test]
433    fn process_intent_from_call_treats_empty_cwd_as_workspace_root() {
434        let call = pending_call(json!({
435            "command": "ping -c 1 baidu.com",
436            "cwd": ""
437        }));
438
439        let intent = process_intent_from_call(&call).expect("process intent should parse");
440
441        assert_eq!(intent.argv(), shell_command_argv("ping -c 1 baidu.com"));
442        assert_eq!(intent.cwd(), None);
443    }
444
445    #[test]
446    fn process_intent_from_call_defaults_omitted_cwd_to_workspace_root() {
447        let call = pending_call(json!({
448            "command": "pwd"
449        }));
450
451        let intent = process_intent_from_call(&call).expect("process intent should parse");
452
453        assert_eq!(intent.cwd(), None);
454    }
455
456    #[test]
457    fn nullable_permission_reason_is_treated_as_omitted() {
458        let call = pending_call(json!({
459            "command": "rg --files",
460            "cwd": null,
461            "reason": null,
462        }));
463
464        assert!(!process_call_requests_permission(&call));
465        process_intent_from_call(&call).expect("nullable reason should remain valid");
466    }
467
468    #[test]
469    fn nullable_permissions_are_treated_as_omitted() {
470        let call = pending_call(json!({
471            "command": "rg --files",
472            "permissions": null,
473        }));
474
475        assert!(!process_call_requests_permission(&call));
476        process_intent_from_call(&call).expect("nullable permissions should remain valid");
477    }
478
479    #[tokio::test(flavor = "current_thread")]
480    async fn malformed_arguments_fail_before_execution() {
481        let call = pending_call(json!({ "command": 42, "cwd": null }));
482        let proposal = ProcessCommandToolExecutor
483            .propose(call.clone(), ToolExecutionContext::default())
484            .await
485            .expect("malformed argv should not be infrastructure failure");
486
487        assert!(matches!(proposal, ToolActionPreflight::Outcome(_)));
488
489        let outcome = ProcessCommandToolExecutor
490            .execute(call, ToolExecutionContext::default())
491            .await
492            .expect("malformed argv should resolve as failed tool outcome");
493
494        assert_eq!(outcome.status(), merry_core::ToolCallResultStatus::Failed);
495        let diagnostic = outcome
496            .diagnostic()
497            .expect("failed process argument outcome should include diagnostic");
498        assert_eq!(diagnostic.code(), PROCESS_COMMAND_INVALID_ARGUMENTS_CODE);
499        let payload: Value = serde_json::from_str(outcome.content().as_str())
500            .expect("failed process argument outcome should parse as JSON");
501        assert_eq!(
502            payload["error"]["message"],
503            "command must be a non-empty string"
504        );
505        assert_eq!(payload["guidance"]["kind"], "invalid_process_arguments");
506        assert!(
507            payload["guidance"]["message"]
508                .as_str()
509                .expect("guidance should be text")
510                .contains("set cwd to null or a workspace-relative directory")
511        );
512    }
513
514    #[tokio::test(flavor = "current_thread")]
515    async fn proposal_carries_process_action_evidence() {
516        let call = pending_call(json!({ "command": "rustc --version", "cwd": null }));
517        let preflight = ProcessCommandToolExecutor
518            .propose(call, ToolExecutionContext::default())
519            .await
520            .expect("proposal should succeed");
521        let ToolActionPreflight::Proposal(proposal) = preflight else {
522            panic!("proposal should be present");
523        };
524
525        let ActionProposalEvidence::ProcessAction(intent) = proposal.evidence() else {
526            panic!("proposal should carry process action evidence");
527        };
528        assert_eq!(intent.argv(), shell_command_argv("rustc --version"));
529    }
530
531    #[tokio::test(flavor = "current_thread")]
532    async fn proposal_accepts_multiline_command_for_policy_classification() {
533        let call = pending_call(json!({
534            "command": "cargo check -p merry-runtime\ncargo test -p merry-runtime",
535            "cwd": "."
536        }));
537        let preflight = ProcessCommandToolExecutor
538            .propose(call, ToolExecutionContext::default())
539            .await
540            .expect("multiline shell argv should not be infrastructure failure");
541        let ToolActionPreflight::Proposal(proposal) = preflight else {
542            panic!("multiline shell argv should produce process proposal");
543        };
544
545        let ActionProposalEvidence::ProcessAction(intent) = proposal.evidence() else {
546            panic!("proposal should carry process action evidence");
547        };
548        assert_eq!(
549            intent.argv(),
550            shell_command_argv("cargo check -p merry-runtime\ncargo test -p merry-runtime")
551        );
552    }
553}