Skip to main content

agent_first_data/
protocol.rs

1use serde::Serialize;
2use serde_json::Value;
3use std::fmt;
4
5// ═══════════════════════════════════════════
6// Event Type and Build Errors (0.16 API)
7// ═══════════════════════════════════════════
8
9/// An SDK-built AFDATA protocol v1 event envelope.
10///
11/// Wraps the complete JSON envelope and provides access to the underlying value.
12/// The non-error builders retain a caller-provided trace verbatim and cannot
13/// fail. Validate externally supplied trace values with
14/// [`validate_protocol_event`] before treating the envelope as protocol-valid.
15#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
16pub struct Event(Value);
17
18impl Event {
19    /// Access the underlying JSON value.
20    pub fn as_value(&self) -> &Value {
21        &self.0
22    }
23
24    /// Convert into the underlying JSON value.
25    pub fn into_value(self) -> Value {
26        self.0
27    }
28}
29
30impl From<Event> for Value {
31    fn from(event: Event) -> Self {
32        event.0
33    }
34}
35
36impl fmt::Display for Event {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        write!(f, "{}", self.0)
39    }
40}
41
42/// Error type for builder failures.
43///
44/// Errors occur when:
45/// - A reserved error field is overwritten (code, message, hint, retryable)
46/// - An object field (.fields or .extend) is not a JSON object
47/// - A required field (code/message for convenience functions) is empty
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub enum BuildError {
50    ReservedField(String),
51    NonObjectField(String),
52    EmptyRequiredField(String),
53}
54
55impl fmt::Display for BuildError {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        match self {
58            Self::ReservedField(msg) => write!(f, "reserved field: {msg}"),
59            Self::NonObjectField(msg) => write!(f, "non-object field: {msg}"),
60            Self::EmptyRequiredField(msg) => write!(f, "empty required field: {msg}"),
61        }
62    }
63}
64
65impl std::error::Error for BuildError {}
66
67/// Log level enumeration (serialized as lowercase).
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
69#[serde(rename_all = "lowercase")]
70pub enum LogLevel {
71    Debug,
72    Info,
73    Warn,
74    Error,
75}
76
77impl LogLevel {
78    /// CLI emission and the optional tracing adapter share the same canonical
79    /// level spelling. Keep the helper out of a core-only build so that
80    /// `--no-default-features` remains free of dead code.
81    #[cfg(any(feature = "cli", feature = "tracing"))]
82    pub(crate) fn as_str(&self) -> &'static str {
83        match self {
84            Self::Debug => "debug",
85            Self::Info => "info",
86            Self::Warn => "warn",
87            Self::Error => "error",
88        }
89    }
90}
91
92// ═══════════════════════════════════════════
93// Result Builder
94// ═══════════════════════════════════════════
95
96/// Builder for result events.
97pub struct ResultBuilder {
98    payload: Value,
99    trace: Option<Value>,
100}
101
102impl ResultBuilder {
103    /// Set the trace object.
104    pub fn trace(mut self, trace: Value) -> Self {
105        self.trace = Some(trace);
106        self
107    }
108
109    /// Build the event. This builder cannot fail.
110    pub fn build(self) -> Event {
111        let trace = self
112            .trace
113            .unwrap_or_else(|| Value::Object(serde_json::Map::new()));
114        let mut obj = serde_json::Map::new();
115        obj.insert("kind".to_string(), Value::String("result".to_string()));
116        obj.insert("result".to_string(), self.payload);
117        obj.insert("trace".to_string(), trace);
118        Event(Value::Object(obj))
119    }
120}
121
122/// Fluent builder: start building a result event.
123pub fn json_result(payload: Value) -> ResultBuilder {
124    ResultBuilder {
125        payload,
126        trace: None,
127    }
128}
129
130// ═══════════════════════════════════════════
131// Error Builder
132// ═══════════════════════════════════════════
133
134/// Builder for error events.
135pub struct ErrorBuilder {
136    code: String,
137    message: String,
138    retryable: bool,
139    hint: Option<String>,
140    fields: serde_json::Map<String, Value>,
141    trace: Option<Value>,
142    build_error: Option<BuildError>,
143}
144
145impl ErrorBuilder {
146    /// Mark the error as retryable.
147    pub fn retryable(mut self) -> Self {
148        self.retryable = true;
149        self
150    }
151
152    /// Set retryable based on a boolean condition.
153    pub fn retryable_if(mut self, should_retry: bool) -> Self {
154        self.retryable = should_retry;
155        self
156    }
157
158    /// Set the hint.
159    pub fn hint(mut self, hint: &str) -> Self {
160        if !hint.is_empty() {
161            self.hint = Some(hint.to_string());
162        }
163        self
164    }
165
166    /// Set the hint if present.
167    pub fn hint_if_some(mut self, hint: Option<&str>) -> Self {
168        if let Some(h) = hint.filter(|hint| !hint.is_empty()) {
169            self.hint = Some(h.to_string());
170        }
171        self
172    }
173
174    /// Add an extension field.
175    pub fn field(mut self, name: &str, value: Value) -> Self {
176        if self.build_error.is_none() {
177            match name {
178                "code" | "message" | "hint" | "retryable" => {
179                    self.build_error = Some(BuildError::ReservedField(format!(
180                        "cannot write reserved field {name:?} to error payload"
181                    )));
182                }
183                _ => {
184                    self.fields.insert(name.to_string(), value);
185                }
186            }
187        }
188        self
189    }
190
191    /// Add multiple extension fields from a JSON object.
192    pub fn fields(mut self, fields: Value) -> Self {
193        if self.build_error.is_none() {
194            match fields {
195                Value::Object(map) => {
196                    for (k, v) in map {
197                        match k.as_str() {
198                            "code" | "message" | "hint" | "retryable" => {
199                                self.build_error = Some(BuildError::ReservedField(format!(
200                                    "cannot write reserved field {k:?} to error payload"
201                                )));
202                                return self;
203                            }
204                            _ => {
205                                self.fields.insert(k, v);
206                            }
207                        }
208                    }
209                }
210                _ => {
211                    self.build_error = Some(BuildError::NonObjectField(
212                        "fields() argument must be a JSON object".to_string(),
213                    ));
214                }
215            }
216        }
217        self
218    }
219
220    /// Extend with a serializable value (must serialize to JSON object).
221    pub fn extend<T: Serialize>(mut self, value: T) -> Self {
222        if self.build_error.is_none() {
223            match serde_json::to_value(&value) {
224                Ok(Value::Object(map)) => {
225                    for (k, v) in map {
226                        match k.as_str() {
227                            "code" | "message" | "hint" | "retryable" => {
228                                self.build_error = Some(BuildError::ReservedField(format!(
229                                    "cannot write reserved field {k:?} to error payload"
230                                )));
231                                return self;
232                            }
233                            _ => {
234                                self.fields.insert(k, v);
235                            }
236                        }
237                    }
238                }
239                Ok(_) => {
240                    self.build_error = Some(BuildError::NonObjectField(
241                        "extend() argument must serialize to a JSON object".to_string(),
242                    ));
243                }
244                Err(_) => {
245                    self.build_error = Some(BuildError::NonObjectField(
246                        "extend() argument serialization failed".to_string(),
247                    ));
248                }
249            }
250        }
251        self
252    }
253
254    /// Set the trace object.
255    pub fn trace(mut self, trace: Value) -> Self {
256        self.trace = Some(trace);
257        self
258    }
259
260    /// Build the event.
261    pub fn build(self) -> Result<Event, BuildError> {
262        if let Some(err) = self.build_error {
263            return Err(err);
264        }
265        if self.trace.as_ref().is_some_and(|trace| !trace.is_object()) {
266            return Err(BuildError::NonObjectField(
267                "trace() argument must be a JSON object".to_string(),
268            ));
269        }
270
271        let mut error_obj = self.fields;
272        error_obj.insert("code".to_string(), Value::String(self.code));
273        error_obj.insert("message".to_string(), Value::String(self.message));
274        error_obj.insert("retryable".to_string(), Value::Bool(self.retryable));
275        if let Some(h) = self.hint {
276            error_obj.insert("hint".to_string(), Value::String(h));
277        }
278
279        let trace = self
280            .trace
281            .unwrap_or_else(|| Value::Object(serde_json::Map::new()));
282        let mut obj = serde_json::Map::new();
283        obj.insert("kind".to_string(), Value::String("error".to_string()));
284        obj.insert("error".to_string(), Value::Object(error_obj));
285        obj.insert("trace".to_string(), trace);
286
287        Ok(Event(Value::Object(obj)))
288    }
289}
290
291/// Fluent builder: start building an error event.
292///
293/// An empty `code` or `message` does not panic here; it seeds a deferred
294/// [`BuildError::EmptyRequiredField`] that is surfaced when [`ErrorBuilder::build`]
295/// is called.
296pub fn json_error(code: &str, message: &str) -> ErrorBuilder {
297    let build_error = if code.is_empty() {
298        Some(BuildError::EmptyRequiredField(
299            "error code must not be empty".to_string(),
300        ))
301    } else if message.is_empty() {
302        Some(BuildError::EmptyRequiredField(
303            "error message must not be empty".to_string(),
304        ))
305    } else {
306        None
307    };
308    ErrorBuilder {
309        code: code.to_string(),
310        message: message.to_string(),
311        retryable: false,
312        hint: None,
313        fields: serde_json::Map::new(),
314        trace: None,
315        build_error,
316    }
317}
318
319// ═══════════════════════════════════════════
320// Progress Builder
321// ═══════════════════════════════════════════
322
323/// Builder for progress events.
324pub struct ProgressBuilder {
325    payload: Value,
326    trace: Option<Value>,
327}
328
329impl ProgressBuilder {
330    /// Write the current time into the payload as `timestamp_epoch_ms`
331    /// (milliseconds since the Unix epoch), replacing any existing value.
332    ///
333    /// Only a JSON object payload has a place for the field; any other payload
334    /// is left unchanged rather than wrapped, which would change the shape the
335    /// caller chose.
336    pub fn timestamp_now(self) -> Self {
337        self.timestamp_epoch_ms(jiff::Timestamp::now().as_millisecond())
338    }
339
340    /// Set the timestamp on an object payload, replacing any existing value.
341    pub fn timestamp_epoch_ms(mut self, timestamp_epoch_ms: i64) -> Self {
342        if let Value::Object(map) = &mut self.payload {
343            map.insert(
344                "timestamp_epoch_ms".to_string(),
345                Value::Number(timestamp_epoch_ms.into()),
346            );
347        }
348        self
349    }
350
351    /// Set the trace object.
352    pub fn trace(mut self, trace: Value) -> Self {
353        self.trace = Some(trace);
354        self
355    }
356
357    /// Build the event. This builder cannot fail.
358    pub fn build(self) -> Event {
359        let trace = self
360            .trace
361            .unwrap_or_else(|| Value::Object(serde_json::Map::new()));
362        let mut obj = serde_json::Map::new();
363        obj.insert("kind".to_string(), Value::String("progress".to_string()));
364        obj.insert("progress".to_string(), self.payload);
365        obj.insert("trace".to_string(), trace);
366
367        Event(Value::Object(obj))
368    }
369}
370
371/// Fluent builder: start building a progress event.
372///
373pub fn json_progress(payload: Value) -> ProgressBuilder {
374    ProgressBuilder {
375        payload,
376        trace: None,
377    }
378}
379
380// ═══════════════════════════════════════════
381// Log Builder
382// ═══════════════════════════════════════════
383
384/// Builder for log events.
385pub struct LogBuilder {
386    payload: Value,
387    trace: Option<Value>,
388}
389
390impl LogBuilder {
391    /// Write the current time into the payload as `timestamp_epoch_ms`
392    /// (milliseconds since the Unix epoch), replacing any existing value.
393    ///
394    /// Only a JSON object payload has a place for the field; any other payload
395    /// is left unchanged rather than wrapped, which would change the shape the
396    /// caller chose.
397    pub fn timestamp_now(self) -> Self {
398        self.timestamp_epoch_ms(jiff::Timestamp::now().as_millisecond())
399    }
400
401    /// Set the timestamp on an object payload, replacing any existing value.
402    pub fn timestamp_epoch_ms(mut self, timestamp_epoch_ms: i64) -> Self {
403        if let Value::Object(map) = &mut self.payload {
404            map.insert(
405                "timestamp_epoch_ms".to_string(),
406                Value::Number(timestamp_epoch_ms.into()),
407            );
408        }
409        self
410    }
411
412    /// Set the trace object.
413    pub fn trace(mut self, trace: Value) -> Self {
414        self.trace = Some(trace);
415        self
416    }
417
418    /// Build the event. This builder cannot fail.
419    pub fn build(self) -> Event {
420        let trace = self
421            .trace
422            .unwrap_or_else(|| Value::Object(serde_json::Map::new()));
423        let mut obj = serde_json::Map::new();
424        obj.insert("kind".to_string(), Value::String("log".to_string()));
425        obj.insert("log".to_string(), self.payload);
426        obj.insert("trace".to_string(), trace);
427
428        Event(Value::Object(obj))
429    }
430}
431
432/// Fluent builder: start building a log event.
433///
434pub fn json_log(payload: Value) -> LogBuilder {
435    LogBuilder {
436        payload,
437        trace: None,
438    }
439}
440
441// ═══════════════════════════════════════════
442// CLI Helper
443// ═══════════════════════════════════════════
444
445/// Build a CLI error event with optional hint.
446///
447/// Always returns a strict-valid `kind:"error"` event with code `"cli_error"`,
448/// `retryable: false`, and an empty `trace`. An empty `message` is replaced with
449/// a generic placeholder so the returned event stays strict-valid without panicking.
450pub fn build_cli_error(message: &str, hint: Option<&str>) -> Event {
451    let message = if message.is_empty() {
452        "unspecified error"
453    } else {
454        message
455    };
456    match json_error("cli_error", message).hint_if_some(hint).build() {
457        Ok(event) => event,
458        // Unreachable in practice (non-empty code+message, no reserved fields);
459        // construct a minimal valid envelope directly rather than panic.
460        Err(_) => {
461            let mut error_obj = serde_json::Map::new();
462            error_obj.insert("code".to_string(), Value::String("cli_error".to_string()));
463            error_obj.insert(
464                "message".to_string(),
465                Value::String("unspecified error".to_string()),
466            );
467            error_obj.insert("retryable".to_string(), Value::Bool(false));
468            let mut obj = serde_json::Map::new();
469            obj.insert("kind".to_string(), Value::String("error".to_string()));
470            obj.insert("error".to_string(), Value::Object(error_obj));
471            obj.insert("trace".to_string(), Value::Object(serde_json::Map::new()));
472            Event(Value::Object(obj))
473        }
474    }
475}
476
477// ═══════════════════════════════════════════
478// Validation
479// ═══════════════════════════════════════════
480
481/// A single protocol-validation violation: a stable machine-readable `rule`
482/// slug, a JSON pointer to the offending location (`""` = the whole event),
483/// and a human-readable `message`.
484///
485/// The `rule` slugs are a stable contract (the CLI maps them 1:1 onto its
486/// `validate` finding `rule_id`s). The full set:
487/// `event_not_object`, `kind_invalid`, `kind_unsupported`, `payload_missing`,
488/// `unexpected_field`, `trace_not_object`, `trace_required`, `error_not_object`,
489/// `error_code_invalid`, `error_message_invalid`, `error_hint_invalid`,
490/// `error_retryable_invalid`, `stream_non_terminal_after_terminal`,
491/// `stream_duplicate_terminal`, `stream_missing_terminal`.
492#[derive(Clone, Debug, PartialEq, Eq)]
493pub struct ProtocolViolation {
494    pub rule: &'static str,
495    pub pointer: String,
496    pub message: String,
497}
498
499impl std::fmt::Display for ProtocolViolation {
500    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
501        write!(f, "{}", self.message)
502    }
503}
504
505impl std::error::Error for ProtocolViolation {}
506
507fn violation(
508    rule: &'static str,
509    pointer: impl Into<String>,
510    message: impl Into<String>,
511) -> ProtocolViolation {
512    ProtocolViolation {
513        rule,
514        pointer: pointer.into(),
515        message: message.into(),
516    }
517}
518
519/// Validate one protocol v1 event envelope.
520///
521/// `strict` additionally enforces the recommended strict profile: `trace` is
522/// required, and kind-specific payload shapes are checked (see
523/// `validate_protocol_event_strict_payload`).
524///
525/// Returns the first [`ProtocolViolation`] found, or `Ok(())`.
526pub fn validate_protocol_event(event: &Value, strict: bool) -> Result<(), ProtocolViolation> {
527    validate_protocol_event_base(event)?;
528    if strict {
529        validate_protocol_event_strict_payload(event)?;
530    }
531    Ok(())
532}
533
534fn validate_protocol_event_base(event: &Value) -> Result<(), ProtocolViolation> {
535    let Some(obj) = event.as_object() else {
536        return Err(violation(
537            "event_not_object",
538            "",
539            "event must be a JSON object",
540        ));
541    };
542    let Some(kind) = obj.get("kind").and_then(Value::as_str) else {
543        return Err(violation(
544            "kind_invalid",
545            "/kind",
546            "event.kind must be one of result, error, progress, log",
547        ));
548    };
549    if !matches!(kind, "result" | "error" | "progress" | "log") {
550        return Err(violation(
551            "kind_unsupported",
552            "/kind",
553            format!("unsupported event kind {kind:?}"),
554        ));
555    }
556    if !obj.contains_key(kind) {
557        return Err(violation(
558            "payload_missing",
559            format!("/{kind}"),
560            format!("event payload field {kind:?} is required"),
561        ));
562    }
563    for key in obj.keys() {
564        if key != "kind" && key != kind && key != "trace" {
565            return Err(violation(
566                "unexpected_field",
567                format!("/{key}"),
568                format!("unexpected top-level field {key:?}"),
569            ));
570        }
571    }
572    if let Some(trace) = obj.get("trace")
573        && !trace.is_object()
574    {
575        return Err(violation(
576            "trace_not_object",
577            "/trace",
578            "event.trace must be a JSON object when present",
579        ));
580    }
581    if kind == "error" {
582        validate_error_payload(obj.get("error"))?;
583    }
584    Ok(())
585}
586
587fn validate_error_payload(error: Option<&Value>) -> Result<(), ProtocolViolation> {
588    let Some(error) = error.and_then(Value::as_object) else {
589        return Err(violation(
590            "error_not_object",
591            "/error",
592            "event.error must be a JSON object",
593        ));
594    };
595    match error.get("code").and_then(Value::as_str) {
596        Some(code) if !code.is_empty() => {}
597        _ => {
598            return Err(violation(
599                "error_code_invalid",
600                "/error/code",
601                "event.error.code must be a non-empty string",
602            ));
603        }
604    }
605    match error.get("message").and_then(Value::as_str) {
606        Some(message) if !message.is_empty() => {}
607        _ => {
608            return Err(violation(
609                "error_message_invalid",
610                "/error/message",
611                "event.error.message must be a non-empty string",
612            ));
613        }
614    }
615    if error.get("hint").is_some_and(|hint| !hint.is_string()) {
616        return Err(violation(
617            "error_hint_invalid",
618            "/error/hint",
619            "event.error.hint must be a string when present",
620        ));
621    }
622    // Absent is "unknown"; a value of the wrong type is not, and decoding it as
623    // absent would turn `"retryable":"false"` into a silent "maybe".
624    if error
625        .get("retryable")
626        .is_some_and(|retryable| !retryable.is_boolean())
627    {
628        return Err(violation(
629            "error_retryable_invalid",
630            "/error/retryable",
631            "event.error.retryable must be a boolean when present",
632        ));
633    }
634    Ok(())
635}
636
637/// Validate a finite structured CLI event stream:
638/// `(log | progress)* -> exactly one (result | error) -> end`.
639///
640/// `strict` is forwarded to [`validate_protocol_event`] for every event.
641///
642/// Unlike [`validate_protocol_event`], this collects every violation across
643/// the whole stream instead of failing fast on the first one; per-event
644/// violation pointers are prefixed with the event's index (`/{idx}{pointer}`).
645pub fn validate_protocol_stream(
646    events: &[Value],
647    strict: bool,
648) -> Result<(), Vec<ProtocolViolation>> {
649    let mut violations = Vec::new();
650    let mut terminal_seen = false;
651    for (idx, event) in events.iter().enumerate() {
652        if let Err(v) = validate_protocol_event(event, strict) {
653            violations.push(ProtocolViolation {
654                rule: v.rule,
655                pointer: format!("/{idx}{}", v.pointer),
656                message: v.message,
657            });
658        }
659        match event.get("kind").and_then(Value::as_str) {
660            Some("log") | Some("progress") => {
661                if terminal_seen {
662                    violations.push(violation(
663                        "stream_non_terminal_after_terminal",
664                        format!("/{idx}"),
665                        "non-terminal event after terminal",
666                    ));
667                }
668            }
669            Some("result") | Some("error") => {
670                if terminal_seen {
671                    violations.push(violation(
672                        "stream_duplicate_terminal",
673                        format!("/{idx}"),
674                        "duplicate terminal event",
675                    ));
676                } else {
677                    terminal_seen = true;
678                }
679            }
680            _ => {} // an invalid/absent kind is already recorded by validate_protocol_event above
681        }
682    }
683    if !terminal_seen {
684        violations.push(violation(
685            "stream_missing_terminal",
686            String::new(),
687            "event stream must contain exactly one terminal result or error",
688        ));
689    }
690    if violations.is_empty() {
691        Ok(())
692    } else {
693        Err(violations)
694    }
695}
696
697/// Validate one protocol v1 event's payload against the recommended strict profile.
698///
699/// Assumes the base envelope shape (see [`validate_protocol_event_base`]) already passed.
700fn validate_protocol_event_strict_payload(event: &Value) -> Result<(), ProtocolViolation> {
701    if !event.get("trace").is_some_and(Value::is_object) {
702        return Err(violation(
703            "trace_required",
704            "/trace",
705            "event.trace is required by the strict profile",
706        ));
707    }
708    match event.get("kind").and_then(Value::as_str) {
709        Some("error") => validate_strict_error_payload(event.get("error")),
710        _ => Ok(()),
711    }
712}
713
714fn validate_strict_error_payload(error: Option<&Value>) -> Result<(), ProtocolViolation> {
715    let Some(error) = error.and_then(Value::as_object) else {
716        return Err(violation(
717            "error_not_object",
718            "/error",
719            "event.error must be a JSON object in the strict profile",
720        ));
721    };
722    require_non_empty_string(
723        error,
724        "code",
725        "error_code_invalid",
726        "/error/code",
727        "event.error",
728    )?;
729    require_non_empty_string(
730        error,
731        "message",
732        "error_message_invalid",
733        "/error/message",
734        "event.error",
735    )?;
736    if error.get("retryable").and_then(Value::as_bool).is_none() {
737        return Err(violation(
738            "error_retryable_invalid",
739            "/error/retryable",
740            "event.error.retryable must be a boolean in the strict profile",
741        ));
742    }
743    if error.contains_key("hint") && !error.get("hint").is_some_and(Value::is_string) {
744        return Err(violation(
745            "error_hint_invalid",
746            "/error/hint",
747            "event.error.hint must be a string when present",
748        ));
749    }
750    Ok(())
751}
752
753fn require_non_empty_string(
754    payload: &serde_json::Map<String, Value>,
755    field: &str,
756    rule: &'static str,
757    pointer: &'static str,
758    path: &str,
759) -> Result<(), ProtocolViolation> {
760    if payload
761        .get(field)
762        .and_then(Value::as_str)
763        .is_some_and(|value| !value.is_empty())
764    {
765        return Ok(());
766    }
767    Err(violation(
768        rule,
769        pointer,
770        format!("{path}.{field} must be a non-empty string in the strict profile"),
771    ))
772}
773
774// ═══════════════════════════════════════════
775// Reader API: decode_protocol_event
776// ═══════════════════════════════════════════
777
778/// A decoded, base-valid AFDATA protocol v1 event, typed by kind.
779#[derive(Clone, Debug, PartialEq)]
780pub enum DecodedEvent {
781    Result(DecodedResult),
782    Error(DecodedError),
783    Progress(DecodedProgress),
784    Log(DecodedLog),
785}
786
787/// Decoded `kind:"result"` event.
788#[derive(Clone, Debug, PartialEq)]
789pub struct DecodedResult {
790    /// The raw `result` payload value.
791    pub result: Value,
792    /// The raw `trace` object, when present.
793    pub trace: Option<Value>,
794}
795
796/// Decoded `kind:"error"` event.
797#[derive(Clone, Debug, PartialEq)]
798pub struct DecodedError {
799    pub code: String,
800    pub message: String,
801    pub retryable: Option<bool>,
802    pub hint: Option<String>,
803    /// Payload keys beyond `code`, `message`, `retryable`, `hint`.
804    pub fields: serde_json::Map<String, Value>,
805    /// The raw `trace` object, when present.
806    pub trace: Option<Value>,
807}
808
809/// Decoded `kind:"progress"` event.
810#[derive(Clone, Debug, PartialEq)]
811pub struct DecodedProgress {
812    /// The raw `progress` payload value.
813    pub progress: Value,
814    /// The raw `trace` object, when present.
815    pub trace: Option<Value>,
816}
817
818/// Decoded `kind:"log"` event.
819#[derive(Clone, Debug, PartialEq)]
820pub struct DecodedLog {
821    /// The raw `log` payload value.
822    pub log: Value,
823    /// The raw `trace` object, when present.
824    pub trace: Option<Value>,
825}
826
827/// Error returned by [`decode_protocol_event`].
828#[derive(Clone, Debug, PartialEq, Eq)]
829pub enum EventDecodeError {
830    /// `text` is not valid JSON.
831    InvalidJson(String),
832    /// The parsed JSON value failed base protocol validation.
833    InvalidEvent(String),
834}
835
836impl fmt::Display for EventDecodeError {
837    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838        match self {
839            Self::InvalidJson(err) => write!(f, "invalid JSON: {err}"),
840            Self::InvalidEvent(err) => write!(f, "invalid protocol event: {err}"),
841        }
842    }
843}
844
845impl std::error::Error for EventDecodeError {}
846
847/// Parse one protocol v1 line, base-validate it, and return a typed decoded event.
848///
849/// `text` is a single JSON text value (one protocol line), not a JSONL stream.
850///
851/// The decode rules every SDK shares come from `serde_json` here: a repeated
852/// key keeps its last value, a lone surrogate `\u` escape is invalid, and
853/// arrays and objects nest at most 127 deep counting the envelope (serde_json's
854/// recursion limit). The other SDKs enforce the same rules explicitly, and
855/// `spec/fixtures/protocol_decode.json` pins each one on both sides.
856pub fn decode_protocol_event(text: &str) -> Result<DecodedEvent, EventDecodeError> {
857    let value: Value =
858        serde_json::from_str(text).map_err(|err| EventDecodeError::InvalidJson(err.to_string()))?;
859    validate_protocol_event(&value, false)
860        .map_err(|v| EventDecodeError::InvalidEvent(v.to_string()))?;
861
862    // Base validation above guarantees the envelope is an object with a
863    // recognized `kind`; the `ok_or_else` fallbacks below are defensive only.
864    let malformed = || {
865        EventDecodeError::InvalidEvent(
866            "event passed base validation but has an unexpected shape".to_string(),
867        )
868    };
869    let obj = value.as_object().ok_or_else(malformed)?;
870    let trace = obj.get("trace").cloned();
871    match obj.get("kind").and_then(Value::as_str) {
872        Some("result") => Ok(DecodedEvent::Result(DecodedResult {
873            result: obj.get("result").cloned().unwrap_or(Value::Null),
874            trace,
875        })),
876        Some("error") => {
877            let mut fields = obj
878                .get("error")
879                .and_then(Value::as_object)
880                .ok_or_else(malformed)?
881                .clone();
882            let code = fields
883                .remove("code")
884                .and_then(|v| v.as_str().map(str::to_string))
885                .ok_or_else(malformed)?;
886            let message = fields
887                .remove("message")
888                .and_then(|v| v.as_str().map(str::to_string))
889                .ok_or_else(malformed)?;
890            let retryable = fields.remove("retryable").and_then(|v| v.as_bool());
891            let hint = fields
892                .remove("hint")
893                .and_then(|v| v.as_str().map(str::to_string));
894            Ok(DecodedEvent::Error(DecodedError {
895                code,
896                message,
897                retryable,
898                hint,
899                fields,
900                trace,
901            }))
902        }
903        Some("progress") => Ok(DecodedEvent::Progress(DecodedProgress {
904            progress: obj.get("progress").cloned().unwrap_or(Value::Null),
905            trace,
906        })),
907        Some("log") => Ok(DecodedEvent::Log(DecodedLog {
908            log: obj.get("log").cloned().unwrap_or(Value::Null),
909            trace,
910        })),
911        _ => Err(malformed()),
912    }
913}