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