Skip to main content

agent_client_protocol_schema/v2/
ext.rs

1//! Extension types and constants for protocol extensibility.
2use derive_more::From;
3use serde::{Deserialize, Serialize};
4use serde_json::value::RawValue;
5use std::sync::Arc;
6
7use crate::MaybeUndefined;
8
9/// Value attached to a given ACP type on the `_meta` field.
10///
11/// The _meta property is reserved by ACP to allow Clients and Agents to attach
12/// additional metadata to their interactions. It is an object with string keys.
13/// Implementations MUST NOT assign meaning to keys they do not recognize.
14///
15/// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
16pub type Meta = serde_json::Map<String, serde_json::Value>;
17
18/// Applies the top-level `_meta` patch of an upsert update to stored metadata.
19///
20/// An omitted `update` leaves `stored` unchanged, and `null` clears it. An
21/// object patches `stored` one top-level key at a time: keys it omits keep
22/// their stored values, a key set to `null` is removed, and any other value
23/// replaces that key's stored value whole. Nested objects are not merged, and
24/// a `null` nested inside a value is kept as data. Removing every key leaves an
25/// empty object, which means the same as no metadata.
26///
27/// Use this for the top-level `_meta` of upsert updates such as
28/// [`ToolCallUpdate`](super::ToolCallUpdate),
29/// [`TerminalUpdate`](super::TerminalUpdate), message updates,
30/// [`SessionInfoUpdate`](super::SessionInfoUpdate), and
31/// [`CompactionUpdate`](super::CompactionUpdate). Other `_meta` fields are not
32/// patches.
33///
34/// See protocol docs: [Metadata Patches](https://agentclientprotocol.com/protocol/v2/extensibility#metadata-patches)
35pub fn apply_meta_update(stored: &mut MaybeUndefined<Meta>, update: MaybeUndefined<Meta>) {
36    match update {
37        MaybeUndefined::Undefined => {}
38        MaybeUndefined::Null => *stored = MaybeUndefined::Null,
39        MaybeUndefined::Value(patch) => {
40            let mut meta = match std::mem::take(stored) {
41                MaybeUndefined::Value(meta) => meta,
42                MaybeUndefined::Undefined | MaybeUndefined::Null => Meta::new(),
43            };
44            for (key, value) in patch {
45                if value.is_null() {
46                    meta.shift_remove(&key);
47                } else {
48                    meta.insert(key, value);
49                }
50            }
51            *stored = MaybeUndefined::Value(meta);
52        }
53    }
54}
55
56/// Allows for sending an arbitrary request that is not part of the ACP spec.
57///
58/// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
59#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
60#[derive(Debug, Clone, Serialize, Deserialize)]
61#[serde(transparent)]
62#[non_exhaustive]
63pub struct ExtRequest {
64    /// Wire method name for this extension request.
65    ///
66    /// Extension method names MUST start with `_`.
67    #[serde(skip)] // this is used for routing, but when serializing we only want the params
68    pub method: Arc<str>,
69    /// Raw JSON parameters for this extension message.
70    #[cfg_attr(feature = "schemars", schemars(with = "serde_json::Value"))]
71    pub params: Arc<RawValue>,
72}
73
74impl ExtRequest {
75    /// Builds [`ExtRequest`] with the required request fields set. Optional fields start unset or empty.
76    #[must_use]
77    pub fn new(method: impl Into<Arc<str>>, params: Arc<RawValue>) -> Self {
78        Self {
79            method: method.into(),
80            params,
81        }
82    }
83}
84
85/// Allows for sending an arbitrary response to an extension request that is not part of the ACP spec.
86///
87/// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
88#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
89#[derive(Debug, Clone, Serialize, Deserialize, From)]
90#[serde(transparent)]
91#[non_exhaustive]
92pub struct ExtResponse(
93    #[cfg_attr(feature = "schemars", schemars(with = "serde_json::Value"))] pub Arc<RawValue>,
94);
95
96impl ExtResponse {
97    /// Builds [`ExtResponse`] with the required response fields set. Optional fields start unset or empty.
98    #[must_use]
99    pub fn new(params: Arc<RawValue>) -> Self {
100        Self(params)
101    }
102}
103
104/// Allows either side to send an arbitrary notification that is not part of the ACP spec.
105///
106/// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
107#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
108#[derive(Debug, Clone, Serialize, Deserialize)]
109#[serde(transparent)]
110#[non_exhaustive]
111pub struct ExtNotification {
112    /// Wire method name for this extension notification.
113    ///
114    /// Extension method names MUST start with `_`.
115    #[serde(skip)] // this is used for routing, but when serializing we only want the params
116    pub method: Arc<str>,
117    /// Raw JSON parameters for this extension message.
118    #[cfg_attr(feature = "schemars", schemars(with = "serde_json::Value"))]
119    pub params: Arc<RawValue>,
120}
121
122impl ExtNotification {
123    /// Builds [`ExtNotification`] with the required notification fields set. Optional fields start unset or empty.
124    #[must_use]
125    pub fn new(method: impl Into<Arc<str>>, params: Arc<RawValue>) -> Self {
126        Self {
127            method: method.into(),
128            params,
129        }
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use serde_json::{from_value, json};
136
137    use super::*;
138
139    fn meta(value: serde_json::Value) -> MaybeUndefined<Meta> {
140        from_value(value).unwrap()
141    }
142
143    #[test]
144    fn meta_update_patches_top_level_keys() {
145        let mut stored = meta(json!({
146            "zed.dev/kept": 1,
147            "zed.dev/removed": true,
148            "acme.dev/nested": {"a": 1, "b": 2},
149            "acme.dev/list": [1, 2]
150        }));
151
152        apply_meta_update(
153            &mut stored,
154            meta(json!({
155                "zed.dev/removed": null,
156                "zed.dev/absent": null,
157                "acme.dev/nested": {"b": 3, "c": null},
158                "acme.dev/list": [3],
159                "acme.dev/added": []
160            })),
161        );
162
163        // Values replace the stored key whole instead of merging or appending,
164        // and nested nulls are data rather than removals.
165        assert_eq!(
166            stored,
167            meta(json!({
168                "zed.dev/kept": 1,
169                "acme.dev/nested": {"b": 3, "c": null},
170                "acme.dev/list": [3],
171                "acme.dev/added": []
172            }))
173        );
174    }
175
176    #[test]
177    fn meta_update_keeps_the_order_of_the_remaining_keys() {
178        let mut stored = meta(json!({ "zeta": 1, "alpha": 2, "mid": 3, "last": 4 }));
179        apply_meta_update(&mut stored, meta(json!({ "alpha": null })));
180        let MaybeUndefined::Value(stored) = stored else {
181            panic!("expected stored metadata");
182        };
183        assert_eq!(stored.keys().collect::<Vec<_>>(), ["zeta", "mid", "last"]);
184    }
185
186    #[test]
187    fn meta_update_omitted_empty_and_null() {
188        let original = meta(json!({"zed.dev/kept": 1}));
189        let mut stored = original.clone();
190
191        apply_meta_update(&mut stored, MaybeUndefined::Undefined);
192        assert_eq!(stored, original);
193
194        // An empty patch changes no keys.
195        apply_meta_update(&mut stored, meta(json!({})));
196        assert_eq!(stored, original);
197
198        apply_meta_update(&mut stored, MaybeUndefined::Null);
199        assert_eq!(stored, MaybeUndefined::Null);
200    }
201
202    #[test]
203    fn meta_update_starts_from_empty_after_clear_or_on_first_update() {
204        for initial in [MaybeUndefined::Undefined, MaybeUndefined::Null] {
205            let mut stored = initial;
206            apply_meta_update(
207                &mut stored,
208                meta(json!({"zed.dev/added": 1, "zed.dev/removed": null})),
209            );
210            // A `null` key value is never stored.
211            assert_eq!(stored, meta(json!({"zed.dev/added": 1})));
212        }
213    }
214}