Skip to main content

adk_harness/tools/
plan.rs

1//! `exit_plan_mode` (spec 3.1 §7.4).
2
3use std::collections::HashSet;
4use std::sync::Arc;
5
6use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, Tool, ToolContext};
7use async_trait::async_trait;
8use chrono::Utc;
9use serde::{Deserialize, Serialize};
10use serde_json::{Value, json};
11
12use crate::audit::HarnessAudit;
13use crate::mode::{HarnessMode, MODE_STATE_KEY, ModeSource, ModeStore, write_mode_change};
14use crate::policy::has_harness_layer;
15
16/// Session-state key of the approved plan's display mirror (spec 3.1 §7.4).
17///
18/// # Example
19///
20/// ```rust
21/// assert_eq!(adk_harness::PLAN_STATE_KEY, "harness:plan");
22/// ```
23pub const PLAN_STATE_KEY: &str = "harness:plan";
24
25/// The approval gate of a plan step (spec 3.1 §7.11).
26///
27/// # Example
28///
29/// ```rust
30/// assert_eq!(adk_harness::PlanGate::default(), adk_harness::PlanGate::None);
31/// ```
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34pub enum PlanGate {
35    /// No gate.
36    #[default]
37    None,
38    /// A person approves before the step runs.
39    Approve,
40    /// A reviewer member checks the step.
41    Review,
42}
43
44/// One step of an approved plan (spec 3.1 §7.11).
45///
46/// # Example
47///
48/// ```rust
49/// use adk_harness::PlanStep;
50/// use serde_json::json;
51///
52/// let step: PlanStep = serde_json::from_value(json!({
53///     "id": "1", "title": "Add the test", "instruction": "Write a failing test", "depends_on": []
54/// })).unwrap();
55/// assert_eq!(step.title, "Add the test");
56/// ```
57#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59pub struct PlanStep {
60    /// Unique id within the plan.
61    pub id: String,
62    /// Short title.
63    pub title: String,
64    /// What the step does.
65    pub instruction: String,
66    /// Ids of the steps this one waits for.
67    #[serde(default, alias = "depends_on")]
68    pub depends_on: Vec<String>,
69    /// The step's gate.
70    #[serde(default)]
71    pub gate: PlanGate,
72}
73
74/// The approved plan as mirrored under [`PLAN_STATE_KEY`].
75#[derive(Clone, Debug, Serialize)]
76#[serde(rename_all = "camelCase")]
77struct PlanRecord<'a> {
78    plan: &'a str,
79    steps: &'a [PlanStep],
80    next_mode: HarnessMode,
81    plan_hash: String,
82    approved_at: chrono::DateTime<Utc>,
83}
84
85fn invalid(message: impl Into<String>) -> AdkError {
86    AdkError::new(
87        ErrorComponent::Tool,
88        ErrorCategory::InvalidInput,
89        "harness.plan.invalid",
90        message,
91    )
92}
93
94/// `exit_plan_mode`: asks to leave Plan mode with a plan (spec 3.1 §7.4).
95///
96/// Always declared, so the tool surface and the prompt cache stay stable; the policy
97/// denies it outside Plan and holds it for a non-waivable approval in Plan. On approval it
98/// writes the mode store with [`ModeSource::PlanApproval`], effective from the next
99/// invocation, mirrors `harness:plan` and `harness:mode` into session state, and ends the
100/// turn (`skip_summarization`), since the invocation that approved the plan stays in Plan. The
101/// approver may edit `next_mode`; edited arguments are checked by the policy again.
102/// Auto is never the default target.
103///
104/// # Example
105///
106/// ```rust
107/// use adk_core::Tool;
108/// use std::sync::Arc;
109///
110/// let tool = adk_harness::ExitPlanModeTool::new(
111///     Arc::new(adk_harness::InMemoryModeStore::new()),
112///     adk_harness::HarnessMode::Plan,
113/// );
114/// assert_eq!(tool.name(), "exit_plan_mode");
115/// ```
116pub struct ExitPlanModeTool {
117    mode_store: Arc<dyn ModeStore>,
118    default_mode: HarnessMode,
119    #[cfg(feature = "graph")]
120    plan_graph: Option<Arc<crate::plan_graph::PlanGraphs>>,
121}
122
123impl ExitPlanModeTool {
124    /// A tool over `mode_store`, whose sessions start in `default_mode`.
125    pub fn new(mode_store: Arc<dyn ModeStore>, default_mode: HarnessMode) -> Self {
126        Self {
127            mode_store,
128            default_mode,
129            #[cfg(feature = "graph")]
130            plan_graph: None,
131        }
132    }
133
134    /// Compiles approved plans with steps into `graphs` (spec 3.1 §7.11).
135    #[cfg(feature = "graph")]
136    pub(crate) fn with_plan_graph(mut self, graphs: Arc<crate::plan_graph::PlanGraphs>) -> Self {
137        self.plan_graph = Some(graphs);
138        self
139    }
140}
141
142#[async_trait]
143impl Tool for ExitPlanModeTool {
144    fn name(&self) -> &str {
145        "exit_plan_mode"
146    }
147
148    /// Keeps the plan in the session.
149    fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
150        adk_core::egress::ToolEgress::None
151    }
152
153    fn description(&self) -> &str {
154        "Present your plan and ask the user to approve leaving plan mode. Call it only in \
155         plan mode, once your investigation is complete; the user sees the plan and may \
156         approve or reject it. On approval your turn ends, and the new mode applies from the \
157         user's next message."
158    }
159
160    fn parameters_schema(&self) -> Option<Value> {
161        Some(json!({
162            "type": "object",
163            "properties": {
164                "plan": { "type": "string", "description": "The plan, in Markdown." },
165                "next_mode": { "type": "string", "enum": ["ask", "auto"], "description": "Mode to switch to; defaults to ask." },
166                "steps": {
167                    "type": "array",
168                    "description": "Optional structured steps.",
169                    "items": {
170                        "type": "object",
171                        "properties": {
172                            "id": { "type": "string" },
173                            "title": { "type": "string" },
174                            "instruction": { "type": "string" },
175                            "depends_on": { "type": "array", "items": { "type": "string" } },
176                            "gate": { "type": "string", "enum": ["none", "approve", "review"] }
177                        },
178                        "required": ["id", "title", "instruction"]
179                    }
180                }
181            },
182            "required": ["plan"]
183        }))
184    }
185
186    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
187        let config = ctx
188            .run_config()
189            .ok_or_else(|| AdkError::tool("exit_plan_mode runs only inside a harness run"))?;
190        if !config.tool_policy.as_deref().is_some_and(has_harness_layer) {
191            return Err(AdkError::tool(
192                "exit_plan_mode refuses to run without the harness policy in the run config",
193            ));
194        }
195        let plan = args
196            .get("plan")
197            .and_then(Value::as_str)
198            .map(str::trim)
199            .filter(|plan| !plan.is_empty())
200            .ok_or_else(|| invalid("plan is required"))?;
201        let next_mode = match args.get("next_mode").and_then(Value::as_str) {
202            None | Some("ask") => HarnessMode::Ask,
203            Some("auto") => HarnessMode::Auto,
204            Some(other) => {
205                return Err(invalid(format!("next_mode must be ask or auto, not '{other}'")));
206            }
207        };
208        let steps: Vec<PlanStep> = match args.get("steps") {
209            None | Some(Value::Null) => Vec::new(),
210            Some(value) => serde_json::from_value(value.clone())
211                .map_err(|error| invalid(format!("steps are malformed: {error}")))?,
212        };
213        let ids: HashSet<&str> = steps.iter().map(|step| step.id.as_str()).collect();
214        if ids.len() != steps.len() {
215            return Err(invalid("step ids must be unique"));
216        }
217        if let Some(step) =
218            steps.iter().find(|step| step.depends_on.iter().any(|dep| !ids.contains(dep.as_str())))
219        {
220            return Err(invalid(format!("step '{}' depends on an unknown step", step.id)));
221        }
222
223        let (app, user, session) = (ctx.app_name(), ctx.user_id(), ctx.session_id());
224        let current = self.mode_store.get(app, user, session).await?;
225        let mode = current
226            .as_ref()
227            .map_or(self.default_mode, |record| record.mode_for_invocation(ctx.invocation_id()));
228        if mode != HarnessMode::Plan {
229            return Err(AdkError::tool(format!(
230                "exit_plan_mode is only valid in plan mode; the session is in {mode} mode"
231            )));
232        }
233        let plan_hash = crate::fsutil::hex_digest(
234            json!({ "plan": plan, "steps": steps }).to_string().as_bytes(),
235        );
236        // A plan with steps compiles to the plan graph (spec 3.1 §7.11); an invalid one is
237        // refused before the mode changes.
238        #[cfg(feature = "graph")]
239        let graph = match (&self.plan_graph, steps.is_empty()) {
240            (Some(graphs), false) => Some((graphs, graphs.validate(&steps, &plan_hash)?)),
241            _ => None,
242        };
243        let audit = HarnessAudit::for_tool(ctx.as_ref());
244        let record = write_mode_change(
245            self.mode_store.as_ref(),
246            self.default_mode,
247            (app, user, session),
248            next_mode,
249            ModeSource::PlanApproval,
250            Some(ctx.invocation_id().to_string()),
251            audit.as_ref(),
252            &[],
253        )
254        .await?;
255        #[cfg(feature = "graph")]
256        let graph_nodes = match graph {
257            Some((graphs, _)) => {
258                Some(graphs.install(ctx.as_ref(), plan, &steps, &plan_hash).await?.nodes)
259            }
260            None => None,
261        };
262        #[cfg(not(feature = "graph"))]
263        let graph_nodes: Option<Vec<String>> = None;
264        let mut actions = ctx.actions();
265        actions.state_delta.insert(
266            MODE_STATE_KEY.to_string(),
267            json!({ "mode": record.mode, "revision": record.revision, "setBy": record.set_by }),
268        );
269        actions.state_delta.insert(
270            PLAN_STATE_KEY.to_string(),
271            serde_json::to_value(PlanRecord {
272                plan,
273                steps: &steps,
274                next_mode,
275                plan_hash: plan_hash.clone(),
276                approved_at: Utc::now(),
277            })
278            .unwrap_or(Value::Null),
279        );
280        // The approved mode applies from the next invocation, so this one ends here rather
281        // than continuing under Plan.
282        actions.skip_summarization = true;
283        ctx.set_actions(actions);
284        tracing::info!(harness.mode = %next_mode, plan.steps = steps.len(), "plan approved");
285        Ok(json!({
286            "status": "approved",
287            "mode": next_mode,
288            "effective": "from the user's next turn",
289            "steps": steps.len(),
290            "planHash": plan_hash,
291            "planGraph": graph_nodes,
292            "instruction": "The plan is approved. End your turn now; the user's next message starts the work.",
293        }))
294    }
295}