Skip to main content

agent_client_protocol_schema/v2/
terminal.rs

1//! Agent-owned terminal output reported for display by Clients.
2
3use std::{num::NonZeroU16, sync::Arc};
4
5use derive_more::{Display, From};
6use serde::{Deserialize, Serialize};
7use serde_with::{DefaultOnError, serde_as, skip_serializing_none};
8
9use super::{AbsolutePath, Meta, apply_meta_update};
10use crate::{IntoMaybeUndefined, IntoOption, MaybeUndefined};
11
12/// Unique identifier for an Agent-owned terminal within a session.
13#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
14#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
15#[serde(transparent)]
16#[from(forward)]
17#[non_exhaustive]
18pub struct TerminalId(pub Arc<str>);
19
20impl TerminalId {
21    /// Wraps a protocol string as a typed [`TerminalId`].
22    #[must_use]
23    pub fn new(id: impl Into<Self>) -> Self {
24        id.into()
25    }
26}
27
28impl IntoOption<TerminalId> for &str {
29    fn into_option(self) -> Option<TerminalId> {
30        Some(TerminalId::new(self))
31    }
32}
33
34/// A display-only reference to an Agent-owned terminal.
35///
36/// Terminal state and output are delivered separately through
37/// `terminal_update` and `terminal_output_chunk` session updates.
38#[serde_as]
39#[skip_serializing_none]
40#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43#[non_exhaustive]
44pub struct Terminal {
45    /// The ID of the terminal to display.
46    pub terminal_id: TerminalId,
47    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
48    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
49    /// Implementations MUST NOT assign meaning to keys they do not recognize.
50    ///
51    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
52    #[serde_as(deserialize_as = "DefaultOnError")]
53    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
54    #[serde(default)]
55    #[serde(rename = "_meta")]
56    pub meta: Option<Meta>,
57}
58
59impl Terminal {
60    /// Builds a terminal reference for the given terminal ID.
61    #[must_use]
62    pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
63        Self {
64            terminal_id: terminal_id.into(),
65            meta: None,
66        }
67    }
68
69    /// Sets or clears metadata scoped to this content reference.
70    #[must_use]
71    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
72        self.meta = meta.into_option();
73        self
74    }
75}
76
77/// An authoritative replacement snapshot of terminal output bytes.
78#[serde_as]
79#[skip_serializing_none]
80#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82#[serde(rename_all = "camelCase")]
83#[non_exhaustive]
84pub struct TerminalOutput {
85    /// Base64-encoded replacement terminal output bytes.
86    #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
87    pub data: String,
88    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
89    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
90    /// Implementations MUST NOT assign meaning to keys they do not recognize.
91    ///
92    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
93    #[serde_as(deserialize_as = "DefaultOnError")]
94    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
95    #[serde(default)]
96    #[serde(rename = "_meta")]
97    pub meta: Option<Meta>,
98}
99
100impl TerminalOutput {
101    /// Builds an authoritative terminal output replacement.
102    #[must_use]
103    pub fn new(data: impl Into<String>) -> Self {
104        Self {
105            data: data.into(),
106            meta: None,
107        }
108    }
109
110    /// Sets or clears metadata scoped to this replacement snapshot.
111    #[must_use]
112    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
113        self.meta = meta.into_option();
114        self
115    }
116}
117
118/// Exit information for an Agent-owned terminal.
119///
120/// The presence of this object marks the terminal as exited, even when neither
121/// an exit code nor a signal is known.
122#[serde_as]
123#[skip_serializing_none]
124#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
125#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
126#[serde(rename_all = "camelCase")]
127#[non_exhaustive]
128pub struct TerminalExitStatus {
129    /// Process exit code as the platform reports it, when known. Negative values are
130    /// allowed, for example signed Windows exit codes. Omitted and `null` are equivalent.
131    #[serde_as(deserialize_as = "DefaultOnError")]
132    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
133    #[serde(default)]
134    pub exit_code: Option<i64>,
135    /// Signal that terminated the process, when known.
136    ///
137    /// Agents SHOULD use the conventional platform signal name. POSIX examples
138    /// include `SIGTERM`, `SIGKILL`, and `SIGINT`. Other platforms may use a
139    /// platform-specific name. Omitted and `null` are equivalent.
140    #[serde_as(deserialize_as = "DefaultOnError")]
141    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
142    #[serde(default)]
143    pub signal: Option<String>,
144    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
145    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
146    /// Implementations MUST NOT assign meaning to keys they do not recognize.
147    ///
148    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
149    #[serde_as(deserialize_as = "DefaultOnError")]
150    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
151    #[serde(default)]
152    #[serde(rename = "_meta")]
153    pub meta: Option<Meta>,
154}
155
156impl TerminalExitStatus {
157    /// Builds terminal exit information with no known exit code or signal.
158    #[must_use]
159    pub fn new() -> Self {
160        Self::default()
161    }
162
163    /// Sets or clears the optional exit code.
164    #[must_use]
165    pub fn exit_code(mut self, exit_code: impl IntoOption<i64>) -> Self {
166        self.exit_code = exit_code.into_option();
167        self
168    }
169
170    /// Sets or clears the optional terminating signal.
171    #[must_use]
172    pub fn signal(mut self, signal: impl IntoOption<String>) -> Self {
173        self.signal = signal.into_option();
174        self
175    }
176
177    /// Sets or clears metadata scoped to this exit information.
178    #[must_use]
179    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
180        self.meta = meta.into_option();
181        self
182    }
183}
184
185/// Client-initiated controls a terminal currently supports.
186///
187/// See protocol docs: [Cancelling Terminals](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-terminals)
188#[serde_as]
189#[skip_serializing_none]
190#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
191#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
192#[serde(rename_all = "camelCase")]
193#[non_exhaustive]
194pub struct TerminalCapabilities {
195    /// Permits the Client to cancel this terminal with `terminal/cancel`.
196    ///
197    /// Omitted and `null` are equivalent and mean unsupported. An object (including `{}`)
198    /// means supported. Agents SHOULD stop advertising it once the terminal reports `exitStatus`.
199    #[serde_as(deserialize_as = "DefaultOnError")]
200    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
201    #[serde(default)]
202    pub cancel: Option<TerminalCancelCapabilities>,
203    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
204    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
205    /// Implementations MUST NOT assign meaning to keys they do not recognize.
206    ///
207    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
208    #[serde_as(deserialize_as = "DefaultOnError")]
209    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
210    #[serde(default)]
211    #[serde(rename = "_meta")]
212    pub meta: Option<Meta>,
213}
214
215impl TerminalCapabilities {
216    /// Builds an empty capability set. Cancellation is not advertised.
217    #[must_use]
218    pub fn new() -> Self {
219        Self::default()
220    }
221
222    /// Sets or removes permission to cancel this terminal.
223    #[must_use]
224    pub fn cancel(mut self, cancel: impl IntoOption<TerminalCancelCapabilities>) -> Self {
225        self.cancel = cancel.into_option();
226        self
227    }
228
229    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
230    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
231    /// do not recognize.
232    ///
233    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
234    #[must_use]
235    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
236        self.meta = meta.into_option();
237        self
238    }
239}
240
241/// Capability to cancel a terminal with `terminal/cancel`.
242///
243/// Supplying `{}` advertises support. An omitted or `null` `cancel` does not.
244#[serde_as]
245#[skip_serializing_none]
246#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
247#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
248#[non_exhaustive]
249pub struct TerminalCancelCapabilities {
250    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
251    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
252    /// Implementations MUST NOT assign meaning to keys they do not recognize.
253    ///
254    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
255    #[serde_as(deserialize_as = "DefaultOnError")]
256    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
257    #[serde(default)]
258    #[serde(rename = "_meta")]
259    pub meta: Option<Meta>,
260}
261
262impl TerminalCancelCapabilities {
263    /// Builds an empty capability object advertising cancellation support.
264    #[must_use]
265    pub fn new() -> Self {
266        Self::default()
267    }
268
269    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
270    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
271    /// do not recognize.
272    ///
273    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
274    #[must_use]
275    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
276        self.meta = meta.into_option();
277        self
278    }
279}
280
281/// An upsert for the stored state of an Agent-owned terminal.
282///
283/// Only `terminalId` is required. Other fields have patch
284/// semantics: omitted fields leave the stored value unchanged, `null` clears
285/// it, and concrete values replace it. A concrete `_meta` object instead
286/// patches the stored metadata by top-level key. When the terminal ID is new,
287/// omitted fields start unknown.
288#[serde_as]
289#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(rename_all = "camelCase")]
292#[non_exhaustive]
293pub struct TerminalUpdate {
294    /// Unique identifier for this terminal within the session.
295    pub terminal_id: TerminalId,
296    /// The command being run.
297    #[serde_as(deserialize_as = "DefaultOnError")]
298    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
299    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
300    pub command: MaybeUndefined<String>,
301    /// The absolute working directory of the command.
302    #[serde_as(deserialize_as = "DefaultOnError")]
303    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
304    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
305    pub cwd: MaybeUndefined<AbsolutePath>,
306    /// An authoritative replacement snapshot of terminal output bytes.
307    #[serde_as(deserialize_as = "DefaultOnError")]
308    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
309    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
310    pub output: MaybeUndefined<TerminalOutput>,
311    /// Exit information. A concrete object marks the terminal as exited.
312    #[serde_as(deserialize_as = "DefaultOnError")]
313    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
314    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
315    pub exit_status: MaybeUndefined<TerminalExitStatus>,
316    /// The terminal size the command runs with, when known.
317    ///
318    /// Clients can render output at this size so that column layouts, progress bars,
319    /// and cursor-positioned output display as the program wrote them.
320    #[serde_as(deserialize_as = "DefaultOnError")]
321    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
322    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
323    pub size: MaybeUndefined<TerminalSize>,
324    /// Client-initiated controls this terminal currently supports, such as cancellation.
325    ///
326    /// Omission leaves the capabilities unchanged, `null` clears them, and an object replaces
327    /// the whole previous value. A new terminal starts with none.
328    #[serde_as(deserialize_as = "DefaultOnError")]
329    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
330    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
331    pub capabilities: MaybeUndefined<TerminalCapabilities>,
332    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
333    /// metadata to their interactions. Omitted leaves the stored metadata unchanged. `null`
334    /// clears it. An object patches the stored metadata by top-level key: keys it omits are
335    /// unchanged, a key set to `null` is removed, and any other value replaces that key's
336    /// stored value without merging nested objects. Beyond this patch rule, implementations
337    /// MUST NOT assign meaning to keys they do not recognize.
338    ///
339    /// See protocol docs: [Metadata Patches](https://agentclientprotocol.com/protocol/v2/extensibility#metadata-patches)
340    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
341    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
342    #[serde(
343        rename = "_meta",
344        default,
345        skip_serializing_if = "MaybeUndefined::is_undefined"
346    )]
347    pub meta: MaybeUndefined<Meta>,
348}
349
350impl TerminalUpdate {
351    /// Builds a terminal upsert with only its required ID set.
352    #[must_use]
353    pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
354        Self {
355            terminal_id: terminal_id.into(),
356            command: MaybeUndefined::Undefined,
357            cwd: MaybeUndefined::Undefined,
358            output: MaybeUndefined::Undefined,
359            exit_status: MaybeUndefined::Undefined,
360            size: MaybeUndefined::Undefined,
361            capabilities: MaybeUndefined::Undefined,
362            meta: MaybeUndefined::Undefined,
363        }
364    }
365
366    /// Sets, clears, or leaves unchanged the command being run.
367    #[must_use]
368    pub fn command(mut self, command: impl IntoMaybeUndefined<String>) -> Self {
369        self.command = command.into_maybe_undefined();
370        self
371    }
372
373    /// Sets, clears, or leaves unchanged the absolute working directory.
374    #[must_use]
375    pub fn cwd(mut self, cwd: impl IntoMaybeUndefined<AbsolutePath>) -> Self {
376        self.cwd = cwd.into_maybe_undefined();
377        self
378    }
379
380    /// Sets, clears, or leaves unchanged the authoritative output snapshot.
381    #[must_use]
382    pub fn output(mut self, output: impl IntoMaybeUndefined<TerminalOutput>) -> Self {
383        self.output = output.into_maybe_undefined();
384        self
385    }
386
387    /// Sets, clears, or leaves unchanged the terminal exit information.
388    #[must_use]
389    pub fn exit_status(mut self, exit_status: impl IntoMaybeUndefined<TerminalExitStatus>) -> Self {
390        self.exit_status = exit_status.into_maybe_undefined();
391        self
392    }
393
394    /// Sets, clears, or leaves unchanged the terminal size.
395    #[must_use]
396    pub fn size(mut self, size: impl IntoMaybeUndefined<TerminalSize>) -> Self {
397        self.size = size.into_maybe_undefined();
398        self
399    }
400
401    /// Sets, clears, or leaves unchanged the Client-initiated controls.
402    #[must_use]
403    pub fn capabilities(
404        mut self,
405        capabilities: impl IntoMaybeUndefined<TerminalCapabilities>,
406    ) -> Self {
407        self.capabilities = capabilities.into_maybe_undefined();
408        self
409    }
410
411    /// Patches, clears, or leaves unchanged terminal metadata.
412    ///
413    /// A concrete object patches stored metadata by top-level key. See
414    /// [`apply_meta_update`].
415    #[must_use]
416    pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
417        self.meta = meta.into_maybe_undefined();
418        self
419    }
420
421    /// Applies a later terminal patch to this stored terminal state.
422    ///
423    /// Fields set to `null` remain `null` so callers can distinguish explicit
424    /// clearing from an update that did not mention the field. A concrete
425    /// `_meta` object patches the stored metadata by top-level key, as described
426    /// by [`apply_meta_update`].
427    pub fn apply_update(&mut self, update: TerminalUpdate) {
428        debug_assert_eq!(self.terminal_id, update.terminal_id);
429        if !update.command.is_undefined() {
430            self.command = update.command;
431        }
432        if !update.cwd.is_undefined() {
433            self.cwd = update.cwd;
434        }
435        if !update.output.is_undefined() {
436            self.output = update.output;
437        }
438        if !update.exit_status.is_undefined() {
439            self.exit_status = update.exit_status;
440        }
441        if !update.size.is_undefined() {
442            self.size = update.size;
443        }
444        if !update.capabilities.is_undefined() {
445            self.capabilities = update.capabilities;
446        }
447        apply_meta_update(&mut self.meta, update.meta);
448    }
449}
450
451/// The size of an Agent-owned terminal in character cells.
452#[serde_as]
453#[skip_serializing_none]
454#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
455#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
456#[serde(rename_all = "camelCase")]
457#[non_exhaustive]
458pub struct TerminalSize {
459    /// Number of columns. At least 1.
460    pub cols: NonZeroU16,
461    /// Number of rows. At least 1.
462    pub rows: NonZeroU16,
463    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
464    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
465    /// Implementations MUST NOT assign meaning to keys they do not recognize.
466    ///
467    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
468    #[serde_as(deserialize_as = "DefaultOnError")]
469    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
470    #[serde(default)]
471    #[serde(rename = "_meta")]
472    pub meta: Option<Meta>,
473}
474
475impl TerminalSize {
476    /// Builds a terminal size from its columns and rows.
477    #[must_use]
478    pub fn new(cols: NonZeroU16, rows: NonZeroU16) -> Self {
479        Self {
480            cols,
481            rows,
482            meta: None,
483        }
484    }
485
486    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
487    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
488    /// do not recognize.
489    ///
490    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
491    #[must_use]
492    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
493        self.meta = meta.into_option();
494        self
495    }
496}
497
498/// A chunk of bytes appended to an Agent-owned terminal's output.
499#[serde_as]
500#[skip_serializing_none]
501#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
502#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
503#[serde(rename_all = "camelCase")]
504#[non_exhaustive]
505pub struct TerminalOutputChunk {
506    /// The terminal receiving these bytes.
507    pub terminal_id: TerminalId,
508    /// Independently base64-encoded terminal output bytes.
509    #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
510    pub data: String,
511    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
512    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
513    /// Implementations MUST NOT assign meaning to keys they do not recognize.
514    /// This metadata is scoped to the chunk and does not patch stored metadata.
515    ///
516    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
517    #[serde_as(deserialize_as = "DefaultOnError")]
518    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
519    #[serde(default)]
520    #[serde(rename = "_meta")]
521    pub meta: Option<Meta>,
522}
523
524impl TerminalOutputChunk {
525    /// Builds a terminal output chunk with the required fields set.
526    #[must_use]
527    pub fn new(terminal_id: impl Into<TerminalId>, data: impl Into<String>) -> Self {
528        Self {
529            terminal_id: terminal_id.into(),
530            data: data.into(),
531            meta: None,
532        }
533    }
534
535    /// Sets or clears chunk-scoped metadata.
536    #[must_use]
537    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
538        self.meta = meta.into_option();
539        self
540    }
541}
542
543#[cfg(test)]
544mod tests {
545
546    #[test]
547    fn terminal_capabilities_patch_and_tolerate_malformed_values() {
548        use serde_json::json;
549        let update = TerminalUpdate::new("term_003")
550            .capabilities(TerminalCapabilities::new().cancel(TerminalCancelCapabilities::new()));
551        assert_eq!(
552            serde_json::to_value(&update).unwrap(),
553            json!({ "terminalId": "term_003", "capabilities": { "cancel": {} } })
554        );
555
556        let mut stored = update;
557        stored.apply_update(TerminalUpdate::new("term_003"));
558        assert!(stored.capabilities.is_value());
559        stored.apply_update(TerminalUpdate::new("term_003").capabilities(MaybeUndefined::Null));
560        assert!(stored.capabilities.is_null());
561
562        for bad in [json!("yes"), json!(1)] {
563            let parsed: TerminalUpdate =
564                serde_json::from_value(json!({ "terminalId": "term_003", "capabilities": bad }))
565                    .unwrap();
566            assert!(parsed.capabilities.is_undefined());
567        }
568        let parsed: TerminalCapabilities =
569            serde_json::from_value(json!({ "cancel": "yes" })).unwrap();
570        assert_eq!(parsed.cancel, None);
571    }
572
573    #[test]
574    fn terminal_size_is_an_optional_patch_field() {
575        let update = TerminalUpdate::new("term_1").size(TerminalSize::new(
576            NonZeroU16::new(120).unwrap(),
577            NonZeroU16::new(40).unwrap(),
578        ));
579        assert_eq!(
580            serde_json::to_value(&update).unwrap(),
581            serde_json::json!({ "terminalId": "term_1", "size": { "cols": 120, "rows": 40 } })
582        );
583
584        let mut stored = update;
585        stored.apply_update(TerminalUpdate::new("term_1").command("ls"));
586        assert_eq!(
587            stored.size,
588            MaybeUndefined::Value(TerminalSize::new(
589                NonZeroU16::new(120).unwrap(),
590                NonZeroU16::new(40).unwrap()
591            ))
592        );
593        stored.apply_update(TerminalUpdate::new("term_1").size(None));
594        assert_eq!(stored.size, MaybeUndefined::Null);
595    }
596
597    #[test]
598    fn terminal_size_of_zero_is_not_applied() {
599        // A terminal cannot have zero columns or rows, so such a size is not a size.
600        for size in [
601            json!({ "cols": 0, "rows": 40 }),
602            json!({ "cols": 120, "rows": 0 }),
603        ] {
604            assert!(serde_json::from_value::<TerminalSize>(size.clone()).is_err());
605            let update: TerminalUpdate =
606                serde_json::from_value(json!({ "terminalId": "term_1", "size": size })).unwrap();
607            assert!(update.size.is_undefined());
608        }
609    }
610
611    #[test]
612    fn exit_code_accepts_negative_values() {
613        let status: TerminalExitStatus =
614            serde_json::from_value(serde_json::json!({ "exitCode": -1_073_741_819_i64 })).unwrap();
615        assert_eq!(status.exit_code, Some(-1_073_741_819));
616    }
617
618    use super::*;
619    use serde_json::{from_value, json, to_value};
620
621    #[test]
622    fn terminal_reference_meta_is_optional_and_content_scoped() {
623        let omitted = Terminal::new("term_1");
624        assert_eq!(
625            serde_json::to_value(&omitted).unwrap(),
626            serde_json::json!({
627                "terminalId": "term_1"
628            })
629        );
630
631        let null: Terminal = serde_json::from_value(serde_json::json!({
632            "terminalId": "term_1",
633            "_meta": null
634        }))
635        .unwrap();
636        assert_eq!(null.meta, None);
637
638        let mut meta = Meta::new();
639        meta.insert("view".to_string(), serde_json::json!("expanded"));
640        assert_eq!(
641            serde_json::to_value(Terminal::new("term_1").meta(meta)).unwrap(),
642            serde_json::json!({
643                "terminalId": "term_1",
644                "_meta": {
645                    "view": "expanded"
646                }
647            })
648        );
649    }
650
651    #[test]
652    fn terminal_update_distinguishes_omitted_null_and_value() {
653        let update = TerminalUpdate::new("term_1")
654            .command("cargo test")
655            .cwd("/workspace/project")
656            .output(None::<TerminalOutput>)
657            .exit_status(TerminalExitStatus::new().exit_code(0));
658
659        assert_eq!(
660            serde_json::to_value(update).unwrap(),
661            serde_json::json!({
662                "terminalId": "term_1",
663                "command": "cargo test",
664                "cwd": "/workspace/project",
665                "output": null,
666                "exitStatus": {
667                    "exitCode": 0
668                }
669            })
670        );
671
672        let parsed: TerminalUpdate = serde_json::from_value(serde_json::json!({
673            "terminalId": "term_1",
674            "command": null,
675            "cwd": "/workspace/project"
676        }))
677        .unwrap();
678        assert_eq!(parsed.command, MaybeUndefined::Null);
679        assert_eq!(
680            parsed.cwd,
681            MaybeUndefined::Value(AbsolutePath::new("/workspace/project"))
682        );
683        assert_eq!(parsed.output, MaybeUndefined::Undefined);
684        assert_eq!(parsed.exit_status, MaybeUndefined::Undefined);
685        assert_eq!(parsed.meta, MaybeUndefined::Undefined);
686    }
687
688    #[test]
689    fn terminal_update_applies_patch_fields() {
690        let mut stored = TerminalUpdate::new("term_1")
691            .command("cargo test")
692            .cwd("/workspace/project")
693            .output(TerminalOutput::new("b2xk"));
694
695        stored.apply_update(
696            TerminalUpdate::new("term_1")
697                .command(None::<String>)
698                .output(TerminalOutput::new("bmV3"))
699                .exit_status(TerminalExitStatus::new().signal("SIGTERM")),
700        );
701
702        assert_eq!(stored.command, MaybeUndefined::Null);
703        assert_eq!(
704            stored.cwd,
705            MaybeUndefined::Value(AbsolutePath::new("/workspace/project"))
706        );
707        assert_eq!(
708            stored.output,
709            MaybeUndefined::Value(TerminalOutput::new("bmV3"))
710        );
711        assert_eq!(
712            stored.exit_status,
713            MaybeUndefined::Value(TerminalExitStatus::new().signal("SIGTERM"))
714        );
715    }
716
717    #[test]
718    fn terminal_wire_patches_preserve_omitted_fields_and_replace_values() {
719        let initial = json!({
720            "terminalId": "term_1",
721            "_meta": {"source": "replay", "opaque": {"sequence": 1}}
722        });
723        let mut stored: TerminalUpdate = from_value(initial.clone()).unwrap();
724        // A metadata-only first update leaves output and exit status unknown.
725        assert_eq!(to_value(&stored).unwrap(), initial);
726
727        let populated = json!({
728            "terminalId": "term_1",
729            "command": "cargo check",
730            "cwd": "/workspace/project",
731            "output": {"data": "b2xk", "_meta": {"source": "snapshot"}},
732            "exitStatus": {"exitCode": 0, "_meta": {"observed": true}}
733        });
734        stored.apply_update(from_value(populated.clone()).unwrap());
735        let mut expected = populated;
736        expected["_meta"] = initial["_meta"].clone();
737        assert_eq!(to_value(&stored).unwrap(), expected);
738
739        for (field, empty) in [
740            ("command", json!("")),
741            ("output", json!({"data": ""})),
742            ("exitStatus", json!({})),
743        ] {
744            let original = expected[field].clone();
745            // Nested objects are replacements too: an empty output snapshot
746            // must not inherit snapshot metadata, and an empty exit-status
747            // object means exited with unknown details, not exit code zero.
748            for replacement in [empty, json!(null), original] {
749                stored.apply_update(
750                    from_value(json!({"terminalId": "term_1", (field): replacement})).unwrap(),
751                );
752                expected[field] = replacement;
753                assert_eq!(to_value(&stored).unwrap(), expected, "patching {field}");
754
755                stored.apply_update(from_value(json!({"terminalId": "term_1"})).unwrap());
756                assert_eq!(to_value(&stored).unwrap(), expected, "omitting {field}");
757            }
758        }
759
760        // Top-level `_meta` patches individual keys instead of replacing the object.
761        stored.apply_update(
762            from_value(json!({
763                "terminalId": "term_1",
764                "_meta": {"source": null, "opaque": {"other": 2}, "extra": true}
765            }))
766            .unwrap(),
767        );
768        expected["_meta"] = json!({"opaque": {"other": 2}, "extra": true});
769        assert_eq!(to_value(&stored).unwrap(), expected, "patching _meta keys");
770
771        stored.apply_update(from_value(json!({"terminalId": "term_1", "_meta": null})).unwrap());
772        expected["_meta"] = json!(null);
773        assert_eq!(to_value(&stored).unwrap(), expected, "clearing _meta");
774    }
775
776    #[test]
777    fn terminal_output_chunk_serializes_base64_data_and_meta() {
778        let mut meta = Meta::new();
779        meta.insert("source".to_string(), serde_json::json!("pty"));
780
781        assert_eq!(
782            serde_json::to_value(TerminalOutputChunk::new("term_1", "8J+agA==").meta(meta))
783                .unwrap(),
784            serde_json::json!({
785                "terminalId": "term_1",
786                "data": "8J+agA==",
787                "_meta": {
788                    "source": "pty"
789                }
790            })
791        );
792    }
793
794    #[test]
795    fn terminal_output_meta_is_optional_and_snapshot_scoped() {
796        let omitted = TerminalOutput::new("b2s=");
797        assert_eq!(
798            serde_json::to_value(&omitted).unwrap(),
799            serde_json::json!({ "data": "b2s=" })
800        );
801
802        let null: TerminalOutput = serde_json::from_value(serde_json::json!({
803            "data": "b2s=",
804            "_meta": null
805        }))
806        .unwrap();
807        assert_eq!(null, omitted);
808
809        let mut meta = Meta::new();
810        meta.insert("source".to_string(), serde_json::json!("replay"));
811        assert_eq!(
812            serde_json::to_value(TerminalOutput::new("b2s=").meta(meta)).unwrap(),
813            serde_json::json!({
814                "data": "b2s=",
815                "_meta": {
816                    "source": "replay"
817                }
818            })
819        );
820    }
821
822    #[cfg(feature = "schemars")]
823    #[test]
824    fn terminal_output_fields_use_base64_content_encoding() {
825        let output = serde_json::to_value(schemars::schema_for!(TerminalOutput)).unwrap();
826        assert_eq!(output["properties"]["data"]["contentEncoding"], "base64");
827        assert!(output["properties"]["data"].get("format").is_none());
828        assert_eq!(output["required"], serde_json::json!(["data"]));
829        assert!(output["properties"].get("_meta").is_some());
830        assert!(output["properties"].get("truncated").is_none());
831
832        let chunk = serde_json::to_value(schemars::schema_for!(TerminalOutputChunk)).unwrap();
833        assert_eq!(chunk["properties"]["data"]["contentEncoding"], "base64");
834        assert!(chunk["properties"]["data"].get("format").is_none());
835    }
836
837    #[test]
838    fn terminal_exit_status_treats_omitted_and_null_as_unknown() {
839        let omitted: TerminalExitStatus = serde_json::from_value(serde_json::json!({})).unwrap();
840        let null: TerminalExitStatus = serde_json::from_value(serde_json::json!({
841            "exitCode": null,
842            "signal": null,
843            "_meta": null
844        }))
845        .unwrap();
846
847        assert_eq!(omitted, TerminalExitStatus::new());
848        assert_eq!(null, TerminalExitStatus::new());
849        assert_eq!(serde_json::to_value(null).unwrap(), serde_json::json!({}));
850    }
851
852    #[test]
853    fn terminal_exit_status_meta_is_exit_scoped() {
854        let mut meta = Meta::new();
855        meta.insert("reason".to_string(), serde_json::json!("timeout"));
856
857        assert_eq!(
858            serde_json::to_value(TerminalExitStatus::new().signal("SIGTERM").meta(meta)).unwrap(),
859            serde_json::json!({
860                "signal": "SIGTERM",
861                "_meta": {
862                    "reason": "timeout"
863                }
864            })
865        );
866    }
867}