Skip to main content

docsrs_cli/render/
envelope.rs

1//! Typed JSON envelopes for the agent contract (success, dry-run, error).
2//!
3//! Every envelope serializes directly from a typed struct — no intermediate
4//! `serde_json::Value` on the write path. Optional fields are omitted on `None`
5//! (`skip_serializing_if`) rather than emitted as JSON `null`.
6
7use serde::Serialize;
8
9use crate::config::SCHEMA_VERSION;
10use crate::error::{AppError, ErrorDetail, ErrorKind, Suggestion};
11
12/// JSON success envelope for agents (`schema_version`, `ok`, `command`, `data`, `duration_ms`).
13///
14/// Typed wire shape — serializes directly without an intermediate `serde_json::Value`.
15/// Optional fields use omit-on-`None` (`skip_serializing_if`), not JSON `null`.
16#[derive(Debug, Serialize)]
17pub struct SuccessEnvelope<'a, T: Serialize> {
18    /// Envelope schema version.
19    pub schema_version: u32,
20    /// Always `true` for success envelopes.
21    pub ok: bool,
22    /// Command name that produced this payload.
23    pub command: &'a str,
24    /// Command-specific typed data payload.
25    pub data: T,
26    /// Wall-clock duration of the command in milliseconds.
27    pub duration_ms: u64,
28    /// Final source URL when the command fetched remote content.
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub source_url: Option<&'a str>,
31}
32
33/// JSON dry-run success envelope with planned URL and params.
34///
35/// `P` is a typed per-command params struct (`Serialize`). No intermediate
36/// `serde_json::Value` on the agent write path.
37#[derive(Debug, Serialize)]
38pub struct DryRunEnvelope<'a, P: Serialize> {
39    /// Envelope schema version.
40    pub schema_version: u32,
41    /// Always `true` for dry-run envelopes.
42    pub ok: bool,
43    /// Command name that would have run.
44    pub command: &'a str,
45    /// Always `true` — marks the response as a dry-run plan.
46    pub dry_run: bool,
47    /// Planned request details.
48    pub data: DryRunData<'a, P>,
49    /// Wall-clock duration until the plan was emitted.
50    pub duration_ms: u64,
51}
52
53/// Dry-run `data` object (`planned_url` + typed `planned_params`).
54#[derive(Debug, Serialize)]
55pub struct DryRunData<'a, P: Serialize> {
56    /// Absolute URL that would be requested.
57    pub planned_url: &'a str,
58    /// Command-specific planned query/body parameters (typed struct).
59    pub planned_params: P,
60}
61
62/// JSON error envelope for agents.
63///
64/// Parity with success envelopes: agents always get `command` + `duration_ms`
65/// (Camada Y / GAP-X-004) so failures correlate with the attempted wire command.
66#[derive(Debug, Serialize)]
67pub struct ErrorEnvelope<'a> {
68    /// Envelope schema version.
69    pub schema_version: u32,
70    /// Always `false` for error envelopes.
71    pub ok: bool,
72    /// Wire command name (`get-item`, `usage`, `cache-path`, …).
73    pub command: &'a str,
74    /// Wall-clock duration of the attempt in milliseconds.
75    pub duration_ms: u64,
76    /// Structured error body.
77    pub error: ErrorBody,
78}
79
80/// Error body fields inside the envelope.
81#[derive(Debug, Serialize)]
82pub struct ErrorBody {
83    /// Process exit code as an integer.
84    pub code: u8,
85    /// Snake_case error kind.
86    pub kind: String,
87    /// Technical English message.
88    pub message: String,
89    /// Whether an agent may retry after backoff.
90    pub retryable: bool,
91    /// Optional Retry-After seconds.
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub retry_after_secs: Option<u64>,
94    /// Ranked `--suggest` alternatives, best first.
95    ///
96    /// Present only when the recovery ladder produced at least one candidate, so
97    /// an ordinary not-found keeps the shape it always had. The same list is also
98    /// spelled out inside [`Self::message`] for humans; agents read it here
99    /// instead of splitting that sentence apart.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub suggestions: Option<Vec<Suggestion>>,
102}
103
104/// Build a typed success envelope (`schema_version`, `ok`, `command`, `data`, `duration_ms`).
105pub fn success_envelope<'a, T: Serialize>(
106    command: &'a str,
107    data: T,
108    duration_ms: u64,
109    source_url: Option<&'a str>,
110) -> SuccessEnvelope<'a, T> {
111    success_envelope_with_ok(command, data, duration_ms, source_url, true)
112}
113
114/// Build a success-shaped envelope with an explicit top-level `ok` (used by `doctor`).
115pub fn success_envelope_with_ok<'a, T: Serialize>(
116    command: &'a str,
117    data: T,
118    duration_ms: u64,
119    source_url: Option<&'a str>,
120    ok: bool,
121) -> SuccessEnvelope<'a, T> {
122    SuccessEnvelope {
123        schema_version: SCHEMA_VERSION,
124        ok,
125        command,
126        data,
127        duration_ms,
128        source_url,
129    }
130}
131
132/// Build a typed dry-run success envelope with planned URL/params.
133pub fn dry_run_envelope<'a, P: Serialize>(
134    command: &'a str,
135    planned_url: &'a str,
136    planned_params: P,
137    duration_ms: u64,
138) -> DryRunEnvelope<'a, P> {
139    DryRunEnvelope {
140        schema_version: SCHEMA_VERSION,
141        ok: true,
142        command,
143        dry_run: true,
144        data: DryRunData {
145            planned_url,
146            planned_params,
147        },
148        duration_ms,
149    }
150}
151
152/// Build an error envelope. SIGINT/SIGTERM surface as kind `canceled` with exit 130/143.
153///
154/// `command` is the wire name of the attempted command (`usage` when clap fails
155/// before dispatch). `duration_ms` is wall time since process start for that
156/// attempt (may be `0` for early parse failures).
157pub fn error_envelope<'a>(err: &AppError, command: &'a str, duration_ms: u64) -> ErrorEnvelope<'a> {
158    let kind = err.kind();
159    let kind_str = match kind {
160        ErrorKind::Interrupted | ErrorKind::Terminated => "canceled",
161        ErrorKind::BrokenPipe => "broken_pipe",
162        other => other.as_str(),
163    };
164    ErrorEnvelope {
165        schema_version: SCHEMA_VERSION,
166        ok: false,
167        command,
168        duration_ms,
169        error: ErrorBody {
170            code: kind.exit_code(),
171            kind: kind_str.to_string(),
172            message: err.message().to_string(),
173            retryable: kind.retryable(),
174            retry_after_secs: err.retry_after_secs(),
175            // Empty stays absent: `--suggest` on a leaf close to nothing renders
176            // "(none)" in the sentence, and an empty array would read as a
177            // different claim than "no suggestion field at all".
178            suggestions: err
179                .suggestions()
180                .filter(|s| !s.is_empty())
181                .map(<[Suggestion]>::to_vec),
182        },
183    }
184}
185
186/// Map clap parse failures to usage errors.
187pub fn usage_error(msg: impl Into<String>) -> AppError {
188    AppError::of(ErrorDetail::ClapUsage {
189        message: msg.into(),
190    })
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196    use crate::crates_io::CrateSearchHit;
197    use crate::docs_rs::ReadmeData;
198
199    #[test]
200    fn cancel_kinds_in_envelope() {
201        let e = error_envelope(&AppError::terminated(), "get-item", 0);
202        assert_eq!(e.error.code, 143);
203        assert_eq!(e.command, "get-item");
204        assert_eq!(e.duration_ms, 0);
205        assert_eq!(e.error.kind, "canceled");
206        let e = error_envelope(&AppError::interrupted(), "get-item", 1);
207        assert_eq!(e.error.code, 130);
208        assert_eq!(e.error.kind, "canceled");
209    }
210
211    #[test]
212    fn success_and_dry_run_envelopes() {
213        let payload = serde_json::json!({"n": 1});
214        let v = success_envelope("version", &payload, 3, Some("https://x"));
215        let v = serde_json::to_value(&v).expect("serialize success envelope");
216        assert_eq!(v["ok"], true);
217        assert_eq!(v["source_url"], "https://x");
218        assert_eq!(v["schema_version"], SCHEMA_VERSION);
219        // Optional source_url omitted when None (not JSON null).
220        let no_url = success_envelope("version", &payload, 1, None);
221        let no_url = serde_json::to_value(&no_url).expect("serialize");
222        assert!(no_url.get("source_url").is_none());
223        #[derive(serde::Serialize)]
224        struct EmptyParams {}
225        let d = dry_run_envelope("readme", "https://u", EmptyParams {}, 1);
226        let d = serde_json::to_value(&d).expect("serialize dry-run envelope");
227        assert_eq!(d["dry_run"], true);
228        assert_eq!(d["data"]["planned_url"], "https://u");
229        assert_eq!(d["data"]["planned_params"], serde_json::json!({}));
230        assert!(usage_error("x").kind() == ErrorKind::Usage);
231    }
232
233    #[test]
234    fn optional_fields_omitted_not_null() {
235        let hit = CrateSearchHit {
236            name: "x".into(),
237            description: "d".into(),
238            downloads: 1,
239            version: "1.0.0".into(),
240            documentation: None,
241            max_version: None,
242            max_stable_version: None,
243            default_version: None,
244            recent_downloads: None,
245            exact_match: None,
246            yanked: None,
247            repository: None,
248            homepage: None,
249        };
250        let v = serde_json::to_value(&hit).expect("serialize hit");
251        assert!(v.get("documentation").is_none());
252        assert!(v.get("repository").is_none());
253        assert!(!v.as_object().expect("object").values().any(|x| x.is_null()));
254
255        let readme = ReadmeData {
256            crate_name: "c".into(),
257            version: "latest".into(),
258            resolved_version: None,
259            markdown: "m".into(),
260            empty: false,
261            truncated: false,
262            source_url: "https://example.com".into(),
263            cache_hit: false,
264        };
265        let r = serde_json::to_value(&readme).expect("serialize readme");
266        assert!(r.get("resolved_version").is_none());
267        assert!(!r.as_object().expect("object").values().any(|x| x.is_null()));
268    }
269
270    #[test]
271    fn budget_error_is_not_retryable() {
272        let e = AppError::of(ErrorDetail::OutputOverBudget);
273        let env = error_envelope(&e, "get-item", 12);
274        assert_eq!(env.command, "get-item");
275        assert_eq!(env.duration_ms, 12);
276        assert_eq!(env.error.kind, "budget");
277        assert_eq!(env.error.code, 74);
278        assert!(!env.error.retryable);
279    }
280
281    #[test]
282    fn suggestions_reach_the_wire_as_data_not_only_as_prose() {
283        // `--suggest` computed a correct ranking and then buried it inside
284        // `error.message`, so the only way to consume it was to split on
285        // "; suggestions: ", split again on ", " and regex the "(kind)" off each
286        // entry. The sentence still carries the list for humans; this locks the
287        // machine-readable half beside it.
288        let e = AppError::of(ErrorDetail::WithSuggestions {
289            base: Box::new(ErrorDetail::AssocAnchorMissing {
290                anchors: "method.unwrp".into(),
291            }),
292            suggestions: vec![
293                Suggestion::new("option::Option::unwrap", "method"),
294                Suggestion::new("option::Option::unzip", "method"),
295            ],
296        });
297        let env = error_envelope(&e, "get-item", 3);
298        let got = env.error.suggestions.as_deref().expect("suggestions field");
299        assert_eq!(got.len(), 2);
300        assert_eq!(got[0].path, "option::Option::unwrap");
301        assert_eq!(got[0].kind, "method");
302        assert!(env.error.message.contains("suggestions:"), "prose kept");
303    }
304
305    #[test]
306    fn a_plain_failure_omits_the_suggestions_field_entirely() {
307        // Absent, never `null` and never `[]`: an empty array would claim "we
308        // looked and found nothing", which is a different fact from "no ranking
309        // ran". `--suggest` on a leaf close to nothing still renders "(none)" in
310        // the sentence, and that path is covered by the error-render tests.
311        let e = AppError::of(ErrorDetail::OutputOverBudget);
312        let env = error_envelope(&e, "get-item", 1);
313        assert!(env.error.suggestions.is_none());
314        let v = serde_json::to_value(&env).expect("serialize");
315        assert!(v["error"].get("suggestions").is_none());
316    }
317}