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
//! Serializable agent configuration.
//!
//! [`AgentConfig`] captures the subset of [`AgentOptions`](crate::AgentOptions)
//! that can be round-tripped through serde. Trait objects (tools, transformers,
//! policies, callbacks) are represented by name so they can be re-registered
//! after deserialization.
use std::time::Duration;
use serde::{Deserialize, Serialize};
use crate::stream::StreamTransport;
use crate::tool::ApprovalMode;
use crate::types::ModelSpec;
// ─── RetryConfig ─────────────────────────────────────────────────────────────
/// Serializable representation of [`DefaultRetryStrategy`](crate::DefaultRetryStrategy) parameters.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryConfig {
/// Maximum number of attempts (including the initial call).
pub max_attempts: u32,
/// Base delay in milliseconds before the first retry.
pub base_delay_ms: u64,
/// Maximum delay cap in milliseconds.
pub max_delay_ms: u64,
/// Exponential multiplier per attempt.
pub multiplier: f64,
/// Whether jitter is applied to delays.
pub jitter: bool,
}
impl Default for RetryConfig {
fn default() -> Self {
let default = crate::retry::DefaultRetryStrategy::default();
Self {
max_attempts: default.max_attempts,
base_delay_ms: default
.base_delay
.as_millis()
.try_into()
.unwrap_or(u64::MAX),
max_delay_ms: default.max_delay.as_millis().try_into().unwrap_or(u64::MAX),
multiplier: default.multiplier,
jitter: default.jitter,
}
}
}
impl From<&crate::retry::DefaultRetryStrategy> for RetryConfig {
fn from(s: &crate::retry::DefaultRetryStrategy) -> Self {
Self {
max_attempts: s.max_attempts,
base_delay_ms: s.base_delay.as_millis().try_into().unwrap_or(u64::MAX),
max_delay_ms: s.max_delay.as_millis().try_into().unwrap_or(u64::MAX),
multiplier: s.multiplier,
jitter: s.jitter,
}
}
}
impl RetryConfig {
/// Convert back to a [`DefaultRetryStrategy`](crate::DefaultRetryStrategy).
#[must_use]
pub const fn to_retry_strategy(&self) -> crate::retry::DefaultRetryStrategy {
crate::retry::DefaultRetryStrategy {
max_attempts: self.max_attempts,
base_delay: Duration::from_millis(self.base_delay_ms),
max_delay: Duration::from_millis(self.max_delay_ms),
multiplier: self.multiplier,
jitter: self.jitter,
}
}
/// Set the maximum number of attempts (including the initial call).
#[must_use]
pub const fn with_max_attempts(mut self, n: u32) -> Self {
self.max_attempts = n;
self
}
/// Set the base delay in milliseconds before the first retry.
#[must_use]
pub const fn with_base_delay_ms(mut self, ms: u64) -> Self {
self.base_delay_ms = ms;
self
}
/// Set the maximum delay cap in milliseconds.
#[must_use]
pub const fn with_max_delay_ms(mut self, ms: u64) -> Self {
self.max_delay_ms = ms;
self
}
/// Set the exponential multiplier per attempt.
#[must_use]
pub const fn with_multiplier(mut self, m: f64) -> Self {
self.multiplier = m;
self
}
/// Enable or disable jitter.
#[must_use]
pub const fn with_jitter(mut self, j: bool) -> Self {
self.jitter = j;
self
}
}
// ─── StreamOptionsConfig ─────────────────────────────────────────────────────
/// Serializable representation of [`StreamOptions`](crate::StreamOptions).
///
/// The `api_key` field is intentionally omitted — secrets should not be
/// persisted in config snapshots.
#[non_exhaustive]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct StreamOptionsConfig {
/// Sampling temperature.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub temperature: Option<f64>,
/// Output token limit.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_tokens: Option<u64>,
/// Provider-side session identifier.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
/// Preferred transport protocol.
#[serde(default)]
pub transport: StreamTransport,
/// Provider-native serving options (local backends).
#[serde(
default,
skip_serializing_if = "crate::stream::ServingOptions::is_default"
)]
pub serving: crate::stream::ServingOptions,
}
impl From<&crate::stream::StreamOptions> for StreamOptionsConfig {
fn from(opts: &crate::stream::StreamOptions) -> Self {
Self {
temperature: opts.temperature,
max_tokens: opts.max_tokens,
session_id: opts.session_id.clone(),
transport: opts.transport,
serving: opts.serving.clone(),
}
}
}
impl StreamOptionsConfig {
/// Convert back to [`StreamOptions`](crate::StreamOptions), leaving `api_key` as `None`.
#[must_use]
pub fn to_stream_options(&self) -> crate::stream::StreamOptions {
crate::stream::StreamOptions {
temperature: self.temperature,
max_tokens: self.max_tokens,
session_id: self.session_id.clone(),
api_key: None,
transport: self.transport,
cache_strategy: crate::stream::CacheStrategy::default(),
on_raw_payload: None,
on_rate_limit: None,
serving: self.serving.clone(),
}
}
/// Set the sampling temperature.
#[must_use]
pub const fn with_temperature(mut self, temperature: f64) -> Self {
self.temperature = Some(temperature);
self
}
/// Set the output token limit.
#[must_use]
pub const fn with_max_tokens(mut self, max_tokens: u64) -> Self {
self.max_tokens = Some(max_tokens);
self
}
/// Set the provider-side session identifier.
#[must_use]
pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
self.session_id = Some(session_id.into());
self
}
/// Set the preferred transport protocol.
#[must_use]
pub const fn with_transport(mut self, transport: StreamTransport) -> Self {
self.transport = transport;
self
}
/// Set the provider-native serving options (local backends).
#[must_use]
pub fn with_serving(mut self, serving: crate::stream::ServingOptions) -> Self {
self.serving = serving;
self
}
}
// ─── SteeringMode / FollowUpMode serde wrappers ─────────────────────────────
/// Serializable mirror of [`SteeringMode`](crate::SteeringMode).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SteeringModeConfig {
All,
#[default]
OneAtATime,
}
impl From<crate::agent::SteeringMode> for SteeringModeConfig {
fn from(m: crate::agent::SteeringMode) -> Self {
match m {
crate::agent::SteeringMode::All => Self::All,
crate::agent::SteeringMode::OneAtATime => Self::OneAtATime,
}
}
}
impl From<SteeringModeConfig> for crate::agent::SteeringMode {
fn from(m: SteeringModeConfig) -> Self {
match m {
SteeringModeConfig::All => Self::All,
SteeringModeConfig::OneAtATime => Self::OneAtATime,
}
}
}
/// Serializable mirror of [`FollowUpMode`](crate::FollowUpMode).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FollowUpModeConfig {
All,
#[default]
OneAtATime,
}
impl From<crate::agent::FollowUpMode> for FollowUpModeConfig {
fn from(m: crate::agent::FollowUpMode) -> Self {
match m {
crate::agent::FollowUpMode::All => Self::All,
crate::agent::FollowUpMode::OneAtATime => Self::OneAtATime,
}
}
}
impl From<FollowUpModeConfig> for crate::agent::FollowUpMode {
fn from(m: FollowUpModeConfig) -> Self {
match m {
FollowUpModeConfig::All => Self::All,
FollowUpModeConfig::OneAtATime => Self::OneAtATime,
}
}
}
/// Serializable mirror of [`ApprovalMode`](crate::ApprovalMode).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalModeConfig {
#[default]
Enabled,
Smart,
Bypassed,
}
// ─── CacheConfigData ────────────────────────────────────────────────────────
/// Serializable representation of [`CacheConfig`](crate::context_cache::CacheConfig).
///
/// Duration is stored as milliseconds for serde-friendliness.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfigData {
/// Time-to-live in milliseconds.
pub ttl_ms: u64,
/// Minimum token count for the cached prefix.
pub min_tokens: usize,
/// Number of turns between cache refreshes.
pub cache_intervals: usize,
}
impl From<&crate::context_cache::CacheConfig> for CacheConfigData {
fn from(c: &crate::context_cache::CacheConfig) -> Self {
Self {
ttl_ms: c.ttl.as_millis().try_into().unwrap_or(u64::MAX),
min_tokens: c.min_tokens,
cache_intervals: c.cache_intervals,
}
}
}
impl CacheConfigData {
/// Create a new cache config snapshot.
#[must_use]
pub const fn new(ttl_ms: u64, min_tokens: usize, cache_intervals: usize) -> Self {
Self {
ttl_ms,
min_tokens,
cache_intervals,
}
}
/// Convert back to a [`CacheConfig`](crate::context_cache::CacheConfig).
#[must_use]
pub const fn to_cache_config(&self) -> crate::context_cache::CacheConfig {
crate::context_cache::CacheConfig::new(
std::time::Duration::from_millis(self.ttl_ms),
self.min_tokens,
self.cache_intervals,
)
}
}
impl From<ApprovalMode> for ApprovalModeConfig {
fn from(m: ApprovalMode) -> Self {
match m {
ApprovalMode::Enabled => Self::Enabled,
ApprovalMode::Smart => Self::Smart,
ApprovalMode::Bypassed => Self::Bypassed,
}
}
}
impl From<ApprovalModeConfig> for ApprovalMode {
fn from(m: ApprovalModeConfig) -> Self {
match m {
ApprovalModeConfig::Enabled => Self::Enabled,
ApprovalModeConfig::Smart => Self::Smart,
ApprovalModeConfig::Bypassed => Self::Bypassed,
}
}
}
// ─── AgentConfig ─────────────────────────────────────────────────────────────
/// A fully serializable snapshot of agent configuration.
///
/// Captures the subset of [`AgentOptions`](crate::AgentOptions) fields that can
/// survive a serde round-trip. Trait objects (tools, stream functions,
/// transformers, policies, callbacks) **cannot** be serialized and must be
/// re-registered by the consumer after deserialization.
///
/// # What round-trips faithfully
///
/// `system_prompt`, `model`, `retry`, `stream_options`, `steering_mode`,
/// `follow_up_mode`, `structured_output_max_retries`, `approval_mode`,
/// `plan_mode_addendum`, and `cache_config` are all restored by
/// [`into_agent_options()`](Self::into_agent_options).
///
/// # What does NOT round-trip
///
/// - **`tool_names`** — stored for informational use only (e.g., re-registering
/// tools by name). The consumer must supply the actual tool implementations.
/// - **`extra`** — application-level metadata that has no corresponding
/// `AgentOptions` field. Survives serde but is not fed back into the agent.
/// - **Trait objects** — `stream_fn`, `convert_to_llm`, `transform_context`,
/// `approve_tool`, policies, event forwarders, etc. must be re-attached.
///
/// # Example
///
/// ```ignore
/// // Save
/// let config = agent.options().to_config();
/// let json = serde_json::to_string(&config)?;
///
/// // Restore
/// let config: AgentConfig = serde_json::from_str(&json)?;
/// let opts = AgentOptions::from_config(config, stream_fn, convert_to_llm)
/// .with_tools(re_register_tools(&config.tool_names));
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
/// System prompt sent to the LLM.
pub system_prompt: String,
/// Model specification (provider, model ID, thinking level, etc.).
pub model: ModelSpec,
/// Names of registered tools (routing keys from [`AgentTool::name()`](crate::AgentTool::name)).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tool_names: Vec<String>,
/// Retry strategy parameters.
#[serde(default)]
pub retry: RetryConfig,
/// Per-call stream options (temperature, max tokens, transport).
#[serde(default)]
pub stream_options: StreamOptionsConfig,
/// Steering queue drain mode.
#[serde(default)]
pub steering_mode: SteeringModeConfig,
/// Follow-up queue drain mode.
#[serde(default)]
pub follow_up_mode: FollowUpModeConfig,
/// Max retries for structured output validation.
#[serde(default = "default_structured_output_max_retries")]
pub structured_output_max_retries: usize,
/// Approval mode for the tool gate.
#[serde(default)]
pub approval_mode: ApprovalModeConfig,
/// Optional plan mode addendum appended to the system prompt.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub plan_mode_addendum: Option<String>,
/// Optional context caching configuration.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_config: Option<CacheConfigData>,
/// Arbitrary extension data for application-specific config.
///
/// This field survives serialization but is **not** restored into
/// [`AgentOptions`](crate::AgentOptions) — it has no corresponding field
/// there. Use it to store application-level metadata alongside the config.
#[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
pub extra: serde_json::Value,
}
const fn default_structured_output_max_retries() -> usize {
3
}
impl AgentConfig {
/// Create a new config with the required fields; everything else takes
/// its default value (matching the serde defaults used on deserialize).
#[must_use]
pub fn new(system_prompt: impl Into<String>, model: ModelSpec) -> Self {
Self {
system_prompt: system_prompt.into(),
model,
tool_names: Vec::new(),
retry: RetryConfig::default(),
stream_options: StreamOptionsConfig::default(),
steering_mode: SteeringModeConfig::default(),
follow_up_mode: FollowUpModeConfig::default(),
structured_output_max_retries: default_structured_output_max_retries(),
approval_mode: ApprovalModeConfig::default(),
plan_mode_addendum: None,
cache_config: None,
extra: serde_json::Value::Null,
}
}
/// Set the routing-key names of tools to re-register on restore.
#[must_use]
pub fn with_tool_names(mut self, tool_names: Vec<String>) -> Self {
self.tool_names = tool_names;
self
}
/// Set the retry strategy parameters.
#[must_use]
pub fn with_retry(mut self, retry: RetryConfig) -> Self {
self.retry = retry;
self
}
/// Set the per-call stream options.
#[must_use]
pub fn with_stream_options(mut self, stream_options: StreamOptionsConfig) -> Self {
self.stream_options = stream_options;
self
}
/// Set the steering queue drain mode.
#[must_use]
pub const fn with_steering_mode(mut self, steering_mode: SteeringModeConfig) -> Self {
self.steering_mode = steering_mode;
self
}
/// Set the follow-up queue drain mode.
#[must_use]
pub const fn with_follow_up_mode(mut self, follow_up_mode: FollowUpModeConfig) -> Self {
self.follow_up_mode = follow_up_mode;
self
}
/// Set the max retries for structured output validation.
#[must_use]
pub const fn with_structured_output_max_retries(mut self, max_retries: usize) -> Self {
self.structured_output_max_retries = max_retries;
self
}
/// Set the approval mode for the tool gate.
#[must_use]
pub const fn with_approval_mode(mut self, approval_mode: ApprovalModeConfig) -> Self {
self.approval_mode = approval_mode;
self
}
/// Set the plan mode addendum appended to the system prompt.
#[must_use]
pub fn with_plan_mode_addendum(mut self, addendum: impl Into<String>) -> Self {
self.plan_mode_addendum = Some(addendum.into());
self
}
/// Set the context caching configuration.
#[must_use]
pub fn with_cache_config(mut self, cache_config: CacheConfigData) -> Self {
self.cache_config = Some(cache_config);
self
}
/// Set the arbitrary application-specific extension data.
#[must_use]
pub fn with_extra(mut self, extra: serde_json::Value) -> Self {
self.extra = extra;
self
}
/// Restore an [`AgentOptions`](crate::AgentOptions) builder from this config.
///
/// The caller must supply the required non-serializable arguments
/// (`stream_fn` and `convert_to_llm`) and then re-attach any trait objects
/// (tools, transformers, policies) via the builder methods.
#[must_use]
pub fn into_agent_options(
self,
stream_fn: std::sync::Arc<dyn crate::stream::StreamFn>,
convert_to_llm: impl Fn(&crate::types::AgentMessage) -> Option<crate::types::LlmMessage>
+ Send
+ Sync
+ 'static,
) -> crate::agent::AgentOptions {
let mut opts = crate::agent::AgentOptions::new(
self.system_prompt,
self.model,
stream_fn,
convert_to_llm,
);
opts.retry_strategy = Box::new(self.retry.to_retry_strategy());
opts.stream_options = self.stream_options.to_stream_options();
opts.steering_mode = self.steering_mode.into();
opts.follow_up_mode = self.follow_up_mode.into();
opts.structured_output_max_retries = self.structured_output_max_retries;
opts.approval_mode = self.approval_mode.into();
opts.plan_mode_addendum = self.plan_mode_addendum;
opts.cache_config = self.cache_config.map(|c| c.to_cache_config());
// Clear the default transform_context — the caller may want to re-attach
// their own, and `from_config` should not silently override.
opts.transform_context = None;
opts
}
}
// ─── AgentOptions::to_config / from_config ───────────────────────────────────
impl crate::agent::AgentOptions {
/// Extract a serializable [`AgentConfig`] from these options.
///
/// Tool implementations are represented by name only. Trait objects
/// (transformers, policies, callbacks) are omitted — their presence must
/// be restored by the consumer after deserialization.
#[must_use]
pub fn to_config(&self) -> AgentConfig {
let tool_names: Vec<String> = self.tools.iter().map(|t| t.name().to_string()).collect();
// Attempt to extract retry params from a DefaultRetryStrategy. If the
// caller used a custom RetryStrategy we fall back to defaults.
let retry = downcast_retry_config(&*self.retry_strategy);
AgentConfig {
system_prompt: self.system_prompt.clone(),
model: self.model.clone(),
tool_names,
retry,
stream_options: StreamOptionsConfig::from(&self.stream_options),
steering_mode: self.steering_mode.into(),
follow_up_mode: self.follow_up_mode.into(),
structured_output_max_retries: self.structured_output_max_retries,
approval_mode: self.approval_mode.into(),
plan_mode_addendum: self.plan_mode_addendum.clone(),
cache_config: self.cache_config.as_ref().map(CacheConfigData::from),
extra: serde_json::Value::Null,
}
}
/// Construct `AgentOptions` from a deserialized [`AgentConfig`].
///
/// Equivalent to [`AgentConfig::into_agent_options`] — provided here for
/// discoverability.
#[must_use]
pub fn from_config(
config: AgentConfig,
stream_fn: std::sync::Arc<dyn crate::stream::StreamFn>,
convert_to_llm: impl Fn(&crate::types::AgentMessage) -> Option<crate::types::LlmMessage>
+ Send
+ Sync
+ 'static,
) -> Self {
config.into_agent_options(stream_fn, convert_to_llm)
}
}
/// Try to downcast the retry strategy to `DefaultRetryStrategy` and extract its
/// parameters. Falls back to `RetryConfig::default()` for custom strategies.
fn downcast_retry_config(strategy: &dyn crate::retry::RetryStrategy) -> RetryConfig {
strategy
.as_any()
.downcast_ref::<crate::retry::DefaultRetryStrategy>()
.map_or_else(RetryConfig::default, RetryConfig::from)
}
// ─── Send + Sync assertions ─────────────────────────────────────────────────
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<AgentConfig>();
assert_send_sync::<RetryConfig>();
assert_send_sync::<StreamOptionsConfig>();
assert_send_sync::<SteeringModeConfig>();
assert_send_sync::<FollowUpModeConfig>();
assert_send_sync::<ApprovalModeConfig>();
};
// ─── Tests ───────────────────────────────────────────────────────────────────
#[cfg(test)]
#[path = "config_tests.rs"]
mod tests;