1use 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
16pub const PLAN_STATE_KEY: &str = "harness:plan";
24
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34pub enum PlanGate {
35 #[default]
37 None,
38 Approve,
40 Review,
42}
43
44#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59pub struct PlanStep {
60 pub id: String,
62 pub title: String,
64 pub instruction: String,
66 #[serde(default, alias = "depends_on")]
68 pub depends_on: Vec<String>,
69 #[serde(default)]
71 pub gate: PlanGate,
72}
73
74#[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
94pub 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 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 #[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 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 #[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 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}