iron-core 0.1.37

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
//! Handoff export/import for session continuity.
//!
//! The handoff bundle transfers conversation state (messages, instructions,
//! compacted context) but explicitly EXCLUDES:
//! - Runtime-local tool capabilities (including MCP server inventory)
//! - Runtime-local capability configurations
//! - Session MCP enablement state
//! - Session plugin enablement state and plugin auth bindings
//! - Other runtime-local state that may differ between environments
//!
//! This preserves portability: the destination runtime determines its own
//! available integrations and tools.

use crate::context::config::ContextManagementConfig;
use crate::context::model_switch::ModelSwitchRecord;
use crate::context::models::CompressedBlock;
use crate::durable::{DurableSession, SessionId, StructuredMessage};
use crate::skill::SessionSkillState;
use serde::{Deserialize, Serialize};

/// Current serialized handoff bundle format version.
pub const HANDOFF_BUNDLE_VERSION: &str = "1";

/// Provenance and approximate size of a handoff bundle.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HandoffBundleMetadata {
    /// Metadata schema version.
    pub version: String,
    /// Model reported by the exporter.
    pub source_model: String,
    /// Source provider name, when known.
    pub source_provider: Option<String>,
    /// Display form of the source session identifier.
    pub source_session_id: String,
    /// Heuristic size of instructions, summaries, tail, and active skills.
    pub size_estimate_tokens: usize,
}

/// Portable continuity state transferred between durable sessions.
///
/// The bundle owns cloned instructions, summaries, recent messages, skill
/// state, profile snapshots, and model-switch state. Runtime-local MCP and
/// plugin enablement are intentionally absent. Managed provider credentials
/// are included when present, so serialized bundles must be handled as secrets.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HandoffBundle {
    /// Bundle schema version.
    pub version: String,
    /// Explicit source-session instructions.
    pub instructions: Option<String>,
    /// Human-readable continuity and portability note.
    pub handoff_note: String,
    /// Durable summaries selected for transfer.
    pub compressed_blocks: Vec<CompressedBlock>,
    /// Recent structured messages selected for transfer.
    pub recent_tail: Vec<StructuredMessage>,
    /// Activated skill state preserved across runtimes.
    pub skill_state: SessionSkillState,
    /// Bundle provenance and size estimate.
    pub metadata: HandoffBundleMetadata,
    /// Model-switch history preserved across handoffs.
    pub model_switch_history: Vec<ModelSwitchRecord>,
    /// Current model after the most recent switch.
    pub current_model: Option<String>,
    /// Current managed-provider slug, if any.
    pub current_provider_slug: Option<String>,
    /// Current managed-provider API key, if any.
    ///
    /// Wrapped in a [`crate::secret::SecretString`] so the credential is redacted
    /// from debug output. It still serializes transparently because serialized
    /// bundles must remain usable as portable secrets.
    pub current_provider_api_key: Option<crate::secret::SecretString>,
    /// Profile identity prompt selected for this session, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile_identity: Option<String>,
    /// Tools hidden due to model capability differences.
    #[serde(default)]
    pub hidden_tools: Vec<String>,
    /// The profile id last used for this session, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<crate::profile::AgentProfileId>,
    /// Session-effective snapshot of the profile's tool filter at setup time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_tool_filter: Option<crate::profile::ToolFilter>,
    /// Session-effective snapshot of the profile's approval posture at setup time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_approval: Option<crate::profile::AgentApproval>,
    /// Session-effective snapshot of the resolved model at setup time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_model: Option<String>,
    /// Whether the session was created with a profile that is no longer available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile_unavailable: Option<String>,
    /// Session-effective snapshot of the resolved provider context at setup time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_provider_context:
        Option<crate::provider_credential::domain::ProviderPromptContext>,
}

/// Validator and builder for portable handoff bundles.
pub struct HandoffExporter;

impl HandoffExporter {
    /// Returns whether the session has no pending or running tool calls.
    ///
    /// Handoff export is restricted to this idle tool lifecycle boundary.
    pub fn can_export(session: &DurableSession) -> bool {
        !session.tool_records.iter().any(|r| {
            matches!(
                r.status,
                crate::durable::ToolRecordStatus::PendingApproval
                    | crate::durable::ToolRecordStatus::Running
            )
        })
    }

    /// Clones selected continuity state into a portable bundle.
    ///
    /// `compressed_blocks` and `tail` are caller-selected views; they need not
    /// equal all context currently owned by `session`. Runtime-local tool and
    /// plugin enablement are not exported.
    ///
    /// # Errors
    ///
    /// Returns an error while a tool call is pending approval or running.
    pub fn export(
        session: &DurableSession,
        model: &str,
        compressed_blocks: &[CompressedBlock],
        tail: Vec<StructuredMessage>,
        config: &ContextManagementConfig,
        provider_name: Option<&str>,
    ) -> Result<HandoffBundle, String> {
        if !Self::can_export(session) {
            return Err("Cannot export handoff bundle: session has active tool calls".into());
        }

        let target_tokens = config.handoff_export.default_target_tokens;
        let size_estimate = estimate_bundle_size(
            compressed_blocks,
            &tail,
            session.instruction_text_for_estimate().as_deref(),
            &session.skill_state,
        );

        let mut handoff_note = format!(
            "Context transferred from session {} on model {}.",
            session.id, model
        );

        let mut loss_notes = Vec::new();
        for msg in &tail {
            for block in msg.content_blocks().iter() {
                if let crate::durable::ContentBlock::Resource { uri, .. } = block {
                    if is_local_resource(uri.as_str()) {
                        loss_notes.push(format!(
                            "Local resource '{}' may not be accessible at destination",
                            uri
                        ));
                    }
                }
            }
        }

        if !loss_notes.is_empty() {
            handoff_note.push_str(&format!("\nPortability notes: {}", loss_notes.join("; ")));
        }

        if size_estimate > target_tokens {
            handoff_note.push_str(&format!(
                "\nBundle size (~{} tokens) exceeds target (~{} tokens).",
                size_estimate, target_tokens
            ));
        }

        let mut bundle = HandoffBundle {
            version: HANDOFF_BUNDLE_VERSION.to_string(),
            instructions: session.instructions.clone(),
            handoff_note,
            compressed_blocks: compressed_blocks.to_vec(),
            recent_tail: tail,
            skill_state: session.skill_state.clone(),
            metadata: HandoffBundleMetadata {
                version: HANDOFF_BUNDLE_VERSION.to_string(),
                source_model: model.to_string(),
                source_provider: provider_name.map(|s| s.to_string()),
                source_session_id: session.id.to_string(),
                size_estimate_tokens: size_estimate,
            },
            model_switch_history: session.model_switch_history.clone(),
            current_model: session.current_model.clone(),
            current_provider_slug: session.current_provider_slug.clone(),
            current_provider_api_key: session.current_provider_api_key.clone(),
            profile_identity: session.profile_identity.clone(),
            hidden_tools: session.hidden_tools.clone(),
            profile_id: session.profile_id.clone(),
            effective_tool_filter: session.effective_tool_filter.clone(),
            effective_approval: session.effective_approval,
            effective_model: session.effective_model.clone(),
            profile_unavailable: session.profile_unavailable.clone(),
            effective_provider_context: session.effective_provider_context.clone(),
        };

        if config.handoff_export.include_portability_notes && !loss_notes.is_empty() {
            // Portability notes are no longer stored in a structured compacted_context.
            // They are appended to the handoff_note instead.
            for note in loss_notes {
                bundle
                    .handoff_note
                    .push_str(&format!("\nPortability note: {}", note));
            }
        }

        Ok(bundle)
    }
}

/// Hydrates durable sessions from owned handoff bundles.
pub struct HandoffImporter;

impl HandoffImporter {
    /// Merges an owned bundle into an existing durable session.
    ///
    /// Imported summaries are rendered as an agent message, recent tail items
    /// are appended directly to message storage, and model-switch timeline
    /// metadata is recreated. Existing runtime-local MCP and plugin enablement
    /// remains owned by the target and is not replaced. The target retains its
    /// session identity.
    ///
    /// # Errors
    ///
    /// Returns an error if the target identifier equals the newly allocated
    /// identity used by the method's mismatch guard.
    pub fn hydrate(target: &mut DurableSession, bundle: HandoffBundle) -> Result<(), String> {
        if target.id == SessionId::new() {
            return Err(
                "Cannot hydrate into a freshly-constructed session with mismatched identity".into(),
            );
        }

        if !bundle.handoff_note.is_empty() {
            target.add_agent_text(format!("[Handoff] {}", bundle.handoff_note));
        }

        if let Some(instr) = bundle.instructions {
            target.set_instructions(instr);
        }

        if let Some(identity) = bundle.profile_identity {
            target.set_profile_identity(identity);
        }

        if !bundle.compressed_blocks.is_empty() {
            let rendered = bundle
                .compressed_blocks
                .iter()
                .map(|b| b.render_to_text())
                .collect::<Vec<_>>()
                .join("\n");
            if !rendered.is_empty() {
                target.add_agent_text(format!("[Compressed context]\n{}", rendered));
            }
        }

        for msg in bundle.recent_tail {
            target.messages.push(msg);
        }

        // Restore skill state so activated skills survive handoff
        target.skill_state = bundle.skill_state;

        // Restore model switch history and capability restrictions
        target.model_switch_history = bundle.model_switch_history.clone();
        target.current_model = bundle.current_model.clone();
        target.current_provider_slug = bundle.current_provider_slug.clone();
        target.current_provider_api_key = bundle.current_provider_api_key.clone();
        target.hidden_tools = bundle.hidden_tools.clone();
        target.profile_id = bundle.profile_id.clone();
        target.effective_tool_filter = bundle.effective_tool_filter.clone();
        target.effective_approval = bundle.effective_approval;
        target.effective_model = bundle.effective_model.clone();
        target.profile_unavailable = bundle.profile_unavailable.clone();
        target.effective_provider_context = bundle.effective_provider_context.clone();

        // Recreate timeline entries from model switch history
        for record in &bundle.model_switch_history {
            let timeline_index = target.timeline.len() as u64;
            target
                .timeline
                .push(crate::durable::TimelineEntry::ModelSwitched {
                    index: timeline_index,
                    from_model: record.from_model.clone(),
                    to_model: record.to_model.clone(),
                    from_provider: record.from_provider.clone(),
                    to_provider: record.to_provider.clone(),
                    adapted: record.adapted,
                    visible_id: None,
                });
        }

        // Note: MCP server and plugin enablement are NOT imported as part of handoff.
        // The destination runtime determines its own tool availability.

        Ok(())
    }

    /// Creates a fresh durable session and hydrates it from an owned bundle.
    ///
    /// The destination receives a new [`SessionId`]. Runtime-local MCP and
    /// plugin enablement starts empty rather than crossing the handoff boundary.
    pub fn hydrate_into_new(bundle: HandoffBundle) -> DurableSession {
        let mut session = DurableSession::new(SessionId::new());

        if let Some(instr) = bundle.instructions {
            session.set_instructions(instr);
        }

        if let Some(identity) = bundle.profile_identity {
            session.set_profile_identity(identity);
        }

        if !bundle.handoff_note.is_empty() {
            session.add_agent_text(format!("[Handoff] {}", bundle.handoff_note));
        }

        if !bundle.compressed_blocks.is_empty() {
            let rendered = bundle
                .compressed_blocks
                .iter()
                .map(|b| b.render_to_text())
                .collect::<Vec<_>>()
                .join("\n");
            if !rendered.is_empty() {
                session.add_agent_text(format!("[Compressed context]\n{}", rendered));
            }
        }

        for msg in bundle.recent_tail {
            session.messages.push(msg);
        }

        // Restore skill state so activated skills survive handoff
        session.skill_state = bundle.skill_state;

        // Restore model switch history and capability restrictions
        session.model_switch_history = bundle.model_switch_history.clone();
        session.current_model = bundle.current_model.clone();
        session.current_provider_slug = bundle.current_provider_slug.clone();
        session.current_provider_api_key = bundle.current_provider_api_key.clone();
        session.hidden_tools = bundle.hidden_tools.clone();
        session.profile_id = bundle.profile_id.clone();
        session.effective_tool_filter = bundle.effective_tool_filter.clone();
        session.effective_approval = bundle.effective_approval;
        session.effective_model = bundle.effective_model.clone();
        session.profile_unavailable = bundle.profile_unavailable.clone();
        session.effective_provider_context = bundle.effective_provider_context.clone();

        // Recreate timeline entries from model switch history
        for record in &bundle.model_switch_history {
            let timeline_index = session.timeline.len() as u64;
            session
                .timeline
                .push(crate::durable::TimelineEntry::ModelSwitched {
                    index: timeline_index,
                    from_model: record.from_model.clone(),
                    to_model: record.to_model.clone(),
                    from_provider: record.from_provider.clone(),
                    to_provider: record.to_provider.clone(),
                    adapted: record.adapted,
                    visible_id: None,
                });
        }

        // Note: MCP server and plugin enablement are NOT imported as part of handoff.
        // The destination runtime determines its own tool availability.

        session
    }
}

fn estimate_bundle_size(
    compressed_blocks: &[CompressedBlock],
    tail: &[StructuredMessage],
    instructions: Option<&str>,
    skill_state: &SessionSkillState,
) -> usize {
    let mut total = 0usize;
    if let Some(instr) = instructions {
        total += (instr.len() as f64 * 0.25).ceil() as usize;
    }
    for block in compressed_blocks {
        total += (block.render_to_text().len() as f64 * 0.25).ceil() as usize;
    }
    for msg in tail {
        total += (msg.text_content().len() as f64 * 0.25).ceil() as usize;
    }
    // Include activated skill instructions in size estimate
    let skill_instructions = skill_state.active_skill_instructions();
    if !skill_instructions.is_empty() {
        total += (skill_instructions.len() as f64 * 0.25).ceil() as usize;
    }
    total
}

fn is_local_resource(uri: &str) -> bool {
    uri.starts_with("file://")
        || uri.starts_with("localhost")
        || uri.starts_with("127.0.0.1")
        || uri.starts_with("unix://")
        || uri.starts_with("/dev/")
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Verifies that `hydrate_into_new` does **not** carry over plugin
    /// enablement state from the source session.  The destination runtime
    /// must determine its own tool availability.
    #[test]
    fn hydrate_into_new_produces_empty_plugin_enablement() {
        // Create a source session with plugin enablement state.
        let mut source = DurableSession::new(SessionId::new());
        source.set_plugin_enabled("plugin-a", true);
        source.set_plugin_enabled("plugin-b", false);
        assert_eq!(
            source.list_enabled_plugins(),
            vec!["plugin-a".to_string()],
            "sanity check: source should have plugin-a enabled"
        );

        // Export a handoff bundle (minimal — no messages needed).
        let config = ContextManagementConfig::default();
        let bundle = HandoffExporter::export(&source, "test-model", &[], vec![], &config, None)
            .expect("export should succeed for idle session");

        // Hydrate into a new session.
        let hydrated = HandoffImporter::hydrate_into_new(bundle);

        // The hydrated session must have empty plugin enablement.
        assert!(
            hydrated.list_enabled_plugins().is_empty(),
            "plugin enablement must not survive handoff; got {:?}",
            hydrated.list_enabled_plugins()
        );
        assert_eq!(
            hydrated.is_plugin_enabled("plugin-a"),
            None,
            "plugin-a must have no explicit enablement after hydration"
        );
        assert_eq!(
            hydrated.is_plugin_enabled("plugin-b"),
            None,
            "plugin-b must have no explicit enablement after hydration"
        );
    }

    /// Verifies that the `hydrate` (in-place) path also excludes plugin
    /// enablement — the import path never touches plugin_enablement.
    #[test]
    fn hydrate_in_place_does_not_modify_plugin_enablement() {
        let mut source = DurableSession::new(SessionId::new());
        source.set_plugin_enabled("plugin-x", true);
        source.add_agent_text("hello");

        let config = ContextManagementConfig::default();
        let bundle = HandoffExporter::export(&source, "test-model", &[], vec![], &config, None)
            .expect("export should succeed");

        // Create a target with its own plugin enablement.
        let mut target = DurableSession::new(SessionId::new());
        target.set_plugin_enabled("plugin-y", true);

        HandoffImporter::hydrate(&mut target, bundle).expect("hydrate should succeed");

        // Target must retain its own enablement; nothing from source imported.
        assert_eq!(
            target.is_plugin_enabled("plugin-x"),
            None,
            "source plugin enablement must not leak into target"
        );
        assert_eq!(
            target.is_plugin_enabled("plugin-y"),
            Some(true),
            "target's own plugin enablement must be preserved"
        );
    }

    #[test]
    fn handoff_preserves_activated_skills() {
        let mut source = DurableSession::new(SessionId::new());
        source.activate_skill("test-skill", "# Test Skill\nDo something useful.", vec![]);
        source.add_agent_text("hello");

        assert!(source.skill_state.is_active("test-skill"));

        let config = ContextManagementConfig::default();
        let bundle = HandoffExporter::export(&source, "test-model", &[], vec![], &config, None)
            .expect("export should succeed");

        // Verify skill state is in the bundle
        assert!(bundle.skill_state.is_active("test-skill"));
        assert_eq!(bundle.skill_state.active.len(), 1);
        assert_eq!(bundle.skill_state.active[0].name, "test-skill");
        assert_eq!(
            bundle.skill_state.active[0].body,
            "# Test Skill\nDo something useful."
        );

        // Hydrate into a new session
        let hydrated = HandoffImporter::hydrate_into_new(bundle);

        // Skill state should survive handoff
        assert!(hydrated.skill_state.is_active("test-skill"));
        assert_eq!(hydrated.skill_state.active.len(), 1);
        assert_eq!(
            hydrated.active_skill_instructions(),
            "<skill_content name=\"test-skill\">\n# Test Skill\nDo something useful.\n</skill_content>"
        );
    }

    #[test]
    fn handoff_includes_skill_state_in_size_estimate() {
        let mut source = DurableSession::new(SessionId::new());
        source.activate_skill("big-skill", "x".repeat(1000), vec![]);

        let config = ContextManagementConfig::default();
        let bundle = HandoffExporter::export(&source, "test-model", &[], vec![], &config, None)
            .expect("export should succeed");

        // Size estimate should include skill instructions (~250 tokens for 1000 chars)
        assert!(
            bundle.metadata.size_estimate_tokens >= 250,
            "Size estimate should include skill instructions, got {} tokens",
            bundle.metadata.size_estimate_tokens
        );
    }
}