add offline-compact
#2
by lamlt - opened
Files changed (3)
- offline-compact/compact.pyAdded+634
- offline-compact/describe.mdAdded+8
- offline-compact/ext.pyAdded+47
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634#!/usr/bin/env python3"""Session Compactor - compact agent session text right in your terminal.
Usage: python3 compact.py
- Works offline: no API, no third-party packages (Python 3.7+).- Language-agnostic: Latin, Vietnamese, CJK, Thai, Arabic, Cyrillic, Indic, ...- Works on Windows, macOS and Linux.
Type or paste text at the ">" prompt and press Enter.Type "/" to see slash commands."""
import base64import mathimport osimport reimport shutilimport subprocessimport sysimport timeimport unicodedatafrom collections import Counterfrom functools import lru_cache
try: # line editing, history and tab completion (macOS / Linux) import readlineexcept ImportError: # Windows readline = None
# --------------------------------------------------------------------------# Settings# --------------------------------------------------------------------------
AUTO_RATIO = 0.35 # target size when /max_token is not setMIN_AUTO_TOKENS = 40 # very short inputs are left almost untouchedNEAR_DUP_JACCARD = 0.70 # sentences more similar than this are redundant
COMMANDS = [ ("/max_token", "<n|off>", "Set the max tokens of the compacted output"), ("/copy", "", "Copy the last compacted output to the clipboard"), ("/help", "", "Show this help"), ("/exit", "", "Quit"),]
GREEN = "\033[32m"DIM = "\033[2m"RESET = "\033[0m"USE_COLOR = sys.stdout.isatty() and "NO_COLOR" not in os.environ
def paint(text, color): return f"{color}{text}{RESET}" if USE_COLOR else text
# --------------------------------------------------------------------------# Token estimation (offline, works for any language)# --------------------------------------------------------------------------# Heuristic similar to BPE tokenizers:# * ASCII letters ~ 4 chars / token# * other letters ~ 2.5 chars / token (accents, Cyrillic, Arabic, ...)# * digits ~ 3 chars / token# * CJK / Hangul ~ 1 token / char# * Thai, Lao, Khmer, Myanmar ~ 2 chars / token# * punctuation ~ 1 token / char, emoji ~ 2 tokens
def _is_cjk(o): return ( 0x3040 <= o <= 0x30FF or 0x3400 <= o <= 0x4DBF or 0x4E00 <= o <= 0x9FFF or 0xAC00 <= o <= 0xD7AF or 0xF900 <= o <= 0xFAFF or 0x20000 <= o <= 0x2FA1F )
@lru_cache(maxsize=65536)def _char_kind(ch): o = ord(ch) if ch == "\n": return "nl", 0.0 if ch.isspace(): return "sp", 0.0 if _is_cjk(o): return "cjk", 1.0 if 0xFE00 <= o <= 0xFE0F or o == 0x200D: return "zero", 0.0 cat = unicodedata.category(ch) if cat[0] in "LM" or ch == "_": if o < 128: return "w", 0.25 if 0x0E00 <= o <= 0x109F or 0x1780 <= o <= 0x17FF: return "w", 0.5 return "w", 0.4 if cat[0] == "N": return "w", 0.34 if cat in ("Cc", "Cf", "Cs", "Co"): return "zero", 0.0 if o >= 0x1F000 or 0x2600 <= o <= 0x27BF: return "sym", 2.0 return "sym", 1.0
def count_tokens(text): """Estimate the number of LLM tokens in `text`.""" text = unicodedata.normalize("NFC", text) total = 0.0 acc = 0.0 prev_nl = False for ch in text: kind, weight = _char_kind(ch) if kind == "w": acc += weight prev_nl = False continue if kind == "zero": continue if acc: total += max(1, math.ceil(acc - 1e-9)) acc = 0.0 if kind == "nl": if not prev_nl: total += 1 prev_nl = True continue prev_nl = False if kind == "sp": continue total += weight if acc: total += max(1, math.ceil(acc - 1e-9)) return int(math.ceil(total))
def truncate_to_tokens(text, limit): if limit <= 0: return "" if count_tokens(text) <= limit: return text lo, hi = 0, len(text) while lo < hi: mid = (lo + hi + 1) // 2 if count_tokens(text[:mid].rstrip() + "…") <= limit: lo = mid else: hi = mid - 1 return text[:lo].rstrip() + "…" if lo else ""
# --------------------------------------------------------------------------# Compaction (extractive, language-agnostic, fully offline)# --------------------------------------------------------------------------
_CJKLIKE = ( r"\u0e00-\u0eff\u1000-\u109f\u1780-\u17ff\u3040-\u30ff\u3400-\u4dbf" r"\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff")_WORD_EXTRA = ( r"\u0300-\u036f\u0591-\u05c7\u0610-\u061a\u064b-\u065f\u0900-\u0dff")_SCAN_RE = re.compile( rf"([{_CJKLIKE}]+)|((?:(?![{_CJKLIKE}])[\w{_WORD_EXTRA}])+)")_SENT_RE = re.compile(r"(?<=[.!?…。!?؟।۔])\s+|(?<=[。!?])")_SEPARATOR_RE = re.compile(r"^[-=_*~#.\s|+]{3,}$")_BULLET_RE = re.compile(r"^(?:[-*+•]|\d+[.)])\s+")_ROLE_RE = re.compile( r"^(?:user|assistant|system|human|ai|tool|you|bot)\s*:", re.I)_EMPHASIS_RE = re.compile(r"(\*\*|__)(?=\S)(.+?)(?<=\S)\1")_CODEISH_RE = re.compile( r"(https?://|\w+\.\w{1,5}\b|[/\\]\w+[/\\]|\w+\(|[{}\[\]<>=;]|\w_\w|`)")_KEYWORD_RE = re.compile( r"\b(?:error|errors|fail|failed|failure|bug|fix|fixed|todo|must|should|" r"need|needs|needed|decide|decided|decision|important|warning|goal|" r"requirement|result|summary|conclusion|solution|issue|because)\b" r"|lỗi|quan trọng|cần|phải|quyết định|kết luận|mục tiêu|kết quả" r"|错误|錯誤|重要|必须|必須|需要|决定|決定|结论|結論|目标|目標|结果" r"|エラー|必要|決定|目標|結果|오류|중요|필요|결정|목표|결과" r"|ошибка|важно|нужно|решение|цель|результат" r"|importante|debe|erreur|fehler|wichtig|muss|errore|erro" r"|خطأ|مهم|ข้อผิดพลาด|สำคัญ|त्रुटि|महत्वपूर्ण", re.I,)
class Unit: __slots__ = ("text", "line", "kind", "terms", "cost", "score")
def __init__(self, text, line, kind): self.text = text self.line = line self.kind = kind self.terms = set() self.cost = count_tokens(text) + 1 # +1 for the separator self.score = 0.0
def extract_terms(text): out = [] for m in _SCAN_RE.finditer(text.casefold()): cjk, word = m.groups() if cjk: if len(cjk) == 1: out.append(cjk) else: # no spaces in these scripts: use character bigrams out.extend(cjk[i:i + 2] for i in range(len(cjk) - 1)) elif len(word) > 1 or word.isdigit(): out.append(word) return out
def normalize_text(text): text = text.replace("\r\n", "\n").replace("\r", "\n").replace("\t", " ") return text.strip()
def clean_inline(line): line = _EMPHASIS_RE.sub(r"\2", line) return re.sub(r"[ \u00a0]+", " ", line).strip()
def split_units(text): """Break text into sentence-like units, keeping fenced code blocks whole.""" units = [] lines = text.split("\n") i = 0 line_no = 0 while i < len(lines): raw = lines[i] stripped = raw.strip() if stripped.startswith("```") or stripped.startswith("~~~"): fence = stripped[:3] block = [raw.rstrip()] i += 1 while i < len(lines): block.append(lines[i].rstrip()) closed = lines[i].strip().startswith(fence) i += 1 if closed: break units.append(Unit("\n".join(block), line_no, "code")) line_no += 1 continue i += 1 if not stripped or _SEPARATOR_RE.match(stripped): continue line = clean_inline(stripped) if not line: continue if line.startswith("#"): units.append(Unit(line, line_no, "head")) elif _BULLET_RE.match(line): units.append(Unit(line, line_no, "text")) else: for part in _SENT_RE.split(line): part = part.strip() if part: units.append(Unit(part, line_no, "text")) line_no += 1 return units
def dedupe(units): seen = set() result = [] for u in units: key = re.sub(r"[\W_]+", "", u.text.casefold()) if key and key in seen: continue seen.add(key) result.append(u) return result
def score_units(units): n = len(units) tf, df = Counter(), Counter() for u in units: terms = extract_terms(u.text) u.terms = set(terms) tf.update(terms) df.update(u.terms)
base = [] for u in units: if not u.terms: base.append(0.0) continue weight = sum(tf[t] * math.log(1 + n / df[t]) for t in u.terms) base.append(weight / (len(u.terms) ** 0.7)) top = max(base) if base else 0.0
for idx, u in enumerate(units): score = base[idx] / top if top else 0.0 if u.kind == "code": score = max(score, 0.5) if u.kind == "head": score += 0.25 if idx == 0: score += 0.30 elif idx == 1: score += 0.10 if idx >= n - 2: score += 0.20 if any(c.isdigit() for c in u.text): score += 0.10 if _CODEISH_RE.search(u.text): score += 0.15 if _KEYWORD_RE.search(u.text): score += 0.15 if _ROLE_RE.match(u.text): score += 0.10 if u.text.rstrip().endswith(("?", "?")): score += 0.05 caps = len(re.findall(r"(?<=\s)[^\W\d_a-z][\w-]+", u.text)) score += min(caps, 3) * 0.05 u.score = score
def _similar(a, b): if len(a) < 3 or len(b) < 3: return False inter = len(a & b) return inter / (len(a) + len(b) - inter) >= NEAR_DUP_JACCARD
def assemble(units, texts): """Join chosen units back in their original order.""" out = [] last_line = None for idx in sorted(texts): u = units[idx] piece = texts[idx] if u.line == last_line and out: sep = "" if out[-1][-1:] in "。!?" else " " out[-1] += sep + piece else: out.append(piece) last_line = u.line return "\n".join(out)
def compact(text, max_tokens=None): """Return the compacted text (never above the token budget).""" text = normalize_text(text) original = count_tokens(text) if max_tokens: budget = max_tokens else: budget = max(int(original * AUTO_RATIO), min(original, MIN_AUTO_TOKENS)) budget = max(1, budget)
units = dedupe(split_units(text)) if not units: return truncate_to_tokens(text, budget)
cleaned = assemble(units, dict(enumerate(u.text for u in units))) if count_tokens(cleaned) <= budget: return cleaned
score_units(units) order = sorted( range(len(units)), key=lambda i: units[i].score / math.sqrt(units[i].cost), reverse=True, )
chosen = {} used = 0 for i in order: u = units[i] if used + u.cost > budget: continue if any(_similar(u.terms, units[j].terms) for j in chosen): continue chosen[i] = u.text used += u.cost if used >= budget - 1: break
# Use leftover budget for a shortened version of the best skipped unit. remaining = budget - used if remaining >= 12: for i in order: if i in chosen: continue if any(_similar(units[i].terms, units[j].terms) for j in chosen): continue short = truncate_to_tokens(units[i].text, remaining - 1) if short: chosen[i] = short break
result = assemble(units, chosen) if count_tokens(result) > budget: result = truncate_to_tokens(result, budget) return result or truncate_to_tokens(cleaned, budget)
# --------------------------------------------------------------------------# Clipboard (Windows, macOS, Linux, WSL, SSH fallback)# --------------------------------------------------------------------------
def copy_to_clipboard(text): """Copy text to the clipboard. Returns (ok, message).""" candidates = [] if sys.platform == "win32": candidates.append((["clip"], "utf-16", text.replace("\n", "\r\n"))) elif sys.platform == "darwin": candidates.append((["pbcopy"], "utf-8", text)) else: if os.environ.get("WAYLAND_DISPLAY"): candidates.append((["wl-copy"], "utf-8", text)) candidates.append((["xclip", "-selection", "clipboard"], "utf-8", text)) candidates.append((["xsel", "--clipboard", "--input"], "utf-8", text)) candidates.append((["wl-copy"], "utf-8", text)) candidates.append((["termux-clipboard-set"], "utf-8", text)) candidates.append((["clip.exe"], "utf-16", text.replace("\n", "\r\n")))
env = dict(os.environ, LANG="en_US.UTF-8", LC_CTYPE="UTF-8") for cmd, enc, payload in candidates: if not shutil.which(cmd[0]): continue try: subprocess.run( cmd, input=payload.encode(enc), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5, check=True, env=env, ) return True, "Copied to clipboard." except Exception: continue
try: # tkinter fallback import tkinter
root = tkinter.Tk() root.withdraw() root.clipboard_clear() root.clipboard_append(text) root.update() root.destroy() return True, "Copied to clipboard." except Exception: pass
if sys.stdout.isatty(): # OSC 52: works in many terminals, even over SSH data = base64.b64encode(text.encode("utf-8")).decode("ascii") sys.stdout.write(f"\033]52;c;{data}\a") sys.stdout.flush() return True, "Sent to terminal clipboard (OSC 52); your terminal must support it."
return False, "No clipboard tool found (install xclip, xsel or wl-clipboard)."
# --------------------------------------------------------------------------# Terminal UI# --------------------------------------------------------------------------
def enable_ansi(): if os.name == "nt": os.system("") # enables ANSI escape codes in Windows terminals for stream in (sys.stdout, sys.stderr): try: stream.reconfigure(errors="replace") except Exception: pass
def setup_readline(): if not readline: return names = [c[0] for c in COMMANDS]
def completer(text, state): matches = [n for n in names if n.startswith(text)] if text.startswith("/") else [] return matches[state] if state < len(matches) else None
try: readline.set_completer(completer) readline.set_completer_delims(" \t\n") if "libedit" in (readline.__doc__ or ""): readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") except Exception: pass
def pending_input(): """True if more pasted lines are waiting in the terminal buffer.""" try: if os.name == "nt": import msvcrt
time.sleep(0.03) return msvcrt.kbhit() import select
return bool(select.select([sys.stdin], [], [], 0.05)[0]) except Exception: return False
def read_input(): first = input("> ") if first.strip() == '"""': # explicit multi-line block lines = [] while True: try: line = input("") except EOFError: break if line.strip() == '"""': break lines.append(line) return "\n".join(lines) lines = [first] if first.strip() and sys.stdin.isatty(): # pasted multi-line text while pending_input(): try: lines.append(input("")) except EOFError: break return "\n".join(lines)
def print_commands(): for name, args, desc in COMMANDS: label = f"{name} {args}".strip() print(f" {label:<20}{paint(desc, DIM)}")
def run_compact(text, state): result = compact(text, state["max_token"]) state["last"] = result print(result) print(paint(f"{count_tokens(text):,} -> {count_tokens(result):,}", GREEN)) print()
def handle_command(name, arg, state): """Returns False when the program should exit.""" name = name.lower() if name == "": print_commands() elif name == "help": print_commands() print(paint(' Tip: wrap text in """ lines to enter multiple lines manually.', DIM)) elif name in ("exit", "quit"): return False elif name == "max_token": arg = (arg or "").strip().lower() if not arg: cur = state["max_token"] print(f"max_token = {cur:,}" if cur else "max_token = off (auto, ~35% of input)") elif arg in ("off", "auto", "0", "none"): state["max_token"] = None print("max_token = off (auto, ~35% of input)") else: try: value = int(arg.replace(",", "").replace("_", "")) if value < 1: raise ValueError state["max_token"] = value print(f"max_token = {value:,}") except ValueError: print("Usage: /max_token <positive number | off>") elif name == "copy": if not state["last"]: print("Nothing to copy yet. Compact some text first.") else: ok, message = copy_to_clipboard(state["last"]) print(message) else: print(f"Unknown command: /{name}. Type / to list commands.") return True
COMMAND_RE = re.compile(r"^/([A-Za-z_]*)(?:\s+(.*))?$")
def main(): enable_ansi() state = {"max_token": None, "last": None}
if not sys.stdin.isatty(): # piped input: compact everything and exit text = sys.stdin.read() if text.strip(): print(compact(text)) return
setup_readline() print("Session Compactor") print('Type or paste text to compact. Type "/" for commands.\n')
while True: try: text = read_input() except EOFError: print() break except KeyboardInterrupt: print() continue
if not text.strip(): continue
match = COMMAND_RE.match(text.strip()) if "\n" not in text else None if match: if not handle_command(match.group(1), match.group(2), state): break continue
run_compact(text, state)
if __name__ == "__main__": try: main() except KeyboardInterrupt: print()12345678---name: offline-compactdescription: /compact offline - compact the chat with compact.py (no AI call, free, offline)---`/compact offline` writes the summary with compact.py instead of asking an AI. Plain `/compact` and auto-compact work as usual.It keeps the most important sentences in order (nothing is rewritten). The summary is at most 10% of the model's context window, at least 1/10 of that, and always at least 10% shorter than the conversation. Edit the settings at the top of ext.py to tune it.
This extension takes over the /compact command itself (MshCode is not modified): `/compact` goes to MshCode as usual, `/compact offline` uses compact.py.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Offline compact: `/compact offline` writes the summary with compact.py. No AI call, no cost, works without internet.Plain `/compact` and auto-compact are unchanged (the AI writes the summary).
compact.py keeps the most important sentences of the conversation (in their original order) and drops the rest. It does not rewrite,so it is faster and free but less "clever" than a summary written by the AI. Use plain /compact to get the AI summary."""
WINDOW_SHARE = 0.10 # the summary is never longer than this share of the model's context window (= max tokens)MIN_DIVISOR = 10 # min tokens = max tokens / 10RATIO = 0.25 # the summary is about this share of the conversation (kept between min and max)SHORT_CUT = 0.10 # a conversation shorter than min tokens is only cut by this much (kept at 90%), not kept wholeFALLBACK_WINDOW = 100000 # used when MshCode does not know the context window of the modelTOOL_CHARS = 600 # tool output (file contents, test logs...) is cut to this many characters before choosing
def setup(api): import sys compact = api.module("compact.py") # the compact.py next to this file msh = sys.modules[type(api).__module__] # MshCode itself: we call its own /compact for the normal case state = {"offline": False}
def before_compact(chat, keep): if not state["offline"]: return None # plain /compact and auto-compact: the AI writes the summary as usual text = api.transcript(chat, tool_chars=TOOL_CHARS) # the conversation as plain text (tool output is cut short) if not text.strip(): return None # nothing to summarize: let MshCode do its normal thing n = compact.count_tokens(text) window = msh.context_window() or FALLBACK_WINDOW # tokens of the current model (manual /connect value, or auto-detected) max_t = int(window * WINDOW_SHARE) min_t = max_t // MIN_DIVISOR budget = min(int(n * (1 - SHORT_CUT)), max(min_t, min(max_t, int(n * RATIO)))) # never more than 90% of the conversation summary = compact.compact(text, budget) return "Key points kept from the earlier conversation (extracted, not rewritten):\n\n" + summary
def cmd(chat, arg): state["offline"] = arg.strip().lower() == "offline" # anything else = plain /compact try: msh.cmd_compact(chat) # MshCode's own compaction; the hook above only acts when offline finally: state["offline"] = False
# api.command() refuses names MshCode already has, so /compact is put in the table directly. # Extension commands run before the built-in ones, so this takes over /compact and hands plain /compact back to MshCode. api._cmds["/compact"] = {"ext": api.name, "desc": "compact the chat into a summary (/compact offline: no AI call)", "fn": cmd, "args": [("offline", "write the summary with compact.py, no AI call (free)")]} api.on("before_compact", before_compact)offline-compact/compact.pyAdded+634
offline-compact/describe.mdAdded+8
offline-compact/ext.pyAdded+47