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