A tiny, local-first CLI that finds the files your AI coding agent actually needs — and packs them into a focused context.
| 1 | """Fast approximate token estimation. |
| 2 | |
| 3 | This module does **not** use a real tokenizer. Estimates are based on a |
| 4 | characters/4 heuristic that works reasonably for English prose and source |
| 5 | code. Treat all values as approximate guidance for context budgeting. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | from pathlib import Path |
| 11 | |
| 12 | # Characters per estimated token. Empirically reasonable for mixed code/prose. |
| 13 | CHARS_PER_TOKEN = 4.0 |
| 14 | |
| 15 | # Cap how much of a huge file we read just to estimate tokens. |
| 16 | _MAX_READ_BYTES = 2_000_000 |
| 17 | |
| 18 | |
| 19 | def estimate_tokens_from_text(text: str) -> int: |
| 20 | """Estimate tokens from a Unicode string. |
| 21 | |
| 22 | Empty / whitespace-only text returns 0. |
| 23 | """ |
| 24 | if not text or not text.strip(): |
| 25 | return 0 |
| 26 | # Normalize newlines so CRLF vs LF does not skew estimates. |
| 27 | normalized = text.replace("\r\n", "\n").replace("\r", "\n") |
| 28 | return max(1, int(round(len(normalized) / CHARS_PER_TOKEN))) |
| 29 | |
| 30 | |
| 31 | def estimate_tokens_from_bytes(data: bytes) -> int: |
| 32 | """Estimate tokens from raw bytes, decoding as UTF-8 with replacement.""" |
| 33 | if not data: |
| 34 | return 0 |
| 35 | text = data.decode("utf-8", errors="replace") |
| 36 | return estimate_tokens_from_text(text) |
| 37 | |
| 38 | |
| 39 | def estimate_tokens_from_file(path: Path, *, max_bytes: int = _MAX_READ_BYTES) -> int: |
| 40 | """Estimate tokens for a file without loading unbounded content. |
| 41 | |
| 42 | If the file is larger than ``max_bytes``, the estimate is extrapolated |
| 43 | from the sample that was read. |
| 44 | """ |
| 45 | try: |
| 46 | size = path.stat().st_size |
| 47 | except OSError: |
| 48 | return 0 |
| 49 | |
| 50 | if size == 0: |
| 51 | return 0 |
| 52 | |
| 53 | try: |
| 54 | with path.open("rb") as fh: |
| 55 | sample = fh.read(max_bytes) |
| 56 | except OSError: |
| 57 | return 0 |
| 58 | |
| 59 | sample_tokens = estimate_tokens_from_bytes(sample) |
| 60 | if size <= max_bytes or not sample: |
| 61 | return sample_tokens |
| 62 | |
| 63 | # Extrapolate linearly from the sample. |
| 64 | ratio = size / len(sample) |
| 65 | return max(1, int(round(sample_tokens * ratio))) |
| 66 | |
| 67 | |
| 68 | def format_int(n: int) -> str: |
| 69 | """Format an integer with thousands separators.""" |
| 70 | return f"{n:,}" |