Skip to main content

agent_client_protocol_schema/v2/
tool_call.rs

1//! Tool calls represent actions that language models request agents to perform.
2//!
3//! Examples include reading a file or running a command. The agent executes the tool call on
4//! the model's behalf and reports its progress to the client.
5//!
6/// See protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls)
7use std::{collections::BTreeMap, sync::Arc};
8
9use derive_more::{Display, From};
10#[cfg(feature = "schemars")]
11use schemars::Schema;
12use serde::{Deserialize, Serialize};
13use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
14
15use super::SessionId;
16use super::{AbsolutePath, ContentBlock, MediaType, Meta, Terminal, apply_meta_update};
17use crate::{IntoMaybeUndefined, IntoOption, MaybeUndefined};
18
19/// Represents an upsert for a tool call that the language model has requested.
20///
21/// Tool calls are actions that the agent executes on behalf of the language model,
22/// such as reading files, executing code, or fetching data from external sources.
23///
24/// Only `toolCallId` is required. Other fields have patch semantics:
25/// omitted fields leave the existing tool call value unchanged, `null` clears or
26/// unsets the value, and concrete values replace the previous value. For
27/// collection fields, concrete arrays replace the previous collection, and both
28/// `null` and `[]` clear the collection. A concrete `_meta` object instead
29/// patches the stored metadata by top-level key. When a client receives a tool
30/// call ID it has not seen before, omitted fields start at their protocol defaults.
31///
32/// See protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls)
33#[serde_as]
34#[skip_serializing_none]
35#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "camelCase")]
38#[non_exhaustive]
39pub struct ToolCallUpdate {
40    /// Unique identifier for this tool call within the session.
41    pub tool_call_id: ToolCallId,
42    /// Programmatic name of the tool being invoked.
43    ///
44    /// This field is optional and has patch semantics. Omission means no
45    /// change, `null` clears the name, and a string replaces it. For a tool
46    /// call ID the client has not seen before, omission or `null` means that no
47    /// tool name is available.
48    #[serde_as(deserialize_as = "DefaultOnError")]
49    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
50    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
51    pub name: MaybeUndefined<String>,
52    /// Human-readable title describing what the tool is doing.
53    ///
54    /// Omission leaves the title unchanged, `null` unsets it, and a string replaces it.
55    /// A new tool call starts without a title.
56    #[serde_as(deserialize_as = "DefaultOnError")]
57    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
58    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
59    pub title: MaybeUndefined<String>,
60    /// The category of tool being invoked.
61    /// Helps clients choose appropriate icons and UI treatment.
62    ///
63    /// Omission leaves the kind unchanged, `null` resets it to `other`, and a value replaces it.
64    /// A new tool call starts as `other`.
65    #[serde_as(deserialize_as = "DefaultOnError")]
66    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
67    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
68    pub kind: MaybeUndefined<ToolKind>,
69    /// Current execution status of the tool call.
70    ///
71    /// Omission leaves the status unchanged, `null` resets it to `pending`, and a value
72    /// replaces it. A new tool call starts as `pending`. Agents do not move a tool call
73    /// back to `pending` once it has another status.
74    #[serde_as(deserialize_as = "DefaultOnError")]
75    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
76    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
77    pub status: MaybeUndefined<ToolCallStatus>,
78    /// Content produced by the tool call.
79    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
80    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
81    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
82    pub content: MaybeUndefined<Vec<ToolCallContent>>,
83    /// File locations affected by this tool call.
84    /// Enables "follow-along" features in clients.
85    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
86    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
87    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
88    pub locations: MaybeUndefined<Vec<ToolCallLocation>>,
89    /// Raw input parameters sent to the tool.
90    #[serde_as(deserialize_as = "DefaultOnError")]
91    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
92    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
93    pub raw_input: MaybeUndefined<serde_json::Value>,
94    /// Raw output returned by the tool.
95    #[serde_as(deserialize_as = "DefaultOnError")]
96    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
97    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
98    pub raw_output: MaybeUndefined<serde_json::Value>,
99    /// Client-initiated controls this tool call currently supports, such as cancellation.
100    ///
101    /// Omission leaves the capabilities unchanged, `null` clears them, and an object replaces
102    /// the whole previous value. A new tool call starts with none.
103    #[serde_as(deserialize_as = "DefaultOnError")]
104    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
105    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
106    pub capabilities: MaybeUndefined<ToolCallCapabilities>,
107    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
108    /// metadata to their interactions. Omitted leaves the stored metadata unchanged. `null`
109    /// clears it. An object patches the stored metadata by top-level key: keys it omits are
110    /// unchanged, a key set to `null` is removed, and any other value replaces that key's
111    /// stored value without merging nested objects. Beyond this patch rule, implementations
112    /// MUST NOT assign meaning to keys they do not recognize.
113    ///
114    /// See protocol docs: [Metadata Patches](https://agentclientprotocol.com/protocol/v2/extensibility#metadata-patches)
115    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
116    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
117    #[serde(
118        rename = "_meta",
119        default,
120        skip_serializing_if = "MaybeUndefined::is_undefined"
121    )]
122    pub meta: MaybeUndefined<Meta>,
123}
124
125impl ToolCallUpdate {
126    /// Builds [`ToolCallUpdate`] with the required fields set. Optional fields start unset or empty.
127    #[must_use]
128    pub fn new(tool_call_id: impl Into<ToolCallId>) -> Self {
129        Self {
130            tool_call_id: tool_call_id.into(),
131            name: MaybeUndefined::Undefined,
132            title: MaybeUndefined::Undefined,
133            kind: MaybeUndefined::Undefined,
134            status: MaybeUndefined::Undefined,
135            content: MaybeUndefined::Undefined,
136            locations: MaybeUndefined::Undefined,
137            raw_input: MaybeUndefined::Undefined,
138            raw_output: MaybeUndefined::Undefined,
139            capabilities: MaybeUndefined::Undefined,
140            meta: MaybeUndefined::Undefined,
141        }
142    }
143
144    /// Programmatic name of the tool being invoked.
145    #[must_use]
146    pub fn name(mut self, name: impl IntoMaybeUndefined<String>) -> Self {
147        self.name = name.into_maybe_undefined();
148        self
149    }
150
151    /// Human-readable title describing what the tool is doing.
152    #[must_use]
153    pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
154        self.title = title.into_maybe_undefined();
155        self
156    }
157
158    /// The category of tool being invoked.
159    /// Helps clients choose appropriate icons and UI treatment.
160    #[must_use]
161    pub fn kind(mut self, kind: impl IntoMaybeUndefined<ToolKind>) -> Self {
162        self.kind = kind.into_maybe_undefined();
163        self
164    }
165
166    /// Current execution status of the tool call.
167    #[must_use]
168    pub fn status(mut self, status: impl IntoMaybeUndefined<ToolCallStatus>) -> Self {
169        self.status = status.into_maybe_undefined();
170        self
171    }
172
173    /// Content produced by the tool call.
174    #[must_use]
175    pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ToolCallContent>>) -> Self {
176        self.content = content.into_maybe_undefined();
177        self
178    }
179
180    /// File locations affected by this tool call.
181    /// Enables "follow-along" features in clients.
182    #[must_use]
183    pub fn locations(mut self, locations: impl IntoMaybeUndefined<Vec<ToolCallLocation>>) -> Self {
184        self.locations = locations.into_maybe_undefined();
185        self
186    }
187
188    /// Raw input parameters sent to the tool.
189    #[must_use]
190    pub fn raw_input(mut self, raw_input: impl IntoMaybeUndefined<serde_json::Value>) -> Self {
191        self.raw_input = raw_input.into_maybe_undefined();
192        self
193    }
194
195    /// Raw output returned by the tool.
196    #[must_use]
197    pub fn raw_output(mut self, raw_output: impl IntoMaybeUndefined<serde_json::Value>) -> Self {
198        self.raw_output = raw_output.into_maybe_undefined();
199        self
200    }
201
202    /// Sets, clears, or leaves unchanged the Client-initiated controls.
203    #[must_use]
204    pub fn capabilities(
205        mut self,
206        capabilities: impl IntoMaybeUndefined<ToolCallCapabilities>,
207    ) -> Self {
208        self.capabilities = capabilities.into_maybe_undefined();
209        self
210    }
211
212    /// Patches, clears, or leaves unchanged tool-call metadata.
213    ///
214    /// A concrete object patches stored metadata by top-level key. See
215    /// [`apply_meta_update`].
216    #[must_use]
217    pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
218        self.meta = meta.into_maybe_undefined();
219        self
220    }
221
222    /// Applies a later tool-call patch to this stored tool-call state.
223    ///
224    /// Fields set to `null` are preserved as `null` so callers can decide how to
225    /// render an explicitly cleared value. A concrete `_meta` object patches the
226    /// stored metadata by top-level key, as described by [`apply_meta_update`].
227    pub fn apply_update(&mut self, update: ToolCallUpdate) {
228        debug_assert_eq!(self.tool_call_id, update.tool_call_id);
229        if !update.name.is_undefined() {
230            self.name = update.name;
231        }
232        if !update.title.is_undefined() {
233            self.title = update.title;
234        }
235        if !update.kind.is_undefined() {
236            self.kind = update.kind;
237        }
238        if !update.status.is_undefined() {
239            self.status = update.status;
240        }
241        if !update.content.is_undefined() {
242            self.content = update.content;
243        }
244        if !update.locations.is_undefined() {
245            self.locations = update.locations;
246        }
247        if !update.raw_input.is_undefined() {
248            self.raw_input = update.raw_input;
249        }
250        if !update.raw_output.is_undefined() {
251            self.raw_output = update.raw_output;
252        }
253        if !update.capabilities.is_undefined() {
254            self.capabilities = update.capabilities;
255        }
256        apply_meta_update(&mut self.meta, update.meta);
257    }
258}
259
260/// Client-initiated controls a tool call currently supports.
261///
262/// A malformed value falls back to no controls, so the Client never sends a request the
263/// Agent did not advertise.
264///
265/// See protocol docs: [Cancelling Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-tool-calls)
266#[serde_as]
267#[skip_serializing_none]
268#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
269#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
270#[serde(rename_all = "camelCase")]
271#[non_exhaustive]
272pub struct ToolCallCapabilities {
273    /// Permits the Client to cancel this tool call with `tool_call/cancel`.
274    ///
275    /// Omitted and `null` are equivalent and mean unsupported. An object (including `{}`)
276    /// means supported. Agents SHOULD stop advertising it once the tool call reaches a final status.
277    #[serde_as(deserialize_as = "DefaultOnError")]
278    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
279    #[serde(default)]
280    pub cancel: Option<ToolCallCancelCapabilities>,
281    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
282    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
283    /// Implementations MUST NOT assign meaning to keys they do not recognize.
284    ///
285    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
286    #[serde_as(deserialize_as = "DefaultOnError")]
287    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
288    #[serde(default)]
289    #[serde(rename = "_meta")]
290    pub meta: Option<Meta>,
291}
292
293impl ToolCallCapabilities {
294    /// Builds an empty capability set. Cancellation is not advertised.
295    #[must_use]
296    pub fn new() -> Self {
297        Self::default()
298    }
299
300    /// Sets or removes permission to cancel this tool call.
301    #[must_use]
302    pub fn cancel(mut self, cancel: impl IntoOption<ToolCallCancelCapabilities>) -> Self {
303        self.cancel = cancel.into_option();
304        self
305    }
306
307    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
308    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
309    /// do not recognize.
310    ///
311    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
312    #[must_use]
313    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
314        self.meta = meta.into_option();
315        self
316    }
317}
318
319/// Capability to cancel a tool call with `tool_call/cancel`.
320///
321/// Supplying `{}` advertises support. An omitted or `null` `cancel` does not.
322#[serde_as]
323#[skip_serializing_none]
324#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
325#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
326#[non_exhaustive]
327pub struct ToolCallCancelCapabilities {
328    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
329    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
330    /// Implementations MUST NOT assign meaning to keys they do not recognize.
331    ///
332    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
333    #[serde_as(deserialize_as = "DefaultOnError")]
334    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
335    #[serde(default)]
336    #[serde(rename = "_meta")]
337    pub meta: Option<Meta>,
338}
339
340impl ToolCallCancelCapabilities {
341    /// Builds an empty capability object advertising cancellation support.
342    #[must_use]
343    pub fn new() -> Self {
344        Self::default()
345    }
346
347    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
348    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
349    /// do not recognize.
350    ///
351    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
352    #[must_use]
353    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
354        self.meta = meta.into_option();
355        self
356    }
357}
358
359/// A streamed item of tool-call content.
360///
361/// Tool-call content chunks append one `ToolCallContent` item to the current
362/// content for the matching `toolCallId`. Agents can send a `tool_call_update`
363/// with `content` when they need to replace the whole content collection
364/// instead.
365#[serde_as]
366#[skip_serializing_none]
367#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
368#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
369#[serde(rename_all = "camelCase")]
370#[non_exhaustive]
371pub struct ToolCallContentChunk {
372    /// The ID of the tool call this content belongs to.
373    pub tool_call_id: ToolCallId,
374    /// A single item of content produced by the tool call.
375    pub content: ToolCallContent,
376    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
377    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
378    /// Implementations MUST NOT assign meaning to keys they do not recognize.
379    /// This metadata is scoped to the chunk and does not patch stored metadata.
380    ///
381    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
382    #[serde_as(deserialize_as = "DefaultOnError")]
383    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
384    #[serde(default)]
385    #[serde(rename = "_meta")]
386    pub meta: Option<Meta>,
387}
388
389impl ToolCallContentChunk {
390    /// Builds [`ToolCallContentChunk`] with the required fields set. Optional fields start unset or empty.
391    #[must_use]
392    pub fn new(tool_call_id: impl Into<ToolCallId>, content: impl Into<ToolCallContent>) -> Self {
393        Self {
394            tool_call_id: tool_call_id.into(),
395            content: content.into(),
396            meta: None,
397        }
398    }
399
400    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
401    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
402    /// do not recognize. This field is chunk-scoped.
403    ///
404    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
405    #[must_use]
406    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
407        self.meta = meta.into_option();
408        self
409    }
410}
411
412/// Unique identifier for a tool call within a session.
413#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
414#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
415#[serde(transparent)]
416#[from(forward)]
417#[non_exhaustive]
418pub struct ToolCallId(pub Arc<str>);
419
420impl ToolCallId {
421    /// Wraps a protocol string as a typed [`ToolCallId`].
422    #[must_use]
423    pub fn new(id: impl Into<Self>) -> Self {
424        id.into()
425    }
426}
427
428impl IntoOption<ToolCallId> for &str {
429    fn into_option(self) -> Option<ToolCallId> {
430        Some(ToolCallId::new(self))
431    }
432}
433
434/// Categories of tools that can be invoked.
435///
436/// Tool kinds help clients choose appropriate icons and optimize how they
437/// display tool execution progress.
438///
439/// See protocol docs: [Reporting](https://agentclientprotocol.com/protocol/v2/tool-calls#reporting)
440#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
441#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
442#[serde(rename_all = "snake_case")]
443#[non_exhaustive]
444pub enum ToolKind {
445    /// Reading files or data.
446    Read,
447    /// Modifying files or content.
448    Edit,
449    /// Removing files or data.
450    Delete,
451    /// Moving or renaming files.
452    Move,
453    /// Searching for information.
454    Search,
455    /// Running commands or code.
456    Execute,
457    /// Internal reasoning or planning.
458    Think,
459    /// Retrieving external data.
460    Fetch,
461    /// Changing the session's mode, a [config option](https://agentclientprotocol.com/protocol/v2/session-config-options) with the `mode` category.
462    SwitchMode,
463    /// Other tool types (default).
464    #[default]
465    Other,
466    /// Custom or future tool kind.
467    ///
468    /// Values beginning with `_` are reserved for implementation-specific
469    /// extensions. Unknown values that do not begin with `_` are reserved for
470    /// future ACP variants. Clients display an unrecognized kind as `other`.
471    #[serde(untagged)]
472    Unknown(String),
473}
474
475/// Execution status of a tool call.
476///
477/// Tool calls progress through different statuses during their lifecycle.
478///
479/// See protocol docs: [Status](https://agentclientprotocol.com/protocol/v2/tool-calls#status)
480#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
481#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
482#[serde(rename_all = "snake_case")]
483#[non_exhaustive]
484pub enum ToolCallStatus {
485    /// The tool call hasn't started running yet, for example because its input is
486    /// streaming, it is awaiting approval, or it is scheduled to run later.
487    #[default]
488    Pending,
489    /// The tool call is currently running.
490    InProgress,
491    /// The tool call has started, is not running now, and will not continue until
492    /// something resumes it. It may return to `in_progress` any number of times.
493    Paused,
494    /// The tool call completed successfully.
495    Completed,
496    /// The tool call failed with an error.
497    Failed,
498    /// The tool call was cancelled before it completed.
499    Cancelled,
500    /// Custom or future tool call status.
501    ///
502    /// Values beginning with `_` are reserved for implementation-specific
503    /// extensions. Unknown values that do not begin with `_` are reserved for
504    /// future ACP variants.
505    ///
506    /// Clients treat a tool call with an unrecognized status as still in progress.
507    #[serde(untagged)]
508    Other(String),
509}
510
511/// Content produced by a tool call.
512///
513/// Tool calls can produce different types of content including standard
514/// content blocks (text, images), file diffs, or display-only terminals.
515///
516/// See protocol docs: [Content](https://agentclientprotocol.com/protocol/v2/tool-calls#content)
517#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
518#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
519#[serde(tag = "type", rename_all = "snake_case")]
520#[non_exhaustive]
521pub enum ToolCallContent {
522    /// Standard content block (text, images, resources).
523    Content(Box<Content>),
524    /// File modification shown as a diff.
525    Diff(Diff),
526    /// A display-only reference to an agent-owned terminal.
527    Terminal(Terminal),
528    /// A display-only reference to another session, such as a subagent.
529    Session(SessionReference),
530    /// Custom or future tool call content.
531    ///
532    /// Values beginning with `_` are reserved for implementation-specific
533    /// extensions. Unknown values that do not begin with `_` are reserved for
534    /// future ACP variants.
535    ///
536    /// Receivers that do not understand this content type should preserve the
537    /// raw payload when storing, replaying, proxying, or forwarding tool call
538    /// output, and otherwise ignore it or display it generically.
539    #[serde(untagged)]
540    Other(OtherToolCallContent),
541}
542
543/// Custom or future tool call content payload.
544#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
545#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
546#[cfg_attr(feature = "schemars", schemars(inline))]
547#[cfg_attr(feature = "schemars", schemars(transform = other_tool_call_content_schema))]
548#[serde(rename_all = "camelCase")]
549#[non_exhaustive]
550pub struct OtherToolCallContent {
551    /// Custom or future tool call content type.
552    ///
553    /// Values beginning with `_` are reserved for implementation-specific
554    /// extensions. Unknown values that do not begin with `_` are reserved for
555    /// future ACP variants.
556    #[serde(rename = "type")]
557    pub type_: String,
558    /// Additional fields from the unknown tool call content payload.
559    #[serde(flatten)]
560    pub fields: BTreeMap<String, serde_json::Value>,
561}
562
563impl OtherToolCallContent {
564    /// Builds [`OtherToolCallContent`] from an unknown discriminator and preserves the remaining extension fields.
565    #[must_use]
566    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
567        fields.remove("type");
568        Self {
569            type_: type_.into(),
570            fields,
571        }
572    }
573}
574
575impl<'de> Deserialize<'de> for OtherToolCallContent {
576    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
577    where
578        D: serde::Deserializer<'de>,
579    {
580        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
581        let type_ = fields
582            .remove("type")
583            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
584        let serde_json::Value::String(type_) = type_ else {
585            return Err(serde::de::Error::custom("`type` must be a string"));
586        };
587
588        if is_known_tool_call_content_type(&type_) {
589            return Err(serde::de::Error::custom(format!(
590                "known tool call content `{type_}` did not match its schema"
591            )));
592        }
593
594        Ok(Self { type_, fields })
595    }
596}
597
598fn is_known_tool_call_content_type(type_: &str) -> bool {
599    KNOWN_TOOL_CALL_CONTENT_TYPES.contains(&type_)
600}
601
602const KNOWN_TOOL_CALL_CONTENT_TYPES: &[&str] = &["content", "diff", "terminal", "session"];
603
604#[cfg(feature = "schemars")]
605fn other_tool_call_content_schema(schema: &mut Schema) {
606    super::schema_util::reject_known_string_discriminators(
607        schema,
608        "type",
609        KNOWN_TOOL_CALL_CONTENT_TYPES,
610    );
611}
612
613impl<T: Into<ContentBlock>> From<T> for ToolCallContent {
614    fn from(content: T) -> Self {
615        ToolCallContent::Content(Box::new(Content::new(content)))
616    }
617}
618
619impl From<Diff> for ToolCallContent {
620    fn from(diff: Diff) -> Self {
621        ToolCallContent::Diff(diff)
622    }
623}
624
625impl From<Terminal> for ToolCallContent {
626    fn from(terminal: Terminal) -> Self {
627        ToolCallContent::Terminal(terminal)
628    }
629}
630
631/// A display-only reference to another session that this tool call operates on,
632/// such as a subagent it created, delegated to, or is waiting on.
633///
634/// The referenced session must already be known to the Client through ordinary
635/// session setup or a `subagent_update` announcement. The reference does not
636/// establish ownership, grant any Client-initiated controls, or report that the
637/// referenced session received or finished any work.
638#[serde_as]
639#[skip_serializing_none]
640#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
641#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
642#[serde(rename_all = "camelCase")]
643#[non_exhaustive]
644pub struct SessionReference {
645    /// The referenced session.
646    pub session_id: SessionId,
647    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
648    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
649    /// Implementations MUST NOT assign meaning to keys they do not recognize.
650    ///
651    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
652    #[serde_as(deserialize_as = "DefaultOnError")]
653    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
654    #[serde(default)]
655    #[serde(rename = "_meta")]
656    pub meta: Option<Meta>,
657}
658
659impl SessionReference {
660    /// Builds [`SessionReference`] with the required fields set. Optional fields start unset or empty.
661    #[must_use]
662    pub fn new(session_id: impl Into<SessionId>) -> Self {
663        Self {
664            session_id: session_id.into(),
665            meta: None,
666        }
667    }
668
669    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
670    /// metadata to their interactions.
671    #[must_use]
672    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
673        self.meta = meta.into_option();
674        self
675    }
676}
677
678impl From<SessionReference> for ToolCallContent {
679    fn from(session: SessionReference) -> Self {
680        ToolCallContent::Session(session)
681    }
682}
683
684/// Standard content block (text, images, resources).
685#[serde_as]
686#[skip_serializing_none]
687#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
688#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
689#[serde(rename_all = "camelCase")]
690#[non_exhaustive]
691pub struct Content {
692    /// The actual content block.
693    pub content: ContentBlock,
694    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
695    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
696    /// Implementations MUST NOT assign meaning to keys they do not recognize.
697    ///
698    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
699    #[serde_as(deserialize_as = "DefaultOnError")]
700    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
701    #[serde(default)]
702    #[serde(rename = "_meta")]
703    pub meta: Option<Meta>,
704}
705
706impl Content {
707    /// Builds [`Content`] with the required fields set. Optional fields start unset or empty.
708    #[must_use]
709    pub fn new(content: impl Into<ContentBlock>) -> Self {
710        Self {
711            content: content.into(),
712            meta: None,
713        }
714    }
715
716    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
717    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
718    /// do not recognize.
719    ///
720    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
721    #[must_use]
722    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
723        self.meta = meta.into_option();
724        self
725    }
726}
727
728/// File changes produced by a tool call.
729///
730/// `changes` is authoritative for affected absolute paths and operations.
731/// `patch` optionally carries renderable text for some or all of those changes
732/// and MUST be consistent with `changes`. Agents SHOULD provide `patch` whenever
733/// feasible. Clients MUST handle diffs where `patch` is omitted or `null`.
734///
735/// See protocol docs: [Content](https://agentclientprotocol.com/protocol/v2/tool-calls#content)
736#[serde_as]
737#[skip_serializing_none]
738#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
739#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
740#[serde(rename_all = "camelCase")]
741#[non_exhaustive]
742pub struct Diff {
743    /// Structured file changes described by this diff. Agents MUST include at least one entry.
744    ///
745    /// Clients can use this field without parsing patch text to determine affected paths.
746    #[serde_as(deserialize_as = "VecSkipError<_>")]
747    #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-skip-invalid-items" = true)))]
748    pub changes: Vec<DiffChange>,
749    /// Renderable patch text for some or all of the structured changes.
750    ///
751    /// Agents SHOULD provide patch text whenever feasible. Omitted and `null` are
752    /// equivalent and mean no renderable patch text was provided.
753    #[serde_as(deserialize_as = "DefaultOnError")]
754    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
755    #[serde(default)]
756    pub patch: Option<DiffPatch>,
757    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
758    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
759    /// Implementations MUST NOT assign meaning to keys they do not recognize.
760    ///
761    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
762    #[serde_as(deserialize_as = "DefaultOnError")]
763    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
764    #[serde(default)]
765    #[serde(rename = "_meta")]
766    pub meta: Option<Meta>,
767}
768
769impl Diff {
770    /// Builds [`Diff`] with structured file changes.
771    #[must_use]
772    pub fn new(changes: Vec<DiffChange>) -> Self {
773        Self {
774            changes,
775            patch: None,
776            meta: None,
777        }
778    }
779
780    /// Builds [`Diff`] with Git `--patch` text and structured file changes.
781    #[must_use]
782    pub fn patch(text: impl Into<String>, changes: Vec<DiffChange>) -> Self {
783        Self::new(changes).with_patch(DiffPatch::new(text))
784    }
785
786    /// Sets renderable patch text.
787    #[must_use]
788    pub fn with_patch(mut self, patch: impl IntoOption<DiffPatch>) -> Self {
789        self.patch = patch.into_option();
790        self
791    }
792
793    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
794    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
795    /// do not recognize.
796    ///
797    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
798    #[must_use]
799    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
800        self.meta = meta.into_option();
801        self
802    }
803}
804
805/// Renderable patch text and its format.
806#[serde_as]
807#[skip_serializing_none]
808#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
809#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
810#[serde(rename_all = "camelCase")]
811#[non_exhaustive]
812pub struct DiffPatch {
813    /// Patch format. The only ACP-defined value is `git_patch`.
814    pub format: DiffPatchFormat,
815    /// Patch text in the format named by `format`.
816    pub text: String,
817    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
818    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
819    /// Implementations MUST NOT assign meaning to keys they do not recognize.
820    ///
821    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
822    #[serde_as(deserialize_as = "DefaultOnError")]
823    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
824    #[serde(default)]
825    #[serde(rename = "_meta")]
826    pub meta: Option<Meta>,
827}
828
829impl DiffPatch {
830    /// Builds [`DiffPatch`] with Git `--patch` text.
831    #[must_use]
832    pub fn new(text: impl Into<String>) -> Self {
833        Self {
834            format: DiffPatchFormat::GitPatch,
835            text: text.into(),
836            meta: None,
837        }
838    }
839
840    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
841    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
842    /// do not recognize.
843    ///
844    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
845    #[must_use]
846    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
847        self.meta = meta.into_option();
848        self
849    }
850}
851
852/// Text patch format used by `DiffPatch`.
853#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
854#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
855#[serde(rename_all = "snake_case")]
856#[non_exhaustive]
857pub enum DiffPatchFormat {
858    /// One or more `diff --git` sections in Git's `--patch` (`-p`) text format.
859    ///
860    /// Unlike Git, which writes paths relative to the repository root, every
861    /// path MUST be absolute, including in `rename from`, `rename to`,
862    /// `copy from`, and `copy to` lines, and MUST NOT have a prefix such as
863    /// Git's default `a/` and `b/`. Otherwise paths follow Git: `/dev/null`
864    /// names the missing side of an added or deleted file in the `---` and
865    /// `+++` lines, and paths with unusual characters are quoted as Git quotes
866    /// them. Each path, once unquoted, is the same native absolute path string as
867    /// the matching `changes` entry. Surrounding commit metadata and email envelopes MUST NOT be
868    /// included.
869    GitPatch,
870    /// Custom or future patch format.
871    ///
872    /// Values beginning with `_` are reserved for implementation-specific
873    /// extensions. Unknown values that do not begin with `_` are reserved for
874    /// future ACP variants.
875    #[serde(untagged)]
876    Other(String),
877}
878
879/// Kind of file content represented by a diff change.
880#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
881#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
882#[serde(rename_all = "snake_case")]
883#[non_exhaustive]
884pub enum DiffFileType {
885    /// Text content.
886    Text,
887    /// Binary or otherwise non-text content.
888    Binary,
889    /// Directory entry.
890    Directory,
891    /// Symbolic link.
892    Symlink,
893    /// Custom or future file type.
894    ///
895    /// Values beginning with `_` are reserved for implementation-specific
896    /// extensions. Unknown values that do not begin with `_` are reserved for
897    /// future ACP variants.
898    #[serde(untagged)]
899    Other(String),
900}
901
902/// One file-level change described by a `Diff`.
903///
904/// Structured change metadata lets clients identify affected files and
905/// operations without parsing the text patch.
906#[serde_as]
907#[skip_serializing_none]
908#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
909#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
910#[serde(rename_all = "camelCase")]
911#[non_exhaustive]
912pub struct DiffChange {
913    /// File content kind after the operation (for `delete`, of the deleted file).
914    ///
915    /// Omitted and `null` are equivalent and mean the content kind is unknown.
916    #[serde_as(deserialize_as = "DefaultOnError")]
917    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
918    #[serde(default)]
919    pub file_type: Option<DiffFileType>,
920    /// MIME type of the file contents after the operation (for `delete`, of the deleted file).
921    ///
922    /// Omitted and `null` are equivalent and mean the MIME type is unknown.
923    #[serde_as(deserialize_as = "DefaultOnError")]
924    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
925    #[serde(default)]
926    pub mime_type: Option<MediaType>,
927    /// File operation-specific fields.
928    #[serde(flatten)]
929    pub operation: DiffChangeOperation,
930    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
931    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
932    /// Implementations MUST NOT assign meaning to keys they do not recognize.
933    ///
934    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
935    #[serde_as(deserialize_as = "DefaultOnError")]
936    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
937    #[serde(default)]
938    #[serde(rename = "_meta")]
939    pub meta: Option<Meta>,
940}
941
942impl DiffChange {
943    /// Builds [`DiffChange`] with the required fields set. Optional fields start unset or empty.
944    #[must_use]
945    pub fn new(operation: DiffChangeOperation) -> Self {
946        Self {
947            file_type: None,
948            mime_type: None,
949            operation,
950            meta: None,
951        }
952    }
953
954    /// Builds a file add change.
955    #[must_use]
956    pub fn add(path: impl Into<AbsolutePath>) -> Self {
957        Self::new(DiffChangeOperation::Add(DiffPathChange::new(path)))
958    }
959
960    /// Builds a file delete change.
961    #[must_use]
962    pub fn delete(path: impl Into<AbsolutePath>) -> Self {
963        Self::new(DiffChangeOperation::Delete(DiffPathChange::new(path)))
964    }
965
966    /// Builds a file modify change.
967    #[must_use]
968    pub fn modify(path: impl Into<AbsolutePath>) -> Self {
969        Self::new(DiffChangeOperation::Modify(DiffPathChange::new(path)))
970    }
971
972    /// Builds a file move or rename change.
973    #[must_use]
974    pub fn move_file(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
975        Self::new(DiffChangeOperation::Move(DiffPathPairChange::new(
976            old_path, path,
977        )))
978    }
979
980    /// Builds a file copy change.
981    #[must_use]
982    pub fn copy(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
983        Self::new(DiffChangeOperation::Copy(DiffPathPairChange::new(
984            old_path, path,
985        )))
986    }
987
988    /// File content kind.
989    ///
990    /// Omitted and `null` are equivalent and mean the content kind is unknown.
991    #[must_use]
992    pub fn file_type(mut self, file_type: impl IntoOption<DiffFileType>) -> Self {
993        self.file_type = file_type.into_option();
994        self
995    }
996
997    /// MIME type of the file contents.
998    ///
999    /// Omitted and `null` are equivalent and mean the MIME type is unknown.
1000    #[must_use]
1001    pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
1002        self.mime_type = mime_type.into_option();
1003        self
1004    }
1005
1006    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1007    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1008    /// do not recognize.
1009    ///
1010    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1011    #[must_use]
1012    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1013        self.meta = meta.into_option();
1014        self
1015    }
1016}
1017
1018/// File operation for a [`DiffChange`].
1019#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1020#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1021#[serde(tag = "operation", rename_all = "snake_case")]
1022#[non_exhaustive]
1023pub enum DiffChangeOperation {
1024    /// A file was added.
1025    Add(DiffPathChange),
1026    /// A file was deleted.
1027    Delete(DiffPathChange),
1028    /// A file was modified in place.
1029    Modify(DiffPathChange),
1030    /// A file was moved or renamed.
1031    Move(DiffPathPairChange),
1032    /// A file was copied.
1033    Copy(DiffPathPairChange),
1034    /// Custom or future file operation.
1035    ///
1036    /// Values beginning with `_` are reserved for implementation-specific
1037    /// extensions. Unknown values that do not begin with `_` are reserved for
1038    /// future ACP variants.
1039    #[serde(untagged)]
1040    Other(OtherDiffChange),
1041}
1042
1043/// Operation metadata for add, delete, and modify changes.
1044#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1045#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1046#[serde(rename_all = "camelCase")]
1047#[non_exhaustive]
1048pub struct DiffPathChange {
1049    /// Absolute path for the operation.
1050    pub path: AbsolutePath,
1051}
1052
1053impl DiffPathChange {
1054    /// Builds [`DiffPathChange`] with the required fields set. Optional fields start unset or empty.
1055    #[must_use]
1056    pub fn new(path: impl Into<AbsolutePath>) -> Self {
1057        Self { path: path.into() }
1058    }
1059}
1060
1061/// Operation metadata for move and copy changes.
1062#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1063#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1064#[serde(rename_all = "camelCase")]
1065#[non_exhaustive]
1066pub struct DiffPathPairChange {
1067    /// Absolute path before the operation.
1068    pub old_path: AbsolutePath,
1069    /// Absolute path after the operation.
1070    pub path: AbsolutePath,
1071}
1072
1073impl DiffPathPairChange {
1074    /// Builds [`DiffPathPairChange`] with the required fields set. Optional fields start unset or empty.
1075    #[must_use]
1076    pub fn new(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
1077        Self {
1078            old_path: old_path.into(),
1079            path: path.into(),
1080        }
1081    }
1082}
1083
1084/// Custom or future file operation payload.
1085#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1086#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1087#[cfg_attr(feature = "schemars", schemars(inline))]
1088#[cfg_attr(feature = "schemars", schemars(transform = other_diff_change_schema))]
1089#[serde(rename_all = "camelCase")]
1090#[non_exhaustive]
1091pub struct OtherDiffChange {
1092    /// Custom or future file operation.
1093    ///
1094    /// Values beginning with `_` are reserved for implementation-specific
1095    /// extensions. Unknown values that do not begin with `_` are reserved for
1096    /// future ACP variants.
1097    pub operation: String,
1098    /// Additional fields from the unknown file operation payload.
1099    #[serde(flatten)]
1100    pub fields: BTreeMap<String, serde_json::Value>,
1101}
1102
1103impl OtherDiffChange {
1104    /// Builds [`OtherDiffChange`] from an unknown discriminator and preserves the remaining extension fields.
1105    #[must_use]
1106    pub fn new(
1107        operation: impl Into<String>,
1108        mut fields: BTreeMap<String, serde_json::Value>,
1109    ) -> Self {
1110        fields.remove("operation");
1111        fields.remove("fileType");
1112        fields.remove("mimeType");
1113        fields.remove("_meta");
1114        Self {
1115            operation: operation.into(),
1116            fields,
1117        }
1118    }
1119}
1120
1121impl<'de> Deserialize<'de> for OtherDiffChange {
1122    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1123    where
1124        D: serde::Deserializer<'de>,
1125    {
1126        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1127        let operation = fields
1128            .remove("operation")
1129            .ok_or_else(|| serde::de::Error::missing_field("operation"))?;
1130        let serde_json::Value::String(operation) = operation else {
1131            return Err(serde::de::Error::custom("`operation` must be a string"));
1132        };
1133
1134        if is_known_diff_change_operation(&operation) {
1135            return Err(serde::de::Error::custom(format!(
1136                "known diff change operation `{operation}` did not match its schema"
1137            )));
1138        }
1139        fields.remove("fileType");
1140        fields.remove("mimeType");
1141        fields.remove("_meta");
1142
1143        Ok(Self { operation, fields })
1144    }
1145}
1146
1147fn is_known_diff_change_operation(operation: &str) -> bool {
1148    matches!(operation, "add" | "delete" | "modify" | "move" | "copy")
1149}
1150
1151#[cfg(feature = "schemars")]
1152fn other_diff_change_schema(schema: &mut Schema) {
1153    super::schema_util::reject_known_string_discriminators(
1154        schema,
1155        "operation",
1156        &["add", "delete", "modify", "move", "copy"],
1157    );
1158}
1159
1160/// A file location being accessed or modified by a tool.
1161///
1162/// Enables clients to implement "follow-along" features that track
1163/// which files the agent is working with in real-time.
1164///
1165/// See protocol docs: [Following the Agent](https://agentclientprotocol.com/protocol/v2/tool-calls#following-the-agent)
1166#[serde_as]
1167#[skip_serializing_none]
1168#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1169#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1170#[serde(rename_all = "camelCase")]
1171#[non_exhaustive]
1172pub struct ToolCallLocation {
1173    /// The absolute file path being accessed or modified.
1174    pub path: AbsolutePath,
1175    /// Optional 1-based line number within the file. Omitted and `null` are equivalent and
1176    /// mean no specific line. `0` is invalid.
1177    #[serde_as(deserialize_as = "DefaultOnError")]
1178    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1179    #[serde(default)]
1180    pub line: Option<std::num::NonZeroU32>,
1181    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1182    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1183    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1184    ///
1185    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1186    #[serde_as(deserialize_as = "DefaultOnError")]
1187    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1188    #[serde(default)]
1189    #[serde(rename = "_meta")]
1190    pub meta: Option<Meta>,
1191}
1192
1193impl ToolCallLocation {
1194    /// Builds [`ToolCallLocation`] with the required fields set. Optional fields start unset or empty.
1195    #[must_use]
1196    pub fn new(path: impl Into<AbsolutePath>) -> Self {
1197        Self {
1198            path: path.into(),
1199            line: None,
1200            meta: None,
1201        }
1202    }
1203
1204    /// Optional line number within the file.
1205    ///
1206    /// Line numbers are 1-based, and `0` is invalid on the wire. This builder maps `0` to no
1207    /// specific line.
1208    #[must_use]
1209    pub fn line(mut self, line: impl IntoOption<u32>) -> Self {
1210        self.line = line.into_option().and_then(std::num::NonZeroU32::new);
1211        self
1212    }
1213
1214    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1215    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1216    /// do not recognize.
1217    ///
1218    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1219    #[must_use]
1220    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1221        self.meta = meta.into_option();
1222        self
1223    }
1224}
1225
1226#[cfg(test)]
1227mod tests {
1228
1229    #[test]
1230    fn session_reference_tool_call_content_round_trips() {
1231        use serde_json::json;
1232        let content = ToolCallContent::from(SessionReference::new("sess_child_1"));
1233        let value = serde_json::to_value(&content).unwrap();
1234        assert_eq!(
1235            value,
1236            json!({ "type": "session", "sessionId": "sess_child_1" })
1237        );
1238        assert_eq!(
1239            serde_json::from_value::<ToolCallContent>(value).unwrap(),
1240            content
1241        );
1242        // A malformed known variant must not fall through to `Other`.
1243        assert!(serde_json::from_value::<ToolCallContent>(json!({ "type": "session" })).is_err());
1244    }
1245
1246    #[test]
1247    fn location_line_is_one_based() {
1248        let location: ToolCallLocation =
1249            serde_json::from_value(serde_json::json!({ "path": "/a.rs", "line": 0 })).unwrap();
1250        assert_eq!(location.line, None);
1251        let location: ToolCallLocation =
1252            serde_json::from_value(serde_json::json!({ "path": "/a.rs", "line": 3 })).unwrap();
1253        assert_eq!(location.line.map(std::num::NonZeroU32::get), Some(3));
1254        assert_eq!(ToolCallLocation::new("/a.rs").line(0).line, None);
1255    }
1256
1257    #[test]
1258    fn toolcall_capabilities_patch_and_tolerate_malformed_values() {
1259        use serde_json::json;
1260        let update = ToolCallUpdate::new("call_012")
1261            .capabilities(ToolCallCapabilities::new().cancel(ToolCallCancelCapabilities::new()));
1262        assert_eq!(
1263            serde_json::to_value(&update).unwrap(),
1264            json!({ "toolCallId": "call_012", "capabilities": { "cancel": {} } })
1265        );
1266
1267        let mut stored = update;
1268        stored.apply_update(ToolCallUpdate::new("call_012"));
1269        assert!(stored.capabilities.is_value());
1270        stored.apply_update(ToolCallUpdate::new("call_012").capabilities(MaybeUndefined::Null));
1271        assert!(stored.capabilities.is_null());
1272
1273        for bad in [json!("yes"), json!(1)] {
1274            let parsed: ToolCallUpdate =
1275                serde_json::from_value(json!({ "toolCallId": "call_012", "capabilities": bad }))
1276                    .unwrap();
1277            assert!(parsed.capabilities.is_undefined());
1278        }
1279        let parsed: ToolCallCapabilities =
1280            serde_json::from_value(json!({ "cancel": "yes" })).unwrap();
1281        assert_eq!(parsed.cancel, None);
1282    }
1283
1284    #[test]
1285    fn paused_is_a_known_tool_call_status() {
1286        use serde_json::json;
1287        assert_eq!(
1288            serde_json::to_value(ToolCallStatus::Paused).unwrap(),
1289            json!("paused")
1290        );
1291        assert_eq!(
1292            serde_json::from_value::<ToolCallStatus>(json!("paused")).unwrap(),
1293            ToolCallStatus::Paused
1294        );
1295    }
1296
1297    use super::*;
1298    use crate::MaybeUndefined;
1299    use serde_json::{from_value, json, to_value};
1300
1301    #[test]
1302    fn tool_call_serializes_as_upsert() {
1303        let tool_call = ToolCallUpdate::new("tc_1")
1304            .title("Reading configuration")
1305            .status(ToolCallStatus::InProgress)
1306            .raw_input(serde_json::json!({"path": "settings.json"}));
1307
1308        assert_eq!(
1309            serde_json::to_value(tool_call).unwrap(),
1310            serde_json::json!({
1311                "toolCallId": "tc_1",
1312                "title": "Reading configuration",
1313                "status": "in_progress",
1314                "rawInput": {
1315                    "path": "settings.json"
1316                }
1317            })
1318        );
1319    }
1320
1321    #[test]
1322    fn tool_call_update_distinguishes_omitted_null_and_value() {
1323        let tool_call = ToolCallUpdate::new("tc_1")
1324            .status(ToolCallStatus::Completed)
1325            .content(None::<Vec<ToolCallContent>>);
1326
1327        assert_eq!(
1328            serde_json::to_value(tool_call).unwrap(),
1329            serde_json::json!({
1330                "toolCallId": "tc_1",
1331                "status": "completed",
1332                "content": null
1333            })
1334        );
1335
1336        let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1337            "toolCallId": "tc_1",
1338            "status": null,
1339            "locations": []
1340        }))
1341        .unwrap();
1342        assert_eq!(deserialized.title, MaybeUndefined::Undefined);
1343        assert_eq!(deserialized.status, MaybeUndefined::Null);
1344        assert_eq!(deserialized.locations, MaybeUndefined::Value(Vec::new()));
1345    }
1346
1347    #[test]
1348    fn tool_call_name_patch_distinguishes_omitted_null_and_value() {
1349        let named = ToolCallUpdate::new("tc_1").name("read_file");
1350        assert_eq!(
1351            serde_json::to_value(named).unwrap(),
1352            serde_json::json!({
1353                "toolCallId": "tc_1",
1354                "name": "read_file"
1355            })
1356        );
1357
1358        let omitted = ToolCallUpdate::new("tc_1");
1359        assert_eq!(omitted.name, MaybeUndefined::Undefined);
1360
1361        let from_null: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1362            "toolCallId": "tc_1",
1363            "name": null
1364        }))
1365        .unwrap();
1366        assert_eq!(from_null.name, MaybeUndefined::Null);
1367
1368        let mut stored = ToolCallUpdate::new("tc_1").name("read_file");
1369        stored.apply_update(ToolCallUpdate::new("tc_1"));
1370        assert_eq!(stored.name, MaybeUndefined::Value("read_file".to_string()));
1371
1372        stored.apply_update(ToolCallUpdate::new("tc_1").name(None::<String>));
1373        assert_eq!(stored.name, MaybeUndefined::Null);
1374
1375        stored.apply_update(ToolCallUpdate::new("tc_1").name("write_file"));
1376        assert_eq!(stored.name, MaybeUndefined::Value("write_file".to_string()));
1377    }
1378
1379    #[test]
1380    fn tool_call_update_distinguishes_meta_omitted_null_and_value() {
1381        let mut meta = Meta::new();
1382        meta.insert("source".to_string(), serde_json::json!("tool-call"));
1383
1384        assert_eq!(
1385            serde_json::to_value(ToolCallUpdate::new("tc_1").meta(meta.clone())).unwrap(),
1386            serde_json::json!({
1387                "toolCallId": "tc_1",
1388                "_meta": {
1389                    "source": "tool-call"
1390                }
1391            })
1392        );
1393
1394        assert_eq!(
1395            serde_json::to_value(ToolCallUpdate::new("tc_1").meta(None::<Meta>)).unwrap(),
1396            serde_json::json!({
1397                "toolCallId": "tc_1",
1398                "_meta": null
1399            })
1400        );
1401
1402        let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1403            "toolCallId": "tc_1",
1404            "_meta": null
1405        }))
1406        .unwrap();
1407        assert_eq!(deserialized.meta, MaybeUndefined::Null);
1408
1409        let patch = ToolCallUpdate::new("tc_1");
1410        assert_eq!(patch.meta, MaybeUndefined::Undefined);
1411
1412        let mut stored = ToolCallUpdate::new("tc_1").meta(meta);
1413        stored.apply_update(ToolCallUpdate::new("tc_1").meta(None::<Meta>));
1414        assert_eq!(stored.meta, MaybeUndefined::Null);
1415    }
1416
1417    #[test]
1418    fn tool_call_update_patches_meta_by_top_level_key() {
1419        let mut stored: ToolCallUpdate = from_value(json!({
1420            "toolCallId": "tc_1",
1421            "_meta": {"zed.dev/a": 1, "acme.dev/b": {"x": 1}}
1422        }))
1423        .unwrap();
1424
1425        // A writer that only knows its own key must not erase other keys.
1426        stored.apply_update(
1427            from_value(json!({"toolCallId": "tc_1", "_meta": {"proxy.dev/c": true}})).unwrap(),
1428        );
1429        stored.apply_update(
1430            from_value(json!({
1431                "toolCallId": "tc_1",
1432                "_meta": {"zed.dev/a": null, "acme.dev/b": {"y": 2}}
1433            }))
1434            .unwrap(),
1435        );
1436
1437        assert_eq!(
1438            to_value(&stored).unwrap(),
1439            json!({
1440                "toolCallId": "tc_1",
1441                "_meta": {"acme.dev/b": {"y": 2}, "proxy.dev/c": true}
1442            })
1443        );
1444    }
1445
1446    #[test]
1447    fn tool_call_wire_patches_preserve_omitted_fields_and_replace_values() {
1448        let initial = json!({
1449            "toolCallId": "tc_1",
1450            "_meta": {"source": "replay", "opaque": {"sequence": 1}}
1451        });
1452        let mut stored: ToolCallUpdate = from_value(initial.clone()).unwrap();
1453        // A metadata-only first update must not invent content or a status.
1454        assert_eq!(to_value(&stored).unwrap(), initial);
1455
1456        let populated = json!({
1457            "toolCallId": "tc_1",
1458            "name": "read_file",
1459            "title": "Reading configuration",
1460            "kind": "read",
1461            "status": "in_progress",
1462            "content": [{
1463                "type": "content",
1464                "content": {
1465                    "type": "text",
1466                    "text": "old",
1467                    "_meta": {"source": "tool"}
1468                }
1469            }],
1470            "locations": [{"path": "/workspace/config.json", "line": 3}],
1471            "rawInput": {"path": "/workspace/config.json"},
1472            "rawOutput": {"text": "old"}
1473        });
1474        stored.apply_update(from_value(populated.clone()).unwrap());
1475        let mut expected = populated;
1476        expected["_meta"] = initial["_meta"].clone();
1477        assert_eq!(to_value(&stored).unwrap(), expected);
1478
1479        for (field, empty) in [
1480            ("content", json!([])),
1481            ("locations", json!([])),
1482            ("rawInput", json!({})),
1483            ("rawOutput", json!({})),
1484        ] {
1485            let original = expected[field].clone();
1486            // Empty values replace rather than merge; null remains distinct.
1487            // Restoring the value also checks that clearing is not permanent.
1488            for replacement in [empty, json!(null), original] {
1489                stored.apply_update(
1490                    from_value(json!({"toolCallId": "tc_1", (field): replacement})).unwrap(),
1491                );
1492                expected[field] = replacement;
1493                assert_eq!(to_value(&stored).unwrap(), expected, "patching {field}");
1494
1495                stored.apply_update(from_value(json!({"toolCallId": "tc_1"})).unwrap());
1496                assert_eq!(to_value(&stored).unwrap(), expected, "omitting {field}");
1497            }
1498        }
1499    }
1500
1501    #[test]
1502    fn tool_call_wire_patches_preserve_unknown_statuses() {
1503        for status in ["deferred", "_awaiting_review"] {
1504            let mut stored = ToolCallUpdate::new("tc_1").status(ToolCallStatus::InProgress);
1505            stored
1506                .apply_update(from_value(json!({"toolCallId": "tc_1", "status": status})).unwrap());
1507            let expected_status = MaybeUndefined::Value(ToolCallStatus::Other(status.to_owned()));
1508            assert_eq!(stored.status, expected_status);
1509
1510            // An unrelated patch must not reset a future or extension status
1511            // to a known value, including a success or failure state.
1512            stored.apply_update(
1513                from_value(json!({"toolCallId": "tc_1", "title": "Still waiting"})).unwrap(),
1514            );
1515            assert_eq!(stored.status, expected_status);
1516            assert_eq!(
1517                to_value(&stored).unwrap(),
1518                json!({"toolCallId": "tc_1", "title": "Still waiting", "status": status})
1519            );
1520        }
1521    }
1522
1523    #[test]
1524    fn tool_call_update_skips_malformed_list_items() {
1525        let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1526            "toolCallId": "tc_1",
1527            "content": [
1528                {
1529                    "type": "content",
1530                    "content": {
1531                        "type": "text",
1532                        "text": "ok"
1533                    }
1534                },
1535                {
1536                    "type": "diff",
1537                    "path": "/bad"
1538                }
1539            ],
1540            "locations": [
1541                {
1542                    "path": "/ok",
1543                    "line": 3
1544                },
1545                {
1546                    "line": 4
1547                }
1548            ]
1549        }))
1550        .unwrap();
1551
1552        let MaybeUndefined::Value(content) = deserialized.content else {
1553            panic!("content should deserialize to a value");
1554        };
1555        assert_eq!(content.len(), 1);
1556
1557        let MaybeUndefined::Value(locations) = deserialized.locations else {
1558            panic!("locations should deserialize to a value");
1559        };
1560        assert_eq!(locations.len(), 1);
1561    }
1562
1563    #[test]
1564    fn tool_call_content_chunk_serializes_single_content_item() {
1565        let chunk = ToolCallContentChunk::new(
1566            "tc_1",
1567            ContentBlock::Text(crate::v2::TextContent::new("partial output")),
1568        );
1569
1570        assert_eq!(
1571            serde_json::to_value(chunk).unwrap(),
1572            serde_json::json!({
1573                "toolCallId": "tc_1",
1574                "content": {
1575                    "type": "content",
1576                    "content": {
1577                        "type": "text",
1578                        "text": "partial output"
1579                    }
1580                }
1581            })
1582        );
1583    }
1584
1585    #[test]
1586    fn terminal_content_serializes_as_display_reference() {
1587        let terminal = ToolCallContent::from(Terminal::new("term_1"));
1588
1589        assert_eq!(
1590            serde_json::to_value(terminal).unwrap(),
1591            serde_json::json!({
1592                "type": "terminal",
1593                "terminalId": "term_1"
1594            })
1595        );
1596    }
1597
1598    #[test]
1599    fn diff_patch_serializes_git_patch_with_structured_changes() {
1600        let patch_text = "diff --git /repo/config.json /repo/config.json\n--- /repo/config.json\n+++ /repo/config.json\n@@ -1 +1 @@\n-old\n+new\n";
1601        let diff = ToolCallContent::Diff(Diff::patch(
1602            patch_text,
1603            vec![
1604                DiffChange::modify("/repo/config.json")
1605                    .file_type(DiffFileType::Text)
1606                    .mime_type("application/json"),
1607            ],
1608        ));
1609
1610        assert_eq!(
1611            serde_json::to_value(diff).unwrap(),
1612            serde_json::json!({
1613                "type": "diff",
1614                "changes": [
1615                    {
1616                        "operation": "modify",
1617                        "path": "/repo/config.json",
1618                        "fileType": "text",
1619                        "mimeType": "application/json"
1620                    }
1621                ],
1622                "patch": {
1623                    "format": "git_patch",
1624                    "text": patch_text
1625                }
1626            })
1627        );
1628    }
1629
1630    #[test]
1631    fn diff_patch_requires_text() {
1632        let result = serde_json::from_value::<DiffPatch>(serde_json::json!({
1633            "format": "git_patch",
1634            "diff": "diff --git /repo/config.json /repo/config.json\n"
1635        }));
1636
1637        assert!(result.is_err());
1638    }
1639
1640    #[test]
1641    fn diff_serializes_binary_modify_without_patch_text() {
1642        let diff = ToolCallContent::Diff(Diff::new(vec![
1643            DiffChange::modify("/repo/assets/logo.png")
1644                .file_type(DiffFileType::Binary)
1645                .mime_type("image/png"),
1646        ]));
1647
1648        assert_eq!(
1649            serde_json::to_value(diff).unwrap(),
1650            serde_json::json!({
1651                "type": "diff",
1652                "changes": [
1653                    {
1654                        "operation": "modify",
1655                        "path": "/repo/assets/logo.png",
1656                        "fileType": "binary",
1657                        "mimeType": "image/png"
1658                    }
1659                ]
1660            })
1661        );
1662    }
1663
1664    #[test]
1665    fn diff_move_serializes_shared_fields_with_operation_payload() {
1666        let diff = ToolCallContent::Diff(Diff::new(vec![
1667            DiffChange::move_file("/repo/src/old.rs", "/repo/src/new.rs")
1668                .file_type(DiffFileType::Text)
1669                .mime_type("text/rust"),
1670        ]));
1671
1672        assert_eq!(
1673            serde_json::to_value(diff).unwrap(),
1674            serde_json::json!({
1675                "type": "diff",
1676                "changes": [
1677                    {
1678                        "operation": "move",
1679                        "oldPath": "/repo/src/old.rs",
1680                        "path": "/repo/src/new.rs",
1681                        "fileType": "text",
1682                        "mimeType": "text/rust"
1683                    }
1684                ]
1685            })
1686        );
1687    }
1688
1689    #[test]
1690    fn diff_changes_skip_malformed_list_items() {
1691        let patch_text = "diff --git /ok /ok\ndeleted file mode 100644\n--- /ok\n+++ /dev/null\n@@ -1 +0,0 @@\n-old\n";
1692        let content: ToolCallContent = serde_json::from_value(serde_json::json!({
1693            "type": "diff",
1694            "changes": [
1695                {
1696                    "operation": "modify"
1697                },
1698                {
1699                    "operation": "delete",
1700                    "path": "/ok"
1701                }
1702            ],
1703            "patch": {
1704                "format": "git_patch",
1705                "text": patch_text
1706            }
1707        }))
1708        .unwrap();
1709
1710        let ToolCallContent::Diff(diff) = content else {
1711            panic!("expected diff content");
1712        };
1713        assert_eq!(diff.changes, vec![DiffChange::delete("/ok")]);
1714        assert_eq!(diff.patch, Some(DiffPatch::new(patch_text)));
1715    }
1716
1717    #[cfg(feature = "schemars")]
1718    #[test]
1719    fn diff_schema_requires_at_least_one_change() {
1720        let schema = serde_json::to_value(schemars::schema_for!(Diff)).unwrap();
1721        assert_eq!(schema["properties"]["changes"]["minItems"], 1);
1722    }
1723
1724    #[test]
1725    fn diff_with_no_changes_still_deserializes() {
1726        let diff: Diff = serde_json::from_value(serde_json::json!({ "changes": [] })).unwrap();
1727        assert_eq!(diff.changes, Vec::<DiffChange>::new());
1728    }
1729
1730    #[test]
1731    fn tool_kind_preserves_unknown_variant() {
1732        let kind: ToolKind = serde_json::from_str("\"review\"").unwrap();
1733        assert_eq!(kind, ToolKind::Unknown("review".to_string()));
1734        assert_eq!(serde_json::to_value(&kind).unwrap(), "review");
1735    }
1736
1737    #[test]
1738    fn tool_call_status_preserves_unknown_variant() {
1739        let status: ToolCallStatus = serde_json::from_str("\"deferred\"").unwrap();
1740        assert_eq!(status, ToolCallStatus::Other("deferred".to_string()));
1741        assert_eq!(serde_json::to_value(&status).unwrap(), "deferred");
1742    }
1743
1744    #[test]
1745    fn tool_call_status_recognizes_cancelled_variant() {
1746        let status: ToolCallStatus = serde_json::from_str("\"cancelled\"").unwrap();
1747        assert_eq!(status, ToolCallStatus::Cancelled);
1748        assert_eq!(serde_json::to_value(&status).unwrap(), "cancelled");
1749    }
1750
1751    #[test]
1752    fn tool_call_content_preserves_unknown_variant() {
1753        let content: ToolCallContent = serde_json::from_value(serde_json::json!({
1754            "type": "_chart",
1755            "title": "Tests",
1756            "data": [1, 2, 3]
1757        }))
1758        .unwrap();
1759
1760        let ToolCallContent::Other(unknown) = content else {
1761            panic!("expected unknown tool call content");
1762        };
1763
1764        assert_eq!(unknown.type_, "_chart");
1765        assert_eq!(
1766            unknown.fields.get("title"),
1767            Some(&serde_json::json!("Tests"))
1768        );
1769        assert_eq!(
1770            serde_json::to_value(ToolCallContent::Other(unknown)).unwrap(),
1771            serde_json::json!({
1772                "type": "_chart",
1773                "title": "Tests",
1774                "data": [1, 2, 3]
1775            })
1776        );
1777    }
1778
1779    #[test]
1780    fn tool_call_content_does_not_hide_malformed_known_variant() {
1781        assert!(
1782            serde_json::from_value::<ToolCallContent>(serde_json::json!({
1783                "type": "diff"
1784            }))
1785            .is_err()
1786        );
1787        assert!(
1788            serde_json::from_value::<ToolCallContent>(serde_json::json!({
1789                "type": "terminal"
1790            }))
1791            .is_err()
1792        );
1793    }
1794}