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
15#[cfg(feature = "unstable_subagents")]
16use super::SessionId;
17use super::{AbsolutePath, ContentBlock, MediaType, Meta, Terminal, apply_meta_update};
18use crate::{IntoMaybeUndefined, IntoOption, MaybeUndefined};
19
20/// Represents an upsert for a tool call that the language model has requested.
21///
22/// Tool calls are actions that the agent executes on behalf of the language model,
23/// such as reading files, executing code, or fetching data from external sources.
24///
25/// Only `toolCallId` is required. Other fields have patch semantics:
26/// omitted fields leave the existing tool call value unchanged, `null` clears or
27/// unsets the value, and concrete values replace the previous value. For
28/// collection fields, concrete arrays replace the previous collection, and both
29/// `null` and `[]` clear the collection. A concrete `_meta` object instead
30/// patches the stored metadata by top-level key. When a client receives a tool
31/// call ID it has not seen before, omitted fields start at their protocol defaults.
32///
33/// See protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls)
34#[serde_as]
35#[skip_serializing_none]
36#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "camelCase")]
39#[non_exhaustive]
40pub struct ToolCallUpdate {
41    /// Unique identifier for this tool call within the session.
42    pub tool_call_id: ToolCallId,
43    /// Programmatic name of the tool being invoked.
44    ///
45    /// This field is optional and has patch semantics. Omission means no
46    /// change, `null` clears the name, and a string replaces it. For a tool
47    /// call ID the client has not seen before, omission or `null` means that no
48    /// tool name is available.
49    #[serde_as(deserialize_as = "DefaultOnError")]
50    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
51    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
52    pub name: MaybeUndefined<String>,
53    /// Human-readable title describing what the tool is doing.
54    ///
55    /// Omission leaves the title unchanged, `null` unsets it, and a string replaces it.
56    /// A new tool call starts without a title.
57    #[serde_as(deserialize_as = "DefaultOnError")]
58    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
59    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
60    pub title: MaybeUndefined<String>,
61    /// The category of tool being invoked.
62    /// Helps clients choose appropriate icons and UI treatment.
63    ///
64    /// Omission leaves the kind unchanged, `null` resets it to `other`, and a value replaces it.
65    /// A new tool call starts as `other`.
66    #[serde_as(deserialize_as = "DefaultOnError")]
67    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
68    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
69    pub kind: MaybeUndefined<ToolKind>,
70    /// Current execution status of the tool call.
71    ///
72    /// Omission leaves the status unchanged, `null` resets it to `pending`, and a value
73    /// replaces it. A new tool call starts as `pending`.
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    /// **UNSTABLE**
529    ///
530    /// This capability is not part of the spec yet, and may be removed or changed at any point.
531    ///
532    /// A display-only reference to another session, such as a subagent.
533    #[cfg(feature = "unstable_subagents")]
534    Session(SessionReference),
535    /// Custom or future tool call content.
536    ///
537    /// Values beginning with `_` are reserved for implementation-specific
538    /// extensions. Unknown values that do not begin with `_` are reserved for
539    /// future ACP variants.
540    ///
541    /// Receivers that do not understand this content type should preserve the
542    /// raw payload when storing, replaying, proxying, or forwarding tool call
543    /// output, and otherwise ignore it or display it generically.
544    #[serde(untagged)]
545    Other(OtherToolCallContent),
546}
547
548/// Custom or future tool call content payload.
549#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
550#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
551#[cfg_attr(feature = "schemars", schemars(inline))]
552#[cfg_attr(feature = "schemars", schemars(transform = other_tool_call_content_schema))]
553#[serde(rename_all = "camelCase")]
554#[non_exhaustive]
555pub struct OtherToolCallContent {
556    /// Custom or future tool call content type.
557    ///
558    /// Values beginning with `_` are reserved for implementation-specific
559    /// extensions. Unknown values that do not begin with `_` are reserved for
560    /// future ACP variants.
561    #[serde(rename = "type")]
562    pub type_: String,
563    /// Additional fields from the unknown tool call content payload.
564    #[serde(flatten)]
565    pub fields: BTreeMap<String, serde_json::Value>,
566}
567
568impl OtherToolCallContent {
569    /// Builds [`OtherToolCallContent`] from an unknown discriminator and preserves the remaining extension fields.
570    #[must_use]
571    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
572        fields.remove("type");
573        Self {
574            type_: type_.into(),
575            fields,
576        }
577    }
578}
579
580impl<'de> Deserialize<'de> for OtherToolCallContent {
581    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
582    where
583        D: serde::Deserializer<'de>,
584    {
585        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
586        let type_ = fields
587            .remove("type")
588            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
589        let serde_json::Value::String(type_) = type_ else {
590            return Err(serde::de::Error::custom("`type` must be a string"));
591        };
592
593        if is_known_tool_call_content_type(&type_) {
594            return Err(serde::de::Error::custom(format!(
595                "known tool call content `{type_}` did not match its schema"
596            )));
597        }
598
599        Ok(Self { type_, fields })
600    }
601}
602
603fn is_known_tool_call_content_type(type_: &str) -> bool {
604    KNOWN_TOOL_CALL_CONTENT_TYPES.contains(&type_)
605}
606
607const KNOWN_TOOL_CALL_CONTENT_TYPES: &[&str] = &[
608    "content",
609    "diff",
610    "terminal",
611    #[cfg(feature = "unstable_subagents")]
612    "session",
613];
614
615#[cfg(feature = "schemars")]
616fn other_tool_call_content_schema(schema: &mut Schema) {
617    super::schema_util::reject_known_string_discriminators(
618        schema,
619        "type",
620        KNOWN_TOOL_CALL_CONTENT_TYPES,
621    );
622}
623
624impl<T: Into<ContentBlock>> From<T> for ToolCallContent {
625    fn from(content: T) -> Self {
626        ToolCallContent::Content(Box::new(Content::new(content)))
627    }
628}
629
630impl From<Diff> for ToolCallContent {
631    fn from(diff: Diff) -> Self {
632        ToolCallContent::Diff(diff)
633    }
634}
635
636impl From<Terminal> for ToolCallContent {
637    fn from(terminal: Terminal) -> Self {
638        ToolCallContent::Terminal(terminal)
639    }
640}
641
642/// **UNSTABLE**
643///
644/// This capability is not part of the spec yet, and may be removed or changed at any point.
645///
646/// A display-only reference to another session that this tool call operates on,
647/// such as a subagent it created, delegated to, or is waiting on.
648///
649/// The referenced session must already be known to the Client through ordinary
650/// session setup or a `subagent_update` announcement. The reference does not
651/// establish ownership, grant any Client-initiated controls, or report that the
652/// referenced session received or finished any work.
653#[cfg(feature = "unstable_subagents")]
654#[serde_as]
655#[skip_serializing_none]
656#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
657#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
658#[serde(rename_all = "camelCase")]
659#[non_exhaustive]
660pub struct SessionReference {
661    /// The referenced session.
662    pub session_id: SessionId,
663    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
664    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
665    /// Implementations MUST NOT assign meaning to keys they do not recognize.
666    ///
667    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
668    #[serde_as(deserialize_as = "DefaultOnError")]
669    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
670    #[serde(default)]
671    #[serde(rename = "_meta")]
672    pub meta: Option<Meta>,
673}
674
675#[cfg(feature = "unstable_subagents")]
676impl SessionReference {
677    /// Builds [`SessionReference`] with the required fields set. Optional fields start unset or empty.
678    #[must_use]
679    pub fn new(session_id: impl Into<SessionId>) -> Self {
680        Self {
681            session_id: session_id.into(),
682            meta: None,
683        }
684    }
685
686    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
687    /// metadata to their interactions.
688    #[must_use]
689    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
690        self.meta = meta.into_option();
691        self
692    }
693}
694
695#[cfg(feature = "unstable_subagents")]
696impl From<SessionReference> for ToolCallContent {
697    fn from(session: SessionReference) -> Self {
698        ToolCallContent::Session(session)
699    }
700}
701
702/// Standard content block (text, images, resources).
703#[serde_as]
704#[skip_serializing_none]
705#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
706#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
707#[serde(rename_all = "camelCase")]
708#[non_exhaustive]
709pub struct Content {
710    /// The actual content block.
711    pub content: ContentBlock,
712    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
713    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
714    /// Implementations MUST NOT assign meaning to keys they do not recognize.
715    ///
716    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
717    #[serde_as(deserialize_as = "DefaultOnError")]
718    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
719    #[serde(default)]
720    #[serde(rename = "_meta")]
721    pub meta: Option<Meta>,
722}
723
724impl Content {
725    /// Builds [`Content`] with the required fields set. Optional fields start unset or empty.
726    #[must_use]
727    pub fn new(content: impl Into<ContentBlock>) -> Self {
728        Self {
729            content: content.into(),
730            meta: None,
731        }
732    }
733
734    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
735    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
736    /// do not recognize.
737    ///
738    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
739    #[must_use]
740    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
741        self.meta = meta.into_option();
742        self
743    }
744}
745
746/// File changes produced by a tool call.
747///
748/// `changes` is authoritative for affected absolute paths and operations.
749/// `patch` optionally carries renderable text for some or all of those changes
750/// and MUST be consistent with `changes`. Agents SHOULD provide `patch` whenever
751/// feasible. Clients MUST handle diffs where `patch` is omitted or `null`.
752///
753/// See protocol docs: [Content](https://agentclientprotocol.com/protocol/v2/tool-calls#content)
754#[serde_as]
755#[skip_serializing_none]
756#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
757#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
758#[serde(rename_all = "camelCase")]
759#[non_exhaustive]
760pub struct Diff {
761    /// Structured file changes described by this diff.
762    ///
763    /// Clients can use this field without parsing patch text to determine affected paths.
764    #[serde_as(deserialize_as = "VecSkipError<_>")]
765    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
766    pub changes: Vec<DiffChange>,
767    /// Renderable patch text for some or all of the structured changes.
768    ///
769    /// Agents SHOULD provide patch text whenever feasible. Omitted and `null` are
770    /// equivalent and mean no renderable patch text was provided.
771    #[serde_as(deserialize_as = "DefaultOnError")]
772    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
773    #[serde(default)]
774    pub patch: Option<DiffPatch>,
775    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
776    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
777    /// Implementations MUST NOT assign meaning to keys they do not recognize.
778    ///
779    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
780    #[serde_as(deserialize_as = "DefaultOnError")]
781    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
782    #[serde(default)]
783    #[serde(rename = "_meta")]
784    pub meta: Option<Meta>,
785}
786
787impl Diff {
788    /// Builds [`Diff`] with structured file changes.
789    #[must_use]
790    pub fn new(changes: Vec<DiffChange>) -> Self {
791        Self {
792            changes,
793            patch: None,
794            meta: None,
795        }
796    }
797
798    /// Builds [`Diff`] with Git `--patch` text and structured file changes.
799    #[must_use]
800    pub fn patch(text: impl Into<String>, changes: Vec<DiffChange>) -> Self {
801        Self::new(changes).with_patch(DiffPatch::new(text))
802    }
803
804    /// Sets renderable patch text.
805    #[must_use]
806    pub fn with_patch(mut self, patch: impl IntoOption<DiffPatch>) -> Self {
807        self.patch = patch.into_option();
808        self
809    }
810
811    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
812    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
813    /// do not recognize.
814    ///
815    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
816    #[must_use]
817    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
818        self.meta = meta.into_option();
819        self
820    }
821}
822
823/// Renderable patch text and its format.
824#[serde_as]
825#[skip_serializing_none]
826#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
827#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
828#[serde(rename_all = "camelCase")]
829#[non_exhaustive]
830pub struct DiffPatch {
831    /// Patch format. The only ACP-defined value is `git_patch`.
832    pub format: DiffPatchFormat,
833    /// Patch text in the format named by `format`.
834    pub text: String,
835    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
836    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
837    /// Implementations MUST NOT assign meaning to keys they do not recognize.
838    ///
839    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
840    #[serde_as(deserialize_as = "DefaultOnError")]
841    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
842    #[serde(default)]
843    #[serde(rename = "_meta")]
844    pub meta: Option<Meta>,
845}
846
847impl DiffPatch {
848    /// Builds [`DiffPatch`] with Git `--patch` text.
849    #[must_use]
850    pub fn new(text: impl Into<String>) -> Self {
851        Self {
852            format: DiffPatchFormat::GitPatch,
853            text: text.into(),
854            meta: None,
855        }
856    }
857
858    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
859    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
860    /// do not recognize.
861    ///
862    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
863    #[must_use]
864    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
865        self.meta = meta.into_option();
866        self
867    }
868}
869
870/// Text patch format used by `DiffPatch`.
871#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
872#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
873#[serde(rename_all = "snake_case")]
874#[non_exhaustive]
875pub enum DiffPatchFormat {
876    /// One or more `diff --git` sections in Git's `--patch` (`-p`) text format.
877    ///
878    /// Unlike Git, which writes paths relative to the repository root, every
879    /// path MUST be absolute, including in `rename from`, `rename to`,
880    /// `copy from`, and `copy to` lines, and MUST NOT have a prefix such as
881    /// Git's default `a/` and `b/`. Otherwise paths follow Git: `/dev/null`
882    /// names the missing side of an added or deleted file in the `---` and
883    /// `+++` lines, and paths with unusual characters are quoted as Git quotes
884    /// them. Each path, once unquoted, is the same native absolute path string as
885    /// the matching `changes` entry. Surrounding commit metadata and email envelopes MUST NOT be
886    /// included.
887    GitPatch,
888    /// Custom or future patch format.
889    ///
890    /// Values beginning with `_` are reserved for implementation-specific
891    /// extensions. Unknown values that do not begin with `_` are reserved for
892    /// future ACP variants.
893    #[serde(untagged)]
894    Other(String),
895}
896
897/// Kind of file content represented by a diff change.
898#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
899#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
900#[serde(rename_all = "snake_case")]
901#[non_exhaustive]
902pub enum DiffFileType {
903    /// Text content.
904    Text,
905    /// Binary or otherwise non-text content.
906    Binary,
907    /// Directory entry.
908    Directory,
909    /// Symbolic link.
910    Symlink,
911    /// Custom or future file type.
912    ///
913    /// Values beginning with `_` are reserved for implementation-specific
914    /// extensions. Unknown values that do not begin with `_` are reserved for
915    /// future ACP variants.
916    #[serde(untagged)]
917    Other(String),
918}
919
920/// One file-level change described by a `Diff`.
921///
922/// Structured change metadata lets clients identify affected files and
923/// operations without parsing the text patch.
924#[serde_as]
925#[skip_serializing_none]
926#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
927#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
928#[serde(rename_all = "camelCase")]
929#[non_exhaustive]
930pub struct DiffChange {
931    /// File content kind after the operation (for `delete`, of the deleted file).
932    ///
933    /// Omitted and `null` are equivalent and mean the content kind is unknown.
934    #[serde_as(deserialize_as = "DefaultOnError")]
935    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
936    #[serde(default)]
937    pub file_type: Option<DiffFileType>,
938    /// MIME type of the file contents after the operation (for `delete`, of the deleted file).
939    ///
940    /// Omitted and `null` are equivalent and mean the MIME type is unknown.
941    #[serde_as(deserialize_as = "DefaultOnError")]
942    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
943    #[serde(default)]
944    pub mime_type: Option<MediaType>,
945    /// File operation-specific fields.
946    #[serde(flatten)]
947    pub operation: DiffChangeOperation,
948    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
949    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
950    /// Implementations MUST NOT assign meaning to keys they do not recognize.
951    ///
952    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
953    #[serde_as(deserialize_as = "DefaultOnError")]
954    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
955    #[serde(default)]
956    #[serde(rename = "_meta")]
957    pub meta: Option<Meta>,
958}
959
960impl DiffChange {
961    /// Builds [`DiffChange`] with the required fields set. Optional fields start unset or empty.
962    #[must_use]
963    pub fn new(operation: DiffChangeOperation) -> Self {
964        Self {
965            file_type: None,
966            mime_type: None,
967            operation,
968            meta: None,
969        }
970    }
971
972    /// Builds a file add change.
973    #[must_use]
974    pub fn add(path: impl Into<AbsolutePath>) -> Self {
975        Self::new(DiffChangeOperation::Add(DiffPathChange::new(path)))
976    }
977
978    /// Builds a file delete change.
979    #[must_use]
980    pub fn delete(path: impl Into<AbsolutePath>) -> Self {
981        Self::new(DiffChangeOperation::Delete(DiffPathChange::new(path)))
982    }
983
984    /// Builds a file modify change.
985    #[must_use]
986    pub fn modify(path: impl Into<AbsolutePath>) -> Self {
987        Self::new(DiffChangeOperation::Modify(DiffPathChange::new(path)))
988    }
989
990    /// Builds a file move or rename change.
991    #[must_use]
992    pub fn move_file(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
993        Self::new(DiffChangeOperation::Move(DiffPathPairChange::new(
994            old_path, path,
995        )))
996    }
997
998    /// Builds a file copy change.
999    #[must_use]
1000    pub fn copy(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
1001        Self::new(DiffChangeOperation::Copy(DiffPathPairChange::new(
1002            old_path, path,
1003        )))
1004    }
1005
1006    /// File content kind.
1007    ///
1008    /// Omitted and `null` are equivalent and mean the content kind is unknown.
1009    #[must_use]
1010    pub fn file_type(mut self, file_type: impl IntoOption<DiffFileType>) -> Self {
1011        self.file_type = file_type.into_option();
1012        self
1013    }
1014
1015    /// MIME type of the file contents.
1016    ///
1017    /// Omitted and `null` are equivalent and mean the MIME type is unknown.
1018    #[must_use]
1019    pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
1020        self.mime_type = mime_type.into_option();
1021        self
1022    }
1023
1024    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1025    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1026    /// do not recognize.
1027    ///
1028    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1029    #[must_use]
1030    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1031        self.meta = meta.into_option();
1032        self
1033    }
1034}
1035
1036/// File operation for a [`DiffChange`].
1037#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1038#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1039#[serde(tag = "operation", rename_all = "snake_case")]
1040#[non_exhaustive]
1041pub enum DiffChangeOperation {
1042    /// A file was added.
1043    Add(DiffPathChange),
1044    /// A file was deleted.
1045    Delete(DiffPathChange),
1046    /// A file was modified in place.
1047    Modify(DiffPathChange),
1048    /// A file was moved or renamed.
1049    Move(DiffPathPairChange),
1050    /// A file was copied.
1051    Copy(DiffPathPairChange),
1052    /// Custom or future file operation.
1053    ///
1054    /// Values beginning with `_` are reserved for implementation-specific
1055    /// extensions. Unknown values that do not begin with `_` are reserved for
1056    /// future ACP variants.
1057    #[serde(untagged)]
1058    Other(OtherDiffChange),
1059}
1060
1061/// Operation metadata for add, delete, and modify 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 DiffPathChange {
1067    /// Absolute path for the operation.
1068    pub path: AbsolutePath,
1069}
1070
1071impl DiffPathChange {
1072    /// Builds [`DiffPathChange`] with the required fields set. Optional fields start unset or empty.
1073    #[must_use]
1074    pub fn new(path: impl Into<AbsolutePath>) -> Self {
1075        Self { path: path.into() }
1076    }
1077}
1078
1079/// Operation metadata for move and copy changes.
1080#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1081#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1082#[serde(rename_all = "camelCase")]
1083#[non_exhaustive]
1084pub struct DiffPathPairChange {
1085    /// Absolute path before the operation.
1086    pub old_path: AbsolutePath,
1087    /// Absolute path after the operation.
1088    pub path: AbsolutePath,
1089}
1090
1091impl DiffPathPairChange {
1092    /// Builds [`DiffPathPairChange`] with the required fields set. Optional fields start unset or empty.
1093    #[must_use]
1094    pub fn new(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
1095        Self {
1096            old_path: old_path.into(),
1097            path: path.into(),
1098        }
1099    }
1100}
1101
1102/// Custom or future file operation payload.
1103#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1104#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1105#[cfg_attr(feature = "schemars", schemars(inline))]
1106#[cfg_attr(feature = "schemars", schemars(transform = other_diff_change_schema))]
1107#[serde(rename_all = "camelCase")]
1108#[non_exhaustive]
1109pub struct OtherDiffChange {
1110    /// Custom or future file operation.
1111    ///
1112    /// Values beginning with `_` are reserved for implementation-specific
1113    /// extensions. Unknown values that do not begin with `_` are reserved for
1114    /// future ACP variants.
1115    pub operation: String,
1116    /// Additional fields from the unknown file operation payload.
1117    #[serde(flatten)]
1118    pub fields: BTreeMap<String, serde_json::Value>,
1119}
1120
1121impl OtherDiffChange {
1122    /// Builds [`OtherDiffChange`] from an unknown discriminator and preserves the remaining extension fields.
1123    #[must_use]
1124    pub fn new(
1125        operation: impl Into<String>,
1126        mut fields: BTreeMap<String, serde_json::Value>,
1127    ) -> Self {
1128        fields.remove("operation");
1129        fields.remove("fileType");
1130        fields.remove("mimeType");
1131        fields.remove("_meta");
1132        Self {
1133            operation: operation.into(),
1134            fields,
1135        }
1136    }
1137}
1138
1139impl<'de> Deserialize<'de> for OtherDiffChange {
1140    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1141    where
1142        D: serde::Deserializer<'de>,
1143    {
1144        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1145        let operation = fields
1146            .remove("operation")
1147            .ok_or_else(|| serde::de::Error::missing_field("operation"))?;
1148        let serde_json::Value::String(operation) = operation else {
1149            return Err(serde::de::Error::custom("`operation` must be a string"));
1150        };
1151
1152        if is_known_diff_change_operation(&operation) {
1153            return Err(serde::de::Error::custom(format!(
1154                "known diff change operation `{operation}` did not match its schema"
1155            )));
1156        }
1157        fields.remove("fileType");
1158        fields.remove("mimeType");
1159        fields.remove("_meta");
1160
1161        Ok(Self { operation, fields })
1162    }
1163}
1164
1165fn is_known_diff_change_operation(operation: &str) -> bool {
1166    matches!(operation, "add" | "delete" | "modify" | "move" | "copy")
1167}
1168
1169#[cfg(feature = "schemars")]
1170fn other_diff_change_schema(schema: &mut Schema) {
1171    super::schema_util::reject_known_string_discriminators(
1172        schema,
1173        "operation",
1174        &["add", "delete", "modify", "move", "copy"],
1175    );
1176}
1177
1178/// A file location being accessed or modified by a tool.
1179///
1180/// Enables clients to implement "follow-along" features that track
1181/// which files the agent is working with in real-time.
1182///
1183/// See protocol docs: [Following the Agent](https://agentclientprotocol.com/protocol/v2/tool-calls#following-the-agent)
1184#[serde_as]
1185#[skip_serializing_none]
1186#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1187#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1188#[serde(rename_all = "camelCase")]
1189#[non_exhaustive]
1190pub struct ToolCallLocation {
1191    /// The absolute file path being accessed or modified.
1192    pub path: AbsolutePath,
1193    /// Optional 1-based line number within the file. Omitted and `null` are equivalent and
1194    /// mean no specific line. `0` is invalid.
1195    #[serde_as(deserialize_as = "DefaultOnError")]
1196    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1197    #[serde(default)]
1198    pub line: Option<std::num::NonZeroU32>,
1199    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1200    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1201    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1202    ///
1203    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1204    #[serde_as(deserialize_as = "DefaultOnError")]
1205    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1206    #[serde(default)]
1207    #[serde(rename = "_meta")]
1208    pub meta: Option<Meta>,
1209}
1210
1211impl ToolCallLocation {
1212    /// Builds [`ToolCallLocation`] with the required fields set. Optional fields start unset or empty.
1213    #[must_use]
1214    pub fn new(path: impl Into<AbsolutePath>) -> Self {
1215        Self {
1216            path: path.into(),
1217            line: None,
1218            meta: None,
1219        }
1220    }
1221
1222    /// Optional line number within the file.
1223    ///
1224    /// Line numbers are 1-based, and `0` is invalid on the wire. This builder maps `0` to no
1225    /// specific line.
1226    #[must_use]
1227    pub fn line(mut self, line: impl IntoOption<u32>) -> Self {
1228        self.line = line.into_option().and_then(std::num::NonZeroU32::new);
1229        self
1230    }
1231
1232    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1233    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1234    /// do not recognize.
1235    ///
1236    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1237    #[must_use]
1238    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1239        self.meta = meta.into_option();
1240        self
1241    }
1242}
1243
1244#[cfg(test)]
1245mod tests {
1246
1247    #[cfg(feature = "unstable_subagents")]
1248    #[test]
1249    fn session_reference_tool_call_content_round_trips() {
1250        use serde_json::json;
1251        let content = ToolCallContent::from(SessionReference::new("sess_child_1"));
1252        let value = serde_json::to_value(&content).unwrap();
1253        assert_eq!(
1254            value,
1255            json!({ "type": "session", "sessionId": "sess_child_1" })
1256        );
1257        assert_eq!(
1258            serde_json::from_value::<ToolCallContent>(value).unwrap(),
1259            content
1260        );
1261        // A malformed known variant must not fall through to `Other`.
1262        assert!(serde_json::from_value::<ToolCallContent>(json!({ "type": "session" })).is_err());
1263    }
1264
1265    #[test]
1266    fn location_line_is_one_based() {
1267        let location: ToolCallLocation =
1268            serde_json::from_value(serde_json::json!({ "path": "/a.rs", "line": 0 })).unwrap();
1269        assert_eq!(location.line, None);
1270        let location: ToolCallLocation =
1271            serde_json::from_value(serde_json::json!({ "path": "/a.rs", "line": 3 })).unwrap();
1272        assert_eq!(location.line.map(std::num::NonZeroU32::get), Some(3));
1273        assert_eq!(ToolCallLocation::new("/a.rs").line(0).line, None);
1274    }
1275
1276    #[test]
1277    fn toolcall_capabilities_patch_and_tolerate_malformed_values() {
1278        use serde_json::json;
1279        let update = ToolCallUpdate::new("call_012")
1280            .capabilities(ToolCallCapabilities::new().cancel(ToolCallCancelCapabilities::new()));
1281        assert_eq!(
1282            serde_json::to_value(&update).unwrap(),
1283            json!({ "toolCallId": "call_012", "capabilities": { "cancel": {} } })
1284        );
1285
1286        let mut stored = update;
1287        stored.apply_update(ToolCallUpdate::new("call_012"));
1288        assert!(stored.capabilities.is_value());
1289        stored.apply_update(ToolCallUpdate::new("call_012").capabilities(MaybeUndefined::Null));
1290        assert!(stored.capabilities.is_null());
1291
1292        for bad in [json!("yes"), json!(1)] {
1293            let parsed: ToolCallUpdate =
1294                serde_json::from_value(json!({ "toolCallId": "call_012", "capabilities": bad }))
1295                    .unwrap();
1296            assert!(parsed.capabilities.is_undefined());
1297        }
1298        let parsed: ToolCallCapabilities =
1299            serde_json::from_value(json!({ "cancel": "yes" })).unwrap();
1300        assert_eq!(parsed.cancel, None);
1301    }
1302
1303    #[test]
1304    fn paused_is_a_known_tool_call_status() {
1305        use serde_json::json;
1306        assert_eq!(
1307            serde_json::to_value(ToolCallStatus::Paused).unwrap(),
1308            json!("paused")
1309        );
1310        assert_eq!(
1311            serde_json::from_value::<ToolCallStatus>(json!("paused")).unwrap(),
1312            ToolCallStatus::Paused
1313        );
1314    }
1315
1316    use super::*;
1317    use crate::MaybeUndefined;
1318    use serde_json::{from_value, json, to_value};
1319
1320    #[test]
1321    fn tool_call_serializes_as_upsert() {
1322        let tool_call = ToolCallUpdate::new("tc_1")
1323            .title("Reading configuration")
1324            .status(ToolCallStatus::InProgress)
1325            .raw_input(serde_json::json!({"path": "settings.json"}));
1326
1327        assert_eq!(
1328            serde_json::to_value(tool_call).unwrap(),
1329            serde_json::json!({
1330                "toolCallId": "tc_1",
1331                "title": "Reading configuration",
1332                "status": "in_progress",
1333                "rawInput": {
1334                    "path": "settings.json"
1335                }
1336            })
1337        );
1338    }
1339
1340    #[test]
1341    fn tool_call_update_distinguishes_omitted_null_and_value() {
1342        let tool_call = ToolCallUpdate::new("tc_1")
1343            .status(ToolCallStatus::Completed)
1344            .content(None::<Vec<ToolCallContent>>);
1345
1346        assert_eq!(
1347            serde_json::to_value(tool_call).unwrap(),
1348            serde_json::json!({
1349                "toolCallId": "tc_1",
1350                "status": "completed",
1351                "content": null
1352            })
1353        );
1354
1355        let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1356            "toolCallId": "tc_1",
1357            "status": null,
1358            "locations": []
1359        }))
1360        .unwrap();
1361        assert_eq!(deserialized.title, MaybeUndefined::Undefined);
1362        assert_eq!(deserialized.status, MaybeUndefined::Null);
1363        assert_eq!(deserialized.locations, MaybeUndefined::Value(Vec::new()));
1364    }
1365
1366    #[test]
1367    fn tool_call_name_patch_distinguishes_omitted_null_and_value() {
1368        let named = ToolCallUpdate::new("tc_1").name("read_file");
1369        assert_eq!(
1370            serde_json::to_value(named).unwrap(),
1371            serde_json::json!({
1372                "toolCallId": "tc_1",
1373                "name": "read_file"
1374            })
1375        );
1376
1377        let omitted = ToolCallUpdate::new("tc_1");
1378        assert_eq!(omitted.name, MaybeUndefined::Undefined);
1379
1380        let from_null: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1381            "toolCallId": "tc_1",
1382            "name": null
1383        }))
1384        .unwrap();
1385        assert_eq!(from_null.name, MaybeUndefined::Null);
1386
1387        let mut stored = ToolCallUpdate::new("tc_1").name("read_file");
1388        stored.apply_update(ToolCallUpdate::new("tc_1"));
1389        assert_eq!(stored.name, MaybeUndefined::Value("read_file".to_string()));
1390
1391        stored.apply_update(ToolCallUpdate::new("tc_1").name(None::<String>));
1392        assert_eq!(stored.name, MaybeUndefined::Null);
1393
1394        stored.apply_update(ToolCallUpdate::new("tc_1").name("write_file"));
1395        assert_eq!(stored.name, MaybeUndefined::Value("write_file".to_string()));
1396    }
1397
1398    #[test]
1399    fn tool_call_update_distinguishes_meta_omitted_null_and_value() {
1400        let mut meta = Meta::new();
1401        meta.insert("source".to_string(), serde_json::json!("tool-call"));
1402
1403        assert_eq!(
1404            serde_json::to_value(ToolCallUpdate::new("tc_1").meta(meta.clone())).unwrap(),
1405            serde_json::json!({
1406                "toolCallId": "tc_1",
1407                "_meta": {
1408                    "source": "tool-call"
1409                }
1410            })
1411        );
1412
1413        assert_eq!(
1414            serde_json::to_value(ToolCallUpdate::new("tc_1").meta(None::<Meta>)).unwrap(),
1415            serde_json::json!({
1416                "toolCallId": "tc_1",
1417                "_meta": null
1418            })
1419        );
1420
1421        let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1422            "toolCallId": "tc_1",
1423            "_meta": null
1424        }))
1425        .unwrap();
1426        assert_eq!(deserialized.meta, MaybeUndefined::Null);
1427
1428        let patch = ToolCallUpdate::new("tc_1");
1429        assert_eq!(patch.meta, MaybeUndefined::Undefined);
1430
1431        let mut stored = ToolCallUpdate::new("tc_1").meta(meta);
1432        stored.apply_update(ToolCallUpdate::new("tc_1").meta(None::<Meta>));
1433        assert_eq!(stored.meta, MaybeUndefined::Null);
1434    }
1435
1436    #[test]
1437    fn tool_call_update_patches_meta_by_top_level_key() {
1438        let mut stored: ToolCallUpdate = from_value(json!({
1439            "toolCallId": "tc_1",
1440            "_meta": {"zed.dev/a": 1, "acme.dev/b": {"x": 1}}
1441        }))
1442        .unwrap();
1443
1444        // A writer that only knows its own key must not erase other keys.
1445        stored.apply_update(
1446            from_value(json!({"toolCallId": "tc_1", "_meta": {"proxy.dev/c": true}})).unwrap(),
1447        );
1448        stored.apply_update(
1449            from_value(json!({
1450                "toolCallId": "tc_1",
1451                "_meta": {"zed.dev/a": null, "acme.dev/b": {"y": 2}}
1452            }))
1453            .unwrap(),
1454        );
1455
1456        assert_eq!(
1457            to_value(&stored).unwrap(),
1458            json!({
1459                "toolCallId": "tc_1",
1460                "_meta": {"acme.dev/b": {"y": 2}, "proxy.dev/c": true}
1461            })
1462        );
1463    }
1464
1465    #[test]
1466    fn tool_call_wire_patches_preserve_omitted_fields_and_replace_values() {
1467        let initial = json!({
1468            "toolCallId": "tc_1",
1469            "_meta": {"source": "replay", "opaque": {"sequence": 1}}
1470        });
1471        let mut stored: ToolCallUpdate = from_value(initial.clone()).unwrap();
1472        // A metadata-only first update must not invent content or a status.
1473        assert_eq!(to_value(&stored).unwrap(), initial);
1474
1475        let populated = json!({
1476            "toolCallId": "tc_1",
1477            "name": "read_file",
1478            "title": "Reading configuration",
1479            "kind": "read",
1480            "status": "in_progress",
1481            "content": [{
1482                "type": "content",
1483                "content": {
1484                    "type": "text",
1485                    "text": "old",
1486                    "_meta": {"source": "tool"}
1487                }
1488            }],
1489            "locations": [{"path": "/workspace/config.json", "line": 3}],
1490            "rawInput": {"path": "/workspace/config.json"},
1491            "rawOutput": {"text": "old"}
1492        });
1493        stored.apply_update(from_value(populated.clone()).unwrap());
1494        let mut expected = populated;
1495        expected["_meta"] = initial["_meta"].clone();
1496        assert_eq!(to_value(&stored).unwrap(), expected);
1497
1498        for (field, empty) in [
1499            ("content", json!([])),
1500            ("locations", json!([])),
1501            ("rawInput", json!({})),
1502            ("rawOutput", json!({})),
1503        ] {
1504            let original = expected[field].clone();
1505            // Empty values replace rather than merge; null remains distinct.
1506            // Restoring the value also checks that clearing is not permanent.
1507            for replacement in [empty, json!(null), original] {
1508                stored.apply_update(
1509                    from_value(json!({"toolCallId": "tc_1", (field): replacement})).unwrap(),
1510                );
1511                expected[field] = replacement;
1512                assert_eq!(to_value(&stored).unwrap(), expected, "patching {field}");
1513
1514                stored.apply_update(from_value(json!({"toolCallId": "tc_1"})).unwrap());
1515                assert_eq!(to_value(&stored).unwrap(), expected, "omitting {field}");
1516            }
1517        }
1518    }
1519
1520    #[test]
1521    fn tool_call_wire_patches_preserve_unknown_statuses() {
1522        for status in ["deferred", "_awaiting_review"] {
1523            let mut stored = ToolCallUpdate::new("tc_1").status(ToolCallStatus::InProgress);
1524            stored
1525                .apply_update(from_value(json!({"toolCallId": "tc_1", "status": status})).unwrap());
1526            let expected_status = MaybeUndefined::Value(ToolCallStatus::Other(status.to_owned()));
1527            assert_eq!(stored.status, expected_status);
1528
1529            // An unrelated patch must not reset a future or extension status
1530            // to a known value, including a success or failure state.
1531            stored.apply_update(
1532                from_value(json!({"toolCallId": "tc_1", "title": "Still waiting"})).unwrap(),
1533            );
1534            assert_eq!(stored.status, expected_status);
1535            assert_eq!(
1536                to_value(&stored).unwrap(),
1537                json!({"toolCallId": "tc_1", "title": "Still waiting", "status": status})
1538            );
1539        }
1540    }
1541
1542    #[test]
1543    fn tool_call_update_skips_malformed_list_items() {
1544        let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1545            "toolCallId": "tc_1",
1546            "content": [
1547                {
1548                    "type": "content",
1549                    "content": {
1550                        "type": "text",
1551                        "text": "ok"
1552                    }
1553                },
1554                {
1555                    "type": "diff",
1556                    "path": "/bad"
1557                }
1558            ],
1559            "locations": [
1560                {
1561                    "path": "/ok",
1562                    "line": 3
1563                },
1564                {
1565                    "line": 4
1566                }
1567            ]
1568        }))
1569        .unwrap();
1570
1571        let MaybeUndefined::Value(content) = deserialized.content else {
1572            panic!("content should deserialize to a value");
1573        };
1574        assert_eq!(content.len(), 1);
1575
1576        let MaybeUndefined::Value(locations) = deserialized.locations else {
1577            panic!("locations should deserialize to a value");
1578        };
1579        assert_eq!(locations.len(), 1);
1580    }
1581
1582    #[test]
1583    fn tool_call_content_chunk_serializes_single_content_item() {
1584        let chunk = ToolCallContentChunk::new(
1585            "tc_1",
1586            ContentBlock::Text(crate::v2::TextContent::new("partial output")),
1587        );
1588
1589        assert_eq!(
1590            serde_json::to_value(chunk).unwrap(),
1591            serde_json::json!({
1592                "toolCallId": "tc_1",
1593                "content": {
1594                    "type": "content",
1595                    "content": {
1596                        "type": "text",
1597                        "text": "partial output"
1598                    }
1599                }
1600            })
1601        );
1602    }
1603
1604    #[test]
1605    fn terminal_content_serializes_as_display_reference() {
1606        let terminal = ToolCallContent::from(Terminal::new("term_1"));
1607
1608        assert_eq!(
1609            serde_json::to_value(terminal).unwrap(),
1610            serde_json::json!({
1611                "type": "terminal",
1612                "terminalId": "term_1"
1613            })
1614        );
1615    }
1616
1617    #[test]
1618    fn diff_patch_serializes_git_patch_with_structured_changes() {
1619        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";
1620        let diff = ToolCallContent::Diff(Diff::patch(
1621            patch_text,
1622            vec![
1623                DiffChange::modify("/repo/config.json")
1624                    .file_type(DiffFileType::Text)
1625                    .mime_type("application/json"),
1626            ],
1627        ));
1628
1629        assert_eq!(
1630            serde_json::to_value(diff).unwrap(),
1631            serde_json::json!({
1632                "type": "diff",
1633                "changes": [
1634                    {
1635                        "operation": "modify",
1636                        "path": "/repo/config.json",
1637                        "fileType": "text",
1638                        "mimeType": "application/json"
1639                    }
1640                ],
1641                "patch": {
1642                    "format": "git_patch",
1643                    "text": patch_text
1644                }
1645            })
1646        );
1647    }
1648
1649    #[test]
1650    fn diff_patch_requires_text() {
1651        let result = serde_json::from_value::<DiffPatch>(serde_json::json!({
1652            "format": "git_patch",
1653            "diff": "diff --git /repo/config.json /repo/config.json\n"
1654        }));
1655
1656        assert!(result.is_err());
1657    }
1658
1659    #[test]
1660    fn diff_serializes_binary_modify_without_patch_text() {
1661        let diff = ToolCallContent::Diff(Diff::new(vec![
1662            DiffChange::modify("/repo/assets/logo.png")
1663                .file_type(DiffFileType::Binary)
1664                .mime_type("image/png"),
1665        ]));
1666
1667        assert_eq!(
1668            serde_json::to_value(diff).unwrap(),
1669            serde_json::json!({
1670                "type": "diff",
1671                "changes": [
1672                    {
1673                        "operation": "modify",
1674                        "path": "/repo/assets/logo.png",
1675                        "fileType": "binary",
1676                        "mimeType": "image/png"
1677                    }
1678                ]
1679            })
1680        );
1681    }
1682
1683    #[test]
1684    fn diff_move_serializes_shared_fields_with_operation_payload() {
1685        let diff = ToolCallContent::Diff(Diff::new(vec![
1686            DiffChange::move_file("/repo/src/old.rs", "/repo/src/new.rs")
1687                .file_type(DiffFileType::Text)
1688                .mime_type("text/rust"),
1689        ]));
1690
1691        assert_eq!(
1692            serde_json::to_value(diff).unwrap(),
1693            serde_json::json!({
1694                "type": "diff",
1695                "changes": [
1696                    {
1697                        "operation": "move",
1698                        "oldPath": "/repo/src/old.rs",
1699                        "path": "/repo/src/new.rs",
1700                        "fileType": "text",
1701                        "mimeType": "text/rust"
1702                    }
1703                ]
1704            })
1705        );
1706    }
1707
1708    #[test]
1709    fn diff_changes_skip_malformed_list_items() {
1710        let patch_text = "diff --git /ok /ok\ndeleted file mode 100644\n--- /ok\n+++ /dev/null\n@@ -1 +0,0 @@\n-old\n";
1711        let content: ToolCallContent = serde_json::from_value(serde_json::json!({
1712            "type": "diff",
1713            "changes": [
1714                {
1715                    "operation": "modify"
1716                },
1717                {
1718                    "operation": "delete",
1719                    "path": "/ok"
1720                }
1721            ],
1722            "patch": {
1723                "format": "git_patch",
1724                "text": patch_text
1725            }
1726        }))
1727        .unwrap();
1728
1729        let ToolCallContent::Diff(diff) = content else {
1730            panic!("expected diff content");
1731        };
1732        assert_eq!(diff.changes, vec![DiffChange::delete("/ok")]);
1733        assert_eq!(diff.patch, Some(DiffPatch::new(patch_text)));
1734    }
1735
1736    #[test]
1737    fn tool_kind_preserves_unknown_variant() {
1738        let kind: ToolKind = serde_json::from_str("\"review\"").unwrap();
1739        assert_eq!(kind, ToolKind::Unknown("review".to_string()));
1740        assert_eq!(serde_json::to_value(&kind).unwrap(), "review");
1741    }
1742
1743    #[test]
1744    fn tool_call_status_preserves_unknown_variant() {
1745        let status: ToolCallStatus = serde_json::from_str("\"deferred\"").unwrap();
1746        assert_eq!(status, ToolCallStatus::Other("deferred".to_string()));
1747        assert_eq!(serde_json::to_value(&status).unwrap(), "deferred");
1748    }
1749
1750    #[test]
1751    fn tool_call_status_recognizes_cancelled_variant() {
1752        let status: ToolCallStatus = serde_json::from_str("\"cancelled\"").unwrap();
1753        assert_eq!(status, ToolCallStatus::Cancelled);
1754        assert_eq!(serde_json::to_value(&status).unwrap(), "cancelled");
1755    }
1756
1757    #[test]
1758    fn tool_call_content_preserves_unknown_variant() {
1759        let content: ToolCallContent = serde_json::from_value(serde_json::json!({
1760            "type": "_chart",
1761            "title": "Tests",
1762            "data": [1, 2, 3]
1763        }))
1764        .unwrap();
1765
1766        let ToolCallContent::Other(unknown) = content else {
1767            panic!("expected unknown tool call content");
1768        };
1769
1770        assert_eq!(unknown.type_, "_chart");
1771        assert_eq!(
1772            unknown.fields.get("title"),
1773            Some(&serde_json::json!("Tests"))
1774        );
1775        assert_eq!(
1776            serde_json::to_value(ToolCallContent::Other(unknown)).unwrap(),
1777            serde_json::json!({
1778                "type": "_chart",
1779                "title": "Tests",
1780                "data": [1, 2, 3]
1781            })
1782        );
1783    }
1784
1785    #[test]
1786    fn tool_call_content_does_not_hide_malformed_known_variant() {
1787        assert!(
1788            serde_json::from_value::<ToolCallContent>(serde_json::json!({
1789                "type": "diff"
1790            }))
1791            .is_err()
1792        );
1793        assert!(
1794            serde_json::from_value::<ToolCallContent>(serde_json::json!({
1795                "type": "terminal"
1796            }))
1797            .is_err()
1798        );
1799    }
1800}