Skip to main content

agentmux_common/
tokens.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The token estimate every AgentMux surface shows, labelled "~N tok (est.)":
5//! ⌈Unicode scalar values ÷ 4⌉. The frontend's `estimateTokenCount`
6//! (`frontend/util/format-count.ts`) counts the same way, and both test the
7//! same vector, so the Memory pane, the context delivery card and the
8//! reinjection card agree to the token (SPEC_MEMORY_PANE_TOKENS_2026_10_15.md
9//! §4.1).
10
11/// Estimated tokens in `text`.
12pub fn estimate_tokens(text: &str) -> u64 {
13    tokens_for_chars(text.chars().count() as u64)
14}
15
16/// Estimated tokens in a text of `chars` Unicode scalar values.
17pub fn tokens_for_chars(chars: u64) -> u64 {
18    chars.div_ceil(4)
19}
20
21/// Lines in `text`, as `str::lines` counts them: a final line needs no
22/// newline, and an empty text has none.
23pub fn count_lines(text: &str) -> u64 {
24    text.lines().count() as u64
25}
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30
31    /// The vector `frontend/util/format-count.test.ts` checks too.
32    pub(crate) const VECTOR: &[(&str, u64)] = &[
33        ("", 0),
34        ("abcd", 1),
35        ("abcde", 2),
36        ("héllo", 2),
37        ("日本語テキスト", 2),
38        ("🙂🙂🙂🙂", 1),
39        ("e\u{301}e\u{301}", 1),
40        ("# Memory\n\nOne line.\n", 5),
41    ];
42
43    #[test]
44    fn the_estimate_is_scalar_values_over_four_rounded_up() {
45        for (text, tokens) in VECTOR {
46            assert_eq!(estimate_tokens(text), *tokens, "{text:?}");
47        }
48    }
49
50    #[test]
51    fn lines_count_like_str_lines() {
52        assert_eq!(count_lines(""), 0);
53        assert_eq!(count_lines("a"), 1);
54        assert_eq!(count_lines("a\n"), 1);
55        assert_eq!(count_lines("a\nb"), 2);
56        assert_eq!(count_lines("a\r\nb\n"), 2);
57        assert_eq!(count_lines("\n"), 1);
58    }
59}