Skip to main content

agent_client_protocol_schema/v2/
plan.rs

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