tokensafe 2.0.1 → 2.2.0
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.
- package/README.md +184 -334
- package/bin/tokensafe.js +2 -1
- package/hooks/pre_tool_use.py +11 -6
- package/package.json +4 -3
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +16 -8
- package/src/__init__.py +1 -1
- package/src/adapter_core.py +37 -3
- package/src/cli.py +127 -1
- package/src/command_sanitizer.py +264 -120
- package/src/dashboard.py +1 -1
- package/src/diff_slicer.py +18 -2
- package/src/guard.py +3 -1
- package/src/installer.py +1 -1
- package/src/mcp_server.py +66 -3
- package/src/metrics.py +16 -1
- package/src/slicer.py +69 -3
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
- package/src/weekly_digest.py +118 -42
package/src/command_sanitizer.py
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
Command Sanitizer: Intercepts and rewrites shell commands in PreToolUse
|
|
3
3
|
to prevent context window poisoning from lockfile diffs, unconstrained logs,
|
|
4
4
|
and verbose test output.
|
|
5
|
+
|
|
6
|
+
Every rule operates per-stage: compound commands (a && b ; c | d) are split
|
|
7
|
+
quote-aware, each stage is optimized independently, and the result is rejoined
|
|
8
|
+
so rewrites never leak pathspecs into an unrelated stage (e.g. lockfile
|
|
9
|
+
excludes landing on `npm test` after `git diff && npm test`).
|
|
5
10
|
"""
|
|
6
11
|
|
|
7
12
|
import re
|
|
@@ -10,18 +15,57 @@ from typing import Tuple, Dict, Any, List, Optional
|
|
|
10
15
|
class CommandSanitizer:
|
|
11
16
|
"""Optimizes terminal command lines to eliminate token waste."""
|
|
12
17
|
|
|
18
|
+
# Lockfiles and binary patterns that should never be dumped in git diffs or searches
|
|
19
|
+
LOCKFILE_EXCLUDES = [
|
|
20
|
+
"':!package-lock.json'",
|
|
21
|
+
"':!pnpm-lock.yaml'",
|
|
22
|
+
"':!yarn.lock'",
|
|
23
|
+
"':!bun.lock'",
|
|
24
|
+
"':!bun.lockb'",
|
|
25
|
+
"':!Cargo.lock'",
|
|
26
|
+
"':!go.sum'",
|
|
27
|
+
"':!composer.lock'",
|
|
28
|
+
"':!*.lock'",
|
|
29
|
+
"':!*.min.js'",
|
|
30
|
+
"':!*.min.css'",
|
|
31
|
+
"':!*.bundle.js'",
|
|
32
|
+
"':!*.map'",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
# Files whose `cat` dumps thousands of near-useless tokens into context
|
|
36
|
+
_CAT_JUNK_RE = re.compile(
|
|
37
|
+
r"(^|/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lock|bun\.lockb"
|
|
38
|
+
r"|Cargo\.lock|go\.sum|composer\.lock|poetry\.lock|Gemfile\.lock"
|
|
39
|
+
r"|.*\.min\.js|.*\.min\.css|.*\.bundle\.js|.*\.map)$"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
# Output limiters that make an extra `| head` at the end redundant
|
|
43
|
+
_LIMITER_RE = re.compile(r"\b(head|tail|less|wc|jq)\b")
|
|
44
|
+
|
|
45
|
+
# (unit, limit) specs for end-of-command output caps
|
|
46
|
+
_CAP_LINES_30 = ("n", 30)
|
|
47
|
+
_CAP_LINES_200 = ("n", 200)
|
|
48
|
+
_CAP_BYTES_4K = ("c", 4096)
|
|
49
|
+
|
|
13
50
|
@staticmethod
|
|
14
|
-
def
|
|
51
|
+
def split_stages(cmd: str) -> List[Tuple[str, str]]:
|
|
15
52
|
"""
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
53
|
+
Quote-aware split of a shell command into (operator, stage) pairs.
|
|
54
|
+
Operators: '' (first stage), '|', '||', '&&', ';'. Stages are stripped;
|
|
55
|
+
rejoining with join_stages() yields an equivalent command line.
|
|
19
56
|
"""
|
|
20
|
-
|
|
57
|
+
pairs: List[Tuple[str, str]] = []
|
|
21
58
|
buf: List[str] = []
|
|
22
59
|
quote = ""
|
|
60
|
+
pending_op = "" # operator preceding the stage being collected
|
|
23
61
|
i = 0
|
|
24
62
|
n = len(cmd)
|
|
63
|
+
|
|
64
|
+
def flush():
|
|
65
|
+
stage = "".join(buf).strip()
|
|
66
|
+
buf.clear()
|
|
67
|
+
pairs.append((pending_op, stage))
|
|
68
|
+
|
|
25
69
|
while i < n:
|
|
26
70
|
ch = cmd[i]
|
|
27
71
|
if quote:
|
|
@@ -36,140 +80,240 @@ class CommandSanitizer:
|
|
|
36
80
|
elif ch in ("'", '"', "`"):
|
|
37
81
|
quote = ch
|
|
38
82
|
buf.append(ch)
|
|
83
|
+
elif ch == "&" and i + 1 < n and cmd[i + 1] == "&":
|
|
84
|
+
flush()
|
|
85
|
+
pending_op = "&&"
|
|
86
|
+
i += 2
|
|
87
|
+
continue
|
|
88
|
+
elif ch == "|" and i + 1 < n and cmd[i + 1] == "|":
|
|
89
|
+
flush()
|
|
90
|
+
pending_op = "||"
|
|
91
|
+
i += 2
|
|
92
|
+
continue
|
|
39
93
|
elif ch == "|":
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
buf = []
|
|
94
|
+
flush()
|
|
95
|
+
pending_op = "|"
|
|
96
|
+
elif ch == ";":
|
|
97
|
+
flush()
|
|
98
|
+
pending_op = ";"
|
|
46
99
|
else:
|
|
47
100
|
buf.append(ch)
|
|
48
101
|
i += 1
|
|
49
|
-
|
|
102
|
+
flush()
|
|
103
|
+
# Drop empty stages but keep at least one slot so rejoin stays valid
|
|
104
|
+
cleaned = [(op, s) for op, s in pairs if s]
|
|
105
|
+
if not cleaned:
|
|
106
|
+
cleaned = [("", "")]
|
|
107
|
+
return cleaned
|
|
108
|
+
|
|
109
|
+
@staticmethod
|
|
110
|
+
def join_stages(pairs: List[Tuple[str, str]]) -> str:
|
|
111
|
+
"""Rejoins (operator, stage) pairs from split_stages into a command line."""
|
|
112
|
+
out = ""
|
|
113
|
+
for op, stage in pairs:
|
|
114
|
+
if not out:
|
|
115
|
+
out = stage
|
|
116
|
+
elif op == "|":
|
|
117
|
+
out += f" | {stage}"
|
|
118
|
+
else:
|
|
119
|
+
out += f" {op} {stage}"
|
|
120
|
+
return out
|
|
121
|
+
|
|
122
|
+
@staticmethod
|
|
123
|
+
def _split_pipeline_stages(cmd: str) -> List[str]:
|
|
124
|
+
"""
|
|
125
|
+
Splits a shell command on single '|' pipe operators while respecting
|
|
126
|
+
quoting ('...', "...", `...`) and '||' logical OR, so regex patterns like
|
|
127
|
+
grep "foo|bar" are never torn apart mid-string.
|
|
128
|
+
"""
|
|
129
|
+
pairs = CommandSanitizer.split_stages(cmd)
|
|
130
|
+
# Legacy contract: only pipe boundaries split; '&&'/';'/'||' stay inside stages.
|
|
131
|
+
stages: List[str] = []
|
|
132
|
+
pipe_open = False
|
|
133
|
+
for op, stage in pairs:
|
|
134
|
+
if op in ("", "|"):
|
|
135
|
+
if pipe_open and stages:
|
|
136
|
+
stages[-1] = f"{stages[-1]} | {stage}"
|
|
137
|
+
else:
|
|
138
|
+
stages.append(stage)
|
|
139
|
+
pipe_open = op == "|"
|
|
140
|
+
else:
|
|
141
|
+
# Non-pipe operator: glue operator + stage back into current stage
|
|
142
|
+
if stages:
|
|
143
|
+
stages[-1] = f"{stages[-1]} {op} {stage}"
|
|
144
|
+
else:
|
|
145
|
+
stages.append(stage)
|
|
50
146
|
return [s for s in (st.strip() for st in stages) if s]
|
|
51
147
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
"':!yarn.lock'",
|
|
57
|
-
"':!bun.lock'",
|
|
58
|
-
"':!bun.lockb'",
|
|
59
|
-
"':!Cargo.lock'",
|
|
60
|
-
"':!go.sum'",
|
|
61
|
-
"':!composer.lock'",
|
|
62
|
-
"':!*.lock'",
|
|
63
|
-
"':!*.min.js'",
|
|
64
|
-
"':!*.min.css'",
|
|
65
|
-
"':!*.bundle.js'",
|
|
66
|
-
"':!*.map'",
|
|
67
|
-
]
|
|
148
|
+
@staticmethod
|
|
149
|
+
def _has_redirect(stage: str) -> bool:
|
|
150
|
+
"""True if the stage redirects stdout somewhere (> , >>, 2>, &>)."""
|
|
151
|
+
return bool(re.search(r"(^|\s)[0-9&]*>{1,2}", stage))
|
|
68
152
|
|
|
69
153
|
@classmethod
|
|
70
|
-
def
|
|
154
|
+
def _optimize_stage(cls, stage: str) -> Optional[Tuple[str, int, str, Optional[Tuple[str, int]]]]:
|
|
71
155
|
"""
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
156
|
+
Applies one rewrite rule to a single stage.
|
|
157
|
+
Returns (new_stage, est_saved, reason, cap_spec) or None.
|
|
158
|
+
cap_spec = (unit, limit) marks rules whose unbounded output must be
|
|
159
|
+
capped; the cap is appended to the END of the whole command (never
|
|
160
|
+
mid-compound), so `||` / `&&` exit-status semantics are untouched.
|
|
161
|
+
new_stage may equal stage for cap-only rules (git show, blame, curl).
|
|
75
162
|
"""
|
|
76
|
-
if not command or not command.strip():
|
|
77
|
-
return None, 0, ""
|
|
78
|
-
|
|
79
|
-
cmd = command.strip()
|
|
80
|
-
has_compound_operators = bool(re.search(r"(&&|\|\||;)", cmd))
|
|
81
163
|
|
|
82
|
-
#
|
|
83
|
-
if re.search(r"\bgit\s+diff\b",
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
tokens = cmd.split()[2:] # args after git diff
|
|
164
|
+
# git diff: exclude lockfiles/bundles when diffing unscoped repository
|
|
165
|
+
if re.search(r"\bgit\s+diff\b", stage):
|
|
166
|
+
if ":!package-lock" not in stage and ":!*.lock" not in stage and ":!" not in stage:
|
|
167
|
+
tokens = stage.split()[2:] # args after git diff
|
|
87
168
|
has_path = any(not t.startswith('-') and not re.match(r'^(HEAD(~[0-9]+)?|main|master|[0-9a-f]{7,40})$', t) for t in tokens)
|
|
88
169
|
if not has_path:
|
|
89
170
|
excludes_str = " ".join(cls.LOCKFILE_EXCLUDES)
|
|
90
|
-
if " -- " in
|
|
91
|
-
|
|
171
|
+
if " -- " in stage:
|
|
172
|
+
new_stage = f"{stage} {excludes_str}"
|
|
92
173
|
else:
|
|
93
|
-
|
|
174
|
+
new_stage = f"{stage} -- {excludes_str}"
|
|
175
|
+
return new_stage, 3500, "Excluded lockfiles/bundles from git diff", None
|
|
94
176
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
# 2. git log optimization (Cap unbounded commit history)
|
|
99
|
-
if re.search(r"\bgit\s+log\b", cmd):
|
|
100
|
-
# Check if already limited by -n, -[0-9], or --max-count
|
|
101
|
-
has_limit = re.search(r"(\s-[0-9]+|\s-n\s*\d+|\s--max-count[=\s]\d+)", cmd)
|
|
177
|
+
# git log: cap unbounded commit history
|
|
178
|
+
if re.search(r"\bgit\s+log\b", stage):
|
|
179
|
+
has_limit = re.search(r"(\s-[0-9]+|\s-n\s*\d+|\s--max-count[=\s]\d+)", stage)
|
|
102
180
|
if not has_limit:
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
new_cmd = re.sub(r"\bgit\s+log\b", "git log -n 10 --oneline", cmd, count=1)
|
|
181
|
+
if "--oneline" not in stage:
|
|
182
|
+
new_stage = re.sub(r"\bgit\s+log\b", "git log -n 10 --oneline", stage, count=1)
|
|
106
183
|
else:
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
return new_cmd, est_saved, "Capped unbounded git log to 10 entries"
|
|
184
|
+
new_stage = re.sub(r"\bgit\s+log\b", "git log -n 10", stage, count=1)
|
|
185
|
+
return new_stage, 1200, "Capped unbounded git log to 10 entries", None
|
|
110
186
|
|
|
111
|
-
#
|
|
112
|
-
if re.search(r"\bpytest\b",
|
|
113
|
-
has_tb = "--tb=" in
|
|
187
|
+
# pytest: compact quiet traceback
|
|
188
|
+
if re.search(r"\bpytest\b", stage):
|
|
189
|
+
has_tb = "--tb=" in stage or "-q" in stage
|
|
114
190
|
if not has_tb:
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
# 5. git grep search (Exclude lockfiles & directories via pathspecs)
|
|
127
|
-
if re.search(r"\bgit\b.*?\bgrep\b", cmd):
|
|
128
|
-
if ":!*.lock" not in cmd and ":!bun.lock" not in cmd:
|
|
191
|
+
return f"{stage} -q --tb=short", 800, "Applied short traceback to pytest", None
|
|
192
|
+
|
|
193
|
+
# find: prune unbounded recursion
|
|
194
|
+
if re.search(r"\bfind\s+(\.|\/|\w+)\s*$", stage) or re.search(r"\bfind\s+\.\s+-name\b", stage):
|
|
195
|
+
if "node_modules" not in stage and ".git" not in stage:
|
|
196
|
+
new_stage = f"{stage} -not -path '*/.*' -not -path '*/node_modules/*' -not -path '*/venv/*'"
|
|
197
|
+
return new_stage, 1500, "Pruned .git, node_modules, and venv from find", None
|
|
198
|
+
|
|
199
|
+
# git grep: exclude lockfiles & generated dirs via pathspecs
|
|
200
|
+
if re.search(r"\bgit\b.*?\bgrep\b", stage):
|
|
201
|
+
if ":!*.lock" not in stage and ":!bun.lock" not in stage:
|
|
129
202
|
git_excludes = "':!*.lock' ':!bun.lock' ':!bun.lockb' ':!package-lock.json' ':!dist' ':!build' ':!node_modules'"
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
stages[i] = f"{left} || {right.strip()}"
|
|
141
|
-
elif " -- " in stage:
|
|
142
|
-
stages[i] = f"{stage} {git_excludes}"
|
|
143
|
-
else:
|
|
144
|
-
stages[i] = f"{stage} -- . {git_excludes}"
|
|
145
|
-
new_cmd = " | ".join(stages)
|
|
146
|
-
has_limiter = any(re.search(r'\b(head|tail|less)\b', s) for s in stages)
|
|
147
|
-
if not has_limiter:
|
|
148
|
-
new_cmd = f"{new_cmd} | head -n 30"
|
|
149
|
-
est_saved = 3500
|
|
150
|
-
return new_cmd, est_saved, "Excluded lockfiles from git grep and capped output"
|
|
151
|
-
|
|
152
|
-
# 6. grep / ripgrep unbounded search (only when recursive or scanning directory)
|
|
153
|
-
if re.search(r"\b(grep|egrep)\b", cmd) and not re.search(r"\bgit\b.*?\bgrep\b", cmd):
|
|
154
|
-
is_recursive = bool(re.search(r"\b(grep|egrep)\b.*?\s-[a-zA-Z]*[rR]", cmd))
|
|
155
|
-
if is_recursive and "--exclude-dir" not in cmd and "node_modules" not in cmd:
|
|
203
|
+
if " -- " in stage:
|
|
204
|
+
new_stage = f"{stage} {git_excludes}"
|
|
205
|
+
else:
|
|
206
|
+
new_stage = f"{stage} -- . {git_excludes}"
|
|
207
|
+
return new_stage, 3500, "Excluded lockfiles from git grep and capped output", cls._CAP_LINES_30
|
|
208
|
+
|
|
209
|
+
# grep / egrep recursive search: exclude junk dirs and cap output
|
|
210
|
+
if re.search(r"\b(grep|egrep)\b", stage) and not re.search(r"\bgit\b.*?\bgrep\b", stage):
|
|
211
|
+
is_recursive = bool(re.search(r"\b(grep|egrep)\b.*?\s-[a-zA-Z]*[rR]", stage))
|
|
212
|
+
if is_recursive and "--exclude-dir" not in stage and "node_modules" not in stage:
|
|
156
213
|
excludes = "--exclude='*.lock' --exclude='*.lockb' --exclude-dir={dist,build,node_modules,.git,coverage,__pycache__,.next,data}"
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
if
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
214
|
+
return f"{stage} {excludes}", 2500, "Sanitized grep directories and capped output to 30 matches", cls._CAP_LINES_30
|
|
215
|
+
|
|
216
|
+
# ripgrep: cap per-command output; add ignore excludes only for --no-ignore runs
|
|
217
|
+
if re.search(r"(^|\s|\()rg\b", stage) and "-- " not in stage:
|
|
218
|
+
if "-m " not in stage and "--max-count" not in stage and "-g " not in stage:
|
|
219
|
+
new_stage = stage
|
|
220
|
+
if "--no-ignore" in stage:
|
|
221
|
+
new_stage += " -g '!node_modules' -g '!.git' -g '!dist' -g '!build'"
|
|
222
|
+
return new_stage, 2500, "Capped rg output to 30 matches and excluded junk dirs", cls._CAP_LINES_30
|
|
223
|
+
|
|
224
|
+
# git show: full patch dumps are capped
|
|
225
|
+
if re.search(r"\bgit\s+show\b", stage):
|
|
226
|
+
if not re.search(r"--stat|--name-only|--name-status|\s-s\b|--oneline", stage):
|
|
227
|
+
return stage, 1500, "Capped git show patch output", cls._CAP_LINES_200
|
|
228
|
+
|
|
229
|
+
# git blame: one output line per file line — huge on big files unless -L limited
|
|
230
|
+
if re.search(r"\bgit\s+blame\b", stage):
|
|
231
|
+
if "-L" not in stage:
|
|
232
|
+
return stage, 1500, "Capped git blame output", cls._CAP_LINES_200
|
|
233
|
+
|
|
234
|
+
# docker logs: bound container log dumps
|
|
235
|
+
if re.search(r"\bdocker\s+(container\s+)?logs\b", stage):
|
|
236
|
+
if "--tail" not in stage and not re.search(r"\s-n\s*\d+", stage):
|
|
237
|
+
return f"{stage} --tail 100", 2000, "Capped docker logs to last 100 lines", None
|
|
238
|
+
|
|
239
|
+
# kubectl logs: bound pod log dumps
|
|
240
|
+
if re.search(r"\bkubectl\s+logs\b", stage):
|
|
241
|
+
if "--tail" not in stage:
|
|
242
|
+
return f"{stage} --tail=100", 2000, "Capped kubectl logs to last 100 lines", None
|
|
243
|
+
|
|
244
|
+
# npm installs: suppress progress bars, funding and audit noise
|
|
245
|
+
if re.search(r"\bnpm\s+(install|i|ci|add)\b", stage):
|
|
246
|
+
if "--no-audit" not in stage:
|
|
247
|
+
return f"{stage} --no-progress --no-fund --no-audit", 600, "Silenced npm install progress/audit output", None
|
|
248
|
+
|
|
249
|
+
# pip installs: quiet mode keeps dependency walls out of context
|
|
250
|
+
if re.search(r"\bpip3?\s+install\b", stage):
|
|
251
|
+
if not re.search(r"\s-q\b|--quiet", stage):
|
|
252
|
+
return f"{stage} -q", 400, "Applied quiet mode to pip install", None
|
|
253
|
+
|
|
254
|
+
# cat on lockfiles/minified bundles: switch to a bounded head window
|
|
255
|
+
if re.match(r"\bcat\s", stage):
|
|
256
|
+
if not cls._has_redirect(stage):
|
|
257
|
+
parts = stage.split()
|
|
258
|
+
paths = parts[1:]
|
|
259
|
+
if paths and all(not p.startswith("-") for p in paths):
|
|
260
|
+
if any(cls._CAT_JUNK_RE.search(p) for p in paths):
|
|
261
|
+
return f"head -n 120 {' '.join(paths)}", 3000, "Replaced cat of lockfile/bundle with bounded head", None
|
|
262
|
+
|
|
263
|
+
# curl printing to stdout (JSON/HTML dumps land in context): bounded byte cap
|
|
264
|
+
if re.search(r"\bcurl\b", stage):
|
|
265
|
+
if not re.search(r"-o\s|-O\b|--output|-F\b|--form|-T\b|--upload-file|-I\b|--head", stage):
|
|
266
|
+
return stage, 3000, "Capped curl stdout to 4096 bytes", cls._CAP_BYTES_4K
|
|
267
|
+
|
|
268
|
+
# ls: replace verbose permissions/timestamps with compact single-column format
|
|
269
|
+
if re.search(r"\bls\b", stage):
|
|
270
|
+
if re.search(r"\bls\s+-[a-zA-Z]*(l|a)[a-zA-Z]*\b", stage):
|
|
271
|
+
new_stage = re.sub(r"\bls\s+-[a-zA-Z]+\b", "ls -1 -p", stage)
|
|
272
|
+
return new_stage, 380, "Replaced verbose ls flags with compact, secret-safe format (-1 -p)", None
|
|
273
|
+
|
|
274
|
+
return None
|
|
275
|
+
|
|
276
|
+
@classmethod
|
|
277
|
+
def sanitize(cls, command: str) -> Tuple[Optional[str], int, str]:
|
|
278
|
+
"""
|
|
279
|
+
Analyzes a shell command stage by stage. If any stage creates massive
|
|
280
|
+
token waste, returns (rewritten_command, est_tokens_saved, reason).
|
|
281
|
+
If no change is needed, returns (None, 0, "").
|
|
282
|
+
"""
|
|
283
|
+
if not command or not command.strip():
|
|
284
|
+
return None, 0, ""
|
|
285
|
+
|
|
286
|
+
pairs = cls.split_stages(command.strip())
|
|
287
|
+
string_changed = False
|
|
288
|
+
total_saved = 0
|
|
289
|
+
reasons: List[str] = []
|
|
290
|
+
cap_spec: Optional[Tuple[str, int]] = None
|
|
291
|
+
|
|
292
|
+
for i, (op, stage) in enumerate(pairs):
|
|
293
|
+
res = cls._optimize_stage(stage)
|
|
294
|
+
if not res:
|
|
295
|
+
continue
|
|
296
|
+
new_stage, saved, reason, rule_cap = res
|
|
297
|
+
if new_stage != stage:
|
|
298
|
+
pairs[i] = (op, new_stage)
|
|
299
|
+
string_changed = True
|
|
300
|
+
total_saved += saved
|
|
301
|
+
reasons.append(reason)
|
|
302
|
+
# Only the FINAL stage may request the end-of-command cap: an
|
|
303
|
+
# earlier stage's cap would land after unrelated trailing stages
|
|
304
|
+
# (e.g. capping `npm test` instead of the `git grep` that fed it).
|
|
305
|
+
if rule_cap and i == len(pairs) - 1:
|
|
306
|
+
cap_spec = rule_cap
|
|
307
|
+
|
|
308
|
+
cap_applied = False
|
|
309
|
+
if cap_spec:
|
|
310
|
+
last_stage = pairs[-1][1]
|
|
311
|
+
if not cls._LIMITER_RE.search(last_stage) and not cls._has_redirect(last_stage):
|
|
312
|
+
unit, limit = cap_spec
|
|
313
|
+
pairs[-1] = (pairs[-1][0], f"{last_stage} | head -{unit} {limit}")
|
|
314
|
+
cap_applied = True
|
|
315
|
+
|
|
316
|
+
if not (string_changed or cap_applied):
|
|
317
|
+
return None, 0, ""
|
|
318
|
+
|
|
319
|
+
return cls.join_stages(pairs), total_saved, "; ".join(reasons)
|
package/src/dashboard.py
CHANGED
|
@@ -314,7 +314,7 @@ class Dashboard:
|
|
|
314
314
|
<div class="header">
|
|
315
315
|
<div>
|
|
316
316
|
<h1 class="title">⚡ TokenSafe</h1>
|
|
317
|
-
<p class="subtitle">
|
|
317
|
+
<p class="subtitle">Local-First AI Coding Guardrails & Context Telemetry</p>
|
|
318
318
|
</div>
|
|
319
319
|
<div id="live-pill" class="subtitle" style="display: flex; align-items: center; gap: 6px;">
|
|
320
320
|
<span style="color: #10b981;">●</span> Live SQLite Tracking
|
package/src/diff_slicer.py
CHANGED
|
@@ -106,6 +106,9 @@ class DiffSlicer:
|
|
|
106
106
|
def optimize_git_diff_command(cls, cmd: str) -> Tuple[Optional[str], int, str]:
|
|
107
107
|
"""
|
|
108
108
|
Rewrites git diff commands to enforce 2-line unified diffs and ignore lockfiles.
|
|
109
|
+
Per-stage: excludes are appended to each `git diff` stage itself, never
|
|
110
|
+
to the tail of a compound command (which would leak pathspecs into an
|
|
111
|
+
unrelated trailing command like `npm test`).
|
|
109
112
|
"""
|
|
110
113
|
clean_cmd = cmd.strip()
|
|
111
114
|
if not re.search(r"\bgit\s+diff\b", clean_cmd):
|
|
@@ -114,7 +117,20 @@ class DiffSlicer:
|
|
|
114
117
|
if "--unified=" in clean_cmd or "-U" in clean_cmd:
|
|
115
118
|
return None, 0, ""
|
|
116
119
|
|
|
120
|
+
from src.command_sanitizer import CommandSanitizer
|
|
121
|
+
pairs = CommandSanitizer.split_stages(clean_cmd)
|
|
117
122
|
lockfile_excludes = " ':!*lock*' ':!*.min.*' ':!*.map'"
|
|
118
|
-
|
|
123
|
+
changed = False
|
|
124
|
+
for i, (op, stage) in enumerate(pairs):
|
|
125
|
+
if not re.search(r"\bgit\s+diff\b", stage):
|
|
126
|
+
continue
|
|
127
|
+
if ":!" in stage:
|
|
128
|
+
continue # caller already manages pathspec excludes
|
|
129
|
+
pairs[i] = (op, stage.replace("git diff", "git diff -U2", 1) + lockfile_excludes)
|
|
130
|
+
changed = True
|
|
131
|
+
|
|
132
|
+
if not changed:
|
|
133
|
+
return None, 0, ""
|
|
134
|
+
|
|
119
135
|
est_saved = 4000
|
|
120
|
-
return
|
|
136
|
+
return CommandSanitizer.join_stages(pairs), est_saved, "Enforced 2-line AST diff window and excluded lockfiles"
|
package/src/guard.py
CHANGED
|
@@ -331,7 +331,9 @@ class TokenSafeGuard:
|
|
|
331
331
|
if grep_match:
|
|
332
332
|
has_code_ext = any(ext in sub_cmd for ext in cls.CODE_EXTENSIONS)
|
|
333
333
|
has_code_dir = any(re.search(rf'\b{re.escape(d)}(?:/|\b)', sub_cmd) for d in cls.CODE_DIRS)
|
|
334
|
-
|
|
334
|
+
# '-rn' / '-Rn' are the canonical recursive forms — the flag
|
|
335
|
+
# regex must accept letters after r/R, plus the long --recursive.
|
|
336
|
+
is_recursive_all = bool(re.search(r'\b(grep|egrep)\b.*?\s(?:-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)\b', sub_cmd)) or \
|
|
335
337
|
bool(re.search(r'\brg\b', sub_cmd))
|
|
336
338
|
|
|
337
339
|
if has_code_ext or has_code_dir or is_recursive_all:
|
package/src/installer.py
CHANGED
|
@@ -40,7 +40,7 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
40
40
|
"2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. It preserves the full executable target and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
|
|
41
41
|
"3. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path)` before exploratory multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
|
|
42
42
|
"4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.\n"
|
|
43
|
-
"5. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `
|
|
43
|
+
"5. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`) — compound commands (`a && b ; c`) are rewritten per stage. Run unit tests via the `tokensafe tests [pytest]` CLI (compact failure report) instead of raw `python3 -m unittest discover`; never leave `vitest`/`jest` in watch mode.\n"
|
|
44
44
|
"6. **Proof-of-Savings Turn Footer (always in English)**:\n"
|
|
45
45
|
"At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:\n"
|
|
46
46
|
"`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
|
package/src/mcp_server.py
CHANGED
|
@@ -39,7 +39,7 @@ from src.scoped_search import ScopedSearch
|
|
|
39
39
|
|
|
40
40
|
SERVER_INFO = {
|
|
41
41
|
"name": "tokensafe-mcp",
|
|
42
|
-
"version": "2.0
|
|
42
|
+
"version": "2.2.0"
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -128,7 +128,10 @@ TOOLS = [
|
|
|
128
128
|
},
|
|
129
129
|
{
|
|
130
130
|
"name": "sanitize_command",
|
|
131
|
-
"description": "
|
|
131
|
+
"description": "Per-stage shell command rewrites: prunes lockfiles, caps unbounded git log/show/blame/rg "
|
|
132
|
+
"and docker/kubectl logs, quiets npm/pip installs, bounds cat/curl output. Compound commands "
|
|
133
|
+
"(a && b ; c) are optimized per stage without breaking operators. For unit-test runs prefer "
|
|
134
|
+
"the `tests` CLI wrapper (tokensafe tests [pytest]) over raw `python3 -m unittest discover`.",
|
|
132
135
|
"inputSchema": {
|
|
133
136
|
"type": "object",
|
|
134
137
|
"properties": {
|
|
@@ -159,7 +162,7 @@ TOOLS = [
|
|
|
159
162
|
},
|
|
160
163
|
{
|
|
161
164
|
"name": "guard_inspect",
|
|
162
|
-
"description": "Pre-flight security & hygiene audit for commands or code snippets. Detects secret leaks, SQL injection, TLS bypass, CORS wildcard, destructive commands, and
|
|
165
|
+
"description": "Pre-flight security & hygiene audit for commands or code snippets. Detects secret leaks, SQL injection, TLS bypass (incl. git-level), CORS wildcard, destructive commands, raw grep, and never-terminating streams (tail -f, watch, docker attach).",
|
|
163
166
|
"inputSchema": {
|
|
164
167
|
"type": "object",
|
|
165
168
|
"properties": {
|
|
@@ -703,6 +706,66 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
703
706
|
optimized_tokens=0,
|
|
704
707
|
details={"cmd": cmd[:100], "reason": c_res.reason}
|
|
705
708
|
)
|
|
709
|
+
else:
|
|
710
|
+
# Adapter-level command checks (v2.1.0): TokenSafeGuard's
|
|
711
|
+
# command audit does not scan for literal credentials, so
|
|
712
|
+
# deny-level secrets/destruction come from the adapter core —
|
|
713
|
+
# the same patterns the Claude Code / Cursor shell guards use.
|
|
714
|
+
try:
|
|
715
|
+
from src.adapter_core import (_SECRET_PATTERNS, _DESTRUCTIVE_PATTERNS,
|
|
716
|
+
_INFINITE_PATTERNS, _TLS_BYPASS_PATTERNS)
|
|
717
|
+
hit = None
|
|
718
|
+
for pat in _SECRET_PATTERNS:
|
|
719
|
+
if re.search(pat, cmd):
|
|
720
|
+
hit = ("SECRET", "Blocked: command contains a hardcoded secret", True)
|
|
721
|
+
break
|
|
722
|
+
if hit is None:
|
|
723
|
+
for pat in _DESTRUCTIVE_PATTERNS:
|
|
724
|
+
if re.search(pat, cmd):
|
|
725
|
+
hit = ("DESTRUCTIVE", "Blocked: irreversible/destructive operation", True)
|
|
726
|
+
break
|
|
727
|
+
if hit:
|
|
728
|
+
results.append({
|
|
729
|
+
"target": "command",
|
|
730
|
+
"input": cmd,
|
|
731
|
+
"allowed": False,
|
|
732
|
+
"blocked": True,
|
|
733
|
+
"check_name": hit[0],
|
|
734
|
+
"reason": hit[1],
|
|
735
|
+
"warning_only": False
|
|
736
|
+
})
|
|
737
|
+
tracker.record_event(
|
|
738
|
+
session_id=_mcp_session_id(),
|
|
739
|
+
event_type=f"GUARD_{hit[0]}",
|
|
740
|
+
original_tokens=count_tokens(cmd),
|
|
741
|
+
optimized_tokens=0,
|
|
742
|
+
details={"cmd": cmd[:100], "reason": hit[1]}
|
|
743
|
+
)
|
|
744
|
+
else:
|
|
745
|
+
# Advisory tier: infinite streams and TLS bypass never
|
|
746
|
+
# block an inspection, and inspections write no events.
|
|
747
|
+
advisory = None
|
|
748
|
+
for pat in _INFINITE_PATTERNS:
|
|
749
|
+
if re.search(pat, cmd):
|
|
750
|
+
advisory = ("INFINITE_STREAM", "Command never terminates on its own (follow/streaming) — run it in the background or confirm intent")
|
|
751
|
+
break
|
|
752
|
+
if advisory is None:
|
|
753
|
+
for pat in _TLS_BYPASS_PATTERNS:
|
|
754
|
+
if re.search(pat, cmd):
|
|
755
|
+
advisory = ("TLS_VERIFY_BYPASS", "Certificate verification disabled — confirm this is intentional")
|
|
756
|
+
break
|
|
757
|
+
if advisory:
|
|
758
|
+
results.append({
|
|
759
|
+
"target": "command",
|
|
760
|
+
"input": cmd,
|
|
761
|
+
"allowed": True,
|
|
762
|
+
"blocked": False,
|
|
763
|
+
"check_name": advisory[0],
|
|
764
|
+
"reason": advisory[1],
|
|
765
|
+
"warning_only": True
|
|
766
|
+
})
|
|
767
|
+
except Exception:
|
|
768
|
+
pass
|
|
706
769
|
|
|
707
770
|
if code is not None:
|
|
708
771
|
w_res = TokenSafeGuard.inspect_file_write(file_path, code)
|
package/src/metrics.py
CHANGED
|
@@ -24,11 +24,22 @@ USD_PER_TOKEN = 1.50 / 1_000_000.0
|
|
|
24
24
|
# replace-mode is verified end-to-end.
|
|
25
25
|
# ROLLUP_LIFETIME: pruned-and-rolled-up historical mass of mixed provenance;
|
|
26
26
|
# conservatively labelled estimated.
|
|
27
|
+
# Counterfactual event types: their original_tokens are heuristic guesses of
|
|
28
|
+
# output that WOULD have entered context (command rewrites, blocked calls,
|
|
29
|
+
# prompt compaction), not metered I/O deltas. See METRICS.md.
|
|
27
30
|
ESTIMATED_EVENT_TYPES = frozenset({
|
|
28
31
|
"GRAPH_TOPOLOGY",
|
|
29
32
|
"HISTORY_FOLD",
|
|
30
33
|
"PROMPT",
|
|
31
34
|
"ROLLUP_LIFETIME",
|
|
35
|
+
"COMMAND_FILTER",
|
|
36
|
+
"LOOP_GUARD",
|
|
37
|
+
"GUARD_SECRET",
|
|
38
|
+
"GUARD_DESTRUCTIVE",
|
|
39
|
+
"GUARD_TLS_VERIFY_BYPASS",
|
|
40
|
+
"GUARD_JUNK_READ",
|
|
41
|
+
"GUARD_INFINITE",
|
|
42
|
+
"GUARD_RAW_CODE_SEARCH",
|
|
32
43
|
})
|
|
33
44
|
|
|
34
45
|
def resolve_measurement(event_type: str, explicit: Optional[str] = None) -> str:
|
|
@@ -163,7 +174,11 @@ class MetricsTracker:
|
|
|
163
174
|
cursor.execute(
|
|
164
175
|
"UPDATE events SET measurement = 'estimated' "
|
|
165
176
|
"WHERE measurement = 'measured' AND event_type IN "
|
|
166
|
-
"('GRAPH_TOPOLOGY', 'HISTORY_FOLD', 'PROMPT', 'ROLLUP_LIFETIME'
|
|
177
|
+
"('GRAPH_TOPOLOGY', 'HISTORY_FOLD', 'PROMPT', 'ROLLUP_LIFETIME', "
|
|
178
|
+
"'COMMAND_FILTER', 'LOOP_GUARD', 'GUARD_SECRET', "
|
|
179
|
+
"'GUARD_DESTRUCTIVE', 'GUARD_TLS_VERIFY_BYPASS', "
|
|
180
|
+
"'GUARD_JUNK_READ', 'GUARD_INFINITE', "
|
|
181
|
+
"'GUARD_RAW_CODE_SEARCH');"
|
|
167
182
|
)
|
|
168
183
|
cursor.execute("""
|
|
169
184
|
CREATE TABLE IF NOT EXISTS lifetime_aggregates (
|