Skip to main content

agent_client_protocol_schema/v2/
client.rs

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