@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

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 (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +150 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3612 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +129 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +72 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +277 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +423 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +397 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +58739 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,434 @@
1
+ """Codex command rewrite adapter. Execute once, retain failures and archive originals.
2
+
3
+ Security model (hardened relative to the original design):
4
+
5
+ - ``tool_input`` execution-context fields (``shell``, ``env``, ``cwd`` and any
6
+ sibling) are IGNORED, never propagated. A prompt-injected model could
7
+ otherwise point this auto-approved wrapper at an attacker-named interpreter
8
+ or redirect a confined read to a sensitive directory. Both the rewrite
9
+ quoting and the ``--run`` exec always use runtime defaults resolved here, and
10
+ ``updatedInput`` carries only the rewritten ``command`` so no model-supplied
11
+ field can survive into the tool call. ``--run`` also refuses to execute when
12
+ the ambient working directory differs from the rewrite-time cwd recorded in
13
+ the plan.
14
+ - ``permissionDecision: 'allow'`` is emitted ONLY for commands whose file
15
+ operands are provably confined to the working directory (non-hidden,
16
+ non-sensitive, non-absolute, glob-free, no symlink escape). Eligible but
17
+ non-confined commands are passed through UNREWRITTEN -- no updatedInput and
18
+ no decision -- so Codex's own consent evaluates the literal command text.
19
+ Rewriting an unvetted read would launder e.g. ``head ~/.ssh/id_rsa`` into an
20
+ opaque ``python ... --run <blob>`` that path-based rules cannot see; under a
21
+ permissive ``python`` policy that would execute silently. Pass-through keeps
22
+ Codex's consent fully informed regardless of whether it checks the original
23
+ or the rewritten command.
24
+ - ``--run`` revalidates eligibility AND confinement at exec time and re-derives
25
+ the shell, so a forged plan can never widen what this wrapper executes.
26
+ """
27
+ import base64
28
+ import json
29
+ import os
30
+ from pathlib import Path
31
+ import re
32
+ import shlex
33
+ import shutil
34
+ import subprocess
35
+ import sys
36
+ import tempfile
37
+ import uuid
38
+
39
+ from bash_whitelist import has_dangerous_chars, is_auto_approvable, is_whitelisted
40
+
41
+ MAX_COMPRESS_BYTES = 8 * 1024 * 1024
42
+
43
+ # --- Confinement gate for the 'allow' decision + rewrite ----------------------
44
+ # A command is wrapped (and auto-allowed) only when every file operand stays
45
+ # provably inside the working directory and names nothing sensitive. Failing
46
+ # the gate costs only the compression: the command reaches Codex verbatim.
47
+ # A single leading backslash is also absolute on Windows (drive-relative,
48
+ # e.g. ``\Users\x\.ssh\id_rsa``). Catching it fail-closes the confinement
49
+ # gate for rootless Windows paths that shlex would otherwise mangle.
50
+ _ABSOLUTE_OPERAND_RE = re.compile(r'^(?:/|\\|[A-Za-z]:[\\/])')
51
+ _GLOB_OPERAND_RE = re.compile(r'[*?\[\]{}!]')
52
+ # Path components that hold credential/key material or secret stores. Applied
53
+ # per-component so `src/.ssh/config` and `.env.local` are caught, not just
54
+ # top-level names.
55
+ _SENSITIVE_COMPONENT_RE = re.compile(
56
+ r'(?i)(?:^id_(?:rsa|dsa|ecdsa|ed25519)$|^\.env(?:\..*)?$|.*\.(?:pem|key|p12|'
57
+ r'pfx|jks|keystore|kdbx?|ppk|asc|gpg)$|^\.netrc$|^\.pgpass$|^\.npmrc$|'
58
+ r'^\.pypirc$|^credentials(?:\.[a-z]+)?$|^secrets?\.(?:json|ya?ml|toml|env|txt)$|'
59
+ r'^\.ssh$|^\.gnupg$|^\.aws$|^\.azure$|^\.kube$|^\.docker$|^\.config$)'
60
+ )
61
+ # Flags that widen a search's read scope into hidden/ignored files. `rg` is
62
+ # recursive-by-default but skips hidden+ignored files unless one of these is
63
+ # given; `grep` only recurses (and thereby reads in-tree dotfiles) with -r/-R.
64
+ _RG_SCOPE_FLAGS = frozenset({
65
+ '-u', '-uu', '-uuu', '--hidden', '--no-ignore', '--no-ignore-vcs',
66
+ '--no-ignore-dot', '--no-ignore-parent', '--files', '--no-require-git',
67
+ })
68
+ # Flags whose following argument is itself a file operand (`rg -f pats`,
69
+ # `tree --fromfile f`). The value must pass the path check like any operand,
70
+ # and a pattern-supplying flag (-e/-f) means there is no pattern positional.
71
+ _PATTERN_FLAGS = frozenset({'-e', '--regexp', '-f', '--file', '--fromfile'})
72
+ _FILE_VALUE_FLAGS = frozenset({'-f', '--file', '--fromfile', '--ignore-file',
73
+ '--files0-from'})
74
+ # Flags that widen a listing to hidden files (``ls -a``, ``ls -A``,
75
+ # ``ls -la``, ``tree -a``, ``--all``, ``--almost-all``). Confinement checks
76
+ # operands, but these flags reveal dotfile names inside the cwd.
77
+ _HIDDEN_LISTING_RE = re.compile(r'-[a-zA-Z]*[aA][a-zA-Z]*')
78
+ _HIDDEN_LISTING_LONG = frozenset({'--all', '--almost-all'})
79
+ # First positional of these commands is a pattern, not a path.
80
+ _PATTERN_FIRST_COMMANDS = frozenset({'rg', 'grep'})
81
+ # PowerShell switches that widen a literal Get-Content/Get-ChildItem into
82
+ # recursion or hidden-file reads.
83
+ _PS_SCOPE_FLAGS = frozenset({'-recurse', '-force', '-hidden'})
84
+
85
+
86
+ def eligible(command):
87
+ if not isinstance(command, str) or not command.strip() or len(command) > 16000:
88
+ return False
89
+ if has_dangerous_chars(command) or 'codex_command_compress' in command:
90
+ return False
91
+ # Literal read-only PowerShell cmdlets. No script blocks, expressions or
92
+ # profile functions; the original text is passed intact to the same shell.
93
+ if re.match(r'^(Get-Content|Get-ChildItem)\s', command, re.I):
94
+ return not re.search(r'[{}()]|\s-(?:Wait|Stream)\b', command, re.I)
95
+ try:
96
+ args = shlex.split(command)
97
+ except ValueError:
98
+ return False
99
+ if not args:
100
+ return False
101
+ # The shared Claude list also contains builds, tests and write-capable
102
+ # subcommands. Codex 'allow' must only rewrite inspection commands.
103
+ if args[0] == 'git':
104
+ return len(args) > 1 and args[1] in ('status', 'log') and not any(
105
+ a.startswith(('--output', '--ext-diff', '--textconv')) for a in args[2:])
106
+ if args[0] in ('rg', 'grep', 'ls', 'tree', 'wc', 'tail'):
107
+ # is_auto_approvable is the gate every host shares; it is what refuses
108
+ # write-capable forms such as `tree -o <file>`.
109
+ return is_auto_approvable(command)
110
+ return False
111
+
112
+
113
+ def _default_shell():
114
+ """The shell this runtime would use. ``tool_input.shell`` is never read:
115
+ it is model-controlled text and must not steer an auto-approved hook.
116
+
117
+ PATH is walked entry by entry and every candidate must resolve under a
118
+ system directory. ``shutil.which`` would return the first PATH hit, so a
119
+ model-controlled ``env.PATH`` could otherwise point this wrapper at an
120
+ attacker-placed ``bash``/``pwsh``. An environment with no validated shell
121
+ yields ``None`` (fail closed: the command passes through unrewritten).
122
+ """
123
+ if os.name == 'nt':
124
+ names = ('pwsh.exe', 'powershell.exe')
125
+ roots = []
126
+ for var, fallback in (('SystemRoot', r'C:\Windows'),
127
+ ('ProgramFiles', r'C:\Program Files'),
128
+ ('ProgramFiles(x86)', r'C:\Program Files (x86)')):
129
+ raw = os.environ.get(var) or fallback
130
+ try:
131
+ roots.append(Path(raw).resolve())
132
+ except OSError:
133
+ continue
134
+ else:
135
+ names = ('bash', 'sh')
136
+ roots = []
137
+ for directory in ('/bin', '/sbin', '/usr/bin', '/usr/sbin',
138
+ '/usr/local/bin', '/usr/local/sbin',
139
+ '/opt/homebrew/bin', '/opt/homebrew/sbin'):
140
+ try:
141
+ roots.append(Path(directory).resolve())
142
+ except OSError:
143
+ continue
144
+ for name in names:
145
+ for directory in os.environ.get('PATH', '').split(os.pathsep):
146
+ if not directory:
147
+ continue
148
+ try:
149
+ candidate = (Path(directory) / name).resolve()
150
+ if (candidate.name.lower() == name and candidate.is_file()
151
+ and os.access(candidate, os.X_OK)
152
+ and any(candidate.is_relative_to(root)
153
+ for root in roots)):
154
+ return str(candidate)
155
+ except OSError:
156
+ # Unreadable PATH entries (e.g. another user's ~/.cargo/bin on
157
+ # a shared machine) must not crash shell resolution -- skip
158
+ # them like any other non-match and keep scanning.
159
+ continue
160
+ return None
161
+
162
+
163
+ def _operand_confined(arg, base):
164
+ """True when a single operand is a provably in-cwd, non-hidden,
165
+ non-sensitive path -- or not path-shaped at all."""
166
+ arg = arg.strip('"\'') # posix=False shlex keeps quote characters
167
+ if (not arg or arg.startswith(('~', '$')) or _ABSOLUTE_OPERAND_RE.match(arg)
168
+ or _GLOB_OPERAND_RE.search(arg)):
169
+ return False
170
+ components = [c for c in re.split(r'[\\/]+', arg) if c and c != '.']
171
+ if any(c.startswith('.') or _SENSITIVE_COMPONENT_RE.search(c) for c in components):
172
+ return False
173
+ try:
174
+ return (base / arg).resolve().is_relative_to(base)
175
+ except OSError:
176
+ return False
177
+
178
+
179
+ def _confined(command, base):
180
+ """True when every file operand of `command` is confined to `base`.
181
+
182
+ `base` is always the real process cwd at call time -- never the
183
+ model-influenced payload cwd, which cannot be trusted as a confinement
184
+ boundary.
185
+
186
+ Tokenization uses ``posix=False`` so backslashes in Windows path
187
+ operands (``C:\\Users\\x\\.ssh\\id_rsa``) are preserved for the
188
+ absolute-path and sensitive-component checks. POSIX-mode shlex would
189
+ consume the backslashes, collapsing the path to a relative-looking
190
+ token that bypasses confinement. Quote characters retained by
191
+ ``posix=False`` are stripped before every flag/operand comparison
192
+ (mirroring the PowerShell branch and ``_operand_confined``).
193
+ """
194
+ if re.match(r'^(Get-Content|Get-ChildItem)\s', command, re.I):
195
+ # PowerShell quoting differs from POSIX; flag-looking tokens are still
196
+ # dashed and the rest are operands.
197
+ try:
198
+ args = shlex.split(command, posix=False)[1:]
199
+ except ValueError:
200
+ return False
201
+ if any(a.strip('"\'').lower() in _PS_SCOPE_FLAGS for a in args):
202
+ return False
203
+ cmd0 = ''
204
+ else:
205
+ try:
206
+ args = shlex.split(command, posix=False)
207
+ except ValueError:
208
+ return False
209
+ cmd0 = args[0].strip('"\'') if args else ''
210
+ args = args[1:]
211
+ if cmd0 == 'rg' and any(a.strip('\'"') in _RG_SCOPE_FLAGS for a in args):
212
+ return False
213
+ if cmd0 == 'grep':
214
+ stripped = [a.strip('\'"') for a in args]
215
+ if any(a == '--recursive' or a == '--dereference-recursive'
216
+ or re.fullmatch(r'-[a-zA-Z]*[rR][a-zA-Z]*', a) for a in stripped):
217
+ return False
218
+ # ``grep -d recurse`` / ``--directories=recurse`` is functionally -r:
219
+ # it recurses into directories and reads dotfiles in the cwd. The
220
+ # value following ``-d``/``--directories`` is the action keyword.
221
+ for i, a in enumerate(stripped):
222
+ if a == '-d' or a == '--directories':
223
+ nxt = stripped[i + 1] if i + 1 < len(stripped) else ''
224
+ if nxt == 'recurse':
225
+ return False
226
+ elif a.startswith('--directories='):
227
+ if a.split('=', 1)[1] == 'recurse':
228
+ return False
229
+ if cmd0 in ('ls', 'tree') and any(
230
+ _HIDDEN_LISTING_RE.fullmatch(a.strip('\'"')) or a.strip('\'"') in _HIDDEN_LISTING_LONG
231
+ for a in args):
232
+ return False
233
+ expect_pattern = cmd0 in _PATTERN_FIRST_COMMANDS
234
+ file_value_next = False
235
+ for arg in args:
236
+ tok = arg.strip('\'"') # posix=False keeps quote characters
237
+ if file_value_next:
238
+ file_value_next = False
239
+ elif tok.startswith('-') and tok != '-':
240
+ name, sep, value = tok.partition('=')
241
+ if name in _FILE_VALUE_FLAGS:
242
+ if sep:
243
+ # Attached ``--flag=VALUE``: the value is a file operand
244
+ # too, so it gets the same confinement check.
245
+ if not _operand_confined(value, base):
246
+ return False
247
+ else:
248
+ file_value_next = True
249
+ elif not sep and len(tok) > 2 and tok[:2] in _FILE_VALUE_FLAGS:
250
+ # Glued short form: ``grep -fFILE`` / ``rg -fFILE``.
251
+ if not _operand_confined(tok[2:], base):
252
+ return False
253
+ if name in _PATTERN_FLAGS or (
254
+ not sep and len(tok) > 2 and tok[:2] in _PATTERN_FLAGS):
255
+ expect_pattern = False
256
+ continue
257
+ elif expect_pattern:
258
+ expect_pattern = False
259
+ continue
260
+ if not _operand_confined(arg, base):
261
+ return False
262
+ return True
263
+
264
+
265
+ def rewrite(payload):
266
+ from plugin_env import is_v5_flag_enabled
267
+ if not is_v5_flag_enabled('v5_bash_compress', 'TOKEN_OPTIMIZER_BASH_COMPRESS', default=True):
268
+ return None
269
+ if not isinstance(payload, dict) or payload.get('tool_name') != 'Bash':
270
+ return None
271
+ tool_input = payload.get('tool_input')
272
+ if not isinstance(tool_input, dict):
273
+ return None
274
+ command = tool_input.get('command')
275
+ shell = _default_shell()
276
+ if not eligible(command) or not shell:
277
+ return None
278
+ if not _confined(command, Path.cwd().resolve()):
279
+ # Provably-safe reads only. Anything else passes through untouched so
280
+ # Codex's consent sees the literal command (e.g. `head ~/.ssh/id_rsa`
281
+ # prompts exactly as it would without this hook).
282
+ return None
283
+ plan = {'command': command, 'session_id': payload.get('session_id'),
284
+ 'model': payload.get('model'), 'cwd': str(Path.cwd().resolve())}
285
+ encoded = base64.b64encode(json.dumps(plan).encode()).decode()
286
+ argv = [sys.executable, str(Path(__file__).resolve()), '--run', encoded]
287
+ if Path(shell).stem.lower() in ('pwsh', 'powershell'):
288
+ rewritten = '& ' + ' '.join("'" + a.replace("'", "''") + "'" for a in argv) + '; exit $LASTEXITCODE'
289
+ else:
290
+ rewritten = shlex.join(argv)
291
+ # updatedInput carries ONLY the rewritten command. Every other tool_input
292
+ # field (shell, env, cwd, and any future execution-context sibling) is
293
+ # model-controlled and must never reach an auto-approved tool call: env
294
+ # could steer PATH resolution, cwd could redirect the confined read.
295
+ updated = {'command': rewritten}
296
+ return {'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'allow',
297
+ 'updatedInput': updated}}
298
+
299
+
300
+ def run(plan):
301
+ command = plan.get('command') if isinstance(plan, dict) else None
302
+ # Revalidate at execution time: never turn a trusted wrapper into a generic
303
+ # command launcher. Ineligible or non-confined commands are not executed by
304
+ # this wrapper -- a forged plan cannot exceed the inspection envelope.
305
+ if not eligible(command) or not _confined(command, Path.cwd().resolve()):
306
+ print('Token Optimizer: command is not eligible', file=sys.stderr)
307
+ return 2
308
+ # The plan pins the rewrite-time working directory. Confinement was proven
309
+ # against THAT cwd; if the ambient cwd differs (e.g. a model-controlled
310
+ # tool_input.cwd survived into the tool call), re-running the confined
311
+ # command here would read files in a different directory. Refuse.
312
+ expected_cwd = plan.get('cwd')
313
+ if expected_cwd:
314
+ try:
315
+ same_cwd = Path.cwd().resolve() == Path(str(expected_cwd)).resolve()
316
+ except OSError:
317
+ same_cwd = False
318
+ if not same_cwd:
319
+ print('Token Optimizer: working directory changed since approval',
320
+ file=sys.stderr)
321
+ return 2
322
+ shell = _default_shell()
323
+ if not shell:
324
+ print('Token Optimizer: no usable default shell', file=sys.stderr)
325
+ return 2
326
+ # Scope runtime markers to the child environment only. Mutating the
327
+ # parent's os.environ leaks 'codex' into any process that calls run()
328
+ # in-process (and poisons detect_runtime() for everything after it).
329
+ child_env = dict(os.environ, TOKEN_OPTIMIZER_RUNTIME='codex')
330
+ if plan.get('session_id'):
331
+ child_env['TOKEN_OPTIMIZER_SESSION_ID'] = str(plan['session_id'])
332
+ if Path(shell).stem.lower() in ('pwsh', 'powershell'):
333
+ tail = '; $toSucceeded=$?; $toExit=$LASTEXITCODE; if ($null -ne $toExit) { exit $toExit }; if (-not $toSucceeded) { exit 1 }'
334
+ argv = [shell, '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command + tail]
335
+ else:
336
+ argv = [shell, '-c', command]
337
+ with tempfile.TemporaryFile() as output, tempfile.TemporaryFile() as errors:
338
+ try:
339
+ result = subprocess.run(argv, stdout=output, stderr=errors, env=child_env,
340
+ timeout=6,
341
+ creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
342
+ except subprocess.TimeoutExpired:
343
+ # Stream whatever was captured before the timeout, then exit.
344
+ output.seek(0)
345
+ shutil.copyfileobj(output, sys.stdout.buffer)
346
+ errors.seek(0)
347
+ shutil.copyfileobj(errors, sys.stderr.buffer)
348
+ print('Token Optimizer: command timed out', file=sys.stderr)
349
+ return 124
350
+ except OSError:
351
+ # Spawn failed (shell binary deleted between check and exec, etc.).
352
+ print('Token Optimizer: failed to spawn command', file=sys.stderr)
353
+ return 127
354
+ output.seek(0, 2)
355
+ size = output.tell()
356
+ output.seek(0)
357
+ errors.seek(0)
358
+ # Failure/oversized output is streamed verbatim, never buffered in RAM.
359
+ if result.returncode != 0 or size > MAX_COMPRESS_BYTES:
360
+ shutil.copyfileobj(output, sys.stdout.buffer)
361
+ shutil.copyfileobj(errors, sys.stderr.buffer)
362
+ return result.returncode
363
+ raw_bytes = output.read()
364
+ error_bytes = errors.read(MAX_COMPRESS_BYTES + 1)
365
+ if error_bytes: # preserve warnings too; no simplification on stderr
366
+ sys.stdout.buffer.write(raw_bytes)
367
+ sys.stderr.buffer.write(error_bytes)
368
+ shutil.copyfileobj(errors, sys.stderr.buffer)
369
+ return result.returncode
370
+ try:
371
+ raw = raw_bytes.decode('utf-8', errors='strict')
372
+ except UnicodeError:
373
+ sys.stdout.buffer.write(raw_bytes)
374
+ return result.returncode
375
+ try:
376
+ from bash_compress import compress
377
+ from plugin_env import resolve_snapshot_dir
378
+ from token_estimate import estimate_tokens
379
+ short = compress(command, raw)
380
+ if short != raw and len(short) < len(raw) * 0.9:
381
+ archive = resolve_snapshot_dir() / 'codex-command-output'
382
+ archive.mkdir(parents=True, exist_ok=True)
383
+ target = archive / (uuid.uuid4().hex + '.txt')
384
+ try:
385
+ with target.open('xb') as handle:
386
+ handle.write(raw_bytes)
387
+ # Restrict to owner-only read: the archive may hold command
388
+ # output that touched sensitive in-cwd files. Mirrors
389
+ # archive_result._chmod_private_file on the tool-archive path.
390
+ try:
391
+ os.chmod(target, 0o600)
392
+ except OSError:
393
+ pass
394
+ except OSError:
395
+ target = None # disk full or permission denied; skip archive
396
+ if target:
397
+ short += f'\n[Token Optimizer: full command output saved to {target}]\n'
398
+ if estimate_tokens(short) < estimate_tokens(raw):
399
+ sys.stdout.buffer.write(short.encode('utf-8'))
400
+ sys.stdout.buffer.flush()
401
+ try:
402
+ from compression_log import log_compression_event
403
+ log_compression_event(feature='codex_command_compress', original_text=raw,
404
+ compressed_text=short, session_id=plan.get('session_id'),
405
+ model=plan.get('model') or 'unknown', command_pattern='read-only command',
406
+ verified=True, tier='measured')
407
+ except Exception:
408
+ pass
409
+ return 0
410
+ except Exception:
411
+ pass
412
+ sys.stdout.buffer.write(raw_bytes)
413
+ return result.returncode
414
+
415
+
416
+ def main():
417
+ from utf8_io import enforce_utf8_io
418
+ enforce_utf8_io()
419
+ if len(sys.argv) == 3 and sys.argv[1] == '--run':
420
+ try:
421
+ plan = json.loads(base64.b64decode(sys.argv[2]))
422
+ except (ValueError, UnicodeError):
423
+ print('Token Optimizer: malformed plan', file=sys.stderr)
424
+ return 2
425
+ return run(plan)
426
+ from hook_io import read_stdin_hook_input
427
+ result = rewrite(read_stdin_hook_input() or {})
428
+ if result:
429
+ print(json.dumps(result))
430
+ return 0
431
+
432
+
433
+ if __name__ == '__main__':
434
+ raise SystemExit(main())