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