@alexgreensh/token-optimizer 5.13.67 → 5.13.68

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.
Files changed (31) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/package.json +1 -1
  4. package/skills/token-optimizer/scripts/_measure/_vendor/README.md +8 -2
  5. package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +46 -6
  6. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +34 -3
  7. package/skills/token-optimizer/scripts/_measure/audit.py +5 -21
  8. package/skills/token-optimizer/scripts/_measure/daemon.py +21 -51
  9. package/skills/token-optimizer/scripts/_measure/lifecycle.py +82 -521
  10. package/skills/token-optimizer/scripts/{_measure/_vendor/tomli/_parser.py → _tomli.py} +156 -10
  11. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  12. package/skills/token-optimizer/scripts/cloud_kit.py +21 -21
  13. package/skills/token-optimizer/scripts/codex_doctor.py +33 -7
  14. package/skills/token-optimizer/scripts/codex_hook_provenance.py +268 -0
  15. package/skills/token-optimizer/scripts/codex_install.py +33 -69
  16. package/skills/token-optimizer/scripts/command_filters.py +39 -309
  17. package/skills/token-optimizer/scripts/copilot_install.py +5 -0
  18. package/skills/token-optimizer/scripts/cursor_install.py +5 -0
  19. package/skills/token-optimizer/scripts/devin_install.py +6 -12
  20. package/skills/token-optimizer/scripts/devin_source.py +5 -4
  21. package/skills/token-optimizer/scripts/devin_verify.py +16 -0
  22. package/skills/token-optimizer/scripts/grok_install.py +5 -0
  23. package/skills/token-optimizer/scripts/heal_report.py +92 -0
  24. package/skills/token-optimizer/scripts/hook_heal.py +138 -0
  25. package/skills/token-optimizer/scripts/hook_provenance.py +878 -0
  26. package/skills/token-optimizer/scripts/owned_hooks.py +420 -0
  27. package/skills/token-optimizer/scripts/shipped_codex_hook_templates.json +5815 -0
  28. package/skills/token-optimizer/scripts/shipped_hook_templates.py +252 -0
  29. package/skills/token-optimizer/scripts/shipped_starter_hooks.py +55 -0
  30. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_re.py +0 -112
  31. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_types.py +0 -10
@@ -18,6 +18,8 @@ from typing import Any
18
18
  import codex_compact_prompt
19
19
  import codex_io
20
20
  import codex_statusline
21
+ import codex_hook_provenance
22
+ import hook_provenance
21
23
  from runtime_env import codex_home
22
24
 
23
25
  TOKEN_OPTIMIZER_MARKER = "token-optimizer/scripts"
@@ -96,7 +98,6 @@ def _short_path(path: str) -> str | None:
96
98
  return None
97
99
  try:
98
100
  import ctypes
99
-
100
101
  buf = ctypes.create_unicode_buffer(32768)
101
102
  n = ctypes.windll.kernel32.GetShortPathNameW(path, buf, len(buf))
102
103
  if 0 < n < len(buf) and os.path.exists(buf.value):
@@ -636,64 +637,19 @@ def _load_hooks(path: Path) -> dict[str, Any]:
636
637
  return data
637
638
 
638
639
 
639
- # Anchors for the generated Windows versioned-install command signature.
640
- # _hook_command has emitted exactly two such shapes: the current one, which
641
- # invokes the consolidated runner through the FOR variable
642
- # ("{base}\%R\hooks\run.py"), and the pre-5.13.12 broken one, which invoked it
643
- # through the delayed-expansion var ("!TOKEN_OPTIMIZER_RUNTIME_ROOT!\hooks\
644
- # run.py"). Both always carry the quoted set-assignment AND a hooks\run.py
645
- # runner invocation rooted under a token-optimizer directory (or through one
646
- # of OUR OWN variables, which a foreign command cannot use). Matching on the
647
- # assignment alone silently deletes a user's own hook that merely references
648
- # our env var, so all anchors must hold TOGETHER. (The patterns run on the
649
- # JSON-serialized group, where a literal " arrives as \" and \ as \\, hence
650
- # the escaped-quote and separator-class spellings.)
651
- _WIN_ROOT_SET_RE = re.compile(r'set \\"TOKEN_OPTIMIZER_RUNTIME_ROOT=')
652
- _WIN_RUNNER_RE = re.compile(r'hooks[/\\]+run\.py')
653
- _WIN_TO_DIR_RE = re.compile(r'token-optimizer[/\\]')
654
- _WIN_RUNNER_VIA_VAR_RE = re.compile(
655
- r'(?:!TOKEN_OPTIMIZER_RUNTIME_ROOT!|%R)[/\\]+hooks[/\\]+run\.py'
656
- )
640
+ def _codex_proof(path=None):
641
+ """Exact-bytes ownership for this hooks.json (codex_hook_provenance)."""
642
+ return codex_hook_provenance.for_codex(
643
+ path, _repo_root(), codex_hook_provenance.current_contexts(_managed_hooks),
644
+ codex_home() / "token-optimizer")
657
645
 
658
646
 
659
- # The consolidated runners (hooks/<event>_runner.py) carry no
660
- # "token-optimizer/scripts" text on POSIX marketplace installs, so without this
661
- # signature a reinstall appended a second copy of each runner hook and uninstall
662
- # left them all behind. Ours = a runner name AND our hooks/run.py (or
663
- # python-launcher.sh) AND a path under a token-optimizer folder, together.
664
- _RUNNER_SCRIPT_RE = re.compile(
665
- r'hooks[/\\]+(?:sessionstart|userpromptsubmit|posttooluse|stop)_runner\.py'
666
- )
667
- _RUNNER_ENTRY_RE = re.compile(r'hooks[/\\]+(?:run\.py|python-launcher\.sh)|\$\{R\}hooks/')
668
-
669
-
670
- def _is_token_optimizer_group(group: Any) -> bool:
671
- # The path marker misses generated Windows commands: on versioned
672
- # marketplace installs the baked paths use backslashes
673
- # (...\token-optimizer\X.Y.Z\hooks\run.py) and consolidated-runner args
674
- # like hooks/stop_runner.py, so "token-optimizer/scripts" never appears
675
- # in them. Those commands are instead identified by their full generated
676
- # signature, so a foreign hook that merely contains
677
- # set "TOKEN_OPTIMIZER_RUNTIME_ROOT= (or %TOKEN_OPTIMIZER_RUNTIME_ROOT%,
678
- # or a POSIX-style VAR=x prefix) is never swept up by reinstall/uninstall.
679
- serialized = json.dumps(group, sort_keys=True)
680
- if TOKEN_OPTIMIZER_MARKER in serialized:
681
- return True
682
- if (
683
- _RUNNER_SCRIPT_RE.search(serialized)
684
- and _RUNNER_ENTRY_RE.search(serialized)
685
- and _WIN_TO_DIR_RE.search(serialized)
686
- ):
687
- return True
688
- if not _WIN_ROOT_SET_RE.search(serialized):
689
- return False
690
- return (
691
- _WIN_RUNNER_VIA_VAR_RE.search(serialized) is not None
692
- or (
693
- _WIN_RUNNER_RE.search(serialized) is not None
694
- and _WIN_TO_DIR_RE.search(serialized) is not None
695
- )
696
- )
647
+ def _is_token_optimizer_group(event: str, group: Any, proof=None) -> bool:
648
+ # Ours only when every command in the group is proven by exact bytes: in
649
+ # the ledger beside hooks.json, or generated by a shipped codex_install for
650
+ # this install. Text markers decided this before and deleted foreign hooks
651
+ # that merely mentioned our names.
652
+ return (proof or _codex_proof()).group_is_ours(event, group)
697
653
 
698
654
 
699
655
  # Matches the --baked-root token of a generated launcher-file command, as
@@ -749,7 +705,9 @@ def _merge_hooks(
749
705
  enable_hot_path_hooks: bool = False,
750
706
  enable_prompt_hooks: bool = False,
751
707
  enable_subagent_hooks: bool = False,
708
+ proof=None,
752
709
  ) -> dict[str, Any]:
710
+ proof = proof or _codex_proof()
753
711
  result = json.loads(json.dumps(existing))
754
712
  hooks = result.setdefault("hooks", {})
755
713
  managed = _managed_hooks(
@@ -764,7 +722,7 @@ def _merge_hooks(
764
722
  groups = []
765
723
  for fresh_group in managed.get(event, []):
766
724
  for old_group in groups:
767
- if not _is_token_optimizer_group(old_group):
725
+ if not proof.group_is_ours(event, old_group):
768
726
  continue
769
727
  old_handlers = old_group.get('hooks', [])
770
728
  fresh_handlers = fresh_group.get('hooks', [])
@@ -772,20 +730,21 @@ def _merge_hooks(
772
730
  old_handler, fresh_handler = old_handlers[0], fresh_handlers[0]
773
731
  if _launcher_signature(old_handler.get('command', '')) == _launcher_signature(fresh_handler.get('command', '')):
774
732
  fresh_handler['command'] = old_handler['command']
775
- hooks[event] = [group for group in groups if not _is_token_optimizer_group(group)]
733
+ hooks[event] = [g for g in (proof.strip(event, g) for g in groups) if g is not None]
776
734
  hooks[event].extend(managed.get(event, []))
777
735
  if not hooks[event]:
778
736
  hooks.pop(event, None)
779
737
  return result
780
738
 
781
739
 
782
- def _remove_hooks(existing: dict[str, Any]) -> dict[str, Any]:
740
+ def _remove_hooks(existing: dict[str, Any], proof=None) -> dict[str, Any]:
741
+ proof = proof or _codex_proof()
783
742
  result = json.loads(json.dumps(existing))
784
743
  hooks = result.setdefault("hooks", {})
785
744
  for event, groups in list(hooks.items()):
786
745
  if not isinstance(groups, list):
787
746
  continue
788
- kept = [group for group in groups if not _is_token_optimizer_group(group)]
747
+ kept = [g for g in (proof.strip(event, g) for g in groups) if g is not None]
789
748
  if kept:
790
749
  hooks[event] = kept
791
750
  else:
@@ -860,9 +819,9 @@ def install(
860
819
  force_status_line: bool = False,
861
820
  ) -> tuple[Path, str, dict[str, Any]]:
862
821
  path = _global_hooks_path(ensure_dir=not dry_run) if is_global else _hooks_path(project)
863
- existing = _load_hooks(path)
822
+ existing, proof = _load_hooks(path), _codex_proof(path)
864
823
  updated = _merge_hooks(
865
- existing,
824
+ existing, proof=proof,
866
825
  enable_bash_compression=enable_bash_compression,
867
826
  enable_hot_path_hooks=enable_hot_path_hooks,
868
827
  enable_prompt_hooks=enable_prompt_hooks,
@@ -896,7 +855,7 @@ def install(
896
855
  details["compact_prompt"] = codex_compact_prompt.install(force=force_compact_prompt)
897
856
  if enable_status_line:
898
857
  details["status_line"] = codex_statusline.install(force=force_status_line)
899
- codex_io.atomic_write_json(path, updated)
858
+ hook_provenance.write_codex_hooks(path, updated, proof, codex_io.atomic_write_json)
900
859
  return path, "installed", details
901
860
 
902
861
 
@@ -1046,13 +1005,13 @@ def heal_quoted_launcher_commands(paths=None) -> int:
1046
1005
  try:
1047
1006
  if not path.is_file():
1048
1007
  continue
1049
- data = _load_hooks(path)
1008
+ data, proof, rewritten = _load_hooks(path), _codex_proof(path), []
1050
1009
  changed = 0
1051
- for groups in data.get("hooks", {}).values():
1010
+ for event, groups in data.get("hooks", {}).items():
1052
1011
  if not isinstance(groups, list):
1053
1012
  continue
1054
1013
  for group in groups:
1055
- if not _is_token_optimizer_group(group):
1014
+ if not proof.group_is_ours(event, group):
1056
1015
  continue
1057
1016
  for handler in group.get("hooks", []):
1058
1017
  command = handler.get("command") if isinstance(handler, dict) else None
@@ -1062,13 +1021,18 @@ def heal_quoted_launcher_commands(paths=None) -> int:
1062
1021
  if (neutral is not None and neutral != command
1063
1022
  and launcher_ready(command)):
1064
1023
  handler["command"] = neutral
1024
+ rewritten.append(codex_hook_provenance.entry_context(event, group, handler))
1065
1025
  changed += 1
1066
1026
  elif (command.startswith('"') and _LAUNCHER_MARKER in command):
1067
1027
  handler["command"] = f"{_WIN_UNQUOTED_PREFIX} {command}"
1028
+ rewritten.append(codex_hook_provenance.entry_context(event, group, handler))
1068
1029
  changed += 1
1069
1030
  if changed:
1070
- codex_io.atomic_write_json(path, data)
1031
+ hook_provenance.write_codex_hooks(path, data, proof, codex_io.atomic_write_json,
1032
+ rewritten, "codex_heal")
1071
1033
  fixed += changed
1034
+ else:
1035
+ proof.record_present(data) # seed: survives a later interpreter upgrade
1072
1036
  except Exception:
1073
1037
  continue
1074
1038
  return fixed
@@ -1077,7 +1041,7 @@ def heal_quoted_launcher_commands(paths=None) -> int:
1077
1041
  def uninstall(project: Path, *, is_global: bool = False, dry_run: bool = False) -> tuple[Path, str, dict[str, Any]]:
1078
1042
  path = _global_hooks_path() if is_global else _hooks_path(project)
1079
1043
  existing = _load_hooks(path)
1080
- updated = _remove_hooks(existing)
1044
+ updated = _remove_hooks(existing, _codex_proof(path))
1081
1045
  details: dict[str, Any] = {"hook_events": sorted(updated.get("hooks", {}).keys())}
1082
1046
  # Reverse the config.toml writes the installer made: the compact-prompt
1083
1047
  # managed block + prompt file and the [tui]
@@ -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, or a strict subset reader on Python 3.9/3.10), performs no file writes,
6
+ is pure stdlib (tomllib, or the vendored _tomli parser 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
 
@@ -39,6 +39,7 @@ from __future__ import annotations
39
39
  import fnmatch
40
40
  import functools
41
41
  import os
42
+ import stat
42
43
  import re
43
44
  import sys
44
45
  from dataclasses import dataclass, field
@@ -51,307 +52,26 @@ except ImportError:
51
52
  tomllib = None # type: ignore[assignment]
52
53
 
53
54
  # ---------------------------------------------------------------------------
54
- # TOML subset fallback (Python 3.9 and 3.10 have no tomllib)
55
+ # TOML parser fallback (Python 3.9 and 3.10 have no tomllib)
55
56
  # ---------------------------------------------------------------------------
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
57
+ # The vendored flat Tomli parser ships as the _tomli payload module so the
58
+ # Devin closed set can serve it without importing _measure. It is imported
59
+ # lazily on first use so hooks that never read a filters file pay nothing.
102
60
 
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()
61
+ _MISSING = object()
62
+ _tomli_module = _MISSING
350
63
 
351
64
 
352
- def _loads_subset(text: str) -> dict:
353
- """Parse the supported TOML subset; raise _SubsetError on anything else."""
354
- return _SubsetReader(text).parse()
65
+ def _load_tomli_fallback():
66
+ """Return the vendored Tomli module, importing it once. None if absent."""
67
+ global _tomli_module
68
+ if _tomli_module is _MISSING:
69
+ try:
70
+ import _tomli as module
71
+ except ImportError:
72
+ module = None
73
+ _tomli_module = module
74
+ return _tomli_module
355
75
 
356
76
 
357
77
  # ---------------------------------------------------------------------------
@@ -884,18 +604,28 @@ def load_filters() -> CommandFilterConfig:
884
604
  if path is None or not path.exists():
885
605
  return CommandFilterConfig()
886
606
  try:
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"))
607
+ parser = tomllib if tomllib is not None else _load_tomli_fallback()
608
+ if parser is None:
609
+ _warn_once(path, "no TOML parser available; ignoring")
610
+ return CommandFilterConfig()
611
+ # Open without blocking and require a regular file, so a FIFO or
612
+ # device at the filters path can never hang the hook.
613
+ fd = os.open(str(path), os.O_RDONLY | getattr(os, "O_NONBLOCK", 0))
614
+ try:
615
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
616
+ os.close(fd)
617
+ _warn_once(path, "not a regular file; ignoring")
618
+ return CommandFilterConfig()
619
+ handle = os.fdopen(fd, "rb")
620
+ except BaseException:
621
+ os.close(fd)
622
+ raise
623
+ with handle:
624
+ data = parser.load(handle)
895
625
  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")
626
+ # tomllib.TOMLDecodeError and tomli.TOMLDecodeError are both ValueError;
627
+ # a deeply nested file can also exhaust the parser's recursion.
628
+ _warn_once(path, f"malformed TOML ({exc}); ignoring")
899
629
  return CommandFilterConfig()
900
630
  return _parse_filters(data, path)
901
631
 
@@ -50,6 +50,11 @@ _PAYLOAD_MODULES = (
50
50
  "bash_compress.py",
51
51
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
52
52
  "bash_whitelist.py",
53
+ # command_filters + _tomli: user [filters.*] TOML config consulted by
54
+ # bash_compress/bash_whitelist; _tomli is the 3.9/3.10 parser it
55
+ # lazy-imports when tomllib is absent.
56
+ "command_filters.py",
57
+ "_tomli.py",
53
58
  "hook_io.py",
54
59
  "plugin_env.py",
55
60
  "runtime_env.py",
@@ -51,6 +51,11 @@ _PAYLOAD_MODULES = (
51
51
  "bash_compress.py",
52
52
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
53
53
  "bash_whitelist.py",
54
+ # command_filters + _tomli: user [filters.*] TOML config consulted by
55
+ # bash_compress/bash_whitelist; _tomli is the 3.9/3.10 parser it
56
+ # lazy-imports when tomllib is absent.
57
+ "command_filters.py",
58
+ "_tomli.py",
54
59
  "hook_io.py",
55
60
  "plugin_env.py",
56
61
  "runtime_env.py",
@@ -23,7 +23,7 @@ if str(SCRIPTS) not in sys.path:
23
23
  sys.path.insert(0, str(SCRIPTS))
24
24
 
25
25
  import devin_state as state
26
- from devin_verify import PAYLOAD
26
+ from devin_verify import PAYLOAD, payload_key_shapes
27
27
  from py_trust import py_path_is_trusted
28
28
  import devin_hooks as hooks
29
29
  SKILL_NAME = 'token-optimizer-output'
@@ -132,16 +132,12 @@ def _ownership(*, allow_missing=False) -> dict | None:
132
132
  raise OSError('invalid ownership record; run uninstall --purge (which also removes stored captures) to discard adapter state')
133
133
  if not isinstance(record, dict) or record.get('owner') != MARKER or not isinstance(record.get('files'), dict):
134
134
  raise OSError('invalid ownership record; run uninstall --purge (which also removes stored captures) to discard adapter state')
135
- expected = {str(state.data_dir() / 'plugin' / name) for name in PAYLOAD} | {str(skill_dir() / 'SKILL.md')}
136
- # Earlier releases shipped fewer payload files: 5.13.43 had no hook module,
137
- # and releases before it also lacked the two plugin-env modules.
138
- previous = expected - {str(state.data_dir() / 'plugin' / 'devin_hooks.py')}
139
- legacy = previous - {str(state.data_dir() / 'plugin' / name) for name in ('plugin_env.py', 'refetch_fingerprint.py')}
135
+ _, shapes = payload_key_shapes(state.data_dir() / 'plugin', PAYLOAD, skill_dir() / 'SKILL.md')
140
136
  try:
141
137
  record_keys = _resolved_keys(record['files'])
142
138
  except (OSError, ValueError, TypeError, RuntimeError):
143
139
  raise OSError('recorded paths cannot be resolved; run uninstall --purge (which also removes stored captures) to discard adapter state')
144
- if record_keys not in (sorted(expected), sorted(previous), sorted(legacy)):
140
+ if record_keys not in shapes:
145
141
  # A recorded path routed through a symlink resolves elsewhere; name the
146
142
  # real cause before falling through to the version/spelling advice.
147
143
  for name in record['files']:
@@ -533,16 +529,14 @@ def _recover_pending() -> None:
533
529
  value=json.loads(_private_bytes(pending))
534
530
  except (ValueError,RecursionError):
535
531
  value=None
536
- expected={str(state.data_dir()/'plugin'/name) for name in PAYLOAD}|{str(skill_dir()/'SKILL.md')}
537
- previous=expected - {str(state.data_dir()/'plugin'/'devin_hooks.py')}
538
- legacy=previous - {str(state.data_dir()/'plugin'/name) for name in ('plugin_env.py','refetch_fingerprint.py')}
532
+ expected,shapes=payload_key_shapes(state.data_dir()/'plugin',PAYLOAD,skill_dir()/'SKILL.md')
539
533
  files=value.get('files') if isinstance(value,dict) else None
540
534
  try:
541
535
  keys=_resolved_keys(files) if isinstance(files,dict) else None
542
536
  except (OSError,ValueError,TypeError,RuntimeError):
543
537
  keys=None
544
538
  if (not isinstance(value,dict) or value.get('owner')!=MARKER
545
- or keys not in (sorted(expected),sorted(previous),sorted(legacy))):
539
+ or keys not in shapes):
546
540
  raise OSError('invalid pending install record: ' + str(pending) + '; preserved; run uninstall --purge (which also removes stored captures) to discard adapter state')
547
541
  # Reconcile published new bytes first: stale pending must not undo a completed update.
548
542
  if manifest_path().exists():
@@ -563,7 +557,7 @@ def _recover_pending() -> None:
563
557
  raise OSError('pending version/content ambiguous: ' + str(pending) + '; preserved; run uninstall --purge (which also removes stored captures) to discard adapter state, or follow the documented manual repair')
564
558
  old=value.get('previous')
565
559
  if old is not None:
566
- if not isinstance(old,dict) or _resolved_keys(old) not in (sorted(expected),sorted(legacy)):raise OSError('invalid refresh recovery record')
560
+ if not isinstance(old,dict) or _resolved_keys(old) not in shapes:raise OSError('invalid refresh recovery record')
567
561
  if any(not isinstance(content,str) for content in old.values()) or not isinstance(value.get('previous_manifest'),str):
568
562
  raise OSError('invalid refresh recovery encoding')
569
563
  previous={name:base64.b64decode(content,validate=True) for name,content in old.items()}