kaynine-core 0.1.0

Core agent loop, messages, events, policies, and provider abstractions for Kaynine
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
//! Context compaction (SPEC §10): trigger-threshold detection, oldest
//! contiguous turn-range selection, summary generation via a tool-free
//! provider request, and checkpoint payload assembly.

use crate::assembler::{Assembled, ResponseAssembler};
use crate::error::ProviderError;
use crate::ids::{EntryId, ModelId};
use crate::message::{ContentBlock, FinishReason, Message, Usage};
use crate::provider::{
    CredentialProvider, GenerationOptions, ModelMessage, ModelProvider, ModelRequest,
    ReasoningLevel,
};
use crate::store::SummaryRecord;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
use tokio_util::sync::CancellationToken;

/// Compaction thresholds and retry bounds (SPEC §10).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct CompactionConfig {
    /// Preemptive compaction trigger: compact once the measured input
    /// exceeds `trigger_ratio * available_tokens` even while Within.
    pub trigger_ratio: f64,
    /// Number of most-recent complete turns always kept verbatim.
    pub keep_recent_turns: usize,
    /// Upper bound on summary-generation attempts per compaction cycle.
    pub max_attempts: u32,
}

impl Default for CompactionConfig {
    fn default() -> Self {
        Self {
            trigger_ratio: 0.8,
            keep_recent_turns: 4,
            max_attempts: 3,
        }
    }
}

/// Selector input carried from the active run.
pub struct CompactionContext {
    pub current_model: ModelId,
}

/// Picks the model used for summary generation. v0.1 always issues the
/// summary request through the run's current provider; the selector only
/// names the model id on that request.
pub trait CompactionModelSelector: Send + Sync {
    fn select_model(&self, current: &ModelId) -> ModelId;
}

/// Identity selector: summarize with the model the run is already using.
pub struct CurrentModelSelector;

impl CompactionModelSelector for CurrentModelSelector {
    fn select_model(&self, current: &ModelId) -> ModelId {
        current.clone()
    }
}

/// Selects the oldest contiguous prefix of turns to summarize.
///
/// A turn boundary is the index of each `Message::User`; covering a prefix
/// that ends exactly at a turn boundary can never split a ToolCall from its
/// results (chain validation forbids a User message between them). Returns
/// `(cover_len, retain_from)`; both are the index of the first retained
/// turn's User message. Returns `None` when fewer than
/// `keep_recent_turns + 1` user turns exist (nothing compactable) or the
/// coverable prefix would be empty.
pub fn select_compaction_range(
    messages: &[Message],
    keep_recent_turns: usize,
) -> Option<(usize, usize)> {
    let user_indices: Vec<usize> = messages
        .iter()
        .enumerate()
        .filter_map(|(i, m)| matches!(m, Message::User { .. }).then_some(i))
        .collect();
    // Keeping zero turns is rejected: a compaction that retains nothing
    // (not even the current turn) is never useful.
    if keep_recent_turns == 0 || user_indices.len() < keep_recent_turns + 1 {
        return None;
    }
    let cover_len = *user_indices
        .get(user_indices.len() - keep_recent_turns)
        .expect("index guarded above");
    // Same value: everything before the first retained turn is covered.
    let retain_from = cover_len;
    (cover_len > 0).then_some((cover_len, retain_from))
}

/// Replaces `messages[..retain_from]` with a single `Message::Summary`.
/// Original messages are never mutated or dropped from persistence; this
/// only shapes the working context.
pub fn apply_summary(messages: &[Message], summary_text: &str, retain_from: usize) -> Vec<Message> {
    let mut out = Vec::with_capacity(1 + messages.len().saturating_sub(retain_from));
    out.push(Message::Summary {
        text: summary_text.to_string(),
    });
    out.extend(messages.iter().skip(retain_from).cloned());
    out
}

/// What the loop hands to `RunHooks::on_summary_checkpoint` (SPEC §10):
/// the runtime derives `covered_until_entry` from `covered_message_count`
/// via its message→entry mapping and persists the SummaryRecord.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SummaryPayload {
    pub text: String,
    pub covered_message_count: usize,
    pub retain_from: usize,
    /// Hash over the covered messages' serde serialization.
    pub source_hash: String,
    pub usage: Usage,
}

pub fn source_hash(covered: &[Message]) -> String {
    let mut hasher = DefaultHasher::new();
    for message in covered {
        if let Ok(json) = serde_json::to_string(message) {
            hasher.write(json.as_bytes());
        }
    }
    format!("{:016x}", hasher.finish())
}

const SUMMARY_SYSTEM_PROMPT: &str = "你是助手,请将以下对话历史压缩为保留关键信息(目标、已做决定、结果、未决事项)的摘要,直接输出摘要正文。";

/// Generates a summary of `covered` through a tool-free request to the
/// run's provider (v0.1 simplification: same provider, selector-chosen
/// model id). A Length/Invalid finish or empty text is a protocol error
/// (truncated summaries are never used); stream-establishment errors pass
/// through unchanged.
pub async fn generate_summary(
    provider: &dyn ModelProvider,
    credentials: &dyn CredentialProvider,
    cancel: CancellationToken,
    summary_model: &ModelId,
    covered: &[Message],
) -> Result<String, ProviderError> {
    let request = ModelRequest {
        model: summary_model.clone(),
        system_prompt: SUMMARY_SYSTEM_PROMPT.to_string(),
        messages: covered.iter().map(project_for_summary).collect(),
        tools: Vec::new(),
        reasoning: ReasoningLevel::Off,
        generation: GenerationOptions::default(),
        provider_options: serde_json::Value::Null,
    };

    let stream = tokio::select! {
        biased;
        _ = cancel.cancelled() => return Err(ProviderError::Cancelled),
        stream = provider.stream(request, credentials, cancel.clone()) => stream?,
    };

    let mut assembler = ResponseAssembler::new();
    let mut stream = stream;
    while let Some(item) = stream.next().await {
        match item {
            Ok(event) => {
                if let Err(error) = assembler.push(event) {
                    return Err(ProviderError::Protocol(format!("{error:?}")));
                }
            }
            Err(error) => return Err(error),
        }
    }
    match assembler.finalize() {
        Assembled::Complete {
            blocks,
            finish_reason: FinishReason::Stop,
            ..
        } => {
            let text = blocks
                .iter()
                .filter_map(|b| match b {
                    ContentBlock::Text { text } => Some(text.as_str()),
                    _ => None,
                })
                .collect::<Vec<_>>()
                .join("");
            if text.trim().is_empty() {
                Err(ProviderError::Protocol(
                    "summary truncated or invalid".into(),
                ))
            } else {
                Ok(text)
            }
        }
        _ => Err(ProviderError::Protocol(
            "summary truncated or invalid".into(),
        )),
    }
}

/// Text-only projection of covered messages for the summary request: drops
/// tool calls, reasoning blocks, and images; keeps the conversation shape
/// as alternating user/assistant text.
fn project_for_summary(message: &Message) -> ModelMessage {
    match message {
        Message::User { blocks } => ModelMessage::User {
            blocks: blocks
                .iter()
                .filter(|b| matches!(b, ContentBlock::Text { .. }))
                .cloned()
                .collect(),
        },
        Message::Assistant { blocks, .. } => {
            let texts: Vec<ContentBlock> = blocks
                .iter()
                .filter_map(|b| match b {
                    ContentBlock::Text { text } => Some(ContentBlock::Text { text: text.clone() }),
                    _ => None,
                })
                .collect();
            ModelMessage::Assistant {
                blocks: if texts.is_empty() {
                    vec![ContentBlock::Text {
                        text: "(调用了工具)".into(),
                    }]
                } else {
                    texts
                },
            }
        }
        Message::ToolResult { results } => ModelMessage::User {
            blocks: vec![ContentBlock::Text {
                text: format!(
                    "(工具结果) {}",
                    results
                        .iter()
                        .map(|r| r.text.as_str())
                        .collect::<Vec<_>>()
                        .join("\n")
                ),
            }],
        },
        Message::Summary { text } => ModelMessage::Summary { text: text.clone() },
    }
}

/// Finds the latest persisted checkpoint that still applies to the loaded
/// chain: its `covered_until_entry` must be one of `entry_ids` (a fork that
/// dropped the covered prefix invalidates it).
pub fn latest_valid_summary<'a>(
    entry_ids: &[EntryId],
    summaries: &'a [SummaryRecord],
) -> Option<(usize, &'a SummaryRecord)> {
    summaries.iter().enumerate().rev().find_map(|(_i, record)| {
        let position = entry_ids
            .iter()
            .position(|id| *id == record.covered_until_entry)?;
        Some((position, record))
    })
}

/// Restores the working context from the latest valid checkpoint:
/// `[Summary] + messages after the covered entry`. Returns the input
/// unchanged when no checkpoint applies.
pub fn apply_latest_valid_summary(
    messages: &[Message],
    entry_ids: &[EntryId],
    summaries: &[SummaryRecord],
) -> Vec<Message> {
    match latest_valid_summary(entry_ids, summaries) {
        Some((position, record)) => {
            let mut out = Vec::with_capacity(1 + messages.len().saturating_sub(position + 1));
            out.push(Message::Summary {
                text: record.text.clone(),
            });
            out.extend(messages.iter().skip(position + 1).cloned());
            out
        }
        None => messages.to_vec(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ids::ToolCallId;
    use crate::ids::{BranchId, ProviderId};
    use crate::message::{FinishReason, ToolResultPayload};
    use crate::provider::ProviderEvent;
    use crate::testing::{FakeCredentialProvider, FakeProvider};

    fn user(text: &str) -> Message {
        Message::User {
            blocks: vec![ContentBlock::Text { text: text.into() }],
        }
    }

    fn assistant_text(text: &str) -> Message {
        Message::Assistant {
            blocks: vec![ContentBlock::Text { text: text.into() }],
            finish_reason: FinishReason::Stop,
            truncated: false,
        }
    }

    fn assistant_tool_call(id: &str) -> Message {
        Message::Assistant {
            blocks: vec![ContentBlock::ToolCall {
                id: ToolCallId::from(id),
                name: "t".into(),
                arguments: serde_json::json!({}),
            }],
            finish_reason: FinishReason::Stop,
            truncated: false,
        }
    }

    fn results(ids: &[&str]) -> Message {
        Message::ToolResult {
            results: ids
                .iter()
                .map(|id| ToolResultPayload {
                    call_id: ToolCallId::from(*id),
                    is_error: false,
                    text: "ok".into(),
                })
                .collect(),
        }
    }

    fn alternating(turns: usize) -> Vec<Message> {
        let mut out = Vec::new();
        for i in 0..turns {
            out.push(user(&format!("q{i}")));
            out.push(assistant_text(&format!("a{i}")));
        }
        out
    }

    fn caps() -> crate::provider::ModelCapabilities {
        crate::provider::ModelCapabilities {
            context_tokens: 200_000,
            max_output_tokens: 8_192,
            supports_tools: true,
            supports_images: true,
            supports_reasoning: true,
        }
    }

    fn text_events(text: &str, finish: FinishReason) -> Vec<ProviderEvent> {
        vec![
            ProviderEvent::ResponseStarted,
            ProviderEvent::TextDelta {
                block: 0,
                text: text.into(),
            },
            ProviderEvent::ResponseCompleted {
                finish_reason: finish,
            },
        ]
    }

    #[test]
    fn config_defaults_match_spec() {
        let config = CompactionConfig::default();
        assert_eq!(config.trigger_ratio, 0.8);
        assert_eq!(config.keep_recent_turns, 4);
        assert_eq!(config.max_attempts, 3);
        let json = serde_json::to_string(&config).unwrap();
        assert_eq!(
            serde_json::from_str::<CompactionConfig>(&json).unwrap(),
            config
        );
    }

    #[test]
    fn range_six_turns_keep_four_covers_two() {
        let history = alternating(6);
        let (cover, retain) = select_compaction_range(&history, 4).expect("compactable");
        assert_eq!(cover, 4);
        assert_eq!(retain, 4);
        assert!(matches!(history[cover], Message::User { .. }));
    }

    #[test]
    fn range_five_turns_keep_four_covers_one_turn() {
        let history = alternating(5);
        let (cover, _) = select_compaction_range(&history, 4).expect("compactable");
        assert_eq!(cover, 2); // first turn only
    }

    #[test]
    fn range_four_turns_keep_four_is_none() {
        assert!(select_compaction_range(&alternating(4), 4).is_none());
    }

    #[test]
    fn range_keep_more_than_turns_is_none() {
        assert!(select_compaction_range(&alternating(2), 5).is_none());
    }

    #[test]
    fn range_boundary_never_splits_tool_pairs() {
        // Turn shape: U, A(tool c1), R(c1) — the User of the next turn is
        // the only legal cut point, so any boundary must land on a User.
        let history = vec![
            user("q0"),
            assistant_tool_call("c1"),
            results(&["c1"]),
            user("q1"),
            assistant_tool_call("c2"),
            results(&["c2"]),
            user("q2"),
            assistant_tool_call("c3"),
            results(&["c3"]),
            user("q3"),
            assistant_text("a3"),
        ];
        for keep in 1..=3 {
            if let Some((cover, _)) = select_compaction_range(&history, keep) {
                assert!(
                    matches!(history[cover], Message::User { .. }),
                    "boundary at {cover} must be a User message"
                );
                // The message before the boundary must not be a dangling
                // tool call: it is a User, Assistant(text-only) or a
                // complete ToolResult batch (validated by projection).
                let covered = &history[..cover];
                assert!(
                    crate::chain::project_and_validate(covered).is_ok(),
                    "covered prefix must project as a valid chain"
                );
            }
        }
        let (cover, _) = select_compaction_range(&history, 2).expect("compactable");
        assert_eq!(cover, 6); // q0..q1 turns covered (6 messages)
    }

    #[test]
    fn apply_summary_shapes_working_context() {
        let history = alternating(3);
        let out = apply_summary(&history, "摘要", 4);
        assert_eq!(out.len(), 1 + (6 - 4));
        assert!(matches!(&out[0], Message::Summary { text } if text == "摘要"));
        assert_eq!(out[1], history[4]);
    }

    #[tokio::test]
    async fn generate_summary_returns_joined_text() {
        let provider = FakeProvider::new(caps());
        provider.push_events(text_events("目标:测试", FinishReason::Stop));
        let creds = FakeCredentialProvider::default();
        let text = generate_summary(
            &provider,
            &creds,
            CancellationToken::new(),
            &ModelId::from("sum-model"),
            &alternating(3),
        )
        .await
        .expect("summary ok");
        assert_eq!(text, "目标:测试");
        let request = &provider.requests()[0];
        assert_eq!(request.model, ModelId::from("sum-model"));
        assert!(request.tools.is_empty());
        assert_eq!(request.reasoning, ReasoningLevel::Off);
        assert!(request.system_prompt.contains("摘要"));
        assert_eq!(request.messages.len(), 6);
    }

    #[tokio::test]
    async fn generate_summary_length_finish_is_protocol_error() {
        let provider = FakeProvider::new(caps());
        provider.push_events(text_events("截断", FinishReason::Length));
        let err = generate_summary(
            &provider,
            &FakeCredentialProvider::default(),
            CancellationToken::new(),
            &ModelId::from("m"),
            &alternating(2),
        )
        .await
        .expect_err("length must fail");
        assert!(matches!(err, ProviderError::Protocol(_)));
    }

    #[tokio::test]
    async fn generate_summary_passes_provider_error_through() {
        let provider = FakeProvider::new(caps());
        provider.push_error(ProviderError::Network("down".into()));
        let err = generate_summary(
            &provider,
            &FakeCredentialProvider::default(),
            CancellationToken::new(),
            &ModelId::from("m"),
            &alternating(2),
        )
        .await
        .expect_err("provider error passes through");
        assert!(matches!(err, ProviderError::Network(_)));
    }

    #[tokio::test]
    async fn summary_projection_flattens_tools() {
        let provider = FakeProvider::new(caps());
        provider.push_events(text_events("s", FinishReason::Stop));
        let covered = vec![user("q"), assistant_tool_call("c1"), results(&["c1"])];
        generate_summary(
            &provider,
            &FakeCredentialProvider::default(),
            CancellationToken::new(),
            &ModelId::from("m"),
            &covered,
        )
        .await
        .unwrap();
        let messages = &provider.requests()[0].messages;
        assert_eq!(messages.len(), 3);
        assert!(matches!(&messages[1], ModelMessage::Assistant { blocks }
            if matches!(&blocks[0], ContentBlock::Text { text } if text == "(调用了工具)")));
        assert!(matches!(&messages[2], ModelMessage::User { blocks }
            if matches!(&blocks[0], ContentBlock::Text { text } if text.starts_with("(工具结果)"))));
    }

    fn summary_record(entry: &str, text: &str) -> SummaryRecord {
        SummaryRecord {
            summary_id: format!("summary-{entry}"),
            branch_id: BranchId::from("b1"),
            covered_until_entry: EntryId::from(entry),
            text: text.to_string(),
            source_hash: "h".to_string(),
            provider: ProviderId::from("fake"),
            model: ModelId::from("m"),
            prompt_version: String::new(),
            usage: Usage::default(),
        }
    }

    #[test]
    fn latest_valid_summary_prefers_latest_applicable() {
        let entry_ids: Vec<EntryId> = (0..4).map(|i| EntryId::from(format!("e{i}"))).collect();
        let messages: Vec<Message> = entry_ids
            .iter()
            .enumerate()
            .map(|(i, _)| {
                if i % 2 == 0 {
                    user(&format!("q{i}"))
                } else {
                    assistant_text("a")
                }
            })
            .collect();
        let summaries = vec![
            summary_record("e1", "旧摘要"),
            summary_record("e9", "不在链上"),
            summary_record("e2", "新摘要"),
        ];
        let out = apply_latest_valid_summary(&messages, &entry_ids, &summaries);
        assert_eq!(out.len(), 1 + (4 - 3));
        assert!(matches!(&out[0], Message::Summary { text } if text == "新摘要"));
        assert_eq!(out[1], messages[3]);
    }

    #[test]
    fn latest_valid_summary_none_when_covered_entry_missing() {
        let entry_ids = vec![EntryId::from("e0"), EntryId::from("e1")];
        let messages = vec![user("q0"), assistant_text("a0")];
        let summaries = vec![summary_record("e9", "陈旧")];
        let out = apply_latest_valid_summary(&messages, &entry_ids, &summaries);
        assert_eq!(out, messages);
    }

    #[test]
    fn source_hash_is_stable_and_sensitive() {
        let covered = alternating(2);
        assert_eq!(source_hash(&covered), source_hash(&covered));
        let mut other = covered.clone();
        other[0] = user("different");
        assert_ne!(source_hash(&covered), source_hash(&other));
    }

    #[test]
    fn current_model_selector_is_identity() {
        let model = ModelId::from("m1");
        assert_eq!(CurrentModelSelector.select_model(&model), model);
        let _context = CompactionContext {
            current_model: model.clone(),
        };
    }
}