@alexgreensh/token-optimizer 5.13.67 → 5.13.69

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 (75) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/package.json +1 -1
  5. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  6. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  7. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  8. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  9. package/skills/token-coach/SKILL.md +21 -23
  10. package/skills/token-dashboard/SKILL.md +5 -4
  11. package/skills/token-optimizer/SKILL.md +1 -1
  12. package/skills/token-optimizer/assets/dashboard.html +101 -50
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  15. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  16. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  17. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  18. package/skills/token-optimizer/scripts/_measure/_vendor/README.md +8 -2
  19. package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +46 -6
  20. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +34 -3
  21. package/skills/token-optimizer/scripts/_measure/audit.py +5 -21
  22. package/skills/token-optimizer/scripts/_measure/cli.py +86 -0
  23. package/skills/token-optimizer/scripts/_measure/daemon.py +34 -76
  24. package/skills/token-optimizer/scripts/_measure/dashboard.py +63 -37
  25. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  26. package/skills/token-optimizer/scripts/_measure/lifecycle.py +88 -528
  27. package/skills/token-optimizer/scripts/_measure/savings.py +20 -70
  28. package/skills/token-optimizer/scripts/_measure/sessions.py +58 -20
  29. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  30. package/skills/token-optimizer/scripts/{_measure/_vendor/tomli/_parser.py → _tomli.py} +156 -10
  31. package/skills/token-optimizer/scripts/antigravity_install.py +7 -0
  32. package/skills/token-optimizer/scripts/bash_compress.py +8 -40
  33. package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -0
  34. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  35. package/skills/token-optimizer/scripts/cloud_kit.py +22 -22
  36. package/skills/token-optimizer/scripts/codex_doctor.py +34 -8
  37. package/skills/token-optimizer/scripts/codex_hook_provenance.py +268 -0
  38. package/skills/token-optimizer/scripts/codex_install.py +33 -69
  39. package/skills/token-optimizer/scripts/command_filters.py +39 -309
  40. package/skills/token-optimizer/scripts/copilot_install.py +9 -0
  41. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  42. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  43. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  44. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  45. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  46. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  47. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  48. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  49. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  50. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  51. package/skills/token-optimizer/scripts/cursor_install.py +111 -19
  52. package/skills/token-optimizer/scripts/cursor_quality.py +505 -0
  53. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  54. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  55. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  56. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  57. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  58. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  59. package/skills/token-optimizer/scripts/devin_install.py +6 -12
  60. package/skills/token-optimizer/scripts/devin_source.py +17 -6
  61. package/skills/token-optimizer/scripts/devin_verify.py +17 -0
  62. package/skills/token-optimizer/scripts/grok_install.py +9 -0
  63. package/skills/token-optimizer/scripts/heal_report.py +92 -0
  64. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  65. package/skills/token-optimizer/scripts/hermes_install.py +4 -1
  66. package/skills/token-optimizer/scripts/hook_heal.py +138 -0
  67. package/skills/token-optimizer/scripts/hook_provenance.py +878 -0
  68. package/skills/token-optimizer/scripts/measure.py +2 -2
  69. package/skills/token-optimizer/scripts/owned_hooks.py +420 -0
  70. package/skills/token-optimizer/scripts/shipped_codex_hook_templates.json +5815 -0
  71. package/skills/token-optimizer/scripts/shipped_hook_templates.py +252 -0
  72. package/skills/token-optimizer/scripts/shipped_starter_hooks.py +55 -0
  73. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
  74. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_re.py +0 -112
  75. 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
 
@@ -48,8 +48,14 @@ _PAYLOAD_MODULES = (
48
48
  "copilot_vscode.py",
49
49
  "bash_hook.py",
50
50
  "bash_compress.py",
51
+ "bash_search_results.py",
51
52
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
52
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",
53
59
  "hook_io.py",
54
60
  "plugin_env.py",
55
61
  "runtime_env.py",
@@ -70,6 +76,9 @@ _PAYLOAD_MODULES = (
70
76
  # credential_patterns: bash_compress's credential-preservation patterns and
71
77
  # copilot_session's topic redaction (both fall back to less without it).
72
78
  "credential_patterns.py",
79
+ # credential_patterns imports this at module import time (URL family split
80
+ # under the 1,000-line ratchet); missing = import failure in the payload.
81
+ "credential_url_patterns.py",
73
82
  )
74
83
 
75
84
 
@@ -18,6 +18,8 @@ from datetime import datetime, timezone
18
18
  from pathlib import Path
19
19
  from typing import Dict, List, Optional, Tuple
20
20
 
21
+ from credential_url_patterns import URL_CREDENTIAL_PATTERNS
22
+
21
23
  # (label, compiled_regex) pairs. Label is used in redaction placeholders.
22
24
  CREDENTIAL_PATTERNS: List[Tuple[str, "re.Pattern[str]"]] = [
23
25
  ("AWS access key", re.compile(r"AKIA[0-9A-Z]{16}")),
@@ -81,25 +83,7 @@ CREDENTIAL_PATTERNS: List[Tuple[str, "re.Pattern[str]"]] = [
81
83
  # of the text so a truncated body is never left behind.
82
84
  ("PEM private key", re.compile(
83
85
  r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|\Z)")),
84
- ("Database URI", re.compile(r"(?:postgres|postgresql|mysql|mongodb|mongodb\+srv|redis)://[^:\s/]+:[^@\s]+@", re.I)),
85
- ("HTTP basic auth URL", re.compile(r"https?://[^:\s/@]+:[^@\s]+@", re.I)),
86
- # Credentials passed as URL query/matrix parameters OR OAuth-implicit-flow
87
- # fragment params (e.g. ?token=..., ?api_key=..., ;password=..., #access_token=...).
88
- # The named `keep` group captures the "?name="/"#name=" prefix so redaction
89
- # preserves the parameter name and blanks only the value (see redact_credentials).
90
- # The value class stops at the next delimiter (& # ; whitespace quote < >) but
91
- # otherwise matches EVERYTHING — including brackets — so a secret that itself
92
- # contains a `[` (common in passwords) is redacted whole, not leaked past the
93
- # bracket. To still avoid re-wrapping an already-inserted "[CREDENTIAL REDACTED:
94
- # ...]" placeholder (when the value is itself another credential shape an earlier
95
- # pattern redacted, e.g. ?token=<Bearer ...>), a negative lookahead skips a value
96
- # that begins with the placeholder rather than excluding brackets from real values.
97
- ("URL auth param", re.compile(
98
- r"(?P<keep>[?&#;](?:authorization|access[_-]?token|refresh[_-]?token|client[_-]?secret"
99
- r"|session[_-]?token|id[_-]?token|api[_-]?key|sessionid|session|password|passwd|signature"
100
- r"|secret|bearer|token|auth|sig|pwd|key|jwt)=)(?!\[CREDENTIAL REDACTED:)[^&#;\s\"'<>]+",
101
- re.I,
102
- )),
86
+ *URL_CREDENTIAL_PATTERNS,
103
87
  # M-12: mysql -p<password> (inline password after -p with no space).
104
88
  # The -p flag is special: the password immediately follows with no = or space.
105
89
  # N-3: re.I so "MySQL -pSECRET" (capitalized client name, as MySQL ships
@@ -1128,6 +1112,7 @@ _PATTERN_ANCHORS = {
1128
1112
  "Bearer token": ("bearer",),
1129
1113
  "Database URI": ("://",),
1130
1114
  "HTTP basic auth URL": ("://",),
1115
+ "HTTP token userinfo URL": ("://",),
1131
1116
  "URL auth param": ("=",),
1132
1117
  "MySQL password flag": ("mysql",),
1133
1118
  "Database env password": ("password=", "pwd=", "passwd=",