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]
4885#[allow(clippy::large_enum_variant)]
4886pub enum AgentRequest {
4887    /// Writes content to a text file in the client's file system.
4888    ///
4889    /// Only available if the client advertises the `fs.writeTextFile` capability.
4890    /// Allows the agent to create or modify files within the client's environment.
4891    ///
4892    /// See protocol docs: [Client](https://agentclientprotocol.com/protocol/v1/overview#client)
4893    WriteTextFileRequest(WriteTextFileRequest),
4894    /// Reads content from a text file in the client's file system.
4895    ///
4896    /// Only available if the client advertises the `fs.readTextFile` capability.
4897    /// Allows the agent to access file contents within the client's environment.
4898    ///
4899    /// See protocol docs: [Client](https://agentclientprotocol.com/protocol/v1/overview#client)
4900    ReadTextFileRequest(ReadTextFileRequest),
4901    /// Requests permission from the user for a tool call operation.
4902    ///
4903    /// Called by the agent when it needs user authorization before executing
4904    /// a potentially sensitive operation. The client should present the options
4905    /// to the user and return their decision.
4906    ///
4907    /// If the client cancels the prompt turn via `session/cancel`, it MUST
4908    /// respond to this request with the `cancelled` outcome.
4909    ///
4910    /// See protocol docs: [Requesting Permission](https://agentclientprotocol.com/protocol/v1/tool-calls#requesting-permission)
4911    RequestPermissionRequest(RequestPermissionRequest),
4912    /// Executes a command in a new terminal
4913    ///
4914    /// Only available if the `terminal` Client capability is set to `true`.
4915    ///
4916    /// Returns a `TerminalId` that can be used with other terminal methods
4917    /// to get the current output, wait for exit, and kill the command.
4918    ///
4919    /// The `TerminalId` can also be used to embed the terminal in a tool call
4920    /// by using `terminal` tool call content.
4921    ///
4922    /// The Agent is responsible for releasing the terminal by using the `terminal/release`
4923    /// method.
4924    ///
4925    /// See protocol docs: [Terminals](https://agentclientprotocol.com/protocol/v1/terminals)
4926    CreateTerminalRequest(CreateTerminalRequest),
4927    /// Gets the terminal output and exit status
4928    ///
4929    /// Returns the current content in the terminal without waiting for the command to exit.
4930    /// If the command has already exited, the exit status is included.
4931    ///
4932    /// See protocol docs: [Terminals](https://agentclientprotocol.com/protocol/v1/terminals)
4933    TerminalOutputRequest(TerminalOutputRequest),
4934    /// Releases a terminal
4935    ///
4936    /// The command is killed if it hasn't exited yet. Use `terminal/wait_for_exit`
4937    /// to wait for the command to exit before releasing the terminal.
4938    ///
4939    /// After release, the `TerminalId` can no longer be used with other `terminal/*` methods,
4940    /// but tool calls that already contain it, continue to display its output.
4941    ///
4942    /// The `terminal/kill` method can be used to terminate the command without releasing
4943    /// the terminal, allowing the Agent to call `terminal/output` and other methods.
4944    ///
4945    /// See protocol docs: [Terminals](https://agentclientprotocol.com/protocol/v1/terminals)
4946    ReleaseTerminalRequest(ReleaseTerminalRequest),
4947    /// Waits for the terminal command to exit and return its exit status
4948    ///
4949    /// See protocol docs: [Terminals](https://agentclientprotocol.com/protocol/v1/terminals)
4950    WaitForTerminalExitRequest(WaitForTerminalExitRequest),
4951    /// Kills the terminal command without releasing the terminal
4952    ///
4953    /// While `terminal/release` will also kill the command, this method will keep
4954    /// the `TerminalId` valid so it can be used with other methods.
4955    ///
4956    /// This method can be helpful when implementing command timeouts which terminate
4957    /// the command as soon as elapsed, and then get the final output so it can be sent
4958    /// to the model.
4959    ///
4960    /// Note: Call `terminal/release` when `TerminalId` is no longer needed.
4961    ///
4962    /// See protocol docs: [Terminals](https://agentclientprotocol.com/protocol/v1/terminals)
4963    KillTerminalRequest(KillTerminalRequest),
4964    /// Requests structured user input via a form or URL.
4965    ///
4966    /// See protocol docs: [Elicitation](https://agentclientprotocol.com/protocol/v1/elicitation)
4967    CreateElicitationRequest(CreateElicitationRequest),
4968    /// **UNSTABLE**
4969    ///
4970    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4971    ///
4972    /// Exchanges an MCP-over-ACP message.
4973    #[cfg(feature = "unstable_mcp_over_acp")]
4974    MessageMcpRequest(MessageMcpRequest),
4975    /// Handles extension method requests from the agent.
4976    ///
4977    /// Allows the Agent to send an arbitrary request that is not part of the ACP spec.
4978    /// Extension methods provide a way to add custom functionality while maintaining
4979    /// protocol compatibility.
4980    ///
4981    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4982    ExtMethodRequest(ExtRequest),
4983}
4984
4985impl_request_dispatch! {
4986    AgentRequest => ClientResponse {
4987        WriteTextFileRequest => WriteTextFileResponse: CLIENT_METHOD_NAMES.fs_write_text_file,
4988        ReadTextFileRequest => ReadTextFileResponse: CLIENT_METHOD_NAMES.fs_read_text_file,
4989        RequestPermissionRequest => RequestPermissionResponse: CLIENT_METHOD_NAMES.session_request_permission,
4990        CreateTerminalRequest => CreateTerminalResponse: CLIENT_METHOD_NAMES.terminal_create,
4991        TerminalOutputRequest => TerminalOutputResponse: CLIENT_METHOD_NAMES.terminal_output,
4992        ReleaseTerminalRequest => ReleaseTerminalResponse: CLIENT_METHOD_NAMES.terminal_release,
4993        WaitForTerminalExitRequest => WaitForTerminalExitResponse: CLIENT_METHOD_NAMES.terminal_wait_for_exit,
4994        KillTerminalRequest => KillTerminalResponse: CLIENT_METHOD_NAMES.terminal_kill,
4995        CreateElicitationRequest => CreateElicitationResponse: CLIENT_METHOD_NAMES.elicitation_create,
4996        #[cfg(feature = "unstable_mcp_over_acp")]
4997        MessageMcpRequest => MessageMcpResponse: CLIENT_METHOD_NAMES.mcp_message,
4998    }
4999    extension ExtMethodRequest(ExtRequest) => ExtMethodResponse;
5000}
5001
5002/// All possible responses that a client can send to an agent.
5003///
5004/// This enum is used internally for routing RPC responses. You typically won't need
5005/// to use this directly - the responses are handled automatically by the connection.
5006///
5007/// These are responses to the corresponding `AgentRequest` variants.
5008#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5009#[derive(Clone, Debug, Serialize, Deserialize)]
5010#[serde(untagged)]
5011#[cfg_attr(feature = "schemars", schemars(inline))]
5012#[non_exhaustive]
5013pub enum ClientResponse {
5014    /// Successful result returned for a `fs/write_text_file` request.
5015    WriteTextFileResponse(#[serde(default)] WriteTextFileResponse),
5016    /// Successful result returned for a `fs/read_text_file` request.
5017    ReadTextFileResponse(ReadTextFileResponse),
5018    /// Successful result returned for a `session/request_permission` request.
5019    RequestPermissionResponse(RequestPermissionResponse),
5020    /// Successful result returned for a `terminal/create` request.
5021    CreateTerminalResponse(CreateTerminalResponse),
5022    /// Successful result returned for a `terminal/output` request.
5023    TerminalOutputResponse(TerminalOutputResponse),
5024    /// Successful result returned for a `terminal/release` request.
5025    ReleaseTerminalResponse(#[serde(default)] ReleaseTerminalResponse),
5026    /// Successful result returned for a `terminal/wait_for_exit` request.
5027    WaitForTerminalExitResponse(WaitForTerminalExitResponse),
5028    /// Successful result returned for a `terminal/kill` request.
5029    KillTerminalResponse(#[serde(default)] KillTerminalResponse),
5030    /// Successful result returned for a `elicitation/create` request.
5031    CreateElicitationResponse(CreateElicitationResponse),
5032    /// Successful result returned by an MCP-over-ACP `mcp/message` request.
5033    #[cfg(feature = "unstable_mcp_over_acp")]
5034    MessageMcpResponse(MessageMcpResponse),
5035    /// Successful result returned by an extension method outside the core ACP method set.
5036    ExtMethodResponse(ExtResponse),
5037}
5038
5039/// All possible notifications that an agent can send to a client.
5040///
5041/// This enum is used internally for routing RPC notifications. You typically won't need
5042/// to use this directly.
5043///
5044/// Notifications do not expect a response.
5045#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5046#[derive(Clone, Debug, Serialize, Deserialize)]
5047#[serde(untagged)]
5048#[expect(clippy::large_enum_variant)]
5049#[cfg_attr(feature = "schemars", schemars(inline))]
5050#[non_exhaustive]
5051pub enum AgentNotification {
5052    /// Handles session update notifications from the agent.
5053    ///
5054    /// This is a notification endpoint (no response expected) that receives
5055    /// real-time updates about session progress, including message chunks,
5056    /// tool calls, and execution plans.
5057    ///
5058    /// Note: Clients SHOULD continue accepting tool call updates even after
5059    /// sending a `session/cancel` notification, as the agent may send final
5060    /// updates before responding with the cancelled stop reason.
5061    ///
5062    /// See protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/v1/prompt-turn#3-agent-reports-output)
5063    SessionNotification(SessionNotification),
5064    /// Notification that a URL-based elicitation has completed.
5065    ///
5066    /// See protocol docs: [Elicitation](https://agentclientprotocol.com/protocol/v1/elicitation#url-completion)
5067    CompleteElicitationNotification(CompleteElicitationNotification),
5068    /// **UNSTABLE**
5069    ///
5070    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5071    ///
5072    /// Notification that the agent's authentication state changed.
5073    ///
5074    /// Only sent by agents that advertise the `auth.status` capability.
5075    #[cfg(feature = "unstable_auth_status")]
5076    AuthStatusUpdateNotification(AuthStatusUpdateNotification),
5077    /// Handles extension notifications from the agent.
5078    ///
5079    /// Allows the Agent to send an arbitrary notification that is not part of the ACP spec.
5080    /// Extension notifications provide a way to send one-way messages for custom functionality
5081    /// while maintaining protocol compatibility.
5082    ///
5083    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5084    ExtNotification(ExtNotification),
5085}
5086
5087impl_message_dispatch! {
5088    AgentNotification {
5089        SessionNotification => CLIENT_METHOD_NAMES.session_update,
5090        CompleteElicitationNotification => CLIENT_METHOD_NAMES.elicitation_complete,
5091        #[cfg(feature = "unstable_auth_status")]
5092        AuthStatusUpdateNotification => CLIENT_METHOD_NAMES.auth_status_update,
5093    }
5094    extension ExtNotification(ExtNotification);
5095}
5096
5097#[cfg(test)]
5098mod tests {
5099    use super::*;
5100
5101    #[test]
5102    fn notice_preserves_wire_shape_nullable_fields_and_open_severity() {
5103        use serde_json::json;
5104
5105        let mut meta = Meta::new();
5106        meta.insert("source".into(), json!("fallback"));
5107        assert_eq!(
5108            serde_json::to_value(SessionUpdate::Notice(
5109                Notice::new(NoticeSeverity::Warning, "MCP server unavailable")
5110                    .description("Continuing without it.")
5111                    .meta(meta),
5112            ))
5113            .unwrap(),
5114            json!({
5115                "sessionUpdate": "notice",
5116                "severity": "warning",
5117                "title": "MCP server unavailable",
5118                "description": "Continuing without it.",
5119                "_meta": { "source": "fallback" }
5120            })
5121        );
5122
5123        assert_eq!(
5124            serde_json::to_value(SessionUpdate::Notice(Notice::new(
5125                NoticeSeverity::Info,
5126                "Indexing workspace",
5127            )))
5128            .unwrap(),
5129            json!({
5130                "sessionUpdate": "notice",
5131                "severity": "info",
5132                "title": "Indexing workspace"
5133            })
5134        );
5135
5136        let SessionUpdate::Notice(notice) = serde_json::from_value(json!({
5137            "sessionUpdate": "notice",
5138            "severity": "critical",
5139            "title": "Provider degraded",
5140            "description": null,
5141            "_meta": null
5142        }))
5143        .unwrap() else {
5144            panic!("expected notice");
5145        };
5146
5147        assert_eq!(
5148            notice.severity,
5149            NoticeSeverity::Other("critical".to_string())
5150        );
5151        assert_eq!(notice.description, None);
5152        assert_eq!(notice.meta, None);
5153        assert_eq!(
5154            serde_json::to_value(SessionUpdate::Notice(notice)).unwrap(),
5155            json!({
5156                "sessionUpdate": "notice",
5157                "severity": "critical",
5158                "title": "Provider degraded"
5159            })
5160        );
5161    }
5162
5163    #[test]
5164    fn notice_requires_string_severity_and_title() {
5165        use serde_json::json;
5166
5167        for malformed in [
5168            json!({
5169                "sessionUpdate": "notice",
5170                "severity": "warning",
5171                "title": 42
5172            }),
5173            json!({
5174                "sessionUpdate": "notice",
5175                "severity": 42,
5176                "title": "MCP server unavailable"
5177            }),
5178            json!({
5179                "sessionUpdate": "notice",
5180                "severity": "warning"
5181            }),
5182            json!({
5183                "sessionUpdate": "notice",
5184                "severity": "warning",
5185                "title": null
5186            }),
5187            json!({
5188                "sessionUpdate": "notice",
5189                "title": "MCP server unavailable"
5190            }),
5191            json!({
5192                "sessionUpdate": "notice",
5193                "severity": null,
5194                "title": "MCP server unavailable"
5195            }),
5196        ] {
5197            assert!(serde_json::from_str::<SessionUpdate>(&malformed.to_string()).is_err());
5198            assert!(serde_json::from_value::<SessionUpdate>(malformed).is_err());
5199        }
5200    }
5201
5202    #[test]
5203    fn notice_tolerates_invalid_optional_display_fields_and_custom_severity() {
5204        use serde_json::json;
5205
5206        let wire = json!({
5207            "sessionUpdate": "notice",
5208            "severity": "_custom",
5209            "title": "Provider degraded",
5210            "description": 42,
5211            "_meta": false
5212        });
5213        let SessionUpdate::Notice(notice) = serde_json::from_value(wire.clone()).unwrap() else {
5214            panic!("expected notice");
5215        };
5216        // Streaming deserialization must enforce the same contract as from_value.
5217        assert_eq!(
5218            serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
5219            SessionUpdate::Notice(notice.clone())
5220        );
5221        assert_eq!(notice.severity, NoticeSeverity::Other("_custom".into()));
5222        assert_eq!(notice.description, None);
5223        assert_eq!(notice.meta, None);
5224        assert_eq!(
5225            serde_json::to_value(notice).unwrap(),
5226            json!({"severity": "_custom", "title": "Provider degraded"})
5227        );
5228    }
5229
5230    #[cfg(feature = "schemars")]
5231    #[test]
5232    fn notice_schema_preserves_required_and_nullable_fields() {
5233        use serde_json::json;
5234
5235        let schema = serde_json::to_value(schemars::schema_for!(Notice)).unwrap();
5236        assert_eq!(schema["required"], json!(["severity", "title"]));
5237        assert_eq!(schema["properties"]["title"]["minLength"], 1);
5238        for field in ["description", "_meta"] {
5239            assert!(
5240                schema["properties"][field]["type"]
5241                    .as_array()
5242                    .unwrap()
5243                    .contains(&json!("null"))
5244            );
5245        }
5246        let capabilities =
5247            serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap();
5248        assert!(
5249            capabilities["properties"]["notices"]["anyOf"]
5250                .as_array()
5251                .unwrap()
5252                .contains(&json!({"type": "null"}))
5253        );
5254        assert!(
5255            !capabilities["required"]
5256                .as_array()
5257                .is_some_and(|required| required.contains(&json!("notices")))
5258        );
5259    }
5260
5261    #[test]
5262    fn notice_capability_advertises_support_only_when_present() {
5263        use serde_json::json;
5264
5265        let capabilities = ClientCapabilities::new()
5266            .session(ClientSessionCapabilities::new().notices(NoticeCapabilities::new()));
5267        let value = serde_json::to_value(&capabilities).unwrap();
5268        assert_eq!(value["session"], json!({ "notices": {} }));
5269        assert_eq!(
5270            serde_json::from_value::<ClientCapabilities>(value).unwrap(),
5271            capabilities
5272        );
5273
5274        for unsupported in [
5275            json!({}),
5276            json!({ "session": null }),
5277            json!({ "session": {} }),
5278            json!({ "session": { "notices": null } }),
5279            json!({ "session": { "notices": false } }),
5280            json!({ "session": { "notices": true } }),
5281            json!({ "session": { "notices": "supported" } }),
5282        ] {
5283            let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
5284            assert!(
5285                capabilities
5286                    .session
5287                    .and_then(|session| session.notices)
5288                    .is_none()
5289            );
5290        }
5291
5292        assert_eq!(
5293            serde_json::to_value(
5294                ClientSessionCapabilities::new()
5295                    .notices(NoticeCapabilities::new())
5296                    .notices(None)
5297            )
5298            .unwrap(),
5299            json!({})
5300        );
5301    }
5302
5303    #[cfg(feature = "unstable_prompt_suggestions")]
5304    #[test]
5305    fn prompt_suggestions_update_round_trips_prompt_content_and_meta() {
5306        use crate::v1::{ResourceLink, TextContent};
5307        use serde_json::json;
5308
5309        let mut meta = Meta::new();
5310        meta.insert("rank".into(), json!(1));
5311        let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
5312            PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(
5313                "Run the test suite and fix what breaks",
5314            ))])
5315            .meta(meta),
5316            PromptSuggestion::new(vec![
5317                ContentBlock::Text(TextContent::new("Add tests for ")),
5318                ContentBlock::ResourceLink(ResourceLink::new(
5319                    "parser.rs",
5320                    "file:///home/user/project/src/parser.rs",
5321                )),
5322            ]),
5323        ]));
5324        let wire = json!({
5325            "sessionUpdate": "prompt_suggestions_update",
5326            "suggestions": [
5327                {
5328                    "prompt": [
5329                        { "type": "text", "text": "Run the test suite and fix what breaks" }
5330                    ],
5331                    "_meta": { "rank": 1 }
5332                },
5333                {
5334                    "prompt": [
5335                        { "type": "text", "text": "Add tests for " },
5336                        {
5337                            "type": "resource_link",
5338                            "name": "parser.rs",
5339                            "uri": "file:///home/user/project/src/parser.rs"
5340                        }
5341                    ]
5342                }
5343            ]
5344        });
5345        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5346        assert_eq!(
5347            serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5348            update
5349        );
5350    }
5351
5352    #[cfg(feature = "unstable_prompt_suggestions")]
5353    #[test]
5354    fn prompt_suggestions_update_with_an_empty_list_withdraws_suggestions() {
5355        use serde_json::json;
5356
5357        let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![]));
5358        let wire = json!({
5359            "sessionUpdate": "prompt_suggestions_update",
5360            "suggestions": []
5361        });
5362        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5363        assert_eq!(
5364            serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5365            update
5366        );
5367
5368        // The list is required and non-null. Only its entries are lenient.
5369        for malformed in [json!(null), json!("none"), json!({ "prompt": [] })] {
5370            assert!(
5371                serde_json::from_value::<SessionUpdate>(json!({
5372                    "sessionUpdate": "prompt_suggestions_update",
5373                    "suggestions": malformed
5374                }))
5375                .is_err()
5376            );
5377        }
5378        assert!(
5379            serde_json::from_value::<SessionUpdate>(json!({
5380                "sessionUpdate": "prompt_suggestions_update"
5381            }))
5382            .is_err()
5383        );
5384    }
5385
5386    #[cfg(feature = "unstable_prompt_suggestions")]
5387    #[test]
5388    fn prompt_suggestions_update_skips_whole_suggestions_it_cannot_parse() {
5389        use crate::v1::TextContent;
5390        use serde_json::json;
5391
5392        let text =
5393            |text: &str| PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(text))]);
5394
5395        // One bad block fails the whole suggestion. Dropping only that block
5396        // would change what the prompt asks for.
5397        let update: SessionUpdate = serde_json::from_value(json!({
5398            "sessionUpdate": "prompt_suggestions_update",
5399            "suggestions": [
5400                { "prompt": [{ "type": "text", "text": "Keep the first" }] },
5401                { "text": "A suggestion without a prompt" },
5402                { "prompt": "Not a list" },
5403                { "prompt": [{ "type": "text", "text": "Open " }, { "type": "text" }] },
5404                { "prompt": [{ "type": "hologram", "data": "AAAA" }] },
5405                "not an object",
5406                { "prompt": [{ "type": "text", "text": "Keep the last" }], "_meta": false }
5407            ]
5408        }))
5409        .unwrap();
5410
5411        assert_eq!(
5412            update,
5413            SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
5414                text("Keep the first"),
5415                text("Keep the last"),
5416            ]))
5417        );
5418    }
5419
5420    #[cfg(feature = "unstable_prompt_suggestions")]
5421    #[test]
5422    fn prompt_suggestions_capability_advertises_support_and_content_types() {
5423        use serde_json::json;
5424
5425        let capabilities = ClientCapabilities::new().session(
5426            ClientSessionCapabilities::new()
5427                .prompt_suggestions(PromptSuggestionsCapabilities::new()),
5428        );
5429        let value = serde_json::to_value(&capabilities).unwrap();
5430        assert_eq!(value["session"], json!({ "promptSuggestions": {} }));
5431        assert_eq!(
5432            serde_json::from_value::<ClientCapabilities>(value).unwrap(),
5433            capabilities
5434        );
5435
5436        let content_types = PromptSuggestionsCapabilities::new()
5437            .image(PromptSuggestionsImageCapabilities::new())
5438            .audio(PromptSuggestionsAudioCapabilities::new())
5439            .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new());
5440        let wire = json!({ "image": {}, "audio": {}, "embeddedContext": {} });
5441        assert_eq!(serde_json::to_value(&content_types).unwrap(), wire);
5442        assert_eq!(
5443            serde_json::from_value::<PromptSuggestionsCapabilities>(wire).unwrap(),
5444            content_types
5445        );
5446
5447        for unsupported in [
5448            json!({}),
5449            json!({ "session": null }),
5450            json!({ "session": {} }),
5451            json!({ "session": { "promptSuggestions": null } }),
5452            json!({ "session": { "promptSuggestions": false } }),
5453            json!({ "session": { "promptSuggestions": true } }),
5454            json!({ "session": { "promptSuggestions": "supported" } }),
5455        ] {
5456            let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
5457            assert!(
5458                capabilities
5459                    .session
5460                    .and_then(|session| session.prompt_suggestions)
5461                    .is_none()
5462            );
5463        }
5464
5465        // A content type is advertised only by an object. The other types and
5466        // the capability itself are unaffected by a malformed one.
5467        assert_eq!(
5468            serde_json::from_value::<PromptSuggestionsCapabilities>(json!({
5469                "image": true,
5470                "audio": null,
5471                "embeddedContext": {}
5472            }))
5473            .unwrap(),
5474            PromptSuggestionsCapabilities::new()
5475                .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new())
5476        );
5477    }
5478
5479    #[cfg(all(feature = "schemars", feature = "unstable_prompt_suggestions"))]
5480    #[test]
5481    fn prompt_suggestions_schema_requires_the_list_and_a_non_empty_prompt() {
5482        use serde_json::json;
5483
5484        let update = serde_json::to_value(schemars::schema_for!(PromptSuggestionsUpdate)).unwrap();
5485        assert_eq!(update["required"], json!(["suggestions"]));
5486        assert_eq!(update["properties"]["suggestions"]["type"], "array");
5487
5488        let suggestion = serde_json::to_value(schemars::schema_for!(PromptSuggestion)).unwrap();
5489        assert_eq!(suggestion["required"], json!(["prompt"]));
5490        assert_eq!(suggestion["properties"]["prompt"]["type"], "array");
5491        assert_eq!(suggestion["properties"]["prompt"]["minItems"], 1);
5492
5493        let capabilities =
5494            serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap();
5495        assert!(
5496            capabilities["properties"]["promptSuggestions"]["anyOf"]
5497                .as_array()
5498                .unwrap()
5499                .contains(&json!({"type": "null"}))
5500        );
5501        assert!(
5502            !capabilities["required"]
5503                .as_array()
5504                .is_some_and(|required| required.contains(&json!("promptSuggestions")))
5505        );
5506
5507        let content_types =
5508            serde_json::to_value(schemars::schema_for!(PromptSuggestionsCapabilities)).unwrap();
5509        assert!(content_types.get("required").is_none());
5510        for field in ["image", "audio", "embeddedContext"] {
5511            assert!(
5512                content_types["properties"][field]["anyOf"]
5513                    .as_array()
5514                    .unwrap()
5515                    .contains(&json!({"type": "null"}))
5516            );
5517        }
5518    }
5519
5520    #[test]
5521    fn compaction_updates_preserve_patch_and_open_status_semantics() {
5522        use serde_json::json;
5523
5524        assert_eq!(
5525            serde_json::to_value(SessionUpdate::CompactionUpdate(CompactionUpdate::new(
5526                "cmp_001",
5527                CompactionStatus::InProgress,
5528            )))
5529            .unwrap(),
5530            json!({
5531                "sessionUpdate": "compaction_update",
5532                "compactionId": "cmp_001",
5533                "status": "in_progress"
5534            })
5535        );
5536
5537        let SessionUpdate::CompactionUpdate(update) = serde_json::from_value(json!({
5538            "sessionUpdate": "compaction_update",
5539            "compactionId": "cmp_001",
5540            "status": "paused",
5541            "summary": null,
5542            "error": null
5543        }))
5544        .unwrap() else {
5545            panic!("expected compaction update");
5546        };
5547        assert_eq!(update.status, CompactionStatus::Other("paused".into()));
5548        assert!(update.summary.is_null());
5549        assert!(update.error.is_null());
5550        assert!(update.meta.is_undefined());
5551    }
5552
5553    #[test]
5554    fn compaction_chunk_and_v1_capability_serialize() {
5555        use serde_json::json;
5556
5557        assert_eq!(
5558            serde_json::to_value(SessionUpdate::CompactionSummaryChunk(
5559                CompactionSummaryChunk::new(
5560                    "cmp_001",
5561                    ContentBlock::Text(crate::v1::TextContent::new("retained")),
5562                ),
5563            ))
5564            .unwrap(),
5565            json!({
5566                "sessionUpdate": "compaction_summary_chunk",
5567                "compactionId": "cmp_001",
5568                "content": { "type": "text", "text": "retained" }
5569            })
5570        );
5571        assert_eq!(
5572            serde_json::to_value(
5573                ClientSessionCapabilities::new().compaction(CompactionCapabilities::new())
5574            )
5575            .unwrap(),
5576            json!({ "compaction": {} })
5577        );
5578        let absent: ClientSessionCapabilities = serde_json::from_value(json!({})).unwrap();
5579        let null: ClientSessionCapabilities =
5580            serde_json::from_value(json!({ "compaction": null })).unwrap();
5581        assert!(absent.compaction.is_none());
5582        assert!(null.compaction.is_none());
5583    }
5584
5585    #[test]
5586    fn test_subagent_updates_serialization() {
5587        use serde_json::json;
5588
5589        let announced = SessionUpdate::SubagentUpdate(SubagentUpdate::new("sess_child_1"));
5590        assert_eq!(
5591            serde_json::to_value(&announced).unwrap(),
5592            json!({
5593                "sessionUpdate": "subagent_update",
5594                "sessionId": "sess_child_1"
5595            })
5596        );
5597        assert_eq!(
5598            serde_json::from_value::<SessionUpdate>(serde_json::to_value(&announced).unwrap())
5599                .unwrap(),
5600            announced
5601        );
5602        let capable = SubagentUpdate::new("sess_child_1").capabilities(
5603            SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new()),
5604        );
5605        assert_eq!(
5606            serde_json::to_value(capable).unwrap(),
5607            json!({
5608                "sessionId": "sess_child_1",
5609                "capabilities": {"cancel": {}}
5610            })
5611        );
5612        let minimal: SubagentUpdate =
5613            serde_json::from_value(json!({ "sessionId": "sess_child_3" })).unwrap();
5614        assert!(minimal.capabilities.is_undefined());
5615        assert!(minimal.state.is_undefined());
5616
5617        let nulls: SubagentUpdate = serde_json::from_value(json!({
5618            "sessionId": "sess_child_3",
5619            "capabilities": null,
5620            "state": null
5621        }))
5622        .unwrap();
5623        assert!(nulls.capabilities.is_null());
5624        assert!(nulls.state.is_null());
5625        assert_eq!(
5626            serde_json::to_value(nulls).unwrap(),
5627            json!({"sessionId": "sess_child_3", "capabilities": null, "state": null})
5628        );
5629    }
5630
5631    #[test]
5632    fn test_subagent_display_metadata() {
5633        use serde_json::json;
5634
5635        let update = SubagentUpdate::new("child")
5636            .title("Test investigator".to_string())
5637            .description("Investigates platform-specific test failures.".to_string());
5638        let wire = json!({
5639            "sessionId": "child",
5640            "title": "Test investigator",
5641            "description": "Investigates platform-specific test failures."
5642        });
5643        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5644        assert_eq!(
5645            serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5646            update
5647        );
5648
5649        let minimal = SubagentUpdate::new("child");
5650        assert_eq!(
5651            serde_json::to_value(&minimal).unwrap(),
5652            json!({"sessionId": "child"})
5653        );
5654        let cleared: SubagentUpdate = serde_json::from_value(json!({
5655            "sessionId": "child", "title": null, "description": null
5656        }))
5657        .unwrap();
5658        assert!(cleared.title.is_null());
5659        assert!(cleared.description.is_null());
5660        assert_eq!(
5661            serde_json::to_value(cleared).unwrap(),
5662            json!({"sessionId": "child", "title": null, "description": null})
5663        );
5664        let invalid: SubagentUpdate = serde_json::from_value(json!({
5665            "sessionId": "child", "title": false, "description": false
5666        }))
5667        .unwrap();
5668        assert_eq!(invalid, minimal);
5669
5670        let title_only: SubagentUpdate = serde_json::from_value(json!({
5671            "sessionId": "child", "title": "Updated title"
5672        }))
5673        .unwrap();
5674        assert_eq!(
5675            title_only.title.value().map(String::as_str),
5676            Some("Updated title")
5677        );
5678        assert!(title_only.description.is_undefined());
5679    }
5680
5681    #[test]
5682    fn subagent_directories_use_strict_patch_semantics() {
5683        use serde_json::json;
5684
5685        let update = SubagentUpdate::new("child")
5686            .cwd("/home/user/project/.worktrees/investigator")
5687            .additional_directories(vec![]);
5688        let wire = json!({
5689            "sessionId": "child",
5690            "cwd": "/home/user/project/.worktrees/investigator",
5691            "additionalDirectories": []
5692        });
5693        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5694        assert_eq!(
5695            serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5696            update
5697        );
5698
5699        let inherited: SubagentUpdate =
5700            serde_json::from_value(json!({"sessionId": "child"})).unwrap();
5701        assert!(inherited.cwd.is_undefined());
5702        assert!(inherited.additional_directories.is_undefined());
5703
5704        let cleared_wire = json!({
5705            "sessionId": "child", "cwd": null, "additionalDirectories": null
5706        });
5707        let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5708        assert!(cleared.cwd.is_null());
5709        assert!(cleared.additional_directories.is_null());
5710        assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5711
5712        for malformed in [
5713            json!({"sessionId": "child", "cwd": false}),
5714            json!({"sessionId": "child", "additionalDirectories": "/tmp/wt"}),
5715            json!({"sessionId": "child", "additionalDirectories": ["/tmp/wt", false]}),
5716        ] {
5717            assert!(
5718                serde_json::from_value::<SubagentUpdate>(malformed.clone()).is_err(),
5719                "{malformed}"
5720            );
5721        }
5722    }
5723
5724    #[test]
5725    fn subagent_patch_fields_preserve_omitted_null_and_concrete() {
5726        use serde_json::json;
5727
5728        let omitted = SubagentUpdate::new("child");
5729        for field in ["title", "description", "capabilities", "state", "_meta"] {
5730            let wire = json!({"sessionId": "child", field: null});
5731            let decoded: SubagentUpdate = serde_json::from_value(wire.clone()).unwrap();
5732            assert_eq!(serde_json::to_value(decoded).unwrap(), wire, "{field}");
5733            let malformed = json!({"sessionId": "child", field: false});
5734            let decoded: SubagentUpdate = serde_json::from_value(malformed).unwrap();
5735            assert_eq!(decoded, omitted, "{field}");
5736        }
5737        let concrete = json!({
5738            "sessionId": "child", "title": "Investigator",
5739            "description": "Tests", "capabilities": {"cancel": {}},
5740            "state": {"state": "running"}, "_meta": {"source": "parent"}
5741        });
5742        let decoded: SubagentUpdate = serde_json::from_value(concrete.clone()).unwrap();
5743        assert!(decoded.title.value().is_some());
5744        assert!(decoded.description.value().is_some());
5745        assert!(decoded.capabilities.value().is_some());
5746        assert!(decoded.state.value().is_some());
5747        assert!(decoded.meta.value().is_some());
5748        assert_eq!(serde_json::to_value(decoded).unwrap(), concrete);
5749        let cleared = SubagentUpdate::new("child")
5750            .title(None)
5751            .description(None)
5752            .capabilities(None)
5753            .state(None)
5754            .meta(None);
5755        assert_eq!(
5756            serde_json::to_value(cleared).unwrap(),
5757            json!({
5758                "sessionId": "child", "title": null, "description": null,
5759                "capabilities": null, "state": null, "_meta": null
5760            })
5761        );
5762    }
5763
5764    #[test]
5765    fn test_subagent_notification_keeps_parent_and_child_ids_nested() {
5766        use serde_json::json;
5767
5768        let notification = SessionNotification::new(
5769            "parent",
5770            SessionUpdate::SubagentUpdate(SubagentUpdate::new("child")),
5771        );
5772        let wire = json!({
5773            "sessionId": "parent",
5774            "update": {
5775                "sessionUpdate": "subagent_update",
5776                "sessionId": "child"
5777            }
5778        });
5779        assert_eq!(serde_json::to_value(&notification).unwrap(), wire);
5780        assert_eq!(
5781            serde_json::from_value::<SessionNotification>(wire).unwrap(),
5782            notification
5783        );
5784        // Neither ID can stand in for the other: both nesting levels require one.
5785        for malformed in [
5786            json!({"sessionId": "parent", "update": {"sessionUpdate": "subagent_update"}}),
5787            json!({"update": {"sessionUpdate": "subagent_update", "sessionId": "child"}}),
5788        ] {
5789            assert!(serde_json::from_value::<SessionNotification>(malformed).is_err());
5790        }
5791    }
5792
5793    #[test]
5794    fn test_subagent_states_round_trip() {
5795        use serde_json::json;
5796
5797        for (wire_state, expected) in [
5798            (
5799                json!({"state": "running"}),
5800                StateUpdate::Running(RunningStateUpdate::new()),
5801            ),
5802            (
5803                json!({"state": "idle", "stopReason": "end_turn"}),
5804                StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn)),
5805            ),
5806            (
5807                json!({"state": "requires_action"}),
5808                StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5809            ),
5810            (
5811                json!({"state": "unknown"}),
5812                StateUpdate::Unknown(UnknownStateUpdate::new()),
5813            ),
5814            (
5815                json!({"state": "_waiting", "detail": {"ticket": 7}}),
5816                StateUpdate::Other(OtherStateUpdate::new(
5817                    "_waiting",
5818                    [("detail".into(), json!({"ticket": 7}))].into(),
5819                )),
5820            ),
5821            (
5822                json!({"state": "paused", "retryAt": 42}),
5823                StateUpdate::Other(OtherStateUpdate::new(
5824                    "paused",
5825                    [("retryAt".into(), json!(42))].into(),
5826                )),
5827            ),
5828        ] {
5829            let wire = json!({
5830                "sessionUpdate": "subagent_update",
5831                "sessionId": "sess_child",
5832                "state": wire_state
5833            });
5834            let parsed: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
5835            let SessionUpdate::SubagentUpdate(update) = &parsed else {
5836                panic!("expected subagent update");
5837            };
5838            assert_eq!(update.state.value(), Some(&expected));
5839            assert_eq!(serde_json::to_value(parsed).unwrap(), wire);
5840        }
5841
5842        for reason in [
5843            "end_turn",
5844            "max_tokens",
5845            "max_turn_requests",
5846            "refusal",
5847            "cancelled",
5848        ] {
5849            let state: StateUpdate = serde_json::from_value(json!({
5850                "state": "idle", "stopReason": reason
5851            }))
5852            .unwrap();
5853            assert_eq!(serde_json::to_value(state).unwrap()["stopReason"], reason);
5854        }
5855
5856        // Unknown activity is a replaceable snapshot, not a session outcome.
5857        // Later snapshots still address the same child without stale stop reasons.
5858        for state in [
5859            StateUpdate::Running(RunningStateUpdate::new()),
5860            StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5861            StateUpdate::Unknown(UnknownStateUpdate::new()),
5862            StateUpdate::Running(RunningStateUpdate::new()),
5863            StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn)),
5864            StateUpdate::Unknown(UnknownStateUpdate::new()),
5865            StateUpdate::Running(RunningStateUpdate::new()),
5866        ] {
5867            let update = SubagentUpdate::new("sess_child").state(state.clone());
5868            let wire = serde_json::to_value(&update).unwrap();
5869            assert_eq!(wire["sessionId"], "sess_child");
5870            assert_eq!(
5871                serde_json::from_value::<SubagentUpdate>(wire)
5872                    .unwrap()
5873                    .state,
5874                MaybeUndefined::Value(state)
5875            );
5876        }
5877        assert_eq!(
5878            serde_json::to_value(
5879                SubagentUpdate::new("sess_child").state(StateUpdate::Idle(IdleStateUpdate::new()))
5880            )
5881            .unwrap()["state"],
5882            json!({"state": "idle"})
5883        );
5884    }
5885
5886    #[test]
5887    fn subagent_idle_snapshot_reports_child_failure() {
5888        use serde_json::json;
5889
5890        let update = SubagentUpdate::new("sess_child").state(StateUpdate::Idle(
5891            IdleStateUpdate::new().stop_reason(IdleStopReason::from(
5892                ErrorStopReason::new().error(Error::auth_required()),
5893            )),
5894        ));
5895        let wire = json!({
5896            "sessionId": "sess_child",
5897            "state": {
5898                "state": "idle",
5899                "stopReason": "error",
5900                "error": { "code": -32000, "message": "Authentication required" }
5901            }
5902        });
5903        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5904        assert_eq!(
5905            serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5906            update
5907        );
5908
5909        // Missing, null, and malformed details still end the work as a failure.
5910        let without_details = StateUpdate::Idle(
5911            IdleStateUpdate::new().stop_reason(IdleStopReason::from(ErrorStopReason::new())),
5912        );
5913        for error in [None, Some(json!(null)), Some(json!("failed"))] {
5914            let mut wire = json!({ "state": "idle", "stopReason": "error" });
5915            if let Some(error) = error {
5916                wire["error"] = error;
5917            }
5918            assert_eq!(
5919                serde_json::from_value::<StateUpdate>(wire).unwrap(),
5920                without_details
5921            );
5922        }
5923
5924        // `error` belongs to the `error` stop reason; beside another one it is
5925        // an unknown field.
5926        let parsed: StateUpdate = serde_json::from_value(json!({
5927            "state": "idle",
5928            "stopReason": "end_turn",
5929            "error": { "code": -32603, "message": "Internal error" }
5930        }))
5931        .unwrap();
5932        assert_eq!(
5933            parsed,
5934            StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn))
5935        );
5936
5937        // Omitted, null, and malformed stop reasons mean none was reported,
5938        // and the rest of the snapshot survives.
5939        let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
5940        for stop_reason in [None, Some(json!(null)), Some(json!(true))] {
5941            let mut wire = json!({ "state": "idle", "_meta": { "source": "worker" } });
5942            if let Some(stop_reason) = stop_reason {
5943                wire["stopReason"] = stop_reason;
5944            }
5945            assert_eq!(
5946                serde_json::from_value::<StateUpdate>(wire).unwrap(),
5947                StateUpdate::Idle(IdleStateUpdate::new().meta(meta.clone()))
5948            );
5949        }
5950
5951        // Unknown stop reasons keep their own fields, as in v2, while the
5952        // snapshot's fields stay on the snapshot.
5953        for stop_reason in ["_paused", "not_a_reason"] {
5954            let wire = json!({
5955                "state": "idle",
5956                "stopReason": stop_reason,
5957                "resumeAfter": 30,
5958                "_meta": { "source": "worker" }
5959            });
5960            let parsed: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
5961            assert_eq!(
5962                parsed,
5963                StateUpdate::Idle(
5964                    IdleStateUpdate::new()
5965                        .stop_reason(IdleStopReason::Other(OtherStopReason::new(
5966                            stop_reason,
5967                            [("resumeAfter".into(), json!(30))].into_iter().collect(),
5968                        )))
5969                        .meta(meta.clone())
5970                )
5971            );
5972            assert_eq!(serde_json::to_value(&parsed).unwrap(), wire);
5973        }
5974    }
5975
5976    #[test]
5977    fn subagent_known_stop_reasons_are_never_read_as_other() {
5978        use serde_json::json;
5979
5980        let known = [
5981            IdleStopReason::EndTurn,
5982            IdleStopReason::MaxTokens,
5983            IdleStopReason::MaxTurnRequests,
5984            IdleStopReason::Refusal,
5985            IdleStopReason::Cancelled,
5986            IdleStopReason::Error(ErrorStopReason::new()),
5987        ];
5988        // Adding a variant breaks this match, so `known` stays complete.
5989        for stop_reason in &known {
5990            match stop_reason {
5991                IdleStopReason::EndTurn
5992                | IdleStopReason::MaxTokens
5993                | IdleStopReason::MaxTurnRequests
5994                | IdleStopReason::Refusal
5995                | IdleStopReason::Cancelled
5996                | IdleStopReason::Error(_)
5997                | IdleStopReason::Other(_) => {}
5998            }
5999        }
6000
6001        for stop_reason in known {
6002            let state = StateUpdate::Idle(IdleStateUpdate::new().stop_reason(stop_reason));
6003            let wire = serde_json::to_value(&state).unwrap();
6004            assert_eq!(
6005                serde_json::from_value::<StateUpdate>(wire.clone()).unwrap(),
6006                state
6007            );
6008            assert!(
6009                serde_json::from_value::<OtherStopReason>(
6010                    json!({ "stopReason": wire["stopReason"] })
6011                )
6012                .is_err(),
6013                "{} must not be accepted as a custom stop reason",
6014                wire["stopReason"]
6015            );
6016        }
6017    }
6018
6019    #[test]
6020    fn subagent_unknown_stop_reason_leaves_usage_on_the_snapshot() {
6021        use serde_json::json;
6022
6023        let usage = json!({ "totalTokens": 10, "inputTokens": 6, "outputTokens": 4 });
6024        let wire = json!({ "state": "idle", "stopReason": "_paused", "usage": usage });
6025        let StateUpdate::Idle(idle) = serde_json::from_value(wire).unwrap() else {
6026            panic!("expected idle state snapshot");
6027        };
6028        let Some(IdleStopReason::Other(other)) = &idle.stop_reason else {
6029            panic!("expected a custom stop reason");
6030        };
6031        assert!(other.fields.is_empty());
6032
6033        #[cfg(feature = "unstable_end_turn_token_usage")]
6034        {
6035            assert!(idle.usage.is_some());
6036            assert_eq!(serde_json::to_value(&idle).unwrap()["usage"], usage);
6037        }
6038        // Without the feature, `usage` is not a field of the snapshot, and it
6039        // must not be smuggled through as a field of the stop reason either.
6040        #[cfg(not(feature = "unstable_end_turn_token_usage"))]
6041        assert!(serde_json::to_value(&idle).unwrap().get("usage").is_none());
6042    }
6043
6044    #[test]
6045    fn test_subagent_unknown_activity_metadata_and_capabilities() {
6046        use serde_json::json;
6047
6048        let update = SubagentUpdate::new("child").state(StateUpdate::Unknown(
6049            UnknownStateUpdate::new().meta(
6050                [("source".into(), json!("worker"))]
6051                    .into_iter()
6052                    .collect::<Meta>(),
6053            ),
6054        ));
6055        let wire = json!({
6056            "sessionId": "child",
6057            "state": {
6058                "state": "unknown",
6059                "_meta": { "source": "worker" }
6060            }
6061        });
6062        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6063        assert_eq!(
6064            serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
6065            update
6066        );
6067        // Reporting unknown activity does not send a capability revocation.
6068        assert!(update.capabilities.is_undefined());
6069
6070        for meta in [json!(null), json!(false)] {
6071            let state: StateUpdate = serde_json::from_value(json!({
6072                "state": "unknown",
6073                "_meta": meta
6074            }))
6075            .unwrap();
6076            assert_eq!(state, StateUpdate::Unknown(UnknownStateUpdate::new()));
6077            assert_eq!(
6078                serde_json::to_value(state).unwrap(),
6079                json!({"state": "unknown"})
6080            );
6081        }
6082        // The standard unknown-activity report is recognized, not an extension fallback.
6083        assert!(serde_json::from_value::<OtherStateUpdate>(json!({"state": "unknown"})).is_err());
6084    }
6085
6086    #[test]
6087    fn test_subagent_malformed_optional_state() {
6088        use serde_json::json;
6089
6090        for malformed in [json!("running"), json!({}), json!({"state": 4})] {
6091            assert!(serde_json::from_value::<StateUpdate>(malformed.clone()).is_err());
6092            let update: SubagentUpdate = serde_json::from_value(json!({
6093                "sessionId": "child", "state": malformed
6094            }))
6095            .unwrap();
6096            assert!(update.state.is_undefined());
6097        }
6098        let bad_reason: StateUpdate =
6099            serde_json::from_value(json!({"state": "idle", "stopReason": false})).unwrap();
6100        assert_eq!(bad_reason, StateUpdate::Idle(IdleStateUpdate::new()));
6101        let null_reason: StateUpdate =
6102            serde_json::from_value(json!({"state": "idle", "stopReason": null})).unwrap();
6103        assert_eq!(null_reason, StateUpdate::Idle(IdleStateUpdate::new()));
6104    }
6105
6106    #[cfg(feature = "unstable_protocol_v2")]
6107    #[test]
6108    fn test_subagent_state_v2_wire_parity() {
6109        use serde_json::json;
6110
6111        for wire in [
6112            json!({"state": "running"}),
6113            json!({"state": "idle", "stopReason": "cancelled"}),
6114            json!({"state": "requires_action"}),
6115            json!({"state": "unknown"}),
6116            json!({"state": "unknown", "_meta": {"source": "worker"}}),
6117            json!({"state": "_waiting", "detail": {"ticket": 7}}),
6118        ] {
6119            let v1: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
6120            let v2: crate::v2::StateUpdate = serde_json::from_value(wire.clone()).unwrap();
6121            assert_eq!(serde_json::to_value(v1).unwrap(), wire);
6122            assert_eq!(serde_json::to_value(v2).unwrap(), wire);
6123        }
6124    }
6125
6126    #[test]
6127    fn test_subagent_capability_semantics() {
6128        use serde_json::json;
6129
6130        let capabilities =
6131            serde_json::to_value(ClientCapabilities::new().subagents(SubagentCapabilities::new()))
6132                .unwrap();
6133        assert_eq!(capabilities["subagents"], json!({}));
6134
6135        let omitted: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6136        assert!(omitted.subagents.is_none());
6137
6138        let null: ClientCapabilities =
6139            serde_json::from_value(json!({ "subagents": null })).unwrap();
6140        assert!(null.subagents.is_none());
6141        assert_eq!(null, omitted);
6142        let serialized = serde_json::to_value(null).unwrap();
6143        assert_eq!(serialized, serde_json::to_value(omitted).unwrap());
6144        assert!(serialized.get("subagents").is_none());
6145
6146        for wire in [
6147            json!({}),
6148            json!({"cancel": null}),
6149            json!({"cancel": true}),
6150            json!({"cancel": false}),
6151        ] {
6152            let child: SubagentSessionCapabilities = serde_json::from_value(wire).unwrap();
6153            assert!(child.cancel.is_none());
6154            assert_eq!(serde_json::to_value(child).unwrap(), json!({}));
6155        }
6156        let enabled = SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new());
6157        assert_eq!(
6158            serde_json::to_value(&enabled).unwrap(),
6159            json!({"cancel": {}})
6160        );
6161        assert_eq!(
6162            serde_json::from_value::<SubagentSessionCapabilities>(json!({"cancel": {}})).unwrap(),
6163            enabled
6164        );
6165        let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
6166        let with_meta =
6167            SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new().meta(meta));
6168        let wire = json!({"cancel": {"_meta": {"source": "worker"}}});
6169        assert_eq!(serde_json::to_value(&with_meta).unwrap(), wire);
6170        assert_eq!(
6171            serde_json::from_value::<SubagentSessionCapabilities>(wire).unwrap(),
6172            with_meta
6173        );
6174        // Each supplied child capability set replaces the previous set.
6175        let removed = SubagentSessionCapabilities::new();
6176        assert_eq!(serde_json::to_value(&removed).unwrap(), json!({}));
6177        assert!(removed.cancel.is_none());
6178        assert!(enabled.cancel.is_some());
6179        assert!(enabled.cancel(None).cancel.is_none());
6180        let replacement = SubagentUpdate::new("child").capabilities(removed);
6181        assert_eq!(
6182            serde_json::to_value(replacement).unwrap(),
6183            json!({"sessionId": "child", "capabilities": {}})
6184        );
6185    }
6186
6187    #[cfg(feature = "schemars")]
6188    #[test]
6189    fn test_subagent_capability_schema_is_optional_and_nullable() {
6190        use serde_json::json;
6191
6192        let schema = serde_json::to_value(schemars::schema_for!(ClientCapabilities)).unwrap();
6193        let variants = schema["properties"]["subagents"]["anyOf"]
6194            .as_array()
6195            .expect("subagents must allow the capability object or null");
6196        assert!(variants.contains(&json!({"type": "null"})));
6197        assert!(
6198            !schema["required"]
6199                .as_array()
6200                .is_some_and(|required| required.contains(&json!("subagents")))
6201        );
6202        let child =
6203            serde_json::to_value(schemars::schema_for!(SubagentSessionCapabilities)).unwrap();
6204        let variants = child["properties"]["cancel"]["anyOf"]
6205            .as_array()
6206            .expect("cancel must allow the capability object or null");
6207        assert!(variants.contains(&json!({"type": "null"})));
6208        assert!(
6209            variants
6210                .iter()
6211                .any(|variant| variant["type"] == "object" || variant.get("$ref").is_some())
6212        );
6213        assert!(!variants.iter().any(|variant| variant["type"] == "boolean"));
6214        let cancel =
6215            serde_json::to_value(schemars::schema_for!(SessionCancelCapabilities)).unwrap();
6216        assert_eq!(cancel["type"], "object");
6217        assert!(
6218            !child["required"]
6219                .as_array()
6220                .is_some_and(|required| required.contains(&json!("cancel")))
6221        );
6222    }
6223
6224    #[test]
6225    fn test_elicitation_capability_semantics() {
6226        use serde_json::json;
6227
6228        let unsupported: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6229        assert!(unsupported.elicitation.is_none());
6230
6231        let null: ClientCapabilities =
6232            serde_json::from_value(json!({ "elicitation": null })).unwrap();
6233        assert!(null.elicitation.is_none());
6234
6235        let malformed: ClientCapabilities =
6236            serde_json::from_value(json!({ "elicitation": false })).unwrap();
6237        assert!(malformed.elicitation.is_none());
6238
6239        let empty: ClientCapabilities =
6240            serde_json::from_value(json!({ "elicitation": {} })).unwrap();
6241        let empty = empty.elicitation.expect("present capability");
6242        assert!(!empty.supports_form());
6243        assert!(!empty.supports_url());
6244
6245        let form_only: ClientCapabilities = serde_json::from_value(json!({
6246            "elicitation": { "form": {} }
6247        }))
6248        .unwrap();
6249        let form_only = form_only.elicitation.expect("advertised capability");
6250        assert!(form_only.supports_form());
6251        assert!(!form_only.supports_url());
6252
6253        let url_only: ClientCapabilities = serde_json::from_value(json!({
6254            "elicitation": { "url": {} }
6255        }))
6256        .unwrap();
6257        let url_only = url_only.elicitation.expect("advertised capability");
6258        assert!(!url_only.supports_form());
6259        assert!(url_only.supports_url());
6260
6261        let both: ClientCapabilities = serde_json::from_value(json!({
6262            "elicitation": { "form": {}, "url": {} }
6263        }))
6264        .unwrap();
6265        let both = both.elicitation.expect("advertised capability");
6266        assert!(both.supports_form());
6267        assert!(both.supports_url());
6268    }
6269
6270    #[test]
6271    fn test_elicitation_method_routing_and_envelopes() {
6272        use serde_json::json;
6273
6274        assert_eq!(CLIENT_METHOD_NAMES.elicitation_create, "elicitation/create");
6275        assert_eq!(
6276            CLIENT_METHOD_NAMES.elicitation_complete,
6277            "elicitation/complete"
6278        );
6279
6280        let request = AgentRequest::CreateElicitationRequest(CreateElicitationRequest::new(
6281            crate::v1::ElicitationFormMode::new(
6282                crate::v1::ElicitationSessionScope::new("sess_1"),
6283                crate::v1::ElicitationSchema::new(),
6284            ),
6285            "Choose a value",
6286        ));
6287        assert_eq!(request.method(), "elicitation/create");
6288        let method = Arc::from(request.method());
6289        let request = crate::v1::JsonRpcMessage::wrap(crate::v1::Request {
6290            id: crate::v1::RequestId::Number(7),
6291            method,
6292            params: Some(request),
6293        });
6294        assert_eq!(
6295            serde_json::to_value(request).unwrap(),
6296            json!({
6297                "jsonrpc": "2.0",
6298                "id": 7,
6299                "method": "elicitation/create",
6300                "params": {
6301                    "mode": "form",
6302                    "sessionId": "sess_1",
6303                    "message": "Choose a value",
6304                    "requestedSchema": { "type": "object", "properties": {} }
6305                }
6306            })
6307        );
6308
6309        let notification = AgentNotification::CompleteElicitationNotification(
6310            CompleteElicitationNotification::new("elic_1"),
6311        );
6312        assert_eq!(notification.method(), "elicitation/complete");
6313        let method = Arc::from(notification.method());
6314        let notification = crate::v1::JsonRpcMessage::wrap(crate::v1::Notification {
6315            method,
6316            params: Some(notification),
6317        });
6318        assert_eq!(
6319            serde_json::to_value(notification).unwrap(),
6320            json!({
6321                "jsonrpc": "2.0",
6322                "method": "elicitation/complete",
6323                "params": { "elicitationId": "elic_1" }
6324            })
6325        );
6326    }
6327
6328    #[test]
6329    fn test_client_capabilities_default_on_malformed_values() {
6330        use serde_json::json;
6331
6332        let capabilities: ClientCapabilities = serde_json::from_value(json!({
6333            "fs": {
6334                "readTextFile": "yes",
6335                "writeTextFile": true
6336            },
6337            "terminal": {}
6338        }))
6339        .unwrap();
6340
6341        assert!(!capabilities.fs.read_text_file);
6342        assert!(capabilities.fs.write_text_file);
6343        assert!(!capabilities.terminal);
6344
6345        let capabilities: ClientCapabilities = serde_json::from_value(json!({
6346            "fs": false
6347        }))
6348        .unwrap();
6349        assert_eq!(capabilities.fs, FileSystemCapabilities::default());
6350
6351        {
6352            let capabilities: ClientCapabilities = serde_json::from_value(json!({
6353                "auth": false
6354            }))
6355            .unwrap();
6356            assert_eq!(capabilities.auth, AuthCapabilities::default());
6357
6358            let capabilities: AuthCapabilities = serde_json::from_value(json!({
6359                "terminal": {}
6360            }))
6361            .unwrap();
6362            assert!(!capabilities.terminal);
6363        }
6364    }
6365
6366    #[test]
6367    fn test_serialization_behavior() {
6368        use serde_json::json;
6369
6370        assert_eq!(
6371            serde_json::from_value::<SessionInfoUpdate>(json!({})).unwrap(),
6372            SessionInfoUpdate {
6373                title: MaybeUndefined::Undefined,
6374                updated_at: MaybeUndefined::Undefined,
6375                meta: None
6376            }
6377        );
6378        assert_eq!(
6379            serde_json::from_value::<SessionInfoUpdate>(json!({"title": null, "updatedAt": null}))
6380                .unwrap(),
6381            SessionInfoUpdate {
6382                title: MaybeUndefined::Null,
6383                updated_at: MaybeUndefined::Null,
6384                meta: None
6385            }
6386        );
6387        assert_eq!(
6388            serde_json::from_value::<SessionInfoUpdate>(
6389                json!({"title": "title", "updatedAt": "timestamp"})
6390            )
6391            .unwrap(),
6392            SessionInfoUpdate {
6393                title: MaybeUndefined::Value("title".to_string()),
6394                updated_at: MaybeUndefined::Value("timestamp".to_string()),
6395                meta: None
6396            }
6397        );
6398
6399        assert_eq!(
6400            serde_json::to_value(SessionInfoUpdate::new()).unwrap(),
6401            json!({})
6402        );
6403        assert_eq!(
6404            serde_json::to_value(SessionInfoUpdate::new().title("title")).unwrap(),
6405            json!({"title": "title"})
6406        );
6407        assert_eq!(
6408            serde_json::to_value(SessionInfoUpdate::new().title(None)).unwrap(),
6409            json!({"title": null})
6410        );
6411        assert_eq!(
6412            serde_json::to_value(
6413                SessionInfoUpdate::new()
6414                    .title("title")
6415                    .title(MaybeUndefined::Undefined)
6416            )
6417            .unwrap(),
6418            json!({})
6419        );
6420    }
6421
6422    #[test]
6423    fn test_content_chunk_message_id_serialization() {
6424        use serde_json::json;
6425
6426        assert_eq!(
6427            serde_json::to_value(SessionUpdate::AgentMessageChunk(ContentChunk::new(
6428                ContentBlock::Text(crate::v1::TextContent::new("Hello"))
6429            )))
6430            .unwrap(),
6431            json!({
6432                "sessionUpdate": "agent_message_chunk",
6433                "content": {
6434                    "type": "text",
6435                    "text": "Hello"
6436                }
6437            })
6438        );
6439
6440        assert_eq!(
6441            serde_json::to_value(SessionUpdate::AgentMessageChunk(
6442                ContentChunk::new(ContentBlock::Text(crate::v1::TextContent::new("Hello")))
6443                    .message_id("msg_agent_c42b9")
6444            ))
6445            .unwrap(),
6446            json!({
6447                "sessionUpdate": "agent_message_chunk",
6448                "messageId": "msg_agent_c42b9",
6449                "content": {
6450                    "type": "text",
6451                    "text": "Hello"
6452                }
6453            })
6454        );
6455
6456        let SessionUpdate::AgentMessageChunk(chunk) = serde_json::from_value(json!({
6457            "sessionUpdate": "agent_message_chunk",
6458            "messageId": null,
6459            "content": {
6460                "type": "text",
6461                "text": "Hello"
6462            }
6463        }))
6464        .unwrap() else {
6465            panic!("expected agent message chunk");
6466        };
6467
6468        assert_eq!(chunk.message_id, None);
6469    }
6470
6471    #[test]
6472    fn test_usage_update_serialization() {
6473        use serde_json::json;
6474
6475        assert_eq!(
6476            serde_json::to_value(SessionUpdate::UsageUpdate(UsageUpdate::new(
6477                53_000, 200_000
6478            )))
6479            .unwrap(),
6480            json!({
6481                "sessionUpdate": "usage_update",
6482                "used": 53000,
6483                "size": 200_000
6484            })
6485        );
6486
6487        assert_eq!(
6488            serde_json::to_value(SessionUpdate::UsageUpdate(
6489                UsageUpdate::new(53_000, 200_000).cost(Cost::new(0.045, "USD"))
6490            ))
6491            .unwrap(),
6492            json!({
6493                "sessionUpdate": "usage_update",
6494                "used": 53000,
6495                "size": 200_000,
6496                "cost": {
6497                    "amount": 0.045,
6498                    "currency": "USD"
6499                }
6500            })
6501        );
6502
6503        let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
6504            "sessionUpdate": "usage_update",
6505            "used": 53000,
6506            "size": 200_000,
6507            "cost": null
6508        }))
6509        .unwrap() else {
6510            panic!("expected usage update");
6511        };
6512
6513        assert_eq!(update.cost, None);
6514    }
6515
6516    #[test]
6517    fn test_client_capabilities_boolean_config_options_serialization() {
6518        use serde_json::json;
6519
6520        let capabilities = ClientCapabilities::new().session(
6521            ClientSessionCapabilities::new().config_options(
6522                SessionConfigOptionsCapabilities::new()
6523                    .boolean(BooleanConfigOptionCapabilities::new()),
6524            ),
6525        );
6526        let json = serde_json::to_value(&capabilities).unwrap();
6527
6528        assert_eq!(json["session"]["configOptions"]["boolean"], json!({}));
6529
6530        let omitted: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6531        assert!(omitted.session.is_none());
6532
6533        let null_session: ClientCapabilities = serde_json::from_value(json!({
6534            "session": null
6535        }))
6536        .unwrap();
6537        assert!(null_session.session.is_none());
6538
6539        let null_config_options: ClientCapabilities = serde_json::from_value(json!({
6540            "session": {
6541                "configOptions": null
6542            }
6543        }))
6544        .unwrap();
6545        assert!(
6546            null_config_options
6547                .session
6548                .and_then(|session| session.config_options)
6549                .is_none()
6550        );
6551
6552        let null_boolean: ClientCapabilities = serde_json::from_value(json!({
6553            "session": {
6554                "configOptions": {
6555                    "boolean": null
6556                }
6557            }
6558        }))
6559        .unwrap();
6560        assert!(
6561            null_boolean
6562                .session
6563                .and_then(|session| session.config_options)
6564                .and_then(|config_options| config_options.boolean)
6565                .is_none()
6566        );
6567    }
6568
6569    #[test]
6570    fn test_plan_operations_serialization() {
6571        use serde_json::json;
6572
6573        use crate::v1::{PlanEntry, PlanEntryPriority, PlanEntryStatus, PlanUpdateContent};
6574
6575        let plan_update = SessionUpdate::PlanUpdate(PlanUpdate::new(PlanUpdateContent::items(
6576            "plan-1",
6577            vec![PlanEntry::new(
6578                "Step 1",
6579                PlanEntryPriority::High,
6580                PlanEntryStatus::Pending,
6581            )],
6582        )));
6583
6584        assert_eq!(
6585            serde_json::to_value(plan_update).unwrap(),
6586            json!({
6587                "sessionUpdate": "plan_update",
6588                "plan": {
6589                    "type": "items",
6590                    "planId": "plan-1",
6591                    "entries": [
6592                        {
6593                            "content": "Step 1",
6594                            "priority": "high",
6595                            "status": "pending"
6596                        }
6597                    ]
6598                }
6599            })
6600        );
6601
6602        assert_eq!(
6603            serde_json::to_value(SessionUpdate::PlanRemoved(PlanRemoved::new("plan-1"))).unwrap(),
6604            json!({
6605                "sessionUpdate": "plan_removed",
6606                "planId": "plan-1"
6607            })
6608        );
6609
6610        let markdown = json!({
6611            "sessionUpdate": "plan_update",
6612            "plan": {
6613                "type": "markdown", "planId": "plan-1",
6614                "content": "# Next steps", "path": "/workspace/plan.md"
6615            }
6616        });
6617        let update: SessionUpdate = serde_json::from_value(markdown.clone()).unwrap();
6618        assert_eq!(serde_json::to_value(update).unwrap(), markdown);
6619
6620        let capabilities = ClientCapabilities::new().plan(PlanCapabilities::new());
6621        let json = serde_json::to_value(&capabilities).unwrap();
6622        assert_eq!(json["plan"], json!({}));
6623
6624        assert_eq!(
6625            serde_json::from_value::<ClientCapabilities>(json!({ "plan": null }))
6626                .unwrap()
6627                .plan,
6628            None
6629        );
6630    }
6631
6632    #[cfg(feature = "unstable_mcp_over_acp")]
6633    #[test]
6634    fn test_agent_mcp_request_method_names() {
6635        use serde_json::json;
6636
6637        let params: serde_json::Map<String, serde_json::Value> =
6638            [("cursor".to_string(), json!("abc"))].into_iter().collect();
6639
6640        assert_eq!(CLIENT_METHOD_NAMES.mcp_message, "mcp/message");
6641        assert_eq!(
6642            AgentRequest::MessageMcpRequest(MessageMcpRequest::new(
6643                "server-1",
6644                "req-1",
6645                "tools/list"
6646            ))
6647            .method(),
6648            "mcp/message"
6649        );
6650        assert_eq!(
6651            serde_json::to_value(
6652                MessageMcpRequest::new("server-1", "req-1", "tools/list").params(params)
6653            )
6654            .unwrap(),
6655            json!({
6656                "serverId": "server-1",
6657                "requestId": "req-1",
6658                "method": "tools/list",
6659                "params": { "cursor": "abc" }
6660            })
6661        );
6662
6663        let request_with_null_params: MessageMcpRequest = serde_json::from_value(json!({
6664            "serverId": "server-1",
6665            "requestId": "req-1",
6666            "method": "tools/list",
6667            "params": null,
6668            "_meta": null
6669        }))
6670        .unwrap();
6671        assert_eq!(request_with_null_params.params, None);
6672        assert_eq!(request_with_null_params.meta, None);
6673        for key in ["serverId", "requestId", "method"] {
6674            let mut value =
6675                json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
6676            value.as_object_mut().unwrap().remove(key);
6677            assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
6678        }
6679        for key in ["serverId", "requestId", "method"] {
6680            let mut value =
6681                json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
6682            value[key] = serde_json::Value::Null;
6683            assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
6684        }
6685    }
6686
6687    #[test]
6688    fn request_permission_request_rejects_malformed_options() {
6689        use serde_json::json;
6690
6691        assert!(
6692            serde_json::from_value::<RequestPermissionRequest>(json!({
6693                "sessionId": "sess-1",
6694                "toolCall": {"toolCallId": "tc-1"},
6695                "options": "not-an-array"
6696            }))
6697            .is_err()
6698        );
6699        assert!(
6700            serde_json::from_value::<RequestPermissionRequest>(json!({
6701                "sessionId": "sess-1",
6702                "toolCall": {"toolCallId": "tc-1"},
6703                "options": [{"optionId": "allow"}]
6704            }))
6705            .is_err()
6706        );
6707    }
6708
6709    #[test]
6710    fn create_terminal_request_rejects_malformed_fields() {
6711        use serde_json::json;
6712
6713        let request = |field: &str, value: serde_json::Value| {
6714            let mut request = json!({"sessionId": "sess-1", "command": "npx"});
6715            request[field] = value;
6716            serde_json::from_value::<CreateTerminalRequest>(request)
6717        };
6718
6719        // Defaulting any of these would run a different command than requested.
6720        for (field, value) in [
6721            ("args", json!(["serve", "--port", 3000])),
6722            ("args", json!("serve --port 3000")),
6723            ("env", json!([{"name": "PORT", "value": 3000}])),
6724            ("env", json!({"PORT": "3000"})),
6725            ("cwd", json!({"path": "/repo"})),
6726            ("outputByteLimit", json!("1048576")),
6727        ] {
6728            assert!(request(field, value.clone()).is_err(), "{field}: {value}");
6729        }
6730
6731        for field in ["args", "env", "cwd", "outputByteLimit"] {
6732            assert_eq!(
6733                request(field, serde_json::Value::Null).unwrap(),
6734                CreateTerminalRequest::new("sess-1", "npx"),
6735                "{field}"
6736            );
6737        }
6738    }
6739
6740    #[test]
6741    fn read_text_file_request_rejects_malformed_range() {
6742        use serde_json::json;
6743
6744        let request = |field: &str, value: serde_json::Value| {
6745            let mut request = json!({"sessionId": "sess-1", "path": "/repo/src/main.rs"});
6746            request[field] = value;
6747            serde_json::from_value::<ReadTextFileRequest>(request)
6748        };
6749
6750        // Defaulting either bound would return a different part of the file.
6751        for field in ["line", "limit"] {
6752            assert!(request(field, json!("120")).is_err(), "{field}");
6753            assert!(request(field, json!(-1)).is_err(), "{field}");
6754            assert_eq!(
6755                request(field, serde_json::Value::Null).unwrap(),
6756                ReadTextFileRequest::new("sess-1", "/repo/src/main.rs"),
6757                "{field}"
6758            );
6759        }
6760    }
6761
6762    #[cfg(feature = "unstable_session_cursors")]
6763    #[test]
6764    fn cursor_updates_round_trip_and_patch_capabilities() {
6765        use serde_json::json;
6766
6767        let update = SessionUpdate::CursorUpdate(
6768            CursorUpdate::new("cur_1")
6769                .capabilities(CursorCapabilities::new())
6770                .anchor(CursorAnchor::UserMessage(CursorMessageAnchor::new(
6771                    "msg_user_2",
6772                    CursorAnchorPosition::Before,
6773                ))),
6774        );
6775        let wire = json!({
6776            "sessionUpdate": "cursor_update",
6777            "cursorId": "cur_1",
6778            "capabilities": {},
6779            "anchor": { "type": "user_message", "messageId": "msg_user_2", "position": "before" }
6780        });
6781        assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6782        assert_eq!(
6783            serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6784            update
6785        );
6786
6787        // A later update can carry the ID alone. Nothing is changed.
6788        let SessionUpdate::CursorUpdate(omitted) = serde_json::from_value(json!({
6789            "sessionUpdate": "cursor_update",
6790            "cursorId": "cur_1"
6791        }))
6792        .unwrap() else {
6793            panic!("expected cursor update");
6794        };
6795        assert!(omitted.capabilities.is_undefined());
6796        assert_eq!(omitted.anchor, None);
6797        assert!(omitted.meta.is_undefined());
6798        assert_eq!(
6799            serde_json::to_value(SessionUpdate::CursorUpdate(CursorUpdate::new("cur_1"))).unwrap(),
6800            json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1" })
6801        );
6802
6803        // `null` clears the capabilities. A `null` anchor is the same as an omitted one.
6804        let SessionUpdate::CursorUpdate(cleared) = serde_json::from_value(json!({
6805            "sessionUpdate": "cursor_update",
6806            "cursorId": "cur_1",
6807            "capabilities": null,
6808            "anchor": null
6809        }))
6810        .unwrap() else {
6811            panic!("expected cursor update");
6812        };
6813        assert!(cleared.capabilities.is_null());
6814        assert_eq!(cleared.anchor, None);
6815        assert_eq!(
6816            serde_json::to_value(SessionUpdate::CursorUpdate(
6817                CursorUpdate::new("cur_1").capabilities(None)
6818            ))
6819            .unwrap(),
6820            json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1", "capabilities": null })
6821        );
6822    }
6823
6824    #[cfg(feature = "unstable_session_cursors")]
6825    #[test]
6826    fn cursor_anchors_cover_each_entity_type_and_preserve_unknown_ones() {
6827        use serde_json::json;
6828
6829        for (anchor, wire) in [
6830            (
6831                CursorAnchor::AgentMessage(CursorMessageAnchor::new(
6832                    "msg_agent_1",
6833                    CursorAnchorPosition::After,
6834                )),
6835                json!({ "type": "agent_message", "messageId": "msg_agent_1", "position": "after" }),
6836            ),
6837            (
6838                CursorAnchor::AgentThought(CursorMessageAnchor::new(
6839                    "msg_agent_1",
6840                    CursorAnchorPosition::After,
6841                )),
6842                json!({ "type": "agent_thought", "messageId": "msg_agent_1", "position": "after" }),
6843            ),
6844            (
6845                CursorAnchor::SessionMessage(CursorMessageAnchor::new(
6846                    "msg_session_1",
6847                    CursorAnchorPosition::Before,
6848                )),
6849                json!({ "type": "session_message", "messageId": "msg_session_1", "position": "before" }),
6850            ),
6851            (
6852                CursorAnchor::ToolCall(CursorToolCallAnchor::new(
6853                    "call_1",
6854                    CursorAnchorPosition::After,
6855                )),
6856                json!({ "type": "tool_call", "toolCallId": "call_1", "position": "after" }),
6857            ),
6858            (
6859                CursorAnchor::Compaction(CursorCompactionAnchor::new(
6860                    "cmp_1",
6861                    CursorAnchorPosition::Before,
6862                )),
6863                json!({ "type": "compaction", "compactionId": "cmp_1", "position": "before" }),
6864            ),
6865        ] {
6866            assert_eq!(serde_json::to_value(&anchor).unwrap(), wire);
6867            assert_eq!(
6868                serde_json::from_value::<CursorAnchor>(wire).unwrap(),
6869                anchor
6870            );
6871        }
6872
6873        // An unknown anchor type keeps its payload.
6874        let wire = json!({ "type": "_acme_marker", "markerId": "mk_1", "position": "after" });
6875        let other = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
6876        assert!(matches!(other, CursorAnchor::Other(_)));
6877        assert_eq!(serde_json::to_value(&other).unwrap(), wire);
6878
6879        // An unknown position keeps its value.
6880        let wire =
6881            json!({ "type": "user_message", "messageId": "msg_user_2", "position": "inside" });
6882        let future = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
6883        assert_eq!(
6884            future,
6885            CursorAnchor::UserMessage(CursorMessageAnchor::new(
6886                "msg_user_2",
6887                CursorAnchorPosition::Other("inside".into()),
6888            ))
6889        );
6890        assert_eq!(serde_json::to_value(&future).unwrap(), wire);
6891    }
6892
6893    #[cfg(feature = "unstable_session_cursors")]
6894    #[test]
6895    fn malformed_cursor_anchor_fails_the_update() {
6896        use serde_json::json;
6897
6898        // A wrong anchor would place the cursor somewhere else, so it is never defaulted.
6899        for anchor in [
6900            json!({ "type": "user_message", "position": "before" }),
6901            json!({ "type": "tool_call", "toolCallId": 7, "position": "after" }),
6902            json!({ "type": "compaction", "compactionId": "cmp_1" }),
6903            json!({ "messageId": "msg_user_2", "position": "before" }),
6904            json!("before"),
6905        ] {
6906            assert!(
6907                serde_json::from_value::<SessionUpdate>(json!({
6908                    "sessionUpdate": "cursor_update",
6909                    "cursorId": "cur_1",
6910                    "anchor": anchor
6911                }))
6912                .is_err(),
6913                "{anchor}"
6914            );
6915        }
6916        assert!(
6917            serde_json::from_value::<SessionUpdate>(json!({ "sessionUpdate": "cursor_update" }))
6918                .is_err()
6919        );
6920    }
6921
6922    #[cfg(feature = "unstable_session_cursors")]
6923    #[test]
6924    fn malformed_cursor_capabilities_are_not_advertised() {
6925        use serde_json::json;
6926
6927        // Malformed capabilities are treated as omitted. The update still parses.
6928        let SessionUpdate::CursorUpdate(update) = serde_json::from_value(json!({
6929            "sessionUpdate": "cursor_update",
6930            "cursorId": "cur_1",
6931            "capabilities": "fork"
6932        }))
6933        .unwrap() else {
6934            panic!("expected cursor update");
6935        };
6936        assert!(update.capabilities.is_undefined());
6937
6938        // Capabilities this implementation does not know are ignored.
6939        assert_eq!(
6940            serde_json::from_value::<CursorCapabilities>(json!({ "futureMethod": {} })).unwrap(),
6941            CursorCapabilities::new()
6942        );
6943
6944        #[cfg(feature = "unstable_session_fork")]
6945        {
6946            assert_eq!(
6947                serde_json::to_value(CursorCapabilities::new().fork(CursorForkCapabilities::new()))
6948                    .unwrap(),
6949                json!({ "fork": {} })
6950            );
6951            assert_eq!(
6952                serde_json::from_value::<CursorCapabilities>(json!({ "fork": {} }))
6953                    .unwrap()
6954                    .fork,
6955                Some(CursorForkCapabilities::new())
6956            );
6957            for fork in [json!(null), json!(true), json!("yes")] {
6958                assert_eq!(
6959                    serde_json::from_value::<CursorCapabilities>(json!({ "fork": fork }))
6960                        .unwrap()
6961                        .fork,
6962                    None
6963                );
6964            }
6965        }
6966    }
6967
6968    #[cfg(feature = "unstable_session_cursors")]
6969    #[test]
6970    fn client_session_cursors_capability_is_optional_and_lenient() {
6971        use serde_json::json;
6972
6973        assert_eq!(
6974            serde_json::to_value(
6975                ClientSessionCapabilities::new().cursors(SessionCursorsCapabilities::new())
6976            )
6977            .unwrap(),
6978            json!({ "cursors": {} })
6979        );
6980        assert_eq!(
6981            serde_json::from_value::<ClientSessionCapabilities>(json!({ "cursors": {} }))
6982                .unwrap()
6983                .cursors,
6984            Some(SessionCursorsCapabilities::new())
6985        );
6986        for wire in [
6987            json!({}),
6988            json!({ "cursors": null }),
6989            json!({ "cursors": "yes" }),
6990        ] {
6991            assert_eq!(
6992                serde_json::from_value::<ClientSessionCapabilities>(wire)
6993                    .unwrap()
6994                    .cursors,
6995                None
6996            );
6997        }
6998    }
6999}