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