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