@alexgreensh/token-optimizer 5.13.66 → 5.13.67
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/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/hooks.json +0 -10
- package/package.json +1 -1
- package/skills/token-optimizer/examples/hooks-starter.json +0 -10
- package/skills/token-optimizer/scripts/_measure/_compat.py +2 -2
- package/skills/token-optimizer/scripts/_measure/_vendor/README.md +9 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +23 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/LICENSE +21 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +8 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_parser.py +770 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_re.py +112 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_types.py +10 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/py.typed +1 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +54 -1
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +198 -5
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +11 -3
- package/skills/token-optimizer/scripts/bash_compress.py +3 -3
- package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -7
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +2 -2
- package/skills/token-optimizer/scripts/command_filters.py +630 -19
- package/skills/token-optimizer/scripts/devin_source.py +1 -1
- package/skills/token-optimizer/scripts/measure.py +2 -2
- package/skills/token-optimizer/scripts/read_cache.py +20 -21
- package/skills/token-optimizer/scripts/reset_epoch.py +177 -0
- package/skills/token-optimizer/scripts/session_store.py +11 -48
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
Lets a user opt NEW read-only commands into existing compression handlers
|
|
5
5
|
and exclude commands from compression, without weakening safety. The loader
|
|
6
|
-
is pure stdlib (tomllib
|
|
6
|
+
is pure stdlib (tomllib, or a strict subset reader on Python 3.9/3.10), performs no file writes,
|
|
7
7
|
and gates every ``add`` entry through ``_is_safe_add`` before it reaches the
|
|
8
8
|
effective allowlist.
|
|
9
9
|
|
|
@@ -37,7 +37,9 @@ Rules:
|
|
|
37
37
|
from __future__ import annotations
|
|
38
38
|
|
|
39
39
|
import fnmatch
|
|
40
|
+
import functools
|
|
40
41
|
import os
|
|
42
|
+
import re
|
|
41
43
|
import sys
|
|
42
44
|
from dataclasses import dataclass, field
|
|
43
45
|
from pathlib import Path
|
|
@@ -48,6 +50,310 @@ try:
|
|
|
48
50
|
except ImportError:
|
|
49
51
|
tomllib = None # type: ignore[assignment]
|
|
50
52
|
|
|
53
|
+
# ---------------------------------------------------------------------------
|
|
54
|
+
# TOML subset fallback (Python 3.9 and 3.10 have no tomllib)
|
|
55
|
+
# ---------------------------------------------------------------------------
|
|
56
|
+
# The command-filters file only needs tables, bare/quoted/dotted keys, strings,
|
|
57
|
+
# booleans, integers, arrays and single-line inline tables. This reader accepts
|
|
58
|
+
# exactly that and raises on anything else (multi-line strings, arrays of
|
|
59
|
+
# tables, floats, dates, ...), so an unsupported file fails open instead of
|
|
60
|
+
# being half-read. On Python 3.11+ the stdlib parser is always used.
|
|
61
|
+
|
|
62
|
+
class _SubsetError(ValueError):
|
|
63
|
+
"""The file uses TOML syntax outside the supported subset, or is invalid."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
_MAX_DEPTH = 32 # nesting of arrays / inline tables; real filter files use 2
|
|
67
|
+
_BARE_KEY_CHARS = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-")
|
|
68
|
+
_ESCAPES = {"b": "\b", "t": "\t", "n": "\n", "f": "\f", "r": "\r", '"': '"', "\\": "\\"}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class _SubsetReader:
|
|
72
|
+
def __init__(self, text: str):
|
|
73
|
+
self.s = text
|
|
74
|
+
self.i = 0
|
|
75
|
+
# TOML forbids reopening a table that a dotted key or an inline table
|
|
76
|
+
# created, and defining the same [header] twice. Track those by identity.
|
|
77
|
+
self.inline_ids = set()
|
|
78
|
+
self.dotted_ids = set()
|
|
79
|
+
self.header_ids = set()
|
|
80
|
+
self.depth = 0
|
|
81
|
+
|
|
82
|
+
def fail(self, msg: str):
|
|
83
|
+
line = self.s.count("\n", 0, self.i) + 1
|
|
84
|
+
raise _SubsetError(f"{msg} (line {line})")
|
|
85
|
+
|
|
86
|
+
def peek(self) -> str:
|
|
87
|
+
return self.s[self.i] if self.i < len(self.s) else ""
|
|
88
|
+
|
|
89
|
+
def skip_inline_ws(self):
|
|
90
|
+
while self.peek() in (" ", "\t"):
|
|
91
|
+
self.i += 1
|
|
92
|
+
|
|
93
|
+
def newline(self) -> bool:
|
|
94
|
+
"""Consume one LF or CRLF; a lone CR is not a newline in TOML."""
|
|
95
|
+
if self.peek() == "\n":
|
|
96
|
+
self.i += 1
|
|
97
|
+
return True
|
|
98
|
+
if self.peek() == "\r" and self.s[self.i + 1:self.i + 2] == "\n":
|
|
99
|
+
self.i += 2
|
|
100
|
+
return True
|
|
101
|
+
return False
|
|
102
|
+
|
|
103
|
+
def skip_comment(self):
|
|
104
|
+
if self.peek() == "#":
|
|
105
|
+
while self.peek() not in ("", "\n") and self.s[self.i:self.i + 2] != "\r\n":
|
|
106
|
+
ch = self.peek()
|
|
107
|
+
if ord(ch) < 0x20 and ch != "\t" or ch == "\x7f":
|
|
108
|
+
self.fail("control character in comment")
|
|
109
|
+
self.i += 1
|
|
110
|
+
|
|
111
|
+
def skip_ws_and_newlines(self):
|
|
112
|
+
# Inside arrays: whitespace, newlines and comments are all insignificant.
|
|
113
|
+
while True:
|
|
114
|
+
self.skip_inline_ws()
|
|
115
|
+
if self.peek() == "#":
|
|
116
|
+
self.skip_comment()
|
|
117
|
+
elif not self.newline():
|
|
118
|
+
return
|
|
119
|
+
|
|
120
|
+
def end_of_line(self):
|
|
121
|
+
self.skip_inline_ws()
|
|
122
|
+
self.skip_comment()
|
|
123
|
+
if self.peek() != "" and not self.newline():
|
|
124
|
+
self.fail("unexpected text after value")
|
|
125
|
+
|
|
126
|
+
def key_part(self) -> str:
|
|
127
|
+
self.skip_inline_ws()
|
|
128
|
+
c = self.peek()
|
|
129
|
+
if c == '"':
|
|
130
|
+
return self.basic_string()
|
|
131
|
+
if c == "'":
|
|
132
|
+
return self.literal_string()
|
|
133
|
+
start = self.i
|
|
134
|
+
while self.peek() and self.peek() in _BARE_KEY_CHARS:
|
|
135
|
+
self.i += 1
|
|
136
|
+
if start == self.i:
|
|
137
|
+
self.fail("expected a key")
|
|
138
|
+
return self.s[start:self.i]
|
|
139
|
+
|
|
140
|
+
def dotted_key(self) -> list:
|
|
141
|
+
parts = [self.key_part()]
|
|
142
|
+
self.skip_inline_ws()
|
|
143
|
+
while self.peek() == ".":
|
|
144
|
+
self.i += 1
|
|
145
|
+
parts.append(self.key_part())
|
|
146
|
+
self.skip_inline_ws()
|
|
147
|
+
return parts
|
|
148
|
+
|
|
149
|
+
def basic_string(self) -> str:
|
|
150
|
+
if self.s.startswith('"""', self.i):
|
|
151
|
+
self.fail("multi-line strings are not supported")
|
|
152
|
+
self.i += 1
|
|
153
|
+
out = []
|
|
154
|
+
while True:
|
|
155
|
+
c = self.peek()
|
|
156
|
+
if c in ("", "\n", "\r"):
|
|
157
|
+
self.fail("unterminated string")
|
|
158
|
+
self.i += 1
|
|
159
|
+
if c == '"':
|
|
160
|
+
return "".join(out)
|
|
161
|
+
if c == "\\":
|
|
162
|
+
e = self.peek()
|
|
163
|
+
self.i += 1
|
|
164
|
+
if e in _ESCAPES:
|
|
165
|
+
out.append(_ESCAPES[e])
|
|
166
|
+
elif e in ("u", "U"):
|
|
167
|
+
n = 4 if e == "u" else 8
|
|
168
|
+
digits = self.s[self.i:self.i + n]
|
|
169
|
+
if len(digits) != n or any(d not in "0123456789abcdefABCDEF" for d in digits):
|
|
170
|
+
self.fail("invalid unicode escape")
|
|
171
|
+
code = int(digits, 16)
|
|
172
|
+
if code > 0x10FFFF or 0xD800 <= code <= 0xDFFF:
|
|
173
|
+
self.fail("invalid unicode escape")
|
|
174
|
+
out.append(chr(code))
|
|
175
|
+
self.i += n
|
|
176
|
+
else:
|
|
177
|
+
self.fail("invalid escape sequence")
|
|
178
|
+
elif ord(c) < 0x20 and c != "\t" or c == "\x7f":
|
|
179
|
+
self.fail("control character in string")
|
|
180
|
+
else:
|
|
181
|
+
out.append(c)
|
|
182
|
+
|
|
183
|
+
def literal_string(self) -> str:
|
|
184
|
+
if self.s.startswith("'''", self.i):
|
|
185
|
+
self.fail("multi-line strings are not supported")
|
|
186
|
+
end = self.i + 1
|
|
187
|
+
while end < len(self.s) and self.s[end] not in ("'", "\n", "\r"):
|
|
188
|
+
end += 1
|
|
189
|
+
if end >= len(self.s) or self.s[end] != "'":
|
|
190
|
+
self.fail("unterminated string")
|
|
191
|
+
text = self.s[self.i + 1:end]
|
|
192
|
+
if any(ord(ch) < 0x20 and ch != "\t" or ch == "\x7f" for ch in text):
|
|
193
|
+
self.fail("control character in string")
|
|
194
|
+
self.i = end + 1
|
|
195
|
+
return text
|
|
196
|
+
|
|
197
|
+
def value(self):
|
|
198
|
+
self.skip_inline_ws()
|
|
199
|
+
c = self.peek()
|
|
200
|
+
if c == '"':
|
|
201
|
+
return self.basic_string()
|
|
202
|
+
if c == "'":
|
|
203
|
+
return self.literal_string()
|
|
204
|
+
if c == "[":
|
|
205
|
+
return self.array()
|
|
206
|
+
if c == "{":
|
|
207
|
+
return self.inline_table()
|
|
208
|
+
for word, val in (("true", True), ("false", False)):
|
|
209
|
+
if self.s.startswith(word, self.i):
|
|
210
|
+
after = self.s[self.i + len(word):self.i + len(word) + 1]
|
|
211
|
+
if after == "" or after in " \t\r\n,]}#":
|
|
212
|
+
self.i += len(word)
|
|
213
|
+
return val
|
|
214
|
+
start = self.i
|
|
215
|
+
if self.peek() in ("+", "-"):
|
|
216
|
+
self.i += 1
|
|
217
|
+
digits_start = self.i
|
|
218
|
+
while self.peek().isdigit() and self.peek().isascii():
|
|
219
|
+
self.i += 1
|
|
220
|
+
text = self.s[digits_start:self.i]
|
|
221
|
+
after = self.peek()
|
|
222
|
+
if not text or (len(text) > 1 and text[0] == "0") or (after and after not in " \t\r\n,]}#"):
|
|
223
|
+
self.i = start
|
|
224
|
+
self.fail("unsupported value")
|
|
225
|
+
return int(self.s[start:self.i])
|
|
226
|
+
|
|
227
|
+
def enter(self):
|
|
228
|
+
self.depth += 1
|
|
229
|
+
if self.depth > _MAX_DEPTH:
|
|
230
|
+
self.fail("arrays and inline tables nested too deeply")
|
|
231
|
+
|
|
232
|
+
def array(self) -> list:
|
|
233
|
+
self.enter()
|
|
234
|
+
try:
|
|
235
|
+
return self._array()
|
|
236
|
+
finally:
|
|
237
|
+
self.depth -= 1
|
|
238
|
+
|
|
239
|
+
def _array(self) -> list:
|
|
240
|
+
self.i += 1
|
|
241
|
+
items = []
|
|
242
|
+
while True:
|
|
243
|
+
self.skip_ws_and_newlines()
|
|
244
|
+
if self.peek() == "]":
|
|
245
|
+
self.i += 1
|
|
246
|
+
return items
|
|
247
|
+
items.append(self.value())
|
|
248
|
+
self.skip_ws_and_newlines()
|
|
249
|
+
if self.peek() == ",":
|
|
250
|
+
self.i += 1
|
|
251
|
+
elif self.peek() != "]":
|
|
252
|
+
self.fail("expected ',' or ']' in array")
|
|
253
|
+
|
|
254
|
+
def inline_table(self) -> dict:
|
|
255
|
+
self.enter()
|
|
256
|
+
try:
|
|
257
|
+
return self._inline_table()
|
|
258
|
+
finally:
|
|
259
|
+
self.depth -= 1
|
|
260
|
+
|
|
261
|
+
def _inline_table(self) -> dict:
|
|
262
|
+
self.i += 1
|
|
263
|
+
table: dict = {}
|
|
264
|
+
self.inline_ids.add(id(table))
|
|
265
|
+
self.skip_inline_ws()
|
|
266
|
+
if self.peek() == "}":
|
|
267
|
+
self.i += 1
|
|
268
|
+
return table
|
|
269
|
+
while True:
|
|
270
|
+
keys = self.dotted_key()
|
|
271
|
+
self.skip_inline_ws()
|
|
272
|
+
if self.peek() != "=":
|
|
273
|
+
self.fail("expected '='")
|
|
274
|
+
self.i += 1
|
|
275
|
+
self.assign(table, keys, self.value(), "inline table")
|
|
276
|
+
self.skip_inline_ws()
|
|
277
|
+
c = self.peek()
|
|
278
|
+
self.i += 1
|
|
279
|
+
if c == "}":
|
|
280
|
+
return table
|
|
281
|
+
if c != ",":
|
|
282
|
+
self.fail("expected ',' or '}' in inline table")
|
|
283
|
+
self.skip_inline_ws()
|
|
284
|
+
if self.peek() == "}":
|
|
285
|
+
self.fail("trailing comma in inline table")
|
|
286
|
+
|
|
287
|
+
def assign(self, table: dict, keys: list, val, what: str):
|
|
288
|
+
for part in keys[:-1]:
|
|
289
|
+
if part in table:
|
|
290
|
+
nxt = table[part]
|
|
291
|
+
# A dotted key may extend a table made by dotted keys or created
|
|
292
|
+
# implicitly as the parent of a [header]; not one a header, an
|
|
293
|
+
# inline table or a value defined itself.
|
|
294
|
+
if (not isinstance(nxt, dict) or id(nxt) in self.inline_ids
|
|
295
|
+
or id(nxt) in self.header_ids):
|
|
296
|
+
self.fail(f"key conflicts with an existing value in {what}")
|
|
297
|
+
self.dotted_ids.add(id(nxt))
|
|
298
|
+
else:
|
|
299
|
+
nxt = table[part] = {}
|
|
300
|
+
self.dotted_ids.add(id(nxt))
|
|
301
|
+
table = nxt
|
|
302
|
+
if keys[-1] in table:
|
|
303
|
+
self.fail(f"duplicate key in {what}")
|
|
304
|
+
table[keys[-1]] = val
|
|
305
|
+
|
|
306
|
+
def parse(self) -> dict:
|
|
307
|
+
root: dict = {}
|
|
308
|
+
current = root
|
|
309
|
+
while True:
|
|
310
|
+
self.skip_inline_ws()
|
|
311
|
+
c = self.peek()
|
|
312
|
+
if c == "":
|
|
313
|
+
return root
|
|
314
|
+
if c == "#":
|
|
315
|
+
self.skip_comment()
|
|
316
|
+
if self.newline():
|
|
317
|
+
continue
|
|
318
|
+
if self.peek() == "":
|
|
319
|
+
return root
|
|
320
|
+
if self.peek() == "[":
|
|
321
|
+
if self.s.startswith("[[", self.i):
|
|
322
|
+
self.fail("arrays of tables are not supported")
|
|
323
|
+
self.i += 1
|
|
324
|
+
keys = self.dotted_key()
|
|
325
|
+
self.skip_inline_ws()
|
|
326
|
+
if self.peek() != "]":
|
|
327
|
+
self.fail("expected ']'")
|
|
328
|
+
self.i += 1
|
|
329
|
+
current = root
|
|
330
|
+
for n, part in enumerate(keys):
|
|
331
|
+
nxt = current.setdefault(part, {})
|
|
332
|
+
# A table made by dotted keys can still gain sub-tables, but
|
|
333
|
+
# the header may not name it itself; inline tables are closed.
|
|
334
|
+
if (not isinstance(nxt, dict) or id(nxt) in self.inline_ids
|
|
335
|
+
or (n == len(keys) - 1 and id(nxt) in self.dotted_ids)):
|
|
336
|
+
self.fail("table conflicts with an existing value")
|
|
337
|
+
current = nxt
|
|
338
|
+
if id(current) in self.header_ids:
|
|
339
|
+
self.fail("table defined twice")
|
|
340
|
+
self.header_ids.add(id(current))
|
|
341
|
+
self.end_of_line()
|
|
342
|
+
continue
|
|
343
|
+
keys = self.dotted_key()
|
|
344
|
+
self.skip_inline_ws()
|
|
345
|
+
if self.peek() != "=":
|
|
346
|
+
self.fail("expected '='")
|
|
347
|
+
self.i += 1
|
|
348
|
+
self.assign(current, keys, self.value(), "table")
|
|
349
|
+
self.end_of_line()
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _loads_subset(text: str) -> dict:
|
|
353
|
+
"""Parse the supported TOML subset; raise _SubsetError on anything else."""
|
|
354
|
+
return _SubsetReader(text).parse()
|
|
355
|
+
|
|
356
|
+
|
|
51
357
|
# ---------------------------------------------------------------------------
|
|
52
358
|
# Constants
|
|
53
359
|
# ---------------------------------------------------------------------------
|
|
@@ -71,6 +377,7 @@ _UNSAFE_INTERPRETERS = frozenset({
|
|
|
71
377
|
"bash", "sh", "zsh", "dash", "ksh", "fish", "csh", "tcsh",
|
|
72
378
|
"python", "python3", "python2", "ruby", "perl", "node", "deno", "bun",
|
|
73
379
|
"lua", "tcl", "awk", "sed", "eval", "exec", "source", ".",
|
|
380
|
+
"osascript", "php", "gawk", "mawk", "nawk", "rscript",
|
|
74
381
|
})
|
|
75
382
|
_UNSAFE_PREFIXES = frozenset({"sudo", "su", "doas", "pkexec", "gksudo"})
|
|
76
383
|
_UNSAFE_WRITE_SUBCMDS = frozenset({
|
|
@@ -80,6 +387,75 @@ _UNSAFE_WRITE_SUBCMDS = frozenset({
|
|
|
80
387
|
})
|
|
81
388
|
_DANGEROUS_CHARS = frozenset(";|&`$(){}><\n\r\x00")
|
|
82
389
|
|
|
390
|
+
# git subcommands that write. Superset of bash_whitelist._GIT_WRITE_SUBCMDS
|
|
391
|
+
# (a test pins the superset relation; importing it here would create a
|
|
392
|
+
# circular dependency on the hot path). Bounded, not a full git grammar:
|
|
393
|
+
# ambiguous subcommands that can write with the right flag (``branch -D``,
|
|
394
|
+
# ``config``, ``reflog delete``) are treated as writes outright.
|
|
395
|
+
_GIT_WRITE_SUBCMDS = frozenset({
|
|
396
|
+
"commit", "push", "pull", "merge", "rebase", "reset", "checkout",
|
|
397
|
+
"switch", "stash", "tag", "cherry-pick", "revert", "am", "apply",
|
|
398
|
+
"add", "rm", "mv", "restore", "bisect", "clean", "fetch", "clone",
|
|
399
|
+
"init", "remote", "submodule", "worktree",
|
|
400
|
+
"branch", "config", "gc", "prune", "reflog", "notes", "replace",
|
|
401
|
+
"filter-branch", "update-ref", "symbolic-ref", "repack", "write-tree",
|
|
402
|
+
"commit-tree", "update-index", "read-tree", "hash-object",
|
|
403
|
+
})
|
|
404
|
+
# git subcommands treated as read-only. Anything outside
|
|
405
|
+
# _GIT_WRITE_SUBCMDS | _GIT_READONLY_SUBCMDS (aliases, plumbing, new
|
|
406
|
+
# subcommands) is refused, matching the compress hook's own stance that an
|
|
407
|
+
# unknown git invocation is not provably read-only.
|
|
408
|
+
_GIT_READONLY_SUBCMDS = frozenset({
|
|
409
|
+
"status", "log", "diff", "show", "ls-files", "ls-tree", "blame",
|
|
410
|
+
"annotate", "grep", "rev-parse", "rev-list", "describe", "shortlog",
|
|
411
|
+
"show-ref", "cat-file", "count-objects", "var", "version", "whatchanged",
|
|
412
|
+
})
|
|
413
|
+
# find flags that delete, write or run another program.
|
|
414
|
+
_FIND_DESTRUCTIVE_FLAGS = frozenset({
|
|
415
|
+
"-delete", "-exec", "-execdir", "-ok", "-okdir",
|
|
416
|
+
"-fprint", "-fprint0", "-fls", "-fprintf",
|
|
417
|
+
})
|
|
418
|
+
_GLOB_CHARS = frozenset("*?[")
|
|
419
|
+
# Runner / wrapper commands: they exec another command (``timeout 5 rm -rf x``,
|
|
420
|
+
# ``nice rm x``, ``xargs rm``), so the real command is not argv[0]. Refused
|
|
421
|
+
# outright (fail closed) rather than unwrapped, since each has its own option
|
|
422
|
+
# grammar. Windows shells are interpreters too.
|
|
423
|
+
_LAUNCHERS = frozenset({
|
|
424
|
+
"timeout", "nice", "ionice", "nohup", "stdbuf", "time", "chrt", "taskset",
|
|
425
|
+
"watch", "xargs", "parallel", "command", "exec", "builtin", "setsid",
|
|
426
|
+
"unbuffer", "strace", "ltrace", "nsenter", "chroot", "flock", "busybox",
|
|
427
|
+
"script", "runuser", "systemd-run", "at", "batch", "ssh", "wsl", "cmd",
|
|
428
|
+
"powershell", "pwsh", "start", "sh.exe",
|
|
429
|
+
})
|
|
430
|
+
# Minimum set of known writers that are not in _UNSAFE_WRITE_SUBCMDS. This is
|
|
431
|
+
# a bounded denylist, not a claim that every other command is read-only.
|
|
432
|
+
_KNOWN_WRITERS = frozenset({
|
|
433
|
+
"tee", "truncate", "shred", "touch", "unlink", "install", "rsync", "patch",
|
|
434
|
+
"sponge", "scp", "rename", "del", "erase", "rd", "move", "copy", "ren",
|
|
435
|
+
})
|
|
436
|
+
_NEVER_COMPRESS_CMD0 = (
|
|
437
|
+
_UNSAFE_INTERPRETERS | _UNSAFE_PREFIXES | _UNSAFE_WRITE_SUBCMDS
|
|
438
|
+
| _LAUNCHERS | _KNOWN_WRITERS
|
|
439
|
+
)
|
|
440
|
+
# Interpreters named by version (python3.12.1, python3.13t, python3.12m,
|
|
441
|
+
# pypy3.10-v7.3) and the Windows ``py`` launcher; fullmatch on the normalized
|
|
442
|
+
# word, so python3-config, pyright, pytest and pyenv do not match.
|
|
443
|
+
_VERSIONED_INTERPRETER_RE = re.compile(
|
|
444
|
+
r"python\d+(?:\.\d+)*[a-z]*|pypy\d*(?:\.\d+)*(?:[-.][a-z0-9.]+)?|py")
|
|
445
|
+
_EXE_SUFFIXES = (".exe", ".com", ".bat", ".cmd")
|
|
446
|
+
# fnmatch candidates: bare names plus their Windows executable spellings, so
|
|
447
|
+
# ``rm.*`` / ``r*.exe`` are caught as well as ``r*``. Versioned interpreter
|
|
448
|
+
# spellings carry ABI suffixes (t, m, d) so ``python3.13?`` is caught too.
|
|
449
|
+
# Built on first use: only the add-entry gate needs it, not per-command matching.
|
|
450
|
+
@functools.lru_cache(maxsize=1)
|
|
451
|
+
def _glob_names() -> frozenset:
|
|
452
|
+
return frozenset(
|
|
453
|
+
n + ext for n in _NEVER_COMPRESS_CMD0 | {"py", "pypy", "pypy2", "pypy3"}
|
|
454
|
+
| {f"{p}{m}.{n}{abi}" for p in ("python", "pypy") for m in (2, 3)
|
|
455
|
+
for n in range(20) for abi in ("", "t", "m", "d", "td")}
|
|
456
|
+
for ext in ("",) + _EXE_SUFFIXES
|
|
457
|
+
)
|
|
458
|
+
|
|
83
459
|
_warned_paths: set = set()
|
|
84
460
|
|
|
85
461
|
|
|
@@ -110,7 +486,10 @@ class CommandFilterConfig:
|
|
|
110
486
|
|
|
111
487
|
def find_add(self, command_str: str) -> Optional[AddEntry]:
|
|
112
488
|
"""Return the first add entry whose command matches ``command_str``,
|
|
113
|
-
or None."""
|
|
489
|
+
or None. Never matches a destructive command."""
|
|
490
|
+
# No entries means no match; skip the tokenizing check on the hot path.
|
|
491
|
+
if not self.adds or is_destructive_command(command_str):
|
|
492
|
+
return None
|
|
114
493
|
for entry in self.adds:
|
|
115
494
|
if entry.command == command_str:
|
|
116
495
|
return entry
|
|
@@ -134,6 +513,11 @@ class EffectiveFilters:
|
|
|
134
513
|
return False
|
|
135
514
|
|
|
136
515
|
def find_user_add(self, command_str: str) -> Optional[AddEntry]:
|
|
516
|
+
# A glob in an add entry must never make a destructive command
|
|
517
|
+
# eligible for compression (the wrapper would run it). No entries means
|
|
518
|
+
# no match, so the tokenizing check is skipped on the hot path.
|
|
519
|
+
if not self.user_adds or is_destructive_command(command_str):
|
|
520
|
+
return None
|
|
137
521
|
for entry in self.user_adds:
|
|
138
522
|
if entry.command == command_str:
|
|
139
523
|
return entry
|
|
@@ -153,20 +537,28 @@ def _is_all_wildcard(token: str) -> bool:
|
|
|
153
537
|
return bool(token) and set(token) <= {"*"}
|
|
154
538
|
|
|
155
539
|
|
|
156
|
-
def
|
|
157
|
-
"""Return the
|
|
540
|
+
def _effective_cmd_token(tokens: List[str]) -> Optional[str]:
|
|
541
|
+
"""Return the token of the REAL command being run.
|
|
158
542
|
|
|
159
543
|
Normalizes away the path (so ``/bin/bash``, ``./python``, ``/usr/bin/sudo``
|
|
160
544
|
are recognized as ``bash``/``python``/``sudo``) and resolves a leading
|
|
161
545
|
``env`` invocation by skipping ``VAR=val`` assignments and env's own options
|
|
162
|
-
(``-i``, and the operand-taking ``-u``/``-C
|
|
163
|
-
env would exec
|
|
546
|
+
(``-i``, and the operand-taking ``-u``/``-C``/``--chdir``) to reach the
|
|
547
|
+
command env would exec, looping through nested ``env``. ``-S`` /
|
|
548
|
+
``--split-string`` and any unrecognized ``-`` option fail closed (None).
|
|
549
|
+
Returns None when no command token remains.
|
|
164
550
|
"""
|
|
165
551
|
if not tokens:
|
|
166
552
|
return None
|
|
167
553
|
i = 0
|
|
168
|
-
|
|
169
|
-
|
|
554
|
+
# ``env`` may be nested (``env env rm x``) and may carry assignments and
|
|
555
|
+
# options before the real command, so unwrap repeatedly. Any option token
|
|
556
|
+
# this parser does not model exactly -- ``--opt=val``, joined
|
|
557
|
+
# ``-uVAL``/``-CVAL``/``-SVAL``, or ``-S``/``--split-string`` whose operand
|
|
558
|
+
# is itself a command string -- fails closed by returning None rather
|
|
559
|
+
# than guessing which later token is the command.
|
|
560
|
+
while i < len(tokens) and _norm_cmd(tokens[i]) == "env":
|
|
561
|
+
i += 1
|
|
170
562
|
while i < len(tokens):
|
|
171
563
|
tok = tokens[i]
|
|
172
564
|
if "=" in tok and not tok.startswith("-"):
|
|
@@ -175,13 +567,203 @@ def _effective_cmd0(tokens: List[str]) -> Optional[str]:
|
|
|
175
567
|
if tok in ("-i", "--ignore-environment", "-", "-v", "--debug"):
|
|
176
568
|
i += 1
|
|
177
569
|
continue
|
|
178
|
-
if tok in ("-u", "--unset", "-C", "--chdir"
|
|
179
|
-
i += 2 # option consumes its operand
|
|
570
|
+
if tok in ("-u", "--unset", "-C", "--chdir"):
|
|
571
|
+
i += 2 # option consumes its operand (``--`` included: it is
|
|
572
|
+
# a legal operand, e.g. ``env -u -- rm`` unsets ``--``)
|
|
180
573
|
continue
|
|
574
|
+
if tok == "--":
|
|
575
|
+
i += 1
|
|
576
|
+
break # env end-of-options: the next token is the command
|
|
577
|
+
if tok.startswith("-"):
|
|
578
|
+
return None
|
|
181
579
|
break # first non-option, non-assignment token = the command
|
|
182
580
|
if i >= len(tokens):
|
|
183
581
|
return None
|
|
184
|
-
return
|
|
582
|
+
return tokens[i]
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _effective_cmd0(tokens: List[str]) -> Optional[str]:
|
|
586
|
+
tok = _effective_cmd_token(tokens)
|
|
587
|
+
return None if tok is None else _norm_cmd(tok)
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def _raw_cmd_word(tokens: List[str]) -> str:
|
|
591
|
+
"""Lower-cased basename of the command word, backslash paths included,
|
|
592
|
+
WITHOUT stripping an executable suffix (so ``rm.*`` stays a glob)."""
|
|
593
|
+
cmd = _effective_cmd_token(tokens)
|
|
594
|
+
return os.path.basename(cmd.replace("\\", "/")).lower() if cmd else ""
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def _norm_cmd(token: str) -> str:
|
|
598
|
+
"""Basename, lower-cased, without a Windows executable suffix, so
|
|
599
|
+
``RM``, ``/bin/rm`` and ``rm.exe`` all compare as ``rm``."""
|
|
600
|
+
name = os.path.basename(token.replace("\\", "/")).lower()
|
|
601
|
+
for ext in (".exe", ".com", ".bat", ".cmd"):
|
|
602
|
+
if name.endswith(ext):
|
|
603
|
+
return name[: -len(ext)]
|
|
604
|
+
return name
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def _git_subcommand_tokens(tokens: List[str]) -> List[str]:
|
|
608
|
+
"""Return the tokens after ``git``'s global options, starting at the
|
|
609
|
+
subcommand word (skips ``-C <dir>``, ``-c k=v``, ``--git-dir <d>``...)."""
|
|
610
|
+
idx = next((i for i, t in enumerate(tokens) if _norm_cmd(t) == "git"), None)
|
|
611
|
+
if idx is None:
|
|
612
|
+
return []
|
|
613
|
+
rest = tokens[idx + 1:]
|
|
614
|
+
j = 0
|
|
615
|
+
while j < len(rest) and rest[j].startswith("-"):
|
|
616
|
+
j += 2 if rest[j] in ("-C", "-c", "--git-dir", "--work-tree", "--namespace") else 1
|
|
617
|
+
return rest[j:]
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def _git_writes_output(sub: List[str]) -> bool:
|
|
621
|
+
"""``git diff/log/show --output[=]FILE`` writes FILE: treat it as a write."""
|
|
622
|
+
return any(t == "--output" or t.startswith("--output=") for t in sub[1:])
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _git_has_config_options(tokens: List[str]) -> bool:
|
|
626
|
+
"""True when git global options other than ``-C <dir>`` / ``--no-pager``
|
|
627
|
+
/ ``--no-optional-locks`` precede the subcommand. ``-c alias.x=!cmd``,
|
|
628
|
+
``--config-env``, ``--exec-path`` and friends can run arbitrary programs."""
|
|
629
|
+
idx = next((i for i, t in enumerate(tokens) if _norm_cmd(t) == "git"), None)
|
|
630
|
+
if idx is None:
|
|
631
|
+
return False
|
|
632
|
+
rest = tokens[idx + 1:]
|
|
633
|
+
j = 0
|
|
634
|
+
while j < len(rest) and rest[j].startswith("-"):
|
|
635
|
+
if rest[j] == "-C":
|
|
636
|
+
j += 2
|
|
637
|
+
elif rest[j] in ("--no-pager", "--no-optional-locks"):
|
|
638
|
+
j += 1
|
|
639
|
+
else:
|
|
640
|
+
return True
|
|
641
|
+
return False
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def is_destructive_command(command_str: str) -> bool:
|
|
645
|
+
"""True when ``command_str`` runs something that writes, deletes or
|
|
646
|
+
launches another program (rm, mv, sudo, an interpreter, a git write
|
|
647
|
+
subcommand, find -delete/-exec, ...).
|
|
648
|
+
|
|
649
|
+
Used at match time so a glob in a user ``add`` entry can never make such
|
|
650
|
+
a command eligible for compression, whatever the glob expands to.
|
|
651
|
+
Fails closed: an unparseable command counts as destructive, and unknown
|
|
652
|
+
git subcommands (possible aliases) count as writes.
|
|
653
|
+
|
|
654
|
+
Bounded by design: this module ships inside the Devin payload closed
|
|
655
|
+
set, so it cannot depend on the hook's read-only classifier
|
|
656
|
+
(pipeline_analyzer); the closed-set policy test forbids that import.
|
|
657
|
+
The checks are self-contained denylists, not a full shell parser;
|
|
658
|
+
commands they do not recognize stay eligible for user ``add`` entries,
|
|
659
|
+
as before.
|
|
660
|
+
"""
|
|
661
|
+
# Multi-line input hides extra commands (``mytool --flag\nrm -rf x``)
|
|
662
|
+
# and command/process substitution executes whatever it nests
|
|
663
|
+
# (``echo $(rm -rf x)``, ``cat <(rm -rf x)``): refuse on the raw string.
|
|
664
|
+
if any(c in command_str for c in ("\n", "\r")):
|
|
665
|
+
return True
|
|
666
|
+
if "$(" in command_str or "`" in command_str or "<(" in command_str:
|
|
667
|
+
return True
|
|
668
|
+
import shlex
|
|
669
|
+
try:
|
|
670
|
+
# punctuation_chars splits glued shell operators (``cat;rm -rf x``)
|
|
671
|
+
# into real separator tokens so the per-stage checks below see them.
|
|
672
|
+
tokens = list(shlex.shlex(command_str, posix=True,
|
|
673
|
+
punctuation_chars="|&;<>(){}"))
|
|
674
|
+
except ValueError:
|
|
675
|
+
return True
|
|
676
|
+
# POSIX shlex eats backslashes (``C:\\bin\\rm.exe`` -> ``C:binrm.exe``), so
|
|
677
|
+
# also judge the raw whitespace split; destructive if either view is.
|
|
678
|
+
raw = command_str.split()
|
|
679
|
+
if raw != tokens and _tokens_destructive(raw):
|
|
680
|
+
return True
|
|
681
|
+
return _tokens_destructive(tokens)
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def _segment_destructive(tokens: List[str]) -> bool:
|
|
685
|
+
# Skip leading VAR=val assignments; _effective_cmd0 then resolves env.
|
|
686
|
+
start = 0
|
|
687
|
+
while start < len(tokens) and "=" in tokens[start] and not tokens[start].startswith("-"):
|
|
688
|
+
start += 1
|
|
689
|
+
tokens = tokens[start:]
|
|
690
|
+
# A bare ``--`` ends option parsing, but inside ``env`` it is also a
|
|
691
|
+
# legal option operand (``env -u -- rm`` unsets a var named ``--`` and
|
|
692
|
+
# runs ``rm``) or env's own end-of-options marker, so only non-env
|
|
693
|
+
# segments get the blanket strip; the env unwrapper models ``--``.
|
|
694
|
+
if not tokens or _norm_cmd(tokens[0]) != "env":
|
|
695
|
+
tokens = [t for t in tokens if t != "--"]
|
|
696
|
+
if not tokens:
|
|
697
|
+
return False
|
|
698
|
+
cmd0 = _effective_cmd0(tokens)
|
|
699
|
+
if (cmd0 is None or cmd0 in _NEVER_COMPRESS_CMD0
|
|
700
|
+
or _VERSIONED_INTERPRETER_RE.fullmatch(cmd0)):
|
|
701
|
+
return True
|
|
702
|
+
if tokens and tokens[0] in _SHELL_STRUCT_TOKENS:
|
|
703
|
+
return True
|
|
704
|
+
if cmd0 == "git":
|
|
705
|
+
if _git_has_config_options(tokens):
|
|
706
|
+
return True
|
|
707
|
+
sub = _git_subcommand_tokens(tokens)
|
|
708
|
+
if not sub:
|
|
709
|
+
return True
|
|
710
|
+
name = sub[0].lower()
|
|
711
|
+
if name in _GIT_WRITE_SUBCMDS or _git_writes_output(sub):
|
|
712
|
+
return True
|
|
713
|
+
if name not in _GIT_READONLY_SUBCMDS:
|
|
714
|
+
# Unknown subcommand: could be an alias defined in repo config.
|
|
715
|
+
return True
|
|
716
|
+
if cmd0 == "find" and any(t in _FIND_DESTRUCTIVE_FLAGS for t in tokens):
|
|
717
|
+
return True
|
|
718
|
+
if cmd0 == "sed" and any(t == "-i" or t.startswith("-i")
|
|
719
|
+
or t.startswith("--in-place") for t in tokens):
|
|
720
|
+
return True
|
|
721
|
+
return False
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
_PIPELINE_SEPARATORS = frozenset({
|
|
725
|
+
"|", "||", "&", "&&", ";", ";;", ";&", ";;&", "|&", "(", ")", "{", "}",
|
|
726
|
+
})
|
|
727
|
+
_PUNCT_CHARS = frozenset("|&;<>(){}")
|
|
728
|
+
# Shell grammar keywords and groupers: a segment LED by one of these hides
|
|
729
|
+
# the real command behind it (``if true; then rm x; fi``, ``{ rm x; }``).
|
|
730
|
+
# Refused outright (fail closed on recognized grammar) rather than
|
|
731
|
+
# mini-interpreting the shell.
|
|
732
|
+
_SHELL_STRUCT_TOKENS = frozenset({
|
|
733
|
+
"if", "then", "else", "elif", "fi", "for", "while", "until", "do",
|
|
734
|
+
"done", "case", "esac", "select", "coproc", "!", "{", "}", "(", ")",
|
|
735
|
+
})
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
def _tokens_destructive(tokens: List[str]) -> bool:
|
|
739
|
+
# shlex splits runs of punctuation into single tokens (``|&``, ``;;``).
|
|
740
|
+
# Only the exact recognized separators split a stage; ANY other
|
|
741
|
+
# all-punctuation run (every redirect, fd dup, glued or invalid grammar)
|
|
742
|
+
# fails closed rather than risking an exception that hides a writer.
|
|
743
|
+
segments = [[]]
|
|
744
|
+
i = 0
|
|
745
|
+
while i < len(tokens):
|
|
746
|
+
t = tokens[i]
|
|
747
|
+
if t and all(c in _PUNCT_CHARS for c in t):
|
|
748
|
+
if t in _PIPELINE_SEPARATORS:
|
|
749
|
+
segments.append([])
|
|
750
|
+
i += 1
|
|
751
|
+
continue
|
|
752
|
+
# Unrecognized punctuation run (incl. all redirects): fail closed.
|
|
753
|
+
return True
|
|
754
|
+
segments[-1].append(t)
|
|
755
|
+
i += 1
|
|
756
|
+
# Check every pipeline stage, not just argv[0]: ``ls | tee out`` writes
|
|
757
|
+
# through the second stage.
|
|
758
|
+
return any(_segment_destructive(seg) for seg in segments if seg)
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _glob_can_match_unsafe(token: str, names) -> bool:
|
|
762
|
+
"""True when ``token`` contains a glob and fnmatch could expand it to one
|
|
763
|
+
of ``names`` (e.g. ``r*``, ``?m``, ``[r]m`` all match ``rm``)."""
|
|
764
|
+
if not any(ch in _GLOB_CHARS for ch in token):
|
|
765
|
+
return False
|
|
766
|
+
return any(fnmatch.fnmatchcase(name, token) for name in names)
|
|
185
767
|
|
|
186
768
|
|
|
187
769
|
def _is_safe_add(command: str, handler: str) -> bool:
|
|
@@ -221,12 +803,35 @@ def _is_safe_add(command: str, handler: str) -> bool:
|
|
|
221
803
|
return False
|
|
222
804
|
if _is_all_wildcard(cmd0):
|
|
223
805
|
return False
|
|
224
|
-
|
|
806
|
+
cmd0 = cmd0.lower()
|
|
807
|
+
# _raw_cmd_word already lower-cases and takes the basename of any
|
|
808
|
+
# backslash path, so one glob check against the dangerous names suffices.
|
|
809
|
+
raw0 = _raw_cmd_word(tokens)
|
|
810
|
+
if raw0 and _glob_can_match_unsafe(raw0, _glob_names()):
|
|
811
|
+
return False
|
|
812
|
+
if cmd0 in _SHELL_STRUCT_TOKENS or _glob_can_match_unsafe(cmd0, _SHELL_STRUCT_TOKENS):
|
|
813
|
+
return False
|
|
814
|
+
if raw0 and _glob_can_match_unsafe(raw0, _SHELL_STRUCT_TOKENS):
|
|
815
|
+
return False
|
|
816
|
+
if cmd0 in _UNSAFE_INTERPRETERS or _VERSIONED_INTERPRETER_RE.fullmatch(cmd0):
|
|
225
817
|
return False
|
|
226
818
|
if cmd0 in _UNSAFE_PREFIXES:
|
|
227
819
|
return False
|
|
228
820
|
if cmd0 in _UNSAFE_WRITE_SUBCMDS:
|
|
229
821
|
return False
|
|
822
|
+
# Globs: the command string is later matched with fnmatch, so ``r*`` also
|
|
823
|
+
# matches ``rm -rf target``. Reject a glob command word that could match
|
|
824
|
+
# any destructive / interpreter / privilege command name.
|
|
825
|
+
if cmd0 in _NEVER_COMPRESS_CMD0 or _glob_can_match_unsafe(cmd0, _glob_names()):
|
|
826
|
+
return False
|
|
827
|
+
# ``git <glob>``: the subcommand word must not be able to match a write.
|
|
828
|
+
if cmd0 == "git":
|
|
829
|
+
if _git_has_config_options(tokens):
|
|
830
|
+
return False
|
|
831
|
+
sub = _git_subcommand_tokens(tokens)
|
|
832
|
+
if sub and (sub[0].lower() in _GIT_WRITE_SUBCMDS or _git_writes_output(sub)
|
|
833
|
+
or _glob_can_match_unsafe(sub[0].lower(), _GIT_WRITE_SUBCMDS)):
|
|
834
|
+
return False
|
|
230
835
|
return True
|
|
231
836
|
|
|
232
837
|
|
|
@@ -278,14 +883,19 @@ def load_filters() -> CommandFilterConfig:
|
|
|
278
883
|
path = _filters_path()
|
|
279
884
|
if path is None or not path.exists():
|
|
280
885
|
return CommandFilterConfig()
|
|
281
|
-
if tomllib is None:
|
|
282
|
-
_warn_once(path, "tomllib not available; ignoring")
|
|
283
|
-
return CommandFilterConfig()
|
|
284
886
|
try:
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
887
|
+
if tomllib is not None:
|
|
888
|
+
with open(path, "rb") as handle:
|
|
889
|
+
data = tomllib.load(handle)
|
|
890
|
+
else:
|
|
891
|
+
# Python 3.9/3.10: no stdlib TOML. Read the supported subset, and
|
|
892
|
+
# fail open on anything outside it.
|
|
893
|
+
with open(path, "rb") as handle:
|
|
894
|
+
data = _loads_subset(handle.read().decode("utf-8"))
|
|
895
|
+
except (OSError, UnicodeDecodeError, ValueError, RecursionError) as exc:
|
|
896
|
+
# tomllib.TOMLDecodeError and _SubsetError are both ValueError; a deeply
|
|
897
|
+
# nested file can also exhaust the stdlib parser's recursion.
|
|
898
|
+
_warn_once(path, f"malformed or unsupported TOML ({exc}); ignoring")
|
|
289
899
|
return CommandFilterConfig()
|
|
290
900
|
return _parse_filters(data, path)
|
|
291
901
|
|
|
@@ -380,6 +990,7 @@ __all__ = [
|
|
|
380
990
|
"EffectiveFilters",
|
|
381
991
|
"VALID_HANDLERS",
|
|
382
992
|
"get_effective_filters",
|
|
993
|
+
"is_destructive_command",
|
|
383
994
|
"load_filters",
|
|
384
995
|
"merge_filters",
|
|
385
996
|
"reset_cache",
|