vexel-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- vexel_cli/__init__.py +3 -0
- vexel_cli/cli.py +257 -0
- vexel_cli/core.py +237 -0
- vexel_cli/templates.py +86 -0
- vexel_cli-0.1.0.dist-info/METADATA +61 -0
- vexel_cli-0.1.0.dist-info/RECORD +9 -0
- vexel_cli-0.1.0.dist-info/WHEEL +5 -0
- vexel_cli-0.1.0.dist-info/entry_points.txt +2 -0
- vexel_cli-0.1.0.dist-info/top_level.txt +1 -0
vexel_cli/__init__.py
ADDED
vexel_cli/cli.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Vexel CLI — deterministic context pruning for LLM agent loops.
|
|
2
|
+
|
|
3
|
+
Zero external dependencies. Every command uses only the Python standard library.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from vexel_cli import __version__
|
|
16
|
+
from vexel_cli.core import prune_messages, prune_text
|
|
17
|
+
|
|
18
|
+
STATS_PATH = Path.home() / ".vexel" / "stats.json"
|
|
19
|
+
CHAR_THRESHOLD = 1500
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _load_stats() -> dict:
|
|
23
|
+
if STATS_PATH.exists():
|
|
24
|
+
try:
|
|
25
|
+
return json.loads(STATS_PATH.read_text(encoding="utf-8"))
|
|
26
|
+
except (json.JSONDecodeError, OSError):
|
|
27
|
+
pass
|
|
28
|
+
return {"runs": 0, "before_tokens": 0, "after_tokens": 0, "saved_tokens": 0}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _save_stats(stats: dict) -> None:
|
|
32
|
+
STATS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
33
|
+
STATS_PATH.write_text(json.dumps(stats, indent=2) + "\n", encoding="utf-8")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _record(before: int, after: int) -> None:
|
|
37
|
+
s = _load_stats()
|
|
38
|
+
s["runs"] = s.get("runs", 0) + 1
|
|
39
|
+
s["before_tokens"] = s.get("before_tokens", 0) + before
|
|
40
|
+
s["after_tokens"] = s.get("after_tokens", 0) + after
|
|
41
|
+
s["saved_tokens"] = s.get("saved_tokens", 0) + (before - after)
|
|
42
|
+
_save_stats(s)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# ── vexel prune ──────────────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
def cmd_prune(args: argparse.Namespace) -> None:
|
|
48
|
+
if args.file and args.file != "-":
|
|
49
|
+
text = Path(args.file).read_text(encoding="utf-8", errors="replace")
|
|
50
|
+
else:
|
|
51
|
+
text = sys.stdin.read()
|
|
52
|
+
|
|
53
|
+
result = prune_text(text, max_lines=args.max_lines)
|
|
54
|
+
_record(result["before_tokens"], result["after_tokens"])
|
|
55
|
+
|
|
56
|
+
if args.json:
|
|
57
|
+
json.dump(
|
|
58
|
+
{k: v for k, v in result.items() if k != "pruned"},
|
|
59
|
+
sys.stdout,
|
|
60
|
+
indent=2,
|
|
61
|
+
)
|
|
62
|
+
sys.stdout.write("\n")
|
|
63
|
+
else:
|
|
64
|
+
sys.stdout.write(result["pruned"])
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# ── vexel wrap ───────────────────────────────────────────────────────────
|
|
68
|
+
|
|
69
|
+
def cmd_wrap(args: argparse.Namespace) -> None:
|
|
70
|
+
cmd = args.cmd
|
|
71
|
+
if cmd and cmd[0] == "--":
|
|
72
|
+
cmd = cmd[1:]
|
|
73
|
+
proc = subprocess.run(
|
|
74
|
+
cmd,
|
|
75
|
+
capture_output=True,
|
|
76
|
+
text=True,
|
|
77
|
+
)
|
|
78
|
+
combined = proc.stdout + proc.stderr
|
|
79
|
+
if len(combined) > CHAR_THRESHOLD:
|
|
80
|
+
result = prune_text(combined, max_lines=getattr(args, "max_lines", 80))
|
|
81
|
+
_record(result["before_tokens"], result["after_tokens"])
|
|
82
|
+
sys.stdout.write(result["pruned"])
|
|
83
|
+
else:
|
|
84
|
+
sys.stdout.write(proc.stdout)
|
|
85
|
+
sys.stderr.write(proc.stderr)
|
|
86
|
+
sys.exit(proc.returncode)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# ── vexel hook-post-tool ─────────────────────────────────────────────────
|
|
90
|
+
|
|
91
|
+
def cmd_hook_post_tool(_args: argparse.Namespace) -> None:
|
|
92
|
+
try:
|
|
93
|
+
payload = json.loads(sys.stdin.read())
|
|
94
|
+
except (json.JSONDecodeError, OSError):
|
|
95
|
+
sys.exit(0)
|
|
96
|
+
|
|
97
|
+
tool_response = payload.get("tool_response", "")
|
|
98
|
+
if not isinstance(tool_response, str):
|
|
99
|
+
tool_response = json.dumps(tool_response)
|
|
100
|
+
|
|
101
|
+
stdout_field = payload.get("stdout", "")
|
|
102
|
+
if isinstance(stdout_field, str) and len(stdout_field) > len(tool_response):
|
|
103
|
+
tool_response = stdout_field
|
|
104
|
+
|
|
105
|
+
if len(tool_response) <= CHAR_THRESHOLD:
|
|
106
|
+
sys.exit(0)
|
|
107
|
+
|
|
108
|
+
result = prune_text(tool_response)
|
|
109
|
+
_record(result["before_tokens"], result["after_tokens"])
|
|
110
|
+
|
|
111
|
+
output = {
|
|
112
|
+
"hookSpecificOutput": {
|
|
113
|
+
"updatedToolOutput": result["pruned"],
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
json.dump(output, sys.stdout)
|
|
117
|
+
sys.stdout.write("\n")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# ── vexel install ────────────────────────────────────────────────────────
|
|
121
|
+
|
|
122
|
+
def cmd_install(args: argparse.Namespace) -> None:
|
|
123
|
+
from vexel_cli.templates import (
|
|
124
|
+
CLAUDE_SETTINGS_HOOK,
|
|
125
|
+
CLAUDE_SKILL,
|
|
126
|
+
CURSOR_HOOKS,
|
|
127
|
+
CURSOR_RULE,
|
|
128
|
+
CURSOR_SKILL,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
targets = args.target
|
|
132
|
+
base = Path.home() if args.is_global else Path.cwd()
|
|
133
|
+
|
|
134
|
+
installed: list[str] = []
|
|
135
|
+
|
|
136
|
+
if targets in ("cursor", "all"):
|
|
137
|
+
_install_cursor(base, CURSOR_RULE, CURSOR_SKILL, CURSOR_HOOKS)
|
|
138
|
+
installed.append("Cursor")
|
|
139
|
+
|
|
140
|
+
if targets in ("claude", "all"):
|
|
141
|
+
_install_claude(base, CLAUDE_SKILL, CLAUDE_SETTINGS_HOOK)
|
|
142
|
+
installed.append("Claude Code")
|
|
143
|
+
|
|
144
|
+
if installed:
|
|
145
|
+
print(f"Vexel installed for: {', '.join(installed)}")
|
|
146
|
+
print(f" Base: {base}")
|
|
147
|
+
else:
|
|
148
|
+
print("Nothing to install.")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _write_if_absent(path: Path, content: str) -> bool:
|
|
152
|
+
if path.exists():
|
|
153
|
+
return False
|
|
154
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
155
|
+
path.write_text(content, encoding="utf-8")
|
|
156
|
+
return True
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _merge_json(path: Path, patch: dict) -> None:
|
|
160
|
+
existing: dict = {}
|
|
161
|
+
if path.exists():
|
|
162
|
+
try:
|
|
163
|
+
existing = json.loads(path.read_text(encoding="utf-8"))
|
|
164
|
+
except (json.JSONDecodeError, OSError):
|
|
165
|
+
pass
|
|
166
|
+
_deep_merge(existing, patch)
|
|
167
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
168
|
+
path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _deep_merge(base: dict, patch: dict) -> None:
|
|
172
|
+
for key, val in patch.items():
|
|
173
|
+
if key in base and isinstance(base[key], dict) and isinstance(val, dict):
|
|
174
|
+
_deep_merge(base[key], val)
|
|
175
|
+
elif key in base and isinstance(base[key], list) and isinstance(val, list):
|
|
176
|
+
existing_json = {json.dumps(e, sort_keys=True) for e in base[key] if isinstance(e, dict)}
|
|
177
|
+
for item in val:
|
|
178
|
+
if isinstance(item, dict) and json.dumps(item, sort_keys=True) not in existing_json:
|
|
179
|
+
base[key].append(item)
|
|
180
|
+
else:
|
|
181
|
+
base.setdefault(key, val)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _install_cursor(base: Path, rule: str, skill: str, hooks: dict) -> None:
|
|
185
|
+
cursor = base / ".cursor"
|
|
186
|
+
_write_if_absent(cursor / "rules" / "vexel.mdc", rule)
|
|
187
|
+
_write_if_absent(cursor / "skills" / "vexel" / "SKILL.md", skill)
|
|
188
|
+
_merge_json(cursor / "hooks.json", hooks)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _install_claude(base: Path, skill: str, settings_hook: dict) -> None:
|
|
192
|
+
claude = base / ".claude"
|
|
193
|
+
_write_if_absent(claude / "skills" / "vexel" / "SKILL.md", skill)
|
|
194
|
+
_merge_json(claude / "settings.json", settings_hook)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# ── vexel stats ──────────────────────────────────────────────────────────
|
|
198
|
+
|
|
199
|
+
def cmd_stats(_args: argparse.Namespace) -> None:
|
|
200
|
+
s = _load_stats()
|
|
201
|
+
runs = s.get("runs", 0)
|
|
202
|
+
saved = s.get("saved_tokens", 0)
|
|
203
|
+
before = s.get("before_tokens", 0)
|
|
204
|
+
pct = round(saved / before * 100, 1) if before else 0.0
|
|
205
|
+
print(f"Vexel stats ({STATS_PATH})")
|
|
206
|
+
print(f" Runs: {runs}")
|
|
207
|
+
print(f" Before: {before:,} tokens")
|
|
208
|
+
print(f" After: {s.get('after_tokens', 0):,} tokens")
|
|
209
|
+
print(f" Saved: {saved:,} tokens ({pct}%)")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
# ── main ─────────────────────────────────────────────────────────────────
|
|
213
|
+
|
|
214
|
+
def main(argv: list[str] | None = None) -> None:
|
|
215
|
+
parser = argparse.ArgumentParser(
|
|
216
|
+
prog="vexel",
|
|
217
|
+
description="Deterministic context pruning for LLM agent loops",
|
|
218
|
+
)
|
|
219
|
+
parser.add_argument("--version", action="version", version=f"vexel {__version__}")
|
|
220
|
+
sub = parser.add_subparsers(dest="command")
|
|
221
|
+
|
|
222
|
+
p_prune = sub.add_parser("prune", help="Prune text from file or stdin")
|
|
223
|
+
p_prune.add_argument("file", nargs="?", default="-", help="File to prune (default: stdin)")
|
|
224
|
+
p_prune.add_argument("--json", action="store_true", help="Output JSON telemetry instead of pruned text")
|
|
225
|
+
p_prune.add_argument("--max-lines", type=int, default=80, help="Max output lines (default: 80)")
|
|
226
|
+
|
|
227
|
+
p_wrap = sub.add_parser("wrap", help="Run a command and prune its output")
|
|
228
|
+
p_wrap.add_argument("--max-lines", type=int, default=80, help="Max output lines")
|
|
229
|
+
p_wrap.add_argument("cmd", nargs=argparse.REMAINDER, help="Command to run (after --)")
|
|
230
|
+
|
|
231
|
+
p_hook = sub.add_parser("hook-post-tool", help="PostToolUse hook (reads JSON from stdin)")
|
|
232
|
+
|
|
233
|
+
p_install = sub.add_parser("install", help="Install Vexel IDE configs")
|
|
234
|
+
p_install.add_argument("--global", dest="is_global", action="store_true", help="Install to home directory")
|
|
235
|
+
p_install.add_argument("--target", choices=["cursor", "claude", "all"], default="all", help="IDE target")
|
|
236
|
+
|
|
237
|
+
sub.add_parser("stats", help="Show cumulative token savings")
|
|
238
|
+
|
|
239
|
+
args = parser.parse_args(argv)
|
|
240
|
+
|
|
241
|
+
if args.command == "prune":
|
|
242
|
+
cmd_prune(args)
|
|
243
|
+
elif args.command == "wrap":
|
|
244
|
+
cmd_wrap(args)
|
|
245
|
+
elif args.command == "hook-post-tool":
|
|
246
|
+
cmd_hook_post_tool(args)
|
|
247
|
+
elif args.command == "install":
|
|
248
|
+
cmd_install(args)
|
|
249
|
+
elif args.command == "stats":
|
|
250
|
+
cmd_stats(args)
|
|
251
|
+
else:
|
|
252
|
+
parser.print_help()
|
|
253
|
+
sys.exit(1)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
if __name__ == "__main__":
|
|
257
|
+
main()
|
vexel_cli/core.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""Pure deterministic pruning logic — Python standard library only.
|
|
2
|
+
|
|
3
|
+
Ported from build_memora_context_management_system/backend/optimizer.py without
|
|
4
|
+
FastAPI, Pydantic, tiktoken, or any third-party import.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
SECRET = re.compile(
|
|
13
|
+
r"(?i)(\b(?:api[_-]?key|token|password|secret|authorization)\b\s*[:=]\s*)"
|
|
14
|
+
r"(?:bearer\s+)?[^\s,;]+|\b(?:AIza[\w-]{20,}|sk-[\w-]{16,})\b"
|
|
15
|
+
)
|
|
16
|
+
PATH_RE = re.compile(
|
|
17
|
+
r"(?:^|\s)(?:[./~][\w./-]+|[\w.-]+/[\w./-]+\.(?:py|js|ts|json|yaml|yml))(?=\s|:|$)"
|
|
18
|
+
)
|
|
19
|
+
ERROR_RE = re.compile(
|
|
20
|
+
r"(?i)\b(?:traceback|exception|error|failed|failure|crash|assertion|stack trace)\b"
|
|
21
|
+
)
|
|
22
|
+
CONSTRAINT_RE = re.compile(
|
|
23
|
+
r"(?i)\b(?:must|never|do not|requirement|constraint|invariant|expected|acceptance)\b"
|
|
24
|
+
)
|
|
25
|
+
WORDS = re.compile(r"[a-z0-9]+")
|
|
26
|
+
_TOOL_SIG_HEX = re.compile(r"\b0x[0-9a-f]+\b", re.I)
|
|
27
|
+
_TOOL_SIG_DIGITS = re.compile(r"\d+")
|
|
28
|
+
_TOOL_SIGNATURE_MIN_CHARS = 120
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _approx_tokens(text: str) -> int:
|
|
32
|
+
return len(re.findall(r"\w+|[^\w\s]", text))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _redact(text: str) -> str:
|
|
36
|
+
return SECRET.sub(
|
|
37
|
+
lambda m: f"{m.group(1)}[REDACTED]" if m.group(1) else "[REDACTED]",
|
|
38
|
+
text,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _normalize(text: str) -> str:
|
|
43
|
+
return " ".join(WORDS.findall(_redact(text).lower()))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _compress_text(text: str) -> str:
|
|
47
|
+
clean = _redact(text)
|
|
48
|
+
sentences = re.split(r"(?<=[.!?])\s+", clean)
|
|
49
|
+
return sentences[0][:400].strip() if sentences else clean[:400]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _tool_signature(text: str) -> str:
|
|
53
|
+
clean = _redact(text)
|
|
54
|
+
if len(clean.strip()) < _TOOL_SIGNATURE_MIN_CHARS:
|
|
55
|
+
return ""
|
|
56
|
+
masked = _TOOL_SIG_HEX.sub("#", clean.lower())
|
|
57
|
+
masked = _TOOL_SIG_DIGITS.sub("#", masked)
|
|
58
|
+
return " ".join(WORDS.findall(masked))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _has_error(text: str) -> bool:
|
|
62
|
+
return bool(ERROR_RE.search(text))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _has_path(text: str) -> bool:
|
|
66
|
+
return bool(PATH_RE.search(text))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _has_constraint(text: str) -> bool:
|
|
70
|
+
return bool(CONSTRAINT_RE.search(text))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _is_protected(role: str, kind: str | None, text: str) -> bool:
|
|
74
|
+
if role in ("system", "developer", "user"):
|
|
75
|
+
return True
|
|
76
|
+
if kind == "constraint" or _has_constraint(text):
|
|
77
|
+
return True
|
|
78
|
+
if kind == "error" or _has_error(text):
|
|
79
|
+
return True
|
|
80
|
+
if kind == "file" or _has_path(text):
|
|
81
|
+
return True
|
|
82
|
+
return False
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# ---------------------------------------------------------------------------
|
|
86
|
+
# prune_text: standalone text pruning (for files / stdout / tool output)
|
|
87
|
+
# ---------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
_CONSECUTIVE_DUP = re.compile(r"^(.+?)(\n\1)+$", re.MULTILINE)
|
|
90
|
+
_FRAME_LINE = re.compile(
|
|
91
|
+
r"^\s*File \"[^\"]+\", line \d+",
|
|
92
|
+
)
|
|
93
|
+
_EXIT_CODE = re.compile(r"(?:exit(?:ed)?|return(?:ed)?|code)[:\s]+\d+", re.I)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def prune_text(text: str, *, max_lines: int = 80) -> dict[str, Any]:
|
|
97
|
+
before_tokens = _approx_tokens(text)
|
|
98
|
+
lines = text.splitlines(keepends=True)
|
|
99
|
+
|
|
100
|
+
# 1. Collapse consecutive duplicate lines.
|
|
101
|
+
seen_consecutive: str | None = None
|
|
102
|
+
deduped: list[str] = []
|
|
103
|
+
consecutive_collapsed = 0
|
|
104
|
+
for line in lines:
|
|
105
|
+
stripped = line.rstrip()
|
|
106
|
+
if stripped == seen_consecutive and stripped:
|
|
107
|
+
consecutive_collapsed += 1
|
|
108
|
+
continue
|
|
109
|
+
seen_consecutive = stripped
|
|
110
|
+
deduped.append(line)
|
|
111
|
+
|
|
112
|
+
# 2. Deduplicate repeated stack-trace frames.
|
|
113
|
+
frame_groups: dict[str, int] = {}
|
|
114
|
+
kept: list[str] = []
|
|
115
|
+
frames_collapsed = 0
|
|
116
|
+
i = 0
|
|
117
|
+
while i < len(deduped):
|
|
118
|
+
line = deduped[i]
|
|
119
|
+
if _FRAME_LINE.match(line):
|
|
120
|
+
block_lines = [line]
|
|
121
|
+
j = i + 1
|
|
122
|
+
# Collect indented continuation (the code line under "File ...").
|
|
123
|
+
while j < len(deduped) and not _FRAME_LINE.match(deduped[j]) and deduped[j].startswith((" ", "\t")) and deduped[j].strip():
|
|
124
|
+
block_lines.append(deduped[j])
|
|
125
|
+
j += 1
|
|
126
|
+
sig = _normalize("".join(block_lines))
|
|
127
|
+
if sig in frame_groups:
|
|
128
|
+
frames_collapsed += 1
|
|
129
|
+
i = j
|
|
130
|
+
continue
|
|
131
|
+
frame_groups[sig] = 1
|
|
132
|
+
kept.extend(block_lines)
|
|
133
|
+
i = j
|
|
134
|
+
else:
|
|
135
|
+
kept.append(line)
|
|
136
|
+
i += 1
|
|
137
|
+
|
|
138
|
+
# 3. Preserve error headers, exit codes, file paths — always keep those lines.
|
|
139
|
+
# 4. Trim to max_lines from the tail (most recent), keeping the head error/exit/path lines.
|
|
140
|
+
if len(kept) > max_lines:
|
|
141
|
+
head_keep: list[int] = []
|
|
142
|
+
for idx, line in enumerate(kept):
|
|
143
|
+
if _has_error(line) or _EXIT_CODE.search(line) or _has_path(line):
|
|
144
|
+
head_keep.append(idx)
|
|
145
|
+
tail_start = max(0, len(kept) - max_lines)
|
|
146
|
+
preserved_head = [kept[idx] for idx in head_keep if idx < tail_start]
|
|
147
|
+
budget = max_lines - len(preserved_head)
|
|
148
|
+
tail = kept[-budget:] if budget > 0 else []
|
|
149
|
+
kept = preserved_head + tail
|
|
150
|
+
|
|
151
|
+
pruned = _redact("".join(kept))
|
|
152
|
+
after_tokens = _approx_tokens(pruned)
|
|
153
|
+
saved = round((1 - after_tokens / before_tokens) * 100, 1) if before_tokens else 0.0
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
"pruned": pruned,
|
|
157
|
+
"before_tokens": before_tokens,
|
|
158
|
+
"after_tokens": after_tokens,
|
|
159
|
+
"saved_pct": saved,
|
|
160
|
+
"dropped_blocks": consecutive_collapsed + frames_collapsed,
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
# ---------------------------------------------------------------------------
|
|
165
|
+
# prune_messages: conversation-level KEEP / COMPRESS / DROP
|
|
166
|
+
# ---------------------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
def prune_messages(messages: list[dict[str, Any]]) -> dict[str, Any]:
|
|
169
|
+
seen: set[str] = set()
|
|
170
|
+
seen_tool_sigs: set[str] = set()
|
|
171
|
+
output: list[dict[str, Any]] = []
|
|
172
|
+
decisions: list[dict[str, Any]] = []
|
|
173
|
+
before_tokens = 0
|
|
174
|
+
after_tokens = 0
|
|
175
|
+
|
|
176
|
+
for msg in messages:
|
|
177
|
+
role = msg.get("role", "")
|
|
178
|
+
kind = msg.get("kind")
|
|
179
|
+
content = msg.get("content", "")
|
|
180
|
+
original_tokens = _approx_tokens(content)
|
|
181
|
+
before_tokens += original_tokens
|
|
182
|
+
|
|
183
|
+
normalized = _normalize(content)
|
|
184
|
+
duplicate = bool(normalized) and normalized in seen
|
|
185
|
+
seen.add(normalized)
|
|
186
|
+
|
|
187
|
+
tool_sig = _tool_signature(content) if role == "tool" else ""
|
|
188
|
+
retry_dup = role == "tool" and bool(tool_sig) and tool_sig in seen_tool_sigs and not duplicate
|
|
189
|
+
|
|
190
|
+
is_protected = _is_protected(role, kind, content)
|
|
191
|
+
|
|
192
|
+
action = "KEEP"
|
|
193
|
+
reason = "protected" if is_protected else "conservative_keep"
|
|
194
|
+
|
|
195
|
+
if role in ("assistant", "tool"):
|
|
196
|
+
if duplicate or retry_dup:
|
|
197
|
+
action, reason = "DROP", "exact_duplicate"
|
|
198
|
+
elif not is_protected:
|
|
199
|
+
redacted = _redact(content)
|
|
200
|
+
if role == "tool" and len(content.strip()) > 200 and _approx_tokens(_compress_text(content)) < _approx_tokens(redacted):
|
|
201
|
+
action, reason = "COMPRESS", "deterministic_compress"
|
|
202
|
+
elif role == "assistant" and _approx_tokens(redacted) >= 100 and _approx_tokens(_compress_text(content)) < _approx_tokens(redacted):
|
|
203
|
+
action, reason = "COMPRESS", "deterministic_compress"
|
|
204
|
+
|
|
205
|
+
if action != "DROP" and tool_sig:
|
|
206
|
+
seen_tool_sigs.add(tool_sig)
|
|
207
|
+
|
|
208
|
+
result_content = content
|
|
209
|
+
if action == "COMPRESS":
|
|
210
|
+
result_content = _compress_text(content)
|
|
211
|
+
elif action == "DROP":
|
|
212
|
+
result_content = ""
|
|
213
|
+
|
|
214
|
+
result_tokens = _approx_tokens(result_content) if action != "DROP" else 0
|
|
215
|
+
after_tokens += result_tokens
|
|
216
|
+
|
|
217
|
+
if action != "DROP":
|
|
218
|
+
out_msg = dict(msg)
|
|
219
|
+
out_msg["content"] = result_content
|
|
220
|
+
output.append(out_msg)
|
|
221
|
+
|
|
222
|
+
decisions.append({
|
|
223
|
+
"role": role,
|
|
224
|
+
"action": action,
|
|
225
|
+
"reason": reason,
|
|
226
|
+
"original_tokens": original_tokens,
|
|
227
|
+
"resulting_tokens": result_tokens,
|
|
228
|
+
})
|
|
229
|
+
|
|
230
|
+
saved = round((1 - after_tokens / before_tokens) * 100, 1) if before_tokens else 0.0
|
|
231
|
+
return {
|
|
232
|
+
"messages": output,
|
|
233
|
+
"decisions": decisions,
|
|
234
|
+
"before_tokens": before_tokens,
|
|
235
|
+
"after_tokens": after_tokens,
|
|
236
|
+
"saved_pct": saved,
|
|
237
|
+
}
|
vexel_cli/templates.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""IDE configuration templates for `vexel install`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
CURSOR_RULE = """\
|
|
6
|
+
---
|
|
7
|
+
description: Vexel deterministic context pruning
|
|
8
|
+
alwaysApply: true
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Vexel Context Pruning
|
|
12
|
+
|
|
13
|
+
When tool output or conversation context exceeds 1 500 tokens, Vexel
|
|
14
|
+
deterministically prunes duplicate retry blocks, collapses repeated stack
|
|
15
|
+
frames, and compresses verbose assistant/tool messages — keeping error
|
|
16
|
+
headers, file paths, exit codes and all user/system/developer messages
|
|
17
|
+
intact.
|
|
18
|
+
|
|
19
|
+
### Rules
|
|
20
|
+
- KEEP every user, system and developer message verbatim.
|
|
21
|
+
- KEEP lines containing errors, file paths, exit codes, or constraints.
|
|
22
|
+
- COMPRESS long tool/assistant blocks that are not protected.
|
|
23
|
+
- DROP exact duplicates (content or tool-signature match).
|
|
24
|
+
- Never drop a message whose content matches an error, constraint, or path pattern.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
CURSOR_SKILL = """\
|
|
28
|
+
# Vexel Pruning Skill
|
|
29
|
+
|
|
30
|
+
Invoke `vexel prune` or `vexel wrap -- <command>` to reduce noisy tool
|
|
31
|
+
output before it enters the context window.
|
|
32
|
+
|
|
33
|
+
## Usage
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
# Prune a file or stdin
|
|
37
|
+
vexel prune build.log
|
|
38
|
+
cat output.txt | vexel prune --json
|
|
39
|
+
|
|
40
|
+
# Wrap a noisy command
|
|
41
|
+
vexel wrap -- pytest -x --tb=long
|
|
42
|
+
|
|
43
|
+
# Show cumulative savings
|
|
44
|
+
vexel stats
|
|
45
|
+
```
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
CURSOR_HOOKS = {
|
|
49
|
+
"hooks": [
|
|
50
|
+
{
|
|
51
|
+
"event": "postToolUse",
|
|
52
|
+
"command": "vexel hook-post-tool",
|
|
53
|
+
"description": "Vexel prunes bulky tool output",
|
|
54
|
+
}
|
|
55
|
+
]
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
CLAUDE_SKILL = """\
|
|
59
|
+
# Vexel Pruning Skill
|
|
60
|
+
|
|
61
|
+
Deterministic context pruning for Claude Code agent loops.
|
|
62
|
+
|
|
63
|
+
## Commands
|
|
64
|
+
|
|
65
|
+
- `vexel prune [file]` — prune text from file or stdin
|
|
66
|
+
- `vexel wrap -- <cmd>` — run a command and prune its output
|
|
67
|
+
- `vexel hook-post-tool` — PostToolUse hook (reads JSON from stdin)
|
|
68
|
+
- `vexel stats` — cumulative token savings
|
|
69
|
+
- `vexel install` — install IDE configs for Cursor and/or Claude Code
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
CLAUDE_SETTINGS_HOOK = {
|
|
73
|
+
"hooks": {
|
|
74
|
+
"PostToolUse": [
|
|
75
|
+
{
|
|
76
|
+
"matcher": "Bash|Read|Grep",
|
|
77
|
+
"hooks": [
|
|
78
|
+
{
|
|
79
|
+
"type": "command",
|
|
80
|
+
"command": "vexel hook-post-tool",
|
|
81
|
+
}
|
|
82
|
+
],
|
|
83
|
+
}
|
|
84
|
+
]
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vexel-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Deterministic context pruning for LLM agent loops — zero API dependencies
|
|
5
|
+
License: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
|
|
9
|
+
# vexel-cli
|
|
10
|
+
|
|
11
|
+
Deterministic context pruning for LLM agent loops — zero API dependencies.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
uv tool install vexel-cli
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Commands
|
|
20
|
+
|
|
21
|
+
| Command | Description |
|
|
22
|
+
|---------|-------------|
|
|
23
|
+
| `vexel prune [file]` | Prune text from file or stdin |
|
|
24
|
+
| `vexel wrap -- <cmd>` | Run a command and prune its output |
|
|
25
|
+
| `vexel hook-post-tool` | PostToolUse hook (reads JSON from stdin) |
|
|
26
|
+
| `vexel install [--target cursor\|claude\|all]` | Install IDE configs |
|
|
27
|
+
| `vexel stats` | Show cumulative token savings |
|
|
28
|
+
|
|
29
|
+
## Examples
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
# Prune a noisy build log
|
|
33
|
+
vexel prune build.log
|
|
34
|
+
|
|
35
|
+
# JSON telemetry
|
|
36
|
+
cat output.txt | vexel prune --json
|
|
37
|
+
|
|
38
|
+
# Wrap a noisy test run so the IDE gets clean output
|
|
39
|
+
vexel wrap -- pytest -x --tb=long
|
|
40
|
+
|
|
41
|
+
# Install Vexel hooks into your project
|
|
42
|
+
vexel install
|
|
43
|
+
vexel install --target cursor
|
|
44
|
+
vexel install --global --target claude
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## How it works
|
|
48
|
+
|
|
49
|
+
Vexel's pruning is fully deterministic (no LLM calls):
|
|
50
|
+
|
|
51
|
+
1. **Collapse** consecutive duplicate lines
|
|
52
|
+
2. **Deduplicate** repeated stack-trace frames
|
|
53
|
+
3. **Preserve** error headers, exit codes, file paths, line numbers
|
|
54
|
+
4. **Trim** to max lines from the tail, keeping important head lines
|
|
55
|
+
5. **Redact** secrets (API keys, tokens, passwords)
|
|
56
|
+
|
|
57
|
+
For conversation arrays (`prune_messages`):
|
|
58
|
+
|
|
59
|
+
- **KEEP** all user/system/developer messages and anything with errors, paths, or constraints
|
|
60
|
+
- **COMPRESS** long tool/assistant blocks to their first sentence
|
|
61
|
+
- **DROP** exact duplicates (content or tool-signature match)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
vexel_cli/__init__.py,sha256=pDZDQLLO1OnSYw6lOstQn473gPDwQXXcH3-GOyhjrIM,97
|
|
2
|
+
vexel_cli/cli.py,sha256=7vAmB-OlK04fBtMsko1rkeyZVT4CO8-gXY1tQeZsb-8,9291
|
|
3
|
+
vexel_cli/core.py,sha256=DNSzhQ0Pf8xBAnWYOTixu0yujK_rKOHz_UDBPmbFwa0,8120
|
|
4
|
+
vexel_cli/templates.py,sha256=6OsV4UMuR8gAV_NQDTsY8jxKBJJ9YRWy2yORav-GMVs,2205
|
|
5
|
+
vexel_cli-0.1.0.dist-info/METADATA,sha256=TkzTExt9g-ysY6r32jHJYPH1mh0b5cTm9SpA_dqbXvs,1698
|
|
6
|
+
vexel_cli-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
vexel_cli-0.1.0.dist-info/entry_points.txt,sha256=-NPYogInfBi2GGfqF4VGVQPbZpu47G8BODkNBFCSwBg,45
|
|
8
|
+
vexel_cli-0.1.0.dist-info/top_level.txt,sha256=7MQYqHFxditRAf9dTbc5pJPiOj-QEvMoQZXwQH7Ol0Y,10
|
|
9
|
+
vexel_cli-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
vexel_cli
|