Skip to main content

merry_runtime/process/
output.rs

1//! Shared captured-output fields in process artifacts and model result rendering.
2//!
3//! The process executor writes this envelope and presentation consumers read it.
4//! Execution input and recovery metadata remain writer-owned additional fields.
5//! Readers accept historical omissions and integer exit statuses, but a present
6//! stream must contain text so malformed output cannot silently become empty.
7
8use super::{ProcessExitStatus, ProcessPermissionProfileId, ProcessRunnerOutput};
9use crate::PermissionAdmissionReview;
10use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
11use merry_core::{ToolOutput, ToolOutputKind};
12use serde::{Deserialize, Serialize};
13use std::borrow::Cow;
14
15pub(crate) const TRUNCATION_GUIDANCE: &str =
16    "Output is incomplete; inspect a narrower range before drawing conclusions.";
17pub(crate) const NON_UTF8_GUIDANCE: &str = "Non-UTF-8 bytes are shown as \u{FFFD}; inspect the source with xxd or a format-aware tool for exact bytes.";
18pub(crate) const OUTPUT_RECOVERY_GUIDANCE: &str =
19    "Do not repeat a side-effecting command to recover output.";
20pub(crate) const STILL_RUNNING_GUIDANCE: &str = "The process is still running, so this turn can continue. Ending this tool call does not stop it. Use read_background_process with this id for later output and stop_background_process to stop it. Merry keeps it until the session ends or that stop.";
21
22/// Shared fields of a full process result artifact, including lossless captures.
23///
24/// Serialization borrows runner text; deserialization owns it. Unknown fields
25/// are ignored for artifact compatibility, not used to make admission decisions.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct ProcessOutputEnvelope<'a> {
28    kind: ProcessOutputKind,
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    ok: Option<bool>,
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    permission_profile_id: Option<Cow<'a, str>>,
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    status: Option<ProcessOutputStatus>,
35    #[serde(default)]
36    stdout: ProcessOutputStream<'a>,
37    #[serde(default)]
38    stderr: ProcessOutputStream<'a>,
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    permission_review: Option<ProcessOutputReview<'a>>,
41}
42
43impl<'a> ProcessOutputEnvelope<'a> {
44    pub(crate) fn new(
45        output: &'a ProcessRunnerOutput,
46        permission_profile_id: ProcessPermissionProfileId,
47        permission_review: Option<&'a PermissionAdmissionReview>,
48    ) -> Self {
49        Self {
50            kind: ProcessOutputKind::ProcessAction,
51            ok: Some(output.ok()),
52            permission_profile_id: Some(permission_profile_id.as_str().into()),
53            status: Some(ProcessOutputStatus::Current(output.status())),
54            stdout: ProcessOutputStream::new(
55                output.stdout_data(),
56                output.stdout_text(),
57                output.stdout_truncated(),
58            ),
59            stderr: ProcessOutputStream::new(
60                output.stderr_data(),
61                output.stderr_text(),
62                output.stderr_truncated(),
63            ),
64            permission_review: permission_review.map(ProcessOutputReview::from),
65        }
66    }
67
68    /// Returns recorded success, or `None` if a historical artifact omitted it.
69    #[must_use]
70    pub fn ok(&self) -> Option<bool> {
71        self.ok
72    }
73
74    /// Borrows the recorded profile name without requiring it to still exist.
75    #[must_use]
76    pub fn permission_profile_id(&self) -> Option<&str> {
77        self.permission_profile_id.as_deref()
78    }
79
80    /// Borrows the admission rationale if the artifact includes one.
81    #[must_use]
82    pub fn permission_rationale(&self) -> Option<&str> {
83        self.permission_review.as_ref()?.rationale.as_deref()
84    }
85
86    /// Returns a normal exit code from current or historical status encoding.
87    #[must_use]
88    pub fn exit_code(&self) -> Option<i64> {
89        match self.status.as_ref()? {
90            ProcessOutputStatus::Current(status) => status.exit_code().map(i64::from),
91            ProcessOutputStatus::Legacy(code) => Some(*code),
92        }
93    }
94
95    /// Borrows captured stdout, empty when omitted in a historical artifact.
96    #[must_use]
97    pub fn stdout(&self) -> &ProcessOutputStream<'a> {
98        &self.stdout
99    }
100
101    /// Borrows captured stderr, empty when omitted in a historical artifact.
102    #[must_use]
103    pub fn stderr(&self) -> &ProcessOutputStream<'a> {
104        &self.stderr
105    }
106
107    /// Transfers both captures to a consumer without cloning their text.
108    #[must_use]
109    pub fn into_streams(self) -> (ProcessOutputStream<'a>, ProcessOutputStream<'a>) {
110        (self.stdout, self.stderr)
111    }
112
113    fn derived_model_text(&self) -> Option<String> {
114        let streams = ModelTextStreams {
115            stdout: self.stdout.text(),
116            stdout_truncated: self.stdout.truncated,
117            stdout_utf8: self.stdout.utf8.unwrap_or(true),
118            stderr: self.stderr.text(),
119            stderr_truncated: self.stderr.truncated,
120            stderr_utf8: self.stderr.utf8.unwrap_or(true),
121        };
122        let status = match self.status.as_ref()? {
123            ProcessOutputStatus::Current(status) => *status,
124            ProcessOutputStatus::Legacy(code) => {
125                let mut text = format!("exit {code}");
126                append_model_stream(
127                    &mut text,
128                    "stdout",
129                    streams.stdout,
130                    streams.stdout_truncated,
131                    streams.stdout_utf8,
132                );
133                append_model_stream(
134                    &mut text,
135                    "stderr",
136                    streams.stderr,
137                    streams.stderr_truncated,
138                    streams.stderr_utf8,
139                );
140                return Some(text);
141            }
142        };
143        let header = match status {
144            ProcessExitStatus::Exited(code) => format!("exit {code}"),
145            ProcessExitStatus::Cancelled => "cancelled".to_owned(),
146            ProcessExitStatus::FailedToStart => "not started".to_owned(),
147            ProcessExitStatus::DomainFailed => "failed before normal exit".to_owned(),
148            ProcessExitStatus::Running => return None,
149        };
150        Some(render_model_text_parts(
151            header,
152            streams,
153            recovery_guidance(status),
154        ))
155    }
156}
157
158/// Renders the compact model-facing text view from a live process runner output.
159#[must_use]
160pub(crate) fn render_process_model_text(output: &ProcessRunnerOutput) -> String {
161    let header = match output.status() {
162        ProcessExitStatus::Exited(code) => format!("exit {code}"),
163        ProcessExitStatus::Cancelled => "cancelled".to_owned(),
164        ProcessExitStatus::FailedToStart => "not started".to_owned(),
165        ProcessExitStatus::DomainFailed => "failed before normal exit".to_owned(),
166        ProcessExitStatus::Running => {
167            let prefix = match output.wait_timed_out_secs() {
168                Some(secs) => format!("still running (waited {secs}s, not killed)"),
169                None => "still running".to_owned(),
170            };
171            match (output.running_pid(), output.background_process_id()) {
172                (Some(pid), Some(id)) => format!("{prefix} pid {pid} id {id}"),
173                (Some(pid), None) => format!("{prefix} pid {pid}"),
174                (None, Some(id)) => format!("{prefix} id {id}"),
175                (None, None) => prefix,
176            }
177        }
178    };
179    let recovery = recovery_guidance_for_output(output);
180    render_model_text_parts(
181        header,
182        ModelTextStreams {
183            stdout: output.stdout_text(),
184            stdout_truncated: output.stdout_truncated(),
185            stdout_utf8: output.stdout_is_utf8(),
186            stderr: output.stderr_text(),
187            stderr_truncated: output.stderr_truncated(),
188            stderr_utf8: output.stderr_is_utf8(),
189        },
190        recovery.as_deref(),
191    )
192}
193
194/// Rebuilds the process model text from a stored full output JSON document.
195///
196/// A still-running process names a pid/id that the envelope does not store, so
197/// this returns `None` and the journal retains the model text for that case.
198#[must_use]
199pub(crate) fn derived_process_model_text(full_json: &str) -> Option<String> {
200    let envelope = serde_json::from_str::<ProcessOutputEnvelope<'_>>(full_json).ok()?;
201    envelope.derived_model_text()
202}
203
204/// Strips non-durable admission and shell-fingerprint metadata before writing a
205/// process tool output into `journal.jsonl`.
206///
207/// Non-process outputs are returned unchanged.
208#[must_use]
209pub(crate) fn sanitize_process_output_for_journal(full: &ToolOutput) -> ToolOutput {
210    if full.kind() != ToolOutputKind::Json {
211        return full.clone();
212    }
213    if serde_json::from_str::<ProcessOutputEnvelope<'_>>(full.as_str()).is_err() {
214        return full.clone();
215    }
216    let Ok(mut value) = serde_json::from_str::<serde_json::Value>(full.as_str()) else {
217        return full.clone();
218    };
219    let Some(object) = value.as_object_mut() else {
220        return full.clone();
221    };
222    let removed_profile = object.remove("permission_profile_id").is_some();
223    let removed_review = object.remove("permission_review").is_some();
224    let removed_evidence = object.remove("input_evidence").is_some();
225    if !removed_profile && !removed_review && !removed_evidence {
226        return full.clone();
227    }
228    serde_json::to_string(&value)
229        .map(ToolOutput::json)
230        .unwrap_or_else(|_| full.clone())
231}
232
233pub(crate) fn recovery_guidance(status: ProcessExitStatus) -> Option<&'static str> {
234    match status {
235        ProcessExitStatus::Cancelled | ProcessExitStatus::DomainFailed => {
236            Some("Execution may have had side effects; verify its state before retrying.")
237        }
238        ProcessExitStatus::FailedToStart => {
239            Some("The command did not start; check the error before retrying.")
240        }
241        ProcessExitStatus::Running => Some(STILL_RUNNING_GUIDANCE),
242        ProcessExitStatus::Exited(_) => None,
243    }
244}
245
246pub(crate) fn recovery_guidance_for_output(
247    output: &ProcessRunnerOutput,
248) -> Option<Cow<'static, str>> {
249    if output.status() == ProcessExitStatus::Running
250        && let Some(secs) = output.wait_timed_out_secs()
251    {
252        return Some(Cow::Owned(format!(
253            "The command did not exit within {secs}s and was NOT killed; it is still running in the background. Use read_background_process with this id to check whether it is still making progress or read later output, or use stop_background_process to terminate it and adjust/retry if it is stuck. If this is a long-lived service (such as a web API, dev server, or daemon), leave it running and use background=true with a short display_name next time; for slow finite commands, pass a larger timeout_secs on future run_process calls."
254        )));
255    }
256    recovery_guidance(output.status()).map(Cow::Borrowed)
257}
258
259struct ModelTextStreams<'a> {
260    stdout: &'a str,
261    stdout_truncated: bool,
262    stdout_utf8: bool,
263    stderr: &'a str,
264    stderr_truncated: bool,
265    stderr_utf8: bool,
266}
267
268fn render_model_text_parts(
269    mut text: String,
270    streams: ModelTextStreams<'_>,
271    recovery: Option<&str>,
272) -> String {
273    append_model_stream(
274        &mut text,
275        "stdout",
276        streams.stdout,
277        streams.stdout_truncated,
278        streams.stdout_utf8,
279    );
280    append_model_stream(
281        &mut text,
282        "stderr",
283        streams.stderr,
284        streams.stderr_truncated,
285        streams.stderr_utf8,
286    );
287    let mut guidance = Vec::with_capacity(4);
288    let non_utf8 = !streams.stdout_utf8 || !streams.stderr_utf8;
289    let truncated = streams.stdout_truncated || streams.stderr_truncated;
290    if non_utf8 {
291        guidance.push(NON_UTF8_GUIDANCE);
292    }
293    if truncated {
294        guidance.push(TRUNCATION_GUIDANCE);
295    }
296    if non_utf8 || truncated {
297        guidance.push(OUTPUT_RECOVERY_GUIDANCE);
298    }
299    if let Some(recovery) = recovery {
300        guidance.push(recovery);
301    }
302    if !guidance.is_empty() {
303        append_model_section(&mut text, "guidance", &guidance.join(" "));
304    }
305    text
306}
307
308fn append_model_stream(text: &mut String, name: &str, content: &str, truncated: bool, utf8: bool) {
309    if content.is_empty() && !truncated {
310        return;
311    }
312    match (truncated, utf8) {
313        (false, true) => append_model_section(text, name, content),
314        (true, true) => append_model_section(text, &format!("{name} (truncated)"), content),
315        (false, false) => append_model_section(text, &format!("{name} (non-UTF-8)"), content),
316        (true, false) => {
317            append_model_section(text, &format!("{name} (truncated, non-UTF-8)"), content);
318        }
319    }
320}
321
322fn append_model_section(text: &mut String, name: &str, content: &str) {
323    if !text.ends_with('\n') {
324        text.push('\n');
325    }
326    text.push_str(name);
327    text.push_str(":\n");
328    text.push_str(content);
329}
330
331/// One captured stream, with optional metadata absent in older artifacts.
332#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
333pub struct ProcessOutputStream<'a> {
334    text: Cow<'a, str>,
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    bytes: Option<usize>,
337    #[serde(default)]
338    truncated: bool,
339    #[serde(default, skip_serializing_if = "Option::is_none")]
340    utf8: Option<bool>,
341    #[serde(default, skip_serializing_if = "Option::is_none")]
342    bytes_base64: Option<String>,
343}
344
345impl<'a> ProcessOutputStream<'a> {
346    fn new(bytes: &[u8], text: &'a str, truncated: bool) -> Self {
347        let utf8 = std::str::from_utf8(bytes).is_ok();
348        Self {
349            text: Cow::Borrowed(text),
350            bytes: Some(bytes.len()),
351            truncated,
352            utf8: Some(utf8),
353            bytes_base64: (!utf8).then(|| BASE64.encode(bytes)),
354        }
355    }
356
357    /// Borrows captured text, lossily decoded when `utf8()` is `Some(false)`.
358    #[must_use]
359    pub fn text(&self) -> &str {
360        &self.text
361    }
362
363    /// Returns whether the capture limit discarded output bytes.
364    #[must_use]
365    pub fn truncated(&self) -> bool {
366        self.truncated
367    }
368
369    /// Returns encoding validity, or `None` if it was not recorded.
370    #[must_use]
371    pub fn utf8(&self) -> Option<bool> {
372        self.utf8
373    }
374
375    /// Takes decoded text, allocating only when this envelope borrowed it.
376    #[must_use]
377    pub fn into_text(self) -> String {
378        self.text.into_owned()
379    }
380}
381
382#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
383#[serde(rename_all = "snake_case")]
384enum ProcessOutputKind {
385    ProcessAction,
386}
387
388#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
389#[serde(untagged)]
390enum ProcessOutputStatus {
391    Current(#[serde(with = "ProcessExitStatusWire")] ProcessExitStatus),
392    Legacy(i64),
393}
394
395#[derive(Serialize, Deserialize)]
396#[serde(
397    remote = "ProcessExitStatus",
398    tag = "kind",
399    content = "code",
400    rename_all = "snake_case"
401)]
402enum ProcessExitStatusWire {
403    Exited(i32),
404    Cancelled,
405    FailedToStart,
406    DomainFailed,
407    Running,
408}
409
410#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
411struct ProcessOutputReview<'a> {
412    #[serde(default, skip_serializing_if = "Option::is_none")]
413    source: Option<Cow<'a, str>>,
414    #[serde(default, skip_serializing_if = "Option::is_none")]
415    risk: Option<Cow<'a, str>>,
416    #[serde(default, skip_serializing_if = "Option::is_none")]
417    user_authorization: Option<Cow<'a, str>>,
418    #[serde(default, skip_serializing_if = "Option::is_none")]
419    rationale: Option<Cow<'a, str>>,
420}
421
422impl<'a> From<&'a PermissionAdmissionReview> for ProcessOutputReview<'a> {
423    fn from(review: &'a PermissionAdmissionReview) -> Self {
424        Self {
425            source: Some(review.source().as_str().into()),
426            risk: Some(review.risk().as_str().into()),
427            user_authorization: Some(review.user_authorization().as_str().into()),
428            rationale: Some(review.rationale().into()),
429        }
430    }
431}