Skip to main content

a2a_protocol_server/tool_loop/
run_config.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! How a [`ToolLoop`] is configured: the `with_*` setters and the strict profile.
5
6#[cfg(feature = "otel")]
7use super::GenAiMeter;
8use super::{
9    ArgumentCheck, TextCallRecovery, ToolLoop, ToolModel, ToolPolicy, ToolSet, TraceContent,
10};
11
12impl ToolLoop {
13    /// Names the agent this loop is, recorded as `gen_ai.agent.name` on
14    /// the run's metrics.
15    #[must_use]
16    pub fn with_agent_name(mut self, name: impl Into<String>) -> Self {
17        self.agent_name = Some(name.into());
18        self
19    }
20
21    /// Records the loop's metrics (`gen_ai.client.inference.duration` and
22    /// the rest; ADR 0013) to `meter` rather than to the global provider's
23    /// meter, which is looked up each time one is recorded.
24    ///
25    /// Takes the meter by reference since 0.16.0: the instruments are built
26    /// from it once, here, and the meter itself is not kept (audit C-23).
27    #[cfg(feature = "otel")]
28    #[must_use]
29    pub fn with_meter(mut self, meter: &opentelemetry::metrics::Meter) -> Self {
30        self.meter = GenAiMeter::new(meter);
31        self
32    }
33
34    /// Sets the secret idempotency keys are derived under. Each loop draws
35    /// its own by default, so keys differ between processes; replicas that
36    /// set the same secret give the same call in the same scope the same
37    /// key, so a backend deduplicates a call one replica retries after
38    /// another made it. Keep it as secret as a credential: with it, keys
39    /// can be computed from task ids and arguments.
40    #[must_use]
41    pub const fn with_idempotency_secret(mut self, secret: [u8; 32]) -> Self {
42        self.secret = secret;
43        self.secret_set = true;
44        self
45    }
46
47    /// Keeps each run's progress in `journal`, so a run begun again under the
48    /// same key resumes instead of starting over, and a call a policy says
49    /// needs approval can wait for it (adversarial review, S1 and S7). See
50    /// [`StepJournal`](super::StepJournal) for what is written, what a resume
51    /// promises, and what it does not.
52    ///
53    /// Set [`with_idempotency_secret`](Self::with_idempotency_secret) too if a
54    /// call may be in flight when a replica dies: without it a call whose
55    /// receipt was written and whose result was not cannot be re-run safely, and
56    /// the resumed run fails with [`LoopError::Indeterminate`](super::LoopError::Indeterminate).
57    #[must_use]
58    pub fn with_journal(mut self, journal: std::sync::Arc<dyn super::StepJournal>) -> Self {
59        self.journal.store = Some(journal);
60        self
61    }
62
63    /// Seals each checkpoint's body with `cipher` before the journal stores
64    /// it: the conversation, tool arguments and results and the trace a run
65    /// carries are then not readable from the journal's table, its backups or
66    /// its replicas without the key (adversarial review N07, 2026-11-13). The
67    /// owner (tenant, caller, task), the revision and whether the run is
68    /// finished stay readable: they are what the journal's lifecycle
69    /// ([`StepJournal::erase`](super::StepJournal::erase),
70    /// [`StepJournal::sweep`](super::StepJournal::sweep)) finds a run by.
71    ///
72    /// A body is bound to its run's key and revision, so it does not open
73    /// moved to another run or rolled back. A checkpoint written as JSON
74    /// before the cipher was set is still read, and sealed from its next
75    /// write.
76    #[cfg(feature = "encryption")]
77    #[must_use]
78    pub fn with_journal_cipher(
79        mut self,
80        cipher: std::sync::Arc<dyn crate::store::encrypted::ContentCipher>,
81    ) -> Self {
82        self.journal.cipher = Some(cipher);
83        self
84    }
85
86    /// Shows the model at most `bytes` of one tool's result; the rest is cut,
87    /// at a character boundary, and the model is told how much there was
88    /// ([`DEFAULT_RESULT_LIMIT`](crate::tool_loop::DEFAULT_RESULT_LIMIT), 1 MiB). The
89    /// tool ran either way; this bounds what the run keeps of it (N09).
90    #[must_use]
91    pub const fn with_result_limit(mut self, bytes: usize) -> Self {
92        self.byte_limits.result = bytes;
93        self
94    }
95
96    /// Sends no model request past `bytes` (preamble, conversation and tool
97    /// catalogue, as JSON): the run ends with
98    /// [`LoopError::TooLarge`](super::LoopError::TooLarge) instead
99    /// ([`DEFAULT_REQUEST_LIMIT`](crate::tool_loop::DEFAULT_REQUEST_LIMIT), 8 MiB; N09).
100    #[must_use]
101    pub const fn with_request_limit(mut self, bytes: usize) -> Self {
102        self.byte_limits.request = bytes;
103        self
104    }
105
106    /// Writes no checkpoint body past `bytes`: the run stops before the step
107    /// it would have recorded, as for any checkpoint the journal cannot write
108    /// ([`DEFAULT_CHECKPOINT_LIMIT`](crate::tool_loop::DEFAULT_CHECKPOINT_LIMIT),
109    /// 32 MiB; N09).
110    #[must_use]
111    pub const fn with_checkpoint_limit(mut self, bytes: usize) -> Self {
112        self.journal.max_body = bytes;
113        self
114    }
115
116    /// Whether a journal is installed.
117    pub(in crate::tool_loop) fn has_journal(&self) -> bool {
118        self.journal.store.is_some()
119    }
120
121    /// Adds a pin to every checkpoint: a policy version, a skill bundle digest,
122    /// anything the deployment says a resumed run must still be running under.
123    /// A run whose checkpoint carries other pins is refused on resume.
124    #[must_use]
125    pub fn with_pin(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
126        self.pin_labels.insert(name.into(), value.into());
127        self
128    }
129
130    /// Sets the system preamble every turn is sent with.
131    #[must_use]
132    pub fn with_preamble(mut self, preamble: impl Into<String>) -> Self {
133        self.preamble = preamble.into();
134        self
135    }
136
137    /// Sets how many model turns a run may take. `0` is taken as `1`: a run
138    /// asks the model at least once.
139    #[must_use]
140    pub const fn with_max_turns(mut self, max_turns: usize) -> Self {
141        self.max_turns = if max_turns == 0 { 1 } else { max_turns };
142        self
143    }
144
145    /// Sets how many tool calls one model reply may make; the first this many
146    /// run and the rest are dropped, with a line in the trace saying so. `0` is
147    /// taken as `1`. [`DEFAULT_MAX_CALLS_PER_TURN`](super::DEFAULT_MAX_CALLS_PER_TURN) when not set.
148    #[must_use]
149    pub const fn with_max_calls_per_turn(mut self, max_calls: usize) -> Self {
150        self.max_calls_per_turn = if max_calls == 0 { 1 } else { max_calls };
151        self
152    }
153
154    /// Whether a final reply that is exactly one JSON object naming a tool
155    /// in the set — bare, in a code fence, or between `<tool_call>` tags —
156    /// is run as that call rather than returned as the answer. On by
157    /// default: small models write calls as text, and an answer of raw JSON
158    /// helps nobody. `true` is [`TextCallRecovery::All`] and `false`
159    /// [`TextCallRecovery::Off`]; [`with_text_call_recovery`](Self::with_text_call_recovery)
160    /// also offers [`ReadOnly`](TextCallRecovery::ReadOnly).
161    #[must_use]
162    pub const fn with_recover_text_calls(mut self, on: bool) -> Self {
163        self.text_recovery = if on {
164            TextCallRecovery::All
165        } else {
166            TextCallRecovery::Off
167        };
168        self
169    }
170
171    /// Which tools a reply written as a call may run (adversarial review T3).
172    #[must_use]
173    pub const fn with_text_call_recovery(mut self, recovery: TextCallRecovery) -> Self {
174        self.text_recovery = recovery;
175        self
176    }
177
178    /// What the caller's trace carries for each call (adversarial review T1).
179    #[must_use]
180    pub const fn with_trace_content(mut self, content: TraceContent) -> Self {
181        self.trace_content = content;
182        self
183    }
184
185    /// Whether a call's arguments are checked against the tool's JSON Schema
186    /// before the policy is asked and the call runs (adversarial review T2);
187    /// see [`ArgumentCheck`] for what is checked and what is not.
188    #[must_use]
189    pub const fn with_argument_check(mut self, check: ArgumentCheck) -> Self {
190        self.argument_check = check;
191        self
192    }
193
194    /// Installs a policy asked before every call runs (adversarial review T2).
195    #[must_use]
196    pub fn with_policy(mut self, policy: impl ToolPolicy) -> Self {
197        self.policy = Some(Box::new(policy));
198        self
199    }
200
201    /// A loop for a deployment that takes a tool call to be an action with
202    /// consequences: no call is lifted out of text
203    /// ([`TextCallRecovery::Off`]), the caller's trace is a receipt
204    /// ([`TraceContent::Receipt`]) and arguments are checked against the tool's
205    /// schema ([`ArgumentCheck::Strict`]). Add a [`ToolPolicy`] with
206    /// [`with_policy`](Self::with_policy) for per-action authorisation.
207    #[must_use]
208    pub fn strict(model: impl ToolModel, tools: ToolSet) -> Self {
209        Self::new(model, tools)
210            .with_text_call_recovery(TextCallRecovery::Off)
211            .with_trace_content(TraceContent::Receipt)
212            .with_argument_check(ArgumentCheck::Strict)
213    }
214}