Skip to main content

agent_client_protocol_schema/v2/
plan.rs

1//! Execution plans for multi-step tasks.
2//!
3//! Agents send checklists or Markdown plans to Clients through session updates.
4//!
5//! See: [Agent Plan](https://agentclientprotocol.com/protocol/v2/agent-plan)
6
7use std::sync::Arc;
8
9use derive_more::{Display, From};
10use indexmap::IndexMap;
11#[cfg(feature = "schemars")]
12use schemars::Schema;
13use serde::{Deserialize, Serialize};
14use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
15
16use super::{AbsolutePath, Meta};
17use crate::IntoOption;
18
19/// Unique identifier for a plan within a session.
20#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
22#[serde(transparent)]
23#[from(forward)]
24#[non_exhaustive]
25pub struct PlanId(pub Arc<str>);
26
27impl PlanId {
28    /// Wraps a protocol string as a typed [`PlanId`].
29    #[must_use]
30    pub fn new(id: impl Into<Self>) -> Self {
31        id.into()
32    }
33}
34
35/// A content update for a plan identified by ID.
36#[serde_as]
37#[skip_serializing_none]
38#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
39#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
40#[serde(rename_all = "camelCase")]
41#[non_exhaustive]
42pub struct PlanUpdate {
43    /// Replaces the whole plan with this `planId`, even if its `type` changes.
44    pub plan: PlanUpdateContent,
45    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
46    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
47    /// Implementations MUST NOT assign meaning to keys they do not recognize.
48    ///
49    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
50    #[serde_as(deserialize_as = "DefaultOnError")]
51    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
52    #[serde(default)]
53    #[serde(rename = "_meta")]
54    pub meta: Option<Meta>,
55}
56
57impl PlanUpdate {
58    /// Builds [`PlanUpdate`] with the required fields set. Optional fields start unset or empty.
59    #[must_use]
60    pub fn new(plan: PlanUpdateContent) -> Self {
61        Self { plan, meta: None }
62    }
63
64    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
65    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
66    /// do not recognize.
67    ///
68    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
69    #[must_use]
70    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
71        self.meta = meta.into_option();
72        self
73    }
74}
75
76/// Updated content for a plan.
77#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
78#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
79#[serde(tag = "type", rename_all = "snake_case")]
80#[non_exhaustive]
81pub enum PlanUpdateContent {
82    /// Structured plan entries.
83    Items(PlanItems),
84    /// The complete plan as Markdown.
85    Markdown(PlanMarkdown),
86    /// Custom or future plan update content.
87    ///
88    /// Values beginning with `_` are reserved for implementation-specific
89    /// extensions. Unknown values that do not begin with `_` are reserved for
90    /// future ACP variants.
91    ///
92    /// Receivers that do not understand this content type SHOULD preserve the
93    /// raw payload when storing, replaying, proxying, or forwarding plans, and
94    /// otherwise ignore it or display it generically. It still replaces any earlier
95    /// content for the same `planId`.
96    #[serde(untagged)]
97    Other(OtherPlanUpdateContent),
98}
99
100/// Custom or future plan update content payload.
101#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
102#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
103#[cfg_attr(feature = "schemars", schemars(inline))]
104#[cfg_attr(feature = "schemars", schemars(transform = other_plan_update_content_schema))]
105#[serde(rename_all = "camelCase")]
106#[non_exhaustive]
107pub struct OtherPlanUpdateContent {
108    /// Custom or future plan update content type.
109    ///
110    /// Values beginning with `_` are reserved for implementation-specific
111    /// extensions. Unknown values that do not begin with `_` are reserved for
112    /// future ACP variants.
113    #[serde(rename = "type")]
114    pub type_: String,
115    /// The plan ID to update.
116    pub plan_id: PlanId,
117    /// Additional fields from the unknown plan update content payload.
118    #[serde(flatten)]
119    pub fields: IndexMap<String, serde_json::Value>,
120}
121
122impl OtherPlanUpdateContent {
123    /// Builds [`OtherPlanUpdateContent`] from an unknown discriminator and preserves the remaining extension fields.
124    #[must_use]
125    pub fn new(
126        type_: impl Into<String>,
127        plan_id: impl Into<PlanId>,
128        mut fields: IndexMap<String, serde_json::Value>,
129    ) -> Self {
130        fields.shift_remove("type");
131        fields.shift_remove("planId");
132        Self {
133            type_: type_.into(),
134            plan_id: plan_id.into(),
135            fields,
136        }
137    }
138}
139
140impl<'de> Deserialize<'de> for OtherPlanUpdateContent {
141    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
142    where
143        D: serde::Deserializer<'de>,
144    {
145        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
146        let type_ = fields
147            .shift_remove("type")
148            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
149        let serde_json::Value::String(type_) = type_ else {
150            return Err(serde::de::Error::custom("`type` must be a string"));
151        };
152        let plan_id = fields
153            .shift_remove("planId")
154            .ok_or_else(|| serde::de::Error::missing_field("planId"))?;
155        let serde_json::Value::String(plan_id) = plan_id else {
156            return Err(serde::de::Error::custom("`planId` must be a string"));
157        };
158
159        if is_known_plan_update_content_type(&type_) {
160            return Err(serde::de::Error::custom(format!(
161                "known plan update content `{type_}` did not match its schema"
162            )));
163        }
164
165        Ok(Self {
166            type_,
167            plan_id: PlanId::new(plan_id),
168            fields,
169        })
170    }
171}
172
173fn is_known_plan_update_content_type(type_: &str) -> bool {
174    KNOWN_PLAN_UPDATE_CONTENT_TYPES.contains(&type_)
175}
176
177#[cfg(feature = "schemars")]
178fn other_plan_update_content_schema(schema: &mut Schema) {
179    super::schema_util::reject_known_string_discriminators(
180        schema,
181        "type",
182        KNOWN_PLAN_UPDATE_CONTENT_TYPES,
183    );
184}
185
186const KNOWN_PLAN_UPDATE_CONTENT_TYPES: &[&str] = &["items", "markdown"];
187
188impl PlanUpdateContent {
189    /// Builds a plan update that replaces the itemized entries for a plan.
190    #[must_use]
191    pub fn items(plan_id: impl Into<PlanId>, entries: Vec<PlanEntry>) -> Self {
192        Self::Items(PlanItems::new(plan_id, entries))
193    }
194
195    /// Builds a plan update whose plan content is inline Markdown.
196    ///
197    /// To also name the file that holds the plan, wrap a [`PlanMarkdown`] built with
198    /// [`PlanMarkdown::path`] in [`PlanUpdateContent::Markdown`].
199    #[must_use]
200    pub fn markdown(plan_id: impl Into<PlanId>, content: impl Into<String>) -> Self {
201        Self::Markdown(PlanMarkdown::new(plan_id, content))
202    }
203}
204
205/// A plan represented as structured entries.
206#[serde_as]
207#[skip_serializing_none]
208#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
209#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
210#[serde(rename_all = "camelCase")]
211#[non_exhaustive]
212pub struct PlanItems {
213    /// The plan ID to update.
214    pub plan_id: PlanId,
215    /// The list of tasks to be accomplished.
216    ///
217    /// The Agent MUST send all entries with their current status.
218    /// The Client MUST replace the checklist with this `planId` on each update.
219    #[serde_as(deserialize_as = "VecSkipError<_>")]
220    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
221    pub entries: Vec<PlanEntry>,
222    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
223    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
224    /// Implementations MUST NOT assign meaning to keys they do not recognize.
225    ///
226    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
227    #[serde_as(deserialize_as = "DefaultOnError")]
228    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
229    #[serde(default)]
230    #[serde(rename = "_meta")]
231    pub meta: Option<Meta>,
232}
233
234impl PlanItems {
235    /// Builds [`PlanItems`] with the required fields set. Optional fields start unset or empty.
236    #[must_use]
237    pub fn new(plan_id: impl Into<PlanId>, entries: Vec<PlanEntry>) -> Self {
238        Self {
239            plan_id: plan_id.into(),
240            entries,
241            meta: None,
242        }
243    }
244
245    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
246    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
247    /// do not recognize.
248    ///
249    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
250    #[must_use]
251    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
252        self.meta = meta.into_option();
253        self
254    }
255}
256
257/// A plan represented as Markdown.
258#[serde_as]
259#[skip_serializing_none]
260#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
261#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
262#[serde(rename_all = "camelCase")]
263#[non_exhaustive]
264pub struct PlanMarkdown {
265    /// The plan ID to update.
266    pub plan_id: PlanId,
267    /// The complete plan as Markdown, not just the text that changed.
268    pub content: String,
269    /// The absolute path of the file that holds this plan.
270    ///
271    /// Omitted and `null` both mean the plan has no file. A supplied path MUST
272    /// be absolute. `content` is the plan to display whether or not `path` is set.
273    /// Clients can use `path` to open the file.
274    #[serde_as(deserialize_as = "DefaultOnError")]
275    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
276    #[serde(default)]
277    pub path: Option<AbsolutePath>,
278    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
279    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
280    /// Implementations MUST NOT assign meaning to keys they do not recognize.
281    ///
282    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
283    #[serde_as(deserialize_as = "DefaultOnError")]
284    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
285    #[serde(default)]
286    #[serde(rename = "_meta")]
287    pub meta: Option<Meta>,
288}
289
290impl PlanMarkdown {
291    /// Builds [`PlanMarkdown`] with the required fields set. Optional fields start unset or empty.
292    #[must_use]
293    pub fn new(plan_id: impl Into<PlanId>, content: impl Into<String>) -> Self {
294        Self {
295            plan_id: plan_id.into(),
296            content: content.into(),
297            path: None,
298            meta: None,
299        }
300    }
301
302    /// The absolute path of the file that holds this plan.
303    ///
304    /// `content` is the plan to display whether or not `path` is set.
305    #[must_use]
306    pub fn path(mut self, path: impl IntoOption<AbsolutePath>) -> Self {
307        self.path = path.into_option();
308        self
309    }
310
311    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
312    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
313    /// do not recognize.
314    ///
315    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
316    #[must_use]
317    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
318        self.meta = meta.into_option();
319        self
320    }
321}
322
323/// Removal notice for a plan identified by ID.
324#[serde_as]
325#[skip_serializing_none]
326#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
327#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
328#[serde(rename_all = "camelCase")]
329#[non_exhaustive]
330pub struct PlanRemoved {
331    /// The plan ID to remove. Clients MUST ignore a removal for an unknown ID.
332    pub plan_id: PlanId,
333    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
334    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
335    /// Implementations MUST NOT assign meaning to keys they do not recognize.
336    ///
337    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
338    #[serde_as(deserialize_as = "DefaultOnError")]
339    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
340    #[serde(default)]
341    #[serde(rename = "_meta")]
342    pub meta: Option<Meta>,
343}
344
345impl PlanRemoved {
346    /// Builds [`PlanRemoved`] with the required fields set. Optional fields start unset or empty.
347    #[must_use]
348    pub fn new(plan_id: impl Into<PlanId>) -> Self {
349        Self {
350            plan_id: plan_id.into(),
351            meta: None,
352        }
353    }
354
355    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
356    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
357    /// do not recognize.
358    ///
359    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
360    #[must_use]
361    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
362        self.meta = meta.into_option();
363        self
364    }
365}
366
367/// A single entry in the execution plan.
368///
369/// Represents a task or goal that the assistant intends to accomplish
370/// as part of fulfilling the user's request.
371/// See protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/v2/agent-plan#plan-entries)
372#[serde_as]
373#[skip_serializing_none]
374#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
375#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
376#[serde(rename_all = "camelCase")]
377#[non_exhaustive]
378pub struct PlanEntry {
379    /// Human-readable description of what this task aims to accomplish.
380    /// May contain Markdown.
381    pub content: String,
382    /// The relative importance of this task.
383    /// Used to indicate which tasks are most critical to the overall goal.
384    pub priority: PlanEntryPriority,
385    /// Current execution status of this task.
386    pub status: PlanEntryStatus,
387    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
388    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
389    /// Implementations MUST NOT assign meaning to keys they do not recognize.
390    ///
391    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
392    #[serde_as(deserialize_as = "DefaultOnError")]
393    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
394    #[serde(default)]
395    #[serde(rename = "_meta")]
396    pub meta: Option<Meta>,
397}
398
399impl PlanEntry {
400    /// Builds [`PlanEntry`] with the required fields set. Optional fields start unset or empty.
401    #[must_use]
402    pub fn new(
403        content: impl Into<String>,
404        priority: PlanEntryPriority,
405        status: PlanEntryStatus,
406    ) -> Self {
407        Self {
408            content: content.into(),
409            priority,
410            status,
411            meta: None,
412        }
413    }
414
415    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
416    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
417    /// do not recognize.
418    ///
419    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
420    #[must_use]
421    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
422        self.meta = meta.into_option();
423        self
424    }
425}
426
427/// Priority levels for plan entries.
428///
429/// Used to indicate the relative importance or urgency of different
430/// tasks in the execution plan.
431/// See protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/v2/agent-plan#plan-entries)
432#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
433#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
434#[serde(rename_all = "snake_case")]
435#[non_exhaustive]
436pub enum PlanEntryPriority {
437    /// High priority task. Critical to the overall goal.
438    High,
439    /// Medium priority task. Important but not critical.
440    Medium,
441    /// Low priority task. Nice to have but not essential.
442    Low,
443    /// Custom or future plan entry priority.
444    ///
445    /// Values beginning with `_` are reserved for implementation-specific
446    /// extensions. Unknown values that do not begin with `_` are reserved for
447    /// future ACP variants.
448    #[serde(untagged)]
449    Other(String),
450}
451
452/// Status of a plan entry in the execution flow.
453///
454/// Tracks the lifecycle of each task from planning through completion.
455/// See protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/v2/agent-plan#plan-entries)
456#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
457#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
458#[serde(rename_all = "snake_case")]
459#[non_exhaustive]
460pub enum PlanEntryStatus {
461    /// The task has not started yet.
462    Pending,
463    /// The task is currently being worked on.
464    InProgress,
465    /// The task has been successfully completed.
466    Completed,
467    /// The task was cancelled before it completed.
468    Cancelled,
469    /// Custom or future plan entry status.
470    ///
471    /// Values beginning with `_` are reserved for implementation-specific
472    /// extensions. Unknown values that do not begin with `_` are reserved for
473    /// future ACP variants.
474    #[serde(untagged)]
475    Other(String),
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481
482    #[test]
483    fn plan_entry_priority_preserves_unknown_variant() {
484        let priority: PlanEntryPriority = serde_json::from_str("\"urgent\"").unwrap();
485        assert_eq!(priority, PlanEntryPriority::Other("urgent".to_string()));
486        assert_eq!(serde_json::to_value(&priority).unwrap(), "urgent");
487    }
488
489    #[test]
490    fn plan_entry_status_preserves_unknown_variant() {
491        let status: PlanEntryStatus = serde_json::from_str("\"blocked\"").unwrap();
492        assert_eq!(status, PlanEntryStatus::Other("blocked".to_string()));
493        assert_eq!(serde_json::to_value(&status).unwrap(), "blocked");
494    }
495
496    #[test]
497    fn plan_entry_status_recognizes_cancelled_variant() {
498        let status: PlanEntryStatus = serde_json::from_str("\"cancelled\"").unwrap();
499        assert_eq!(status, PlanEntryStatus::Cancelled);
500        assert_eq!(serde_json::to_value(&status).unwrap(), "cancelled");
501    }
502
503    #[test]
504    fn plan_update_content_preserves_unknown_variant() {
505        let content: PlanUpdateContent = serde_json::from_value(serde_json::json!({
506            "type": "_timeline",
507            "planId": "plan-1",
508            "events": []
509        }))
510        .unwrap();
511
512        let PlanUpdateContent::Other(unknown) = content else {
513            panic!("expected unknown plan update content");
514        };
515
516        assert_eq!(unknown.type_, "_timeline");
517        assert_eq!(unknown.plan_id.to_string(), "plan-1");
518        assert!(!unknown.fields.contains_key("planId"));
519        assert_eq!(
520            serde_json::to_value(PlanUpdateContent::Other(unknown)).unwrap(),
521            serde_json::json!({
522                "type": "_timeline",
523                "planId": "plan-1",
524                "events": []
525            })
526        );
527    }
528
529    #[test]
530    fn plan_update_content_does_not_hide_malformed_known_variant() {
531        for tag in ["items", "markdown"] {
532            let wire = serde_json::json!({
533                "type": tag,
534                "planId": "plan-1"
535            });
536            assert!(serde_json::from_value::<PlanUpdateContent>(wire).is_err());
537        }
538    }
539
540    #[test]
541    fn markdown_plan_path_round_trips() {
542        let wire = serde_json::json!({
543            "type": "markdown",
544            "planId": "plan-1",
545            "content": "# Next steps",
546            "path": "/home/user/project/PLAN.md"
547        });
548        let content: PlanUpdateContent = serde_json::from_value(wire.clone()).unwrap();
549        assert_eq!(
550            content,
551            PlanUpdateContent::Markdown(
552                PlanMarkdown::new("plan-1", "# Next steps").path("/home/user/project/PLAN.md")
553            )
554        );
555        assert_eq!(serde_json::to_value(content).unwrap(), wire);
556    }
557
558    #[test]
559    fn markdown_plan_path_is_optional_and_lenient() {
560        let without_path = PlanUpdateContent::markdown("plan-1", "# Next steps");
561        assert_eq!(
562            serde_json::to_value(&without_path).unwrap(),
563            serde_json::json!({
564                "type": "markdown",
565                "planId": "plan-1",
566                "content": "# Next steps"
567            })
568        );
569        // `null` and a malformed path both mean the plan has no file. The content still parses.
570        for path in [serde_json::Value::Null, serde_json::json!(42)] {
571            let content: PlanUpdateContent = serde_json::from_value(serde_json::json!({
572                "type": "markdown",
573                "planId": "plan-1",
574                "content": "# Next steps",
575                "path": path
576            }))
577            .unwrap();
578            assert_eq!(content, without_path);
579        }
580    }
581
582    #[test]
583    fn plan_update_content_requires_id_for_unknown_variant() {
584        assert!(
585            serde_json::from_value::<PlanUpdateContent>(serde_json::json!({
586                "type": "_timeline"
587            }))
588            .is_err()
589        );
590    }
591}