adk_runner/builder.rs
1//! Typestate builder for [`RunnerConfig`] / [`Runner`].
2//!
3//! The builder enforces at compile time that the three required fields
4//! (`app_name`, `agent`, `session_service`) are set before `build()` is
5//! callable.
6//!
7//! # Example
8//!
9//! ```rust,ignore
10//! let runner = Runner::builder()
11//! .app_name("my-app")
12//! .agent(agent)
13//! .session_service(session_service)
14//! .memory_service(memory)
15//! .build()?;
16//! ```
17
18use std::marker::PhantomData;
19use std::sync::Arc;
20
21#[cfg(feature = "artifacts")]
22use adk_artifact::ArtifactService;
23use adk_core::audit_log::{AuditFailureMode, AuditRecorder, AuditTrail};
24use adk_core::{
25 ActionLedger, Agent, ApprovalStore, CacheCapable, ContextCacheConfig, GovernanceControl,
26 Memory, Result, RunBudget, RunConfig, SpendLedger, ToolPolicy,
27};
28#[cfg(feature = "plugins")]
29use adk_plugin::PluginManager;
30use adk_session::SessionService;
31use tokio_util::sync::CancellationToken;
32
33use crate::runner::{Runner, RunnerConfig};
34
35// ---------------------------------------------------------------------------
36// Typestate marker types
37// ---------------------------------------------------------------------------
38
39/// Marker: `app_name` has not been set.
40pub struct NoAppName;
41/// Marker: `app_name` has been set.
42pub struct HasAppName;
43/// Marker: `agent` has not been set.
44pub struct NoAgent;
45/// Marker: `agent` has been set.
46pub struct HasAgent;
47/// Marker: `session_service` has not been set.
48pub struct NoSessionService;
49/// Marker: `session_service` has been set.
50pub struct HasSessionService;
51
52// ---------------------------------------------------------------------------
53// Builder
54// ---------------------------------------------------------------------------
55
56/// A typestate builder for constructing a [`Runner`].
57///
58/// The three type parameters track whether the required fields have been
59/// provided. `build()` is only available when all three are `Has*`.
60pub struct RunnerConfigBuilder<A, G, S> {
61 app_name: Option<String>,
62 agent: Option<Arc<dyn Agent>>,
63 session_service: Option<Arc<dyn SessionService>>,
64 #[cfg(feature = "artifacts")]
65 artifact_service: Option<Arc<dyn ArtifactService>>,
66 memory_service: Option<Arc<dyn Memory>>,
67 #[cfg(feature = "plugins")]
68 plugin_manager: Option<Arc<PluginManager>>,
69 run_config: Option<RunConfig>,
70 compaction_config: Option<adk_core::EventsCompactionConfig>,
71 context_cache_config: Option<ContextCacheConfig>,
72 cache_capable: Option<Arc<dyn CacheCapable>>,
73 request_context: Option<adk_core::RequestContext>,
74 cancellation_token: Option<CancellationToken>,
75 intra_compaction_config: Option<adk_core::IntraCompactionConfig>,
76 intra_compaction_summarizer: Option<Arc<dyn adk_core::BaseEventsSummarizer>>,
77 #[cfg(feature = "context-compaction")]
78 context_compaction: Option<crate::compaction::CompactionConfig>,
79 budget: Option<RunBudget>,
80 tool_policy: Option<Arc<dyn ToolPolicy>>,
81 session_activity: Option<crate::history::SessionActivity>,
82 egress_policy: Option<adk_core::egress::EgressPolicy>,
83 governance: Option<GovernanceControl>,
84 action_ledger: Option<Arc<dyn ActionLedger>>,
85 approval_store: Option<Arc<dyn ApprovalStore>>,
86 spend_ledger: Option<Arc<dyn SpendLedger>>,
87 durable_runs: Option<Arc<dyn adk_core::DurableRunStore>>,
88 audit_recorder: Option<Arc<dyn AuditRecorder>>,
89 audit_failure_mode: AuditFailureMode,
90 identity_source: Option<Arc<dyn adk_core::IdentitySource>>,
91 subject_delegation: Option<Arc<dyn adk_core::SubjectDelegationPolicy>>,
92 _marker: PhantomData<(A, G, S)>,
93}
94
95impl RunnerConfigBuilder<NoAppName, NoAgent, NoSessionService> {
96 /// Create a new builder with all fields unset and defaults applied.
97 pub fn new() -> Self {
98 Self {
99 app_name: None,
100 agent: None,
101 session_service: None,
102 #[cfg(feature = "artifacts")]
103 artifact_service: None,
104 memory_service: None,
105 #[cfg(feature = "plugins")]
106 plugin_manager: None,
107 run_config: None,
108 compaction_config: None,
109 context_cache_config: None,
110 cache_capable: None,
111 request_context: None,
112 cancellation_token: None,
113 intra_compaction_config: None,
114 intra_compaction_summarizer: None,
115 #[cfg(feature = "context-compaction")]
116 context_compaction: None,
117 budget: None,
118 tool_policy: None,
119 session_activity: None,
120 egress_policy: None,
121 governance: None,
122 action_ledger: None,
123 approval_store: None,
124 spend_ledger: None,
125 durable_runs: None,
126 audit_recorder: None,
127 audit_failure_mode: AuditFailureMode::Block,
128 identity_source: None,
129 subject_delegation: None,
130 _marker: PhantomData,
131 }
132 }
133}
134
135impl Default for RunnerConfigBuilder<NoAppName, NoAgent, NoSessionService> {
136 fn default() -> Self {
137 Self::new()
138 }
139}
140
141// ---------------------------------------------------------------------------
142// Required-field setters (transition type state)
143// ---------------------------------------------------------------------------
144
145impl<A, G, S> RunnerConfigBuilder<A, G, S> {
146 /// Set the application name (required).
147 pub fn app_name(self, name: impl Into<String>) -> RunnerConfigBuilder<HasAppName, G, S> {
148 RunnerConfigBuilder {
149 app_name: Some(name.into()),
150 agent: self.agent,
151 session_service: self.session_service,
152 #[cfg(feature = "artifacts")]
153 artifact_service: self.artifact_service,
154 memory_service: self.memory_service,
155 #[cfg(feature = "plugins")]
156 plugin_manager: self.plugin_manager,
157 run_config: self.run_config,
158 compaction_config: self.compaction_config,
159 context_cache_config: self.context_cache_config,
160 cache_capable: self.cache_capable,
161 request_context: self.request_context,
162 cancellation_token: self.cancellation_token,
163 intra_compaction_config: self.intra_compaction_config,
164 intra_compaction_summarizer: self.intra_compaction_summarizer,
165 #[cfg(feature = "context-compaction")]
166 context_compaction: self.context_compaction,
167 budget: self.budget,
168 tool_policy: self.tool_policy,
169 session_activity: self.session_activity,
170 egress_policy: self.egress_policy,
171 governance: self.governance,
172 action_ledger: self.action_ledger,
173 approval_store: self.approval_store,
174 spend_ledger: self.spend_ledger,
175 durable_runs: self.durable_runs,
176 audit_recorder: self.audit_recorder,
177 audit_failure_mode: self.audit_failure_mode,
178 identity_source: self.identity_source,
179 subject_delegation: self.subject_delegation,
180 _marker: PhantomData,
181 }
182 }
183
184 /// Set the root agent (required).
185 pub fn agent(self, agent: Arc<dyn Agent>) -> RunnerConfigBuilder<A, HasAgent, S> {
186 RunnerConfigBuilder {
187 app_name: self.app_name,
188 agent: Some(agent),
189 session_service: self.session_service,
190 #[cfg(feature = "artifacts")]
191 artifact_service: self.artifact_service,
192 memory_service: self.memory_service,
193 #[cfg(feature = "plugins")]
194 plugin_manager: self.plugin_manager,
195 run_config: self.run_config,
196 compaction_config: self.compaction_config,
197 context_cache_config: self.context_cache_config,
198 cache_capable: self.cache_capable,
199 request_context: self.request_context,
200 cancellation_token: self.cancellation_token,
201 intra_compaction_config: self.intra_compaction_config,
202 intra_compaction_summarizer: self.intra_compaction_summarizer,
203 #[cfg(feature = "context-compaction")]
204 context_compaction: self.context_compaction,
205 budget: self.budget,
206 tool_policy: self.tool_policy,
207 session_activity: self.session_activity,
208 egress_policy: self.egress_policy,
209 governance: self.governance,
210 action_ledger: self.action_ledger,
211 approval_store: self.approval_store,
212 spend_ledger: self.spend_ledger,
213 durable_runs: self.durable_runs,
214 audit_recorder: self.audit_recorder,
215 audit_failure_mode: self.audit_failure_mode,
216 identity_source: self.identity_source,
217 subject_delegation: self.subject_delegation,
218 _marker: PhantomData,
219 }
220 }
221
222 /// Set the session service (required).
223 pub fn session_service(
224 self,
225 service: Arc<dyn SessionService>,
226 ) -> RunnerConfigBuilder<A, G, HasSessionService> {
227 RunnerConfigBuilder {
228 app_name: self.app_name,
229 agent: self.agent,
230 session_service: Some(service),
231 #[cfg(feature = "artifacts")]
232 artifact_service: self.artifact_service,
233 memory_service: self.memory_service,
234 #[cfg(feature = "plugins")]
235 plugin_manager: self.plugin_manager,
236 run_config: self.run_config,
237 compaction_config: self.compaction_config,
238 context_cache_config: self.context_cache_config,
239 cache_capable: self.cache_capable,
240 request_context: self.request_context,
241 cancellation_token: self.cancellation_token,
242 intra_compaction_config: self.intra_compaction_config,
243 intra_compaction_summarizer: self.intra_compaction_summarizer,
244 #[cfg(feature = "context-compaction")]
245 context_compaction: self.context_compaction,
246 budget: self.budget,
247 tool_policy: self.tool_policy,
248 session_activity: self.session_activity,
249 egress_policy: self.egress_policy,
250 governance: self.governance,
251 action_ledger: self.action_ledger,
252 approval_store: self.approval_store,
253 spend_ledger: self.spend_ledger,
254 durable_runs: self.durable_runs,
255 audit_recorder: self.audit_recorder,
256 audit_failure_mode: self.audit_failure_mode,
257 identity_source: self.identity_source,
258 subject_delegation: self.subject_delegation,
259 _marker: PhantomData,
260 }
261 }
262}
263
264// ---------------------------------------------------------------------------
265// Optional-field setters (no type-state change)
266// ---------------------------------------------------------------------------
267
268impl<A, G, S> RunnerConfigBuilder<A, G, S> {
269 /// Set the artifact service (optional).
270 #[cfg(feature = "artifacts")]
271 pub fn artifact_service(mut self, service: Arc<dyn ArtifactService>) -> Self {
272 self.artifact_service = Some(service);
273 self
274 }
275
276 /// Set the memory service (optional).
277 pub fn memory_service(mut self, service: Arc<dyn Memory>) -> Self {
278 self.memory_service = Some(service);
279 self
280 }
281
282 /// Set the plugin manager (optional).
283 #[cfg(feature = "plugins")]
284 pub fn plugin_manager(mut self, manager: Arc<PluginManager>) -> Self {
285 self.plugin_manager = Some(manager);
286 self
287 }
288
289 /// Set the run configuration (optional).
290 pub fn run_config(mut self, config: RunConfig) -> Self {
291 self.run_config = Some(config);
292 self
293 }
294
295 /// Set the resource limits for every run (optional).
296 ///
297 /// Each run gets fresh counters for these limits, checked before every model
298 /// call and tool dispatch. A run that reaches a limit ends with an event
299 /// explaining why and a `ResourceExhausted` error. Overrides any budget in
300 /// [`run_config`](Self::run_config). See [`adk_core::budget`].
301 ///
302 /// # Example
303 ///
304 /// ```rust,ignore
305 /// use adk_core::RunBudget;
306 ///
307 /// let runner = Runner::builder()
308 /// .app_name("my-app")
309 /// .agent(agent)
310 /// .session_service(session_service)
311 /// .budget(RunBudget::new().max_cost_usd(50.0).max_model_calls(200))
312 /// .build()?;
313 /// ```
314 pub fn budget(mut self, budget: RunBudget) -> Self {
315 self.budget = Some(budget);
316 self
317 }
318
319 /// Set the events compaction configuration (optional).
320 pub fn compaction_config(mut self, config: adk_core::EventsCompactionConfig) -> Self {
321 self.compaction_config = Some(config);
322 self
323 }
324
325 /// Set the context cache configuration (optional).
326 pub fn context_cache_config(mut self, config: ContextCacheConfig) -> Self {
327 self.context_cache_config = Some(config);
328 self
329 }
330
331 /// Set the cache-capable model reference (optional).
332 pub fn cache_capable(mut self, model: Arc<dyn CacheCapable>) -> Self {
333 self.cache_capable = Some(model);
334 self
335 }
336
337 /// Set the request context from auth middleware (optional).
338 pub fn request_context(mut self, ctx: adk_core::RequestContext) -> Self {
339 self.request_context = Some(ctx);
340 self
341 }
342
343 /// Set a cooperative cancellation token (optional).
344 ///
345 /// Each run derives a child of this token, so cancelling it stops every in-flight
346 /// run, while [`Runner::interrupt`] cancels only the targeted run.
347 pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
348 self.cancellation_token = Some(token);
349 self
350 }
351
352 /// Sets when agents compact their history before a model call (auto-compaction).
353 ///
354 /// Auto-compaction is on without this call: a request is compacted once it passes 80%
355 /// of the model's context window, or 100,000 estimated tokens when the model reports none.
356 ///
357 /// # Example
358 ///
359 /// ```rust,ignore
360 /// use adk_core::IntraCompactionConfig;
361 ///
362 /// // Compact past 60% of the window, keeping the 6 most recent entries.
363 /// let builder = Runner::builder()
364 /// .intra_compaction_config(IntraCompactionConfig::at_window_fraction(0.6).with_overlap_event_count(6));
365 /// ```
366 pub fn intra_compaction_config(mut self, config: adk_core::IntraCompactionConfig) -> Self {
367 self.intra_compaction_config = Some(config);
368 self
369 }
370
371 /// Turns auto-compaction off: agents send their history as it is until the model rejects
372 /// it.
373 pub fn without_intra_compaction(mut self) -> Self {
374 self.intra_compaction_config = Some(adk_core::IntraCompactionConfig::disabled());
375 self
376 }
377
378 /// Sets the summarizer auto-compaction uses, in place of a summary by the model the agent
379 /// is calling.
380 pub fn intra_compaction_summarizer(
381 mut self,
382 summarizer: Arc<dyn adk_core::BaseEventsSummarizer>,
383 ) -> Self {
384 self.intra_compaction_summarizer = Some(summarizer);
385 self
386 }
387
388 /// Set the policy evaluated for every tool call (optional).
389 ///
390 /// The runner installs it on each run's [`RunConfig::tool_policy`] when the run
391 /// does not carry one, so it governs transfer targets and agents behind an agent
392 /// tool as well. A [`DeclarativePolicy`](adk_core::DeclarativePolicy) denies every
393 /// tool no rule permits.
394 ///
395 /// # Example
396 ///
397 /// ```rust,ignore
398 /// use adk_core::DeclarativePolicy;
399 ///
400 /// let runner = Runner::builder()
401 /// .app_name("ops")
402 /// .agent(agent)
403 /// .session_service(sessions)
404 /// .tool_policy(Arc::new(DeclarativePolicy::builder().allow_read_only().build()))
405 /// .build()?;
406 /// ```
407 pub fn tool_policy(mut self, policy: Arc<dyn ToolPolicy>) -> Self {
408 self.tool_policy = Some(policy);
409 self
410 }
411
412 /// Record this runner's runs in `activity`, shared with the other runners and the
413 /// [`HistoryControl`](crate::HistoryControl) a host builds (optional).
414 ///
415 /// Without one, the runner keeps a registry of its own.
416 ///
417 /// # Example
418 ///
419 /// ```rust,ignore
420 /// let activity = adk_runner::SessionActivity::new();
421 /// let runner = Runner::builder()
422 /// .app_name("ops")
423 /// .agent(agent)
424 /// .session_service(sessions)
425 /// .session_activity(activity.clone())
426 /// .build()?;
427 /// ```
428 pub fn session_activity(mut self, activity: crate::history::SessionActivity) -> Self {
429 self.session_activity = Some(activity);
430 self
431 }
432
433 /// Set the operator's network egress ceiling for tool calls (optional).
434 ///
435 /// Every run is narrowed by it: a run whose [`RunConfig::egress_policy`] is set gets the
436 /// intersection of both, never more. A tool whose
437 /// [`Tool::egress`](adk_core::Tool::egress) declaration the ceiling does not admit is
438 /// refused before it runs. Calling it twice narrows to the intersection. See
439 /// [`adk_core::egress`].
440 ///
441 /// # Example
442 ///
443 /// ```rust,ignore
444 /// use adk_core::egress::EgressPolicy;
445 ///
446 /// let runner = Runner::builder()
447 /// .app_name("ops")
448 /// .agent(agent)
449 /// .session_service(sessions)
450 /// .egress_policy(EgressPolicy::allowlist(["api.github.com:443"])?)
451 /// .build()?;
452 /// ```
453 pub fn egress_policy(mut self, policy: adk_core::egress::EgressPolicy) -> Self {
454 self.egress_policy = Some(match self.egress_policy.take() {
455 Some(existing) => existing.narrow(&policy),
456 None => policy,
457 });
458 self
459 }
460
461 /// Share a kill switch with this runner (optional).
462 ///
463 /// Without one the runner creates its own, reachable through
464 /// [`Runner::governance`]. Freezing it fails new runs at their start and stops
465 /// running ones before their next model or tool call.
466 pub fn governance(mut self, control: GovernanceControl) -> Self {
467 self.governance = Some(control);
468 self
469 }
470
471 /// Set the ledger that records non-idempotent tool calls (optional).
472 ///
473 /// The runner installs it on each run's [`RunConfig::action_ledger`] when the run
474 /// does not carry one. Every backend implements the same
475 /// [`ActionLedger`] trait, so switching from SQLite to PostgreSQL, Redis, or
476 /// MongoDB changes only the value passed here.
477 ///
478 /// # Example
479 ///
480 /// ```rust,ignore
481 /// use adk_session::PostgresActionLedger;
482 ///
483 /// let ledger = PostgresActionLedger::from_pool(pool.clone());
484 /// ledger.migrate().await?;
485 /// let runner = Runner::builder()
486 /// .app_name("payments")
487 /// .agent(agent)
488 /// .session_service(sessions)
489 /// .action_ledger(Arc::new(ledger))
490 /// .build()?;
491 /// ```
492 pub fn action_ledger(mut self, ledger: Arc<dyn ActionLedger>) -> Self {
493 self.action_ledger = Some(ledger);
494 self
495 }
496
497 /// Set where calls held for approval and their decisions are kept (optional).
498 ///
499 /// The runner installs it on each run's [`RunConfig::approval_store`] when the run
500 /// does not carry one.
501 pub fn approval_store(mut self, store: Arc<dyn ApprovalStore>) -> Self {
502 self.approval_store = Some(store);
503 self
504 }
505
506 /// Set the ledger that model calls and payment tools reserve budget against
507 /// (optional).
508 ///
509 /// The runner installs it on each run's [`RunConfig::spend_ledger`] when the run
510 /// does not carry one.
511 pub fn spend_ledger(mut self, ledger: Arc<dyn SpendLedger>) -> Self {
512 self.spend_ledger = Some(ledger);
513 self
514 }
515
516 /// Set the durable run queue shared by every replica (optional).
517 ///
518 /// [`Runner::interrupt`](crate::Runner::interrupt) then also requests cancellation of
519 /// the session's unfinished durable runs, wherever their worker runs.
520 ///
521 /// # Example
522 ///
523 /// ```rust,ignore
524 /// let runner = Runner::builder()
525 /// .app_name("ops")
526 /// .agent(agent)
527 /// .session_service(sessions)
528 /// .durable_run_store(Arc::new(adk_core::InMemoryRunStore::new()))
529 /// .build()?;
530 /// ```
531 pub fn durable_run_store(mut self, store: Arc<dyn adk_core::DurableRunStore>) -> Self {
532 self.durable_runs = Some(store);
533 self
534 }
535
536 /// Record the runner's governed actions in `recorder` (optional).
537 ///
538 /// Every run records each tool decision (allowed, denied, held for approval), each
539 /// approval decision, each payment made through the payment tools, and each call
540 /// answered with an unknown outcome; the runner's kill switch records freezes and
541 /// unfreezes. Records name the acting agent and the subject it acts for, and carry
542 /// argument digests, never arguments. An action whose record cannot be written does
543 /// not happen; see [`audit_failure_mode`](Self::audit_failure_mode).
544 ///
545 /// The runner installs the trail on each run's [`RunConfig::audit`] when the run does
546 /// not carry one.
547 ///
548 /// # Example
549 ///
550 /// ```rust,ignore
551 /// use adk_auth::signed_audit::{AuditLog, Ed25519Signer};
552 ///
553 /// let log = AuditLog::builder(store, "replica-1", signer).open().await?;
554 /// let runner = Runner::builder()
555 /// .app_name("ops")
556 /// .agent(agent)
557 /// .session_service(sessions)
558 /// .audit_log(Arc::new(log))
559 /// .build()?;
560 /// ```
561 pub fn audit_log(mut self, recorder: Arc<dyn AuditRecorder>) -> Self {
562 self.audit_recorder = Some(recorder);
563 self
564 }
565
566 /// Set what happens when the [`audit_log`](Self::audit_log) cannot record an action
567 /// (optional). The default, [`AuditFailureMode::Block`], refuses the action.
568 pub fn audit_failure_mode(mut self, mode: AuditFailureMode) -> Self {
569 self.audit_failure_mode = mode;
570 self
571 }
572
573 /// Sets where each run's agent principals come from.
574 ///
575 /// The runner reads the source at the start of every run: the root agent acts as
576 /// [`principal_for`](adk_core::IdentitySource::principal_for) its name, falling back
577 /// to [`current`](adk_core::IdentitySource::current), and every other agent in the
578 /// tree acts as `principal_for` its name, falling back to
579 /// `urn:adk:agent:{app_name}/{agent_name}`. A principal the run's
580 /// [`RunConfig::acting`] names for an agent takes precedence. A run whose source fails
581 /// ends with the source's error before any agent runs.
582 ///
583 /// # Example
584 ///
585 /// ```rust,ignore
586 /// use adk_core::{AgentId, AgentPrincipal, StaticIdentitySource};
587 ///
588 /// let source = StaticIdentitySource::new(
589 /// AgentPrincipal::new(AgentId::new("spiffe://acme.example/agent/billing")?)
590 /// .with_instance(std::env::var("HOSTNAME")?),
591 /// );
592 /// let runner = Runner::builder()
593 /// .app_name("billing")
594 /// .agent(agent)
595 /// .session_service(sessions)
596 /// .identity_source(Arc::new(source))
597 /// .build()?;
598 /// ```
599 pub fn identity_source(mut self, source: Arc<dyn adk_core::IdentitySource>) -> Self {
600 self.identity_source = Some(source);
601 self
602 }
603
604 /// Sets a fixed principal the root agent acts as.
605 ///
606 /// Shorthand for [`identity_source`](Self::identity_source) with a
607 /// [`StaticIdentitySource`](adk_core::StaticIdentitySource); sub-agents act as their
608 /// derived ids.
609 pub fn agent_principal(self, principal: adk_core::AgentPrincipal) -> Self {
610 self.identity_source(Arc::new(adk_core::StaticIdentitySource::new(principal)))
611 }
612
613 /// Sets which runs may act for a subject other than their session's user.
614 ///
615 /// Without a policy, a run whose [`RunConfig::acting`] asks to act for anyone but the
616 /// session's user is refused with `identity.subject_mismatch` before any agent runs.
617 ///
618 /// # Example
619 ///
620 /// ```rust,ignore
621 /// use adk_core::{StaticSubjectDelegation, SubjectRef};
622 ///
623 /// let runner = Runner::builder()
624 /// .app_name("crm")
625 /// .agent(agent)
626 /// .session_service(sessions)
627 /// .subject_delegation(Arc::new(
628 /// StaticSubjectDelegation::new().allow_any(SubjectRef::service("crm-sync")),
629 /// ))
630 /// .build()?;
631 /// ```
632 pub fn subject_delegation(
633 mut self,
634 policy: Arc<dyn adk_core::SubjectDelegationPolicy>,
635 ) -> Self {
636 self.subject_delegation = Some(policy);
637 self
638 }
639
640 /// Sets a compaction strategy auto-compaction applies in place of a summary.
641 ///
642 /// Before any model call whose request passes `config.context_budget` estimated tokens,
643 /// the agent's history is shortened with the given
644 /// [`CompactionStrategy`](crate::compaction::CompactionStrategy), up to
645 /// `config.max_retries` times.
646 #[cfg(feature = "context-compaction")]
647 pub fn context_compaction(mut self, config: crate::compaction::CompactionConfig) -> Self {
648 self.context_compaction = Some(config);
649 self
650 }
651}
652
653// ---------------------------------------------------------------------------
654// build() — only available when all required fields are set
655// ---------------------------------------------------------------------------
656
657impl RunnerConfigBuilder<HasAppName, HasAgent, HasSessionService> {
658 /// Consume the builder and produce a [`RunnerConfig`] without creating a [`Runner`].
659 ///
660 /// Use this when you need the raw config (e.g. to wrap in `Arc` for A2A handlers).
661 pub fn build_config(self) -> RunnerConfig {
662 let run_config = merge_budget(self.run_config, self.budget);
663 RunnerConfig {
664 app_name: self.app_name.expect("typestate guarantees app_name is set"),
665 agent: self.agent.expect("typestate guarantees agent is set"),
666 session_service: self
667 .session_service
668 .expect("typestate guarantees session_service is set"),
669 #[cfg(feature = "artifacts")]
670 artifact_service: self.artifact_service,
671 memory_service: self.memory_service,
672 #[cfg(feature = "plugins")]
673 plugin_manager: self.plugin_manager,
674 run_config,
675 compaction_config: self.compaction_config,
676 context_cache_config: self.context_cache_config,
677 cache_capable: self.cache_capable,
678 request_context: self.request_context,
679 cancellation_token: self.cancellation_token,
680 intra_compaction_config: self.intra_compaction_config,
681 intra_compaction_summarizer: self.intra_compaction_summarizer,
682 #[cfg(feature = "context-compaction")]
683 context_compaction: self.context_compaction,
684 tool_policy: self.tool_policy,
685 egress_policy: self.egress_policy,
686 governance: self.governance,
687 action_ledger: self.action_ledger,
688 approval_store: self.approval_store,
689 spend_ledger: self.spend_ledger,
690 durable_runs: self.durable_runs,
691 audit: self.audit_recorder.map(|recorder| {
692 AuditTrail::new(recorder).with_failure_mode(self.audit_failure_mode)
693 }),
694 identity_source: self.identity_source,
695 subject_delegation: self.subject_delegation,
696 }
697 }
698
699 /// Consume the builder and create a [`Runner`].
700 ///
701 /// Delegates to [`Runner::new()`] internally.
702 ///
703 /// # Errors
704 ///
705 /// Returns an error if `Runner::new()` fails (e.g. invalid `app_name`).
706 pub fn build(self) -> Result<Runner> {
707 let run_config = merge_budget(self.run_config, self.budget);
708 let config = RunnerConfig {
709 // SAFETY: typestate guarantees these are `Some`.
710 app_name: self.app_name.expect("typestate guarantees app_name is set"),
711 agent: self.agent.expect("typestate guarantees agent is set"),
712 session_service: self
713 .session_service
714 .expect("typestate guarantees session_service is set"),
715 #[cfg(feature = "artifacts")]
716 artifact_service: self.artifact_service,
717 memory_service: self.memory_service,
718 #[cfg(feature = "plugins")]
719 plugin_manager: self.plugin_manager,
720 run_config,
721 compaction_config: self.compaction_config,
722 context_cache_config: self.context_cache_config,
723 cache_capable: self.cache_capable,
724 request_context: self.request_context,
725 cancellation_token: self.cancellation_token,
726 intra_compaction_config: self.intra_compaction_config,
727 intra_compaction_summarizer: self.intra_compaction_summarizer,
728 #[cfg(feature = "context-compaction")]
729 context_compaction: self.context_compaction,
730 tool_policy: self.tool_policy,
731 egress_policy: self.egress_policy,
732 governance: self.governance,
733 action_ledger: self.action_ledger,
734 approval_store: self.approval_store,
735 spend_ledger: self.spend_ledger,
736 durable_runs: self.durable_runs,
737 audit: self.audit_recorder.map(|recorder| {
738 AuditTrail::new(recorder).with_failure_mode(self.audit_failure_mode)
739 }),
740 identity_source: self.identity_source,
741 subject_delegation: self.subject_delegation,
742 };
743 let runner = Runner::new(config)?;
744 Ok(match self.session_activity {
745 Some(activity) => runner.with_session_activity(activity),
746 None => runner,
747 })
748 }
749}
750
751/// Applies a builder-level budget on top of the configured run config.
752fn merge_budget(run_config: Option<RunConfig>, budget: Option<RunBudget>) -> Option<RunConfig> {
753 match budget {
754 Some(budget) => {
755 let mut config = run_config.unwrap_or_default();
756 config.budget = Some(budget);
757 Some(config)
758 }
759 None => run_config,
760 }
761}