opi-agent 0.5.0

General-purpose agent runtime with tool calling and session management
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
//! Compaction integration tests (task 2.8).
//!
//! DoD: "manual/threshold/overflow triggers, summary record with
//! first_kept_entry_id and tokens before/after, hook extensibility tested"

use opi_agent::compaction::{
    CompactionConfig, CompactionEngine, CompactionHooks, DefaultCompactionHooks, Entry,
    SummarySource,
};
use opi_agent::message::AgentMessage;
use opi_agent::session_event::CompactionReason;
use opi_ai::message::{
    AssistantContent, AssistantMessage, ImageSource, InputContent, MediaType, Message,
    OutputContent, ToolResultMessage, UserMessage,
};
use opi_ai::stream::{StopReason, Usage};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn user_text(id: &str, text: &str) -> Entry {
    Entry {
        id: id.into(),
        message: AgentMessage::Llm(Message::User(UserMessage {
            content: vec![InputContent::Text { text: text.into() }],
            timestamp_ms: 0,
        })),
    }
}

fn assistant_text(id: &str, text: &str) -> Entry {
    Entry {
        id: id.into(),
        message: AgentMessage::Llm(Message::Assistant(AssistantMessage {
            content: vec![AssistantContent::Text { text: text.into() }],
            api: opi_ai::ApiKind::Anthropic,
            provider: "mock".into(),
            model: "mock-model".into(),
            response_model: None,
            response_id: None,
            usage: Usage::default(),
            stop_reason: StopReason::Stop,
            error_message: None,
            timestamp_ms: 0,
        })),
    }
}

// ---------------------------------------------------------------------------
// Trigger tests
// ---------------------------------------------------------------------------

#[test]
fn manual_trigger_always_compacts() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    assert!(engine.should_compact(0, CompactionReason::Manual));
    assert!(engine.should_compact(100_000, CompactionReason::Manual));
}

#[test]
fn overflow_trigger_always_compacts() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    assert!(engine.should_compact(0, CompactionReason::Overflow));
    assert!(engine.should_compact(100_000, CompactionReason::Overflow));
}

#[test]
fn threshold_trigger_compacts_above_threshold() {
    let engine = CompactionEngine::new(CompactionConfig {
        threshold_tokens: 1000,
        ..Default::default()
    });
    assert!(
        engine.should_compact(1500, CompactionReason::Threshold),
        "should compact when tokens exceed threshold"
    );
}

#[test]
fn threshold_trigger_does_not_compact_below_threshold() {
    let engine = CompactionEngine::new(CompactionConfig {
        threshold_tokens: 1000,
        ..Default::default()
    });
    assert!(
        !engine.should_compact(500, CompactionReason::Threshold),
        "should not compact when tokens below threshold"
    );
}

#[test]
fn disabled_engine_no_automatic_compaction() {
    let engine = CompactionEngine::new(CompactionConfig {
        enabled: false,
        ..Default::default()
    });
    assert!(
        !engine.should_compact(1_000_000, CompactionReason::Threshold),
        "disabled should not threshold-compact"
    );
    assert!(
        !engine.should_compact(1_000_000, CompactionReason::Overflow),
        "disabled should not overflow-compact"
    );
}

#[test]
fn disabled_engine_manual_still_works() {
    let engine = CompactionEngine::new(CompactionConfig {
        enabled: false,
        ..Default::default()
    });
    assert!(
        engine.should_compact(0, CompactionReason::Manual),
        "manual should always work even when disabled"
    );
}

// ---------------------------------------------------------------------------
// Summary record tests
// ---------------------------------------------------------------------------

#[test]
fn compact_produces_summary_with_first_kept_entry_id() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    let entries = vec![
        user_text("e1", "Hello, this is a test message with some content"),
        assistant_text(
            "e2",
            "I received your message and here is my response with more content",
        ),
        user_text("e3", "Short"),
    ];

    let result = engine
        .compact(&entries, CompactionReason::Manual, &DefaultCompactionHooks)
        .unwrap();

    assert!(
        !result.summary_text.is_empty(),
        "summary should not be empty"
    );
    assert_eq!(
        result.first_kept_entry_id, "e3",
        "first_kept_entry_id should be the last entry"
    );
}

#[test]
fn compact_records_tokens_before_and_after() {
    let engine = CompactionEngine::new(CompactionConfig {
        threshold_tokens: 10,
        ..Default::default()
    });

    // Create enough entries that some will be compacted
    let entries: Vec<Entry> = (0..20)
        .flat_map(|i| {
            vec![
                user_text(
                    &format!("u{}", i),
                    &format!("User message number {} with substantial content", i),
                ),
                assistant_text(
                    &format!("a{}", i),
                    &format!(
                        "Assistant response number {} with substantial content back",
                        i
                    ),
                ),
            ]
        })
        .collect();

    let result = engine
        .compact(
            &entries,
            CompactionReason::Threshold,
            &DefaultCompactionHooks,
        )
        .unwrap();

    assert!(result.tokens_before > 0, "tokens_before should be positive");
    assert!(result.tokens_after > 0, "tokens_after should be positive");
    assert!(
        result.tokens_after < result.tokens_before,
        "tokens_after should be less than tokens_before"
    );
}

#[test]
fn compact_keeps_recent_entries() {
    let engine = CompactionEngine::new(CompactionConfig {
        threshold_tokens: 10,
        ..Default::default()
    });

    let entries = vec![
        user_text("e1", "Old message 1 with enough text"),
        assistant_text("e2", "Old response 1 with enough text"),
        user_text("e3", "Old message 2 with enough text"),
        assistant_text("e4", "Old response 2 with enough text"),
        user_text("e5", "Recent message with enough text"),
        assistant_text("e6", "Recent response with enough text"),
    ];

    let result = engine
        .compact(&entries, CompactionReason::Manual, &DefaultCompactionHooks)
        .unwrap();

    assert!(
        !result.kept_entries.is_empty(),
        "should keep at least one entry"
    );
    assert_eq!(
        result.first_kept_entry_id, result.kept_entries[0].id,
        "first_kept_entry_id should match first kept entry"
    );
}

#[test]
fn compact_summary_contains_reasonable_text() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    let entries = vec![
        user_text("e1", "Please read the file src/main.rs"),
        assistant_text("e2", "The file contains a hello world program"),
        user_text("e3", "Now update it"),
    ];

    let result = engine
        .compact(&entries, CompactionReason::Manual, &DefaultCompactionHooks)
        .unwrap();

    // Core summary should reference the compacted content
    assert!(
        result.summary_text.len() > 10,
        "summary should have meaningful content, got: {:?}",
        result.summary_text
    );
}

// ---------------------------------------------------------------------------
// Hook extensibility tests
// ---------------------------------------------------------------------------

struct CustomSummaryHook;

impl CompactionHooks for CustomSummaryHook {
    fn generate_summary(&self, _messages: &[AgentMessage]) -> Option<String> {
        Some("Custom hook generated this summary".into())
    }
}

#[test]
fn compact_custom_hook_provides_summary() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    let entries = vec![
        user_text("e1", "Message one"),
        assistant_text("e2", "Response one"),
        user_text("e3", "Message two"),
    ];

    let result = engine
        .compact(&entries, CompactionReason::Manual, &CustomSummaryHook)
        .unwrap();

    assert_eq!(
        result.summary_text, "Custom hook generated this summary",
        "custom hook summary should be used"
    );
    assert_eq!(
        result.summary_source,
        SummarySource::Hook,
        "source should indicate hook"
    );
}

#[test]
fn compact_default_hook_uses_core_summary() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    let entries = vec![
        user_text("e1", "Hello world"),
        assistant_text("e2", "Hi there"),
        user_text("e3", "How are you?"),
    ];

    let result = engine
        .compact(&entries, CompactionReason::Manual, &DefaultCompactionHooks)
        .unwrap();

    assert_eq!(
        result.summary_source,
        SummarySource::Core,
        "source should indicate core"
    );
    assert!(
        !result.summary_text.is_empty(),
        "core summary should not be empty"
    );
}

struct NoSummaryHook;

impl CompactionHooks for NoSummaryHook {
    fn generate_summary(&self, _messages: &[AgentMessage]) -> Option<String> {
        None
    }
}

#[test]
fn compact_hook_returns_none_falls_back_to_core() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    let entries = vec![
        user_text("e1", "First message"),
        assistant_text("e2", "First response"),
        user_text("e3", "Second message"),
    ];

    let result = engine
        .compact(&entries, CompactionReason::Manual, &NoSummaryHook)
        .unwrap();

    assert_eq!(
        result.summary_source,
        SummarySource::Core,
        "should fall back to core when hook returns None"
    );
}

// ---------------------------------------------------------------------------
// Edge case tests
// ---------------------------------------------------------------------------

#[test]
fn compact_empty_entries_returns_error() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    let result = engine.compact(&[], CompactionReason::Manual, &DefaultCompactionHooks);
    assert!(result.is_err(), "empty entries should fail");
}

#[test]
fn compact_single_entry_returns_error() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    let entries = vec![user_text("e1", "Only one message")];
    let result = engine.compact(&entries, CompactionReason::Manual, &DefaultCompactionHooks);
    assert!(
        result.is_err(),
        "single entry should fail — nothing to compact"
    );
}

#[test]
fn compact_two_entries_succeeds() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    let entries = vec![user_text("e1", "First"), assistant_text("e2", "Second")];
    let result = engine.compact(&entries, CompactionReason::Manual, &DefaultCompactionHooks);
    assert!(result.is_ok(), "two entries should compact successfully");
}

#[test]
fn compact_output_messages_include_summary_and_kept() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    let entries = vec![
        user_text("e1", "Old message that will be compacted away"),
        assistant_text("e2", "Old response that will be compacted away"),
        user_text("e3", "This should be kept"),
    ];

    let result = engine
        .compact(&entries, CompactionReason::Manual, &DefaultCompactionHooks)
        .unwrap();

    // Kept entries should contain the last entry
    let kept_ids: Vec<&str> = result.kept_entries.iter().map(|e| e.id.as_str()).collect();
    assert!(
        kept_ids.contains(&"e3"),
        "kept entries should contain e3, got: {:?}",
        kept_ids
    );
    // The compacted entries should NOT be in kept
    assert!(
        !kept_ids.contains(&"e1"),
        "e1 should have been compacted away"
    );
}

// ---------------------------------------------------------------------------
// Config default tests
// ---------------------------------------------------------------------------

#[test]
fn default_config_has_reasonable_values() {
    let config = CompactionConfig::default();
    assert!(config.enabled, "compaction should be enabled by default");
    assert!(config.threshold_tokens > 0, "threshold should be positive");
}

// ---------------------------------------------------------------------------
// Image content in compaction summary
// ---------------------------------------------------------------------------

fn user_with_image(id: &str, text: &str) -> Entry {
    Entry {
        id: id.into(),
        message: AgentMessage::Llm(Message::User(UserMessage {
            content: vec![
                InputContent::Text { text: text.into() },
                InputContent::Image {
                    source: ImageSource::Base64 {
                        data: "iVBORw0KGgo=".into(),
                    },
                    media_type: MediaType::Png,
                },
            ],
            timestamp_ms: 0,
        })),
    }
}

fn tool_result_with_image(id: &str, text: &str) -> Entry {
    Entry {
        id: id.into(),
        message: AgentMessage::Llm(Message::ToolResult(ToolResultMessage {
            tool_call_id: "tc_1".into(),
            tool_name: "screenshot".into(),
            content: vec![
                OutputContent::Text { text: text.into() },
                OutputContent::Image {
                    source: ImageSource::Bytes {
                        data: vec![0x89, 0x50, 0x4e, 0x47],
                    },
                    media_type: MediaType::Png,
                },
            ],
            details: None,
            is_error: false,
            timestamp_ms: 0,
        })),
    }
}

#[test]
fn compaction_summary_includes_image_placeholder_for_user_images() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    let entries = vec![
        user_with_image("e1", "Here is a screenshot"),
        assistant_text("e2", "I see the screenshot"),
    ];

    let result = engine
        .compact(&entries, CompactionReason::Manual, &DefaultCompactionHooks)
        .unwrap();

    let summary = &result.summary_text;
    assert!(
        summary.contains("[image: image/png]"),
        "summary should contain image placeholder, got: {summary}"
    );
}

#[test]
fn compaction_summary_includes_image_placeholder_for_tool_results() {
    let engine = CompactionEngine::new(CompactionConfig::default());
    let entries = vec![
        tool_result_with_image("e1", "Tool captured a screenshot"),
        assistant_text("e2", "I analyzed the screenshot"),
    ];

    let result = engine
        .compact(&entries, CompactionReason::Manual, &DefaultCompactionHooks)
        .unwrap();

    let summary = &result.summary_text;
    assert!(
        summary.contains("[image: image/png]"),
        "summary should contain image placeholder for tool result, got: {summary}"
    );
}