adk-runner 3.0.0

Agent execution runtime for Rust Agent Development Kit (ADK-Rust) agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//! Typestate builder for [`RunnerConfig`] / [`Runner`].
//!
//! The builder enforces at compile time that the three required fields
//! (`app_name`, `agent`, `session_service`) are set before `build()` is
//! callable.
//!
//! # Example
//!
//! ```rust,ignore
//! let runner = Runner::builder()
//!     .app_name("my-app")
//!     .agent(agent)
//!     .session_service(session_service)
//!     .memory_service(memory)
//!     .build()?;
//! ```

use std::marker::PhantomData;
use std::sync::Arc;

#[cfg(feature = "artifacts")]
use adk_artifact::ArtifactService;
use adk_core::audit_log::{AuditFailureMode, AuditRecorder, AuditTrail};
use adk_core::{
    ActionLedger, Agent, ApprovalStore, CacheCapable, ContextCacheConfig, GovernanceControl,
    Memory, Result, RunBudget, RunConfig, SpendLedger, ToolPolicy,
};
#[cfg(feature = "plugins")]
use adk_plugin::PluginManager;
use adk_session::SessionService;
use tokio_util::sync::CancellationToken;

use crate::runner::{Runner, RunnerConfig};

// ---------------------------------------------------------------------------
// Typestate marker types
// ---------------------------------------------------------------------------

/// Marker: `app_name` has not been set.
pub struct NoAppName;
/// Marker: `app_name` has been set.
pub struct HasAppName;
/// Marker: `agent` has not been set.
pub struct NoAgent;
/// Marker: `agent` has been set.
pub struct HasAgent;
/// Marker: `session_service` has not been set.
pub struct NoSessionService;
/// Marker: `session_service` has been set.
pub struct HasSessionService;

// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------

/// A typestate builder for constructing a [`Runner`].
///
/// The three type parameters track whether the required fields have been
/// provided. `build()` is only available when all three are `Has*`.
pub struct RunnerConfigBuilder<A, G, S> {
    app_name: Option<String>,
    agent: Option<Arc<dyn Agent>>,
    session_service: Option<Arc<dyn SessionService>>,
    #[cfg(feature = "artifacts")]
    artifact_service: Option<Arc<dyn ArtifactService>>,
    memory_service: Option<Arc<dyn Memory>>,
    #[cfg(feature = "plugins")]
    plugin_manager: Option<Arc<PluginManager>>,
    run_config: Option<RunConfig>,
    compaction_config: Option<adk_core::EventsCompactionConfig>,
    context_cache_config: Option<ContextCacheConfig>,
    cache_capable: Option<Arc<dyn CacheCapable>>,
    request_context: Option<adk_core::RequestContext>,
    cancellation_token: Option<CancellationToken>,
    intra_compaction_config: Option<adk_core::IntraCompactionConfig>,
    intra_compaction_summarizer: Option<Arc<dyn adk_core::BaseEventsSummarizer>>,
    #[cfg(feature = "context-compaction")]
    context_compaction: Option<crate::compaction::CompactionConfig>,
    budget: Option<RunBudget>,
    tool_policy: Option<Arc<dyn ToolPolicy>>,
    session_activity: Option<crate::history::SessionActivity>,
    egress_policy: Option<adk_core::egress::EgressPolicy>,
    governance: Option<GovernanceControl>,
    action_ledger: Option<Arc<dyn ActionLedger>>,
    approval_store: Option<Arc<dyn ApprovalStore>>,
    spend_ledger: Option<Arc<dyn SpendLedger>>,
    durable_runs: Option<Arc<dyn adk_core::DurableRunStore>>,
    audit_recorder: Option<Arc<dyn AuditRecorder>>,
    audit_failure_mode: AuditFailureMode,
    identity_source: Option<Arc<dyn adk_core::IdentitySource>>,
    subject_delegation: Option<Arc<dyn adk_core::SubjectDelegationPolicy>>,
    _marker: PhantomData<(A, G, S)>,
}

impl RunnerConfigBuilder<NoAppName, NoAgent, NoSessionService> {
    /// Create a new builder with all fields unset and defaults applied.
    pub fn new() -> Self {
        Self {
            app_name: None,
            agent: None,
            session_service: None,
            #[cfg(feature = "artifacts")]
            artifact_service: None,
            memory_service: None,
            #[cfg(feature = "plugins")]
            plugin_manager: None,
            run_config: None,
            compaction_config: None,
            context_cache_config: None,
            cache_capable: None,
            request_context: None,
            cancellation_token: None,
            intra_compaction_config: None,
            intra_compaction_summarizer: None,
            #[cfg(feature = "context-compaction")]
            context_compaction: None,
            budget: None,
            tool_policy: None,
            session_activity: None,
            egress_policy: None,
            governance: None,
            action_ledger: None,
            approval_store: None,
            spend_ledger: None,
            durable_runs: None,
            audit_recorder: None,
            audit_failure_mode: AuditFailureMode::Block,
            identity_source: None,
            subject_delegation: None,
            _marker: PhantomData,
        }
    }
}

impl Default for RunnerConfigBuilder<NoAppName, NoAgent, NoSessionService> {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Required-field setters (transition type state)
// ---------------------------------------------------------------------------

impl<A, G, S> RunnerConfigBuilder<A, G, S> {
    /// Set the application name (required).
    pub fn app_name(self, name: impl Into<String>) -> RunnerConfigBuilder<HasAppName, G, S> {
        RunnerConfigBuilder {
            app_name: Some(name.into()),
            agent: self.agent,
            session_service: self.session_service,
            #[cfg(feature = "artifacts")]
            artifact_service: self.artifact_service,
            memory_service: self.memory_service,
            #[cfg(feature = "plugins")]
            plugin_manager: self.plugin_manager,
            run_config: self.run_config,
            compaction_config: self.compaction_config,
            context_cache_config: self.context_cache_config,
            cache_capable: self.cache_capable,
            request_context: self.request_context,
            cancellation_token: self.cancellation_token,
            intra_compaction_config: self.intra_compaction_config,
            intra_compaction_summarizer: self.intra_compaction_summarizer,
            #[cfg(feature = "context-compaction")]
            context_compaction: self.context_compaction,
            budget: self.budget,
            tool_policy: self.tool_policy,
            session_activity: self.session_activity,
            egress_policy: self.egress_policy,
            governance: self.governance,
            action_ledger: self.action_ledger,
            approval_store: self.approval_store,
            spend_ledger: self.spend_ledger,
            durable_runs: self.durable_runs,
            audit_recorder: self.audit_recorder,
            audit_failure_mode: self.audit_failure_mode,
            identity_source: self.identity_source,
            subject_delegation: self.subject_delegation,
            _marker: PhantomData,
        }
    }

    /// Set the root agent (required).
    pub fn agent(self, agent: Arc<dyn Agent>) -> RunnerConfigBuilder<A, HasAgent, S> {
        RunnerConfigBuilder {
            app_name: self.app_name,
            agent: Some(agent),
            session_service: self.session_service,
            #[cfg(feature = "artifacts")]
            artifact_service: self.artifact_service,
            memory_service: self.memory_service,
            #[cfg(feature = "plugins")]
            plugin_manager: self.plugin_manager,
            run_config: self.run_config,
            compaction_config: self.compaction_config,
            context_cache_config: self.context_cache_config,
            cache_capable: self.cache_capable,
            request_context: self.request_context,
            cancellation_token: self.cancellation_token,
            intra_compaction_config: self.intra_compaction_config,
            intra_compaction_summarizer: self.intra_compaction_summarizer,
            #[cfg(feature = "context-compaction")]
            context_compaction: self.context_compaction,
            budget: self.budget,
            tool_policy: self.tool_policy,
            session_activity: self.session_activity,
            egress_policy: self.egress_policy,
            governance: self.governance,
            action_ledger: self.action_ledger,
            approval_store: self.approval_store,
            spend_ledger: self.spend_ledger,
            durable_runs: self.durable_runs,
            audit_recorder: self.audit_recorder,
            audit_failure_mode: self.audit_failure_mode,
            identity_source: self.identity_source,
            subject_delegation: self.subject_delegation,
            _marker: PhantomData,
        }
    }

    /// Set the session service (required).
    pub fn session_service(
        self,
        service: Arc<dyn SessionService>,
    ) -> RunnerConfigBuilder<A, G, HasSessionService> {
        RunnerConfigBuilder {
            app_name: self.app_name,
            agent: self.agent,
            session_service: Some(service),
            #[cfg(feature = "artifacts")]
            artifact_service: self.artifact_service,
            memory_service: self.memory_service,
            #[cfg(feature = "plugins")]
            plugin_manager: self.plugin_manager,
            run_config: self.run_config,
            compaction_config: self.compaction_config,
            context_cache_config: self.context_cache_config,
            cache_capable: self.cache_capable,
            request_context: self.request_context,
            cancellation_token: self.cancellation_token,
            intra_compaction_config: self.intra_compaction_config,
            intra_compaction_summarizer: self.intra_compaction_summarizer,
            #[cfg(feature = "context-compaction")]
            context_compaction: self.context_compaction,
            budget: self.budget,
            tool_policy: self.tool_policy,
            session_activity: self.session_activity,
            egress_policy: self.egress_policy,
            governance: self.governance,
            action_ledger: self.action_ledger,
            approval_store: self.approval_store,
            spend_ledger: self.spend_ledger,
            durable_runs: self.durable_runs,
            audit_recorder: self.audit_recorder,
            audit_failure_mode: self.audit_failure_mode,
            identity_source: self.identity_source,
            subject_delegation: self.subject_delegation,
            _marker: PhantomData,
        }
    }
}

// ---------------------------------------------------------------------------
// Optional-field setters (no type-state change)
// ---------------------------------------------------------------------------

impl<A, G, S> RunnerConfigBuilder<A, G, S> {
    /// Set the artifact service (optional).
    #[cfg(feature = "artifacts")]
    pub fn artifact_service(mut self, service: Arc<dyn ArtifactService>) -> Self {
        self.artifact_service = Some(service);
        self
    }

    /// Set the memory service (optional).
    pub fn memory_service(mut self, service: Arc<dyn Memory>) -> Self {
        self.memory_service = Some(service);
        self
    }

    /// Set the plugin manager (optional).
    #[cfg(feature = "plugins")]
    pub fn plugin_manager(mut self, manager: Arc<PluginManager>) -> Self {
        self.plugin_manager = Some(manager);
        self
    }

    /// Set the run configuration (optional).
    pub fn run_config(mut self, config: RunConfig) -> Self {
        self.run_config = Some(config);
        self
    }

    /// Set the resource limits for every run (optional).
    ///
    /// Each run gets fresh counters for these limits, checked before every model
    /// call and tool dispatch. A run that reaches a limit ends with an event
    /// explaining why and a `ResourceExhausted` error. Overrides any budget in
    /// [`run_config`](Self::run_config). See [`adk_core::budget`].
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_core::RunBudget;
    ///
    /// let runner = Runner::builder()
    ///     .app_name("my-app")
    ///     .agent(agent)
    ///     .session_service(session_service)
    ///     .budget(RunBudget::new().max_cost_usd(50.0).max_model_calls(200))
    ///     .build()?;
    /// ```
    pub fn budget(mut self, budget: RunBudget) -> Self {
        self.budget = Some(budget);
        self
    }

    /// Set the events compaction configuration (optional).
    pub fn compaction_config(mut self, config: adk_core::EventsCompactionConfig) -> Self {
        self.compaction_config = Some(config);
        self
    }

    /// Set the context cache configuration (optional).
    pub fn context_cache_config(mut self, config: ContextCacheConfig) -> Self {
        self.context_cache_config = Some(config);
        self
    }

    /// Set the cache-capable model reference (optional).
    pub fn cache_capable(mut self, model: Arc<dyn CacheCapable>) -> Self {
        self.cache_capable = Some(model);
        self
    }

    /// Set the request context from auth middleware (optional).
    pub fn request_context(mut self, ctx: adk_core::RequestContext) -> Self {
        self.request_context = Some(ctx);
        self
    }

    /// Set a cooperative cancellation token (optional).
    ///
    /// Each run derives a child of this token, so cancelling it stops every in-flight
    /// run, while [`Runner::interrupt`] cancels only the targeted run.
    pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
        self.cancellation_token = Some(token);
        self
    }

    /// Sets when agents compact their history before a model call (auto-compaction).
    ///
    /// Auto-compaction is on without this call: a request is compacted once it passes 80%
    /// of the model's context window, or 100,000 estimated tokens when the model reports none.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_core::IntraCompactionConfig;
    ///
    /// // Compact past 60% of the window, keeping the 6 most recent entries.
    /// let builder = Runner::builder()
    ///     .intra_compaction_config(IntraCompactionConfig::at_window_fraction(0.6).with_overlap_event_count(6));
    /// ```
    pub fn intra_compaction_config(mut self, config: adk_core::IntraCompactionConfig) -> Self {
        self.intra_compaction_config = Some(config);
        self
    }

    /// Turns auto-compaction off: agents send their history as it is until the model rejects
    /// it.
    pub fn without_intra_compaction(mut self) -> Self {
        self.intra_compaction_config = Some(adk_core::IntraCompactionConfig::disabled());
        self
    }

    /// Sets the summarizer auto-compaction uses, in place of a summary by the model the agent
    /// is calling.
    pub fn intra_compaction_summarizer(
        mut self,
        summarizer: Arc<dyn adk_core::BaseEventsSummarizer>,
    ) -> Self {
        self.intra_compaction_summarizer = Some(summarizer);
        self
    }

    /// Set the policy evaluated for every tool call (optional).
    ///
    /// The runner installs it on each run's [`RunConfig::tool_policy`] when the run
    /// does not carry one, so it governs transfer targets and agents behind an agent
    /// tool as well. A [`DeclarativePolicy`](adk_core::DeclarativePolicy) denies every
    /// tool no rule permits.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_core::DeclarativePolicy;
    ///
    /// let runner = Runner::builder()
    ///     .app_name("ops")
    ///     .agent(agent)
    ///     .session_service(sessions)
    ///     .tool_policy(Arc::new(DeclarativePolicy::builder().allow_read_only().build()))
    ///     .build()?;
    /// ```
    pub fn tool_policy(mut self, policy: Arc<dyn ToolPolicy>) -> Self {
        self.tool_policy = Some(policy);
        self
    }

    /// Record this runner's runs in `activity`, shared with the other runners and the
    /// [`HistoryControl`](crate::HistoryControl) a host builds (optional).
    ///
    /// Without one, the runner keeps a registry of its own.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let activity = adk_runner::SessionActivity::new();
    /// let runner = Runner::builder()
    ///     .app_name("ops")
    ///     .agent(agent)
    ///     .session_service(sessions)
    ///     .session_activity(activity.clone())
    ///     .build()?;
    /// ```
    pub fn session_activity(mut self, activity: crate::history::SessionActivity) -> Self {
        self.session_activity = Some(activity);
        self
    }

    /// Set the operator's network egress ceiling for tool calls (optional).
    ///
    /// Every run is narrowed by it: a run whose [`RunConfig::egress_policy`] is set gets the
    /// intersection of both, never more. A tool whose
    /// [`Tool::egress`](adk_core::Tool::egress) declaration the ceiling does not admit is
    /// refused before it runs. Calling it twice narrows to the intersection. See
    /// [`adk_core::egress`].
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_core::egress::EgressPolicy;
    ///
    /// let runner = Runner::builder()
    ///     .app_name("ops")
    ///     .agent(agent)
    ///     .session_service(sessions)
    ///     .egress_policy(EgressPolicy::allowlist(["api.github.com:443"])?)
    ///     .build()?;
    /// ```
    pub fn egress_policy(mut self, policy: adk_core::egress::EgressPolicy) -> Self {
        self.egress_policy = Some(match self.egress_policy.take() {
            Some(existing) => existing.narrow(&policy),
            None => policy,
        });
        self
    }

    /// Share a kill switch with this runner (optional).
    ///
    /// Without one the runner creates its own, reachable through
    /// [`Runner::governance`]. Freezing it fails new runs at their start and stops
    /// running ones before their next model or tool call.
    pub fn governance(mut self, control: GovernanceControl) -> Self {
        self.governance = Some(control);
        self
    }

    /// Set the ledger that records non-idempotent tool calls (optional).
    ///
    /// The runner installs it on each run's [`RunConfig::action_ledger`] when the run
    /// does not carry one. Every backend implements the same
    /// [`ActionLedger`] trait, so switching from SQLite to PostgreSQL, Redis, or
    /// MongoDB changes only the value passed here.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_session::PostgresActionLedger;
    ///
    /// let ledger = PostgresActionLedger::from_pool(pool.clone());
    /// ledger.migrate().await?;
    /// let runner = Runner::builder()
    ///     .app_name("payments")
    ///     .agent(agent)
    ///     .session_service(sessions)
    ///     .action_ledger(Arc::new(ledger))
    ///     .build()?;
    /// ```
    pub fn action_ledger(mut self, ledger: Arc<dyn ActionLedger>) -> Self {
        self.action_ledger = Some(ledger);
        self
    }

    /// Set where calls held for approval and their decisions are kept (optional).
    ///
    /// The runner installs it on each run's [`RunConfig::approval_store`] when the run
    /// does not carry one.
    pub fn approval_store(mut self, store: Arc<dyn ApprovalStore>) -> Self {
        self.approval_store = Some(store);
        self
    }

    /// Set the ledger that model calls and payment tools reserve budget against
    /// (optional).
    ///
    /// The runner installs it on each run's [`RunConfig::spend_ledger`] when the run
    /// does not carry one.
    pub fn spend_ledger(mut self, ledger: Arc<dyn SpendLedger>) -> Self {
        self.spend_ledger = Some(ledger);
        self
    }

    /// Set the durable run queue shared by every replica (optional).
    ///
    /// [`Runner::interrupt`](crate::Runner::interrupt) then also requests cancellation of
    /// the session's unfinished durable runs, wherever their worker runs.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let runner = Runner::builder()
    ///     .app_name("ops")
    ///     .agent(agent)
    ///     .session_service(sessions)
    ///     .durable_run_store(Arc::new(adk_core::InMemoryRunStore::new()))
    ///     .build()?;
    /// ```
    pub fn durable_run_store(mut self, store: Arc<dyn adk_core::DurableRunStore>) -> Self {
        self.durable_runs = Some(store);
        self
    }

    /// Record the runner's governed actions in `recorder` (optional).
    ///
    /// Every run records each tool decision (allowed, denied, held for approval), each
    /// approval decision, each payment made through the payment tools, and each call
    /// answered with an unknown outcome; the runner's kill switch records freezes and
    /// unfreezes. Records name the acting agent and the subject it acts for, and carry
    /// argument digests, never arguments. An action whose record cannot be written does
    /// not happen; see [`audit_failure_mode`](Self::audit_failure_mode).
    ///
    /// The runner installs the trail on each run's [`RunConfig::audit`] when the run does
    /// not carry one.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_auth::signed_audit::{AuditLog, Ed25519Signer};
    ///
    /// let log = AuditLog::builder(store, "replica-1", signer).open().await?;
    /// let runner = Runner::builder()
    ///     .app_name("ops")
    ///     .agent(agent)
    ///     .session_service(sessions)
    ///     .audit_log(Arc::new(log))
    ///     .build()?;
    /// ```
    pub fn audit_log(mut self, recorder: Arc<dyn AuditRecorder>) -> Self {
        self.audit_recorder = Some(recorder);
        self
    }

    /// Set what happens when the [`audit_log`](Self::audit_log) cannot record an action
    /// (optional). The default, [`AuditFailureMode::Block`], refuses the action.
    pub fn audit_failure_mode(mut self, mode: AuditFailureMode) -> Self {
        self.audit_failure_mode = mode;
        self
    }

    /// Sets where each run's agent principals come from.
    ///
    /// The runner reads the source at the start of every run: the root agent acts as
    /// [`principal_for`](adk_core::IdentitySource::principal_for) its name, falling back
    /// to [`current`](adk_core::IdentitySource::current), and every other agent in the
    /// tree acts as `principal_for` its name, falling back to
    /// `urn:adk:agent:{app_name}/{agent_name}`. A principal the run's
    /// [`RunConfig::acting`] names for an agent takes precedence. A run whose source fails
    /// ends with the source's error before any agent runs.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_core::{AgentId, AgentPrincipal, StaticIdentitySource};
    ///
    /// let source = StaticIdentitySource::new(
    ///     AgentPrincipal::new(AgentId::new("spiffe://acme.example/agent/billing")?)
    ///         .with_instance(std::env::var("HOSTNAME")?),
    /// );
    /// let runner = Runner::builder()
    ///     .app_name("billing")
    ///     .agent(agent)
    ///     .session_service(sessions)
    ///     .identity_source(Arc::new(source))
    ///     .build()?;
    /// ```
    pub fn identity_source(mut self, source: Arc<dyn adk_core::IdentitySource>) -> Self {
        self.identity_source = Some(source);
        self
    }

    /// Sets a fixed principal the root agent acts as.
    ///
    /// Shorthand for [`identity_source`](Self::identity_source) with a
    /// [`StaticIdentitySource`](adk_core::StaticIdentitySource); sub-agents act as their
    /// derived ids.
    pub fn agent_principal(self, principal: adk_core::AgentPrincipal) -> Self {
        self.identity_source(Arc::new(adk_core::StaticIdentitySource::new(principal)))
    }

    /// Sets which runs may act for a subject other than their session's user.
    ///
    /// Without a policy, a run whose [`RunConfig::acting`] asks to act for anyone but the
    /// session's user is refused with `identity.subject_mismatch` before any agent runs.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_core::{StaticSubjectDelegation, SubjectRef};
    ///
    /// let runner = Runner::builder()
    ///     .app_name("crm")
    ///     .agent(agent)
    ///     .session_service(sessions)
    ///     .subject_delegation(Arc::new(
    ///         StaticSubjectDelegation::new().allow_any(SubjectRef::service("crm-sync")),
    ///     ))
    ///     .build()?;
    /// ```
    pub fn subject_delegation(
        mut self,
        policy: Arc<dyn adk_core::SubjectDelegationPolicy>,
    ) -> Self {
        self.subject_delegation = Some(policy);
        self
    }

    /// Sets a compaction strategy auto-compaction applies in place of a summary.
    ///
    /// Before any model call whose request passes `config.context_budget` estimated tokens,
    /// the agent's history is shortened with the given
    /// [`CompactionStrategy`](crate::compaction::CompactionStrategy), up to
    /// `config.max_retries` times.
    #[cfg(feature = "context-compaction")]
    pub fn context_compaction(mut self, config: crate::compaction::CompactionConfig) -> Self {
        self.context_compaction = Some(config);
        self
    }
}

// ---------------------------------------------------------------------------
// build() — only available when all required fields are set
// ---------------------------------------------------------------------------

impl RunnerConfigBuilder<HasAppName, HasAgent, HasSessionService> {
    /// Consume the builder and produce a [`RunnerConfig`] without creating a [`Runner`].
    ///
    /// Use this when you need the raw config (e.g. to wrap in `Arc` for A2A handlers).
    pub fn build_config(self) -> RunnerConfig {
        let run_config = merge_budget(self.run_config, self.budget);
        RunnerConfig {
            app_name: self.app_name.expect("typestate guarantees app_name is set"),
            agent: self.agent.expect("typestate guarantees agent is set"),
            session_service: self
                .session_service
                .expect("typestate guarantees session_service is set"),
            #[cfg(feature = "artifacts")]
            artifact_service: self.artifact_service,
            memory_service: self.memory_service,
            #[cfg(feature = "plugins")]
            plugin_manager: self.plugin_manager,
            run_config,
            compaction_config: self.compaction_config,
            context_cache_config: self.context_cache_config,
            cache_capable: self.cache_capable,
            request_context: self.request_context,
            cancellation_token: self.cancellation_token,
            intra_compaction_config: self.intra_compaction_config,
            intra_compaction_summarizer: self.intra_compaction_summarizer,
            #[cfg(feature = "context-compaction")]
            context_compaction: self.context_compaction,
            tool_policy: self.tool_policy,
            egress_policy: self.egress_policy,
            governance: self.governance,
            action_ledger: self.action_ledger,
            approval_store: self.approval_store,
            spend_ledger: self.spend_ledger,
            durable_runs: self.durable_runs,
            audit: self.audit_recorder.map(|recorder| {
                AuditTrail::new(recorder).with_failure_mode(self.audit_failure_mode)
            }),
            identity_source: self.identity_source,
            subject_delegation: self.subject_delegation,
        }
    }

    /// Consume the builder and create a [`Runner`].
    ///
    /// Delegates to [`Runner::new()`] internally.
    ///
    /// # Errors
    ///
    /// Returns an error if `Runner::new()` fails (e.g. invalid `app_name`).
    pub fn build(self) -> Result<Runner> {
        let run_config = merge_budget(self.run_config, self.budget);
        let config = RunnerConfig {
            // SAFETY: typestate guarantees these are `Some`.
            app_name: self.app_name.expect("typestate guarantees app_name is set"),
            agent: self.agent.expect("typestate guarantees agent is set"),
            session_service: self
                .session_service
                .expect("typestate guarantees session_service is set"),
            #[cfg(feature = "artifacts")]
            artifact_service: self.artifact_service,
            memory_service: self.memory_service,
            #[cfg(feature = "plugins")]
            plugin_manager: self.plugin_manager,
            run_config,
            compaction_config: self.compaction_config,
            context_cache_config: self.context_cache_config,
            cache_capable: self.cache_capable,
            request_context: self.request_context,
            cancellation_token: self.cancellation_token,
            intra_compaction_config: self.intra_compaction_config,
            intra_compaction_summarizer: self.intra_compaction_summarizer,
            #[cfg(feature = "context-compaction")]
            context_compaction: self.context_compaction,
            tool_policy: self.tool_policy,
            egress_policy: self.egress_policy,
            governance: self.governance,
            action_ledger: self.action_ledger,
            approval_store: self.approval_store,
            spend_ledger: self.spend_ledger,
            durable_runs: self.durable_runs,
            audit: self.audit_recorder.map(|recorder| {
                AuditTrail::new(recorder).with_failure_mode(self.audit_failure_mode)
            }),
            identity_source: self.identity_source,
            subject_delegation: self.subject_delegation,
        };
        let runner = Runner::new(config)?;
        Ok(match self.session_activity {
            Some(activity) => runner.with_session_activity(activity),
            None => runner,
        })
    }
}

/// Applies a builder-level budget on top of the configured run config.
fn merge_budget(run_config: Option<RunConfig>, budget: Option<RunBudget>) -> Option<RunConfig> {
    match budget {
        Some(budget) => {
            let mut config = run_config.unwrap_or_default();
            config.budget = Some(budget);
            Some(config)
        }
        None => run_config,
    }
}