causa_runtime/config.rs
1//! Run configuration axes — what to ask (`TurnInvocation`), when the loop
2//! gives up (`TurnPolicy`), how tools execute (`ExecutionOptions`), and how
3//! context is materialized (`FramePolicy`, canonical carrier in `budget`).
4//! Deliberately four focused units instead of one universal context config.
5
6use std::sync::Arc;
7use std::time::Duration;
8
9use crate::budget::{FramePolicy, TokenCounter};
10use crate::interaction::TurnInteraction;
11use causa_kernel::StreamDelta;
12use causa_kernel::{
13 ArtifactStore, CacheDirective, GenerationOptions, ModelInvokeErrorKind, ModelRef, ToolSurface,
14};
15
16/// Retry policy — driver-side scheduling, not a kernel fact. The retryability
17/// judgment lives here because interpreting error kinds is loop policy.
18#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
19pub struct RetryPolicy {
20 /// Retries allowed per model round after the first failed attempt;
21 /// `0` (the default) disables retrying entirely.
22 pub max_retries: u32,
23 /// Whether `TimedOut` model errors are retried (`Transient` errors
24 /// always are). Default `false`.
25 pub retry_timeouts: bool,
26 /// Backoff base before the first retry, in milliseconds. `0` = no
27 /// backoff (retry immediately).
28 pub backoff_base_ms: u64,
29 /// Backoff ceiling, in milliseconds.
30 pub backoff_max_ms: u64,
31}
32impl Default for RetryPolicy {
33 /// Conservative defaults: no automatic retries, but a 500ms→8s
34 /// exponential backoff whenever retries are enabled.
35 fn default() -> Self {
36 Self {
37 max_retries: 0,
38 retry_timeouts: false,
39 backoff_base_ms: 500,
40 backoff_max_ms: 8_000,
41 }
42 }
43}
44impl RetryPolicy {
45 /// Whether this policy schedules a further attempt for the error kind.
46 pub fn allows(&self, kind: &ModelInvokeErrorKind) -> bool {
47 match kind {
48 ModelInvokeErrorKind::Transient => true,
49 ModelInvokeErrorKind::TimedOut => self.retry_timeouts,
50 _ => false,
51 }
52 }
53
54 /// Wait before the (1-based) `next_attempt` fires:
55 /// `min(base * 2^(next-2), max)` with ±20% jitter, shared by the
56 /// `invoke` and `stream` retry paths. `ZERO` when the base is 0.
57 pub fn backoff_delay(&self, next_attempt: u32) -> Duration {
58 if self.backoff_base_ms == 0 {
59 return Duration::ZERO;
60 }
61 let exp = next_attempt.saturating_sub(2).min(32);
62 let raw = self.backoff_base_ms.saturating_mul(1u64 << exp);
63 let capped = raw.min(self.backoff_max_ms);
64 // ±20% jitter from wall-clock nanos — scheduling noise, not a
65 // security primitive. 80..=120 percent.
66 let nanos = std::time::SystemTime::now()
67 .duration_since(std::time::UNIX_EPOCH)
68 .map(|d| d.subsec_nanos() as u64)
69 .unwrap_or(0);
70 let jitter_pct = 80 + nanos % 41;
71 Duration::from_millis(capped.saturating_mul(jitter_pct) / 100)
72 }
73}
74
75/// Per-turn loop bounds: model rounds and dispatched tool calls. Exceeding
76/// either interrupts the turn (see [`crate::driver::TurnInterruption`]).
77#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
78pub struct TurnLimits {
79 /// Ceiling on model rounds — checked as `round >= max_model_rounds`
80 /// at the top of every round. Default: 10.
81 pub max_model_rounds: u32,
82 /// Ceiling on tool calls across the whole turn, counted at dispatch
83 /// time (a batch paused pending approval counts when emitted).
84 /// Default: 64.
85 pub max_tool_calls: u32,
86}
87impl Default for TurnLimits {
88 fn default() -> Self {
89 Self {
90 max_model_rounds: 10,
91 max_tool_calls: 64,
92 }
93 }
94}
95
96/// Invocation options — what the model is asked this run.
97#[derive(Debug, Clone)]
98pub struct TurnInvocation {
99 /// Which model the gateway invokes. Default: the `"fake"` placeholder.
100 pub model: ModelRef,
101 /// The tool surface advertised to the model for this run's **first
102 /// model phase** — the baseline snapshot, conventionally
103 /// `executor.tool_surface().await`. At every later round boundary the
104 /// driver re-snapshots the runner's `ToolExecutor` instead, so catalog
105 /// changes (a dynamic source bumping its listing mid-turn) reach the
106 /// next request; registering a source therefore authorizes its
107 /// evolving catalog from the second round on. Retries within one round
108 /// reuse the round's snapshot. A hard per-round cap is a `ToolUseHook`
109 /// (reject) or unregister concern, not a frozen surface. Default:
110 /// empty.
111 pub tool_surface: ToolSurface,
112 /// Generation (sampling) parameters sent with every attempt. Default:
113 /// `GenerationOptions::default()`.
114 pub generation: GenerationOptions,
115 /// Prompt-cache instruction rendered by the gateway's translation face.
116 /// Default: [`CacheDirective::None`].
117 pub cache: CacheDirective,
118}
119impl Default for TurnInvocation {
120 fn default() -> Self {
121 Self {
122 model: ModelRef::new("fake"),
123 tool_surface: ToolSurface::empty(),
124 generation: GenerationOptions::default(),
125 cache: CacheDirective::None,
126 }
127 }
128}
129
130/// Turn policy — when the loop retries or gives up.
131#[derive(Debug, Clone, Default)]
132pub struct TurnPolicy {
133 /// Retry schedule for failed model attempts — see [`RetryPolicy`].
134 pub retry: RetryPolicy,
135 /// Loop bounds for the turn — see [`TurnLimits`].
136 pub limits: TurnLimits,
137 /// Per-model-attempt budget; `None` = unbounded attempt.
138 pub attempt_timeout: Option<Duration>,
139 /// What the execution stack does after committing an `UnknownOutcome`
140 /// tool result — see [`UnknownOutcomeConfig`]. Default: stop the turn.
141 pub unknown_outcome: UnknownOutcomeConfig,
142}
143
144/// Component vocabulary for the action taken after an
145/// `UnknownOutcome` tool result is committed. It is configuration and saved
146/// host-decision data, not tool vocabulary and not a fact: the recorded
147/// result is committed verbatim either way, `Stop` merely interrupts the
148/// turn before the next model call, and `Continue` only allows the next
149/// round — it never re-runs the call, never rewrites the result into a
150/// success, and never cancels sibling calls.
151#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
152pub enum UnknownOutcomePolicy {
153 /// Treat the unknown outcome as unsafe: the turn interrupts rather
154 /// than continue on an unverifiable result (the default).
155 #[default]
156 Stop,
157 /// Keep the turn alive; the `UnknownOutcome` result still lands in the
158 /// transcript.
159 Continue,
160}
161
162/// Unknown-outcome continuation configuration: a default action plus
163/// per-tool-name overrides. Resolution is by the **actual executed tool
164/// name** (post hook / rewrite / resume decision, full namespace for
165/// dynamic tools) — never the original model draft's name, and never read
166/// out of a result body. An explicit override wins over the default.
167#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
168pub struct UnknownOutcomeConfig {
169 /// The action for `UnknownOutcome` results whose tool has no explicit
170 /// override. Default: [`UnknownOutcomePolicy::Stop`].
171 pub default: UnknownOutcomePolicy,
172 /// Explicit per-tool actions, keyed by the executed tool name (the
173 /// executor's full namespace name for dynamic tools).
174 pub overrides: std::collections::HashMap<String, UnknownOutcomePolicy>,
175}
176impl UnknownOutcomeConfig {
177 /// Resolve the action for one executed tool name: the explicit
178 /// override if present, else the default.
179 pub fn resolve(&self, tool_name: &str) -> UnknownOutcomePolicy {
180 self.overrides
181 .get(tool_name)
182 .copied()
183 .unwrap_or(self.default)
184 }
185}
186/// Per-call truncation thresholds for tool outputs — the explicit
187/// truncation effect hosts opt into (output retention is harness
188/// configuration, not a tool declaration).
189#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
190pub struct ToolOutputLimits {
191 /// Maximum estimated tokens a tool result may carry before it gets
192 /// truncated; [`usize::MAX`] (the default) disables truncation.
193 pub max_tokens: usize,
194}
195impl Default for ToolOutputLimits {
196 /// No limit by default — callers opt in to truncation.
197 ///
198 /// Specific limits come from host configuration (`ExecutionOptions`):
199 /// the fallback plus per-tool-name overrides. The default is
200 /// `usize::MAX` so truncation is an *explicit* effect, never the
201 /// absence of configuration.
202 fn default() -> Self {
203 Self {
204 max_tokens: usize::MAX,
205 }
206 }
207}
208
209/// Execution options — how tool calls run inside a round.
210#[derive(Clone, Default)]
211pub struct ExecutionOptions {
212 /// Fallback per-output token limit for truncation; a per-tool-name
213 /// entry in `tool_output_limits_overrides` replaces it (even with a
214 /// larger value — the override is the chosen limit, not a cap).
215 pub tool_output_limits: ToolOutputLimits,
216 /// Per-tool-name limit overrides, keyed by the actual executed tool
217 /// name (full namespace name for dynamic tools). A name not yet
218 /// present in a dynamic catalog may still be configured here; the
219 /// entry applies once that name executes.
220 pub tool_output_limits_overrides: std::collections::HashMap<String, ToolOutputLimits>,
221 /// Where a truncated output's full bytes are spilled as an artifact;
222 /// `None` = truncate without a retrievable original.
223 pub artifact_store: Option<Arc<dyn ArtifactStore>>,
224 /// Counter used for tool-output truncation estimation.
225 pub token_counter: Option<Arc<dyn TokenCounter>>,
226 /// Per-tool-call deadline; `None` = unbounded call (backstop still
227 /// applies if the turn carries a deadline).
228 pub call_timeout: Option<Duration>,
229}
230impl std::fmt::Debug for ExecutionOptions {
231 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232 f.debug_struct("ExecutionOptions")
233 .field("tool_output_limits", &self.tool_output_limits)
234 .field(
235 "tool_output_limits_overrides",
236 &self.tool_output_limits_overrides.len(),
237 )
238 .field("artifact_store", &self.artifact_store.is_some())
239 .field("token_counter", &self.token_counter.is_some())
240 .field("call_timeout", &self.call_timeout)
241 .finish()
242 }
243}
244
245/// The execution stack's input: the four configuration axes plus the
246/// single interaction seam. External assemblers may build any of them
247/// independently; `Default` yields the placeholder/noop wiring.
248#[derive(Clone)]
249pub struct TurnRunOptions {
250 /// What the model is asked this run — see [`TurnInvocation`].
251 pub invocation: TurnInvocation,
252 /// When the loop retries or gives up — see [`TurnPolicy`].
253 pub policy: TurnPolicy,
254 /// How tool calls execute — see [`ExecutionOptions`].
255 pub execution: ExecutionOptions,
256 /// Frame materialization policy for the bare-turn entries; inert for
257 /// the conversation entries (lossless merged view).
258 pub frame: FramePolicy,
259 /// The one host↔driver interaction boundary for the turn. Default:
260 /// [`NoopInteraction`] — observes nothing, decides nothing.
261 pub interaction: Arc<dyn TurnInteraction>,
262}
263impl Default for TurnRunOptions {
264 fn default() -> Self {
265 Self {
266 invocation: TurnInvocation::default(),
267 policy: TurnPolicy::default(),
268 execution: ExecutionOptions::default(),
269 frame: FramePolicy::default(),
270 interaction: Arc::new(NoopInteraction),
271 }
272 }
273}
274impl std::fmt::Debug for TurnRunOptions {
275 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276 f.debug_struct("TurnRunOptions")
277 .field("invocation", &self.invocation)
278 .field("policy", &self.policy)
279 .field("execution", &self.execution)
280 .field("frame", &self.frame)
281 .finish_non_exhaustive()
282 }
283}
284
285/// The interaction-less default: observes no deltas, makes no decisions.
286/// The literal absence of behavior, not a policy.
287#[derive(Debug, Default, Clone, Copy)]
288pub struct NoopInteraction;
289
290#[async_trait::async_trait]
291impl TurnInteraction for NoopInteraction {
292 async fn on_delta(&self, _round_id: causa_kernel::RoundId, _delta: &StreamDelta) {}
293}