Skip to main content

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