1use super::{AgentTool, Approval, CallMonitor, Invocation, ToolSpec, blocking, decoded};
6use async_trait::async_trait;
7use serde::Serialize;
8use serde::de::DeserializeOwned;
9use serde_json::{Value, json};
10use std::sync::Arc;
11
12pub const MAX_BATCH: usize = 20;
14
15pub const NO_RETRY: &str = "No retry was attempted. A network or response error can mean the mutation succeeded; inspect the target before retrying.";
16
17const NOT_STARTED: &str = "The call was cancelled before this operation started.";
18
19pub trait WriteService: Send + Sync + 'static {
21 type Operation: Serialize + DeserializeOwned + Clone + Send + Sync + 'static;
23 type Prepared: Send + Sync + 'static;
25
26 fn validate(&self, operations: &[Self::Operation]) -> Result<(), String>;
28 fn preflight(&self, operations: &[Self::Operation]) -> Result<Self::Prepared, String>;
30 fn describe(&self, operations: &[Self::Operation], prepared: &Self::Prepared) -> String;
32 fn requires_app_approval(&self, _operations: &[Self::Operation]) -> bool {
35 false
36 }
37 fn write(
39 &self,
40 index: usize,
41 operation: &Self::Operation,
42 prepared: &Self::Prepared,
43 ) -> Result<Value, String>;
44
45 fn preflight_monitored(
47 &self,
48 operations: &[Self::Operation],
49 monitor: &dyn CallMonitor,
50 ) -> Result<Self::Prepared, String> {
51 if monitor.cancelled() {
52 return Err(NOT_STARTED.into());
53 }
54 self.preflight(operations)
55 }
56
57 fn write_monitored(
59 &self,
60 index: usize,
61 operation: &Self::Operation,
62 prepared: &Self::Prepared,
63 _monitor: &dyn CallMonitor,
64 ) -> Result<Value, String> {
65 self.write(index, operation, prepared)
66 }
67}
68
69#[derive(serde::Deserialize)]
70#[serde(deny_unknown_fields, bound = "T: DeserializeOwned")]
71struct Batch<T> {
72 operations: Vec<T>,
73}
74
75pub struct WriteTool<S: WriteService> {
77 spec: ToolSpec,
78 service: Arc<S>,
79}
80
81impl<S: WriteService> WriteTool<S> {
82 pub fn new(spec: ToolSpec, service: Arc<S>) -> Self {
83 Self { spec, service }
84 }
85
86 pub fn service(&self) -> &Arc<S> {
87 &self.service
88 }
89
90 pub async fn execute(
92 &self,
93 operations: Vec<S::Operation>,
94 approval: Arc<dyn Approval>,
95 monitor: Arc<dyn CallMonitor>,
96 ) -> Result<Value, String> {
97 let batch = Arc::new(operations);
98 let (service, checked) = (self.service.clone(), batch.clone());
99 let preflight_monitor = monitor.clone();
100 let prepared =
101 blocking(move || prepare(service.as_ref(), &checked, preflight_monitor.as_ref()))
102 .await?;
103 if monitor.cancelled() {
104 return Err(NOT_STARTED.into());
105 }
106 let preview = summary(&batch, &self.service.describe(&batch, &prepared))?;
107 let allowed = if self.service.requires_app_approval(&batch) {
108 approval.approve_in_app(preview).await?
109 } else {
110 approval.approve(preview).await?
111 };
112 if !allowed {
113 return Ok(denied());
114 }
115 let service = self.service.clone();
116 blocking(move || Ok(run(service.as_ref(), &batch, &prepared, monitor.as_ref()))).await
117 }
118}
119
120#[async_trait]
121impl<S: WriteService> AgentTool for WriteTool<S> {
122 fn spec(&self) -> &ToolSpec {
123 &self.spec
124 }
125
126 async fn call(&self, invocation: Invocation) -> Result<Value, String> {
127 let batch = decoded::<Batch<S::Operation>>(invocation.arguments)?;
128 self.execute(batch.operations, invocation.approval, invocation.monitor)
129 .await
130 }
131}
132
133fn prepare<S: WriteService>(
134 service: &S,
135 operations: &[S::Operation],
136 monitor: &dyn CallMonitor,
137) -> Result<S::Prepared, String> {
138 validate_size(operations.len())?;
139 service.validate(operations)?;
140 service.preflight_monitored(operations, monitor)
141}
142
143fn validate_size(len: usize) -> Result<(), String> {
144 if len == 0 || len > MAX_BATCH {
145 Err("Batch requires 1..20 operations.".into())
146 } else {
147 Ok(())
148 }
149}
150
151pub fn summary<T: Serialize>(operations: &[T], details: &str) -> Result<String, String> {
154 let summary = serde_json::to_string_pretty(operations)
155 .map(|body| {
156 format!(
157 "Apply exactly these {} service write operations once:\n{body}{details}",
158 operations.len()
159 )
160 })
161 .map_err(|error| error.to_string())?;
162 if crate::secrets::looks_like_credential(&summary) {
163 Err("The proposed operation includes credential-like data and cannot be approved.".into())
164 } else {
165 Ok(summary)
166 }
167}
168
169fn denied() -> Value {
170 json!({"approved":false,"results":[],"message":"No operations were executed."})
171}
172
173fn run<S: WriteService>(
174 service: &S,
175 operations: &[S::Operation],
176 prepared: &S::Prepared,
177 monitor: &dyn CallMonitor,
178) -> Value {
179 let total = operations.len();
180 let results: Vec<Value> = operations
181 .iter()
182 .enumerate()
183 .map(|(index, operation)| {
184 step(index, total, monitor, || {
185 service.write_monitored(index, operation, prepared, monitor)
186 })
187 })
188 .collect();
189 json!({"approved":true,"results":results})
190}
191
192fn step(
194 index: usize,
195 total: usize,
196 monitor: &dyn CallMonitor,
197 write: impl FnOnce() -> Result<Value, String>,
198) -> Value {
199 if monitor.cancelled() {
200 return json!({"index":index,"success":false,"started":false,"error":NOT_STARTED});
201 }
202 monitor.progress(index, total, &format!("Operation {} of {total}", index + 1));
203 match write() {
204 Ok(value) => json!({"index":index,"success":true,"value":value}),
205 Err(error) => json!({"index":index,"success":false,"error":error,"warning":NO_RETRY}),
206 }
207}
208
209#[cfg(test)]
210mod tests {
211 use super::{WriteService, WriteTool, summary};
212 use crate::test_support::{self, RecordingMonitor};
213 use crate::{Access, AgentTool, ApprovalPolicy, Arguments, ToolSpec};
214 use serde::{Deserialize, Serialize};
215 use serde_json::{Value, json};
216 use std::sync::{Arc, Mutex};
217
218 #[derive(Clone, Serialize, Deserialize)]
219 #[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
220 enum Operation {
221 Note { body: String },
222 }
223
224 struct Notes {
227 written: Mutex<Vec<String>>,
228 preflights: Mutex<usize>,
229 }
230
231 impl WriteService for Notes {
232 type Operation = Operation;
233 type Prepared = usize;
234 fn validate(&self, operations: &[Operation]) -> Result<(), String> {
235 match operations
236 .iter()
237 .any(|Operation::Note { body }| body == "invalid")
238 {
239 true => Err("Invalid note.".into()),
240 false => Ok(()),
241 }
242 }
243 fn preflight(&self, operations: &[Operation]) -> Result<usize, String> {
244 *self.preflights.lock().unwrap() += 1;
245 Ok(operations.len())
246 }
247 fn describe(&self, _: &[Operation], prepared: &usize) -> String {
248 format!("\n\nprepared {prepared}")
249 }
250 fn requires_app_approval(&self, operations: &[Operation]) -> bool {
251 operations
252 .iter()
253 .any(|Operation::Note { body }| body == "sensitive")
254 }
255 fn write(&self, _: usize, operation: &Operation, _: &usize) -> Result<Value, String> {
256 let Operation::Note { body } = operation;
257 self.written.lock().unwrap().push(body.clone());
258 match body.as_str() {
259 "fail" => Err("Ambiguous network failure.".into()),
260 _ => Ok(json!({ "body": body })),
261 }
262 }
263 }
264
265 fn tool() -> WriteTool<Notes> {
266 WriteTool::new(
267 ToolSpec {
268 name: "notes_write",
269 title: "Notes",
270 description: "Notes",
271 access: Access::Write,
272 arguments: Arguments::Single { fields: Vec::new() },
273 approval: ApprovalPolicy::PerCall,
274 },
275 Arc::new(Notes {
276 written: Mutex::new(Vec::new()),
277 preflights: Mutex::new(0),
278 }),
279 )
280 }
281
282 fn notes(bodies: &[&str]) -> Value {
283 let operations: Vec<Value> = bodies
284 .iter()
285 .map(|body| json!({"action":"note","body":body}))
286 .collect();
287 json!({ "operations": operations })
288 }
289
290 fn written(tool: &WriteTool<Notes>) -> Vec<String> {
291 tool.service().written.lock().unwrap().clone()
292 }
293
294 #[tokio::test]
295 async fn a_denied_batch_writes_nothing_and_asks_once_with_every_body() {
296 let tool = tool();
297 let (approval, invocation) = test_support::invocation(notes(&["first", "second"]), false);
298 let value = tool.call(invocation).await.unwrap();
299 assert_eq!(value["approved"], false);
300 assert!(written(&tool).is_empty());
301 let summaries = approval.summaries();
302 assert_eq!(summaries.len(), 1);
303 assert!(summaries[0].contains("first") && summaries[0].contains("second"));
304 assert!(summaries[0].ends_with("prepared 2"));
305 }
306
307 #[tokio::test]
308 async fn sensitive_writes_refuse_unattended_approval_but_accept_manual_decisions() {
309 let tool = tool();
310 let invocation = crate::Invocation {
311 arguments: notes(&["sensitive"]),
312 approval: Arc::new(crate::Unattended),
313 monitor: Arc::new(crate::Unmonitored),
314 };
315 assert_eq!(tool.call(invocation).await.unwrap()["approved"], false);
316 assert!(written(&tool).is_empty());
317 let (_, refused) = test_support::invocation(notes(&["sensitive"]), false);
318 assert_eq!(tool.call(refused).await.unwrap()["approved"], false);
319 assert!(written(&tool).is_empty());
320 let (approval, accepted) = test_support::invocation(notes(&["sensitive"]), true);
321 assert_eq!(tool.call(accepted).await.unwrap()["approved"], true);
322 assert_eq!(written(&tool), ["sensitive"]);
323 assert_eq!(approval.summaries().len(), 1);
324 }
325
326 #[tokio::test]
327 async fn an_invalid_or_oversized_batch_is_refused_before_preflight_and_approval() {
328 let tool = tool();
329 for arguments in [
330 notes(&["first", "invalid"]),
331 notes(&[]),
332 notes(&["x"; 21]),
333 json!({"operations":[],"extra":true}),
334 ] {
335 let (approval, invocation) = test_support::invocation(arguments, true);
336 assert!(tool.call(invocation).await.is_err());
337 assert!(approval.summaries().is_empty());
338 }
339 assert_eq!(*tool.service().preflights.lock().unwrap(), 0);
340 assert!(written(&tool).is_empty());
341 }
342
343 #[tokio::test]
344 async fn a_partial_failure_is_visible_never_retried_and_approval_does_not_carry_over() {
345 let tool = tool();
346 let (approval, invocation) = test_support::invocation(notes(&["fail", "second"]), true);
347 let value = tool.call(invocation).await.unwrap();
348 assert_eq!(value["results"][0]["success"], false);
349 assert!(
350 value["results"][0]["warning"]
351 .as_str()
352 .unwrap()
353 .contains("No retry")
354 );
355 assert_eq!(value["results"][1]["success"], true);
356 assert_eq!(written(&tool), ["fail", "second"]);
357 let (_, again) = test_support::invocation(notes(&["third"]), true);
358 tool.call(again).await.unwrap();
359 assert_eq!(
360 approval.summaries().len(),
361 1,
362 "each call asks its own approval"
363 );
364 assert_eq!(written(&tool).len(), 3);
365 }
366
367 #[tokio::test]
368 async fn progress_precedes_each_operation_and_cancellation_starts_no_more() {
369 let tool = tool();
370 let monitor = Arc::new(RecordingMonitor::cancel_after(1));
371 let value = tool
372 .execute(
373 vec![
374 Operation::Note { body: "a".into() },
375 Operation::Note { body: "b".into() },
376 Operation::Note { body: "c".into() },
377 ],
378 Arc::new(crate::Unattended),
379 monitor.clone(),
380 )
381 .await
382 .unwrap();
383 assert_eq!(monitor.reports(), [(0, 3)]);
384 assert_eq!(written(&tool), ["a"]);
385 assert_eq!(value["results"][1]["started"], false);
386 assert_eq!(value["results"][2]["started"], false);
387 }
388
389 #[test]
390 fn the_preview_escapes_control_characters_and_counts_operations() {
391 let text = summary(
392 &[Operation::Note {
393 body: "exact\ncomment".into(),
394 }],
395 "",
396 )
397 .unwrap();
398 assert!(text.starts_with("Apply exactly these 1 service write operations once:"));
399 assert!(text.contains("exact\\ncomment"));
400 }
401
402 #[test]
403 fn a_credential_like_preview_is_refused_before_any_surface_sees_it() {
404 let error = summary(
405 &[Operation::Note {
406 body: "github_pat_not-a-real-token".into(),
407 }],
408 "",
409 )
410 .unwrap_err();
411 assert!(error.contains("credential-like data"), "{error}");
412 }
413}