iron-core 0.1.38

Core AgentIron loop, session state, and tool registry
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
//! Configuration types and durable storage for `iron-core`.
//!
//! This module provides two categories of types:
//!
//! 1. **Runtime configuration** ([`Config`], [`ConfigSource`]) — the main
//!    runtime configuration surface for `IronAgent` and `IronRuntime`.
//!    Applications that keep their own config type can implement [`ConfigSource`]
//!    to project iron-core settings into a validated [`Config`] snapshot at
//!    construction time.
//!
//! 2. **Durable configuration store** ([`ConfigStore`]) — a SQLite-backed
//!    persistent store for profiles, prompts, schedule entries, encrypted
//!    provider credentials, and shared runtime settings. The store is designed
//!    for desktop application use and manages its own schema migrations.
//!
//!    Runtime settings include provider configuration (without credentials),
//!    custom models, default model selection, MCP server definitions, and
//!    skill settings. These are shared between the AgentIron desktop app and
//!    headless/CLI consumers through typed APIs rather than direct SQLite
//!    access. Provider credentials remain in the encrypted credential store
//!    and are not stored in provider runtime configuration.
//!
//! ## Platform-default paths
//!
//! `ConfigStore::open()` resolves the platform-default database path:
//!
//! - **Linux**: `$XDG_CONFIG_HOME/agentiron/config.db` when `XDG_CONFIG_HOME`
//!   is set, otherwise `~/.config/agentiron/config.db`
//! - **macOS**: `~/Library/Application Support/com.agentiron/iron-core/config.db`
//! - **Windows**: `%APPDATA%\AgentIron\config.db`
//!
//! Parent directories are created automatically when opening the store.
//!
//! ## Encryption
//!
//! Provider credentials are encrypted at rest using XChaCha20-Poly1305 with
//! random per-row nonces. The encryption key is resolved from (in order):
//!
//! 1. `AGENTIRON_CONFIG_ENCRYPTION_KEY` environment variable (base64-encoded
//!    32-byte key, useful for headless/cron operation)
//! 2. OS keyring (`agentiron` / `config-encryption`)
//!
//! If no key source is available, credential operations return
//! [`ConfigError::KeyUnavailable`] while non-secret operations (profiles,
//! prompts, schedules) continue to work normally.
//!
//! ## Frontend usage
//!
//! Frontends must use the `iron_core::config` APIs (`ConfigStore`,
//! `ProfileInput`, `PromptInput`, etc.) and must not write the SQLite database
//! directly. The database schema is an implementation detail; compiled-in
//! migrations ensure forward compatibility without external migration files.
//!
//! ## Migration notes
//!
//! Schema migrations are compiled into the binary. No external migration files
//! need to be packaged or deployed.
//!
//! See [AgentIron/AgentIron#56](https://github.com/AgentIron/AgentIron/issues/56)
//! for the follow-up app config audit and migration task.
//!
//! Projection is a snapshot — later mutations to the caller's config do not
//! affect already-constructed runtimes or agents.
//!
//! ## Example
//!
//! ```
//! use iron_core::{ApprovalStrategy, Config, ContextWindowPolicy};
//!
//! let config = Config::new()
//!     .with_model("gpt-4.1")
//!     .with_max_iterations(6)
//!     .with_approval_strategy(ApprovalStrategy::PerTool)
//!     .with_context_window_policy(ContextWindowPolicy::KeepRecent(24));
//!
//! config.validate()?;
//! assert_eq!(config.model, "gpt-4.1");
//! # Ok::<(), iron_core::RuntimeError>(())
//! ```

use crate::error::RuntimeError;
use iron_providers::{GenerationConfig, ToolPolicy};

pub use crate::context::config::ContextManagementConfig;
pub use crate::prompt::config::PromptCompositionConfig;

/// Projection trait for caller-owned config types.
///
/// Implement this trait on your application config type to project
/// iron-core settings into a validated library-owned `Config` snapshot.
/// The projection occurs at construction time; later mutations to the
/// caller's config object do not affect already-constructed sessions.
pub trait ConfigSource {
    /// Project a validated `Config` snapshot from this source.
    fn to_config(&self) -> Result<Config, RuntimeError>;
}

/// Runtime configuration for `iron-core`.
///
/// This snapshot is validated before use and then owned by the runtime.
/// Builder-style `with_*` helpers return an updated copy for ergonomic setup.
#[derive(Debug, Clone, PartialEq)]
pub struct Config {
    /// Maximum number of inference/tool iterations before stopping a prompt.
    pub max_iterations: u32,
    /// Default approval strategy for tool execution.
    pub default_approval_strategy: ApprovalStrategy,
    /// Policy for pruning or retaining transcript history.
    pub context_window_policy: ContextWindowPolicy,
    /// Model identifier passed to the provider on each inference request.
    pub model: String,
    /// Provider name (e.g. "openai", "anthropic") used to look up provider-specific
    /// system prompt fragments from `iron-providers`. When set, the fragment is
    /// resolved automatically and overrides `prompt_composition.provider_guidance`.
    pub provider_name: Option<String>,
    /// Default generation settings applied to every inference request.
    pub default_generation: GenerationConfig,
    /// Default tool policy applied when requests include tools.
    pub default_tool_policy: ToolPolicy,
    /// Context management configuration (compaction, telemetry, handoff).
    pub context_management: ContextManagementConfig,
    /// Embedded Python runtime configuration.
    pub embedded_python: EmbeddedPythonConfig,
    /// Prompt composition configuration (baseline, repo instructions, runtime context).
    pub prompt_composition: PromptCompositionConfig,
    /// MCP configuration
    pub mcp: McpConfig,
    /// Plugin configuration
    pub plugins: PluginConfig,
    /// Skill configuration
    pub skills: SkillConfig,
    /// Workspace roots used to derive the runtime context working directory
    /// and workspace root list. When non-empty, the first root becomes the
    /// primary working directory and all roots are surfaced as workspace roots.
    /// When empty, `std::env::current_dir()` is used as a fallback.
    pub workspace_roots: Vec<std::path::PathBuf>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            max_iterations: 10,
            default_approval_strategy: ApprovalStrategy::PerTool,
            context_window_policy: ContextWindowPolicy::default(),
            model: "gpt-4o".to_string(),
            provider_name: None,
            default_generation: GenerationConfig::default(),
            default_tool_policy: ToolPolicy::Auto,
            context_management: ContextManagementConfig::default(),
            embedded_python: EmbeddedPythonConfig::default(),
            prompt_composition: PromptCompositionConfig::default(),
            mcp: McpConfig::default(),
            plugins: PluginConfig::default(),
            skills: SkillConfig::default(),
            workspace_roots: Vec::new(),
        }
    }
}

impl Config {
    /// Create a new configuration using the crate defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the maximum iteration limit for each prompt.
    pub fn with_max_iterations(mut self, max: u32) -> Self {
        self.max_iterations = max;
        self
    }

    /// Set the default approval strategy applied to tool calls.
    pub fn with_approval_strategy(mut self, strategy: ApprovalStrategy) -> Self {
        self.default_approval_strategy = strategy;
        self
    }

    /// Set the context window policy used when building provider requests.
    pub fn with_context_window_policy(mut self, policy: ContextWindowPolicy) -> Self {
        self.context_window_policy = policy;
        self
    }

    /// Set the default model identifier used for inference.
    pub fn with_model<S: Into<String>>(mut self, model: S) -> Self {
        self.model = model.into();
        self
    }

    /// Set the provider name used to resolve provider-specific system prompt
    /// fragments from `iron-providers` (e.g. "openai", "anthropic").
    pub fn with_provider_name<S: Into<String>>(mut self, name: S) -> Self {
        self.provider_name = Some(name.into());
        self
    }

    /// Set the default generation settings for future requests.
    pub fn with_default_generation(mut self, generation: GenerationConfig) -> Self {
        self.default_generation = generation;
        self
    }

    /// Set the default tool policy used when tools are present.
    pub fn with_default_tool_policy(mut self, policy: ToolPolicy) -> Self {
        self.default_tool_policy = policy;
        self
    }

    /// Set the context management configuration.
    pub fn with_context_management(mut self, config: ContextManagementConfig) -> Self {
        self.context_management = config;
        self
    }

    /// Set the embedded Python runtime configuration.
    pub fn with_embedded_python(mut self, config: EmbeddedPythonConfig) -> Self {
        self.embedded_python = config;
        self
    }

    /// Set the prompt composition configuration.
    pub fn with_prompt_composition(mut self, config: PromptCompositionConfig) -> Self {
        self.prompt_composition = config;
        self
    }

    /// Enable the embedded Python runtime with its default limits.
    pub fn with_embedded_python_enabled(mut self) -> Self {
        self.embedded_python.enabled = true;
        self
    }

    /// Set the MCP configuration.
    pub fn with_mcp(mut self, mcp: McpConfig) -> Self {
        self.mcp = mcp;
        self
    }

    /// Set the plugin configuration.
    pub fn with_plugins(mut self, plugins: PluginConfig) -> Self {
        self.plugins = plugins;
        self
    }

    /// Set the skill configuration.
    pub fn with_skills(mut self, skills: SkillConfig) -> Self {
        self.skills = skills;
        self
    }

    /// Set the workspace roots used for runtime context rendering.
    pub fn with_workspace_roots(mut self, roots: Vec<std::path::PathBuf>) -> Self {
        self.workspace_roots = roots;
        self
    }

    /// Validate this config, returning an error if required fields are missing
    /// or generation constraints are out of range.
    pub fn validate(&self) -> Result<(), RuntimeError> {
        if self.model.trim().is_empty() {
            return Err(RuntimeError::invalid_config(
                "Config model is required but was empty",
            ));
        }
        if self.max_iterations == 0 {
            return Err(RuntimeError::invalid_config(
                "Config max_iterations must be greater than 0",
            ));
        }
        if let Some(temp) = self.default_generation.temperature {
            if !(0.0..=2.0).contains(&temp) {
                return Err(RuntimeError::invalid_config(format!(
                    "Config default temperature must be between 0.0 and 2.0, got {}",
                    temp
                )));
            }
        }
        self.context_management
            .validate()
            .map_err(RuntimeError::invalid_config)?;
        if self.embedded_python.enabled {
            self.embedded_python.validate()?;
        }
        Ok(())
    }
}

/// Strategy for deciding whether tool execution requires explicit approval.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ApprovalStrategy {
    /// Always require human approval.
    Always,
    /// Never require human approval.
    Never,
    /// Defer to the tool's `requires_approval` setting.
    #[default]
    PerTool,
    /// Auto-approve tool calls.
    ///
    /// This variant is representational plumbing for profile policy; it does
    /// not change existing tool-approval behavior until delegate-task/runtime
    /// enforcement is implemented.
    AutoApprove,
}

impl ApprovalStrategy {
    /// Check if approval is required for the given tool setting
    pub fn is_approval_required(self, tool_requires_approval: bool) -> bool {
        match self {
            ApprovalStrategy::Always => true,
            ApprovalStrategy::Never => false,
            ApprovalStrategy::PerTool => tool_requires_approval,
            ApprovalStrategy::AutoApprove => tool_requires_approval,
        }
    }
}

/// Policy for retaining transcript history as the conversation grows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ContextWindowPolicy {
    /// Keep all messages.
    #[default]
    KeepAll,
    /// Keep only the most recent `N` messages.
    KeepRecent(usize),
}

impl ContextWindowPolicy {
    /// Apply this policy to a message list
    pub fn apply<T>(&self, messages: &mut Vec<T>, _summarize_fn: impl FnOnce(&[T]) -> T) {
        match self {
            ContextWindowPolicy::KeepAll => {
                // No action needed
            }
            ContextWindowPolicy::KeepRecent(n) => {
                if messages.len() > *n {
                    let start = messages.len() - *n;
                    *messages = messages.split_off(start);
                }
            }
        }
    }
}

/// Configuration for the embedded Python runtime.
///
/// `iron-core` keeps the Monty-backed `python_exec` runtime in-tree.
/// Publishing this crate to crates.io is deferred until `monty` is
/// available on crates.io.
///
/// These limits control source size, result size, timeout, and child tool fan-out.
#[derive(Debug, Clone, PartialEq)]
pub struct EmbeddedPythonConfig {
    /// Whether embedded Python execution is enabled.
    pub enabled: bool,
    /// Maximum wall-clock time for a script run in seconds.
    pub max_script_timeout_secs: u64,
    /// Maximum accepted source code size in bytes.
    pub max_source_bytes: usize,
    /// Maximum serialized result payload size in bytes.
    pub max_result_bytes: usize,
    /// Maximum number of child tool calls per script run.
    pub max_child_calls: usize,
    /// Maximum number of items returned in child call outcomes.
    pub max_child_outcome_items: usize,
}

impl Default for EmbeddedPythonConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            max_script_timeout_secs: 30,
            max_source_bytes: 32 * 1024,
            max_result_bytes: 64 * 1024,
            max_child_calls: 20,
            max_child_outcome_items: 20,
        }
    }
}

impl EmbeddedPythonConfig {
    /// Create a new configuration using the default embedded-Python limits.
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable or disable embedded Python execution.
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Set the wall-clock timeout for each script run in seconds.
    pub fn with_timeout(mut self, secs: u64) -> Self {
        self.max_script_timeout_secs = secs;
        self
    }

    /// Set the maximum accepted source size in bytes.
    pub fn with_max_source_bytes(mut self, bytes: usize) -> Self {
        self.max_source_bytes = bytes;
        self
    }

    /// Set the maximum serialized result size in bytes.
    pub fn with_max_result_bytes(mut self, bytes: usize) -> Self {
        self.max_result_bytes = bytes;
        self
    }

    /// Set the maximum number of child tool calls allowed per script.
    pub fn with_max_child_calls(mut self, n: usize) -> Self {
        self.max_child_calls = n;
        self
    }

    /// Validate the embedded Python configuration.
    pub fn validate(&self) -> Result<(), RuntimeError> {
        if self.max_script_timeout_secs == 0 {
            return Err(RuntimeError::invalid_config(
                "EmbeddedPythonConfig max_script_timeout_secs must be > 0",
            ));
        }
        if self.max_source_bytes == 0 {
            return Err(RuntimeError::invalid_config(
                "EmbeddedPythonConfig max_source_bytes must be > 0",
            ));
        }
        if self.max_result_bytes == 0 {
            return Err(RuntimeError::invalid_config(
                "EmbeddedPythonConfig max_result_bytes must be > 0",
            ));
        }
        if self.max_child_calls == 0 {
            return Err(RuntimeError::invalid_config(
                "EmbeddedPythonConfig max_child_calls must be > 0",
            ));
        }
        Ok(())
    }
}

/// Configuration for MCP (Model Context Protocol) servers.
///
/// This configuration controls MCP server behavior and defaults for new sessions.
#[derive(Debug, Clone, PartialEq)]
pub struct McpConfig {
    /// Whether MCP is enabled globally for this runtime.
    pub enabled: bool,
    /// Whether configured MCP servers are enabled by default for new sessions.
    /// If false, new sessions start with all MCP servers disabled.
    pub enabled_by_default: bool,
}

impl Default for McpConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            enabled_by_default: true,
        }
    }
}

impl McpConfig {
    /// Create a new MCP configuration using defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable or disable MCP support globally.
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Set whether MCP servers are enabled by default for new sessions.
    pub fn with_enabled_by_default(mut self, enabled_by_default: bool) -> Self {
        self.enabled_by_default = enabled_by_default;
        self
    }
}

/// Configuration for WASM integration plugins.
///
/// This configuration controls plugin behavior and defaults for new sessions.
#[derive(Debug, Clone, PartialEq)]
pub struct PluginConfig {
    /// Whether plugins are enabled globally for this runtime.
    pub enabled: bool,
    /// Whether configured plugins are enabled by default for new sessions.
    /// If false, new sessions start with all plugins disabled.
    pub enabled_by_default: bool,
    /// Base directory for caching plugin artifacts
    pub artifact_cache_dir: std::path::PathBuf,
    /// Maximum WASM linear memory per plugin, in bytes. Applied as a ceiling —
    /// if a plugin's manifest declares a smaller limit, the smaller limit wins.
    /// Defaults to 128 MB.
    pub max_memory_bytes: u64,
}

impl Default for PluginConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            enabled_by_default: true,
            artifact_cache_dir: std::path::PathBuf::from("./plugin_cache"),
            max_memory_bytes: crate::plugin::wasm_host::DEFAULT_PLUGIN_MAX_MEMORY_BYTES,
        }
    }
}

impl PluginConfig {
    /// Create a new plugin configuration using defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable or disable plugin support globally.
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Set whether plugins are enabled by default for new sessions.
    pub fn with_enabled_by_default(mut self, enabled_by_default: bool) -> Self {
        self.enabled_by_default = enabled_by_default;
        self
    }

    /// Set the artifact cache directory.
    pub fn with_artifact_cache_dir(mut self, dir: std::path::PathBuf) -> Self {
        self.artifact_cache_dir = dir;
        self
    }

    /// Set the per-plugin WASM memory ceiling, in bytes.
    pub fn with_max_memory_bytes(mut self, bytes: u64) -> Self {
        self.max_memory_bytes = bytes;
        self
    }
}

/// Configuration for agent skills.
///
/// Skills are declarative instruction sets that models can discover and activate.
#[derive(Debug, Clone, PartialEq)]
pub struct SkillConfig {
    /// Whether skills are enabled globally for this runtime.
    pub enabled: bool,
    /// Whether to trust project-level skills discovered from the workspace.
    /// When false, project-level skills are hidden from the catalog.
    pub trust_project_skills: bool,
    /// Directories to scan for skills in addition to defaults.
    pub additional_skill_dirs: Vec<std::path::PathBuf>,
}

impl Default for SkillConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            trust_project_skills: false,
            additional_skill_dirs: Vec::new(),
        }
    }
}

impl SkillConfig {
    /// Create a new skill configuration using defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable or disable skill support globally.
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Set whether to trust project-level skills.
    pub fn with_trust_project_skills(mut self, trust: bool) -> Self {
        self.trust_project_skills = trust;
        self
    }

    /// Add an additional skill directory to scan.
    pub fn with_additional_skill_dir(mut self, dir: std::path::PathBuf) -> Self {
        self.additional_skill_dirs.push(dir);
        self
    }
}

// Durable config store submodules
pub mod builtin_models;
pub mod effective_catalog;
pub mod error;
pub mod records;
pub mod store;

pub mod crypto;
mod db;
mod key_source;
pub mod migrations;

#[cfg(test)]
mod automation_task_tests;

#[cfg(test)]
mod scheduled_task_tests;

pub use builtin_models::{builtin_model_catalog, BuiltinModelEntry};
pub use effective_catalog::{
    build_effective_catalog, CatalogError, EffectiveModelCatalog, EffectiveModelEntry,
};
pub use error::ConfigError;
pub use records::{
    BootstrapMetadataInput, BootstrapMetadataRecord, CredentialRecord, CustomModelInput,
    CustomModelRecord, DefaultModelInput, DefaultModelRecord, McpServerConfigInput,
    McpServerConfigRecord, ProfileInput, ProfileRecord, PromptInput, PromptRecord,
    ProviderConfigInput, ProviderConfigRecord, ProviderProfileInput, ProviderProfileRecord,
    RuntimeSettingsSnapshot, SavedHandoffInput, SavedHandoffMetadata, SavedHandoffRecord,
    ScheduleInput, ScheduleRecord, SkillSettingsInput, SkillSettingsRecord,
};
pub use store::{default_config_path, ConfigStore, OpenOptions};