Skip to main content

agent_client_protocol_schema/v2/
client.rs

1//! Methods and notifications the client handles/receives.
2//!
3//! This module defines the Client trait and all associated types for implementing
4//! a client that interacts with AI coding agents via the Agent Client Protocol (ACP).
5
6use std::{collections::BTreeMap, sync::Arc};
7
8use derive_more::{Display, From};
9#[cfg(feature = "schemars")]
10use schemars::Schema;
11use serde::{Deserialize, Serialize};
12use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
13
14#[cfg(feature = "unstable_auth_status")]
15use super::AuthStatusUpdateNotification;
16#[cfg(feature = "unstable_plan_operations")]
17use super::PlanRemoved;
18#[cfg(feature = "unstable_end_turn_token_usage")]
19use super::Usage;
20use super::{
21    AbsolutePath, ContentBlock, ExtNotification, ExtRequest, ExtResponse, Meta, PlanUpdate,
22    SessionConfigOption, SessionId, StopReason, TerminalId, TerminalOutputChunk, TerminalUpdate,
23    ToolCallContentChunk, ToolCallId, ToolCallUpdate,
24};
25use super::{
26    CompleteElicitationNotification, CreateElicitationRequest, CreateElicitationResponse,
27    ElicitationCapabilities,
28};
29use crate::{IntoMaybeUndefined, IntoOption, MaybeUndefined};
30
31#[cfg(feature = "unstable_mcp_over_acp")]
32use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpRequest, MessageMcpResponse};
33
34// Session updates
35
36/// Notification containing a session update from the agent.
37///
38/// Agents can send session updates at any point while the session exists.
39///
40/// See protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#3-agent-reports-output)
41#[serde_as]
42#[skip_serializing_none]
43#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
45#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_UPDATE_NOTIFICATION)))]
46#[serde(rename_all = "camelCase")]
47#[non_exhaustive]
48pub struct UpdateSessionNotification {
49    /// The ID of the session this update pertains to.
50    pub session_id: SessionId,
51    /// The actual update content.
52    pub update: SessionUpdate,
53    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
54    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
55    /// Implementations MUST NOT assign meaning to keys they do not recognize.
56    ///
57    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
58    #[serde_as(deserialize_as = "DefaultOnError")]
59    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
60    #[serde(default)]
61    #[serde(rename = "_meta")]
62    pub meta: Option<Meta>,
63}
64
65impl UpdateSessionNotification {
66    /// Builds [`UpdateSessionNotification`] with the required notification fields set. Optional fields start unset or empty.
67    #[must_use]
68    pub fn new(session_id: impl Into<SessionId>, update: SessionUpdate) -> Self {
69        Self {
70            session_id: session_id.into(),
71            update,
72            meta: None,
73        }
74    }
75
76    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
77    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
78    /// do not recognize.
79    ///
80    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
81    #[must_use]
82    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
83        self.meta = meta.into_option();
84        self
85    }
86}
87
88/// Different types of updates that can be sent while a session exists.
89///
90/// These updates report messages, progress, and other session activity.
91///
92/// See protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#3-agent-reports-output)
93#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
94#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
95#[serde(tag = "sessionUpdate", rename_all = "snake_case")]
96#[non_exhaustive]
97pub enum SessionUpdate {
98    /// A chunk of the user's message being streamed.
99    UserMessageChunk(ContentChunk),
100    /// A user message has been created or updated.
101    ///
102    /// Agents can send this when they accept or replay a user message. When a
103    /// client receives another `user_message` update with the same `messageId`,
104    /// fields in the new update patch the previous fields for that message.
105    UserMessage(UserMessage),
106    /// A chunk of the agent's response being streamed.
107    AgentMessageChunk(ContentChunk),
108    /// An agent message has been created or updated.
109    ///
110    /// Agents can send this in addition to streamed chunks. When a client
111    /// receives another `agent_message` update with the same `messageId`,
112    /// fields in the new update patch the previous fields for that message.
113    AgentMessage(AgentMessage),
114    /// A chunk of the agent's internal reasoning being streamed.
115    AgentThoughtChunk(ContentChunk),
116    /// An agent thought or reasoning message has been created or updated.
117    ///
118    /// Agents can send this in addition to streamed chunks. When a client
119    /// receives another `agent_thought` update with the same `messageId`,
120    /// fields in the new update patch the previous fields for that message.
121    AgentThought(AgentThought),
122    /// A snapshot of the session's aggregate foreground activity.
123    StateUpdate(StateUpdate),
124    /// A chunk of tool-call content being streamed.
125    ToolCallContentChunk(ToolCallContentChunk),
126    /// A tool call has been created or updated.
127    ToolCallUpdate(ToolCallUpdate),
128    /// An agent-owned terminal has been created or updated.
129    TerminalUpdate(TerminalUpdate),
130    /// A chunk of bytes appended to an agent-owned terminal's output.
131    TerminalOutputChunk(TerminalOutputChunk),
132    /// A content update for a plan identified by ID.
133    /// See protocol docs: [Agent Plan](https://agentclientprotocol.com/protocol/v2/agent-plan)
134    PlanUpdate(PlanUpdate),
135    /// **UNSTABLE**
136    ///
137    /// This capability is not part of the spec yet, and may be removed or changed at any point.
138    ///
139    /// Removal notice for a plan identified by ID.
140    #[cfg(feature = "unstable_plan_operations")]
141    PlanRemoved(PlanRemoved),
142    /// Available commands are ready or have changed
143    AvailableCommandsUpdate(AvailableCommandsUpdate),
144    /// Session configuration options have been updated.
145    ConfigOptionUpdate(ConfigOptionUpdate),
146    /// Session metadata has been updated (title, timestamps, custom metadata)
147    SessionInfoUpdate(SessionInfoUpdate),
148    /// Context window and cost update for the session.
149    UsageUpdate(UsageUpdate),
150    /// Information for the user that is not part of session history.
151    ///
152    /// No Client capability is required. Clients that do not understand or
153    /// present notices may ignore them.
154    Notice(Notice),
155    /// A context compaction has been created or updated.
156    CompactionUpdate(CompactionUpdate),
157    /// A content block appended to a context compaction's retained summary.
158    CompactionSummaryChunk(CompactionSummaryChunk),
159    /// The history replay requested by `session/resume` is complete for this session.
160    ///
161    /// Every update for the session between the `session/resume` request and
162    /// this update is replayed history. Every update after it is not.
163    ReplayComplete(ReplayComplete),
164    /// **UNSTABLE**
165    ///
166    /// This capability is not part of the spec yet, and may be removed or changed at any point.
167    ///
168    /// Replaces the session's current list of prompt suggestions.
169    ///
170    /// Agents MUST only send this update when the Client advertised
171    /// the `session.promptSuggestions` Client capability.
172    #[cfg(feature = "unstable_prompt_suggestions")]
173    PromptSuggestionsUpdate(PromptSuggestionsUpdate),
174    /// Announces a child session created and owned by this session, or updates
175    /// that ownership association's metadata.
176    SubagentUpdate(SubagentUpdate),
177    /// A message upsert observed in this session's transcript, sent to or
178    /// received from another session.
179    SessionMessage(SessionMessage),
180    /// One content block appended to a sent or received session message.
181    SessionMessageChunk(SessionMessageChunk),
182    /// Custom or future session update.
183    ///
184    /// Values beginning with `_` are reserved for implementation-specific
185    /// extensions. Unknown values that do not begin with `_` are reserved for
186    /// future ACP variants.
187    ///
188    /// Receivers that do not understand this update type should preserve the
189    /// raw payload when storing, replaying, proxying, or forwarding session
190    /// history, and otherwise ignore it or display it generically.
191    #[serde(untagged)]
192    Other(OtherSessionUpdate),
193}
194
195/// A streamed content block of an inter-session message.
196///
197/// A chunk carries only content. The message's participants and references come from
198/// `session_message` upserts, which can arrive before, between, or after its chunks.
199#[serde_as]
200#[skip_serializing_none]
201#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
202#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
203#[serde(rename_all = "camelCase")]
204#[non_exhaustive]
205pub struct SessionMessageChunk {
206    /// Identifier of this message within the enclosing session's transcript.
207    pub message_id: MessageId,
208    /// A single content block appended to the message.
209    pub content: ContentBlock,
210    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
211    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
212    /// Implementations MUST NOT assign meaning to keys they do not recognize.
213    /// This metadata is scoped to the chunk and does not patch stored metadata.
214    ///
215    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
216    #[serde_as(deserialize_as = "DefaultOnError")]
217    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
218    #[serde(default, rename = "_meta")]
219    pub meta: Option<Meta>,
220}
221
222impl SessionMessageChunk {
223    /// Builds a single streamed content block without chunk metadata.
224    #[must_use]
225    pub fn new(message_id: impl Into<MessageId>, content: ContentBlock) -> Self {
226        Self {
227            message_id: message_id.into(),
228            content,
229            meta: None,
230        }
231    }
232
233    /// Sets optional chunk-scoped metadata.
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/// An upsert for an inter-session message.
242#[serde_as]
243#[skip_serializing_none]
244#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
245#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
246#[serde(rename_all = "camelCase")]
247#[non_exhaustive]
248pub struct SessionMessage {
249    /// Identifier of this message within the enclosing session's transcript.
250    pub message_id: MessageId,
251    /// The sending session.
252    ///
253    /// Omitted leaves the stored value unchanged. `null` clears it. A value replaces it.
254    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
255    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
256    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
257    pub sender_session_id: MaybeUndefined<SessionId>,
258    /// The receiving session.
259    ///
260    /// Omitted leaves the stored value unchanged. `null` clears it. A value replaces it.
261    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
262    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
263    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
264    pub recipient_session_id: MaybeUndefined<SessionId>,
265    /// On an incoming view, the `messageId` of the same message's outgoing view in the
266    /// sender's transcript.
267    ///
268    /// Omitted leaves the stored value unchanged. `null` clears it. A value replaces it. It can arrive
269    /// after the message starts streaming.
270    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
271    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
272    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
273    pub sender_message_id: MaybeUndefined<MessageId>,
274    /// On an outgoing view, the `messageId` of the same message's incoming view in the
275    /// recipient's transcript.
276    ///
277    /// Omitted leaves the stored value unchanged. `null` clears it. A value replaces it. It can arrive
278    /// after the message starts streaming.
279    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
280    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
281    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
282    pub recipient_message_id: MaybeUndefined<MessageId>,
283    /// Omitted leaves content unchanged. `null` clears it. A concrete array
284    /// replaces the whole content collection.
285    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
286    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
287    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
288    pub content: MaybeUndefined<Vec<ContentBlock>>,
289    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
290    /// metadata to their interactions. Omitted leaves the stored metadata unchanged. `null`
291    /// clears it. An object patches the stored metadata by top-level key: keys it omits are
292    /// unchanged, a key set to `null` is removed, and any other value replaces that key's
293    /// stored value without merging nested objects. Beyond this patch rule, implementations
294    /// MUST NOT assign meaning to keys they do not recognize.
295    ///
296    /// See protocol docs: [Metadata Patches](https://agentclientprotocol.com/protocol/v2/extensibility#metadata-patches)
297    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
298    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
299    #[serde(
300        default,
301        rename = "_meta",
302        skip_serializing_if = "MaybeUndefined::is_undefined"
303    )]
304    pub meta: MaybeUndefined<Meta>,
305}
306
307impl SessionMessage {
308    /// Builds a message upsert with its transcript-local ID.
309    #[must_use]
310    pub fn new(message_id: impl Into<MessageId>) -> Self {
311        Self {
312            message_id: message_id.into(),
313            sender_session_id: MaybeUndefined::Undefined,
314            recipient_session_id: MaybeUndefined::Undefined,
315            sender_message_id: MaybeUndefined::Undefined,
316            recipient_message_id: MaybeUndefined::Undefined,
317            content: MaybeUndefined::Undefined,
318            meta: MaybeUndefined::Undefined,
319        }
320    }
321
322    /// Sets, clears, or leaves unchanged the sending session.
323    #[must_use]
324    pub fn sender_session_id(
325        mut self,
326        sender_session_id: impl IntoMaybeUndefined<SessionId>,
327    ) -> Self {
328        self.sender_session_id = sender_session_id.into_maybe_undefined();
329        self
330    }
331
332    /// Sets, clears, or leaves unchanged the receiving session.
333    #[must_use]
334    pub fn recipient_session_id(
335        mut self,
336        recipient_session_id: impl IntoMaybeUndefined<SessionId>,
337    ) -> Self {
338        self.recipient_session_id = recipient_session_id.into_maybe_undefined();
339        self
340    }
341
342    /// Links an incoming view to the outgoing view's message ID in the sender's transcript.
343    #[must_use]
344    pub fn sender_message_id(
345        mut self,
346        sender_message_id: impl IntoMaybeUndefined<MessageId>,
347    ) -> Self {
348        self.sender_message_id = sender_message_id.into_maybe_undefined();
349        self
350    }
351
352    /// Links an outgoing view to the incoming view's message ID in the recipient's transcript.
353    #[must_use]
354    pub fn recipient_message_id(
355        mut self,
356        recipient_message_id: impl IntoMaybeUndefined<MessageId>,
357    ) -> Self {
358        self.recipient_message_id = recipient_message_id.into_maybe_undefined();
359        self
360    }
361
362    /// Replaces, clears, or leaves unchanged the message content.
363    #[must_use]
364    pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
365        self.content = content.into_maybe_undefined();
366        self
367    }
368
369    /// Patches, clears, or leaves unchanged message metadata.
370    ///
371    /// A concrete object patches stored metadata by top-level key. See
372    /// [`apply_meta_update`](super::apply_meta_update).
373    #[must_use]
374    pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
375        self.meta = meta.into_maybe_undefined();
376        self
377    }
378}
379
380#[cfg(test)]
381mod session_message_tests {
382    use super::*;
383    use serde_json::{Value, json};
384
385    #[test]
386    fn transcript_envelopes_and_multimodal_content() {
387        for (transcript, sender, recipient, id) in [
388            ("parent", "parent", "child", "sent-1"),
389            ("child", "parent", "child", "received-9"),
390            ("child", "child", "parent", "sent-2"),
391        ] {
392            let wire = json!({"sessionId": transcript, "update": {
393                "sessionUpdate": "session_message", "messageId": id,
394                "senderSessionId": sender, "recipientSessionId": recipient, "content": [
395                    {"type": "text", "text": "hello"},
396                    {"type": "image", "data": "aGVsbG8=", "mimeType": "image/png"}
397                ]
398            }});
399            let decoded: UpdateSessionNotification = serde_json::from_value(wire.clone()).unwrap();
400            assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
401        }
402    }
403
404    #[test]
405    fn chunks_and_upserts_share_transcript_local_identity() {
406        for (transcript, id) in [("parent", "sent-1"), ("child", "received-9")] {
407            let wire = json!({"sessionId": transcript, "update": {
408                "sessionUpdate": "session_message_chunk", "messageId": id,
409                "content": {"type": "text", "text": "hello"}
410            }});
411            let decoded: UpdateSessionNotification = serde_json::from_value(wire.clone()).unwrap();
412            assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
413            let upsert = SessionMessage::new(id)
414                .sender_session_id(SessionId::new("parent"))
415                .recipient_session_id(SessionId::new("child"))
416                .content(vec![]);
417            let chunk = SessionMessageChunk::new(
418                id,
419                ContentBlock::Text(crate::v2::TextContent::new("hello")),
420            );
421            assert_eq!(chunk.message_id, upsert.message_id);
422            assert_eq!(
423                serde_json::to_value(SessionUpdate::SessionMessageChunk(chunk)).unwrap(),
424                wire["update"]
425            );
426            assert_eq!(serde_json::to_value(upsert).unwrap()["content"], json!([]));
427        }
428        // A chunk carries only content, so identity fields on one are not part of it.
429        let with_identity = json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
430            "senderSessionId": "parent", "recipientSessionId": "child",
431            "senderMessageId": "sent-1", "recipientMessageId": "received-1",
432            "content": {"type": "text", "text": "hello"}});
433        let decoded: SessionUpdate = serde_json::from_value(with_identity).unwrap();
434        assert_eq!(
435            serde_json::to_value(decoded).unwrap(),
436            json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
437                "content": {"type": "text", "text": "hello"}})
438        );
439    }
440
441    #[test]
442    fn required_ids_and_chunk_content_with_upsert_patch_semantics() {
443        for (kind, content) in [
444            ("session_message", json!([])),
445            (
446                "session_message_chunk",
447                json!({"type": "text", "text": "hello"}),
448            ),
449        ] {
450            let mut base = json!({"sessionUpdate": kind, "messageId": "m1", "content": content});
451            if kind == "session_message" {
452                base["senderSessionId"] = json!("parent");
453                base["recipientSessionId"] = json!("child");
454            }
455            {
456                let key = "messageId";
457                let mut missing = base.clone();
458                missing.as_object_mut().unwrap().remove(key);
459                assert!(
460                    serde_json::from_value::<SessionUpdate>(missing).is_err(),
461                    "{kind} {key}"
462                );
463                let mut null = base.clone();
464                null[key] = Value::Null;
465                assert!(
466                    serde_json::from_value::<SessionUpdate>(null).is_err(),
467                    "{kind} {key}"
468                );
469                let mut non_string = base.clone();
470                non_string[key] = json!(42);
471                assert!(
472                    serde_json::from_value::<SessionUpdate>(non_string).is_err(),
473                    "{kind} {key}"
474                );
475            }
476            if kind == "session_message_chunk" {
477                for content in [None, Some(Value::Null), Some(json!([]))] {
478                    let mut invalid = base.clone();
479                    invalid.as_object_mut().unwrap().remove("content");
480                    if let Some(content) = content {
481                        invalid["content"] = content;
482                    }
483                    assert!(serde_json::from_value::<SessionUpdate>(invalid).is_err());
484                }
485            } else {
486                for content in [None, Some(Value::Null), Some(json!([])), Some(json!({}))] {
487                    let mut wire = base.clone();
488                    wire.as_object_mut().unwrap().remove("content");
489                    if let Some(content) = content {
490                        wire["content"] = content;
491                    }
492                    let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
493                    let encoded = serde_json::to_value(decoded).unwrap();
494                    if wire["content"].is_object() {
495                        wire.as_object_mut().unwrap().remove("content");
496                    }
497                    assert_eq!(encoded, wire);
498                }
499            }
500            for meta in [None, Some(Value::Null), Some(json!({"tag": "value"}))] {
501                let mut wire = base.clone();
502                if let Some(meta) = meta {
503                    wire["_meta"] = meta;
504                }
505                let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
506                let encoded = serde_json::to_value(decoded).unwrap();
507                if kind == "session_message" {
508                    assert_eq!(encoded, wire);
509                } else if wire["_meta"].is_null() {
510                    assert_eq!(encoded, base);
511                } else {
512                    assert_eq!(encoded, wire);
513                }
514            }
515        }
516        let metadata_only = json!({"sessionUpdate": "session_message",
517            "messageId": "m1", "senderSessionId": "parent",
518            "recipientSessionId": "child", "_meta": {"tag": "value"}});
519        let decoded: SessionUpdate = serde_json::from_value(metadata_only.clone()).unwrap();
520        assert_eq!(serde_json::to_value(decoded).unwrap(), metadata_only);
521        let cleared = SessionMessage::new("m1")
522            .sender_session_id(SessionId::new("parent"))
523            .recipient_session_id(SessionId::new("child"))
524            .content(None)
525            .meta(None);
526        assert_eq!(
527            serde_json::to_value(cleared).unwrap(),
528            json!({"messageId": "m1", "senderSessionId": "parent",
529                "recipientSessionId": "child", "content": null, "_meta": null})
530        );
531    }
532
533    #[cfg(feature = "schemars")]
534    #[test]
535    fn schemas_require_ids_and_chunk_content_but_not_upsert_content() {
536        let upsert = serde_json::to_value(schemars::schema_for!(SessionMessage)).unwrap();
537        let required = upsert["required"].as_array().unwrap();
538        assert_eq!(required, &vec![json!("messageId")]);
539        let chunk = serde_json::to_value(schemars::schema_for!(SessionMessageChunk)).unwrap();
540        let required = chunk["required"].as_array().unwrap();
541        assert_eq!(required.len(), 2);
542        assert!(required.contains(&json!("messageId")));
543        assert!(required.contains(&json!("content")));
544    }
545
546    #[test]
547    fn endpoints_can_arrive_late_or_be_omitted_from_later_events() {
548        let block = ContentBlock::Text(crate::v2::TextContent::new("hello"));
549        let minimal = SessionMessage::new("m1");
550        let first = SessionMessageChunk::new("m1", block.clone());
551        assert_eq!(
552            serde_json::to_value(&minimal).unwrap(),
553            json!({"messageId": "m1"})
554        );
555        assert_eq!(
556            serde_json::to_value(&first).unwrap(),
557            json!({"messageId": "m1", "content": {"type": "text", "text": "hello"}})
558        );
559        let enriched = SessionMessage::new("m1")
560            .sender_session_id(SessionId::new("parent"))
561            .recipient_session_id(SessionId::new("child"));
562        assert_eq!(
563            enriched.sender_session_id,
564            MaybeUndefined::Value(SessionId::new("parent"))
565        );
566        assert_eq!(
567            enriched.recipient_session_id,
568            MaybeUndefined::Value(SessionId::new("child"))
569        );
570        let later = SessionMessage::new("m1").sender_session_id(SessionId::new("parent"));
571        assert_eq!(
572            later.sender_session_id,
573            MaybeUndefined::Value(SessionId::new("parent"))
574        );
575        assert_eq!(later.recipient_session_id, MaybeUndefined::Undefined);
576        let more = SessionMessageChunk::new("m1", block);
577        for update in [
578            SessionUpdate::SessionMessage(minimal),
579            SessionUpdate::SessionMessageChunk(first),
580            SessionUpdate::SessionMessage(enriched),
581            SessionUpdate::SessionMessage(later),
582            SessionUpdate::SessionMessageChunk(more),
583        ] {
584            let wire = serde_json::to_value(&update).unwrap();
585            let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
586            assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
587        }
588    }
589
590    #[test]
591    fn null_endpoints_clear_invalid_are_absent_but_message_id_is_required() {
592        let mut base = json!({"sessionUpdate": "session_message", "messageId": "m1",
593            "senderSessionId": null, "recipientSessionId": 42});
594        let decoded: SessionUpdate = serde_json::from_value(base.clone()).unwrap();
595        let encoded = serde_json::to_value(decoded).unwrap();
596        base.as_object_mut().unwrap().remove("recipientSessionId");
597        assert_eq!(encoded, base);
598        for bad in [Value::Null, json!(42)] {
599            let mut invalid = base.clone();
600            invalid["messageId"] = bad;
601            assert!(serde_json::from_value::<SessionUpdate>(invalid).is_err());
602        }
603    }
604
605    #[test]
606    fn message_references_link_views_and_can_arrive_late() {
607        let block = ContentBlock::Text(crate::v2::TextContent::new("hello"));
608        let incoming = SessionMessage::new("received-1")
609            .sender_session_id(SessionId::new("parent"))
610            .recipient_session_id(SessionId::new("child"))
611            .sender_message_id(MessageId::new("sent-1"))
612            .content(vec![block]);
613        // The outgoing view gets its reference after it started, with a metadata-only upsert.
614        let outgoing =
615            SessionMessage::new("sent-1").recipient_message_id(MessageId::new("received-1"));
616        for (update, wire) in [
617            (
618                SessionUpdate::SessionMessage(incoming),
619                json!({"sessionUpdate": "session_message", "messageId": "received-1",
620                    "senderSessionId": "parent", "recipientSessionId": "child",
621                    "senderMessageId": "sent-1", "content": [{"type": "text", "text": "hello"}]}),
622            ),
623            (
624                SessionUpdate::SessionMessage(outgoing),
625                json!({"sessionUpdate": "session_message", "messageId": "sent-1",
626                    "recipientMessageId": "received-1"}),
627            ),
628        ] {
629            assert_eq!(serde_json::to_value(&update).unwrap(), wire);
630            let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
631            assert_eq!(decoded, update);
632        }
633
634        let mut wire = json!({"sessionUpdate": "session_message", "messageId": "m1",
635            "senderMessageId": null, "recipientMessageId": 42});
636        let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
637        wire.as_object_mut().unwrap().remove("recipientMessageId");
638        assert_eq!(
639            serde_json::to_value(decoded).unwrap(),
640            wire,
641            "null clears a reference and a malformed one is not supplied"
642        );
643    }
644}
645
646/// Severity hint for a session notice.
647#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
648#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
649#[serde(rename_all = "snake_case")]
650#[non_exhaustive]
651pub enum NoticeSeverity {
652    /// Informational notice.
653    Info,
654    /// Warning notice.
655    Warning,
656    /// Error notice.
657    Error,
658    /// Custom or future notice severity.
659    ///
660    /// Values beginning with `_` are reserved for implementation-specific
661    /// extensions. Other unknown values are reserved for future ACP severities.
662    #[serde(untagged)]
663    Other(String),
664}
665
666/// Fire-and-forget information for the user.
667///
668/// Notices are live events rather than session history. Agents must not rely on
669/// a notice being received, displayed, or seen by the user.
670/// No Client capability is required, and unsupported Clients may ignore notices.
671///
672/// See protocol docs: [Session Notices](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#session-notices)
673#[serde_as]
674#[skip_serializing_none]
675#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
676#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
677#[serde(rename_all = "camelCase")]
678#[non_exhaustive]
679pub struct Notice {
680    /// Presentation severity hint.
681    pub severity: NoticeSeverity,
682    /// Required non-empty plain-text title that can stand alone.
683    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
684    pub title: String,
685    /// Optional plain-text detail or guidance.
686    ///
687    /// Omitted and `null` are equivalent and mean no description was supplied.
688    #[serde_as(deserialize_as = "DefaultOnError")]
689    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
690    #[serde(default)]
691    pub description: Option<String>,
692    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
693    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
694    /// Implementations MUST NOT assign meaning to keys they do not recognize.
695    ///
696    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
697    #[serde_as(deserialize_as = "DefaultOnError")]
698    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
699    #[serde(default, rename = "_meta")]
700    pub meta: Option<Meta>,
701}
702
703impl Notice {
704    /// Builds a notice with the required fields set and optional fields omitted.
705    #[must_use]
706    pub fn new(severity: NoticeSeverity, title: impl Into<String>) -> Self {
707        Self {
708            severity,
709            title: title.into(),
710            description: None,
711            meta: None,
712        }
713    }
714
715    /// Sets or clears the optional description.
716    #[must_use]
717    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
718        self.description = description.into_option();
719        self
720    }
721
722    /// Sets or clears notice-scoped metadata.
723    #[must_use]
724    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
725        self.meta = meta.into_option();
726        self
727    }
728}
729
730/// Unique identifier for a context compaction within a session.
731#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
732#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
733#[serde(transparent)]
734#[from(forward)]
735#[non_exhaustive]
736pub struct CompactionId(pub Arc<str>);
737
738impl CompactionId {
739    /// Wraps a protocol string as a typed [`CompactionId`].
740    #[must_use]
741    pub fn new(id: impl Into<Self>) -> Self {
742        id.into()
743    }
744}
745
746/// Lifecycle state of a context compaction.
747#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
748#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
749#[serde(rename_all = "snake_case")]
750#[non_exhaustive]
751pub enum CompactionStatus {
752    /// Compaction has started and has not finished.
753    #[default]
754    InProgress,
755    /// Compaction finished successfully.
756    Completed,
757    /// Compaction finished unsuccessfully.
758    Failed,
759    /// Compaction was cancelled before it finished.
760    Cancelled,
761    /// Custom or future compaction status.
762    ///
763    /// Values beginning with `_` are reserved for implementation-specific
764    /// extensions. Other unknown values are reserved for future ACP statuses.
765    #[serde(untagged)]
766    Other(String),
767}
768
769/// A context compaction upsert. The first notification fixes the compaction's
770/// timeline position. Later updates with the same ID patch that entity in place.
771///
772/// `summary`, `error`, and `_meta` have patch semantics: omission leaves the
773/// stored value unchanged, `null` clears it, and a concrete value replaces it.
774/// `summary: []` also clears the summary. A concrete `_meta` object patches the
775/// stored metadata by top-level key instead of replacing it.
776#[serde_as]
777#[skip_serializing_none]
778#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
779#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
780#[serde(rename_all = "camelCase")]
781#[non_exhaustive]
782pub struct CompactionUpdate {
783    /// The Agent-owned ID of this compaction, unique within the session.
784    pub compaction_id: CompactionId,
785    /// Current lifecycle status.
786    pub status: CompactionStatus,
787    /// Complete replacement user-displayable summary content for the compaction.
788    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
789    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
790    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
791    pub summary: MaybeUndefined<Vec<ContentBlock>>,
792    /// Human-readable error details for the compaction.
793    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
794    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
795    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
796    pub error: MaybeUndefined<String>,
797    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
798    /// metadata to their interactions. Omitted leaves the stored metadata unchanged. `null`
799    /// clears it. An object patches the stored metadata by top-level key: keys it omits are
800    /// unchanged, a key set to `null` is removed, and any other value replaces that key's
801    /// stored value without merging nested objects. Beyond this patch rule, implementations
802    /// MUST NOT assign meaning to keys they do not recognize.
803    ///
804    /// See protocol docs: [Metadata Patches](https://agentclientprotocol.com/protocol/v2/extensibility#metadata-patches)
805    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
806    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
807    #[serde(
808        rename = "_meta",
809        default,
810        skip_serializing_if = "MaybeUndefined::is_undefined"
811    )]
812    pub meta: MaybeUndefined<Meta>,
813}
814
815impl CompactionUpdate {
816    /// Builds a compaction update with optional patch fields omitted.
817    #[must_use]
818    pub fn new(compaction_id: impl Into<CompactionId>, status: CompactionStatus) -> Self {
819        Self {
820            compaction_id: compaction_id.into(),
821            status,
822            summary: MaybeUndefined::Undefined,
823            error: MaybeUndefined::Undefined,
824            meta: MaybeUndefined::Undefined,
825        }
826    }
827
828    /// Sets, clears, or omits the complete retained summary patch.
829    #[must_use]
830    pub fn summary(mut self, summary: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
831        self.summary = summary.into_maybe_undefined();
832        self
833    }
834
835    /// Sets, clears, or omits the error details patch.
836    #[must_use]
837    pub fn error(mut self, error: impl IntoMaybeUndefined<String>) -> Self {
838        self.error = error.into_maybe_undefined();
839        self
840    }
841
842    /// Patches, clears, or leaves unchanged compaction metadata.
843    ///
844    /// A concrete object patches stored metadata by top-level key. See
845    /// [`apply_meta_update`](super::apply_meta_update).
846    #[must_use]
847    pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
848        self.meta = meta.into_maybe_undefined();
849        self
850    }
851}
852
853/// A content block appended to a compaction's summary. A first-seen ID creates
854/// an in-progress compaction. Chunks append in receive order.
855#[serde_as]
856#[skip_serializing_none]
857#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
858#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
859#[serde(rename_all = "camelCase")]
860#[non_exhaustive]
861pub struct CompactionSummaryChunk {
862    /// ID of the compaction whose summary receives this content.
863    pub compaction_id: CompactionId,
864    /// One content block to append.
865    pub content: ContentBlock,
866    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
867    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
868    /// Implementations MUST NOT assign meaning to keys they do not recognize.
869    /// This metadata is scoped to the chunk and does not patch stored metadata.
870    ///
871    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
872    #[serde_as(deserialize_as = "DefaultOnError")]
873    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
874    #[serde(default, rename = "_meta")]
875    pub meta: Option<Meta>,
876}
877
878impl CompactionSummaryChunk {
879    /// Builds a summary chunk without metadata.
880    #[must_use]
881    pub fn new(compaction_id: impl Into<CompactionId>, content: ContentBlock) -> Self {
882        Self {
883            compaction_id: compaction_id.into(),
884            content,
885            meta: None,
886        }
887    }
888
889    /// Sets or clears chunk-scoped metadata.
890    #[must_use]
891    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
892        self.meta = meta.into_option();
893        self
894    }
895}
896
897/// Marks the end of the history replay requested by `session/resume`.
898///
899/// The Agent sends this once on a session for each `session/resume` request
900/// with a `replayFrom` cursor, after the last replayed update for that session
901/// and before the response. It sends it for an empty history too. Every update
902/// for the session between the request and this update is replayed history.
903/// Every update after it is not.
904///
905/// The Agent does not send it when `replayFrom` is omitted or `null`, or when
906/// it cannot finish the replay. A resume that ends without it delivered a
907/// truncated replay.
908///
909/// See protocol docs: [Replay Complete](https://agentclientprotocol.com/protocol/v2/session-setup#replay-complete)
910#[serde_as]
911#[skip_serializing_none]
912#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
913#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
914#[serde(rename_all = "camelCase")]
915#[non_exhaustive]
916pub struct ReplayComplete {
917    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
918    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
919    /// Implementations MUST NOT assign meaning to keys they do not recognize.
920    ///
921    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
922    #[serde_as(deserialize_as = "DefaultOnError")]
923    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
924    #[serde(default, rename = "_meta")]
925    pub meta: Option<Meta>,
926}
927
928impl ReplayComplete {
929    /// Builds [`ReplayComplete`] with no metadata.
930    #[must_use]
931    pub fn new() -> Self {
932        Self::default()
933    }
934
935    /// Sets or clears optional metadata.
936    #[must_use]
937    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
938        self.meta = meta.into_option();
939        self
940    }
941}
942
943/// Notification that the enclosing parent session created and owns a child session.
944///
945/// Later updates modify the existing association's metadata, not its ownership.
946///
947/// Sent on the immediate parent session. The first update for an unknown
948/// `sessionId` announces the child and MUST be sent
949/// before any live request or notification bearing the child's session ID,
950/// including messages naming it as sender or recipient. Child events are
951/// delivered automatically. No separate child load, resume, or subscription is needed.
952/// Understanding this update, registering child sessions, and applying their
953/// operation restrictions are baseline v2 requirements. No Client capability
954/// is required.
955///
956/// Only `sessionId` is required. Other fields have
957/// patch semantics: omitted fields leave the stored value unchanged, `null`
958/// clears or unsets the value, and concrete values replace it. A concrete
959/// `_meta` object instead patches the stored metadata by top-level key. For
960/// `state`, `null` removes the current state report and leaves activity
961/// unconfirmed. It does not report idle or cancellation. A child whose capabilities are
962/// unset permits no Client-initiated session mutations.
963///
964/// `cwd` and `additionalDirectories` report where the Agent placed the child.
965/// While unset, each inherits the immediate parent's effective value.
966/// The title and description provide the parent's display metadata for the
967/// child. Agents SHOULD mirror known child state changes in the parent's
968/// `state` using the same `StateUpdate` snapshot as the
969/// ordinary `state_update` notification on the child session. This reports
970/// child state, not a separate parent-owned lifecycle. Consumers should
971/// treat duplicate reports idempotently.
972/// Completing or cancelling work does not end the association: the parent may
973/// message the same child again. Individual messages and their outcomes do not
974/// change this association.
975#[serde_as]
976#[skip_serializing_none]
977#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
978#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
979#[serde(rename_all = "camelCase")]
980#[non_exhaustive]
981pub struct SubagentUpdate {
982    /// The opaque session ID identifying the child in all ACP messages.
983    pub session_id: SessionId,
984    /// The parent's human-readable display title for this child. It need not be unique.
985    ///
986    /// Optional and nullable. Omitted means unchanged. `null` clears it. If no
987    /// title is set, the Client chooses a fallback presentation.
988    #[serde_as(deserialize_as = "DefaultOnError")]
989    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
990    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
991    pub title: MaybeUndefined<String>,
992    /// The parent's human-readable description of the child's role or purpose.
993    ///
994    /// Optional and nullable. Omitted means unchanged. `null` clears it. This is
995    /// current display metadata, not the history of instructions sent to the child.
996    #[serde_as(deserialize_as = "DefaultOnError")]
997    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
998    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
999    pub description: MaybeUndefined<String>,
1000    /// Client-initiated session mutations permitted for this subagent session.
1001    ///
1002    /// Read-only operations retain their normal protocol semantics and
1003    /// capability requirements.
1004    #[serde_as(deserialize_as = "DefaultOnError")]
1005    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1006    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1007    pub capabilities: MaybeUndefined<SubagentSessionCapabilities>,
1008    /// The child's current foreground state, mirrored onto its parent association.
1009    ///
1010    /// Optional and nullable. Omitted means unchanged. `null` removes the
1011    /// current report and leaves activity unconfirmed (not idle or cancelled).
1012    /// A concrete `StateUpdate` replaces the entire previous snapshot.
1013    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1014    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1015    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1016    pub state: MaybeUndefined<StateUpdate>,
1017    /// The child's working directory. Must be an absolute path.
1018    ///
1019    /// Optional and nullable. Omitted means unchanged. `null` clears the
1020    /// reported value. While unset, the child inherits its immediate parent's
1021    /// effective working directory.
1022    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1023    pub cwd: MaybeUndefined<AbsolutePath>,
1024    /// Additional workspace roots for the child. Each path must be absolute.
1025    ///
1026    /// Optional and nullable. Omitted means unchanged. `null` clears the
1027    /// reported value. While unset, the child inherits its immediate parent's
1028    /// effective additional directories, independently of `cwd`. A concrete
1029    /// array replaces the whole list. `[]` reports no additional directories.
1030    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1031    pub additional_directories: MaybeUndefined<Vec<AbsolutePath>>,
1032    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1033    /// metadata to their interactions. Omitted leaves the stored metadata unchanged. `null`
1034    /// clears it. An object patches the stored metadata by top-level key: keys it omits are
1035    /// unchanged, a key set to `null` is removed, and any other value replaces that key's
1036    /// stored value without merging nested objects. Beyond this patch rule, implementations
1037    /// MUST NOT assign meaning to keys they do not recognize.
1038    ///
1039    /// See protocol docs: [Metadata Patches](https://agentclientprotocol.com/protocol/v2/extensibility#metadata-patches)
1040    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1041    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1042    #[serde(
1043        rename = "_meta",
1044        default,
1045        skip_serializing_if = "MaybeUndefined::is_undefined"
1046    )]
1047    pub meta: MaybeUndefined<Meta>,
1048}
1049
1050impl SubagentUpdate {
1051    /// Builds a subagent upsert with only its required session ID set.
1052    #[must_use]
1053    pub fn new(session_id: impl Into<SessionId>) -> Self {
1054        Self {
1055            session_id: session_id.into(),
1056            title: MaybeUndefined::Undefined,
1057            description: MaybeUndefined::Undefined,
1058            capabilities: MaybeUndefined::Undefined,
1059            state: MaybeUndefined::Undefined,
1060            cwd: MaybeUndefined::Undefined,
1061            additional_directories: MaybeUndefined::Undefined,
1062            meta: MaybeUndefined::Undefined,
1063        }
1064    }
1065
1066    /// Sets, clears, or leaves unchanged the parent's display title for the child.
1067    #[must_use]
1068    pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
1069        self.title = title.into_maybe_undefined();
1070        self
1071    }
1072
1073    /// Sets, clears, or leaves unchanged the parent's description of the child.
1074    #[must_use]
1075    pub fn description(mut self, description: impl IntoMaybeUndefined<String>) -> Self {
1076        self.description = description.into_maybe_undefined();
1077        self
1078    }
1079
1080    /// Sets, clears, or leaves unchanged the permitted client-initiated session mutations.
1081    #[must_use]
1082    pub fn capabilities(
1083        mut self,
1084        capabilities: impl IntoMaybeUndefined<SubagentSessionCapabilities>,
1085    ) -> Self {
1086        self.capabilities = capabilities.into_maybe_undefined();
1087        self
1088    }
1089
1090    /// Replaces, clears, or leaves unchanged the child's mirrored state snapshot.
1091    #[must_use]
1092    pub fn state(mut self, state: impl IntoMaybeUndefined<StateUpdate>) -> Self {
1093        self.state = state.into_maybe_undefined();
1094        self
1095    }
1096
1097    /// Sets, clears, or leaves unchanged the child's working directory.
1098    ///
1099    /// While unset, the child inherits its parent's working directory.
1100    #[must_use]
1101    pub fn cwd(mut self, cwd: impl IntoMaybeUndefined<AbsolutePath>) -> Self {
1102        self.cwd = cwd.into_maybe_undefined();
1103        self
1104    }
1105
1106    /// Replaces, clears, or leaves unchanged the child's additional directories.
1107    ///
1108    /// While unset, the child inherits its parent's additional directories.
1109    #[must_use]
1110    pub fn additional_directories(
1111        mut self,
1112        additional_directories: impl IntoMaybeUndefined<Vec<AbsolutePath>>,
1113    ) -> Self {
1114        self.additional_directories = additional_directories.into_maybe_undefined();
1115        self
1116    }
1117
1118    /// Patches, clears, or leaves unchanged subagent metadata.
1119    ///
1120    /// A concrete object patches stored metadata by top-level key. See
1121    /// [`apply_meta_update`](super::apply_meta_update).
1122    #[must_use]
1123    pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1124        self.meta = meta.into_maybe_undefined();
1125        self
1126    }
1127}
1128
1129/// Client-initiated session mutations permitted for a specific subagent session.
1130///
1131/// A mutation requires an explicit per-child capability. Support for the method
1132/// on ordinary sessions does not grant support on a child.
1133#[serde_as]
1134#[skip_serializing_none]
1135#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1136#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1137#[serde(rename_all = "camelCase")]
1138#[non_exhaustive]
1139pub struct SubagentSessionCapabilities {
1140    /// Permits the client to cancel this child's current work without ending
1141    /// the session. Omitted and `null` are equivalent and mean unsupported. An object (including
1142    /// `{}`) means supported.
1143    #[serde_as(deserialize_as = "DefaultOnError")]
1144    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1145    #[serde(default)]
1146    pub cancel: Option<SessionCancelCapabilities>,
1147    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1148    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1149    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1150    ///
1151    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1152    #[serde_as(deserialize_as = "DefaultOnError")]
1153    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1154    #[serde(default)]
1155    #[serde(rename = "_meta")]
1156    pub meta: Option<Meta>,
1157}
1158
1159impl SubagentSessionCapabilities {
1160    /// Builds an empty capability set. Cancellation is disabled.
1161    #[must_use]
1162    pub fn new() -> Self {
1163        Self::default()
1164    }
1165
1166    /// Sets or removes permission to cancel this child's current work.
1167    #[must_use]
1168    pub fn cancel(mut self, cancel: impl IntoOption<SessionCancelCapabilities>) -> Self {
1169        self.cancel = cancel.into_option();
1170        self
1171    }
1172
1173    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1174    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1175    /// do not recognize.
1176    #[must_use]
1177    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1178        self.meta = meta.into_option();
1179        self
1180    }
1181}
1182
1183/// Capability to cancel work in a subagent session without ending that session.
1184///
1185/// Supplying `{}` advertises support. An omitted or `null` `cancel` does not.
1186#[serde_as]
1187#[skip_serializing_none]
1188#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1189#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1190#[non_exhaustive]
1191pub struct SessionCancelCapabilities {
1192    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1193    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1194    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1195    ///
1196    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1197    #[serde_as(deserialize_as = "DefaultOnError")]
1198    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1199    #[serde(default)]
1200    #[serde(rename = "_meta")]
1201    pub meta: Option<Meta>,
1202}
1203
1204impl SessionCancelCapabilities {
1205    /// Builds an empty capability object advertising cancellation support.
1206    #[must_use]
1207    pub fn new() -> Self {
1208        Self::default()
1209    }
1210
1211    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1212    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1213    /// do not recognize.
1214    ///
1215    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1216    #[must_use]
1217    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1218        self.meta = meta.into_option();
1219        self
1220    }
1221}
1222
1223/// Custom or future session update payload.
1224///
1225/// This preserves the unknown `sessionUpdate` discriminator and the rest of the
1226/// update object for clients that store, replay, proxy, or forward session
1227/// history.
1228#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1229#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1230#[cfg_attr(feature = "schemars", schemars(inline))]
1231#[cfg_attr(feature = "schemars", schemars(transform = other_session_update_schema))]
1232#[serde(rename_all = "camelCase")]
1233#[non_exhaustive]
1234pub struct OtherSessionUpdate {
1235    /// Custom or future session update type.
1236    ///
1237    /// Values beginning with `_` are reserved for implementation-specific
1238    /// extensions. Unknown values that do not begin with `_` are reserved for
1239    /// future ACP variants.
1240    #[serde(rename = "sessionUpdate")]
1241    pub session_update: String,
1242    /// Additional fields from the unknown update payload.
1243    #[serde(flatten)]
1244    pub fields: BTreeMap<String, serde_json::Value>,
1245}
1246
1247impl OtherSessionUpdate {
1248    /// Builds [`OtherSessionUpdate`] from an unknown discriminator and preserves the remaining extension fields.
1249    #[must_use]
1250    pub fn new(
1251        session_update: impl Into<String>,
1252        mut fields: BTreeMap<String, serde_json::Value>,
1253    ) -> Self {
1254        fields.remove("sessionUpdate");
1255        Self {
1256            session_update: session_update.into(),
1257            fields,
1258        }
1259    }
1260}
1261
1262impl<'de> Deserialize<'de> for OtherSessionUpdate {
1263    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1264    where
1265        D: serde::Deserializer<'de>,
1266    {
1267        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1268        let session_update = fields
1269            .remove("sessionUpdate")
1270            .ok_or_else(|| serde::de::Error::missing_field("sessionUpdate"))?;
1271        let serde_json::Value::String(session_update) = session_update else {
1272            return Err(serde::de::Error::custom("`sessionUpdate` must be a string"));
1273        };
1274
1275        if is_known_session_update(&session_update) {
1276            return Err(serde::de::Error::custom(format!(
1277                "known session update `{session_update}` did not match its schema"
1278            )));
1279        }
1280
1281        Ok(Self {
1282            session_update,
1283            fields,
1284        })
1285    }
1286}
1287
1288fn is_known_session_update(session_update: &str) -> bool {
1289    if session_update == "notice" {
1290        return true;
1291    }
1292    if matches!(
1293        session_update,
1294        "compaction_update" | "compaction_summary_chunk" | "replay_complete"
1295    ) {
1296        return true;
1297    }
1298    #[cfg(feature = "unstable_plan_operations")]
1299    if session_update == "plan_removed" {
1300        return true;
1301    }
1302    #[cfg(feature = "unstable_prompt_suggestions")]
1303    if session_update == "prompt_suggestions_update" {
1304        return true;
1305    }
1306    if matches!(
1307        session_update,
1308        "subagent_update" | "session_message" | "session_message_chunk"
1309    ) {
1310        return true;
1311    }
1312    matches!(
1313        session_update,
1314        "user_message_chunk"
1315            | "user_message"
1316            | "agent_message_chunk"
1317            | "agent_message"
1318            | "agent_thought_chunk"
1319            | "agent_thought"
1320            | "state_update"
1321            | "tool_call_content_chunk"
1322            | "tool_call_update"
1323            | "terminal_update"
1324            | "terminal_output_chunk"
1325            | "plan_update"
1326            | "available_commands_update"
1327            | "config_option_update"
1328            | "session_info_update"
1329            | "usage_update"
1330    )
1331}
1332
1333#[cfg(feature = "schemars")]
1334fn other_session_update_schema(schema: &mut Schema) {
1335    super::schema_util::reject_known_string_discriminators(
1336        schema,
1337        "sessionUpdate",
1338        &[
1339            "user_message_chunk",
1340            "user_message",
1341            "agent_message_chunk",
1342            "agent_message",
1343            "agent_thought_chunk",
1344            "agent_thought",
1345            "state_update",
1346            "tool_call_content_chunk",
1347            "tool_call_update",
1348            "terminal_update",
1349            "terminal_output_chunk",
1350            "plan_update",
1351            "available_commands_update",
1352            "config_option_update",
1353            "session_info_update",
1354            #[cfg(feature = "unstable_plan_operations")]
1355            "plan_removed",
1356            "usage_update",
1357            "notice",
1358            "compaction_update",
1359            "compaction_summary_chunk",
1360            "replay_complete",
1361            #[cfg(feature = "unstable_prompt_suggestions")]
1362            "prompt_suggestions_update",
1363            "subagent_update",
1364            "session_message",
1365            "session_message_chunk",
1366        ],
1367    );
1368}
1369
1370/// Session configuration options have been updated.
1371#[serde_as]
1372#[skip_serializing_none]
1373#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1374#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1375#[serde(rename_all = "camelCase")]
1376#[non_exhaustive]
1377pub struct ConfigOptionUpdate {
1378    /// The full set of configuration options and their current values.
1379    #[serde_as(deserialize_as = "VecSkipError<_>")]
1380    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
1381    pub config_options: Vec<SessionConfigOption>,
1382    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1383    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1384    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1385    ///
1386    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1387    #[serde_as(deserialize_as = "DefaultOnError")]
1388    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1389    #[serde(default)]
1390    #[serde(rename = "_meta")]
1391    pub meta: Option<Meta>,
1392}
1393
1394impl ConfigOptionUpdate {
1395    /// Builds [`ConfigOptionUpdate`] with the required fields set. Optional fields start unset or empty.
1396    #[must_use]
1397    pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
1398        Self {
1399            config_options,
1400            meta: None,
1401        }
1402    }
1403
1404    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1405    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1406    /// do not recognize.
1407    ///
1408    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1409    #[must_use]
1410    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1411        self.meta = meta.into_option();
1412        self
1413    }
1414}
1415
1416/// Update to session metadata. All fields are optional to support partial updates.
1417///
1418/// Agents send this notification to update session information like title or custom metadata.
1419/// Clients can use it to keep session titles and state current.
1420///
1421/// Omitted fields leave the existing session info unchanged. `null` clears the
1422/// corresponding value. A concrete `_meta` object patches the stored metadata by
1423/// top-level key.
1424#[serde_as]
1425#[skip_serializing_none]
1426#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1427#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1428#[serde(rename_all = "camelCase")]
1429#[non_exhaustive]
1430pub struct SessionInfoUpdate {
1431    /// Human-readable title for the session. Set to null to clear.
1432    #[serde_as(deserialize_as = "DefaultOnError")]
1433    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1434    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1435    pub title: MaybeUndefined<String>,
1436    /// RFC 3339 timestamp of last activity. Set to null to clear.
1437    #[serde_as(deserialize_as = "DefaultOnError")]
1438    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
1439    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1440    pub updated_at: MaybeUndefined<String>,
1441    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1442    /// metadata to their interactions. Omitted leaves the stored metadata unchanged. `null`
1443    /// clears it. An object patches the stored metadata by top-level key: keys it omits are
1444    /// unchanged, a key set to `null` is removed, and any other value replaces that key's
1445    /// stored value without merging nested objects. Beyond this patch rule, implementations
1446    /// MUST NOT assign meaning to keys they do not recognize.
1447    ///
1448    /// See protocol docs: [Metadata Patches](https://agentclientprotocol.com/protocol/v2/extensibility#metadata-patches)
1449    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1450    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1451    #[serde(
1452        rename = "_meta",
1453        default,
1454        skip_serializing_if = "MaybeUndefined::is_undefined"
1455    )]
1456    pub meta: MaybeUndefined<Meta>,
1457}
1458
1459impl SessionInfoUpdate {
1460    /// Builds [`SessionInfoUpdate`] with the required fields set. Optional fields start unset or empty.
1461    #[must_use]
1462    pub fn new() -> Self {
1463        Self::default()
1464    }
1465
1466    /// Human-readable title for the session. Set to null to clear.
1467    #[must_use]
1468    pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
1469        self.title = title.into_maybe_undefined();
1470        self
1471    }
1472
1473    /// RFC 3339 timestamp of last activity. Set to null to clear.
1474    #[must_use]
1475    pub fn updated_at(mut self, updated_at: impl IntoMaybeUndefined<String>) -> Self {
1476        self.updated_at = updated_at.into_maybe_undefined();
1477        self
1478    }
1479
1480    /// Patches, clears, or leaves unchanged session metadata.
1481    ///
1482    /// A concrete object patches stored metadata by top-level key. See
1483    /// [`apply_meta_update`](super::apply_meta_update).
1484    #[must_use]
1485    pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1486        self.meta = meta.into_maybe_undefined();
1487        self
1488    }
1489}
1490
1491/// Context window and cost update for a session.
1492#[serde_as]
1493#[skip_serializing_none]
1494#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1495#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1496#[serde(rename_all = "camelCase")]
1497#[non_exhaustive]
1498pub struct UsageUpdate {
1499    /// Tokens currently in context.
1500    pub used: u64,
1501    /// Total context window size in tokens.
1502    pub size: u64,
1503    /// Cumulative session cost.
1504    ///
1505    /// Omitted leaves the last reported cost unchanged. `null` clears it. A value replaces it.
1506    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1507    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1508    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1509    pub cost: MaybeUndefined<Cost>,
1510    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1511    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1512    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1513    ///
1514    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1515    #[serde_as(deserialize_as = "DefaultOnError")]
1516    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1517    #[serde(default)]
1518    #[serde(rename = "_meta")]
1519    pub meta: Option<Meta>,
1520}
1521
1522impl UsageUpdate {
1523    /// Builds [`UsageUpdate`] with the required fields set. Optional fields start unset or empty.
1524    #[must_use]
1525    pub fn new(used: u64, size: u64) -> Self {
1526        Self {
1527            used,
1528            size,
1529            cost: MaybeUndefined::Undefined,
1530            meta: None,
1531        }
1532    }
1533
1534    /// Sets, clears, or leaves unchanged the cumulative session cost.
1535    #[must_use]
1536    pub fn cost(mut self, cost: impl IntoMaybeUndefined<Cost>) -> Self {
1537        self.cost = cost.into_maybe_undefined();
1538        self
1539    }
1540
1541    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1542    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1543    /// do not recognize.
1544    ///
1545    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1546    #[must_use]
1547    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1548        self.meta = meta.into_option();
1549        self
1550    }
1551}
1552
1553/// A snapshot of the session's aggregate foreground activity.
1554///
1555/// Foreground work is the agent's active response or workflow in the session,
1556/// including model processing, tool execution, and waiting for user action needed
1557/// to continue that work. It can start with a prompt or be agent-initiated, for
1558/// example to pursue an ongoing goal or follow up on a completed background task.
1559/// Either way, the agent MUST report `running` when foreground work starts,
1560/// or `requires_action` if it starts blocked on user action, and `idle` when it
1561/// ends. The agent SHOULD include a stop reason on that idle update.
1562/// Agent-initiated work does not require a prompt request or a synthetic user
1563/// message.
1564///
1565/// `running` may precede user-message insertion, for example during a foreground
1566/// hook. It is not acknowledgment of insertion, and rejecting a prompt does not
1567/// itself end foreground work.
1568///
1569/// Background activity can continue and emit other `session/update` notifications
1570/// while `idle`. Those notifications, including a detached task's progress or
1571/// completion, do not by themselves change this state. A permission request only
1572/// warrants `requires_action` when foreground work is blocked on user action.
1573///
1574/// The agent SHOULD report `requires_action` when the foreground workflow as a
1575/// whole cannot progress without user action, including permissions or elicitations.
1576/// Once reported, it MUST report `running` when progress resumes, or `idle` when
1577/// work ends without resuming.
1578/// If other foreground work can progress, the state remains `running`. Resolving
1579/// one of several requests does not itself change the state. Agents SHOULD ignore
1580/// responses for work that has already ended rather than use them to resume it.
1581///
1582/// A new session defaults to idle until a state update reports otherwise.
1583/// Resume MUST send a current-state snapshot after any replay and before its
1584/// response. The snapshot reports foreground state after resuming.
1585/// The response alone does not imply idle.
1586/// Repeated snapshots are idempotent, not additional work, completions, or usage.
1587/// A repeated state may carry updated information without another state transition.
1588/// The agent MUST report `idle` when no foreground activity remains. Completing
1589/// an individual activity while other foreground work continues does not require
1590/// an idle boundary. Local commands use the same lifecycle even without model work.
1591///
1592/// See protocol docs: [Session States](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#session-states)
1593#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1594#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1595#[serde(tag = "state", rename_all = "snake_case")]
1596#[non_exhaustive]
1597pub enum StateUpdate {
1598    /// Foreground work is in progress.
1599    Running(RunningStateUpdate),
1600    /// No foreground work is active. Background activity may continue.
1601    Idle(IdleStateUpdate),
1602    /// Foreground work is blocked on user action.
1603    RequiresAction(RequiresActionStateUpdate),
1604    /// The Agent cannot currently determine foreground activity.
1605    /// This replaces previously confirmed activity without ending the work or session.
1606    Unknown(UnknownStateUpdate),
1607    /// Custom or future session state.
1608    ///
1609    /// Values beginning with `_` are reserved for implementation-specific
1610    /// extensions. Unknown values that do not begin with `_` are reserved for
1611    /// future ACP variants.
1612    ///
1613    /// Unless the Client advertised support for this state, Agents MUST still
1614    /// report the standard states.
1615    /// Clients MUST NOT treat an unrecognized state as `idle` or present the
1616    /// previous state as confirmed, and show a generic busy state until a known
1617    /// state arrives.
1618    #[serde(untagged)]
1619    Other(OtherStateUpdate),
1620}
1621
1622impl StateUpdate {
1623    /// The snapshot's list of work running independently of foreground work.
1624    ///
1625    /// `None` means the Agent is not reporting background work, not that nothing is running.
1626    /// A custom or future state also returns `None`. Its `background` field, if any, stays in
1627    /// [`OtherStateUpdate::fields`].
1628    ///
1629    /// See protocol docs: [Background Work](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#background-work)
1630    #[must_use]
1631    pub fn background(&self) -> Option<&[BackgroundWork]> {
1632        match self {
1633            Self::Running(state) => state.background.as_deref(),
1634            Self::Idle(state) => state.background.as_deref(),
1635            Self::RequiresAction(state) => state.background.as_deref(),
1636            Self::Unknown(state) => state.background.as_deref(),
1637            Self::Other(_) => None,
1638        }
1639    }
1640}
1641
1642/// Foreground work is in progress.
1643#[serde_as]
1644#[skip_serializing_none]
1645#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1646#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1647#[serde(rename_all = "camelCase")]
1648#[non_exhaustive]
1649pub struct RunningStateUpdate {
1650    /// Work running independently of foreground work, as a complete snapshot.
1651    ///
1652    /// Optional. Omitted and `null` are equivalent and mean the Agent is not reporting
1653    /// background work, not that nothing is running. `[]` means no background work is
1654    /// running. An Agent that reports background work MUST include it on every state
1655    /// update for the session. A malformed list is treated as not reported.
1656    ///
1657    /// See protocol docs: [Background Work](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#background-work)
1658    #[serde_as(deserialize_as = "DefaultOnError")]
1659    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1660    #[serde(default)]
1661    pub background: Option<Vec<BackgroundWork>>,
1662    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1663    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1664    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1665    ///
1666    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1667    #[serde_as(deserialize_as = "DefaultOnError")]
1668    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1669    #[serde(default)]
1670    #[serde(rename = "_meta")]
1671    pub meta: Option<Meta>,
1672}
1673
1674impl RunningStateUpdate {
1675    /// Builds [`RunningStateUpdate`] with the required fields set. Optional fields start unset or empty.
1676    #[must_use]
1677    pub fn new() -> Self {
1678        Self::default()
1679    }
1680
1681    /// Work running independently of foreground work, as a complete snapshot.
1682    #[must_use]
1683    pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
1684        self.background = background.into_option();
1685        self
1686    }
1687
1688    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1689    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1690    /// do not recognize.
1691    ///
1692    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1693    #[must_use]
1694    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1695        self.meta = meta.into_option();
1696        self
1697    }
1698}
1699
1700/// No foreground work is active. Background activity may continue.
1701///
1702/// Agents SHOULD include a `stopReason` when the idle transition ends foreground
1703/// work. An idle update that does not end foreground work need not include one.
1704/// Receivers treat an omitted, `null`, or malformed `stopReason` as the agent not
1705/// reporting one.
1706/// Repeated or resume snapshots may carry the last stop reason for context.
1707/// They MUST NOT be counted as new completions, cancellations, or additional usage.
1708#[serde_as]
1709#[skip_serializing_none]
1710#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1711#[cfg_attr(feature = "schemars", schemars(transform = idle_state_update_schema))]
1712#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1713#[serde(rename_all = "camelCase")]
1714#[non_exhaustive]
1715pub struct IdleStateUpdate {
1716    /// Indicates why foreground work stopped, with any fields of that stop reason.
1717    #[serde(flatten)]
1718    pub stop_reason: Option<StopReason>,
1719    /// **UNSTABLE**
1720    ///
1721    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1722    ///
1723    /// Token usage for completed foreground work.
1724    ///
1725    /// Optional. Omitted and `null` are equivalent and mean the agent is not reporting token
1726    /// usage for this state update.
1727    #[cfg(feature = "unstable_end_turn_token_usage")]
1728    #[serde_as(deserialize_as = "DefaultOnError")]
1729    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1730    #[serde(default)]
1731    pub usage: Option<Box<Usage>>,
1732    /// Work running independently of foreground work, as a complete snapshot.
1733    ///
1734    /// Optional. Omitted and `null` are equivalent and mean the Agent is not reporting
1735    /// background work, not that nothing is running. `[]` means no background work is
1736    /// running. An Agent that reports background work MUST include it on every state
1737    /// update for the session. A malformed list is treated as not reported.
1738    ///
1739    /// See protocol docs: [Background Work](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#background-work)
1740    #[serde_as(deserialize_as = "DefaultOnError")]
1741    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1742    #[serde(default)]
1743    pub background: Option<Vec<BackgroundWork>>,
1744    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1745    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1746    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1747    ///
1748    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1749    #[serde_as(deserialize_as = "DefaultOnError")]
1750    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1751    #[serde(default)]
1752    #[serde(rename = "_meta")]
1753    pub meta: Option<Meta>,
1754}
1755
1756impl IdleStateUpdate {
1757    /// Builds [`IdleStateUpdate`] with the required fields set. Optional fields start unset or empty.
1758    #[must_use]
1759    pub fn new() -> Self {
1760        Self::default()
1761    }
1762
1763    /// Indicates why foreground work stopped.
1764    #[must_use]
1765    pub fn stop_reason(mut self, stop_reason: impl IntoOption<StopReason>) -> Self {
1766        self.stop_reason = stop_reason.into_option();
1767        self
1768    }
1769
1770    /// **UNSTABLE**
1771    ///
1772    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1773    ///
1774    /// Token usage for completed foreground work.
1775    #[cfg(feature = "unstable_end_turn_token_usage")]
1776    #[must_use]
1777    pub fn usage(mut self, usage: impl IntoOption<Usage>) -> Self {
1778        self.usage = usage.into_option().map(Box::new);
1779        self
1780    }
1781
1782    /// Work running independently of foreground work, as a complete snapshot.
1783    #[must_use]
1784    pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
1785        self.background = background.into_option();
1786        self
1787    }
1788
1789    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1790    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1791    /// do not recognize.
1792    ///
1793    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1794    #[must_use]
1795    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1796        self.meta = meta.into_option();
1797        self
1798    }
1799}
1800
1801/// Makes the schema check stop reasons and keeps their default-on-error hint.
1802///
1803/// Flattening `Option<StopReason>` adds an empty `{}` branch to the `anyOf`. It
1804/// matches any value, so the stop reason branches would check nothing. This
1805/// replaces it with a branch for an omitted or `null` `stopReason`. Flattening
1806/// also removes the `stopReason` property that carried
1807/// `x-deserialize-default-on-error`, which SDKs generated from the schema rely on
1808/// to tolerate a malformed value, so this adds it back as a shared property.
1809#[cfg(feature = "schemars")]
1810fn idle_state_update_schema(schema: &mut Schema) {
1811    if let Some(properties) = schema
1812        .get_mut("properties")
1813        .and_then(serde_json::Value::as_object_mut)
1814    {
1815        properties.insert(
1816            "stopReason".into(),
1817            serde_json::json!({
1818                "description": "Why foreground work stopped. The value selects one of this type's variants, which may add fields of their own.\n\nOptional. Omitted and `null` are equivalent and mean the agent is not reporting a stop reason; a malformed value is treated the same way.\n\nSee protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#stop-reasons)",
1819                "type": ["string", "null"],
1820                "x-deserialize-default-on-error": true
1821            }),
1822        );
1823    }
1824    let Some(variants) = schema
1825        .get_mut("anyOf")
1826        .and_then(serde_json::Value::as_array_mut)
1827    else {
1828        return;
1829    };
1830    for variant in variants {
1831        if variant.as_object().is_some_and(serde_json::Map::is_empty) {
1832            *variant = serde_json::json!({
1833                "title": "none",
1834                "description": "No stop reason: `stopReason` is omitted or `null`.",
1835                "type": "object",
1836                "properties": {
1837                    "stopReason": { "type": "null" }
1838                }
1839            });
1840        }
1841    }
1842}
1843
1844/// The foreground workflow as a whole is blocked on user action.
1845///
1846/// Agents SHOULD report this state when foreground work cannot progress without
1847/// user action. Pending permissions or elicitations alone do not imply this
1848/// state if other foreground work can progress, or if the requests belong only
1849/// to independent background activity. Once reported, agents MUST report
1850/// `running` when progress resumes, or `idle` if the work ends without resuming.
1851/// Responding to one request does not itself imply `running`.
1852#[serde_as]
1853#[skip_serializing_none]
1854#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1855#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1856#[serde(rename_all = "camelCase")]
1857#[non_exhaustive]
1858pub struct RequiresActionStateUpdate {
1859    /// Work running independently of foreground work, as a complete snapshot.
1860    ///
1861    /// Optional. Omitted and `null` are equivalent and mean the Agent is not reporting
1862    /// background work, not that nothing is running. `[]` means no background work is
1863    /// running. An Agent that reports background work MUST include it on every state
1864    /// update for the session. A malformed list is treated as not reported.
1865    ///
1866    /// See protocol docs: [Background Work](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#background-work)
1867    #[serde_as(deserialize_as = "DefaultOnError")]
1868    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1869    #[serde(default)]
1870    pub background: Option<Vec<BackgroundWork>>,
1871    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1872    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1873    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1874    ///
1875    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1876    #[serde_as(deserialize_as = "DefaultOnError")]
1877    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1878    #[serde(default)]
1879    #[serde(rename = "_meta")]
1880    pub meta: Option<Meta>,
1881}
1882
1883impl RequiresActionStateUpdate {
1884    /// Builds [`RequiresActionStateUpdate`] with the required fields set. Optional fields start unset or empty.
1885    #[must_use]
1886    pub fn new() -> Self {
1887        Self::default()
1888    }
1889
1890    /// Work running independently of foreground work, as a complete snapshot.
1891    #[must_use]
1892    pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
1893        self.background = background.into_option();
1894        self
1895    }
1896
1897    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1898    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1899    /// do not recognize.
1900    ///
1901    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1902    #[must_use]
1903    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1904        self.meta = meta.into_option();
1905        self
1906    }
1907}
1908
1909/// The Agent cannot currently determine foreground activity.
1910///
1911/// Report this when activity becomes unobservable, not merely because the session
1912/// has been quiet. The Client MUST stop presenting the previous state as confirmed
1913/// current activity, but may retain it as last known. A later state replaces this
1914/// snapshot normally.
1915///
1916/// This is not a task outcome or session closure. It does not cancel work, resolve
1917/// pending requests, or revoke capabilities. If a control is no longer available,
1918/// the Agent updates the capabilities explicitly. Unfinished tool calls and
1919/// terminals stay as last reported. The Agent does not invent a final status
1920/// for them, and Clients do not present them as confirmed live activity.
1921#[serde_as]
1922#[skip_serializing_none]
1923#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1924#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1925#[serde(rename_all = "camelCase")]
1926#[non_exhaustive]
1927pub struct UnknownStateUpdate {
1928    /// Work running independently of foreground work, as a complete snapshot.
1929    ///
1930    /// Optional. Omitted and `null` are equivalent and mean the Agent is not reporting
1931    /// background work, not that nothing is running. `[]` means no background work is
1932    /// running. An Agent that reports background work MUST include it on every state
1933    /// update for the session. A malformed list is treated as not reported.
1934    ///
1935    /// See protocol docs: [Background Work](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#background-work)
1936    #[serde_as(deserialize_as = "DefaultOnError")]
1937    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1938    #[serde(default)]
1939    pub background: Option<Vec<BackgroundWork>>,
1940    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1941    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1942    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1943    ///
1944    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1945    #[serde_as(deserialize_as = "DefaultOnError")]
1946    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1947    #[serde(default, rename = "_meta")]
1948    pub meta: Option<Meta>,
1949}
1950
1951impl UnknownStateUpdate {
1952    /// Builds an unknown-activity state.
1953    #[must_use]
1954    pub fn new() -> Self {
1955        Self::default()
1956    }
1957
1958    /// Work running independently of foreground work, as a complete snapshot.
1959    #[must_use]
1960    pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
1961        self.background = background.into_option();
1962        self
1963    }
1964
1965    /// Sets optional metadata for this state snapshot.
1966    #[must_use]
1967    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1968        self.meta = meta.into_option();
1969        self
1970    }
1971}
1972
1973/// Custom or future session state payload.
1974///
1975/// This preserves the unknown `state` discriminator and the rest of the state
1976/// object for clients that store, replay, proxy, or forward session history.
1977#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1978#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1979#[cfg_attr(feature = "schemars", schemars(inline))]
1980#[cfg_attr(feature = "schemars", schemars(transform = other_state_update_schema))]
1981#[serde(rename_all = "camelCase")]
1982#[non_exhaustive]
1983pub struct OtherStateUpdate {
1984    /// Custom or future session state.
1985    ///
1986    /// Values beginning with `_` are reserved for implementation-specific
1987    /// extensions. Unknown values that do not begin with `_` are reserved for
1988    /// future ACP variants.
1989    #[serde(rename = "state")]
1990    pub state: String,
1991    /// Additional fields from the unknown state payload.
1992    #[serde(flatten)]
1993    pub fields: BTreeMap<String, serde_json::Value>,
1994}
1995
1996impl OtherStateUpdate {
1997    /// Builds [`OtherStateUpdate`] from an unknown discriminator and preserves the remaining extension fields.
1998    #[must_use]
1999    pub fn new(state: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
2000        fields.remove("state");
2001        Self {
2002            state: state.into(),
2003            fields,
2004        }
2005    }
2006}
2007
2008impl<'de> Deserialize<'de> for OtherStateUpdate {
2009    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2010    where
2011        D: serde::Deserializer<'de>,
2012    {
2013        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2014        let state = fields
2015            .remove("state")
2016            .ok_or_else(|| serde::de::Error::missing_field("state"))?;
2017        let serde_json::Value::String(state) = state else {
2018            return Err(serde::de::Error::custom("`state` must be a string"));
2019        };
2020
2021        if is_known_state_update(&state) {
2022            return Err(serde::de::Error::custom(format!(
2023                "known state update `{state}` did not match its schema"
2024            )));
2025        }
2026
2027        Ok(Self { state, fields })
2028    }
2029}
2030
2031const KNOWN_STATE_UPDATE_STATES: &[&str] = &["running", "idle", "requires_action", "unknown"];
2032
2033fn is_known_state_update(state: &str) -> bool {
2034    KNOWN_STATE_UPDATE_STATES.contains(&state)
2035}
2036
2037#[cfg(feature = "schemars")]
2038fn other_state_update_schema(schema: &mut Schema) {
2039    super::schema_util::reject_known_string_discriminators(
2040        schema,
2041        "state",
2042        KNOWN_STATE_UPDATE_STATES,
2043    );
2044}
2045
2046/// One piece of work running independently of the session's foreground work.
2047///
2048/// Items reference entities the Client already tracks. The Agent MUST announce each item
2049/// before the first snapshot that lists it, and MUST report a terminal's `exitStatus` or a
2050/// tool call's final status before the snapshot that removes it. Each piece of work is
2051/// listed once: process-backed work is listed as its terminal, not also as its tool call.
2052///
2053/// See protocol docs: [Background Work](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#background-work)
2054#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2055#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2056#[serde(tag = "type", rename_all = "snake_case")]
2057#[non_exhaustive]
2058pub enum BackgroundWork {
2059    /// A process that keeps running after its tool call returned control to the model.
2060    /// Live until its `terminal_update` reports `exitStatus`.
2061    Terminal(BackgroundTerminal),
2062    /// Work started by a tool call that continues without a process of its own, such as
2063    /// a watcher, a workflow, or a scheduled wakeup. `pending` and `paused` tool calls
2064    /// stay listed.
2065    ToolCall(BackgroundToolCall),
2066    /// A detached subagent session that has anything running: its state is not `idle`, or
2067    /// its own `background` list is non-empty or not reported.
2068    Subagent(BackgroundSubagent),
2069    /// Custom or future background work.
2070    ///
2071    /// Values beginning with `_` are reserved for implementation-specific
2072    /// extensions. Unknown values that do not begin with `_` are reserved for
2073    /// future ACP variants.
2074    ///
2075    /// An unknown item still means background work is running, even when the Client
2076    /// cannot show what it is.
2077    #[serde(untagged)]
2078    Other(OtherBackgroundWork),
2079}
2080
2081/// A listed terminal running in the background.
2082#[serde_as]
2083#[skip_serializing_none]
2084#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2085#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2086#[serde(rename_all = "camelCase")]
2087#[non_exhaustive]
2088pub struct BackgroundTerminal {
2089    /// The ID of the listed terminal.
2090    pub terminal_id: TerminalId,
2091    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2092    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2093    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2094    ///
2095    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2096    #[serde_as(deserialize_as = "DefaultOnError")]
2097    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2098    #[serde(default)]
2099    #[serde(rename = "_meta")]
2100    pub meta: Option<Meta>,
2101}
2102
2103impl BackgroundTerminal {
2104    /// Builds [`BackgroundTerminal`] with the required fields set. Optional fields start unset or empty.
2105    #[must_use]
2106    pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
2107        Self {
2108            terminal_id: terminal_id.into(),
2109            meta: None,
2110        }
2111    }
2112
2113    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2114    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2115    /// do not recognize.
2116    ///
2117    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2118    #[must_use]
2119    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2120        self.meta = meta.into_option();
2121        self
2122    }
2123}
2124
2125/// A listed tool call whose work continues in the background.
2126#[serde_as]
2127#[skip_serializing_none]
2128#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2129#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2130#[serde(rename_all = "camelCase")]
2131#[non_exhaustive]
2132pub struct BackgroundToolCall {
2133    /// The ID of the listed tool call.
2134    pub tool_call_id: ToolCallId,
2135    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2136    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2137    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2138    ///
2139    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2140    #[serde_as(deserialize_as = "DefaultOnError")]
2141    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2142    #[serde(default)]
2143    #[serde(rename = "_meta")]
2144    pub meta: Option<Meta>,
2145}
2146
2147impl BackgroundToolCall {
2148    /// Builds [`BackgroundToolCall`] with the required fields set. Optional fields start unset or empty.
2149    #[must_use]
2150    pub fn new(tool_call_id: impl Into<ToolCallId>) -> Self {
2151        Self {
2152            tool_call_id: tool_call_id.into(),
2153            meta: None,
2154        }
2155    }
2156
2157    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2158    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2159    /// do not recognize.
2160    ///
2161    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2162    #[must_use]
2163    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2164        self.meta = meta.into_option();
2165        self
2166    }
2167}
2168
2169/// A listed subagent session associated with this session through `subagent_update`.
2170#[serde_as]
2171#[skip_serializing_none]
2172#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2173#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2174#[serde(rename_all = "camelCase")]
2175#[non_exhaustive]
2176pub struct BackgroundSubagent {
2177    /// The ID of the listed session.
2178    pub session_id: SessionId,
2179    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2180    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2181    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2182    ///
2183    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2184    #[serde_as(deserialize_as = "DefaultOnError")]
2185    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2186    #[serde(default)]
2187    #[serde(rename = "_meta")]
2188    pub meta: Option<Meta>,
2189}
2190
2191impl BackgroundSubagent {
2192    /// Builds [`BackgroundSubagent`] with the required fields set. Optional fields start unset or empty.
2193    #[must_use]
2194    pub fn new(session_id: impl Into<SessionId>) -> Self {
2195        Self {
2196            session_id: session_id.into(),
2197            meta: None,
2198        }
2199    }
2200
2201    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2202    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2203    /// do not recognize.
2204    ///
2205    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2206    #[must_use]
2207    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2208        self.meta = meta.into_option();
2209        self
2210    }
2211}
2212
2213/// Custom or future background work payload.
2214///
2215/// This preserves the unknown `type` discriminator and the rest of the item so Clients
2216/// can store, replay, proxy, or forward it.
2217#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2218#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2219#[cfg_attr(feature = "schemars", schemars(inline))]
2220#[cfg_attr(feature = "schemars", schemars(transform = other_background_work_schema))]
2221#[serde(rename_all = "camelCase")]
2222#[non_exhaustive]
2223pub struct OtherBackgroundWork {
2224    /// Custom or future background work type.
2225    ///
2226    /// Values beginning with `_` are reserved for implementation-specific
2227    /// extensions. Unknown values that do not begin with `_` are reserved for
2228    /// future ACP variants.
2229    #[serde(rename = "type")]
2230    pub kind: String,
2231    /// Additional fields from the unknown item.
2232    #[serde(flatten)]
2233    pub fields: BTreeMap<String, serde_json::Value>,
2234}
2235
2236impl OtherBackgroundWork {
2237    /// Builds [`OtherBackgroundWork`] from an unknown discriminator and preserves the remaining extension fields.
2238    #[must_use]
2239    pub fn new(kind: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
2240        fields.remove("type");
2241        Self {
2242            kind: kind.into(),
2243            fields,
2244        }
2245    }
2246}
2247
2248impl<'de> Deserialize<'de> for OtherBackgroundWork {
2249    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2250    where
2251        D: serde::Deserializer<'de>,
2252    {
2253        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2254        let kind = fields
2255            .remove("type")
2256            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2257        let serde_json::Value::String(kind) = kind else {
2258            return Err(serde::de::Error::custom("`type` must be a string"));
2259        };
2260
2261        if KNOWN_BACKGROUND_WORK_TYPES.contains(&kind.as_str()) {
2262            return Err(serde::de::Error::custom(format!(
2263                "known background work `{kind}` did not match its schema"
2264            )));
2265        }
2266
2267        Ok(Self { kind, fields })
2268    }
2269}
2270
2271const KNOWN_BACKGROUND_WORK_TYPES: &[&str] = &["terminal", "tool_call", "subagent"];
2272
2273#[cfg(feature = "schemars")]
2274fn other_background_work_schema(schema: &mut Schema) {
2275    super::schema_util::reject_known_string_discriminators(
2276        schema,
2277        "type",
2278        KNOWN_BACKGROUND_WORK_TYPES,
2279    );
2280}
2281
2282/// Cost information for a session.
2283#[serde_as]
2284#[skip_serializing_none]
2285#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2286#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2287#[serde(rename_all = "camelCase")]
2288#[non_exhaustive]
2289pub struct Cost {
2290    /// Total cumulative cost for session.
2291    pub amount: f64,
2292    /// Unit of `amount`: an ISO 4217 currency code (e.g., "USD", "EUR") for money, or another
2293    /// unit such as "credits".
2294    pub currency: String,
2295    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2296    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2297    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2298    ///
2299    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2300    #[serde_as(deserialize_as = "DefaultOnError")]
2301    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2302    #[serde(default)]
2303    #[serde(rename = "_meta")]
2304    pub meta: Option<Meta>,
2305}
2306
2307impl Cost {
2308    /// Builds [`Cost`] with the required fields set. Optional fields start unset or empty.
2309    #[must_use]
2310    pub fn new(amount: f64, currency: impl Into<String>) -> Self {
2311        Self {
2312            amount,
2313            currency: currency.into(),
2314            meta: None,
2315        }
2316    }
2317
2318    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2319    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2320    /// do not recognize.
2321    ///
2322    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2323    #[must_use]
2324    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2325        self.meta = meta.into_option();
2326        self
2327    }
2328}
2329
2330/// A streamed item of message content.
2331#[serde_as]
2332#[skip_serializing_none]
2333#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2334#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2335#[serde(rename_all = "camelCase")]
2336#[non_exhaustive]
2337pub struct ContentChunk {
2338    /// A unique identifier for the message this chunk belongs to.
2339    ///
2340    /// All chunks belonging to the same message share the same `messageId`.
2341    /// Chunks for different messages can interleave.
2342    pub message_id: MessageId,
2343    /// A single item of content
2344    pub content: ContentBlock,
2345    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2346    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2347    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2348    /// This metadata is scoped to the chunk and does not patch stored metadata.
2349    ///
2350    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2351    #[serde_as(deserialize_as = "DefaultOnError")]
2352    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2353    #[serde(default)]
2354    #[serde(rename = "_meta")]
2355    pub meta: Option<Meta>,
2356}
2357
2358impl ContentChunk {
2359    /// Builds [`ContentChunk`] with the required fields set. Optional fields start unset or empty.
2360    #[must_use]
2361    pub fn new(content: ContentBlock, message_id: impl Into<MessageId>) -> Self {
2362        Self {
2363            content,
2364            message_id: message_id.into(),
2365            meta: None,
2366        }
2367    }
2368
2369    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2370    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2371    /// do not recognize. This field is chunk-scoped.
2372    ///
2373    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2374    #[must_use]
2375    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2376        self.meta = meta.into_option();
2377        self
2378    }
2379}
2380
2381/// A user message upsert.
2382///
2383/// Only `messageId` is required. `content` has patch semantics:
2384/// an omitted field leaves existing message content unchanged, `null` clears the
2385/// value, and a concrete array replaces the previous value. For a new
2386/// `messageId`, omitted `content` starts empty. `content` is replaced as a
2387/// whole array. Send `[]` or `null` to clear it.
2388///
2389/// Message updates and chunks are applied in the order they are received. When
2390/// a `user_message` update includes `content`, that array replaces any content
2391/// previously accumulated for the message, including content from earlier
2392/// chunks. Later chunks with the same `messageId` append to the current
2393/// content.
2394#[serde_as]
2395#[skip_serializing_none]
2396#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2397#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2398#[serde(rename_all = "camelCase")]
2399#[non_exhaustive]
2400pub struct UserMessage {
2401    /// A unique identifier for the message.
2402    pub message_id: MessageId,
2403    /// Complete replacement content for this message.
2404    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
2405    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2406    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2407    pub content: MaybeUndefined<Vec<ContentBlock>>,
2408    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2409    /// metadata to their interactions. Omitted leaves the stored metadata unchanged. `null`
2410    /// clears it. An object patches the stored metadata by top-level key: keys it omits are
2411    /// unchanged, a key set to `null` is removed, and any other value replaces that key's
2412    /// stored value without merging nested objects. Beyond this patch rule, implementations
2413    /// MUST NOT assign meaning to keys they do not recognize.
2414    ///
2415    /// See protocol docs: [Metadata Patches](https://agentclientprotocol.com/protocol/v2/extensibility#metadata-patches)
2416    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2417    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2418    #[serde(
2419        rename = "_meta",
2420        default,
2421        skip_serializing_if = "MaybeUndefined::is_undefined"
2422    )]
2423    pub meta: MaybeUndefined<Meta>,
2424}
2425
2426impl UserMessage {
2427    /// Builds [`UserMessage`] with the required fields set. Optional fields start unset or empty.
2428    #[must_use]
2429    pub fn new(message_id: impl Into<MessageId>) -> Self {
2430        Self {
2431            message_id: message_id.into(),
2432            content: MaybeUndefined::Undefined,
2433            meta: MaybeUndefined::Undefined,
2434        }
2435    }
2436
2437    /// Complete replacement content for this message.
2438    #[must_use]
2439    pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
2440        self.content = content.into_maybe_undefined();
2441        self
2442    }
2443
2444    /// Patches, clears, or leaves unchanged message metadata.
2445    ///
2446    /// A concrete object patches stored metadata by top-level key. See
2447    /// [`apply_meta_update`](super::apply_meta_update).
2448    #[must_use]
2449    pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
2450        self.meta = meta.into_maybe_undefined();
2451        self
2452    }
2453}
2454
2455/// An agent message upsert.
2456///
2457/// Only `messageId` is required. `content` has patch semantics:
2458/// an omitted field leaves existing message content unchanged, `null` clears the
2459/// value, and a concrete array replaces the previous value. For a new
2460/// `messageId`, omitted `content` starts empty. `content` is replaced as a
2461/// whole array. Send `[]` or `null` to clear it.
2462///
2463/// Message updates and chunks are applied in the order they are received. When
2464/// an `agent_message` update includes `content`, that array replaces any
2465/// content previously accumulated for the message, including content from
2466/// earlier chunks. Later chunks with the same `messageId` append to the current
2467/// content.
2468#[serde_as]
2469#[skip_serializing_none]
2470#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2471#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2472#[serde(rename_all = "camelCase")]
2473#[non_exhaustive]
2474pub struct AgentMessage {
2475    /// A unique identifier for the message.
2476    pub message_id: MessageId,
2477    /// Complete replacement content for this message.
2478    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
2479    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2480    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2481    pub content: MaybeUndefined<Vec<ContentBlock>>,
2482    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2483    /// metadata to their interactions. Omitted leaves the stored metadata unchanged. `null`
2484    /// clears it. An object patches the stored metadata by top-level key: keys it omits are
2485    /// unchanged, a key set to `null` is removed, and any other value replaces that key's
2486    /// stored value without merging nested objects. Beyond this patch rule, implementations
2487    /// MUST NOT assign meaning to keys they do not recognize.
2488    ///
2489    /// See protocol docs: [Metadata Patches](https://agentclientprotocol.com/protocol/v2/extensibility#metadata-patches)
2490    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2491    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2492    #[serde(
2493        rename = "_meta",
2494        default,
2495        skip_serializing_if = "MaybeUndefined::is_undefined"
2496    )]
2497    pub meta: MaybeUndefined<Meta>,
2498}
2499
2500impl AgentMessage {
2501    /// Builds [`AgentMessage`] with the required fields set. Optional fields start unset or empty.
2502    #[must_use]
2503    pub fn new(message_id: impl Into<MessageId>) -> Self {
2504        Self {
2505            message_id: message_id.into(),
2506            content: MaybeUndefined::Undefined,
2507            meta: MaybeUndefined::Undefined,
2508        }
2509    }
2510
2511    /// Complete replacement content for this message.
2512    #[must_use]
2513    pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
2514        self.content = content.into_maybe_undefined();
2515        self
2516    }
2517
2518    /// Patches, clears, or leaves unchanged message metadata.
2519    ///
2520    /// A concrete object patches stored metadata by top-level key. See
2521    /// [`apply_meta_update`](super::apply_meta_update).
2522    #[must_use]
2523    pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
2524        self.meta = meta.into_maybe_undefined();
2525        self
2526    }
2527}
2528
2529/// An agent thought or reasoning message upsert.
2530///
2531/// Only `messageId` is required. `content` has patch semantics:
2532/// an omitted field leaves existing thought content unchanged, `null` clears the
2533/// value, and a concrete array replaces the previous value. For a new
2534/// `messageId`, omitted `content` starts empty. `content` is replaced as a
2535/// whole array. Send `[]` or `null` to clear it.
2536///
2537/// Message updates and chunks are applied in the order they are received. When
2538/// an `agent_thought` update includes `content`, that array replaces any
2539/// content previously accumulated for the thought, including content from
2540/// earlier chunks. Later chunks with the same `messageId` append to the current
2541/// content.
2542#[serde_as]
2543#[skip_serializing_none]
2544#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2545#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2546#[serde(rename_all = "camelCase")]
2547#[non_exhaustive]
2548pub struct AgentThought {
2549    /// A unique identifier for the thought message.
2550    pub message_id: MessageId,
2551    /// Complete replacement content for this thought message.
2552    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
2553    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2554    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2555    pub content: MaybeUndefined<Vec<ContentBlock>>,
2556    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2557    /// metadata to their interactions. Omitted leaves the stored metadata unchanged. `null`
2558    /// clears it. An object patches the stored metadata by top-level key: keys it omits are
2559    /// unchanged, a key set to `null` is removed, and any other value replaces that key's
2560    /// stored value without merging nested objects. Beyond this patch rule, implementations
2561    /// MUST NOT assign meaning to keys they do not recognize.
2562    ///
2563    /// See protocol docs: [Metadata Patches](https://agentclientprotocol.com/protocol/v2/extensibility#metadata-patches)
2564    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2565    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2566    #[serde(
2567        rename = "_meta",
2568        default,
2569        skip_serializing_if = "MaybeUndefined::is_undefined"
2570    )]
2571    pub meta: MaybeUndefined<Meta>,
2572}
2573
2574impl AgentThought {
2575    /// Builds [`AgentThought`] with the required fields set. Optional fields start unset or empty.
2576    #[must_use]
2577    pub fn new(message_id: impl Into<MessageId>) -> Self {
2578        Self {
2579            message_id: message_id.into(),
2580            content: MaybeUndefined::Undefined,
2581            meta: MaybeUndefined::Undefined,
2582        }
2583    }
2584
2585    /// Complete replacement content for this thought message.
2586    #[must_use]
2587    pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
2588        self.content = content.into_maybe_undefined();
2589        self
2590    }
2591
2592    /// Patches, clears, or leaves unchanged thought metadata.
2593    ///
2594    /// A concrete object patches stored metadata by top-level key. See
2595    /// [`apply_meta_update`](super::apply_meta_update).
2596    #[must_use]
2597    pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
2598        self.meta = meta.into_maybe_undefined();
2599        self
2600    }
2601}
2602
2603/// Identifier for a message, unique among messages of the same type within a session.
2604///
2605/// Each message type, such as user messages, agent messages, and agent thoughts,
2606/// has its own ID space: messages of different types may share an ID and remain
2607/// distinct messages.
2608#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2609#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2610#[serde(transparent)]
2611#[from(forward)]
2612#[non_exhaustive]
2613pub struct MessageId(pub Arc<str>);
2614
2615impl MessageId {
2616    /// Wraps a protocol string as a typed [`MessageId`].
2617    #[must_use]
2618    pub fn new(id: impl Into<Self>) -> Self {
2619        id.into()
2620    }
2621}
2622
2623/// **UNSTABLE**
2624///
2625/// This capability is not part of the spec yet, and may be removed or changed at any point.
2626///
2627/// Replaces the session's current list of prompt suggestions.
2628///
2629/// A prompt suggestion is a prompt the Agent predicts the user will send next.
2630/// The Client offers suggestions where the user writes the next prompt. The
2631/// list in the most recent update is the current list until the Agent sends
2632/// another update. A session starts with an empty list.
2633///
2634/// Suggestions are not part of session history. Agents SHOULD NOT include
2635/// this update when they replay a session.
2636///
2637/// Agents MUST only send this update when the Client advertised
2638/// the `session.promptSuggestions` Client capability.
2639#[cfg(feature = "unstable_prompt_suggestions")]
2640#[serde_as]
2641#[skip_serializing_none]
2642#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2643#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2644#[serde(rename_all = "camelCase")]
2645#[non_exhaustive]
2646pub struct PromptSuggestionsUpdate {
2647    /// The suggestions the Client can offer, ordered most likely first.
2648    ///
2649    /// Required and non-null. An empty list withdraws the suggestions the
2650    /// Client is offering. A Client skips an entry it cannot parse and keeps
2651    /// the rest.
2652    #[serde_as(deserialize_as = "VecSkipError<_>")]
2653    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
2654    pub suggestions: Vec<PromptSuggestion>,
2655    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2656    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2657    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2658    ///
2659    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2660    #[serde_as(deserialize_as = "DefaultOnError")]
2661    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2662    #[serde(default)]
2663    #[serde(rename = "_meta")]
2664    pub meta: Option<Meta>,
2665}
2666
2667#[cfg(feature = "unstable_prompt_suggestions")]
2668impl PromptSuggestionsUpdate {
2669    /// Builds [`PromptSuggestionsUpdate`] with the required fields set. Optional fields start unset or empty.
2670    ///
2671    /// Pass an empty list to withdraw the suggestions the Client is offering.
2672    #[must_use]
2673    pub fn new(suggestions: Vec<PromptSuggestion>) -> Self {
2674        Self {
2675            suggestions,
2676            meta: None,
2677        }
2678    }
2679
2680    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2681    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2682    /// do not recognize.
2683    ///
2684    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2685    #[must_use]
2686    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2687        self.meta = meta.into_option();
2688        self
2689    }
2690}
2691
2692/// **UNSTABLE**
2693///
2694/// This capability is not part of the spec yet, and may be removed or changed at any point.
2695///
2696/// A prompt the Agent predicts the user will send next.
2697#[cfg(feature = "unstable_prompt_suggestions")]
2698#[serde_as]
2699#[skip_serializing_none]
2700#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2701#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2702#[serde(rename_all = "camelCase")]
2703#[non_exhaustive]
2704pub struct PromptSuggestion {
2705    /// The content of the suggested prompt.
2706    ///
2707    /// Required and non-null. Must contain at least one content block. This is
2708    /// the same type as the `prompt` field of `session/prompt`, and the Client
2709    /// can send it in that field unchanged.
2710    ///
2711    /// Agents MUST only use `text` and `resource_link` content blocks, and
2712    /// other content block types that both the Agent's `session.prompt`
2713    /// capability and the Client's `session.promptSuggestions` capability
2714    /// advertise. Agents MUST NOT send a prompt whose only content is empty
2715    /// or whitespace-only text.
2716    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
2717    pub prompt: Vec<ContentBlock>,
2718    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2719    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2720    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2721    ///
2722    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2723    #[serde_as(deserialize_as = "DefaultOnError")]
2724    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2725    #[serde(default)]
2726    #[serde(rename = "_meta")]
2727    pub meta: Option<Meta>,
2728}
2729
2730#[cfg(feature = "unstable_prompt_suggestions")]
2731impl PromptSuggestion {
2732    /// Builds [`PromptSuggestion`] with the required fields set. Optional fields start unset or empty.
2733    #[must_use]
2734    pub fn new(prompt: Vec<ContentBlock>) -> Self {
2735        Self { prompt, meta: None }
2736    }
2737
2738    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2739    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2740    /// do not recognize.
2741    ///
2742    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2743    #[must_use]
2744    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2745        self.meta = meta.into_option();
2746        self
2747    }
2748}
2749
2750/// Available commands are ready or have changed
2751#[serde_as]
2752#[skip_serializing_none]
2753#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2754#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2755#[serde(rename_all = "camelCase")]
2756#[non_exhaustive]
2757pub struct AvailableCommandsUpdate {
2758    /// Commands the agent can execute.
2759    #[serde_as(deserialize_as = "VecSkipError<_>")]
2760    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
2761    pub available_commands: Vec<AvailableCommand>,
2762    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2763    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2764    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2765    ///
2766    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2767    #[serde_as(deserialize_as = "DefaultOnError")]
2768    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2769    #[serde(default)]
2770    #[serde(rename = "_meta")]
2771    pub meta: Option<Meta>,
2772}
2773
2774impl AvailableCommandsUpdate {
2775    /// Builds [`AvailableCommandsUpdate`] with the required fields set. Optional fields start unset or empty.
2776    #[must_use]
2777    pub fn new(available_commands: Vec<AvailableCommand>) -> Self {
2778        Self {
2779            available_commands,
2780            meta: None,
2781        }
2782    }
2783
2784    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2785    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2786    /// do not recognize.
2787    ///
2788    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2789    #[must_use]
2790    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2791        self.meta = meta.into_option();
2792        self
2793    }
2794}
2795
2796/// A command the agent advertises to the client.
2797///
2798/// The `type` field acts as the discriminator in the serialized JSON form.
2799#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2800#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2801#[serde(tag = "type", rename_all = "snake_case")]
2802#[non_exhaustive]
2803pub enum AvailableCommand {
2804    /// A slash command the user can invoke by including it in a prompt.
2805    Command(Command),
2806    /// **UNSTABLE**
2807    ///
2808    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2809    ///
2810    /// An Agent Skill the user can invoke with a `skill` content block.
2811    ///
2812    /// Agents MUST only send this entry when the Client advertised
2813    /// the `session.commands.skill` Client capability.
2814    #[cfg(feature = "unstable_agent_skills")]
2815    Skill(Skill),
2816    /// Custom or future command kind.
2817    ///
2818    /// Values beginning with `_` are reserved for implementation-specific
2819    /// extensions. Unknown values that do not begin with `_` are reserved for
2820    /// future ACP variants.
2821    ///
2822    /// Clients that do not understand this command type should preserve the raw
2823    /// payload when storing, replaying, proxying, or forwarding command
2824    /// metadata, and otherwise ignore the command. They MUST NOT display it as a
2825    /// slash command.
2826    #[serde(untagged)]
2827    Other(OtherAvailableCommand),
2828}
2829
2830impl AvailableCommand {
2831    /// Command name (e.g., `create_plan`, `research_codebase`).
2832    #[must_use]
2833    pub fn name(&self) -> &str {
2834        match self {
2835            Self::Command(c) => &c.name,
2836            #[cfg(feature = "unstable_agent_skills")]
2837            Self::Skill(c) => &c.name,
2838            Self::Other(c) => &c.name,
2839        }
2840    }
2841
2842    /// Human-readable description of what the command does.
2843    #[must_use]
2844    pub fn description(&self) -> &str {
2845        match self {
2846            Self::Command(c) => &c.description,
2847            #[cfg(feature = "unstable_agent_skills")]
2848            Self::Skill(c) => &c.description,
2849            Self::Other(c) => &c.description,
2850        }
2851    }
2852
2853    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2854    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2855    /// do not recognize.
2856    ///
2857    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2858    #[must_use]
2859    pub fn meta(&self) -> Option<&Meta> {
2860        match self {
2861            Self::Command(c) => c.meta.as_ref(),
2862            #[cfg(feature = "unstable_agent_skills")]
2863            Self::Skill(c) => c.meta.as_ref(),
2864            Self::Other(c) => c.fields.get("_meta").and_then(serde_json::Value::as_object),
2865        }
2866    }
2867}
2868
2869/// Custom or future command payload.
2870#[serde_as]
2871#[skip_serializing_none]
2872#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2873#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2874#[cfg_attr(feature = "schemars", schemars(inline))]
2875#[cfg_attr(feature = "schemars", schemars(transform = other_available_command_schema))]
2876#[serde(rename_all = "camelCase")]
2877#[non_exhaustive]
2878pub struct OtherAvailableCommand {
2879    /// Custom or future command type.
2880    ///
2881    /// Values beginning with `_` are reserved for implementation-specific
2882    /// extensions. Unknown values that do not begin with `_` are reserved for
2883    /// future ACP variants.
2884    #[serde(rename = "type")]
2885    pub type_: String,
2886    /// Command name. MUST NOT contain whitespace and MUST be unique within the command list.
2887    pub name: String,
2888    /// Human-readable description of what the command does.
2889    pub description: String,
2890    /// The remaining fields of the unknown command payload, preserved verbatim, including
2891    /// `_meta`.
2892    #[serde(flatten)]
2893    pub fields: BTreeMap<String, serde_json::Value>,
2894}
2895
2896impl OtherAvailableCommand {
2897    /// Builds [`OtherAvailableCommand`] from an unknown discriminator and preserves the remaining extension fields.
2898    #[must_use]
2899    pub fn new(
2900        type_: impl Into<String>,
2901        name: impl Into<String>,
2902        description: impl Into<String>,
2903        mut fields: BTreeMap<String, serde_json::Value>,
2904    ) -> Self {
2905        fields.remove("type");
2906        fields.remove("name");
2907        fields.remove("description");
2908        Self {
2909            type_: type_.into(),
2910            name: name.into(),
2911            description: description.into(),
2912            fields,
2913        }
2914    }
2915}
2916
2917impl<'de> Deserialize<'de> for OtherAvailableCommand {
2918    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2919    where
2920        D: serde::Deserializer<'de>,
2921    {
2922        #[derive(Deserialize)]
2923        struct RawOtherAvailableCommand {
2924            #[serde(rename = "type")]
2925            type_: String,
2926            name: String,
2927            description: String,
2928            #[serde(flatten)]
2929            fields: BTreeMap<String, serde_json::Value>,
2930        }
2931
2932        let raw = RawOtherAvailableCommand::deserialize(deserializer)?;
2933        if is_known_available_command_type(&raw.type_) {
2934            return Err(serde::de::Error::custom(format!(
2935                "known available command type `{}` did not match its schema",
2936                raw.type_
2937            )));
2938        }
2939
2940        Ok(Self {
2941            type_: raw.type_,
2942            name: raw.name,
2943            description: raw.description,
2944            fields: raw.fields,
2945        })
2946    }
2947}
2948
2949const KNOWN_AVAILABLE_COMMAND_TYPES: &[&str] = &[
2950    "command",
2951    #[cfg(feature = "unstable_agent_skills")]
2952    "skill",
2953];
2954
2955fn is_known_available_command_type(type_: &str) -> bool {
2956    KNOWN_AVAILABLE_COMMAND_TYPES.contains(&type_)
2957}
2958
2959#[cfg(feature = "schemars")]
2960fn other_available_command_schema(schema: &mut Schema) {
2961    super::schema_util::reject_known_string_discriminators(
2962        schema,
2963        "type",
2964        KNOWN_AVAILABLE_COMMAND_TYPES,
2965    );
2966}
2967
2968/// A slash command the user can invoke by including it in a prompt.
2969///
2970/// The `type` discriminator value is `command`.
2971#[serde_as]
2972#[skip_serializing_none]
2973#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2974#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2975#[serde(rename_all = "camelCase")]
2976#[non_exhaustive]
2977pub struct Command {
2978    /// Command name without the leading `/` (e.g., `create_plan`, `research_codebase`).
2979    ///
2980    /// MUST NOT contain whitespace and MUST be unique within the command list.
2981    pub name: String,
2982    /// Human-readable description of what the command does.
2983    pub description: String,
2984    /// Input for the command if required
2985    ///
2986    /// Omitted and `null` are equivalent and mean the command takes no input.
2987    #[serde_as(deserialize_as = "DefaultOnError")]
2988    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2989    #[serde(default)]
2990    pub input: Option<AvailableCommandInput>,
2991    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2992    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2993    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2994    ///
2995    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2996    #[serde_as(deserialize_as = "DefaultOnError")]
2997    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2998    #[serde(default)]
2999    #[serde(rename = "_meta")]
3000    pub meta: Option<Meta>,
3001}
3002
3003impl Command {
3004    /// Builds [`Command`] with the required fields set. Optional fields start unset or empty.
3005    #[must_use]
3006    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
3007        Self {
3008            name: name.into(),
3009            description: description.into(),
3010            input: None,
3011            meta: None,
3012        }
3013    }
3014
3015    /// Input for the command if required
3016    #[must_use]
3017    pub fn input(mut self, input: impl IntoOption<AvailableCommandInput>) -> Self {
3018        self.input = input.into_option();
3019        self
3020    }
3021
3022    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3023    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3024    /// do not recognize.
3025    ///
3026    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3027    #[must_use]
3028    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3029        self.meta = meta.into_option();
3030        self
3031    }
3032}
3033
3034/// **UNSTABLE**
3035///
3036/// This capability is not part of the spec yet, and may be removed or changed at any point.
3037///
3038/// An Agent Skill the user can invoke.
3039///
3040/// The `type` discriminator value is `skill`.
3041///
3042/// The Client invokes a skill with a `skill` content block that names it. The
3043/// `/name` syntax applies only to `command` entries. An Agent that sends
3044/// `skill` entries MUST advertise the `session.prompt.skill` capability.
3045///
3046/// Agents MUST only send `skill` entries when the Client advertised the
3047/// `session.commands.skill` Client capability. Agents SHOULD advertise only
3048/// skills the user can invoke.
3049#[cfg(feature = "unstable_agent_skills")]
3050#[serde_as]
3051#[skip_serializing_none]
3052#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3053#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3054#[serde(rename_all = "camelCase")]
3055#[non_exhaustive]
3056pub struct Skill {
3057    /// Skill name. The Client uses it to refer to the skill in a `skill` content block.
3058    ///
3059    /// MUST NOT contain whitespace and MUST be unique within the command list,
3060    /// across commands and skills. It need not match the `name` in the skill's
3061    /// frontmatter.
3062    pub name: String,
3063    /// Human-readable description of what the skill does, shown to users.
3064    pub description: String,
3065    /// The absolute path of the file that defines the skill, normally its
3066    /// `SKILL.md`, on the machine the Agent runs on.
3067    ///
3068    /// Omitted and `null` are equivalent and mean the skill has no such file,
3069    /// as with a skill that is built into the Agent or served by an MCP server.
3070    #[serde_as(deserialize_as = "DefaultOnError")]
3071    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3072    #[serde(default)]
3073    pub path: Option<AbsolutePath>,
3074    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3075    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3076    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3077    ///
3078    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3079    #[serde_as(deserialize_as = "DefaultOnError")]
3080    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3081    #[serde(default)]
3082    #[serde(rename = "_meta")]
3083    pub meta: Option<Meta>,
3084}
3085
3086#[cfg(feature = "unstable_agent_skills")]
3087impl Skill {
3088    /// Builds [`Skill`] with the required fields set. Optional fields start unset or empty.
3089    #[must_use]
3090    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
3091        Self {
3092            name: name.into(),
3093            description: description.into(),
3094            path: None,
3095            meta: None,
3096        }
3097    }
3098
3099    /// The absolute path of the file that defines the skill, normally its
3100    /// `SKILL.md`, on the machine the Agent runs on.
3101    #[must_use]
3102    pub fn path(mut self, path: impl IntoOption<AbsolutePath>) -> Self {
3103        self.path = path.into_option();
3104        self
3105    }
3106
3107    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3108    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3109    /// do not recognize.
3110    ///
3111    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3112    #[must_use]
3113    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3114        self.meta = meta.into_option();
3115        self
3116    }
3117}
3118
3119/// The input specification for a command.
3120#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3122#[serde(tag = "type", rename_all = "snake_case")]
3123#[non_exhaustive]
3124pub enum AvailableCommandInput {
3125    /// All text after the command name and the whitespace following it is provided as input.
3126    #[serde(rename = "text")]
3127    Text(TextCommandInput),
3128    /// Custom or future command input specification.
3129    ///
3130    /// Values beginning with `_` are reserved for implementation-specific
3131    /// extensions. Unknown values that do not begin with `_` are reserved for
3132    /// future ACP variants.
3133    ///
3134    /// Clients that do not understand this input type should preserve the raw
3135    /// payload when storing, replaying, proxying, or forwarding command
3136    /// metadata, and otherwise ignore the input specification or display the
3137    /// command without structured input.
3138    #[serde(untagged)]
3139    Other(OtherAvailableCommandInput),
3140}
3141
3142/// Custom or future command input specification.
3143#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3144#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3145#[cfg_attr(feature = "schemars", schemars(inline))]
3146#[cfg_attr(feature = "schemars", schemars(transform = other_available_command_input_schema))]
3147#[serde(rename_all = "camelCase")]
3148#[non_exhaustive]
3149pub struct OtherAvailableCommandInput {
3150    /// Custom or future command input type.
3151    ///
3152    /// Values beginning with `_` are reserved for implementation-specific
3153    /// extensions. Unknown values that do not begin with `_` are reserved for
3154    /// future ACP variants.
3155    #[serde(rename = "type")]
3156    pub type_: String,
3157    /// Additional fields from the unknown command input payload.
3158    #[serde(flatten)]
3159    pub fields: BTreeMap<String, serde_json::Value>,
3160}
3161
3162impl OtherAvailableCommandInput {
3163    /// Builds [`OtherAvailableCommandInput`] from an unknown discriminator and preserves the remaining extension fields.
3164    #[must_use]
3165    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
3166        fields.remove("type");
3167        Self {
3168            type_: type_.into(),
3169            fields,
3170        }
3171    }
3172}
3173
3174impl<'de> Deserialize<'de> for OtherAvailableCommandInput {
3175    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3176    where
3177        D: serde::Deserializer<'de>,
3178    {
3179        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
3180        let type_ = fields
3181            .remove("type")
3182            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
3183        let serde_json::Value::String(type_) = type_ else {
3184            return Err(serde::de::Error::custom("`type` must be a string"));
3185        };
3186
3187        if is_known_available_command_input_type(&type_) {
3188            return Err(serde::de::Error::custom(format!(
3189                "known available command input type `{type_}` did not match its schema"
3190            )));
3191        }
3192
3193        Ok(Self { type_, fields })
3194    }
3195}
3196
3197const KNOWN_AVAILABLE_COMMAND_INPUT_TYPES: &[&str] = &["text"];
3198
3199fn is_known_available_command_input_type(type_: &str) -> bool {
3200    KNOWN_AVAILABLE_COMMAND_INPUT_TYPES.contains(&type_)
3201}
3202
3203#[cfg(feature = "schemars")]
3204fn other_available_command_input_schema(schema: &mut Schema) {
3205    super::schema_util::reject_known_string_discriminators(
3206        schema,
3207        "type",
3208        KNOWN_AVAILABLE_COMMAND_INPUT_TYPES,
3209    );
3210}
3211
3212/// All text that was typed after the command name is provided as input.
3213#[serde_as]
3214#[skip_serializing_none]
3215#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3216#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3217#[serde(rename_all = "camelCase")]
3218#[non_exhaustive]
3219pub struct TextCommandInput {
3220    /// A hint to display when the input hasn't been provided yet
3221    pub hint: String,
3222    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3223    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3224    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3225    ///
3226    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3227    #[serde_as(deserialize_as = "DefaultOnError")]
3228    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3229    #[serde(default)]
3230    #[serde(rename = "_meta")]
3231    pub meta: Option<Meta>,
3232}
3233
3234impl TextCommandInput {
3235    /// Builds [`TextCommandInput`] with the required fields set. Optional fields start unset or empty.
3236    #[must_use]
3237    pub fn new(hint: impl Into<String>) -> Self {
3238        Self {
3239            hint: hint.into(),
3240            meta: None,
3241        }
3242    }
3243
3244    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3245    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3246    /// do not recognize.
3247    ///
3248    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3249    #[must_use]
3250    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3251        self.meta = meta.into_option();
3252        self
3253    }
3254}
3255
3256// Permission
3257
3258/// Request for user permission to proceed with an operation.
3259///
3260/// Sent when the agent needs authorization before performing a sensitive operation.
3261///
3262/// See protocol docs: [Requesting Permission](https://agentclientprotocol.com/protocol/v2/tool-calls#requesting-permission)
3263#[serde_as]
3264#[skip_serializing_none]
3265#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3266#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3267#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
3268#[serde(rename_all = "camelCase")]
3269#[non_exhaustive]
3270pub struct RequestPermissionRequest {
3271    /// The session ID for this request.
3272    pub session_id: SessionId,
3273    /// Human-readable title for the permission prompt.
3274    ///
3275    /// This title is specific to the permission prompt and does not update any
3276    /// subject's displayed title.
3277    pub title: String,
3278    /// Optional human-readable explanation of why permission is needed.
3279    ///
3280    /// This text is specific to the permission prompt and does not update any
3281    /// subject's displayed content. Omitted and `null` are equivalent and mean no separate
3282    /// permission description was provided.
3283    #[serde_as(deserialize_as = "DefaultOnError")]
3284    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3285    #[serde(default)]
3286    pub description: Option<String>,
3287    /// Optional structured context about the operation requiring permission.
3288    ///
3289    /// Omitted and `null` are equivalent and mean no structured subject was provided.
3290    #[serde(default)]
3291    pub subject: Option<RequestPermissionSubject>,
3292    /// Available permission options for the user to choose from.
3293    /// Must contain at least one option.
3294    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
3295    pub options: Vec<PermissionOption>,
3296    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3297    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3298    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3299    ///
3300    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3301    #[serde_as(deserialize_as = "DefaultOnError")]
3302    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3303    #[serde(default)]
3304    #[serde(rename = "_meta")]
3305    pub meta: Option<Meta>,
3306}
3307
3308impl RequestPermissionRequest {
3309    /// Builds [`RequestPermissionRequest`] with the required request fields set. Optional fields start unset or empty.
3310    #[must_use]
3311    pub fn new(
3312        session_id: impl Into<SessionId>,
3313        title: impl Into<String>,
3314        options: Vec<PermissionOption>,
3315    ) -> Self {
3316        Self {
3317            session_id: session_id.into(),
3318            title: title.into(),
3319            description: None,
3320            subject: None,
3321            options,
3322            meta: None,
3323        }
3324    }
3325
3326    /// Sets or clears the optional `description` field.
3327    #[must_use]
3328    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3329        self.description = description.into_option();
3330        self
3331    }
3332
3333    /// Sets or clears the optional `subject` field.
3334    #[must_use]
3335    pub fn subject(mut self, subject: impl IntoOption<RequestPermissionSubject>) -> Self {
3336        self.subject = subject.into_option();
3337        self
3338    }
3339
3340    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3341    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3342    /// do not recognize.
3343    ///
3344    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3345    #[must_use]
3346    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3347        self.meta = meta.into_option();
3348        self
3349    }
3350}
3351
3352/// The operation requiring permission.
3353#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3354#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3355#[serde(tag = "type", rename_all = "snake_case")]
3356#[non_exhaustive]
3357pub enum RequestPermissionSubject {
3358    /// Permission is requested before executing a tool call.
3359    ToolCall(Box<ToolCallPermissionSubject>),
3360    /// Permission is requested before running a command.
3361    Command(CommandPermissionSubject),
3362    /// Custom or future permission subject.
3363    ///
3364    /// Values beginning with `_` are reserved for implementation-specific
3365    /// extensions. Unknown values that do not begin with `_` are reserved for
3366    /// future ACP variants.
3367    ///
3368    /// Clients that do not understand this subject type should preserve the raw
3369    /// payload when storing, replaying, proxying, or forwarding permission
3370    /// requests, and otherwise display a generic permission prompt or decline it
3371    /// according to policy.
3372    #[serde(untagged)]
3373    Other(OtherRequestPermissionSubject),
3374}
3375
3376impl From<ToolCallPermissionSubject> for RequestPermissionSubject {
3377    fn from(subject: ToolCallPermissionSubject) -> Self {
3378        Self::ToolCall(Box::new(subject))
3379    }
3380}
3381
3382impl From<ToolCallUpdate> for RequestPermissionSubject {
3383    fn from(tool_call: ToolCallUpdate) -> Self {
3384        ToolCallPermissionSubject::new(tool_call).into()
3385    }
3386}
3387
3388impl From<CommandPermissionSubject> for RequestPermissionSubject {
3389    fn from(subject: CommandPermissionSubject) -> Self {
3390        Self::Command(subject)
3391    }
3392}
3393
3394/// Permission request details for a tool call.
3395#[serde_as]
3396#[skip_serializing_none]
3397#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3398#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3399#[serde(rename_all = "camelCase")]
3400#[non_exhaustive]
3401pub struct ToolCallPermissionSubject {
3402    /// Details about the tool call requiring permission.
3403    ///
3404    /// Clients apply this to their stored tool call exactly like a `tool_call_update`
3405    /// notification, in the order it was received, before showing the prompt. A first-seen
3406    /// `toolCallId` creates the tool call.
3407    pub tool_call: ToolCallUpdate,
3408    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3409    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3410    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3411    ///
3412    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3413    #[serde_as(deserialize_as = "DefaultOnError")]
3414    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3415    #[serde(default)]
3416    #[serde(rename = "_meta")]
3417    pub meta: Option<Meta>,
3418}
3419
3420impl ToolCallPermissionSubject {
3421    /// Builds [`ToolCallPermissionSubject`] with the required fields set.
3422    #[must_use]
3423    pub fn new(tool_call: ToolCallUpdate) -> Self {
3424        Self {
3425            tool_call,
3426            meta: None,
3427        }
3428    }
3429
3430    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3431    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3432    /// do not recognize.
3433    ///
3434    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3435    #[must_use]
3436    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3437        self.meta = meta.into_option();
3438        self
3439    }
3440}
3441
3442/// Permission request details for a command.
3443#[serde_as]
3444#[skip_serializing_none]
3445#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3446#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3447#[serde(rename_all = "camelCase")]
3448#[non_exhaustive]
3449pub struct CommandPermissionSubject {
3450    /// The command that would be run if permission is granted.
3451    pub command: String,
3452    /// The absolute working directory for the command.
3453    pub cwd: AbsolutePath,
3454    /// The associated tool call, when known. Omitted and `null` are equivalent.
3455    #[serde_as(deserialize_as = "DefaultOnError")]
3456    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3457    #[serde(default)]
3458    pub tool_call_id: Option<ToolCallId>,
3459    /// The associated terminal, when already known. Omitted and `null` are equivalent.
3460    #[serde_as(deserialize_as = "DefaultOnError")]
3461    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3462    #[serde(default)]
3463    pub terminal_id: Option<TerminalId>,
3464    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3465    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3466    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3467    ///
3468    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3469    #[serde_as(deserialize_as = "DefaultOnError")]
3470    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3471    #[serde(default)]
3472    #[serde(rename = "_meta")]
3473    pub meta: Option<Meta>,
3474}
3475
3476impl CommandPermissionSubject {
3477    /// Builds command permission details with the required command and working directory.
3478    #[must_use]
3479    pub fn new(command: impl Into<String>, cwd: impl Into<AbsolutePath>) -> Self {
3480        Self {
3481            command: command.into(),
3482            cwd: cwd.into(),
3483            tool_call_id: None,
3484            terminal_id: None,
3485            meta: None,
3486        }
3487    }
3488
3489    /// Sets or clears the associated tool-call ID.
3490    #[must_use]
3491    pub fn tool_call_id(mut self, tool_call_id: impl IntoOption<ToolCallId>) -> Self {
3492        self.tool_call_id = tool_call_id.into_option();
3493        self
3494    }
3495
3496    /// Sets or clears the associated terminal ID.
3497    #[must_use]
3498    pub fn terminal_id(mut self, terminal_id: impl IntoOption<TerminalId>) -> Self {
3499        self.terminal_id = terminal_id.into_option();
3500        self
3501    }
3502
3503    /// Sets or clears subject-scoped metadata.
3504    #[must_use]
3505    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3506        self.meta = meta.into_option();
3507        self
3508    }
3509}
3510
3511/// Custom or future permission subject payload.
3512#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3513#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3514#[cfg_attr(feature = "schemars", schemars(inline))]
3515#[cfg_attr(feature = "schemars", schemars(transform = other_request_permission_subject_schema))]
3516#[serde(rename_all = "camelCase")]
3517#[non_exhaustive]
3518pub struct OtherRequestPermissionSubject {
3519    /// Custom or future permission subject type.
3520    ///
3521    /// Values beginning with `_` are reserved for implementation-specific
3522    /// extensions. Unknown values that do not begin with `_` are reserved for
3523    /// future ACP variants.
3524    #[serde(rename = "type")]
3525    pub type_: String,
3526    /// Additional fields from the unknown permission subject payload.
3527    #[serde(flatten)]
3528    pub fields: BTreeMap<String, serde_json::Value>,
3529}
3530
3531impl OtherRequestPermissionSubject {
3532    /// Builds [`OtherRequestPermissionSubject`] from an unknown discriminator and preserves the remaining extension fields.
3533    #[must_use]
3534    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
3535        fields.remove("type");
3536        Self {
3537            type_: type_.into(),
3538            fields,
3539        }
3540    }
3541}
3542
3543impl<'de> Deserialize<'de> for OtherRequestPermissionSubject {
3544    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3545    where
3546        D: serde::Deserializer<'de>,
3547    {
3548        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
3549        let type_ = fields
3550            .remove("type")
3551            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
3552        let serde_json::Value::String(type_) = type_ else {
3553            return Err(serde::de::Error::custom("`type` must be a string"));
3554        };
3555
3556        if is_known_request_permission_subject_type(&type_) {
3557            return Err(serde::de::Error::custom(format!(
3558                "known request permission subject `{type_}` did not match its schema"
3559            )));
3560        }
3561
3562        Ok(Self { type_, fields })
3563    }
3564}
3565
3566fn is_known_request_permission_subject_type(type_: &str) -> bool {
3567    matches!(type_, "tool_call" | "command")
3568}
3569
3570#[cfg(feature = "schemars")]
3571fn other_request_permission_subject_schema(schema: &mut Schema) {
3572    super::schema_util::reject_known_string_discriminators(
3573        schema,
3574        "type",
3575        &["tool_call", "command"],
3576    );
3577}
3578
3579/// An option presented to the user when requesting permission.
3580#[serde_as]
3581#[skip_serializing_none]
3582#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3583#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3584#[serde(rename_all = "camelCase")]
3585#[non_exhaustive]
3586pub struct PermissionOption {
3587    /// Identifier for this permission option. MUST be unique within the request.
3588    pub option_id: PermissionOptionId,
3589    /// Human-readable label to display to the user.
3590    pub name: String,
3591    /// Hint about the nature of this permission option.
3592    pub kind: PermissionOptionKind,
3593    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3594    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3595    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3596    ///
3597    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3598    #[serde_as(deserialize_as = "DefaultOnError")]
3599    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3600    #[serde(default)]
3601    #[serde(rename = "_meta")]
3602    pub meta: Option<Meta>,
3603}
3604
3605impl PermissionOption {
3606    /// Builds [`PermissionOption`] with the required fields set. Optional fields start unset or empty.
3607    #[must_use]
3608    pub fn new(
3609        option_id: impl Into<PermissionOptionId>,
3610        name: impl Into<String>,
3611        kind: PermissionOptionKind,
3612    ) -> Self {
3613        Self {
3614            option_id: option_id.into(),
3615            name: name.into(),
3616            kind,
3617            meta: None,
3618        }
3619    }
3620
3621    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3622    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3623    /// do not recognize.
3624    ///
3625    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3626    #[must_use]
3627    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3628        self.meta = meta.into_option();
3629        self
3630    }
3631}
3632
3633/// Unique identifier for a permission option.
3634#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3635#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
3636#[serde(transparent)]
3637#[from(forward)]
3638#[non_exhaustive]
3639pub struct PermissionOptionId(pub Arc<str>);
3640
3641impl PermissionOptionId {
3642    /// Wraps a protocol string as a typed [`PermissionOptionId`].
3643    #[must_use]
3644    pub fn new(id: impl Into<Self>) -> Self {
3645        id.into()
3646    }
3647}
3648
3649/// The type of permission option being presented to the user.
3650///
3651/// Helps clients choose appropriate icons and UI treatment.
3652#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3653#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3654#[serde(rename_all = "snake_case")]
3655#[non_exhaustive]
3656pub enum PermissionOptionKind {
3657    /// Allow this operation only this time.
3658    AllowOnce,
3659    /// Allow this operation and remember the choice.
3660    AllowAlways,
3661    /// Reject this operation only this time.
3662    RejectOnce,
3663    /// Reject this operation and remember the choice.
3664    RejectAlways,
3665    /// Custom or future permission option kind.
3666    ///
3667    /// Values beginning with `_` are reserved for implementation-specific
3668    /// extensions. Unknown values that do not begin with `_` are reserved for
3669    /// future ACP variants.
3670    #[serde(untagged)]
3671    Other(String),
3672}
3673
3674/// Response to a permission request.
3675#[serde_as]
3676#[skip_serializing_none]
3677#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3678#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3679#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
3680#[serde(rename_all = "camelCase")]
3681#[non_exhaustive]
3682pub struct RequestPermissionResponse {
3683    /// The user's decision on the permission request.
3684    pub outcome: RequestPermissionOutcome,
3685    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3686    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3687    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3688    ///
3689    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3690    #[serde_as(deserialize_as = "DefaultOnError")]
3691    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3692    #[serde(default)]
3693    #[serde(rename = "_meta")]
3694    pub meta: Option<Meta>,
3695}
3696
3697impl RequestPermissionResponse {
3698    /// Builds [`RequestPermissionResponse`] with the required response fields set. Optional fields start unset or empty.
3699    #[must_use]
3700    pub fn new(outcome: RequestPermissionOutcome) -> Self {
3701        Self {
3702            outcome,
3703            meta: None,
3704        }
3705    }
3706
3707    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3708    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3709    /// do not recognize.
3710    ///
3711    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3712    #[must_use]
3713    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3714        self.meta = meta.into_option();
3715        self
3716    }
3717}
3718
3719/// The outcome of a permission request.
3720#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3721#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3722#[serde(tag = "outcome", rename_all = "snake_case")]
3723#[non_exhaustive]
3724pub enum RequestPermissionOutcome {
3725    /// The request was not approved and no option was selected: the session's work was
3726    /// cancelled, the user dismissed the prompt, or the client declined it by policy.
3727    /// Agents MUST NOT proceed with the operation.
3728    ///
3729    /// The client answers a request the agent cancels with `$/cancel_request` with
3730    /// this outcome. After sending `session/cancel`, the client MAY also send it
3731    /// without waiting for `$/cancel_request`, for a request it knows belongs to the
3732    /// cancelled foreground work.
3733    ///
3734    /// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
3735    Cancelled(CancelledPermissionOutcome),
3736    /// The user selected one of the provided options.
3737    ///
3738    /// If `optionId` doesn't match an offered option, the agent MUST treat the request as not
3739    /// approved.
3740    #[serde(rename_all = "camelCase")]
3741    Selected(SelectedPermissionOutcome),
3742    /// Custom or future permission outcome.
3743    ///
3744    /// Values beginning with `_` are reserved for implementation-specific
3745    /// extensions. Unknown values that do not begin with `_` are reserved for
3746    /// future ACP variants.
3747    ///
3748    /// Agents that do not understand this outcome MUST NOT treat it as approval.
3749    /// They should preserve the raw payload when storing, replaying, proxying, or
3750    /// forwarding permission responses, and otherwise fail or decline the
3751    /// permission request according to policy.
3752    #[serde(untagged)]
3753    Other(OtherRequestPermissionOutcome),
3754}
3755
3756/// Custom or future permission outcome payload.
3757///
3758/// This preserves the unknown `outcome` discriminator and the rest of the
3759/// outcome object for agents that store, replay, proxy, or forward permission
3760/// responses.
3761#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3762#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3763#[cfg_attr(feature = "schemars", schemars(inline))]
3764#[cfg_attr(feature = "schemars", schemars(transform = other_request_permission_outcome_schema))]
3765#[serde(rename_all = "camelCase")]
3766#[non_exhaustive]
3767pub struct OtherRequestPermissionOutcome {
3768    /// Custom or future permission outcome.
3769    ///
3770    /// Values beginning with `_` are reserved for implementation-specific
3771    /// extensions. Unknown values that do not begin with `_` are reserved for
3772    /// future ACP variants.
3773    pub outcome: String,
3774    /// Additional fields from the unknown permission outcome payload.
3775    #[serde(flatten)]
3776    pub fields: BTreeMap<String, serde_json::Value>,
3777}
3778
3779impl OtherRequestPermissionOutcome {
3780    /// Builds [`OtherRequestPermissionOutcome`] from an unknown discriminator and preserves the remaining extension fields.
3781    #[must_use]
3782    pub fn new(
3783        outcome: impl Into<String>,
3784        mut fields: BTreeMap<String, serde_json::Value>,
3785    ) -> Self {
3786        fields.remove("outcome");
3787        Self {
3788            outcome: outcome.into(),
3789            fields,
3790        }
3791    }
3792}
3793
3794impl<'de> Deserialize<'de> for OtherRequestPermissionOutcome {
3795    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3796    where
3797        D: serde::Deserializer<'de>,
3798    {
3799        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
3800        let outcome = fields
3801            .remove("outcome")
3802            .ok_or_else(|| serde::de::Error::missing_field("outcome"))?;
3803        let serde_json::Value::String(outcome) = outcome else {
3804            return Err(serde::de::Error::custom("`outcome` must be a string"));
3805        };
3806
3807        if is_known_request_permission_outcome(&outcome) {
3808            return Err(serde::de::Error::custom(format!(
3809                "known request permission outcome `{outcome}` did not match its schema"
3810            )));
3811        }
3812
3813        Ok(Self { outcome, fields })
3814    }
3815}
3816
3817fn is_known_request_permission_outcome(outcome: &str) -> bool {
3818    matches!(outcome, "cancelled" | "selected")
3819}
3820
3821#[cfg(feature = "schemars")]
3822fn other_request_permission_outcome_schema(schema: &mut Schema) {
3823    super::schema_util::reject_known_string_discriminators(
3824        schema,
3825        "outcome",
3826        &["cancelled", "selected"],
3827    );
3828}
3829
3830/// The request was not approved and no option was selected.
3831#[serde_as]
3832#[skip_serializing_none]
3833#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3834#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3835#[serde(rename_all = "camelCase")]
3836#[non_exhaustive]
3837pub struct CancelledPermissionOutcome {
3838    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3839    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3840    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3841    ///
3842    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3843    #[serde_as(deserialize_as = "DefaultOnError")]
3844    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3845    #[serde(default)]
3846    #[serde(rename = "_meta")]
3847    pub meta: Option<Meta>,
3848}
3849
3850impl CancelledPermissionOutcome {
3851    /// Builds an empty [`CancelledPermissionOutcome`].
3852    #[must_use]
3853    pub fn new() -> Self {
3854        Self::default()
3855    }
3856
3857    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3858    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3859    /// do not recognize.
3860    ///
3861    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3862    #[must_use]
3863    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3864        self.meta = meta.into_option();
3865        self
3866    }
3867}
3868
3869impl From<CancelledPermissionOutcome> for RequestPermissionOutcome {
3870    fn from(outcome: CancelledPermissionOutcome) -> Self {
3871        Self::Cancelled(outcome)
3872    }
3873}
3874
3875/// The user selected one of the provided options.
3876#[serde_as]
3877#[skip_serializing_none]
3878#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3879#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3880#[serde(rename_all = "camelCase")]
3881#[non_exhaustive]
3882pub struct SelectedPermissionOutcome {
3883    /// The ID of the option the user selected.
3884    pub option_id: PermissionOptionId,
3885    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3886    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3887    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3888    ///
3889    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3890    #[serde_as(deserialize_as = "DefaultOnError")]
3891    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3892    #[serde(default)]
3893    #[serde(rename = "_meta")]
3894    pub meta: Option<Meta>,
3895}
3896
3897impl SelectedPermissionOutcome {
3898    /// Builds [`SelectedPermissionOutcome`] with the required fields set. Optional fields start unset or empty.
3899    #[must_use]
3900    pub fn new(option_id: impl Into<PermissionOptionId>) -> Self {
3901        Self {
3902            option_id: option_id.into(),
3903            meta: None,
3904        }
3905    }
3906
3907    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3908    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3909    /// do not recognize.
3910    ///
3911    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3912    #[must_use]
3913    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3914        self.meta = meta.into_option();
3915        self
3916    }
3917}
3918
3919// Capabilities
3920
3921/// Capabilities supported by the client.
3922///
3923/// Advertised during initialization to inform the agent about
3924/// available features and methods.
3925///
3926/// See protocol docs: [Client Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#client-capabilities)
3927#[serde_as]
3928#[skip_serializing_none]
3929#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3930#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3931#[serde(rename_all = "camelCase")]
3932#[non_exhaustive]
3933pub struct ClientCapabilities {
3934    /// Authentication capabilities supported by the client.
3935    /// Determines which authentication method types the agent may include
3936    /// in its `InitializeResponse`.
3937    ///
3938    /// Optional. Omitted and `null` are equivalent and mean the client does not advertise any
3939    /// authentication-method extensions.
3940    #[serde_as(deserialize_as = "DefaultOnError")]
3941    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3942    #[serde(default)]
3943    pub auth: Option<ClientAuthCapabilities>,
3944    /// Elicitation capabilities supported by the client.
3945    /// Determines which elicitation modes the agent may use.
3946    ///
3947    /// Optional. Omitted and `null` are equivalent and mean the client does not advertise
3948    /// elicitation support.
3949    #[serde_as(deserialize_as = "DefaultOnError")]
3950    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3951    #[serde(default)]
3952    pub elicitation: Option<ElicitationCapabilities>,
3953    /// **UNSTABLE**
3954    ///
3955    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3956    ///
3957    /// Session-related capabilities supported by the client.
3958    ///
3959    /// Optional. Omitted and `null` are equivalent and mean the client does not advertise any
3960    /// session-related capabilities. This object only groups capabilities. Supplying `{}`
3961    /// advertises nothing.
3962    #[cfg(any(
3963        feature = "unstable_prompt_suggestions",
3964        feature = "unstable_agent_skills"
3965    ))]
3966    #[serde_as(deserialize_as = "DefaultOnError")]
3967    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3968    #[serde(default)]
3969    pub session: Option<ClientSessionCapabilities>,
3970
3971    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3972    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3973    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3974    ///
3975    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3976    #[serde_as(deserialize_as = "DefaultOnError")]
3977    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3978    #[serde(default)]
3979    #[serde(rename = "_meta")]
3980    pub meta: Option<Meta>,
3981}
3982
3983impl ClientCapabilities {
3984    /// Builds an empty [`ClientCapabilities`]. Use builder methods to advertise supported sub-capabilities.
3985    #[must_use]
3986    pub fn new() -> Self {
3987        Self::default()
3988    }
3989
3990    /// Authentication capabilities supported by the client.
3991    /// Determines which authentication method types the agent may include
3992    /// in its `InitializeResponse`.
3993    #[must_use]
3994    pub fn auth(mut self, auth: impl IntoOption<ClientAuthCapabilities>) -> Self {
3995        self.auth = auth.into_option();
3996        self
3997    }
3998
3999    /// Elicitation capabilities supported by the client.
4000    /// Determines which elicitation modes the agent may use.
4001    #[must_use]
4002    pub fn elicitation(mut self, elicitation: impl IntoOption<ElicitationCapabilities>) -> Self {
4003        self.elicitation = elicitation.into_option();
4004        self
4005    }
4006
4007    /// **UNSTABLE**
4008    ///
4009    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4010    ///
4011    /// Session-related capabilities supported by the client.
4012    #[cfg(any(
4013        feature = "unstable_prompt_suggestions",
4014        feature = "unstable_agent_skills"
4015    ))]
4016    #[must_use]
4017    pub fn session(mut self, session: impl IntoOption<ClientSessionCapabilities>) -> Self {
4018        self.session = session.into_option();
4019        self
4020    }
4021
4022    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4023    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4024    /// do not recognize.
4025    ///
4026    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4027    #[must_use]
4028    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4029        self.meta = meta.into_option();
4030        self
4031    }
4032}
4033
4034/// **UNSTABLE**
4035///
4036/// This capability is not part of the spec yet, and may be removed or changed at any point.
4037///
4038/// Session-related capabilities supported by the client.
4039///
4040/// This object only groups capabilities. Unlike the agent's `session`
4041/// capability, it is not a support marker, and supplying `{}` advertises
4042/// nothing.
4043#[cfg(any(
4044    feature = "unstable_prompt_suggestions",
4045    feature = "unstable_agent_skills"
4046))]
4047#[serde_as]
4048#[skip_serializing_none]
4049#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4050#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4051#[serde(rename_all = "camelCase")]
4052#[non_exhaustive]
4053pub struct ClientSessionCapabilities {
4054    /// Support for `prompt_suggestions_update` session updates.
4055    ///
4056    /// Optional. Omitted and `null` are equivalent and mean the client does not advertise support.
4057    /// Supplying `{}` means the client can offer prompt suggestions made of
4058    /// `text` and `resource_link` content blocks.
4059    #[cfg(feature = "unstable_prompt_suggestions")]
4060    #[serde_as(deserialize_as = "DefaultOnError")]
4061    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4062    #[serde(default)]
4063    pub prompt_suggestions: Option<PromptSuggestionsCapabilities>,
4064    /// Command types the client understands in addition to `command`.
4065    ///
4066    /// Optional. Omitted and `null` are equivalent and mean the client does not advertise support
4067    /// for any of them. This object only groups capabilities. Supplying `{}` advertises nothing.
4068    #[cfg(feature = "unstable_agent_skills")]
4069    #[serde_as(deserialize_as = "DefaultOnError")]
4070    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4071    #[serde(default)]
4072    pub commands: Option<CommandsCapabilities>,
4073    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4074    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4075    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4076    ///
4077    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4078    #[serde_as(deserialize_as = "DefaultOnError")]
4079    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4080    #[serde(default)]
4081    #[serde(rename = "_meta")]
4082    pub meta: Option<Meta>,
4083}
4084
4085#[cfg(any(
4086    feature = "unstable_prompt_suggestions",
4087    feature = "unstable_agent_skills"
4088))]
4089impl ClientSessionCapabilities {
4090    /// Builds an empty [`ClientSessionCapabilities`]. Use builder methods to advertise supported sub-capabilities.
4091    #[must_use]
4092    pub fn new() -> Self {
4093        Self::default()
4094    }
4095
4096    /// Advertises support for `prompt_suggestions_update` session updates.
4097    #[cfg(feature = "unstable_prompt_suggestions")]
4098    #[must_use]
4099    pub fn prompt_suggestions(
4100        mut self,
4101        prompt_suggestions: impl IntoOption<PromptSuggestionsCapabilities>,
4102    ) -> Self {
4103        self.prompt_suggestions = prompt_suggestions.into_option();
4104        self
4105    }
4106
4107    /// Command types the client understands in addition to `command`.
4108    #[cfg(feature = "unstable_agent_skills")]
4109    #[must_use]
4110    pub fn commands(mut self, commands: impl IntoOption<CommandsCapabilities>) -> Self {
4111        self.commands = commands.into_option();
4112        self
4113    }
4114
4115    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4116    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4117    /// do not recognize.
4118    ///
4119    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4120    #[must_use]
4121    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4122        self.meta = meta.into_option();
4123        self
4124    }
4125}
4126
4127/// **UNSTABLE**
4128///
4129/// This capability is not part of the spec yet, and may be removed or changed at any point.
4130///
4131/// Command types the client understands in addition to `command`.
4132///
4133/// Agents MUST NOT send a command type listed here unless the client
4134/// advertised it. This object only groups capabilities. Supplying `{}`
4135/// advertises nothing.
4136#[cfg(feature = "unstable_agent_skills")]
4137#[serde_as]
4138#[skip_serializing_none]
4139#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4140#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4141#[serde(rename_all = "camelCase")]
4142#[non_exhaustive]
4143pub struct CommandsCapabilities {
4144    /// Support for `skill` command entries.
4145    ///
4146    /// Optional. Omitted and `null` are equivalent and mean the client does not advertise support.
4147    /// Supplying `{}` means the agent may send `skill` entries in `availableCommands`. The
4148    /// client invokes them with `skill` content blocks.
4149    #[serde_as(deserialize_as = "DefaultOnError")]
4150    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4151    #[serde(default)]
4152    pub skill: Option<CommandsSkillCapabilities>,
4153    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4154    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4155    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4156    ///
4157    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4158    #[serde_as(deserialize_as = "DefaultOnError")]
4159    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4160    #[serde(default)]
4161    #[serde(rename = "_meta")]
4162    pub meta: Option<Meta>,
4163}
4164
4165#[cfg(feature = "unstable_agent_skills")]
4166impl CommandsCapabilities {
4167    /// Builds an empty [`CommandsCapabilities`]. Use builder methods to advertise supported sub-capabilities.
4168    #[must_use]
4169    pub fn new() -> Self {
4170        Self::default()
4171    }
4172
4173    /// Advertises support for `skill` command entries.
4174    #[must_use]
4175    pub fn skill(mut self, skill: impl IntoOption<CommandsSkillCapabilities>) -> Self {
4176        self.skill = skill.into_option();
4177        self
4178    }
4179
4180    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4181    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4182    /// do not recognize.
4183    ///
4184    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4185    #[must_use]
4186    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4187        self.meta = meta.into_option();
4188        self
4189    }
4190}
4191
4192/// **UNSTABLE**
4193///
4194/// This capability is not part of the spec yet, and may be removed or changed at any point.
4195///
4196/// Client support for `skill` command entries.
4197///
4198/// Supplying `{}` means the agent may send `skill` entries in
4199/// `availableCommands`. The client invokes them with `skill` content blocks.
4200#[cfg(feature = "unstable_agent_skills")]
4201#[serde_as]
4202#[skip_serializing_none]
4203#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4204#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4205#[non_exhaustive]
4206pub struct CommandsSkillCapabilities {
4207    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4208    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4209    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4210    ///
4211    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4212    #[serde_as(deserialize_as = "DefaultOnError")]
4213    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4214    #[serde(default)]
4215    #[serde(rename = "_meta")]
4216    pub meta: Option<Meta>,
4217}
4218
4219#[cfg(feature = "unstable_agent_skills")]
4220impl CommandsSkillCapabilities {
4221    /// Builds an empty [`CommandsSkillCapabilities`]. Use builder methods to advertise supported sub-capabilities.
4222    #[must_use]
4223    pub fn new() -> Self {
4224        Self::default()
4225    }
4226
4227    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4228    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4229    /// do not recognize.
4230    ///
4231    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4232    #[must_use]
4233    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4234        self.meta = meta.into_option();
4235        self
4236    }
4237}
4238
4239/// **UNSTABLE**
4240///
4241/// This capability is not part of the spec yet, and may be removed or changed at any point.
4242///
4243/// Client support for `prompt_suggestions_update` session updates.
4244///
4245/// Supplying `{}` means the client can offer prompt suggestions made of `text`
4246/// and `resource_link` content blocks. The client opts in to other content
4247/// block types with the fields below. They have the same names as the agent's
4248/// `session.prompt` capability.
4249#[cfg(feature = "unstable_prompt_suggestions")]
4250#[serde_as]
4251#[skip_serializing_none]
4252#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4253#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4254#[serde(rename_all = "camelCase")]
4255#[non_exhaustive]
4256pub struct PromptSuggestionsCapabilities {
4257    /// Whether prompt suggestions may include `image` content blocks.
4258    ///
4259    /// Optional. Omitted and `null` are equivalent and mean the client does not advertise support.
4260    /// Supplying `{}` means the client can offer suggestions that include images.
4261    #[serde_as(deserialize_as = "DefaultOnError")]
4262    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4263    #[serde(default)]
4264    pub image: Option<PromptSuggestionsImageCapabilities>,
4265    /// Whether prompt suggestions may include `audio` content blocks.
4266    ///
4267    /// Optional. Omitted and `null` are equivalent and mean the client does not advertise support.
4268    /// Supplying `{}` means the client can offer suggestions that include audio.
4269    #[serde_as(deserialize_as = "DefaultOnError")]
4270    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4271    #[serde(default)]
4272    pub audio: Option<PromptSuggestionsAudioCapabilities>,
4273    /// Whether prompt suggestions may include `resource` content blocks.
4274    ///
4275    /// Optional. Omitted and `null` are equivalent and mean the client does not advertise support.
4276    /// Supplying `{}` means the client can offer suggestions that include
4277    /// embedded resources.
4278    #[serde_as(deserialize_as = "DefaultOnError")]
4279    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4280    #[serde(default)]
4281    pub embedded_context: Option<PromptSuggestionsEmbeddedContextCapabilities>,
4282    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4283    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4284    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4285    ///
4286    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4287    #[serde_as(deserialize_as = "DefaultOnError")]
4288    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4289    #[serde(default)]
4290    #[serde(rename = "_meta")]
4291    pub meta: Option<Meta>,
4292}
4293
4294#[cfg(feature = "unstable_prompt_suggestions")]
4295impl PromptSuggestionsCapabilities {
4296    /// Builds an empty [`PromptSuggestionsCapabilities`]. Use builder methods to advertise supported sub-capabilities.
4297    #[must_use]
4298    pub fn new() -> Self {
4299        Self::default()
4300    }
4301
4302    /// Whether prompt suggestions may include `image` content blocks.
4303    #[must_use]
4304    pub fn image(mut self, image: impl IntoOption<PromptSuggestionsImageCapabilities>) -> Self {
4305        self.image = image.into_option();
4306        self
4307    }
4308
4309    /// Whether prompt suggestions may include `audio` content blocks.
4310    #[must_use]
4311    pub fn audio(mut self, audio: impl IntoOption<PromptSuggestionsAudioCapabilities>) -> Self {
4312        self.audio = audio.into_option();
4313        self
4314    }
4315
4316    /// Whether prompt suggestions may include `resource` content blocks.
4317    #[must_use]
4318    pub fn embedded_context(
4319        mut self,
4320        embedded_context: impl IntoOption<PromptSuggestionsEmbeddedContextCapabilities>,
4321    ) -> Self {
4322        self.embedded_context = embedded_context.into_option();
4323        self
4324    }
4325
4326    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4327    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4328    /// do not recognize.
4329    ///
4330    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4331    #[must_use]
4332    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4333        self.meta = meta.into_option();
4334        self
4335    }
4336}
4337
4338/// **UNSTABLE**
4339///
4340/// This capability is not part of the spec yet, and may be removed or changed at any point.
4341///
4342/// Capabilities for image content in prompt suggestions.
4343///
4344/// Supplying `{}` means the client can offer suggestions that include images.
4345#[cfg(feature = "unstable_prompt_suggestions")]
4346#[serde_as]
4347#[skip_serializing_none]
4348#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4349#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4350#[non_exhaustive]
4351pub struct PromptSuggestionsImageCapabilities {
4352    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4353    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4354    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4355    ///
4356    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4357    #[serde_as(deserialize_as = "DefaultOnError")]
4358    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4359    #[serde(default)]
4360    #[serde(rename = "_meta")]
4361    pub meta: Option<Meta>,
4362}
4363
4364#[cfg(feature = "unstable_prompt_suggestions")]
4365impl PromptSuggestionsImageCapabilities {
4366    /// Builds an empty [`PromptSuggestionsImageCapabilities`]. Use builder methods to advertise supported sub-capabilities.
4367    #[must_use]
4368    pub fn new() -> Self {
4369        Self::default()
4370    }
4371
4372    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4373    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4374    /// do not recognize.
4375    ///
4376    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4377    #[must_use]
4378    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4379        self.meta = meta.into_option();
4380        self
4381    }
4382}
4383
4384/// **UNSTABLE**
4385///
4386/// This capability is not part of the spec yet, and may be removed or changed at any point.
4387///
4388/// Capabilities for audio content in prompt suggestions.
4389///
4390/// Supplying `{}` means the client can offer suggestions that include audio.
4391#[cfg(feature = "unstable_prompt_suggestions")]
4392#[serde_as]
4393#[skip_serializing_none]
4394#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4395#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4396#[non_exhaustive]
4397pub struct PromptSuggestionsAudioCapabilities {
4398    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4399    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4400    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4401    ///
4402    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4403    #[serde_as(deserialize_as = "DefaultOnError")]
4404    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4405    #[serde(default)]
4406    #[serde(rename = "_meta")]
4407    pub meta: Option<Meta>,
4408}
4409
4410#[cfg(feature = "unstable_prompt_suggestions")]
4411impl PromptSuggestionsAudioCapabilities {
4412    /// Builds an empty [`PromptSuggestionsAudioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
4413    #[must_use]
4414    pub fn new() -> Self {
4415        Self::default()
4416    }
4417
4418    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4419    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4420    /// do not recognize.
4421    ///
4422    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4423    #[must_use]
4424    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4425        self.meta = meta.into_option();
4426        self
4427    }
4428}
4429
4430/// **UNSTABLE**
4431///
4432/// This capability is not part of the spec yet, and may be removed or changed at any point.
4433///
4434/// Capabilities for embedded resources in prompt suggestions.
4435///
4436/// Supplying `{}` means the client can offer suggestions that include
4437/// `resource` content blocks.
4438#[cfg(feature = "unstable_prompt_suggestions")]
4439#[serde_as]
4440#[skip_serializing_none]
4441#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4442#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4443#[non_exhaustive]
4444pub struct PromptSuggestionsEmbeddedContextCapabilities {
4445    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4446    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4447    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4448    ///
4449    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4450    #[serde_as(deserialize_as = "DefaultOnError")]
4451    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4452    #[serde(default)]
4453    #[serde(rename = "_meta")]
4454    pub meta: Option<Meta>,
4455}
4456
4457#[cfg(feature = "unstable_prompt_suggestions")]
4458impl PromptSuggestionsEmbeddedContextCapabilities {
4459    /// Builds an empty [`PromptSuggestionsEmbeddedContextCapabilities`]. Use builder methods to advertise supported sub-capabilities.
4460    #[must_use]
4461    pub fn new() -> Self {
4462        Self::default()
4463    }
4464
4465    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4466    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4467    /// do not recognize.
4468    ///
4469    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4470    #[must_use]
4471    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4472        self.meta = meta.into_option();
4473        self
4474    }
4475}
4476
4477/// Authentication capabilities supported by the client.
4478///
4479/// Advertised during initialization to inform the agent which authentication
4480/// method types the client can handle. This governs opt-in types that require
4481/// additional client-side support.
4482#[serde_as]
4483#[skip_serializing_none]
4484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4485#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4486#[serde(rename_all = "camelCase")]
4487#[non_exhaustive]
4488pub struct ClientAuthCapabilities {
4489    /// Whether the client supports `terminal` authentication methods.
4490    ///
4491    /// Optional. Omitted and `null` are equivalent and mean the client does not advertise support.
4492    /// The client should supply `{}` only when it can reproduce the configured
4493    /// agent invocation in an interactive terminal. Supplying `{}` means the
4494    /// agent may include `terminal` entries in its authentication methods.
4495    #[serde_as(deserialize_as = "DefaultOnError")]
4496    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4497    #[serde(default)]
4498    pub terminal: Option<TerminalAuthCapabilities>,
4499    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4500    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4501    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4502    ///
4503    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4504    #[serde_as(deserialize_as = "DefaultOnError")]
4505    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4506    #[serde(default)]
4507    #[serde(rename = "_meta")]
4508    pub meta: Option<Meta>,
4509}
4510
4511impl ClientAuthCapabilities {
4512    /// Builds an empty [`ClientAuthCapabilities`]. Use builder methods to advertise supported sub-capabilities.
4513    #[must_use]
4514    pub fn new() -> Self {
4515        Self::default()
4516    }
4517
4518    /// Whether the client supports `terminal` authentication methods.
4519    ///
4520    /// Omitted and `null` are equivalent and mean the client does not advertise support.
4521    /// The client should supply `{}` only when it can reproduce the configured
4522    /// agent invocation in an interactive terminal. Supplying `{}` means the
4523    /// agent may include `AuthMethod::Terminal` entries in its authentication
4524    /// methods.
4525    #[must_use]
4526    pub fn terminal(mut self, terminal: impl IntoOption<TerminalAuthCapabilities>) -> Self {
4527        self.terminal = terminal.into_option();
4528        self
4529    }
4530
4531    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4532    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4533    /// do not recognize.
4534    ///
4535    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4536    #[must_use]
4537    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4538        self.meta = meta.into_option();
4539        self
4540    }
4541}
4542
4543/// Capabilities for terminal authentication methods.
4544///
4545/// Supplying `{}` means the client can reproduce the configured agent
4546/// invocation in an interactive terminal and supports terminal authentication
4547/// methods.
4548#[serde_as]
4549#[skip_serializing_none]
4550#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4551#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4552#[non_exhaustive]
4553pub struct TerminalAuthCapabilities {
4554    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4555    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4556    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4557    ///
4558    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4559    #[serde_as(deserialize_as = "DefaultOnError")]
4560    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4561    #[serde(default)]
4562    #[serde(rename = "_meta")]
4563    pub meta: Option<Meta>,
4564}
4565
4566impl TerminalAuthCapabilities {
4567    /// Builds an empty [`TerminalAuthCapabilities`]. Use builder methods to advertise supported sub-capabilities.
4568    #[must_use]
4569    pub fn new() -> Self {
4570        Self::default()
4571    }
4572
4573    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4574    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4575    /// do not recognize.
4576    ///
4577    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4578    #[must_use]
4579    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4580        self.meta = meta.into_option();
4581        self
4582    }
4583}
4584
4585// Method schema
4586
4587/// Names of all methods that clients handle.
4588///
4589/// Provides a centralized definition of method names used in the protocol.
4590#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4591#[non_exhaustive]
4592pub struct ClientMethodNames {
4593    /// Method for requesting permission from the user.
4594    pub session_request_permission: &'static str,
4595    /// Notification for session updates.
4596    pub session_update: &'static str,
4597    /// Method for exchanging MCP-over-ACP messages.
4598    #[cfg(feature = "unstable_mcp_over_acp")]
4599    pub mcp_message: &'static str,
4600    /// Method for elicitation.
4601    pub elicitation_create: &'static str,
4602    /// Notification for elicitation completion.
4603    pub elicitation_complete: &'static str,
4604    /// Notification for authentication status changes.
4605    #[cfg(feature = "unstable_auth_status")]
4606    pub auth_status_update: &'static str,
4607}
4608
4609/// Constant containing all client method names.
4610pub const CLIENT_METHOD_NAMES: ClientMethodNames = ClientMethodNames {
4611    session_update: SESSION_UPDATE_NOTIFICATION,
4612    session_request_permission: SESSION_REQUEST_PERMISSION_METHOD_NAME,
4613    #[cfg(feature = "unstable_mcp_over_acp")]
4614    mcp_message: MCP_MESSAGE_METHOD_NAME,
4615    elicitation_create: ELICITATION_CREATE_METHOD_NAME,
4616    elicitation_complete: ELICITATION_COMPLETE_NOTIFICATION,
4617    #[cfg(feature = "unstable_auth_status")]
4618    auth_status_update: AUTH_STATUS_UPDATE_NOTIFICATION,
4619};
4620
4621/// Notification name for session updates.
4622pub(crate) const SESSION_UPDATE_NOTIFICATION: &str = "session/update";
4623/// Method name for requesting user permission.
4624pub(crate) const SESSION_REQUEST_PERMISSION_METHOD_NAME: &str = "session/request_permission";
4625/// Method name for elicitation.
4626pub(crate) const ELICITATION_CREATE_METHOD_NAME: &str = "elicitation/create";
4627/// Notification name for elicitation completion.
4628pub(crate) const ELICITATION_COMPLETE_NOTIFICATION: &str = "elicitation/complete";
4629/// Notification name for authentication status changes.
4630#[cfg(feature = "unstable_auth_status")]
4631pub(crate) const AUTH_STATUS_UPDATE_NOTIFICATION: &str = "auth/status_update";
4632
4633/// All possible requests that an agent can send to a client.
4634///
4635/// This enum is used internally for routing RPC requests. You typically won't need
4636/// to use this directly.
4637///
4638/// This enum encompasses all method calls from agent to client.
4639#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4640#[derive(Clone, Debug, Serialize, Deserialize)]
4641#[serde(untagged)]
4642#[cfg_attr(feature = "schemars", schemars(inline))]
4643#[non_exhaustive]
4644pub enum AgentRequest {
4645    /// Requests permission from the user for an operation.
4646    ///
4647    /// Called by the agent when it needs user authorization before executing
4648    /// a potentially sensitive operation. The client should present the options
4649    /// to the user and return their decision.
4650    ///
4651    /// After `session/cancel`, the agent stops waiting for requests of the cancelled
4652    /// foreground work and SHOULD cancel them with `$/cancel_request`. The client
4653    /// answers a cancelled request with the `cancelled` outcome.
4654    ///
4655    /// See protocol docs: [Requesting Permission](https://agentclientprotocol.com/protocol/v2/tool-calls#requesting-permission)
4656    RequestPermissionRequest(Box<RequestPermissionRequest>),
4657    /// Requests structured user input via a form or URL.
4658    ///
4659    /// See protocol docs: [Elicitation](https://agentclientprotocol.com/protocol/v2/elicitation)
4660    CreateElicitationRequest(Box<CreateElicitationRequest>),
4661    /// **UNSTABLE**
4662    ///
4663    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4664    ///
4665    /// Exchanges an MCP-over-ACP message.
4666    #[cfg(feature = "unstable_mcp_over_acp")]
4667    MessageMcpRequest(Box<MessageMcpRequest>),
4668    /// Handles extension method requests from the agent.
4669    ///
4670    /// Allows the Agent to send an arbitrary request that is not part of the ACP spec.
4671    /// Extension methods provide a way to add custom functionality while maintaining
4672    /// protocol compatibility.
4673    ///
4674    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4675    ExtMethodRequest(Box<ExtRequest>),
4676}
4677
4678impl AgentRequest {
4679    /// Returns the corresponding method name of the request.
4680    #[must_use]
4681    pub fn method(&self) -> &str {
4682        match self {
4683            Self::RequestPermissionRequest(_) => CLIENT_METHOD_NAMES.session_request_permission,
4684            Self::CreateElicitationRequest(_) => CLIENT_METHOD_NAMES.elicitation_create,
4685            #[cfg(feature = "unstable_mcp_over_acp")]
4686            Self::MessageMcpRequest(_) => CLIENT_METHOD_NAMES.mcp_message,
4687            Self::ExtMethodRequest(ext_request) => &ext_request.method,
4688        }
4689    }
4690}
4691
4692/// All possible responses that a client can send to an agent.
4693///
4694/// This enum is used internally for routing RPC responses. You typically won't need
4695/// to use this directly - the responses are handled automatically by the connection.
4696///
4697/// These are responses to the corresponding `AgentRequest` variants.
4698#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4699#[derive(Clone, Debug, Serialize, Deserialize)]
4700#[serde(untagged)]
4701#[cfg_attr(feature = "schemars", schemars(inline))]
4702#[non_exhaustive]
4703pub enum ClientResponse {
4704    /// Successful result returned for a `session/request_permission` request.
4705    RequestPermissionResponse(Box<RequestPermissionResponse>),
4706    /// Successful result returned for a `elicitation/create` request.
4707    CreateElicitationResponse(Box<CreateElicitationResponse>),
4708    /// Successful result returned by an MCP-over-ACP `mcp/message` request.
4709    #[cfg(feature = "unstable_mcp_over_acp")]
4710    MessageMcpResponse(Box<MessageMcpResponse>),
4711    /// Successful result returned by an extension method outside the core ACP method set.
4712    ExtMethodResponse(Box<ExtResponse>),
4713}
4714
4715/// All possible notifications that an agent can send to a client.
4716///
4717/// This enum is used internally for routing RPC notifications. You typically won't need
4718/// to use this directly.
4719///
4720/// Notifications do not expect a response.
4721#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4722#[derive(Clone, Debug, Serialize, Deserialize)]
4723#[serde(untagged)]
4724#[cfg_attr(feature = "schemars", schemars(inline))]
4725#[non_exhaustive]
4726pub enum AgentNotification {
4727    /// Handles session update notifications from the agent.
4728    ///
4729    /// This is a notification endpoint (no response expected) that receives
4730    /// updates about session activity, including message updates, message chunks,
4731    /// tool calls, and execution plans.
4732    ///
4733    /// Note: Clients SHOULD continue accepting tool call updates even after
4734    /// sending a `session/cancel` notification, as the agent may send final
4735    /// updates before reporting an idle `state_update` with the cancelled
4736    /// stop reason.
4737    ///
4738    /// See protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#3-agent-reports-output)
4739    UpdateSessionNotification(Box<UpdateSessionNotification>),
4740    /// Notification that a URL-based elicitation has completed.
4741    ///
4742    /// See protocol docs: [Elicitation](https://agentclientprotocol.com/protocol/v2/elicitation#url-completion)
4743    CompleteElicitationNotification(Box<CompleteElicitationNotification>),
4744    /// **UNSTABLE**
4745    ///
4746    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4747    ///
4748    /// Notification that the agent's authentication state changed.
4749    ///
4750    /// Only sent by agents that advertise the `auth.status` capability.
4751    #[cfg(feature = "unstable_auth_status")]
4752    AuthStatusUpdateNotification(Box<AuthStatusUpdateNotification>),
4753    /// Handles extension notifications from the agent.
4754    ///
4755    /// Allows the Agent to send an arbitrary notification that is not part of the ACP spec.
4756    /// Extension notifications provide a way to send one-way messages for custom functionality
4757    /// while maintaining protocol compatibility.
4758    ///
4759    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4760    ExtNotification(Box<ExtNotification>),
4761}
4762
4763impl AgentNotification {
4764    /// Returns the corresponding method name of the notification.
4765    #[must_use]
4766    pub fn method(&self) -> &str {
4767        match self {
4768            Self::UpdateSessionNotification(_) => CLIENT_METHOD_NAMES.session_update,
4769            Self::CompleteElicitationNotification(_) => CLIENT_METHOD_NAMES.elicitation_complete,
4770            #[cfg(feature = "unstable_auth_status")]
4771            Self::AuthStatusUpdateNotification(_) => CLIENT_METHOD_NAMES.auth_status_update,
4772            Self::ExtNotification(ext_notification) => &ext_notification.method,
4773        }
4774    }
4775}
4776
4777#[cfg(test)]
4778mod tests {
4779
4780    #[test]
4781    fn background_list_round_trips_on_state_updates() {
4782        use serde_json::json;
4783        let idle = super::StateUpdate::Idle(super::IdleStateUpdate::new().background(vec![
4784            super::BackgroundWork::Terminal(super::BackgroundTerminal::new("term_003")),
4785            super::BackgroundWork::ToolCall(super::BackgroundToolCall::new("call_012")),
4786        ]));
4787        let wire = json!({
4788            "state": "idle",
4789            "background": [
4790                { "type": "terminal", "terminalId": "term_003" },
4791                { "type": "tool_call", "toolCallId": "call_012" }
4792            ]
4793        });
4794        assert_eq!(serde_json::to_value(&idle).unwrap(), wire);
4795        assert_eq!(
4796            serde_json::from_value::<super::StateUpdate>(wire).unwrap(),
4797            idle
4798        );
4799
4800        assert_eq!(idle.background().map(<[_]>::len), Some(2));
4801
4802        let empty = super::RunningStateUpdate::new().background(vec![]);
4803        assert_eq!(
4804            serde_json::to_value(&empty).unwrap(),
4805            json!({ "background": [] })
4806        );
4807        assert_eq!(
4808            super::StateUpdate::Running(empty).background(),
4809            Some(&[][..])
4810        );
4811        assert_eq!(
4812            super::StateUpdate::RequiresAction(super::RequiresActionStateUpdate::new())
4813                .background(),
4814            None
4815        );
4816        let custom: super::StateUpdate = serde_json::from_value(json!({
4817            "state": "_waiting",
4818            "background": [{ "type": "terminal", "terminalId": "term_003" }]
4819        }))
4820        .unwrap();
4821        assert_eq!(custom.background(), None);
4822    }
4823
4824    #[test]
4825    fn background_list_keeps_unknown_items_and_drops_malformed_lists() {
4826        use serde_json::json;
4827        let parsed: super::RunningStateUpdate = serde_json::from_value(json!({
4828            "background": [{ "type": "_cron", "schedule": "* * * * *" }]
4829        }))
4830        .unwrap();
4831        let Some([super::BackgroundWork::Other(other)]) = parsed.background.as_deref() else {
4832            panic!("expected one unknown item: {parsed:?}");
4833        };
4834        assert_eq!(other.kind, "_cron");
4835        assert_eq!(other.fields["schedule"], json!("* * * * *"));
4836
4837        for background in [
4838            json!(null),
4839            json!("oops"),
4840            json!([{ "type": "terminal" }]),
4841            json!([{ "type": "tool_call", "toolCallId": "call_1" }, { "type": "terminal", "terminalId": 7 }]),
4842        ] {
4843            let parsed: super::IdleStateUpdate =
4844                serde_json::from_value(json!({ "background": background })).unwrap();
4845            assert_eq!(parsed.background, None, "{background}");
4846        }
4847    }
4848
4849    #[test]
4850    fn replacement_lists_reject_non_arrays_instead_of_clearing() {
4851        use serde_json::json;
4852        for (update, key) in [
4853            ("config_option_update", "configOptions"),
4854            ("available_commands_update", "availableCommands"),
4855        ] {
4856            let empty = json!({ "sessionUpdate": update, key: [] });
4857            serde_json::from_value::<super::SessionUpdate>(empty).unwrap();
4858            for bad in [json!("oops"), json!(null), json!({})] {
4859                let wire = json!({ "sessionUpdate": update, key: bad });
4860                assert!(
4861                    serde_json::from_value::<super::SessionUpdate>(wire).is_err(),
4862                    "{update} {bad}"
4863                );
4864            }
4865        }
4866        let plan = |entries: serde_json::Value| {
4867            json!({ "sessionUpdate": "plan_update",
4868                "plan": { "type": "items", "planId": "p", "entries": entries } })
4869        };
4870        serde_json::from_value::<super::SessionUpdate>(plan(json!([]))).unwrap();
4871        assert!(serde_json::from_value::<super::SessionUpdate>(plan(json!("oops"))).is_err());
4872        // Invalid items are still skipped.
4873        let skipped =
4874            plan(json!([42, { "content": "a", "priority": "high", "status": "pending" }]));
4875        let super::SessionUpdate::PlanUpdate(update) =
4876            serde_json::from_value::<super::SessionUpdate>(skipped).unwrap()
4877        else {
4878            panic!("expected plan_update");
4879        };
4880        let crate::v2::PlanUpdateContent::Items(items) = update.plan else {
4881            panic!("expected items");
4882        };
4883        assert_eq!(items.entries.len(), 1);
4884    }
4885
4886    #[test]
4887    fn other_available_command_preserves_meta_verbatim() {
4888        for meta in [serde_json::json!({ "k": 1 }), serde_json::json!("bad")] {
4889            let wire = serde_json::json!({ "type": "_custom", "name": "c",
4890                "description": "d", "_meta": meta, "extra": true });
4891            let command: super::AvailableCommand = serde_json::from_value(wire.clone()).unwrap();
4892            assert_eq!(command.meta(), meta.as_object());
4893            assert_eq!(serde_json::to_value(&command).unwrap(), wire);
4894        }
4895    }
4896
4897    #[test]
4898    fn cancelled_permission_outcome_wire_format() {
4899        let outcome: RequestPermissionOutcome =
4900            serde_json::from_value(serde_json::json!({ "outcome": "cancelled" })).unwrap();
4901        assert_eq!(outcome, CancelledPermissionOutcome::new().into());
4902        assert_eq!(
4903            serde_json::to_value(&outcome).unwrap(),
4904            serde_json::json!({ "outcome": "cancelled" })
4905        );
4906
4907        let with_meta: RequestPermissionOutcome = CancelledPermissionOutcome::new()
4908            .meta(serde_json::Map::from_iter([(
4909                "k".to_string(),
4910                serde_json::json!(1),
4911            )]))
4912            .into();
4913        let json = serde_json::to_value(&with_meta).unwrap();
4914        assert_eq!(
4915            json,
4916            serde_json::json!({ "outcome": "cancelled", "_meta": { "k": 1 } })
4917        );
4918        assert_eq!(
4919            serde_json::from_value::<RequestPermissionOutcome>(json).unwrap(),
4920            with_meta
4921        );
4922    }
4923
4924    use super::*;
4925
4926    #[test]
4927    fn subagent_update_serializes_as_upsert() {
4928        use serde_json::json;
4929
4930        let announced =
4931            SessionUpdate::SubagentUpdate(SubagentUpdate::new("sess_child_1").capabilities(
4932                SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new()),
4933            ));
4934        let wire = json!({
4935            "sessionUpdate": "subagent_update",
4936            "sessionId": "sess_child_1",
4937            "capabilities": { "cancel": {} }
4938        });
4939        assert_eq!(serde_json::to_value(&announced).unwrap(), wire);
4940        assert_eq!(
4941            serde_json::from_value::<SessionUpdate>(wire).unwrap(),
4942            announced
4943        );
4944
4945        let minimal = SubagentUpdate::new("sess_child_1");
4946        assert_eq!(
4947            serde_json::to_value(&minimal).unwrap(),
4948            json!({
4949                "sessionId": "sess_child_1"
4950            })
4951        );
4952        assert!(minimal.capabilities.is_undefined());
4953        assert!(minimal.state.is_undefined());
4954        assert!(minimal.meta.is_undefined());
4955
4956        // Patch semantics distinguish omitted fields from explicit nulls.
4957        let cleared_wire = json!({
4958            "sessionId": "sess_child_1",
4959            "capabilities": null,
4960            "state": null,
4961            "_meta": null
4962        });
4963        let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
4964        assert!(cleared.capabilities.is_null());
4965        assert!(cleared.state.is_null());
4966        assert!(cleared.meta.is_null());
4967        assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
4968
4969        let revoked: SubagentUpdate = serde_json::from_value(json!({
4970            "sessionId": "sess_child_1",
4971            "capabilities": {}
4972        }))
4973        .unwrap();
4974        assert_eq!(
4975            revoked.capabilities,
4976            MaybeUndefined::Value(SubagentSessionCapabilities::new())
4977        );
4978        assert!(
4979            matches!(revoked.capabilities, MaybeUndefined::Value(ref child) if child.cancel.is_none())
4980        );
4981
4982        assert!(
4983            serde_json::from_value::<SessionUpdate>(json!({
4984                "sessionUpdate": "subagent_update"
4985            }))
4986            .is_err()
4987        );
4988    }
4989
4990    #[test]
4991    fn subagent_cancel_capability_is_optional_object() {
4992        use serde_json::json;
4993
4994        for wire in [
4995            json!({}),
4996            json!({"cancel": null}),
4997            json!({"cancel": true}),
4998            json!({"cancel": false}),
4999        ] {
5000            let child: SubagentSessionCapabilities = serde_json::from_value(wire).unwrap();
5001            assert!(child.cancel.is_none());
5002            assert_eq!(serde_json::to_value(child).unwrap(), json!({}));
5003        }
5004        let enabled = SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new());
5005        assert_eq!(
5006            serde_json::to_value(&enabled).unwrap(),
5007            json!({"cancel": {}})
5008        );
5009        assert_eq!(
5010            serde_json::from_value::<SubagentSessionCapabilities>(json!({"cancel": {}})).unwrap(),
5011            enabled
5012        );
5013        let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
5014        let with_meta =
5015            SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new().meta(meta));
5016        let wire = json!({"cancel": {"_meta": {"source": "worker"}}});
5017        assert_eq!(serde_json::to_value(&with_meta).unwrap(), wire);
5018        assert_eq!(
5019            serde_json::from_value::<SubagentSessionCapabilities>(wire).unwrap(),
5020            with_meta
5021        );
5022        assert!(enabled.cancel.is_some());
5023        assert!(enabled.cancel(None).cancel.is_none());
5024        let removed = SubagentUpdate::new("child").capabilities(SubagentSessionCapabilities::new());
5025        assert_eq!(
5026            serde_json::to_value(removed).unwrap(),
5027            json!({"sessionId": "child", "capabilities": {}})
5028        );
5029    }
5030
5031    #[test]
5032    fn subagent_display_metadata_uses_patch_semantics() {
5033        use serde_json::json;
5034
5035        let update = SubagentUpdate::new("child")
5036            .title("Test investigator".to_string())
5037            .description("Investigates platform-specific test failures.".to_string());
5038        let wire = json!({
5039            "sessionId": "child",
5040            "title": "Test investigator",
5041            "description": "Investigates platform-specific test failures."
5042        });
5043        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5044        assert_eq!(
5045            serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5046            update
5047        );
5048
5049        let minimal = SubagentUpdate::new("child");
5050        assert!(minimal.title.is_undefined());
5051        assert!(minimal.description.is_undefined());
5052        assert_eq!(
5053            serde_json::to_value(&minimal).unwrap(),
5054            json!({"sessionId": "child"})
5055        );
5056        let cleared_wire = json!({
5057            "sessionId": "child", "title": null, "description": null
5058        });
5059        let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5060        assert!(cleared.title.is_null());
5061        assert!(cleared.description.is_null());
5062        assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5063
5064        let title_only: SubagentUpdate = serde_json::from_value(json!({
5065            "sessionId": "child", "title": "Updated title"
5066        }))
5067        .unwrap();
5068        assert_eq!(
5069            title_only.title,
5070            MaybeUndefined::Value("Updated title".to_string())
5071        );
5072        assert!(title_only.description.is_undefined());
5073        let malformed: SubagentUpdate = serde_json::from_value(json!({
5074            "sessionId": "child", "title": false, "description": false
5075        }))
5076        .unwrap();
5077        assert_eq!(malformed, minimal);
5078    }
5079
5080    #[test]
5081    fn subagent_directories_use_strict_patch_semantics() {
5082        use serde_json::json;
5083
5084        let update = SubagentUpdate::new("child")
5085            .cwd("/home/user/project/.worktrees/investigator")
5086            .additional_directories(vec![]);
5087        let wire = json!({
5088            "sessionId": "child",
5089            "cwd": "/home/user/project/.worktrees/investigator",
5090            "additionalDirectories": []
5091        });
5092        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5093        assert_eq!(
5094            serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5095            update
5096        );
5097
5098        let inherited: SubagentUpdate =
5099            serde_json::from_value(json!({"sessionId": "child"})).unwrap();
5100        assert!(inherited.cwd.is_undefined());
5101        assert!(inherited.additional_directories.is_undefined());
5102
5103        let cleared_wire = json!({
5104            "sessionId": "child", "cwd": null, "additionalDirectories": null
5105        });
5106        let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5107        assert!(cleared.cwd.is_null());
5108        assert!(cleared.additional_directories.is_null());
5109        assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5110
5111        for malformed in [
5112            json!({"sessionId": "child", "cwd": false}),
5113            json!({"sessionId": "child", "additionalDirectories": "/tmp/wt"}),
5114            json!({"sessionId": "child", "additionalDirectories": ["/tmp/wt", false]}),
5115        ] {
5116            assert!(
5117                serde_json::from_value::<SubagentUpdate>(malformed.clone()).is_err(),
5118                "{malformed}"
5119            );
5120        }
5121    }
5122
5123    #[test]
5124    fn subagent_notification_keeps_parent_and_child_ids_nested() {
5125        use serde_json::json;
5126
5127        let notification = UpdateSessionNotification::new(
5128            "parent",
5129            SessionUpdate::SubagentUpdate(SubagentUpdate::new("child")),
5130        );
5131        let wire = json!({
5132            "sessionId": "parent",
5133            "update": {
5134                "sessionUpdate": "subagent_update",
5135                "sessionId": "child"
5136            }
5137        });
5138        assert_eq!(serde_json::to_value(&notification).unwrap(), wire);
5139        assert_eq!(
5140            serde_json::from_value::<UpdateSessionNotification>(wire).unwrap(),
5141            notification
5142        );
5143        for malformed in [
5144            json!({"sessionId": "parent", "update": {"sessionUpdate": "subagent_update"}}),
5145            json!({"update": {"sessionUpdate": "subagent_update", "sessionId": "child"}}),
5146        ] {
5147            assert!(serde_json::from_value::<UpdateSessionNotification>(malformed).is_err());
5148        }
5149    }
5150
5151    #[test]
5152    fn subagent_mirrors_normal_child_state_notifications() {
5153        use serde_json::json;
5154
5155        let association = SubagentUpdate::new("sess_child");
5156        for state in [
5157            StateUpdate::Running(RunningStateUpdate::new()),
5158            StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5159            StateUpdate::Unknown(UnknownStateUpdate::new()),
5160            StateUpdate::Running(RunningStateUpdate::new()),
5161            StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::EndTurn)),
5162            StateUpdate::Running(RunningStateUpdate::new()),
5163            StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::Cancelled)),
5164        ] {
5165            let child_notification = UpdateSessionNotification::new(
5166                association.session_id.clone(),
5167                SessionUpdate::StateUpdate(state.clone()),
5168            );
5169            let parent_notification = UpdateSessionNotification::new(
5170                "sess_parent",
5171                SessionUpdate::SubagentUpdate(association.clone().state(state)),
5172            );
5173            let child_wire = serde_json::to_value(&child_notification).unwrap();
5174            let parent_wire = serde_json::to_value(&parent_notification).unwrap();
5175            assert_eq!(child_wire["sessionId"], json!("sess_child"));
5176            assert_eq!(child_wire["update"]["sessionUpdate"], json!("state_update"));
5177            assert_eq!(parent_wire["sessionId"], json!("sess_parent"));
5178            assert_eq!(parent_wire["update"]["sessionId"], json!("sess_child"));
5179            let mut child_snapshot = child_wire["update"].clone();
5180            child_snapshot
5181                .as_object_mut()
5182                .unwrap()
5183                .remove("sessionUpdate");
5184            assert_eq!(parent_wire["update"]["state"], child_snapshot);
5185            assert_eq!(
5186                serde_json::from_value::<UpdateSessionNotification>(child_wire).unwrap(),
5187                child_notification
5188            );
5189            assert_eq!(
5190                serde_json::from_value::<UpdateSessionNotification>(parent_wire).unwrap(),
5191                parent_notification
5192            );
5193        }
5194    }
5195
5196    #[test]
5197    fn subagent_state_uses_whole_snapshot_patch_semantics() {
5198        use serde_json::json;
5199
5200        let minimal = SubagentUpdate::new("child");
5201        assert!(minimal.state.is_undefined());
5202        assert_eq!(
5203            serde_json::to_value(&minimal).unwrap(),
5204            json!({"sessionId": "child"})
5205        );
5206
5207        let cleared = minimal.clone().state(None::<StateUpdate>);
5208        assert!(cleared.state.is_null());
5209        assert_eq!(
5210            serde_json::to_value(&cleared).unwrap(),
5211            json!({"sessionId": "child", "state": null})
5212        );
5213        assert_eq!(
5214            serde_json::from_value::<SubagentUpdate>(json!({"sessionId": "child", "state": null}))
5215                .unwrap(),
5216            cleared
5217        );
5218
5219        for snapshot in [
5220            json!({"state": "running", "_meta": {"source": "worker"}}),
5221            json!({"state": "idle", "stopReason": "end_turn"}),
5222            json!({"state": "requires_action"}),
5223            json!({"state": "unknown"}),
5224            json!({"state": "_custom", "detail": {"phase": 2}}),
5225        ] {
5226            let state: StateUpdate = serde_json::from_value(snapshot.clone()).unwrap();
5227            let update = minimal.clone().state(state.clone());
5228            let wire = json!({"sessionId": "child", "state": snapshot});
5229            assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5230            assert_eq!(
5231                serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5232                update
5233            );
5234            assert_eq!(update.state, MaybeUndefined::Value(state));
5235        }
5236
5237        // Each concrete value is the entire replacement snapshot, not a merge
5238        // with a previous state's stop reason or metadata.
5239        let idle = SubagentUpdate::new("child").state(StateUpdate::Idle(
5240            IdleStateUpdate::new().stop_reason(StopReason::Cancelled),
5241        ));
5242        let running = idle.state(StateUpdate::Running(RunningStateUpdate::new()));
5243        assert_eq!(
5244            serde_json::to_value(running).unwrap(),
5245            json!({"sessionId": "child", "state": {"state": "running"}})
5246        );
5247        for invalid in [json!(false), json!(42), json!({}), json!({"state": 7})] {
5248            let parsed: SubagentUpdate =
5249                serde_json::from_value(json!({"sessionId": "child", "state": invalid})).unwrap();
5250            assert_eq!(parsed, minimal);
5251        }
5252    }
5253
5254    #[test]
5255    fn unknown_activity_is_a_known_state_update() {
5256        use serde_json::json;
5257
5258        let update = SessionUpdate::StateUpdate(StateUpdate::Unknown(
5259            UnknownStateUpdate::new().meta(
5260                [("source".into(), json!("worker"))]
5261                    .into_iter()
5262                    .collect::<Meta>(),
5263            ),
5264        ));
5265        let wire = json!({
5266            "sessionUpdate": "state_update",
5267            "state": "unknown",
5268            "_meta": { "source": "worker" }
5269        });
5270        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5271        assert_eq!(
5272            serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5273            update
5274        );
5275
5276        for meta in [json!(null), json!(false)] {
5277            let state: StateUpdate = serde_json::from_value(json!({
5278                "state": "unknown",
5279                "_meta": meta
5280            }))
5281            .unwrap();
5282            assert_eq!(state, StateUpdate::Unknown(UnknownStateUpdate::new()));
5283            assert_eq!(
5284                serde_json::to_value(state).unwrap(),
5285                json!({"state": "unknown"})
5286            );
5287        }
5288        assert!(serde_json::from_value::<OtherStateUpdate>(json!({"state": "unknown"})).is_err());
5289    }
5290
5291    #[cfg(feature = "schemars")]
5292    #[test]
5293    fn subagent_schema_carries_optional_nullable_state_snapshot() {
5294        use serde_json::json;
5295
5296        let schema = serde_json::to_value(schemars::schema_for!(SubagentUpdate)).unwrap();
5297        let properties = schema["properties"].as_object().unwrap();
5298        assert!(properties.contains_key("sessionId"));
5299        assert!(properties.contains_key("title"));
5300        assert!(properties.contains_key("description"));
5301        assert!(properties.contains_key("capabilities"));
5302        assert!(properties.contains_key("state"));
5303        assert!(properties.contains_key("_meta"));
5304        assert!(!properties.contains_key("name"));
5305        assert!(!properties.contains_key("task"));
5306        assert_eq!(schema["required"], json!(["sessionId"]));
5307        assert_eq!(
5308            properties["state"]["x-deserialize-default-on-error"],
5309            json!(true)
5310        );
5311        let state_variants = properties["state"]["anyOf"].as_array().unwrap();
5312        assert!(state_variants.contains(&json!({"type": "null"})));
5313        assert!(
5314            state_variants
5315                .iter()
5316                .any(|variant| variant["$ref"] == "#/$defs/StateUpdate")
5317        );
5318        let child =
5319            serde_json::to_value(schemars::schema_for!(SubagentSessionCapabilities)).unwrap();
5320        let variants = child["properties"]["cancel"]["anyOf"]
5321            .as_array()
5322            .expect("cancel must allow the capability object or null");
5323        assert!(variants.contains(&json!({"type": "null"})));
5324        assert!(
5325            variants
5326                .iter()
5327                .any(|variant| variant["type"] == "object" || variant.get("$ref").is_some())
5328        );
5329        assert!(!variants.iter().any(|variant| variant["type"] == "boolean"));
5330        let cancel =
5331            serde_json::to_value(schemars::schema_for!(SessionCancelCapabilities)).unwrap();
5332        assert_eq!(cancel["type"], "object");
5333        assert!(
5334            !child["required"]
5335                .as_array()
5336                .is_some_and(|required| required.contains(&json!("cancel")))
5337        );
5338    }
5339
5340    #[test]
5341    fn notice_preserves_wire_shape_nullable_fields_and_open_severity() {
5342        use serde_json::json;
5343
5344        let mut meta = Meta::new();
5345        meta.insert("source".into(), json!("fallback"));
5346        let v2_notice = SessionUpdate::Notice(
5347            Notice::new(NoticeSeverity::Error, "Provider degraded")
5348                .description("Requests may take longer than usual.")
5349                .meta(meta.clone()),
5350        );
5351        let expected = json!({
5352            "sessionUpdate": "notice",
5353            "severity": "error",
5354            "title": "Provider degraded",
5355            "description": "Requests may take longer than usual.",
5356            "_meta": { "source": "fallback" }
5357        });
5358        assert_eq!(serde_json::to_value(&v2_notice).unwrap(), expected);
5359
5360        let v1_notice = crate::v1::SessionUpdate::Notice(
5361            crate::v1::Notice::new(crate::v1::NoticeSeverity::Error, "Provider degraded")
5362                .description("Requests may take longer than usual.")
5363                .meta(meta),
5364        );
5365        assert_eq!(
5366            serde_json::to_value(v2_notice).unwrap(),
5367            serde_json::to_value(v1_notice).unwrap()
5368        );
5369
5370        let SessionUpdate::Notice(notice) = serde_json::from_value(json!({
5371            "sessionUpdate": "notice",
5372            "severity": "critical",
5373            "title": "Provider degraded",
5374            "description": null,
5375            "_meta": null
5376        }))
5377        .unwrap() else {
5378            panic!("expected notice");
5379        };
5380
5381        assert_eq!(
5382            notice.severity,
5383            NoticeSeverity::Other("critical".to_string())
5384        );
5385        assert_eq!(notice.description, None);
5386        assert_eq!(notice.meta, None);
5387        assert_eq!(
5388            serde_json::to_value(SessionUpdate::Notice(notice)).unwrap(),
5389            json!({
5390                "sessionUpdate": "notice",
5391                "severity": "critical",
5392                "title": "Provider degraded"
5393            })
5394        );
5395    }
5396
5397    #[test]
5398    fn malformed_known_notice_is_not_hidden_as_unknown() {
5399        use serde_json::json;
5400
5401        for malformed in [
5402            json!({
5403                "sessionUpdate": "notice",
5404                "severity": "warning",
5405                "title": 42
5406            }),
5407            json!({
5408                "sessionUpdate": "notice",
5409                "severity": 42,
5410                "title": "MCP server unavailable"
5411            }),
5412            json!({
5413                "sessionUpdate": "notice",
5414                "severity": "warning"
5415            }),
5416            json!({
5417                "sessionUpdate": "notice",
5418                "severity": "warning",
5419                "title": null
5420            }),
5421            json!({
5422                "sessionUpdate": "notice",
5423                "title": "MCP server unavailable"
5424            }),
5425            json!({
5426                "sessionUpdate": "notice",
5427                "severity": null,
5428                "title": "MCP server unavailable"
5429            }),
5430        ] {
5431            assert!(serde_json::from_str::<SessionUpdate>(&malformed.to_string()).is_err());
5432            assert!(serde_json::from_value::<SessionUpdate>(malformed).is_err());
5433        }
5434    }
5435
5436    #[test]
5437    fn notice_tolerates_invalid_optional_display_fields_and_custom_severity() {
5438        use serde_json::json;
5439
5440        let wire = json!({
5441            "sessionUpdate": "notice",
5442            "severity": "_custom",
5443            "title": "Provider degraded",
5444            "description": 42,
5445            "_meta": false
5446        });
5447        let SessionUpdate::Notice(notice) = serde_json::from_value(wire.clone()).unwrap() else {
5448            panic!("expected notice");
5449        };
5450        assert_eq!(
5451            serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
5452            SessionUpdate::Notice(notice.clone())
5453        );
5454        assert_eq!(notice.severity, NoticeSeverity::Other("_custom".into()));
5455        assert_eq!(notice.description, None);
5456        assert_eq!(notice.meta, None);
5457        assert_eq!(
5458            serde_json::to_value(notice).unwrap(),
5459            json!({"severity": "_custom", "title": "Provider degraded"})
5460        );
5461    }
5462
5463    #[cfg(feature = "schemars")]
5464    #[test]
5465    fn notice_schema_preserves_required_fields_and_excludes_unknown_fallback() {
5466        use serde_json::json;
5467
5468        let schema = serde_json::to_value(schemars::schema_for!(Notice)).unwrap();
5469        assert_eq!(schema["required"], json!(["severity", "title"]));
5470        assert_eq!(schema["properties"]["title"]["minLength"], 1);
5471        for field in ["description", "_meta"] {
5472            assert!(
5473                schema["properties"][field]["type"]
5474                    .as_array()
5475                    .unwrap()
5476                    .contains(&json!("null"))
5477            );
5478        }
5479        let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
5480        assert!(
5481            fallback["not"]["anyOf"]
5482                .as_array()
5483                .unwrap()
5484                .iter()
5485                .any(|variant| variant["properties"]["sessionUpdate"]["const"] == "notice")
5486        );
5487    }
5488
5489    #[test]
5490    fn replay_complete_round_trips_with_and_without_meta() {
5491        use serde_json::json;
5492
5493        let bare = json!({ "sessionUpdate": "replay_complete" });
5494        assert_eq!(
5495            serde_json::to_value(SessionUpdate::ReplayComplete(ReplayComplete::new())).unwrap(),
5496            bare
5497        );
5498        assert_eq!(
5499            serde_json::from_value::<SessionUpdate>(bare).unwrap(),
5500            SessionUpdate::ReplayComplete(ReplayComplete::new())
5501        );
5502
5503        let mut meta = Meta::new();
5504        meta.insert("source".into(), json!("transcript"));
5505        let with_meta = json!({
5506            "sessionUpdate": "replay_complete",
5507            "_meta": { "source": "transcript" }
5508        });
5509        let update = SessionUpdate::ReplayComplete(ReplayComplete::new().meta(meta));
5510        assert_eq!(serde_json::to_value(&update).unwrap(), with_meta);
5511        assert_eq!(
5512            serde_json::from_value::<SessionUpdate>(with_meta).unwrap(),
5513            update
5514        );
5515    }
5516
5517    #[test]
5518    fn replay_complete_is_never_preserved_as_an_unknown_update() {
5519        use serde_json::json;
5520
5521        // `_meta` is the only field, and a `null` or malformed value means no
5522        // metadata. The marker must still parse as the known variant so a
5523        // Client does not miss the end of the replay.
5524        for wire in [
5525            json!({ "sessionUpdate": "replay_complete", "_meta": null }),
5526            json!({ "sessionUpdate": "replay_complete", "_meta": false }),
5527            json!({ "sessionUpdate": "replay_complete", "futureField": 1 }),
5528        ] {
5529            assert_eq!(
5530                serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
5531                SessionUpdate::ReplayComplete(ReplayComplete::new())
5532            );
5533            assert_eq!(
5534                serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5535                SessionUpdate::ReplayComplete(ReplayComplete::new())
5536            );
5537        }
5538
5539        assert!(
5540            serde_json::from_value::<OtherSessionUpdate>(
5541                json!({ "sessionUpdate": "replay_complete" })
5542            )
5543            .is_err()
5544        );
5545    }
5546
5547    #[cfg(feature = "schemars")]
5548    #[test]
5549    fn replay_complete_schema_has_only_optional_meta_and_excludes_unknown_fallback() {
5550        use serde_json::json;
5551
5552        let schema = serde_json::to_value(schemars::schema_for!(ReplayComplete)).unwrap();
5553        assert!(schema.get("required").is_none());
5554        assert_eq!(
5555            schema["properties"]
5556                .as_object()
5557                .unwrap()
5558                .keys()
5559                .collect::<Vec<_>>(),
5560            ["_meta"]
5561        );
5562        assert_eq!(
5563            schema["properties"]["_meta"]["type"],
5564            json!(["object", "null"])
5565        );
5566        let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
5567        assert!(
5568            fallback["not"]["anyOf"]
5569                .as_array()
5570                .unwrap()
5571                .iter()
5572                .any(|variant| variant["properties"]["sessionUpdate"]["const"]
5573                    == "replay_complete")
5574        );
5575    }
5576
5577    #[cfg(feature = "unstable_prompt_suggestions")]
5578    #[test]
5579    fn prompt_suggestions_update_round_trips_prompt_content_and_meta() {
5580        use super::{ContentBlock, Meta, PromptSuggestion, PromptSuggestionsUpdate, SessionUpdate};
5581        use crate::v2::{ResourceLink, TextContent};
5582        use serde_json::json;
5583
5584        let mut meta = Meta::new();
5585        meta.insert("rank".into(), json!(1));
5586        let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
5587            PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(
5588                "Run the test suite and fix what breaks",
5589            ))])
5590            .meta(meta),
5591            PromptSuggestion::new(vec![
5592                ContentBlock::Text(TextContent::new("Add tests for ")),
5593                ContentBlock::ResourceLink(ResourceLink::new(
5594                    "parser.rs",
5595                    "file:///home/user/project/src/parser.rs",
5596                )),
5597            ]),
5598        ]));
5599        let wire = json!({
5600            "sessionUpdate": "prompt_suggestions_update",
5601            "suggestions": [
5602                {
5603                    "prompt": [
5604                        { "type": "text", "text": "Run the test suite and fix what breaks" }
5605                    ],
5606                    "_meta": { "rank": 1 }
5607                },
5608                {
5609                    "prompt": [
5610                        { "type": "text", "text": "Add tests for " },
5611                        {
5612                            "type": "resource_link",
5613                            "name": "parser.rs",
5614                            "uri": "file:///home/user/project/src/parser.rs"
5615                        }
5616                    ]
5617                }
5618            ]
5619        });
5620        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5621        assert_eq!(
5622            serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5623            update
5624        );
5625    }
5626
5627    #[cfg(feature = "unstable_prompt_suggestions")]
5628    #[test]
5629    fn prompt_suggestions_update_with_an_empty_list_withdraws_suggestions() {
5630        use super::{PromptSuggestionsUpdate, SessionUpdate};
5631        use serde_json::json;
5632
5633        let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![]));
5634        let wire = json!({
5635            "sessionUpdate": "prompt_suggestions_update",
5636            "suggestions": []
5637        });
5638        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5639        assert_eq!(
5640            serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5641            update
5642        );
5643    }
5644
5645    #[cfg(feature = "unstable_prompt_suggestions")]
5646    #[test]
5647    fn prompt_suggestions_update_is_never_preserved_as_an_unknown_update() {
5648        use super::{OtherSessionUpdate, SessionUpdate};
5649        use serde_json::json;
5650
5651        // The list is required and must be an array. A malformed update is an
5652        // error. It must not parse as a custom or future update.
5653        for wire in [
5654            json!({ "sessionUpdate": "prompt_suggestions_update" }),
5655            json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": null }),
5656            json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": "none" }),
5657            json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": { "prompt": [] } }),
5658        ] {
5659            assert!(serde_json::from_str::<SessionUpdate>(&wire.to_string()).is_err());
5660            assert!(serde_json::from_value::<SessionUpdate>(wire).is_err());
5661        }
5662
5663        assert!(
5664            serde_json::from_value::<OtherSessionUpdate>(json!({
5665                "sessionUpdate": "prompt_suggestions_update",
5666                "suggestions": []
5667            }))
5668            .is_err()
5669        );
5670    }
5671
5672    #[cfg(feature = "unstable_prompt_suggestions")]
5673    #[test]
5674    fn prompt_suggestions_update_skips_whole_suggestions_it_cannot_parse() {
5675        use super::{ContentBlock, PromptSuggestion, PromptSuggestionsUpdate, SessionUpdate};
5676        use crate::v2::TextContent;
5677        use serde_json::json;
5678
5679        let text =
5680            |text: &str| PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(text))]);
5681
5682        // One bad block fails the whole suggestion. Dropping only that block
5683        // would change what the prompt asks for.
5684        let update: SessionUpdate = serde_json::from_value(json!({
5685            "sessionUpdate": "prompt_suggestions_update",
5686            "suggestions": [
5687                { "prompt": [{ "type": "text", "text": "Keep the first" }] },
5688                { "text": "A suggestion without a prompt" },
5689                { "prompt": "Not a list" },
5690                { "prompt": [{ "type": "text", "text": "Open " }, { "type": "text" }] },
5691                "not an object",
5692                { "prompt": [{ "type": "text", "text": "Keep the last" }], "_meta": false }
5693            ]
5694        }))
5695        .unwrap();
5696
5697        assert_eq!(
5698            update,
5699            SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
5700                text("Keep the first"),
5701                text("Keep the last"),
5702            ]))
5703        );
5704    }
5705
5706    #[cfg(feature = "unstable_prompt_suggestions")]
5707    #[test]
5708    fn prompt_suggestions_update_preserves_custom_and_future_content_blocks() {
5709        use super::{ContentBlock, SessionUpdate};
5710        use serde_json::json;
5711
5712        // A content block type the Client does not know still parses, so the
5713        // Client can see it and skip the suggestion.
5714        let wire = json!({
5715            "sessionUpdate": "prompt_suggestions_update",
5716            "suggestions": [
5717                { "prompt": [{ "type": "_hologram", "data": "AAAA" }] }
5718            ]
5719        });
5720        let update: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
5721        let SessionUpdate::PromptSuggestionsUpdate(suggestions) = &update else {
5722            panic!("expected prompt_suggestions_update, got {update:?}");
5723        };
5724        assert!(matches!(
5725            suggestions.suggestions[0].prompt.as_slice(),
5726            [ContentBlock::Other(_)]
5727        ));
5728        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5729    }
5730
5731    #[cfg(feature = "unstable_prompt_suggestions")]
5732    #[test]
5733    fn prompt_suggestions_capability_advertises_support_and_content_types() {
5734        use super::{
5735            ClientCapabilities, ClientSessionCapabilities, PromptSuggestionsAudioCapabilities,
5736            PromptSuggestionsCapabilities, PromptSuggestionsEmbeddedContextCapabilities,
5737            PromptSuggestionsImageCapabilities,
5738        };
5739        use serde_json::json;
5740
5741        let capabilities = ClientCapabilities::new().session(
5742            ClientSessionCapabilities::new()
5743                .prompt_suggestions(PromptSuggestionsCapabilities::new()),
5744        );
5745        let value = serde_json::to_value(&capabilities).unwrap();
5746        assert_eq!(value, json!({ "session": { "promptSuggestions": {} } }));
5747        assert_eq!(
5748            serde_json::from_value::<ClientCapabilities>(value).unwrap(),
5749            capabilities
5750        );
5751
5752        let content_types = PromptSuggestionsCapabilities::new()
5753            .image(PromptSuggestionsImageCapabilities::new())
5754            .audio(PromptSuggestionsAudioCapabilities::new())
5755            .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new());
5756        let wire = json!({ "image": {}, "audio": {}, "embeddedContext": {} });
5757        assert_eq!(serde_json::to_value(&content_types).unwrap(), wire);
5758        assert_eq!(
5759            serde_json::from_value::<PromptSuggestionsCapabilities>(wire).unwrap(),
5760            content_types
5761        );
5762
5763        // The `session` object only groups capabilities. `{}` advertises nothing.
5764        for unsupported in [
5765            json!({}),
5766            json!({ "session": null }),
5767            json!({ "session": {} }),
5768            json!({ "session": { "promptSuggestions": null } }),
5769            json!({ "session": { "promptSuggestions": false } }),
5770            json!({ "session": { "promptSuggestions": true } }),
5771            json!({ "session": { "promptSuggestions": "supported" } }),
5772        ] {
5773            let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
5774            assert!(
5775                capabilities
5776                    .session
5777                    .and_then(|session| session.prompt_suggestions)
5778                    .is_none()
5779            );
5780        }
5781
5782        // A content type is advertised only by an object. The other types and
5783        // the capability itself are unaffected by a malformed one.
5784        assert_eq!(
5785            serde_json::from_value::<PromptSuggestionsCapabilities>(json!({
5786                "image": true,
5787                "audio": null,
5788                "embeddedContext": {}
5789            }))
5790            .unwrap(),
5791            PromptSuggestionsCapabilities::new()
5792                .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new())
5793        );
5794    }
5795
5796    #[cfg(all(feature = "schemars", feature = "unstable_prompt_suggestions"))]
5797    #[test]
5798    fn prompt_suggestions_schema_requires_the_list_and_excludes_unknown_fallback() {
5799        use super::{
5800            ClientCapabilities, ClientSessionCapabilities, OtherSessionUpdate, PromptSuggestion,
5801            PromptSuggestionsCapabilities, PromptSuggestionsUpdate,
5802        };
5803        use serde_json::json;
5804
5805        let update = serde_json::to_value(schemars::schema_for!(PromptSuggestionsUpdate)).unwrap();
5806        assert_eq!(update["required"], json!(["suggestions"]));
5807        assert_eq!(update["properties"]["suggestions"]["type"], "array");
5808
5809        let suggestion = serde_json::to_value(schemars::schema_for!(PromptSuggestion)).unwrap();
5810        assert_eq!(suggestion["required"], json!(["prompt"]));
5811        assert_eq!(suggestion["properties"]["prompt"]["type"], "array");
5812        assert_eq!(suggestion["properties"]["prompt"]["minItems"], 1);
5813
5814        let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
5815        assert!(
5816            fallback["not"]["anyOf"]
5817                .as_array()
5818                .unwrap()
5819                .iter()
5820                .any(|variant| variant["properties"]["sessionUpdate"]["const"]
5821                    == "prompt_suggestions_update")
5822        );
5823
5824        for (schema, field) in [
5825            (
5826                serde_json::to_value(schemars::schema_for!(ClientCapabilities)).unwrap(),
5827                "session",
5828            ),
5829            (
5830                serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap(),
5831                "promptSuggestions",
5832            ),
5833        ] {
5834            assert!(
5835                schema["properties"][field]["anyOf"]
5836                    .as_array()
5837                    .unwrap()
5838                    .contains(&json!({"type": "null"}))
5839            );
5840            assert!(
5841                !schema["required"]
5842                    .as_array()
5843                    .is_some_and(|required| required.contains(&json!(field)))
5844            );
5845        }
5846
5847        let content_types =
5848            serde_json::to_value(schemars::schema_for!(PromptSuggestionsCapabilities)).unwrap();
5849        assert!(content_types.get("required").is_none());
5850        for field in ["image", "audio", "embeddedContext"] {
5851            assert!(
5852                content_types["properties"][field]["anyOf"]
5853                    .as_array()
5854                    .unwrap()
5855                    .contains(&json!({"type": "null"}))
5856            );
5857        }
5858    }
5859
5860    #[test]
5861    fn compaction_updates_preserve_patch_and_open_status_semantics() {
5862        use serde_json::json;
5863
5864        assert_eq!(
5865            serde_json::to_value(SessionUpdate::CompactionUpdate(
5866                CompactionUpdate::new("cmp_001", CompactionStatus::Completed).summary(vec![
5867                    ContentBlock::Text(crate::v2::TextContent::new("retained")),
5868                ]),
5869            ))
5870            .unwrap(),
5871            json!({
5872                "sessionUpdate": "compaction_update",
5873                "compactionId": "cmp_001",
5874                "status": "completed",
5875                "summary": [{ "type": "text", "text": "retained" }]
5876            })
5877        );
5878
5879        let SessionUpdate::CompactionUpdate(update) = serde_json::from_value(json!({
5880            "sessionUpdate": "compaction_update",
5881            "compactionId": "cmp_001",
5882            "status": "paused",
5883            "summary": null
5884        }))
5885        .unwrap() else {
5886            panic!("expected compaction update");
5887        };
5888        assert_eq!(update.status, CompactionStatus::Other("paused".into()));
5889        assert!(update.summary.is_null());
5890        assert!(update.error.is_undefined());
5891    }
5892
5893    #[test]
5894    fn malformed_known_compaction_update_is_not_hidden_as_unknown() {
5895        use serde_json::json;
5896
5897        assert!(
5898            serde_json::from_value::<SessionUpdate>(json!({
5899                "sessionUpdate": "compaction_update",
5900                "status": "completed"
5901            }))
5902            .is_err()
5903        );
5904        assert!(
5905            serde_json::from_value::<SessionUpdate>(json!({
5906                "sessionUpdate": "compaction_summary_chunk",
5907                "compactionId": "cmp_001"
5908            }))
5909            .is_err()
5910        );
5911    }
5912
5913    #[test]
5914    fn test_elicitation_capability_semantics() {
5915        use serde_json::json;
5916
5917        let unsupported: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
5918        assert!(unsupported.elicitation.is_none());
5919
5920        let null: ClientCapabilities =
5921            serde_json::from_value(json!({ "elicitation": null })).unwrap();
5922        assert!(null.elicitation.is_none());
5923
5924        let malformed: ClientCapabilities =
5925            serde_json::from_value(json!({ "elicitation": false })).unwrap();
5926        assert!(malformed.elicitation.is_none());
5927
5928        let empty: ClientCapabilities =
5929            serde_json::from_value(json!({ "elicitation": {} })).unwrap();
5930        let empty = empty.elicitation.expect("present capability");
5931        assert!(!empty.supports_form());
5932        assert!(!empty.supports_url());
5933
5934        let form_only: ClientCapabilities = serde_json::from_value(json!({
5935            "elicitation": { "form": {} }
5936        }))
5937        .unwrap();
5938        let form_only = form_only.elicitation.expect("advertised capability");
5939        assert!(form_only.supports_form());
5940        assert!(!form_only.supports_url());
5941
5942        let url_only: ClientCapabilities = serde_json::from_value(json!({
5943            "elicitation": { "url": {} }
5944        }))
5945        .unwrap();
5946        let url_only = url_only.elicitation.expect("advertised capability");
5947        assert!(!url_only.supports_form());
5948        assert!(url_only.supports_url());
5949
5950        let both: ClientCapabilities = serde_json::from_value(json!({
5951            "elicitation": { "form": {}, "url": {} }
5952        }))
5953        .unwrap();
5954        let both = both.elicitation.expect("advertised capability");
5955        assert!(both.supports_form());
5956        assert!(both.supports_url());
5957    }
5958
5959    #[test]
5960    fn test_elicitation_method_routing_and_envelopes() {
5961        use serde_json::json;
5962
5963        assert_eq!(CLIENT_METHOD_NAMES.elicitation_create, "elicitation/create");
5964        assert_eq!(
5965            CLIENT_METHOD_NAMES.elicitation_complete,
5966            "elicitation/complete"
5967        );
5968
5969        let request =
5970            AgentRequest::CreateElicitationRequest(Box::new(CreateElicitationRequest::new(
5971                crate::v2::ElicitationFormMode::new(
5972                    crate::v2::ElicitationSessionScope::new("sess_1"),
5973                    crate::v2::ElicitationSchema::new(),
5974                ),
5975                "Choose a value",
5976            )));
5977        assert_eq!(request.method(), "elicitation/create");
5978        let method = Arc::from(request.method());
5979        let request = crate::v2::JsonRpcMessage::wrap(crate::v2::Request {
5980            id: crate::v2::RequestId::Number(7),
5981            method,
5982            params: Some(request),
5983        });
5984        assert_eq!(
5985            serde_json::to_value(request).unwrap(),
5986            json!({
5987                "jsonrpc": "2.0",
5988                "id": 7,
5989                "method": "elicitation/create",
5990                "params": {
5991                    "mode": "form",
5992                    "sessionId": "sess_1",
5993                    "message": "Choose a value",
5994                    "requestedSchema": { "type": "object", "properties": {} }
5995                }
5996            })
5997        );
5998
5999        let notification = AgentNotification::CompleteElicitationNotification(Box::new(
6000            CompleteElicitationNotification::new("elic_1"),
6001        ));
6002        assert_eq!(notification.method(), "elicitation/complete");
6003        let method = Arc::from(notification.method());
6004        let notification = crate::v2::JsonRpcMessage::wrap(crate::v2::Notification {
6005            method,
6006            params: Some(notification),
6007        });
6008        assert_eq!(
6009            serde_json::to_value(notification).unwrap(),
6010            json!({
6011                "jsonrpc": "2.0",
6012                "method": "elicitation/complete",
6013                "params": { "elicitationId": "elic_1" }
6014            })
6015        );
6016    }
6017
6018    #[test]
6019    fn test_client_capabilities_auth_defaults_on_malformed_value() {
6020        use serde_json::json;
6021
6022        let capabilities: ClientCapabilities = serde_json::from_value(json!({
6023            "auth": false
6024        }))
6025        .unwrap();
6026
6027        assert_eq!(capabilities.auth, None);
6028    }
6029
6030    #[test]
6031    fn test_serialization_behavior() {
6032        use serde_json::json;
6033
6034        assert_eq!(
6035            serde_json::from_value::<SessionInfoUpdate>(json!({})).unwrap(),
6036            SessionInfoUpdate {
6037                title: MaybeUndefined::Undefined,
6038                updated_at: MaybeUndefined::Undefined,
6039                meta: MaybeUndefined::Undefined
6040            }
6041        );
6042        assert_eq!(
6043            serde_json::from_value::<SessionInfoUpdate>(json!({"title": null, "updatedAt": null}))
6044                .unwrap(),
6045            SessionInfoUpdate {
6046                title: MaybeUndefined::Null,
6047                updated_at: MaybeUndefined::Null,
6048                meta: MaybeUndefined::Undefined
6049            }
6050        );
6051        assert_eq!(
6052            serde_json::from_value::<SessionInfoUpdate>(
6053                json!({"title": "title", "updatedAt": "timestamp"})
6054            )
6055            .unwrap(),
6056            SessionInfoUpdate {
6057                title: MaybeUndefined::Value("title".to_string()),
6058                updated_at: MaybeUndefined::Value("timestamp".to_string()),
6059                meta: MaybeUndefined::Undefined
6060            }
6061        );
6062
6063        let clear_meta =
6064            serde_json::from_value::<SessionInfoUpdate>(json!({"_meta": null})).unwrap();
6065        assert_eq!(clear_meta.meta, MaybeUndefined::Null);
6066
6067        let mut meta = Meta::new();
6068        meta.insert("source".to_string(), json!("session-info"));
6069
6070        assert_eq!(
6071            serde_json::from_value::<SessionInfoUpdate>(json!({"_meta": {
6072                "source": "session-info"
6073            }}))
6074            .unwrap()
6075            .meta,
6076            MaybeUndefined::Value(meta.clone())
6077        );
6078
6079        assert_eq!(
6080            serde_json::to_value(SessionInfoUpdate::new()).unwrap(),
6081            json!({})
6082        );
6083
6084        assert_eq!(
6085            serde_json::to_value(SessionInfoUpdate::new().meta(None::<Meta>)).unwrap(),
6086            json!({"_meta": null})
6087        );
6088
6089        assert_eq!(
6090            serde_json::to_value(SessionInfoUpdate::new().meta(meta)).unwrap(),
6091            json!({"_meta": {
6092                "source": "session-info"
6093            }})
6094        );
6095        assert_eq!(
6096            serde_json::to_value(SessionInfoUpdate::new().title("title")).unwrap(),
6097            json!({"title": "title"})
6098        );
6099        assert_eq!(
6100            serde_json::to_value(SessionInfoUpdate::new().title(None)).unwrap(),
6101            json!({"title": null})
6102        );
6103        assert_eq!(
6104            serde_json::to_value(
6105                SessionInfoUpdate::new()
6106                    .title("title")
6107                    .title(MaybeUndefined::Undefined)
6108            )
6109            .unwrap(),
6110            json!({})
6111        );
6112    }
6113
6114    #[test]
6115    fn test_content_chunk_message_id_serialization() {
6116        use serde_json::json;
6117
6118        assert_eq!(
6119            serde_json::to_value(SessionUpdate::AgentMessageChunk(ContentChunk::new(
6120                ContentBlock::Text(crate::v2::TextContent::new("Hello")),
6121                "msg_agent_c42b9",
6122            )))
6123            .unwrap(),
6124            json!({
6125                "sessionUpdate": "agent_message_chunk",
6126                "messageId": "msg_agent_c42b9",
6127                "content": {
6128                    "type": "text",
6129                    "text": "Hello"
6130                }
6131            })
6132        );
6133
6134        let err = serde_json::from_value::<ContentChunk>(json!({
6135            "content": {
6136                "type": "text",
6137                "text": "Hello"
6138            }
6139        }))
6140        .unwrap_err();
6141
6142        assert!(err.to_string().contains("messageId"), "{err}");
6143    }
6144
6145    #[test]
6146    fn test_tool_call_content_chunk_serialization() {
6147        use serde_json::json;
6148
6149        assert_eq!(
6150            serde_json::to_value(SessionUpdate::ToolCallContentChunk(
6151                ToolCallContentChunk::new(
6152                    "call_001",
6153                    crate::v2::ContentBlock::Text(crate::v2::TextContent::new("partial output")),
6154                )
6155            ))
6156            .unwrap(),
6157            json!({
6158                "sessionUpdate": "tool_call_content_chunk",
6159                "toolCallId": "call_001",
6160                "content": {
6161                    "type": "content",
6162                    "content": {
6163                        "type": "text",
6164                        "text": "partial output"
6165                    }
6166                }
6167            })
6168        );
6169
6170        let err = serde_json::from_value::<ToolCallContentChunk>(json!({
6171            "content": {
6172                "type": "content",
6173                "content": {
6174                    "type": "text",
6175                    "text": "partial output"
6176                }
6177            }
6178        }))
6179        .unwrap_err();
6180
6181        assert!(err.to_string().contains("toolCallId"), "{err}");
6182    }
6183
6184    #[test]
6185    fn test_full_message_serialization() {
6186        use serde_json::json;
6187
6188        assert_eq!(
6189            serde_json::to_value(SessionUpdate::UserMessage(
6190                UserMessage::new("msg_user_8f7a1").content(vec![ContentBlock::Text(
6191                    crate::v2::TextContent::new("Hello")
6192                )])
6193            ))
6194            .unwrap(),
6195            json!({
6196                "sessionUpdate": "user_message",
6197                "messageId": "msg_user_8f7a1",
6198                "content": [
6199                    {
6200                        "type": "text",
6201                        "text": "Hello"
6202                    }
6203                ]
6204            })
6205        );
6206
6207        assert_eq!(
6208            serde_json::to_value(SessionUpdate::AgentMessage(
6209                AgentMessage::new("msg_agent_c42b9").content(vec![ContentBlock::Text(
6210                    crate::v2::TextContent::new("Hello")
6211                )])
6212            ))
6213            .unwrap(),
6214            json!({
6215                "sessionUpdate": "agent_message",
6216                "messageId": "msg_agent_c42b9",
6217                "content": [
6218                    {
6219                        "type": "text",
6220                        "text": "Hello"
6221                    }
6222                ]
6223            })
6224        );
6225
6226        assert_eq!(
6227            serde_json::to_value(SessionUpdate::AgentThought(
6228                AgentThought::new("msg_thought_a12").content(vec![ContentBlock::Text(
6229                    crate::v2::TextContent::new("Need to inspect the call sites first.")
6230                )])
6231            ))
6232            .unwrap(),
6233            json!({
6234                "sessionUpdate": "agent_thought",
6235                "messageId": "msg_thought_a12",
6236                "content": [
6237                    {
6238                        "type": "text",
6239                        "text": "Need to inspect the call sites first."
6240                    }
6241                ]
6242            })
6243        );
6244    }
6245
6246    #[test]
6247    fn test_message_upsert_serialization() {
6248        use serde_json::json;
6249
6250        assert_eq!(
6251            serde_json::to_value(SessionUpdate::UserMessage(
6252                UserMessage::new("msg_empty").content(Vec::<ContentBlock>::new())
6253            ))
6254            .unwrap(),
6255            json!({
6256                "sessionUpdate": "user_message",
6257                "messageId": "msg_empty",
6258                "content": []
6259            })
6260        );
6261
6262        let empty = serde_json::from_value::<UserMessage>(json!({
6263            "messageId": "msg_empty",
6264            "content": []
6265        }))
6266        .unwrap();
6267        assert!(matches!(
6268            empty.content,
6269            MaybeUndefined::Value(ref content) if content.is_empty()
6270        ));
6271
6272        let patch = serde_json::from_value::<AgentMessage>(json!({
6273            "messageId": "msg_agent_c42b9"
6274        }))
6275        .unwrap();
6276        assert_eq!(patch.content, MaybeUndefined::Undefined);
6277        assert_eq!(patch.meta, MaybeUndefined::Undefined);
6278
6279        let malformed_meta = serde_json::from_value::<AgentMessage>(json!({
6280            "messageId": "msg_agent_c42b9",
6281            "_meta": false
6282        }))
6283        .unwrap();
6284        assert_eq!(malformed_meta.meta, MaybeUndefined::Undefined);
6285
6286        let patch = serde_json::from_value::<AgentThought>(json!({
6287            "messageId": "msg_thought_a12"
6288        }))
6289        .unwrap();
6290        assert_eq!(patch.content, MaybeUndefined::Undefined);
6291
6292        let clear = serde_json::from_value::<UserMessage>(json!({
6293            "messageId": "msg_user_8f7a1",
6294            "content": null
6295        }))
6296        .unwrap();
6297        assert_eq!(clear.content, MaybeUndefined::Null);
6298
6299        let clear_meta = serde_json::from_value::<UserMessage>(json!({
6300            "messageId": "msg_user_8f7a1",
6301            "_meta": null
6302        }))
6303        .unwrap();
6304        assert_eq!(clear_meta.meta, MaybeUndefined::Null);
6305
6306        let mut meta = Meta::new();
6307        meta.insert("source".to_string(), json!("replay"));
6308
6309        assert_eq!(
6310            serde_json::to_value(SessionUpdate::UserMessage(
6311                UserMessage::new("msg_user_8f7a1").meta(meta)
6312            ))
6313            .unwrap(),
6314            json!({
6315                "sessionUpdate": "user_message",
6316                "messageId": "msg_user_8f7a1",
6317                "_meta": {
6318                    "source": "replay"
6319                }
6320            })
6321        );
6322
6323        assert_eq!(
6324            serde_json::to_value(SessionUpdate::UserMessage(
6325                UserMessage::new("msg_user_8f7a1").meta(None::<Meta>)
6326            ))
6327            .unwrap(),
6328            json!({
6329                "sessionUpdate": "user_message",
6330                "messageId": "msg_user_8f7a1",
6331                "_meta": null
6332            })
6333        );
6334    }
6335
6336    #[test]
6337    fn test_usage_update_serialization() {
6338        use serde_json::json;
6339
6340        assert_eq!(
6341            serde_json::to_value(SessionUpdate::UsageUpdate(UsageUpdate::new(
6342                53_000, 200_000
6343            )))
6344            .unwrap(),
6345            json!({
6346                "sessionUpdate": "usage_update",
6347                "used": 53000,
6348                "size": 200_000
6349            })
6350        );
6351
6352        assert_eq!(
6353            serde_json::to_value(SessionUpdate::UsageUpdate(
6354                UsageUpdate::new(53_000, 200_000).cost(Cost::new(0.045, "USD"))
6355            ))
6356            .unwrap(),
6357            json!({
6358                "sessionUpdate": "usage_update",
6359                "used": 53000,
6360                "size": 200_000,
6361                "cost": {
6362                    "amount": 0.045,
6363                    "currency": "USD"
6364                }
6365            })
6366        );
6367
6368        let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
6369            "sessionUpdate": "usage_update",
6370            "used": 53000,
6371            "size": 200_000,
6372            "cost": null
6373        }))
6374        .unwrap() else {
6375            panic!("expected usage update");
6376        };
6377
6378        assert_eq!(update.cost, MaybeUndefined::Null);
6379
6380        let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
6381            "sessionUpdate": "usage_update",
6382            "used": 53000,
6383            "size": 200_000
6384        }))
6385        .unwrap() else {
6386            panic!("expected usage update");
6387        };
6388
6389        assert_eq!(update.cost, MaybeUndefined::Undefined);
6390    }
6391
6392    #[test]
6393    fn error_stop_reason_carries_failure_beside_discriminator() {
6394        use crate::v2::{Error, ErrorStopReason};
6395        use serde_json::json;
6396
6397        let update =
6398            SessionUpdate::StateUpdate(StateUpdate::Idle(IdleStateUpdate::new().stop_reason(
6399                StopReason::from(ErrorStopReason::new().error(Error::auth_required())),
6400            )));
6401        let wire = json!({
6402            "sessionUpdate": "state_update",
6403            "state": "idle",
6404            "stopReason": "error",
6405            "error": { "code": -32000, "message": "Authentication required" }
6406        });
6407        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6408        assert_eq!(
6409            serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6410            update
6411        );
6412
6413        let with_data =
6414            StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::from(
6415                ErrorStopReason::new().error(
6416                    Error::new(-32099, "Provider unavailable").data(json!({ "status": 503 })),
6417                ),
6418            )));
6419        let wire = json!({
6420            "state": "idle",
6421            "stopReason": "error",
6422            "error": {
6423                "code": -32099,
6424                "message": "Provider unavailable",
6425                "data": { "status": 503 }
6426            }
6427        });
6428        assert_eq!(serde_json::to_value(&with_data).unwrap(), wire);
6429        assert_eq!(
6430            serde_json::from_value::<StateUpdate>(wire).unwrap(),
6431            with_data
6432        );
6433
6434        // Missing, null, and malformed details leave a failure without details;
6435        // the stop reason still ends foreground work.
6436        let without_details = StateUpdate::Idle(
6437            IdleStateUpdate::new().stop_reason(StopReason::from(ErrorStopReason::new())),
6438        );
6439        for error in [
6440            None,
6441            Some(json!(null)),
6442            Some(json!("failed")),
6443            Some(json!({ "message": "missing code" })),
6444        ] {
6445            let mut wire = json!({ "state": "idle", "stopReason": "error" });
6446            if let Some(error) = error {
6447                wire["error"] = error;
6448            }
6449            assert_eq!(
6450                serde_json::from_value::<StateUpdate>(wire).unwrap(),
6451                without_details
6452            );
6453        }
6454        assert_eq!(
6455            serde_json::to_value(&without_details).unwrap(),
6456            json!({ "state": "idle", "stopReason": "error" })
6457        );
6458
6459        // `error` is a field of the `error` stop reason only. Beside any other
6460        // stop reason it is an unknown field: the update stays readable and the
6461        // error has nowhere to go.
6462        let parsed: StateUpdate = serde_json::from_value(json!({
6463            "state": "idle",
6464            "stopReason": "end_turn",
6465            "error": { "code": -32603, "message": "Internal error" }
6466        }))
6467        .unwrap();
6468        assert_eq!(
6469            parsed,
6470            StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::EndTurn))
6471        );
6472    }
6473
6474    #[test]
6475    fn flattened_stop_reason_keeps_open_enum_tolerance() {
6476        use crate::v2::OtherStopReason;
6477        use serde_json::json;
6478
6479        let meta: Meta = [("source".into(), json!("test"))].into_iter().collect();
6480
6481        // Omitted, null, and malformed stop reasons all mean no stop reason, as
6482        // when `stopReason` was a separate default-on-error field.
6483        for stop_reason in [None, Some(json!(null)), Some(json!(true)), Some(json!({}))] {
6484            let mut wire = json!({ "state": "idle", "_meta": { "source": "test" } });
6485            if let Some(stop_reason) = stop_reason {
6486                wire["stopReason"] = stop_reason;
6487            }
6488            let StateUpdate::Idle(idle) = serde_json::from_value(wire).unwrap() else {
6489                panic!("expected idle state update");
6490            };
6491            assert_eq!(idle.stop_reason, None);
6492            assert_eq!(idle.meta, Some(meta.clone()));
6493        }
6494
6495        // Unknown stop reasons keep their own fields for proxies and replay,
6496        // while the idle update's fields stay on the idle update.
6497        let wire = json!({
6498            "state": "idle",
6499            "stopReason": "_paused",
6500            "resumeAfter": 30,
6501            "_meta": { "source": "test" }
6502        });
6503        let parsed: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
6504        let expected = StateUpdate::Idle(
6505            IdleStateUpdate::new()
6506                .stop_reason(StopReason::Other(OtherStopReason::new(
6507                    "_paused",
6508                    [("resumeAfter".into(), json!(30))].into_iter().collect(),
6509                )))
6510                .meta(meta),
6511        );
6512        assert_eq!(parsed, expected);
6513        assert_eq!(serde_json::to_value(&parsed).unwrap(), wire);
6514    }
6515
6516    #[test]
6517    fn known_stop_reasons_are_never_read_as_other() {
6518        use crate::v2::{ErrorStopReason, OtherStopReason};
6519        use serde_json::json;
6520
6521        let known = [
6522            StopReason::EndTurn,
6523            StopReason::MaxTokens,
6524            StopReason::MaxTurnRequests,
6525            StopReason::Refusal,
6526            StopReason::Cancelled,
6527            StopReason::Error(ErrorStopReason::new()),
6528        ];
6529        // Adding a variant breaks this match, so `known` stays complete.
6530        for stop_reason in &known {
6531            match stop_reason {
6532                StopReason::EndTurn
6533                | StopReason::MaxTokens
6534                | StopReason::MaxTurnRequests
6535                | StopReason::Refusal
6536                | StopReason::Cancelled
6537                | StopReason::Error(_)
6538                | StopReason::Other(_) => {}
6539            }
6540        }
6541
6542        for stop_reason in known {
6543            let update = StateUpdate::Idle(IdleStateUpdate::new().stop_reason(stop_reason));
6544            let wire = serde_json::to_value(&update).unwrap();
6545            assert_eq!(
6546                serde_json::from_value::<StateUpdate>(wire.clone()).unwrap(),
6547                update
6548            );
6549            assert!(
6550                serde_json::from_value::<OtherStopReason>(
6551                    json!({ "stopReason": wire["stopReason"] })
6552                )
6553                .is_err(),
6554                "{} must not be accepted as a custom stop reason",
6555                wire["stopReason"]
6556            );
6557        }
6558    }
6559
6560    #[test]
6561    fn unknown_stop_reason_leaves_usage_on_the_idle_update() {
6562        use serde_json::json;
6563
6564        let usage = json!({ "totalTokens": 10, "inputTokens": 6, "outputTokens": 4 });
6565        let wire = json!({ "state": "idle", "stopReason": "_paused", "usage": usage });
6566        let StateUpdate::Idle(idle) = serde_json::from_value(wire.clone()).unwrap() else {
6567            panic!("expected idle state update");
6568        };
6569        let Some(StopReason::Other(other)) = &idle.stop_reason else {
6570            panic!("expected a custom stop reason");
6571        };
6572        assert!(other.fields.is_empty());
6573
6574        #[cfg(feature = "unstable_end_turn_token_usage")]
6575        {
6576            assert!(idle.usage.is_some());
6577            assert_eq!(serde_json::to_value(&idle).unwrap()["usage"], usage);
6578        }
6579        // Without the feature, `usage` is not a field of the idle update, and it
6580        // must not be smuggled through as a field of the stop reason either.
6581        #[cfg(not(feature = "unstable_end_turn_token_usage"))]
6582        assert!(serde_json::to_value(&idle).unwrap().get("usage").is_none());
6583    }
6584
6585    #[test]
6586    fn test_state_update_serialization() {
6587        use serde_json::json;
6588
6589        assert_eq!(
6590            serde_json::to_value(SessionUpdate::StateUpdate(StateUpdate::Running(
6591                RunningStateUpdate::new()
6592            )))
6593            .unwrap(),
6594            json!({
6595                "sessionUpdate": "state_update",
6596                "state": "running"
6597            })
6598        );
6599
6600        assert_eq!(
6601            serde_json::to_value(SessionUpdate::StateUpdate(StateUpdate::Idle(
6602                IdleStateUpdate::new().stop_reason(StopReason::EndTurn)
6603            )))
6604            .unwrap(),
6605            json!({
6606                "sessionUpdate": "state_update",
6607                "state": "idle",
6608                "stopReason": "end_turn"
6609            })
6610        );
6611
6612        let SessionUpdate::StateUpdate(update) = serde_json::from_value(json!({
6613            "sessionUpdate": "state_update",
6614            "state": "requires_action"
6615        }))
6616        .unwrap() else {
6617            panic!("expected state update");
6618        };
6619
6620        assert!(matches!(update, StateUpdate::RequiresAction(_)));
6621
6622        let SessionUpdate::StateUpdate(StateUpdate::Idle(update)) = serde_json::from_value(json!({
6623            "sessionUpdate": "state_update",
6624            "state": "idle",
6625            "stopReason": null
6626        }))
6627        .unwrap() else {
6628            panic!("expected idle state update");
6629        };
6630
6631        assert_eq!(update.stop_reason, None);
6632
6633        let SessionUpdate::StateUpdate(StateUpdate::Other(update)) =
6634            serde_json::from_value(json!({
6635                "sessionUpdate": "state_update",
6636                "state": "_paused",
6637                "label": "Paused"
6638            }))
6639            .unwrap()
6640        else {
6641            panic!("expected unknown state update");
6642        };
6643
6644        assert_eq!(update.state, "_paused");
6645        assert_eq!(update.fields["label"], json!("Paused"));
6646    }
6647
6648    #[test]
6649    fn session_update_preserves_unknown_variant() {
6650        use serde_json::json;
6651
6652        let update: SessionUpdate = serde_json::from_value(json!({
6653            "sessionUpdate": "_status_badge",
6654            "label": "Indexing",
6655            "progress": 0.5
6656        }))
6657        .unwrap();
6658
6659        let SessionUpdate::Other(unknown) = update else {
6660            panic!("expected unknown session update");
6661        };
6662
6663        assert_eq!(unknown.session_update, "_status_badge");
6664        assert_eq!(unknown.fields.get("label"), Some(&json!("Indexing")));
6665        assert_eq!(unknown.fields.get("progress"), Some(&json!(0.5)));
6666
6667        assert_eq!(
6668            serde_json::to_value(SessionUpdate::Other(unknown)).unwrap(),
6669            json!({
6670                "sessionUpdate": "_status_badge",
6671                "label": "Indexing",
6672                "progress": 0.5
6673            })
6674        );
6675    }
6676
6677    #[test]
6678    fn terminal_session_updates_use_known_discriminators() {
6679        use serde_json::json;
6680
6681        assert_eq!(
6682            serde_json::to_value(SessionUpdate::TerminalUpdate(
6683                TerminalUpdate::new("term_1").command("cargo test")
6684            ))
6685            .unwrap(),
6686            json!({
6687                "sessionUpdate": "terminal_update",
6688                "terminalId": "term_1",
6689                "command": "cargo test"
6690            })
6691        );
6692        assert_eq!(
6693            serde_json::to_value(SessionUpdate::TerminalOutputChunk(
6694                TerminalOutputChunk::new("term_1", "dGVzdAo=")
6695            ))
6696            .unwrap(),
6697            json!({
6698                "sessionUpdate": "terminal_output_chunk",
6699                "terminalId": "term_1",
6700                "data": "dGVzdAo="
6701            })
6702        );
6703    }
6704
6705    #[test]
6706    fn session_update_does_not_hide_malformed_known_terminal_variants() {
6707        use serde_json::json;
6708
6709        assert!(
6710            serde_json::from_value::<SessionUpdate>(json!({
6711                "sessionUpdate": "terminal_update"
6712            }))
6713            .is_err()
6714        );
6715        assert!(
6716            serde_json::from_value::<SessionUpdate>(json!({
6717                "sessionUpdate": "terminal_output_chunk",
6718                "terminalId": "term_1"
6719            }))
6720            .is_err()
6721        );
6722    }
6723
6724    #[test]
6725    fn test_plan_update_serialization() {
6726        use serde_json::json;
6727
6728        let plan_update =
6729            SessionUpdate::PlanUpdate(PlanUpdate::new(crate::v2::PlanUpdateContent::items(
6730                "plan-1",
6731                vec![crate::v2::PlanEntry::new(
6732                    "Step 1",
6733                    crate::v2::PlanEntryPriority::High,
6734                    crate::v2::PlanEntryStatus::Pending,
6735                )],
6736            )));
6737
6738        assert_eq!(
6739            serde_json::to_value(plan_update).unwrap(),
6740            json!({
6741                "sessionUpdate": "plan_update",
6742                "plan": {
6743                    "type": "items",
6744                    "planId": "plan-1",
6745                    "entries": [
6746                        {
6747                            "content": "Step 1",
6748                            "priority": "high",
6749                            "status": "pending"
6750                        }
6751                    ]
6752                }
6753            })
6754        );
6755    }
6756
6757    #[cfg(feature = "unstable_plan_operations")]
6758    #[test]
6759    fn test_plan_removed_serialization() {
6760        use serde_json::json;
6761
6762        assert_eq!(
6763            serde_json::to_value(SessionUpdate::PlanRemoved(PlanRemoved::new("plan-1"))).unwrap(),
6764            json!({
6765                "sessionUpdate": "plan_removed",
6766                "planId": "plan-1"
6767            })
6768        );
6769    }
6770
6771    #[test]
6772    fn available_command_uses_type_discriminator() {
6773        use serde_json::json;
6774
6775        let command = AvailableCommand::Command(
6776            Command::new("web", "Search the web")
6777                .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
6778        );
6779
6780        let json = serde_json::to_value(&command).unwrap();
6781        assert_eq!(
6782            json,
6783            json!({
6784                "type": "command",
6785                "name": "web",
6786                "description": "Search the web",
6787                "input": { "type": "text", "hint": "Query" }
6788            })
6789        );
6790
6791        let roundtripped: AvailableCommand = serde_json::from_value(json).unwrap();
6792        assert_eq!(roundtripped, command);
6793        assert_eq!(roundtripped.name(), "web");
6794        assert_eq!(roundtripped.description(), "Search the web");
6795    }
6796
6797    #[test]
6798    fn available_command_preserves_unknown_typed_variant() {
6799        use serde_json::json;
6800
6801        let payload = json!({
6802            "type": "_skill",
6803            "name": "pdf-processing",
6804            "description": "Extract text from PDFs",
6805            "uri": "skill://pdf-processing/SKILL.md",
6806            "_meta": { "example.com/source": "mcp" }
6807        });
6808        let command: AvailableCommand = serde_json::from_value(payload.clone()).unwrap();
6809
6810        assert_eq!(command.name(), "pdf-processing");
6811        assert_eq!(command.description(), "Extract text from PDFs");
6812        assert!(command.meta().is_some());
6813
6814        let AvailableCommand::Other(unknown) = &command else {
6815            panic!("expected unknown command");
6816        };
6817        assert_eq!(unknown.type_, "_skill");
6818        assert_eq!(
6819            unknown.fields.get("uri"),
6820            Some(&json!("skill://pdf-processing/SKILL.md"))
6821        );
6822        assert_eq!(serde_json::to_value(&command).unwrap(), payload);
6823    }
6824
6825    #[test]
6826    fn available_command_unknown_tolerates_invalid_meta() {
6827        use serde_json::json;
6828
6829        let command: AvailableCommand = serde_json::from_value(json!({
6830            "type": "_skill",
6831            "name": "pdf-processing",
6832            "description": "Extract text from PDFs",
6833            "_meta": "oops"
6834        }))
6835        .unwrap();
6836
6837        assert!(matches!(command, AvailableCommand::Other(_)));
6838        assert!(command.meta().is_none());
6839    }
6840
6841    #[test]
6842    fn available_command_unknown_does_not_hide_malformed_command_variant() {
6843        use serde_json::json;
6844
6845        // A missing discriminator is rejected rather than defaulting to `command`.
6846        assert!(
6847            serde_json::from_value::<AvailableCommand>(json!({
6848                "name": "test",
6849                "description": "Run project tests"
6850            }))
6851            .is_err()
6852        );
6853        assert!(
6854            serde_json::from_value::<AvailableCommand>(json!({
6855                "type": "command",
6856                "name": "test"
6857            }))
6858            .is_err()
6859        );
6860        assert!(
6861            serde_json::from_value::<OtherAvailableCommand>(json!({
6862                "type": "command",
6863                "name": "test",
6864                "description": "Run project tests"
6865            }))
6866            .is_err()
6867        );
6868        assert!(
6869            serde_json::from_value::<AvailableCommand>(json!({
6870                "type": "_skill",
6871                "name": "pdf-processing"
6872            }))
6873            .is_err()
6874        );
6875    }
6876
6877    #[cfg(feature = "unstable_agent_skills")]
6878    #[test]
6879    fn skill_command_uses_type_discriminator() {
6880        use serde_json::json;
6881
6882        let skill = AvailableCommand::Skill(
6883            Skill::new("pdf-processing", "Extract text and tables from PDF files").path(
6884                AbsolutePath::new("/home/alice/.agents/skills/pdf-processing/SKILL.md"),
6885            ),
6886        );
6887
6888        let wire = json!({
6889            "type": "skill",
6890            "name": "pdf-processing",
6891            "description": "Extract text and tables from PDF files",
6892            "path": "/home/alice/.agents/skills/pdf-processing/SKILL.md"
6893        });
6894        assert_eq!(serde_json::to_value(&skill).unwrap(), wire);
6895
6896        let roundtripped: AvailableCommand = serde_json::from_value(wire).unwrap();
6897        assert_eq!(roundtripped, skill);
6898        assert_eq!(roundtripped.name(), "pdf-processing");
6899        assert_eq!(
6900            roundtripped.description(),
6901            "Extract text and tables from PDF files"
6902        );
6903        assert!(roundtripped.meta().is_none());
6904
6905        // A skill with no file omits `path`.
6906        assert_eq!(
6907            serde_json::to_value(AvailableCommand::Skill(Skill::new(
6908                "simplify",
6909                "Simplify the changed code"
6910            )))
6911            .unwrap(),
6912            json!({
6913                "type": "skill",
6914                "name": "simplify",
6915                "description": "Simplify the changed code"
6916            })
6917        );
6918    }
6919
6920    #[cfg(feature = "unstable_agent_skills")]
6921    #[test]
6922    fn skill_command_treats_invalid_display_fields_as_absent() {
6923        use serde_json::json;
6924
6925        let expected = AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text"));
6926        for (field, value) in [
6927            ("path", json!(null)),
6928            ("path", json!(7)),
6929            ("path", json!({ "uri": "file:///SKILL.md" })),
6930            ("_meta", json!(null)),
6931            ("_meta", json!("oops")),
6932        ] {
6933            let mut wire = json!({
6934                "type": "skill",
6935                "name": "pdf-processing",
6936                "description": "Extract text"
6937            });
6938            wire[field] = value;
6939            assert_eq!(
6940                serde_json::from_value::<AvailableCommand>(wire).unwrap(),
6941                expected,
6942                "{field}"
6943            );
6944        }
6945    }
6946
6947    #[cfg(feature = "unstable_agent_skills")]
6948    #[test]
6949    fn skill_command_has_no_input_specification() {
6950        use serde_json::json;
6951
6952        // Skills take no input. A field the entry does not define is ignored.
6953        let skill: AvailableCommand = serde_json::from_value(json!({
6954            "type": "skill",
6955            "name": "pdf-processing",
6956            "description": "Extract text",
6957            "input": { "type": "text", "hint": "file or instructions" }
6958        }))
6959        .unwrap();
6960        assert_eq!(
6961            skill,
6962            AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text"))
6963        );
6964        assert!(serde_json::to_value(&skill).unwrap().get("input").is_none());
6965    }
6966
6967    #[cfg(feature = "unstable_agent_skills")]
6968    #[test]
6969    fn malformed_skill_command_is_skipped_and_never_preserved_as_unknown() {
6970        use serde_json::json;
6971
6972        for malformed in [
6973            json!({ "type": "skill", "name": "pdf-processing" }),
6974            json!({ "type": "skill", "description": "Extract text" }),
6975            json!({ "type": "skill", "name": 1, "description": "Extract text" }),
6976        ] {
6977            assert!(serde_json::from_value::<AvailableCommand>(malformed.clone()).is_err());
6978            assert!(serde_json::from_value::<OtherAvailableCommand>(malformed).is_err());
6979        }
6980
6981        // In a command list, the malformed entry is skipped and the rest are kept.
6982        let update: AvailableCommandsUpdate = serde_json::from_value(json!({
6983            "availableCommands": [
6984                { "type": "skill", "name": "pdf-processing", "description": "Extract text" },
6985                { "type": "skill", "name": "broken" },
6986                { "type": "command", "name": "test", "description": "Run project tests" }
6987            ]
6988        }))
6989        .unwrap();
6990        assert_eq!(
6991            update.available_commands,
6992            vec![
6993                AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text")),
6994                AvailableCommand::Command(Command::new("test", "Run project tests")),
6995            ]
6996        );
6997    }
6998
6999    #[cfg(feature = "unstable_agent_skills")]
7000    #[test]
7001    fn skill_commands_capability_is_advertised_only_by_an_object() {
7002        use serde_json::json;
7003
7004        let capabilities = ClientCapabilities::new().session(
7005            ClientSessionCapabilities::new()
7006                .commands(CommandsCapabilities::new().skill(CommandsSkillCapabilities::new())),
7007        );
7008        let wire = json!({ "session": { "commands": { "skill": {} } } });
7009        assert_eq!(serde_json::to_value(&capabilities).unwrap(), wire);
7010        assert_eq!(
7011            serde_json::from_value::<ClientCapabilities>(wire).unwrap(),
7012            capabilities
7013        );
7014
7015        // `session` and `commands` only group capabilities. `{}` advertises nothing.
7016        for unsupported in [
7017            json!({}),
7018            json!({ "session": null }),
7019            json!({ "session": {} }),
7020            json!({ "session": { "commands": null } }),
7021            json!({ "session": { "commands": {} } }),
7022            json!({ "session": { "commands": true } }),
7023            json!({ "session": { "commands": { "skill": null } } }),
7024            json!({ "session": { "commands": { "skill": true } } }),
7025            json!({ "session": { "commands": { "skill": "supported" } } }),
7026        ] {
7027            let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
7028            assert!(
7029                capabilities
7030                    .session
7031                    .and_then(|session| session.commands)
7032                    .and_then(|commands| commands.skill)
7033                    .is_none()
7034            );
7035        }
7036    }
7037
7038    #[cfg(all(
7039        feature = "unstable_agent_skills",
7040        feature = "unstable_prompt_suggestions"
7041    ))]
7042    #[test]
7043    fn client_session_capabilities_are_independent_of_each_other() {
7044        use serde_json::json;
7045
7046        // A malformed capability does not withdraw the others in the group.
7047        let capabilities: ClientCapabilities = serde_json::from_value(json!({
7048            "session": {
7049                "promptSuggestions": true,
7050                "commands": { "skill": {} }
7051            }
7052        }))
7053        .unwrap();
7054        let session = capabilities.session.unwrap();
7055        assert!(session.prompt_suggestions.is_none());
7056        assert!(session.commands.unwrap().skill.is_some());
7057    }
7058
7059    #[cfg(all(feature = "schemars", feature = "unstable_agent_skills"))]
7060    #[test]
7061    fn skill_schemas_keep_acted_on_fields_strict() {
7062        use serde_json::json;
7063
7064        let skill = serde_json::to_value(schemars::schema_for!(Skill)).unwrap();
7065        assert_eq!(skill["required"], json!(["name", "description"]));
7066        for lenient in ["path", "_meta"] {
7067            assert_eq!(
7068                skill["properties"][lenient]["x-deserialize-default-on-error"], true,
7069                "{lenient}"
7070            );
7071        }
7072
7073        // The Agent acts on the referenced name, so it has no lenient fallback.
7074        let reference =
7075            serde_json::to_value(schemars::schema_for!(crate::v2::SkillReference)).unwrap();
7076        assert_eq!(reference["required"], json!(["name"]));
7077        assert!(
7078            reference["properties"]["name"]
7079                .get("x-deserialize-default-on-error")
7080                .is_none()
7081        );
7082    }
7083
7084    #[test]
7085    fn available_command_input_preserves_unknown_typed_variant() {
7086        use serde_json::json;
7087
7088        let input: AvailableCommandInput = serde_json::from_value(json!({
7089            "type": "_choices",
7090            "hint": "Pick one",
7091            "options": ["fast", "careful"]
7092        }))
7093        .unwrap();
7094
7095        let AvailableCommandInput::Other(unknown) = input else {
7096            panic!("expected unknown command input");
7097        };
7098
7099        assert_eq!(unknown.type_, "_choices");
7100        assert_eq!(unknown.fields.get("hint"), Some(&json!("Pick one")));
7101        assert_eq!(
7102            unknown.fields.get("options"),
7103            Some(&json!(["fast", "careful"]))
7104        );
7105        assert_eq!(
7106            serde_json::to_value(AvailableCommandInput::Other(unknown)).unwrap(),
7107            json!({
7108                "type": "_choices",
7109                "hint": "Pick one",
7110                "options": ["fast", "careful"]
7111            })
7112        );
7113    }
7114
7115    #[test]
7116    fn available_command_input_text_uses_type_discriminator() {
7117        use serde_json::json;
7118
7119        let input = AvailableCommandInput::Text(TextCommandInput::new("Describe changes"));
7120
7121        let json = serde_json::to_value(&input).unwrap();
7122        assert_eq!(
7123            json,
7124            json!({
7125                "type": "text",
7126                "hint": "Describe changes"
7127            })
7128        );
7129
7130        let roundtripped: AvailableCommandInput = serde_json::from_value(json).unwrap();
7131        assert!(matches!(roundtripped, AvailableCommandInput::Text(_)));
7132    }
7133
7134    #[test]
7135    fn request_permission_subject_tool_call_uses_type_discriminator() {
7136        use serde_json::json;
7137
7138        let subject = RequestPermissionSubject::from(ToolCallUpdate::new("call_001"));
7139
7140        let json = serde_json::to_value(&subject).unwrap();
7141        assert_eq!(
7142            json,
7143            json!({
7144                "type": "tool_call",
7145                "toolCall": {
7146                    "toolCallId": "call_001"
7147                }
7148            })
7149        );
7150
7151        let roundtripped: RequestPermissionSubject = serde_json::from_value(json).unwrap();
7152        assert!(matches!(
7153            roundtripped,
7154            RequestPermissionSubject::ToolCall(_)
7155        ));
7156    }
7157
7158    #[test]
7159    fn request_permission_subject_command_uses_type_discriminator() {
7160        use serde_json::json;
7161
7162        let mut meta = Meta::new();
7163        meta.insert("source".to_string(), json!("shell"));
7164        let subject = RequestPermissionSubject::from(
7165            CommandPermissionSubject::new("cargo test", "/workspace/project")
7166                .tool_call_id("call_001")
7167                .terminal_id("term_1")
7168                .meta(meta),
7169        );
7170
7171        let json = serde_json::to_value(&subject).unwrap();
7172        assert_eq!(
7173            json,
7174            json!({
7175                "type": "command",
7176                "command": "cargo test",
7177                "cwd": "/workspace/project",
7178                "toolCallId": "call_001",
7179                "terminalId": "term_1",
7180                "_meta": {
7181                    "source": "shell"
7182                }
7183            })
7184        );
7185
7186        let roundtripped: RequestPermissionSubject = serde_json::from_value(json).unwrap();
7187        assert!(matches!(roundtripped, RequestPermissionSubject::Command(_)));
7188    }
7189
7190    #[test]
7191    fn command_permission_subject_treats_optional_association_nulls_as_omitted() {
7192        use serde_json::json;
7193
7194        let subject: RequestPermissionSubject = serde_json::from_value(json!({
7195            "type": "command",
7196            "command": "cargo test",
7197            "cwd": "/workspace/project",
7198            "toolCallId": null,
7199            "terminalId": null,
7200            "_meta": null
7201        }))
7202        .unwrap();
7203
7204        let RequestPermissionSubject::Command(subject) = subject else {
7205            panic!("expected command permission subject");
7206        };
7207        assert_eq!(subject.cwd, AbsolutePath::new("/workspace/project"));
7208        assert_eq!(subject.tool_call_id, None);
7209        assert_eq!(subject.terminal_id, None);
7210        assert_eq!(subject.meta, None);
7211        assert_eq!(
7212            serde_json::to_value(RequestPermissionSubject::Command(subject)).unwrap(),
7213            json!({
7214                "type": "command",
7215                "command": "cargo test",
7216                "cwd": "/workspace/project"
7217            })
7218        );
7219    }
7220
7221    #[test]
7222    fn request_permission_subject_preserves_unknown_variant() {
7223        use serde_json::json;
7224
7225        let subject: RequestPermissionSubject = serde_json::from_value(json!({
7226            "type": "_review",
7227            "reason": "needs-review",
7228            "retryAfterSeconds": 30
7229        }))
7230        .unwrap();
7231
7232        let RequestPermissionSubject::Other(unknown) = subject else {
7233            panic!("expected unknown permission subject");
7234        };
7235
7236        assert_eq!(unknown.type_, "_review");
7237        assert_eq!(unknown.fields.get("reason"), Some(&json!("needs-review")));
7238        assert_eq!(unknown.fields.get("retryAfterSeconds"), Some(&json!(30)));
7239        assert_eq!(
7240            serde_json::to_value(RequestPermissionSubject::Other(unknown)).unwrap(),
7241            json!({
7242                "type": "_review",
7243                "reason": "needs-review",
7244                "retryAfterSeconds": 30
7245            })
7246        );
7247    }
7248
7249    #[test]
7250    fn request_permission_subject_unknown_does_not_hide_malformed_known_variant() {
7251        use serde_json::json;
7252
7253        assert!(
7254            serde_json::from_value::<RequestPermissionSubject>(json!({
7255                "type": "tool_call"
7256            }))
7257            .is_err()
7258        );
7259        assert!(
7260            serde_json::from_value::<RequestPermissionSubject>(json!({
7261                "type": 1
7262            }))
7263            .is_err()
7264        );
7265        assert!(
7266            serde_json::from_value::<RequestPermissionSubject>(json!({
7267                "type": "command",
7268                "cwd": "/workspace/project"
7269            }))
7270            .is_err()
7271        );
7272        assert!(
7273            serde_json::from_value::<RequestPermissionSubject>(json!({
7274                "type": "command",
7275                "command": "cargo test"
7276            }))
7277            .is_err()
7278        );
7279        assert!(
7280            serde_json::from_value::<RequestPermissionSubject>(json!({
7281                "type": "command",
7282                "command": "cargo test",
7283                "cwd": null
7284            }))
7285            .is_err()
7286        );
7287    }
7288
7289    #[test]
7290    fn request_permission_title_and_description_are_separate_from_tool_call_content() {
7291        use serde_json::json;
7292
7293        let request =
7294            RequestPermissionRequest::new("sess_abc123def456", "Approve file edit?", Vec::new())
7295                .description("Allow this tool to edit src/main.rs?")
7296                .subject(RequestPermissionSubject::from(ToolCallUpdate::new(
7297                    "call_001",
7298                )));
7299
7300        assert_eq!(
7301            serde_json::to_value(request).unwrap(),
7302            json!({
7303                "sessionId": "sess_abc123def456",
7304                "title": "Approve file edit?",
7305                "description": "Allow this tool to edit src/main.rs?",
7306                "subject": {
7307                    "type": "tool_call",
7308                    "toolCall": {
7309                        "toolCallId": "call_001"
7310                    }
7311                },
7312                "options": []
7313            })
7314        );
7315    }
7316
7317    #[test]
7318    fn request_permission_requires_title_and_allows_missing_subject() {
7319        use serde_json::json;
7320
7321        let request = RequestPermissionRequest::new(
7322            "sess_abc123def456",
7323            "Approve elevated permissions?",
7324            Vec::new(),
7325        );
7326
7327        assert_eq!(
7328            serde_json::to_value(request).unwrap(),
7329            json!({
7330                "sessionId": "sess_abc123def456",
7331                "title": "Approve elevated permissions?",
7332                "options": []
7333            })
7334        );
7335
7336        let missing_subject: RequestPermissionRequest = serde_json::from_value(json!({
7337            "sessionId": "sess_abc123def456",
7338            "title": "Approve elevated permissions?",
7339            "options": []
7340        }))
7341        .unwrap();
7342        assert!(missing_subject.subject.is_none());
7343
7344        let null_subject: RequestPermissionRequest = serde_json::from_value(json!({
7345            "sessionId": "sess_abc123def456",
7346            "title": "Approve elevated permissions?",
7347            "subject": null,
7348            "options": []
7349        }))
7350        .unwrap();
7351        assert!(null_subject.subject.is_none());
7352
7353        assert!(
7354            serde_json::from_value::<RequestPermissionRequest>(json!({
7355                "sessionId": "sess_abc123def456",
7356                "options": []
7357            }))
7358            .is_err()
7359        );
7360    }
7361
7362    #[test]
7363    fn request_permission_outcome_preserves_unknown_variant() {
7364        use serde_json::json;
7365
7366        let outcome: RequestPermissionOutcome = serde_json::from_value(json!({
7367            "outcome": "_defer",
7368            "reason": "needs-review",
7369            "retryAfterSeconds": 30
7370        }))
7371        .unwrap();
7372
7373        let RequestPermissionOutcome::Other(unknown) = outcome else {
7374            panic!("expected unknown permission outcome");
7375        };
7376
7377        assert_eq!(unknown.outcome, "_defer");
7378        assert_eq!(unknown.fields.get("reason"), Some(&json!("needs-review")));
7379        assert_eq!(unknown.fields.get("retryAfterSeconds"), Some(&json!(30)));
7380        assert_eq!(
7381            serde_json::to_value(RequestPermissionOutcome::Other(unknown)).unwrap(),
7382            json!({
7383                "outcome": "_defer",
7384                "reason": "needs-review",
7385                "retryAfterSeconds": 30
7386            })
7387        );
7388    }
7389
7390    #[test]
7391    fn request_permission_outcome_unknown_does_not_hide_malformed_known_variant() {
7392        use serde_json::json;
7393
7394        assert!(
7395            serde_json::from_value::<RequestPermissionOutcome>(json!({
7396                "outcome": "selected"
7397            }))
7398            .is_err()
7399        );
7400        assert!(
7401            serde_json::from_value::<RequestPermissionOutcome>(json!({
7402                "outcome": 1
7403            }))
7404            .is_err()
7405        );
7406    }
7407
7408    #[test]
7409    fn available_command_input_unknown_does_not_hide_malformed_text_variant() {
7410        use serde_json::json;
7411
7412        assert!(serde_json::from_value::<AvailableCommandInput>(json!({})).is_err());
7413        assert!(
7414            serde_json::from_value::<AvailableCommandInput>(json!({
7415                "hint": "Pick one"
7416            }))
7417            .is_err()
7418        );
7419        assert!(
7420            serde_json::from_value::<AvailableCommandInput>(json!({
7421                "type": 1,
7422                "hint": "Pick one"
7423            }))
7424            .is_err()
7425        );
7426        assert!(
7427            serde_json::from_value::<OtherAvailableCommandInput>(json!({
7428                "type": "text",
7429                "hint": "Pick one"
7430            }))
7431            .is_err()
7432        );
7433    }
7434
7435    #[cfg(feature = "unstable_mcp_over_acp")]
7436    #[test]
7437    fn test_agent_mcp_request_method_names() {
7438        use serde_json::json;
7439
7440        let params: serde_json::Map<String, serde_json::Value> =
7441            [("cursor".to_string(), json!("abc"))].into_iter().collect();
7442
7443        assert_eq!(CLIENT_METHOD_NAMES.mcp_message, "mcp/message");
7444        assert_eq!(
7445            AgentRequest::MessageMcpRequest(Box::new(MessageMcpRequest::new(
7446                "server-1",
7447                "req-1",
7448                "tools/list"
7449            )))
7450            .method(),
7451            "mcp/message"
7452        );
7453        assert_eq!(
7454            serde_json::to_value(
7455                MessageMcpRequest::new("server-1", "req-1", "tools/list").params(params)
7456            )
7457            .unwrap(),
7458            json!({
7459                "serverId": "server-1",
7460                "requestId": "req-1",
7461                "method": "tools/list",
7462                "params": { "cursor": "abc" }
7463            })
7464        );
7465
7466        let request_with_null_params: MessageMcpRequest = serde_json::from_value(json!({
7467            "serverId": "server-1",
7468            "requestId": "req-1",
7469            "method": "tools/list",
7470            "params": null,
7471            "_meta": null
7472        }))
7473        .unwrap();
7474        assert_eq!(request_with_null_params.params, None);
7475        assert_eq!(request_with_null_params.meta, None);
7476        for key in ["serverId", "requestId", "method"] {
7477            let mut value =
7478                json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
7479            value.as_object_mut().unwrap().remove(key);
7480            assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
7481        }
7482        for key in ["serverId", "requestId", "method"] {
7483            let mut value =
7484                json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
7485            value[key] = serde_json::Value::Null;
7486            assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
7487        }
7488    }
7489
7490    #[test]
7491    fn test_auth_capabilities_serialize_terminal_support_as_object() {
7492        use serde_json::json;
7493
7494        let capabilities = ClientAuthCapabilities::new().terminal(TerminalAuthCapabilities::new());
7495
7496        assert_eq!(
7497            serde_json::to_value(&capabilities).unwrap(),
7498            json!({
7499                "terminal": {}
7500            })
7501        );
7502
7503        let deserialized: ClientAuthCapabilities = serde_json::from_value(json!({
7504            "terminal": false
7505        }))
7506        .unwrap();
7507        assert!(deserialized.terminal.is_none());
7508    }
7509
7510    #[test]
7511    fn request_permission_request_rejects_malformed_options() {
7512        use serde_json::json;
7513
7514        assert!(
7515            serde_json::from_value::<RequestPermissionRequest>(json!({
7516                "sessionId": "sess-1",
7517                "title": "Run tool?",
7518                "options": "not-an-array"
7519            }))
7520            .is_err()
7521        );
7522        assert!(
7523            serde_json::from_value::<RequestPermissionRequest>(json!({
7524                "sessionId": "sess-1",
7525                "title": "Run tool?",
7526                "options": [{"optionId": "allow"}]
7527            }))
7528            .is_err()
7529        );
7530    }
7531
7532    #[cfg(feature = "unstable_plan_operations")]
7533    #[test]
7534    fn malformed_plan_removed_is_not_hidden_as_unknown_update() {
7535        use serde_json::json;
7536
7537        assert!(
7538            serde_json::from_value::<SessionUpdate>(json!({
7539                "sessionUpdate": "plan_removed"
7540            }))
7541            .is_err()
7542        );
7543    }
7544}