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