yk-core 0.1.0

The agent loop and the vocabulary every other crate speaks
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
//! How big a conversation is, when it is too big, and how to summarize it.
//!
//! The size questions are pure arithmetic. The summary is a provider call, which
//! `yk-core` can make because `Provider` is one of its own traits, and it lives
//! here rather than in the binary so the terminal interface and print mode can
//! both ask for one.

use std::fmt::Write as _;

use crate::{Message, Provider, Result};

/// Tokens kept below the model's window for the summary request and the answer.
///
/// Compaction is not free: it sends the branch to the model, and the summary it
/// gets back is part of the next request too. A fixed reserve is simpler to
/// reason about than a fraction and does not move when the window does.
const SUMMARY_RESERVE_TOKENS: u64 = 32_768;

/// The rule-of-thumb ratio between bytes and tokens, used both to measure a
/// conversation and to size the summary request's budget. One constant, so the
/// two cannot drift apart.
const BYTES_PER_TOKEN: u64 = 4;

/// What decides when a conversation is compacted.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CompactSettings {
    /// The model's context window, in tokens.
    pub context_window: u64,
}

impl CompactSettings {
    /// The token count at which compaction runs.
    ///
    /// Saturating rather than subtracting: a window smaller than the reserve is
    /// nonsense, and the honest answer for it is a threshold of zero, which
    /// compacts at the next opportunity instead of underflowing.
    #[must_use]
    pub const fn threshold(&self) -> u64 {
        self.context_window.saturating_sub(SUMMARY_RESERVE_TOKENS)
    }
}

/// Whether `tokens` is at or past the threshold.
#[must_use]
pub const fn should_compact(settings: &CompactSettings, tokens: u64) -> bool {
    tokens >= settings.threshold()
}

/// A rough token count for a conversation.
///
/// Four bytes per token is the rule of thumb for English text and code, and it is
/// what pi falls back to when it has no usage to read. The number only decides
/// whether to compact, so being wrong by a fifth changes when that happens
/// rather than whether it works.
///
/// Tool call names and arguments count, because a long `write` argument is as
/// large on the wire as a long message and the point is to measure the request.
#[must_use]
pub fn estimate_tokens(messages: &[Message]) -> u64 {
    let mut bytes: u64 = 0;
    for message in messages {
        bytes = bytes.saturating_add(message_bytes(message));
    }
    bytes / BYTES_PER_TOKEN
}

/// One message's contribution to [`estimate_tokens`], in bytes.
///
/// Split out because [`summary_request_messages`] budgets the same way per message, and a
/// second measure of the same thing is how the two would disagree.
fn message_bytes(message: &Message) -> u64 {
    let mut bytes = byte_len(message.text());
    if let Message::Assistant { tool_calls, .. } = message {
        for call in tool_calls {
            bytes = bytes.saturating_add(byte_len(&call.name));
            bytes = bytes.saturating_add(byte_len(&call.arguments));
        }
    }
    bytes
}

/// A string's length in bytes, as a `u64`.
fn byte_len(text: &str) -> u64 {
    u64::try_from(text.len()).unwrap_or(u64::MAX)
}

/// The tail of `history` a summary request may carry.
///
/// The summary *request* is the branch, so the branch is what has to fit. Sizing
/// the reserve for the answer while sending the branch unbounded is how a
/// summariser got asked for more than the model's window and refused, and a
/// refusal there used to end the turn before the prompt was appended.
///
/// The tail is kept rather than the head, because the recent turns are the ones
/// the work continues from. The last message is always included even when it
/// alone exceeds the budget, because a summary of nothing is worse than one
/// summary request that is still too large; [`summarize_if_needed`] is what
/// keeps that case from wedging the session.
///
/// Known limit: `bytes >> 2` undercounts. Real tokenizers run nearer 2.5 to 3.5
/// characters per token on source, so this budget can still overshoot. The
/// upgrade is a real tokenizer behind a feature flag, which is a dependency and a
/// decision; leaving room below the threshold and failing open cover it for now.
#[must_use]
pub fn summary_request_messages<'a>(
    history: &'a [Message],
    settings: &CompactSettings,
) -> &'a [Message] {
    let budget = settings
        .threshold()
        .saturating_sub(SUMMARY_RESERVE_TOKENS)
        .saturating_mul(BYTES_PER_TOKEN);

    let mut used: u64 = 0;
    let mut start = history.len();
    for (index, message) in history.iter().enumerate().rev() {
        let cost = message_bytes(message);
        if used.saturating_add(cost) > budget && start != history.len() {
            break;
        }
        used = used.saturating_add(cost);
        start = index;
    }
    history.get(start..).unwrap_or_default()
}

/// The instruction the summarizer is given.
///
/// A different system prompt from yk's own, because this is a different job with
/// a different output. The model is not continuing the work, it is writing down
/// what happened so the work can continue without the transcript.
const SUMMARIZER_SYSTEM_PROMPT: &str = "\
You summarize a coding session so it can continue without the earlier messages. \
Write what was asked, what was done, what was decided, and what is still open. \
Keep file paths, commands, and names exact. Do not add advice or commentary. \
Answer with the summary alone.";

/// What compaction did.
///
/// A refusal is a variant rather than an `Err` because refusing to continue is a
/// worse answer than a session that is still too big, and every caller used to
/// make that choice by propagating.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CompactionOutcome {
    /// The branch was small enough and nothing was sent.
    NotNeeded,
    /// The branch was shadowed by this summary.
    Summarized(String),
    /// It was needed, the summariser was refused, and the branch is untouched.
    ///
    /// The reason is the provider's own message, which is the only thing that
    /// says why, or a note that the answer was empty. Leaving the branch alone
    /// is the point: shadowing it with an empty summary would lose the
    /// transcript to fix a size problem.
    ///
    /// A provider that answers with nothing counts as a refusal rather than a
    /// success. It is reachable, through a stream carrying no content deltas,
    /// and `Session::compact` replaces the whole active branch with whatever it
    /// is handed, so `Summarized("")` would drop the transcript on exactly the
    /// principle this variant refuses.
    Refused(String),
}

/// Ask for a summary only when the branch is too big, and never fail the caller.
///
/// A summariser refused for context length used to end the turn before the
/// prompt was appended. The next prompt re-detected the same oversize branch and
/// was refused identically, the session never advanced, and the only way out was
/// `/new`. That is a soft degradation turned into a dead session, and it is why
/// this reports rather than propagates.
pub async fn summarize_if_needed(
    provider: &dyn Provider,
    settings: &CompactSettings,
    history: &[Message],
) -> CompactionOutcome {
    if !should_compact(settings, estimate_tokens(history)) {
        return CompactionOutcome::NotNeeded;
    }

    match summarize_history(provider, summary_request_messages(history, settings)).await {
        Ok(summary) if summary.trim().is_empty() => {
            CompactionOutcome::Refused("the summariser answered with nothing".to_owned())
        }
        Ok(summary) => CompactionOutcome::Summarized(summary),
        Err(error) => CompactionOutcome::Refused(error.to_string()),
    }
}

/// Ask the model for a summary of `history`.
///
/// The caller clamps with [`summary_request_messages`] first. That is the whole of why this
/// does not clamp itself: the question "what may be sent" belongs with the one
/// place that knows the window, and a second clamp here would be a second answer.
///
/// # Errors
///
/// Whatever the provider returns.
pub async fn summarize_history(provider: &dyn Provider, history: &[Message]) -> Result<String> {
    let request = vec![Message::user(format!(
        "Summarize this session.\n\n{}",
        render_transcript(history)
    ))];

    let mut sink = crate::DiscardSink;
    let turn = provider
        .send(SUMMARIZER_SYSTEM_PROMPT, &request, &[], &mut sink)
        .await?;
    Ok(turn.text)
}

/// Ask for a summary of `history` whether or not it is too big.
///
/// The `/compact` path: a person asking for a summary gets one, and refusing
/// because the branch happens to be small would answer a different question. The
/// clamp is applied here so no caller has to remember it.
///
/// # Errors
///
/// Whatever the provider returns.
pub async fn summarize_now(
    provider: &dyn Provider,
    settings: &CompactSettings,
    history: &[Message],
) -> Result<String> {
    summarize_history(provider, summary_request_messages(history, settings)).await
}

/// Render a conversation as labelled lines for the summarizer.
///
/// The transcript the model is being asked to replace, written out plainly. Tool
/// calls are included because a summary that omits what the tools returned is a
/// summary of the conversation rather than of the work.
fn render_transcript(history: &[Message]) -> String {
    let mut out = String::new();
    for message in history {
        let _ = writeln!(out, "{}: {}", message.role().as_str(), message.text());

        if let Message::Assistant { tool_calls, .. } = message {
            for call in tool_calls {
                let _ = writeln!(out, "  called {}({})", call.name, call.arguments);
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::indexing_slicing,
        clippy::as_conversions,
        clippy::arithmetic_side_effects
    )]

    use super::{
        CompactSettings, CompactionOutcome, SUMMARY_RESERVE_TOKENS, estimate_tokens,
        should_compact, summarize_if_needed, summary_request_messages,
    };
    use crate::{AssistantToolCall, Message, Turn};

    /// A provider that refuses every request, the way an endpoint refuses a
    /// request larger than its window.
    struct Refuses;

    #[async_trait::async_trait]
    impl crate::Provider for Refuses {
        async fn send(
            &self,
            _system: &str,
            _history: &[Message],
            _tools: &[crate::ToolDef],
            _sink: &mut (dyn crate::TextSink + Send),
        ) -> crate::Result<Turn> {
            Err(crate::Error::Provider(
                "maximum context length exceeded".to_owned(),
            ))
        }
    }

    /// A branch of `count` messages, each `size` bytes of text.
    fn branch(count: usize, size: usize) -> Vec<Message> {
        (0..count)
            .map(|_| Message::user("x".repeat(size)))
            .collect()
    }

    #[test]
    fn a_summary_request_carries_only_what_fits() {
        // The wedge, in one number, at a window where the budget is genuinely
        // positive. A smaller window would compute a budget of zero and the
        // result would come entirely from the always-keep-the-last-message
        // guard rather than from budgeting, which is what the earlier version
        // of this test actually measured while claiming otherwise.
        let settings = CompactSettings {
            context_window: 200_000,
        };
        // 20 x 40_000 bytes = 200_000 tokens, past the 167_232 threshold.
        let history = branch(20, 40_000);
        assert!(
            estimate_tokens(&history) >= settings.threshold(),
            "the branch is due a summary: {}",
            estimate_tokens(&history)
        );

        let fitted = summary_request_messages(&history, &settings);
        assert!(
            fitted.len() < history.len() && fitted.len() > 1,
            "clamped part way, not to a single message: {} of {}",
            fitted.len(),
            history.len()
        );
        assert!(
            estimate_tokens(fitted) <= settings.threshold(),
            "what is sent must fit: {} against {}",
            estimate_tokens(fitted),
            settings.threshold()
        );
        assert_eq!(
            fitted.last().map(|m| m.text().len()),
            Some(40_000),
            "the newest message is always kept"
        );
    }

    #[test]
    fn a_branch_that_fits_is_not_shortened() {
        let settings = CompactSettings {
            context_window: 200_000,
        };
        let history = branch(3, 100);
        assert_eq!(summary_request_messages(&history, &settings), &history[..]);
    }

    /// A provider that answers successfully with no text at all, which a stream
    /// carrying no content deltas produces.
    struct SaysNothing;

    #[async_trait::async_trait]
    impl crate::Provider for SaysNothing {
        async fn send(
            &self,
            _system: &str,
            _history: &[Message],
            _tools: &[crate::ToolDef],
            _sink: &mut (dyn crate::TextSink + Send),
        ) -> crate::Result<Turn> {
            Ok(Turn::default())
        }
    }

    #[tokio::test]
    async fn an_empty_summary_is_a_refusal_rather_than_a_silent_loss() {
        // `Session::compact` replaces the whole branch with whatever it is
        // handed, so a successful-but-empty answer would drop the transcript to
        // fix a size problem. That is the trade `CompactionOutcome::Refused` exists to
        // refuse, so it applies to this variant too.
        let settings = CompactSettings {
            context_window: 40_000,
        };
        let history = branch(40, 4_000);

        let outcome = summarize_if_needed(&SaysNothing, &settings, &history).await;

        assert!(
            matches!(outcome, CompactionOutcome::Refused(_)),
            "an empty summary must not shadow the branch: {outcome:?}"
        );
    }

    #[test]
    fn a_branch_smaller_than_the_budget_still_yields_its_last_message() {
        // A summary of nothing is worse than one request that is still too big,
        // and the caller decides what to do about the second.
        let settings = CompactSettings {
            context_window: 4_096,
        };
        let history = branch(2, 8_000);
        let fitted = summary_request_messages(&history, &settings);
        assert_eq!(fitted.len(), 1);
    }

    #[tokio::test]
    async fn a_refused_summariser_is_reported_rather_than_propagated() {
        // The property that keeps a session alive: compaction failing must not
        // end the turn. Propagating it meant the prompt was never appended, the
        // next prompt met the same refusal, and only `/new` recovered.
        let settings = CompactSettings {
            context_window: 40_000,
        };
        let history = branch(40, 4_000);

        let outcome = summarize_if_needed(&Refuses, &settings, &history).await;

        assert!(
            matches!(outcome, CompactionOutcome::Refused(_)),
            "a refusal must be a variant, not an error: {outcome:?}"
        );
        let CompactionOutcome::Refused(reason) = &outcome else {
            // The assertion above has already said what is wrong. Returning here
            // only keeps the panic lints honest about there being no other way
            // out of a failed assertion.
            return;
        };
        assert!(
            reason.contains("maximum context length"),
            "the provider's own reason is kept: {reason}"
        );
    }

    #[tokio::test]
    async fn a_branch_that_does_not_need_compaction_sends_nothing() {
        let settings = CompactSettings {
            context_window: 200_000,
        };
        let outcome = summarize_if_needed(&Refuses, &settings, &branch(3, 100)).await;

        assert_eq!(outcome, CompactionOutcome::NotNeeded);
    }

    #[test]
    fn the_threshold_leaves_room_below_the_window() {
        let settings = CompactSettings {
            context_window: 200_000,
        };
        assert_eq!(settings.threshold(), 200_000 - SUMMARY_RESERVE_TOKENS);
    }

    #[test]
    fn a_window_smaller_than_the_reserve_has_a_zero_threshold() {
        assert_eq!(CompactSettings { context_window: 10 }.threshold(), 0);
    }

    #[test]
    fn compaction_is_due_at_the_threshold_not_only_after_it() {
        let settings = CompactSettings {
            context_window: 100_000,
        };
        assert!(!should_compact(&settings, settings.threshold() - 1));
        assert!(should_compact(&settings, settings.threshold()));
    }

    #[test]
    fn an_empty_conversation_costs_nothing() {
        assert_eq!(estimate_tokens(&[]), 0);
    }

    #[test]
    fn four_bytes_are_roughly_one_token() {
        assert_eq!(estimate_tokens(&[Message::user("x".repeat(400))]), 100);
    }

    #[test]
    fn tool_arguments_count_toward_the_size() {
        let call = AssistantToolCall {
            id: "c1".to_owned(),
            name: "read".to_owned(),
            arguments: "{\"path\":\"a\"}".to_owned(),
        };
        let with = estimate_tokens(&[Message::assistant_with_calls("", vec![call])]);
        let without = estimate_tokens(&[Message::assistant("")]);

        assert!(with > without, "{with} should exceed {without}");
    }
}