a2a_protocol_server/tool_loop/policy.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! What the loop lets a model do and what it tells the caller about it
5//! (adversarial review T1, T2, T3, 2026-11-12): whether a call the model wrote
6//! as text is run, what the caller's trace carries, and a policy asked before
7//! every call runs.
8//!
9//! The defaults keep the loop's documented behaviour. [`ToolLoop::strict`] is
10//! the profile for a deployment that takes tool calls to be actions with
11//! consequences: no call is lifted out of text, the caller's trace is a receipt
12//! (tool, call id, outcome) that holds neither the arguments nor the result, and
13//! a [`ToolPolicy`] can be added for per-action authorisation.
14//!
15//! [`ToolLoop::strict`]: super::ToolLoop::strict
16
17use std::future::Future;
18use std::pin::Pin;
19
20use serde_json::Value;
21
22/// Whether a reply that is exactly one JSON object naming a tool in the set is
23/// run as that call (see [`ToolLoop::with_text_call_recovery`]).
24///
25/// [`ToolLoop::with_text_call_recovery`]: super::ToolLoop::with_text_call_recovery
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27#[non_exhaustive]
28pub enum TextCallRecovery {
29 /// A reply written as a call is never run: it is the answer. What a deployment
30 /// wants when a request for a JSON *example* must stay an example.
31 Off,
32 /// Only a call to a tool that declares [`read_only`](super::Tool::read_only) is
33 /// recovered; a call to any other tool is the answer. A declaration, not a
34 /// sandbox: it is as true as the tool's author made it.
35 ReadOnly,
36 /// Any tool in the set, as every release has done. The default.
37 #[default]
38 All,
39}
40
41impl TextCallRecovery {
42 /// Whether a call to a tool that is (`read_only`) or is not read-only is
43 /// run when written as text.
44 #[must_use]
45 pub const fn permits(self, read_only: bool) -> bool {
46 match self {
47 Self::Off => false,
48 Self::ReadOnly => read_only,
49 Self::All => true,
50 }
51 }
52}
53
54/// What a run's trace, the artifact the caller reads, carries for each call.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56#[non_exhaustive]
57pub enum TraceContent {
58 /// `name(arguments) -> result`, each line cut at
59 /// [`TRACE_LINE_LIMIT`](super::TRACE_LINE_LIMIT): a record for the caller of
60 /// everything the model sent and was sent back. Truncation is not redaction.
61 /// The default.
62 #[default]
63 Full,
64 /// `name [call id]: outcome`, where the outcome is `ran`, `failed` or
65 /// `not run again`: that the call happened and how it ended, with neither
66 /// the arguments nor the result. The model still sees both; the caller
67 /// does not.
68 Receipt,
69}
70
71/// How a call ended, for a [`TraceContent::Receipt`].
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub(super) enum CallStatus {
74 Ran,
75 Failed,
76 NotRun,
77}
78
79impl CallStatus {
80 /// `name [id]: outcome`.
81 pub(super) fn receipt(self, name: &str, id: &str) -> String {
82 let outcome = match self {
83 Self::Ran => "ran",
84 Self::Failed => "failed",
85 Self::NotRun => "not run again",
86 };
87 format!("{name} [{id}]: {outcome}")
88 }
89}
90
91/// The policy's answer.
92#[derive(Debug, Clone, PartialEq, Eq)]
93#[non_exhaustive]
94pub enum PolicyDecision {
95 /// Run the call.
96 Allow,
97 /// Do not run it. The reason is the call's result, as the model sees it
98 /// (an error it can recover from), and it is not recorded as a success.
99 Deny(String),
100 /// Do not run it until a person approves *this call*. The text is what the
101 /// person is shown.
102 ///
103 /// The run is parked in its [`StepJournal`](super::StepJournal) with the call's
104 /// [digest](call_digest), and the task asks for approval under the
105 /// approval extension ([`ApprovalGate`](crate::approval::ApprovalGate)); the call
106 /// runs when a decision for that digest arrives from an approver the gate
107 /// admits, and for no other call. A loop with no journal has nowhere to park
108 /// and refuses the call as it does for [`Deny`](Self::Deny). The policy is
109 /// asked again on resume, and a [`Deny`](Self::Deny) then still denies.
110 RequireApproval(String),
111}
112
113/// `sha256:<hex>` of a call as an action: the tool, its arguments in
114/// canonical form, and who it is for (tenant, requester, task).
115///
116/// What an approval is bound to: a decision for this digest approves this call
117/// from this requester in this tenant and task, and not the same call from
118/// another, nor another call by the same.
119#[must_use]
120pub fn call_digest(
121 tool: &str,
122 arguments: &Value,
123 tenant: Option<&str>,
124 principal: Option<&str>,
125 task: Option<&str>,
126) -> String {
127 let mut text = String::new();
128 super::idempotency::canonical(
129 &serde_json::json!({
130 "tool": tool, "arguments": arguments,
131 "tenant": tenant, "principal": principal, "task": task,
132 }),
133 &mut text,
134 );
135 super::journaling::sha256_text(text.as_bytes())
136}
137
138/// One call, as a [`ToolPolicy`] is asked about it: the tool and arguments the
139/// model chose, and **the request's identity, taken from the authenticated
140/// request and not from anything the model wrote**.
141#[derive(Debug, Clone, Copy)]
142#[non_exhaustive]
143pub struct PolicyRequest<'a> {
144 /// The tool, which is in the set (an unknown name is answered before the policy).
145 pub tool: &'a str,
146 /// The arguments, a JSON object.
147 pub arguments: &'a Value,
148 /// The call's id.
149 pub call_id: &'a str,
150 /// Whether the tool declares itself [`read_only`](super::Tool::read_only).
151 pub read_only: bool,
152 /// Whether the model wrote this call as text and the loop recovered it
153 /// ([`TextCallRecovery`]), rather than the provider returning it as a call.
154 pub recovered_from_text: bool,
155 /// The request's tenant, when the loop runs under
156 /// [`ToolLoopExecutor`](super::ToolLoopExecutor).
157 pub tenant: Option<&'a str>,
158 /// The authenticated caller's identity, when there is one.
159 pub principal: Option<&'a str>,
160 /// The task the call is made for, when the loop runs under
161 /// [`ToolLoopExecutor`](super::ToolLoopExecutor).
162 pub task: Option<&'a str>,
163}
164
165/// Asked before every tool call runs, whatever kind it is (native, recovered
166/// from text, or repeated after a retry), and able to refuse it. Install with
167/// [`ToolLoop::with_policy`](super::ToolLoop::with_policy).
168///
169/// An allowed task is not an authorised action: a task the caller may create
170/// does not authorise every tool a model may reach for. The policy decides per
171/// call, from the tool, the arguments and the request's identity.
172///
173/// # Order
174///
175/// For a call [`authorize`](Self::authorize) allows, nothing else is asked:
176/// it runs. For one it answers [`PolicyDecision::RequireApproval`], the run is
177/// parked; once a person approves exactly that call, the loop asks
178/// `authorize` again (a [`Deny`](PolicyDecision::Deny) still denies), checks
179/// the decision against the call's digest, and then, **immediately before
180/// the call runs**, tells the policy who approved it with
181/// [`approved`](Self::approved). Only that hook sees the effective decision;
182/// a policy that must record or check an approved action does it there, and
183/// an `Err` stops the call (adversarial review N02, 2026-11-13).
184pub trait ToolPolicy: Send + Sync + 'static {
185 /// Whether the call may run.
186 fn authorize<'a>(
187 &'a self,
188 request: &'a PolicyRequest<'a>,
189 ) -> Pin<Box<dyn Future<Output = PolicyDecision> + Send + 'a>>;
190
191 /// A call that [`authorize`](Self::authorize) sent for approval has been
192 /// approved by `approver` (the authenticated identity the approval gate
193 /// verified) and is about to run. `Err(reason)` stops it: it is not run,
194 /// and `reason` is its result as the model sees it.
195 ///
196 /// The default lets it run.
197 // Equivalent mutant: the body is a future of `Ok(())`, and cargo-mutants'
198 // replacement is `Box::pin(async move { Ok(()) })`, the same future; both
199 // arguments are discarded first, so `move` captures nothing. No test can
200 // distinguish the two (ADR 0006). On PR #210 it timed out (a 300 s test
201 // run against the incremental gate's 300 s cap) rather than surviving.
202 #[mutants::skip]
203 fn approved<'a>(
204 &'a self,
205 request: &'a PolicyRequest<'a>,
206 approver: &'a str,
207 ) -> Pin<Box<dyn Future<Output = Result<(), String>> + Send + 'a>> {
208 let _ = (request, approver);
209 Box::pin(async { Ok(()) })
210 }
211}
212
213/// The authenticated request's identity, handed to the loop by its executor.
214#[derive(Debug, Clone, Default)]
215#[non_exhaustive]
216pub struct TrustedIdentity {
217 /// The request's tenant.
218 pub tenant: Option<String>,
219 /// The authenticated caller.
220 pub principal: Option<String>,
221 /// The task the run belongs to.
222 pub task: Option<String>,
223}