@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.
- package/.claude-plugin/marketplace.json +76 -0
- package/.claude-plugin/plugin.json +21 -0
- package/LICENSE +130 -0
- package/LICENSE-SMALL-BUSINESS.md +62 -0
- package/PRIVACY.md +200 -0
- package/README.md +13 -2
- package/hooks/codex-hooks.json +4 -0
- package/hooks/hooks.json +182 -0
- package/hooks/module_runner.py +149 -0
- package/hooks/posttooluse_runner.py +1110 -0
- package/hooks/python-launcher.sh +816 -0
- package/hooks/run.py +776 -0
- package/hooks/sessionstart_runner.py +629 -0
- package/hooks/stop_runner.py +408 -0
- package/hooks/userpromptsubmit_runner.py +722 -0
- package/hooks/windows-launcher.py +163 -0
- package/install-cloud.sh +23 -0
- package/package.json +29 -4
- package/skills/fleet-auditor/SKILL.md +150 -0
- package/skills/fleet-auditor/references/fleet-systems.md +167 -0
- package/skills/fleet-auditor/references/report-template.md +50 -0
- package/skills/fleet-auditor/references/waste-patterns.md +126 -0
- package/skills/fleet-auditor/scripts/fleet.py +3612 -0
- package/skills/fleet-auditor/scripts/shared.py +277 -0
- package/skills/resume-checkpoint/SKILL.md +52 -0
- package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
- package/skills/token-coach/SKILL.md +129 -0
- package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
- package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
- package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
- package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
- package/skills/token-coach/references/agentic-systems.md +147 -0
- package/skills/token-coach/references/coach-patterns.md +120 -0
- package/skills/token-coach/references/coaching-scripts.md +146 -0
- package/skills/token-coach/references/deterministic-stages.md +102 -0
- package/skills/token-coach/references/keepwarm-consent.md +48 -0
- package/skills/token-coach/references/quick-reference.md +155 -0
- package/skills/token-dashboard/SKILL.md +72 -0
- package/skills/token-optimizer/SKILL.md +150 -0
- package/skills/token-optimizer/assets/dashboard.html +7251 -0
- package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
- package/skills/token-optimizer/examples/hooks-starter.json +179 -0
- package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
- package/skills/token-optimizer/pricing/prices.json +695 -0
- package/skills/token-optimizer/references/agent-prompts.md +687 -0
- package/skills/token-optimizer/references/cli-reference.md +92 -0
- package/skills/token-optimizer/references/codex-workflow.md +188 -0
- package/skills/token-optimizer/references/cursor-workflow.md +74 -0
- package/skills/token-optimizer/references/error-recovery.md +37 -0
- package/skills/token-optimizer/references/implementation-playbook.md +416 -0
- package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
- package/skills/token-optimizer/references/opencode-workflow.md +72 -0
- package/skills/token-optimizer/references/optimization-checklist.md +714 -0
- package/skills/token-optimizer/references/phase0-setup.md +142 -0
- package/skills/token-optimizer/references/presentation-workflow.md +72 -0
- package/skills/token-optimizer/references/session-continuity.md +19 -0
- package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
- package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
- package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
- package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
- package/skills/token-optimizer/scripts/archive_result.py +1725 -0
- package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
- package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
- package/skills/token-optimizer/scripts/bash_hook.py +61 -0
- package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
- package/skills/token-optimizer/scripts/benchmark.py +1765 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
- package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
- package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
- package/skills/token-optimizer/scripts/codex_install.py +810 -0
- package/skills/token-optimizer/scripts/codex_io.py +119 -0
- package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
- package/skills/token-optimizer/scripts/codex_models.py +34 -0
- package/skills/token-optimizer/scripts/codex_session.py +1186 -0
- package/skills/token-optimizer/scripts/codex_state.py +707 -0
- package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
- package/skills/token-optimizer/scripts/command_filters.py +386 -0
- package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
- package/skills/token-optimizer/scripts/compression_log.py +230 -0
- package/skills/token-optimizer/scripts/context_intel.py +331 -0
- package/skills/token-optimizer/scripts/context_pressure.py +115 -0
- package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
- package/skills/token-optimizer/scripts/copilot_install.py +277 -0
- package/skills/token-optimizer/scripts/copilot_session.py +496 -0
- package/skills/token-optimizer/scripts/copilot_state.py +569 -0
- package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
- package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
- package/skills/token-optimizer/scripts/cowork_install.py +380 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
- package/skills/token-optimizer/scripts/cursor_install.py +423 -0
- package/skills/token-optimizer/scripts/cursor_session.py +303 -0
- package/skills/token-optimizer/scripts/cursor_state.py +348 -0
- package/skills/token-optimizer/scripts/delta_diff.py +110 -0
- package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
- package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
- package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
- package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
- package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
- package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
- package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
- package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
- package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
- package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
- package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
- package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
- package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
- package/skills/token-optimizer/scripts/devin_compress.py +790 -0
- package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
- package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
- package/skills/token-optimizer/scripts/devin_install.py +1086 -0
- package/skills/token-optimizer/scripts/devin_source.py +119 -0
- package/skills/token-optimizer/scripts/devin_state.py +330 -0
- package/skills/token-optimizer/scripts/devin_verify.py +67 -0
- package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
- package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
- package/skills/token-optimizer/scripts/grok_install.py +397 -0
- package/skills/token-optimizer/scripts/grok_session.py +317 -0
- package/skills/token-optimizer/scripts/grok_state.py +299 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
- package/skills/token-optimizer/scripts/hermes_install.py +668 -0
- package/skills/token-optimizer/scripts/hermes_session.py +691 -0
- package/skills/token-optimizer/scripts/hermes_state.py +448 -0
- package/skills/token-optimizer/scripts/hook_io.py +120 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
- package/skills/token-optimizer/scripts/injection.py +156 -0
- package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
- package/skills/token-optimizer/scripts/measure.py +58739 -0
- package/skills/token-optimizer/scripts/outline.py +53 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
- package/skills/token-optimizer/scripts/plugin_env.py +562 -0
- package/skills/token-optimizer/scripts/py_trust.py +80 -0
- package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
- package/skills/token-optimizer/scripts/read_cache.py +2489 -0
- package/skills/token-optimizer/scripts/recovery_output.py +110 -0
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
- package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
- package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
- package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
- package/skills/token-optimizer/scripts/session_store.py +979 -0
- package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
- package/skills/token-optimizer/scripts/statusline.js +660 -0
- package/skills/token-optimizer/scripts/structure_map.py +2880 -0
- package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
- package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
- package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
- package/skills/token-optimizer/scripts/token_estimate.py +80 -0
- package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
- package/skills/token-optimizer/scripts/utf8_io.py +219 -0
|
@@ -0,0 +1,810 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Install Token Optimizer Codex hooks globally or into a project workspace."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import base64
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import shlex
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import tempfile
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import codex_compact_prompt
|
|
19
|
+
import codex_io
|
|
20
|
+
import codex_statusline
|
|
21
|
+
from runtime_env import codex_home
|
|
22
|
+
|
|
23
|
+
TOKEN_OPTIMIZER_MARKER = "token-optimizer/scripts"
|
|
24
|
+
SUPPORTED_EVENTS = (
|
|
25
|
+
"PreToolUse", "SessionStart", "UserPromptSubmit", "PostToolUse", "Stop",
|
|
26
|
+
"SessionEnd", "StopFailure", "SubagentStart", "SubagentStop",
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
# A Codex marketplace install lives in a versioned directory
|
|
30
|
+
# (.../token-optimizer/<X.Y.Z>/) that the marketplace replaces on upgrade.
|
|
31
|
+
# Used to decide whether the baked hook command must resolve the active version
|
|
32
|
+
# at runtime instead of pinning it (which dies on the next update).
|
|
33
|
+
_SEMVER_DIR_RE = re.compile(r"^\d+\.\d+\.\d+$")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _repo_root() -> Path:
|
|
37
|
+
return Path(__file__).resolve().parents[3]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# Inline POSIX bash-resolver prefix/suffix. When Claude/Codex runs a hook
|
|
41
|
+
# command under `/bin/sh -c` with a stripped/empty PATH, bare `bash` is not
|
|
42
|
+
# found → exit 127 spam on every tool call. The resolver probes `command -v`
|
|
43
|
+
# for bash in PATH then a fixed list of absolute locations (POSIX guarantees
|
|
44
|
+
# `command -v /abs/path` works without PATH). `exec` replaces the shell with
|
|
45
|
+
# bash; the trailing `exit 0` is a quiet no-op when no bash exists anywhere.
|
|
46
|
+
_BASH_RESOLVER_PREFIX = (
|
|
47
|
+
'for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; '
|
|
48
|
+
'do command -v "$b" >/dev/null 2>&1 || continue; '
|
|
49
|
+
)
|
|
50
|
+
_BASH_RESOLVER_SUFFIX = "; done; exit 0"
|
|
51
|
+
|
|
52
|
+
# Marker baked into every generated Windows launcher command so install,
|
|
53
|
+
# uninstall, doctor, and dashboard ownership checks can recognize it. The
|
|
54
|
+
# launcher strips it from the argv it forwards to the runner.
|
|
55
|
+
_LAUNCHER_MARKER = "token-optimizer/scripts/windows-launcher"
|
|
56
|
+
# Filename of the readable launcher codex_install copies NEXT TO the
|
|
57
|
+
# versioned install dirs (issue #183); canonical source ships in hooks/.
|
|
58
|
+
_LAUNCHER_FILENAME = "windows-launcher.py"
|
|
59
|
+
_LAUNCHER_B64_RE = re.compile(r"b64decode\('([A-Za-z0-9+/=]+)'\)")
|
|
60
|
+
# Sentinel version leaf used when normalizing a launcher for signature
|
|
61
|
+
# comparison (see _launcher_signature).
|
|
62
|
+
_SIGNATURE_VERSION = "0.0.0"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _cmd_quote(token: str) -> str:
|
|
66
|
+
"""Quote a token so it survives BOTH cmd.exe's /C metachar parse and the
|
|
67
|
+
MSVCRT argv parser the Python runner is launched through.
|
|
68
|
+
|
|
69
|
+
list2cmdline gives MSVCRT-correct quoting but only wraps a token that
|
|
70
|
+
contains whitespace, so a space-free install path carrying a cmd
|
|
71
|
+
metacharacter (& | < > ^) reaches cmd bare and is parsed as a command
|
|
72
|
+
separator (the base64 form never had this: paths lived inside the encoded
|
|
73
|
+
payload). Force the wrap. Our values never contain a literal " (illegal in
|
|
74
|
+
a Windows path; the generated argv/env values are fixed and quote-free) and
|
|
75
|
+
never end in a backslash, so a plain double-quote wrap stays MSVCRT-safe.
|
|
76
|
+
A literal % still expands inside quotes -- a documented, install-path-only
|
|
77
|
+
limitation, unchanged here.
|
|
78
|
+
"""
|
|
79
|
+
quoted = subprocess.list2cmdline([token])
|
|
80
|
+
return quoted if quoted.startswith('"') else f'"{quoted}"'
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _windows_launcher_command(root: Path, script: str, args, extra_env: dict) -> str:
|
|
84
|
+
"""Build the baked Windows hook command for a versioned marketplace root.
|
|
85
|
+
|
|
86
|
+
The command invokes the readable launcher file that install() copies to
|
|
87
|
+
the STABLE parent of the version dirs (.../token-optimizer/
|
|
88
|
+
windows-launcher.py, which survives the marketplace swapping
|
|
89
|
+
.../token-optimizer/<X.Y.Z>/ on upgrade) by quoted path -- issue #183:
|
|
90
|
+
the retired base64 `python -c` exec-bootstrap tripped
|
|
91
|
+
generic-loader antivirus signatures on the literal encoded-exec
|
|
92
|
+
string. Every value token is force-quoted (see _cmd_quote): the runner
|
|
93
|
+
path and --baked-root can contain cmd.exe metacharacters (& | < > ^)
|
|
94
|
+
with no surrounding space, which list2cmdline alone leaves bare and cmd
|
|
95
|
+
then parses as command separators -- the base64 form hid them inside the
|
|
96
|
+
payload, so this restores that safety. Quoting keeps the /C single-parse
|
|
97
|
+
problem (issue #180) solved with no expansion form. The launcher resolves
|
|
98
|
+
the newest semver sibling of the baked root at runtime; --baked-root is
|
|
99
|
+
the fail-open fallback only. The trailing marker keeps the command
|
|
100
|
+
recognizable to ownership checks; the launcher strips it before
|
|
101
|
+
dispatching, so the runner's sys.argv stays exactly [run.py, script,
|
|
102
|
+
*args].
|
|
103
|
+
"""
|
|
104
|
+
parts = [
|
|
105
|
+
_cmd_quote(sys.executable),
|
|
106
|
+
_cmd_quote(str(root.parent / _LAUNCHER_FILENAME)),
|
|
107
|
+
"--baked-root",
|
|
108
|
+
_cmd_quote(str(root)),
|
|
109
|
+
]
|
|
110
|
+
for key, value in extra_env.items():
|
|
111
|
+
parts += ["--env", _cmd_quote(f"{key}={value}")]
|
|
112
|
+
parts += ["--", _cmd_quote(script), *(_cmd_quote(a) for a in args),
|
|
113
|
+
_cmd_quote(_LAUNCHER_MARKER)]
|
|
114
|
+
return " ".join(parts)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def decode_launcher_command(command: str) -> str | None:
|
|
118
|
+
"""Decode the embedded Python bootstrap of a LEGACY generated launcher.
|
|
119
|
+
|
|
120
|
+
Only pre-launcher-file commands (the base64 `python -c` bootstrap retired
|
|
121
|
+
for issue #183) carry a payload to decode; launcher-file commands are
|
|
122
|
+
self-auditing (the invoked .py is plain source). Returns None when
|
|
123
|
+
`command` is not a legacy one of ours (no launcher marker or no base64
|
|
124
|
+
payload). Pure decode-and-print for audits; never executes.
|
|
125
|
+
"""
|
|
126
|
+
if _LAUNCHER_MARKER not in command:
|
|
127
|
+
return None
|
|
128
|
+
match = _LAUNCHER_B64_RE.search(command)
|
|
129
|
+
if not match:
|
|
130
|
+
return None
|
|
131
|
+
try:
|
|
132
|
+
return base64.b64decode(match.group(1)).decode("utf-8")
|
|
133
|
+
except (ValueError, UnicodeError):
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _hook_command(script: str, *args: str, redirect_quiet: bool = False,
|
|
138
|
+
extra_env: dict[str, str] | None = None) -> str:
|
|
139
|
+
root = _repo_root()
|
|
140
|
+
extra_env = extra_env or {}
|
|
141
|
+
if sys.platform == "win32":
|
|
142
|
+
# Codex runs command hooks through cmd.exe on native Windows. Invoke the
|
|
143
|
+
# current interpreter directly so the hot path does not traverse MSYS
|
|
144
|
+
# bash and python-launcher.sh (several CreateProcess calls per hook).
|
|
145
|
+
# list2cmdline applies native Windows quoting for paths with spaces.
|
|
146
|
+
#
|
|
147
|
+
# Codex uses %COMSPEC% /C on native Windows, not Git Bash. Avoid
|
|
148
|
+
# batch-only SETLOCAL semantics and nested shell quoting here.
|
|
149
|
+
_win_env = ''.join(
|
|
150
|
+
f'set "{k}={v}" && ' for k, v in extra_env.items()
|
|
151
|
+
)
|
|
152
|
+
if _SEMVER_DIR_RE.match(root.name):
|
|
153
|
+
# CMD needs a Windows-native counterpart to the POSIX runtime
|
|
154
|
+
# resolver below. cmd.exe parses a /C command line ONCE, before
|
|
155
|
+
# anything on it runs, so neither %VAR% nor a same-line !VAR!
|
|
156
|
+
# (setlocal does not apply outside batch files) can carry the
|
|
157
|
+
# resolved version into the runner path (issue #180). The command
|
|
158
|
+
# instead invokes the readable launcher file installed next to the
|
|
159
|
+
# version dirs by quoted path (issue #183: the base64 -c bootstrap
|
|
160
|
+
# tripped generic-loader antivirus signatures) -- the launcher
|
|
161
|
+
# resolves the newest semver install in the Python process we are
|
|
162
|
+
# already launching, which removes the nested-quoting and
|
|
163
|
+
# console-codepage problems entirely. Audit by reading the file;
|
|
164
|
+
# legacy base64 commands still decode via --decode-launcher.
|
|
165
|
+
command = _windows_launcher_command(root, script, args, extra_env)
|
|
166
|
+
else:
|
|
167
|
+
prefix = f'set "TOKEN_OPTIMIZER_RUNTIME=codex" && {_win_env}'
|
|
168
|
+
argv = [sys.executable, str(root / "hooks" / "run.py"), script, *args]
|
|
169
|
+
redirect = " >NUL 2>&1" if redirect_quiet else ""
|
|
170
|
+
if _SEMVER_DIR_RE.match(root.name):
|
|
171
|
+
return f"{command}{redirect}"
|
|
172
|
+
return f"{prefix}{subprocess.list2cmdline(argv)}{redirect}"
|
|
173
|
+
|
|
174
|
+
command_args = " ".join(shlex.quote(arg) for arg in (script, *args))
|
|
175
|
+
redirect = " >/dev/null 2>&1" if redirect_quiet else ""
|
|
176
|
+
_posix_env = " ".join(f"{k}={shlex.quote(v)}" for k, v in extra_env.items())
|
|
177
|
+
_posix_env_prefix = f"{_posix_env} " if _posix_env else ""
|
|
178
|
+
if _SEMVER_DIR_RE.match(root.name):
|
|
179
|
+
# Marketplace install: root is .../token-optimizer/<X.Y.Z>/, which is
|
|
180
|
+
# deleted when Codex installs a newer version. Pinning it here makes
|
|
181
|
+
# hooks.json point at a missing directory after every upgrade, so each
|
|
182
|
+
# Codex tool call fails. Resolve the newest installed version at
|
|
183
|
+
# runtime from the stable parent dir, falling back to the baked path.
|
|
184
|
+
base = shlex.quote(str(root.parent))
|
|
185
|
+
fallback = shlex.quote(str(root) + "/")
|
|
186
|
+
# Only consider semver-named subdirs so a stray sibling (latest/, backup/,
|
|
187
|
+
# __pycache__/) can't be picked by `sort -V | tail` over the real version.
|
|
188
|
+
# $0 is set to the resolved bash binary (passed as the first arg after
|
|
189
|
+
# `-c`), so `exec "$0"` re-execs the same bash without needing PATH.
|
|
190
|
+
inner = (
|
|
191
|
+
f'R="$(ls -d {base}/*/ 2>/dev/null | grep -E \'/[0-9]+[.][0-9]+[.][0-9]+/$\' '
|
|
192
|
+
f'| sort -V | tail -n 1)"; '
|
|
193
|
+
f'[ -n "$R" ] || R={fallback}; '
|
|
194
|
+
# bash READS the launcher script (exec "$0" = bash "$T" ...), so it
|
|
195
|
+
# only needs to be readable, not executable; -x would wrongly no-op a
|
|
196
|
+
# readable-but-not-+x launcher (e.g. after an extraction dropped the bit).
|
|
197
|
+
f'T="${{R}}hooks/python-launcher.sh"; P="${{R}}hooks/run.py"; '
|
|
198
|
+
f'[ -r "$T" ] && [ -r "$P" ] || exit 0; exec "$0" "$T" "$P" {command_args}{redirect}'
|
|
199
|
+
)
|
|
200
|
+
command = (
|
|
201
|
+
f"{_BASH_RESOLVER_PREFIX}"
|
|
202
|
+
f'TOKEN_OPTIMIZER_RUNTIME=codex {_posix_env_prefix}exec "$b" -c {shlex.quote(inner)} "$b"'
|
|
203
|
+
f"{_BASH_RESOLVER_SUFFIX}"
|
|
204
|
+
)
|
|
205
|
+
else:
|
|
206
|
+
launcher = shlex.quote(str(root / "hooks" / "python-launcher.sh"))
|
|
207
|
+
runner = shlex.quote(str(root / "hooks" / "run.py"))
|
|
208
|
+
command = (
|
|
209
|
+
f"{_BASH_RESOLVER_PREFIX}"
|
|
210
|
+
f'[ -r {launcher} ] && [ -r {runner} ] || exit 0; TOKEN_OPTIMIZER_RUNTIME=codex {_posix_env_prefix}exec "$b" {launcher} {runner} {command_args}'
|
|
211
|
+
f"{redirect}{_BASH_RESOLVER_SUFFIX}"
|
|
212
|
+
)
|
|
213
|
+
return command
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _managed_hooks(
|
|
217
|
+
*,
|
|
218
|
+
enable_bash_compression: bool = False,
|
|
219
|
+
enable_hot_path_hooks: bool = False,
|
|
220
|
+
enable_prompt_hooks: bool = False,
|
|
221
|
+
enable_subagent_hooks: bool = False,
|
|
222
|
+
) -> dict[str, list[dict[str, Any]]]:
|
|
223
|
+
"""Build Codex project hooks.
|
|
224
|
+
|
|
225
|
+
Default is the aggressive profile (max savings). SessionStart,
|
|
226
|
+
UserPromptSubmit, PostToolUse, and Stop are routed through the consolidated
|
|
227
|
+
runner scripts (hooks/sessionstart_runner.py, hooks/userpromptsubmit_runner.py,
|
|
228
|
+
hooks/posttooluse_runner.py, hooks/stop_runner.py) so Codex users receive the
|
|
229
|
+
same diagnostics-routing, systemMessage-preservation, and process-
|
|
230
|
+
consolidation fixes as Claude Code. SubagentStart/Stop remain on the
|
|
231
|
+
Codex-specific bridge (no runner exists for subagent events). Bash
|
|
232
|
+
compression uses Codex's PreToolUse updatedInput and remains an explicit
|
|
233
|
+
opt-in; it is inert on Codex builds that do not honor updatedInput.
|
|
234
|
+
"""
|
|
235
|
+
hooks = {
|
|
236
|
+
"Stop": [
|
|
237
|
+
{
|
|
238
|
+
"hooks": [
|
|
239
|
+
{
|
|
240
|
+
"type": "command",
|
|
241
|
+
"command": _hook_command(
|
|
242
|
+
"hooks/stop_runner.py",
|
|
243
|
+
redirect_quiet=True,
|
|
244
|
+
),
|
|
245
|
+
"timeout": 15,
|
|
246
|
+
}
|
|
247
|
+
]
|
|
248
|
+
}
|
|
249
|
+
],
|
|
250
|
+
}
|
|
251
|
+
if enable_prompt_hooks:
|
|
252
|
+
hooks.update({
|
|
253
|
+
"SessionStart": [
|
|
254
|
+
{
|
|
255
|
+
"hooks": [
|
|
256
|
+
{
|
|
257
|
+
"type": "command",
|
|
258
|
+
"command": _hook_command(
|
|
259
|
+
"hooks/sessionstart_runner.py",
|
|
260
|
+
),
|
|
261
|
+
"timeout": 20,
|
|
262
|
+
}
|
|
263
|
+
],
|
|
264
|
+
}
|
|
265
|
+
],
|
|
266
|
+
"UserPromptSubmit": [
|
|
267
|
+
{
|
|
268
|
+
"hooks": [
|
|
269
|
+
{
|
|
270
|
+
"type": "command",
|
|
271
|
+
"command": _hook_command(
|
|
272
|
+
"hooks/userpromptsubmit_runner.py",
|
|
273
|
+
),
|
|
274
|
+
"timeout": 20,
|
|
275
|
+
}
|
|
276
|
+
]
|
|
277
|
+
}
|
|
278
|
+
],
|
|
279
|
+
})
|
|
280
|
+
if enable_subagent_hooks:
|
|
281
|
+
hooks.update({
|
|
282
|
+
"SubagentStart": [
|
|
283
|
+
{
|
|
284
|
+
"hooks": [
|
|
285
|
+
{
|
|
286
|
+
"type": "command",
|
|
287
|
+
# Not redirect_quiet: the sprawl nudge is emitted on
|
|
288
|
+
# stdout (only when the threshold is crossed; silent
|
|
289
|
+
# otherwise) so Codex can inject it as context.
|
|
290
|
+
"command": _hook_command(
|
|
291
|
+
"skills/token-optimizer/scripts/codex_hook_bridge.py",
|
|
292
|
+
"subagent-start",
|
|
293
|
+
),
|
|
294
|
+
"timeout": 6,
|
|
295
|
+
}
|
|
296
|
+
]
|
|
297
|
+
}
|
|
298
|
+
],
|
|
299
|
+
"SubagentStop": [
|
|
300
|
+
{
|
|
301
|
+
"hooks": [
|
|
302
|
+
{
|
|
303
|
+
"type": "command",
|
|
304
|
+
"command": _hook_command(
|
|
305
|
+
"skills/token-optimizer/scripts/codex_hook_bridge.py",
|
|
306
|
+
"subagent-stop",
|
|
307
|
+
redirect_quiet=True,
|
|
308
|
+
),
|
|
309
|
+
"timeout": 6,
|
|
310
|
+
}
|
|
311
|
+
]
|
|
312
|
+
}
|
|
313
|
+
],
|
|
314
|
+
})
|
|
315
|
+
if enable_hot_path_hooks:
|
|
316
|
+
hooks["PostToolUse"] = [
|
|
317
|
+
{
|
|
318
|
+
"matcher": "Bash",
|
|
319
|
+
"hooks": [
|
|
320
|
+
{
|
|
321
|
+
"type": "command",
|
|
322
|
+
# TOKEN_OPTIMIZER_NO_UPDATED_TOOL_OUTPUT gates off the
|
|
323
|
+
# updatedToolOutput emission in bash_compress_hook (Codex
|
|
324
|
+
# does not honor that field). thrash_guard recording and
|
|
325
|
+
# archive_result still run -- only the emission is skipped.
|
|
326
|
+
"command": _hook_command(
|
|
327
|
+
"hooks/posttooluse_runner.py",
|
|
328
|
+
redirect_quiet=True,
|
|
329
|
+
extra_env={"TOKEN_OPTIMIZER_NO_UPDATED_TOOL_OUTPUT": "1"},
|
|
330
|
+
),
|
|
331
|
+
"timeout": 10,
|
|
332
|
+
}
|
|
333
|
+
],
|
|
334
|
+
},
|
|
335
|
+
]
|
|
336
|
+
if enable_bash_compression:
|
|
337
|
+
hooks["PreToolUse"] = [
|
|
338
|
+
{
|
|
339
|
+
"matcher": "Bash",
|
|
340
|
+
"hooks": [
|
|
341
|
+
{
|
|
342
|
+
"type": "command",
|
|
343
|
+
"command": _hook_command(
|
|
344
|
+
"skills/token-optimizer/scripts/codex_command_compress.py",
|
|
345
|
+
"--quiet",
|
|
346
|
+
),
|
|
347
|
+
"timeout": 8,
|
|
348
|
+
}
|
|
349
|
+
],
|
|
350
|
+
}
|
|
351
|
+
]
|
|
352
|
+
return hooks
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _resolve_project(project: Path) -> Path:
|
|
356
|
+
try:
|
|
357
|
+
resolved = project.expanduser().resolve(strict=True)
|
|
358
|
+
except OSError as exc:
|
|
359
|
+
raise ValueError(f"project is not accessible: {project}") from exc
|
|
360
|
+
if not resolved.is_dir():
|
|
361
|
+
raise ValueError(f"project is not a directory: {resolved}")
|
|
362
|
+
return resolved
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _hooks_path(project: Path) -> Path:
|
|
366
|
+
project_root = _resolve_project(project)
|
|
367
|
+
codex_dir = project_root / ".codex"
|
|
368
|
+
if codex_dir.exists():
|
|
369
|
+
if codex_dir.is_symlink() or not codex_dir.is_dir():
|
|
370
|
+
raise ValueError(f"{codex_dir} must be a real directory, not a symlink or file")
|
|
371
|
+
try:
|
|
372
|
+
codex_resolved = codex_dir.resolve(strict=True)
|
|
373
|
+
except OSError as exc:
|
|
374
|
+
raise ValueError(f"{codex_dir} is not accessible") from exc
|
|
375
|
+
if not codex_resolved.is_relative_to(project_root):
|
|
376
|
+
raise ValueError(f"{codex_dir} escapes project root")
|
|
377
|
+
|
|
378
|
+
hooks_path = codex_dir / "hooks.json"
|
|
379
|
+
if hooks_path.exists() and hooks_path.is_symlink():
|
|
380
|
+
raise ValueError(f"{hooks_path} must not be a symlink")
|
|
381
|
+
try:
|
|
382
|
+
hooks_resolved = hooks_path.resolve(strict=hooks_path.exists())
|
|
383
|
+
except OSError as exc:
|
|
384
|
+
raise ValueError(f"{hooks_path} is not accessible") from exc
|
|
385
|
+
if not hooks_resolved.is_relative_to(project_root):
|
|
386
|
+
raise ValueError(f"{hooks_path} escapes project root")
|
|
387
|
+
return hooks_path
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _global_hooks_path(*, ensure_dir: bool = False) -> Path:
|
|
391
|
+
home = codex_home()
|
|
392
|
+
if home.exists() and home.is_symlink():
|
|
393
|
+
raise ValueError(f"{home} must not be a symlink")
|
|
394
|
+
if ensure_dir:
|
|
395
|
+
home.mkdir(parents=True, exist_ok=True)
|
|
396
|
+
hooks_path = home / "hooks.json"
|
|
397
|
+
if hooks_path.exists() and hooks_path.is_symlink():
|
|
398
|
+
resolved = hooks_path.resolve(strict=False)
|
|
399
|
+
user_home = Path.home().resolve(strict=True)
|
|
400
|
+
if not resolved.is_relative_to(user_home):
|
|
401
|
+
raise ValueError(f"{hooks_path} symlink target escapes user home")
|
|
402
|
+
return hooks_path
|
|
403
|
+
resolved = hooks_path.resolve(strict=False)
|
|
404
|
+
if not resolved.is_relative_to(Path.home()):
|
|
405
|
+
raise ValueError(f"{hooks_path} escapes user home")
|
|
406
|
+
return hooks_path
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _load_hooks(path: Path) -> dict[str, Any]:
|
|
410
|
+
try:
|
|
411
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
412
|
+
except FileNotFoundError:
|
|
413
|
+
return {"hooks": {}}
|
|
414
|
+
except json.JSONDecodeError as exc:
|
|
415
|
+
raise ValueError(f"{path} is not valid JSON: {exc}") from exc
|
|
416
|
+
if not isinstance(data, dict):
|
|
417
|
+
raise ValueError(f"{path} must contain a JSON object")
|
|
418
|
+
hooks = data.setdefault("hooks", {})
|
|
419
|
+
if not isinstance(hooks, dict):
|
|
420
|
+
raise ValueError(f"{path} must contain a top-level hooks object")
|
|
421
|
+
return data
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
# Anchors for the generated Windows versioned-install command signature.
|
|
425
|
+
# _hook_command has emitted exactly two such shapes: the current one, which
|
|
426
|
+
# invokes the consolidated runner through the FOR variable
|
|
427
|
+
# ("{base}\%R\hooks\run.py"), and the pre-5.13.12 broken one, which invoked it
|
|
428
|
+
# through the delayed-expansion var ("!TOKEN_OPTIMIZER_RUNTIME_ROOT!\hooks\
|
|
429
|
+
# run.py"). Both always carry the quoted set-assignment AND a hooks\run.py
|
|
430
|
+
# runner invocation rooted under a token-optimizer directory (or through one
|
|
431
|
+
# of OUR OWN variables, which a foreign command cannot use). Matching on the
|
|
432
|
+
# assignment alone silently deletes a user's own hook that merely references
|
|
433
|
+
# our env var, so all anchors must hold TOGETHER. (The patterns run on the
|
|
434
|
+
# JSON-serialized group, where a literal " arrives as \" and \ as \\, hence
|
|
435
|
+
# the escaped-quote and separator-class spellings.)
|
|
436
|
+
_WIN_ROOT_SET_RE = re.compile(r'set \\"TOKEN_OPTIMIZER_RUNTIME_ROOT=')
|
|
437
|
+
_WIN_RUNNER_RE = re.compile(r'hooks[/\\]+run\.py')
|
|
438
|
+
_WIN_TO_DIR_RE = re.compile(r'token-optimizer[/\\]')
|
|
439
|
+
_WIN_RUNNER_VIA_VAR_RE = re.compile(
|
|
440
|
+
r'(?:!TOKEN_OPTIMIZER_RUNTIME_ROOT!|%R)[/\\]+hooks[/\\]+run\.py'
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _is_token_optimizer_group(group: Any) -> bool:
|
|
445
|
+
# The path marker misses generated Windows commands: on versioned
|
|
446
|
+
# marketplace installs the baked paths use backslashes
|
|
447
|
+
# (...\token-optimizer\X.Y.Z\hooks\run.py) and consolidated-runner args
|
|
448
|
+
# like hooks/stop_runner.py, so "token-optimizer/scripts" never appears
|
|
449
|
+
# in them. Those commands are instead identified by their full generated
|
|
450
|
+
# signature, so a foreign hook that merely contains
|
|
451
|
+
# set "TOKEN_OPTIMIZER_RUNTIME_ROOT= (or %TOKEN_OPTIMIZER_RUNTIME_ROOT%,
|
|
452
|
+
# or a POSIX-style VAR=x prefix) is never swept up by reinstall/uninstall.
|
|
453
|
+
serialized = json.dumps(group, sort_keys=True)
|
|
454
|
+
if TOKEN_OPTIMIZER_MARKER in serialized:
|
|
455
|
+
return True
|
|
456
|
+
if not _WIN_ROOT_SET_RE.search(serialized):
|
|
457
|
+
return False
|
|
458
|
+
return (
|
|
459
|
+
_WIN_RUNNER_VIA_VAR_RE.search(serialized) is not None
|
|
460
|
+
or (
|
|
461
|
+
_WIN_RUNNER_RE.search(serialized) is not None
|
|
462
|
+
and _WIN_TO_DIR_RE.search(serialized) is not None
|
|
463
|
+
)
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
# Matches the --baked-root token of a generated launcher-file command, as
|
|
468
|
+
# list2cmdline emitted it: quoted when the path carries spaces or cmd
|
|
469
|
+
# metacharacters, bare otherwise.
|
|
470
|
+
_BAKED_ROOT_ARG_RE = re.compile(
|
|
471
|
+
r'--baked-root\s+(?:"(?P<quoted>[^"]*)"|(?P<bare>[^\s]+))'
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _normalize_baked_root(match: "re.Match[str]") -> str:
|
|
476
|
+
"""Replace a semver --baked-root leaf with the signature sentinel,
|
|
477
|
+
preserving the original separator style and quoting."""
|
|
478
|
+
value = match.group("quoted")
|
|
479
|
+
quoted = value is not None
|
|
480
|
+
if not quoted:
|
|
481
|
+
value = match.group("bare")
|
|
482
|
+
leaf = re.search(r"^(.*[/\\])\d+\.\d+\.\d+$", value)
|
|
483
|
+
if leaf is None:
|
|
484
|
+
return match.group(0)
|
|
485
|
+
normalized = f"--baked-root {leaf.group(1)}{_SIGNATURE_VERSION}"
|
|
486
|
+
return f'--baked-root "{leaf.group(1)}{_SIGNATURE_VERSION}"' if quoted else normalized
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _launcher_signature(command):
|
|
490
|
+
"""Canonical form of a generated Windows launcher, modulo the version dir.
|
|
491
|
+
|
|
492
|
+
Preserving an equivalent installed command avoids an unnecessary trust
|
|
493
|
+
review on upgrade. Launcher-file shape: the only versioned path in the
|
|
494
|
+
command is the --baked-root fallback (the launcher itself lives at the
|
|
495
|
+
stable parent of the version dirs), so normalize just that leaf to a
|
|
496
|
+
sentinel. Everything else -- interpreter, launcher path, env, script,
|
|
497
|
+
args, redirect, marker -- must match verbatim, so any tampering forces
|
|
498
|
+
the trust review it should. Legacy base64 launchers compare verbatim:
|
|
499
|
+
they are never equivalent to the launcher-file shape, so the next
|
|
500
|
+
install replaces them (the one-time change that ships the issue #183
|
|
501
|
+
fix), and a blob tampered in any way differs from the untampered
|
|
502
|
+
command.
|
|
503
|
+
"""
|
|
504
|
+
if _LAUNCHER_MARKER not in command:
|
|
505
|
+
return command
|
|
506
|
+
if _LAUNCHER_B64_RE.search(command):
|
|
507
|
+
return command
|
|
508
|
+
return _BAKED_ROOT_ARG_RE.sub(_normalize_baked_root, command)
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def _merge_hooks(
|
|
512
|
+
existing: dict[str, Any],
|
|
513
|
+
*,
|
|
514
|
+
enable_bash_compression: bool = False,
|
|
515
|
+
enable_hot_path_hooks: bool = False,
|
|
516
|
+
enable_prompt_hooks: bool = False,
|
|
517
|
+
enable_subagent_hooks: bool = False,
|
|
518
|
+
) -> dict[str, Any]:
|
|
519
|
+
result = json.loads(json.dumps(existing))
|
|
520
|
+
hooks = result.setdefault("hooks", {})
|
|
521
|
+
managed = _managed_hooks(
|
|
522
|
+
enable_bash_compression=enable_bash_compression,
|
|
523
|
+
enable_hot_path_hooks=enable_hot_path_hooks,
|
|
524
|
+
enable_prompt_hooks=enable_prompt_hooks,
|
|
525
|
+
enable_subagent_hooks=enable_subagent_hooks,
|
|
526
|
+
)
|
|
527
|
+
for event in SUPPORTED_EVENTS:
|
|
528
|
+
groups = hooks.get(event, [])
|
|
529
|
+
if not isinstance(groups, list):
|
|
530
|
+
groups = []
|
|
531
|
+
for fresh_group in managed.get(event, []):
|
|
532
|
+
for old_group in groups:
|
|
533
|
+
if not _is_token_optimizer_group(old_group):
|
|
534
|
+
continue
|
|
535
|
+
old_handlers = old_group.get('hooks', [])
|
|
536
|
+
fresh_handlers = fresh_group.get('hooks', [])
|
|
537
|
+
if len(old_handlers) == len(fresh_handlers) == 1:
|
|
538
|
+
old_handler, fresh_handler = old_handlers[0], fresh_handlers[0]
|
|
539
|
+
if _launcher_signature(old_handler.get('command', '')) == _launcher_signature(fresh_handler.get('command', '')):
|
|
540
|
+
fresh_handler['command'] = old_handler['command']
|
|
541
|
+
hooks[event] = [group for group in groups if not _is_token_optimizer_group(group)]
|
|
542
|
+
hooks[event].extend(managed.get(event, []))
|
|
543
|
+
if not hooks[event]:
|
|
544
|
+
hooks.pop(event, None)
|
|
545
|
+
return result
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def _remove_hooks(existing: dict[str, Any]) -> dict[str, Any]:
|
|
549
|
+
result = json.loads(json.dumps(existing))
|
|
550
|
+
hooks = result.setdefault("hooks", {})
|
|
551
|
+
for event, groups in list(hooks.items()):
|
|
552
|
+
if not isinstance(groups, list):
|
|
553
|
+
continue
|
|
554
|
+
kept = [group for group in groups if not _is_token_optimizer_group(group)]
|
|
555
|
+
if kept:
|
|
556
|
+
hooks[event] = kept
|
|
557
|
+
else:
|
|
558
|
+
hooks.pop(event, None)
|
|
559
|
+
return result
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _windows_launcher_install_path(root: Path) -> Path:
|
|
563
|
+
"""Stable launcher location: NEXT TO the versioned install dirs, so the
|
|
564
|
+
marketplace swapping .../token-optimizer/<X.Y.Z>/ on upgrade never takes
|
|
565
|
+
the file the baked commands invoke."""
|
|
566
|
+
return root.parent / _LAUNCHER_FILENAME
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def _install_windows_launcher(root: Path) -> str:
|
|
570
|
+
"""Copy the canonical hooks/windows-launcher.py to its stable install
|
|
571
|
+
path. Idempotent (no rewrite when already current) and atomic
|
|
572
|
+
(unique same-directory temp + replace, always cleaned up), so a
|
|
573
|
+
concurrent hook run never reads a half-written launcher."""
|
|
574
|
+
source = _repo_root() / "hooks" / _LAUNCHER_FILENAME
|
|
575
|
+
target = _windows_launcher_install_path(root)
|
|
576
|
+
try:
|
|
577
|
+
content = source.read_bytes()
|
|
578
|
+
except OSError as exc:
|
|
579
|
+
raise ValueError(f"cannot read Windows launcher {source}: {exc}") from exc
|
|
580
|
+
try:
|
|
581
|
+
if target.read_bytes() == content:
|
|
582
|
+
return f"already current: {target}"
|
|
583
|
+
except OSError:
|
|
584
|
+
pass
|
|
585
|
+
# Unique same-directory temp (concurrent installers never contend on a
|
|
586
|
+
# fixed name), always cleaned up; os.replace within one filesystem is
|
|
587
|
+
# atomic, so a concurrent hook run never reads a half-written launcher.
|
|
588
|
+
tmp = None
|
|
589
|
+
try:
|
|
590
|
+
with tempfile.NamedTemporaryFile(
|
|
591
|
+
dir=target.parent, prefix=f"{target.name}.", suffix=".tmp",
|
|
592
|
+
delete=False,
|
|
593
|
+
) as handle:
|
|
594
|
+
tmp = Path(handle.name)
|
|
595
|
+
handle.write(content)
|
|
596
|
+
os.replace(tmp, target)
|
|
597
|
+
except OSError as exc:
|
|
598
|
+
raise ValueError(
|
|
599
|
+
f"cannot install Windows launcher to {target}: {exc}"
|
|
600
|
+
) from exc
|
|
601
|
+
finally:
|
|
602
|
+
if tmp is not None:
|
|
603
|
+
try:
|
|
604
|
+
tmp.unlink(missing_ok=True)
|
|
605
|
+
except OSError:
|
|
606
|
+
pass
|
|
607
|
+
return f"installed: {target}"
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def install(
|
|
611
|
+
project: Path,
|
|
612
|
+
*,
|
|
613
|
+
is_global: bool = False,
|
|
614
|
+
dry_run: bool = False,
|
|
615
|
+
skip_compact_prompt: bool = False,
|
|
616
|
+
force_compact_prompt: bool = False,
|
|
617
|
+
enable_bash_compression: bool = False,
|
|
618
|
+
enable_hot_path_hooks: bool = False,
|
|
619
|
+
enable_prompt_hooks: bool = False,
|
|
620
|
+
enable_subagent_hooks: bool = False,
|
|
621
|
+
enable_status_line: bool = False,
|
|
622
|
+
force_status_line: bool = False,
|
|
623
|
+
) -> tuple[Path, str, dict[str, Any]]:
|
|
624
|
+
path = _global_hooks_path(ensure_dir=not dry_run) if is_global else _hooks_path(project)
|
|
625
|
+
existing = _load_hooks(path)
|
|
626
|
+
updated = _merge_hooks(
|
|
627
|
+
existing,
|
|
628
|
+
enable_bash_compression=enable_bash_compression,
|
|
629
|
+
enable_hot_path_hooks=enable_hot_path_hooks,
|
|
630
|
+
enable_prompt_hooks=enable_prompt_hooks,
|
|
631
|
+
enable_subagent_hooks=enable_subagent_hooks,
|
|
632
|
+
)
|
|
633
|
+
details: dict[str, Any] = {
|
|
634
|
+
"hook_events": sorted(updated.get("hooks", {}).keys()),
|
|
635
|
+
"bash_compression": enable_bash_compression,
|
|
636
|
+
"hot_path_hooks": enable_hot_path_hooks,
|
|
637
|
+
"prompt_hooks": enable_prompt_hooks,
|
|
638
|
+
"subagent_hooks": enable_subagent_hooks,
|
|
639
|
+
"compact_prompt": "skipped" if skip_compact_prompt else None,
|
|
640
|
+
"status_line": "skipped" if not enable_status_line else None,
|
|
641
|
+
}
|
|
642
|
+
root = _repo_root()
|
|
643
|
+
if sys.platform == "win32" and _SEMVER_DIR_RE.match(root.name):
|
|
644
|
+
# The baked commands invoke the launcher by path; it must exist
|
|
645
|
+
# before hooks.json points at it. A failed write aborts the install
|
|
646
|
+
# loudly instead of leaving hooks that cannot start.
|
|
647
|
+
details["windows_launcher"] = (
|
|
648
|
+
f"would install: {_windows_launcher_install_path(root)}"
|
|
649
|
+
if dry_run
|
|
650
|
+
else _install_windows_launcher(root)
|
|
651
|
+
)
|
|
652
|
+
if dry_run and not skip_compact_prompt:
|
|
653
|
+
details["compact_prompt"] = codex_compact_prompt.plan_install(force=force_compact_prompt)
|
|
654
|
+
if dry_run and enable_status_line:
|
|
655
|
+
details["status_line"] = codex_statusline.plan_install(force=force_status_line)
|
|
656
|
+
if not dry_run:
|
|
657
|
+
if not skip_compact_prompt:
|
|
658
|
+
details["compact_prompt"] = codex_compact_prompt.install(force=force_compact_prompt)
|
|
659
|
+
if enable_status_line:
|
|
660
|
+
details["status_line"] = codex_statusline.install(force=force_status_line)
|
|
661
|
+
codex_io.atomic_write_json(path, updated)
|
|
662
|
+
return path, "installed", details
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def uninstall(project: Path, *, is_global: bool = False, dry_run: bool = False) -> tuple[Path, str, dict[str, Any]]:
|
|
666
|
+
path = _global_hooks_path() if is_global else _hooks_path(project)
|
|
667
|
+
existing = _load_hooks(path)
|
|
668
|
+
updated = _remove_hooks(existing)
|
|
669
|
+
details: dict[str, Any] = {"hook_events": sorted(updated.get("hooks", {}).keys())}
|
|
670
|
+
# Reverse the config.toml writes the installer made: the compact-prompt
|
|
671
|
+
# managed block + prompt file and the [tui]
|
|
672
|
+
# status-line managed block. Both are idempotent and scoped to TO's own
|
|
673
|
+
# managed markers, so user-authored keys are never clobbered.
|
|
674
|
+
if dry_run:
|
|
675
|
+
details["compact_prompt"] = codex_compact_prompt.plan_uninstall()
|
|
676
|
+
details["status_line"] = codex_statusline.plan_uninstall()
|
|
677
|
+
else:
|
|
678
|
+
details["compact_prompt"] = codex_compact_prompt.uninstall()
|
|
679
|
+
details["status_line"] = codex_statusline.uninstall()
|
|
680
|
+
codex_io.atomic_write_json(path, updated)
|
|
681
|
+
return path, "removed", details
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
685
|
+
parser = argparse.ArgumentParser(description="Install Token Optimizer hooks for Codex (globally by default).")
|
|
686
|
+
target = parser.add_mutually_exclusive_group()
|
|
687
|
+
target.add_argument("--global", dest="use_global", action="store_true", default=True, help="Install hooks globally to ~/.codex/hooks.json (default)")
|
|
688
|
+
target.add_argument("--project", default=None, help="Install hooks to a specific project directory instead of globally")
|
|
689
|
+
parser.add_argument("--dry-run", action="store_true", help="Validate and print intended action without writing")
|
|
690
|
+
parser.add_argument("--uninstall", action="store_true", help="Remove Token Optimizer hooks")
|
|
691
|
+
parser.add_argument(
|
|
692
|
+
"--decode-launcher",
|
|
693
|
+
metavar="COMMAND",
|
|
694
|
+
default=None,
|
|
695
|
+
help=(
|
|
696
|
+
"Print the decoded Python bootstrap embedded in a LEGACY generated "
|
|
697
|
+
"Windows launcher command (the base64 `python -c` exec-bootstrap retired "
|
|
698
|
+
"for issue #183). Audit/diagnostic only: decodes and prints, "
|
|
699
|
+
"never executes. Launcher-file commands are self-auditing: the "
|
|
700
|
+
"invoked .py is plain source at the path in the command."
|
|
701
|
+
),
|
|
702
|
+
)
|
|
703
|
+
parser.add_argument(
|
|
704
|
+
"--profile",
|
|
705
|
+
choices=("quiet", "balanced", "telemetry", "aggressive"),
|
|
706
|
+
default="aggressive",
|
|
707
|
+
help=(
|
|
708
|
+
"Hook profile: aggressive=max savings, all silent hooks (default); "
|
|
709
|
+
"balanced=Stop+prompt hooks; quiet=Stop only; telemetry=Stop+PostToolUse. "
|
|
710
|
+
"Bash compression stays opt-in (--enable-bash-compression) on every profile "
|
|
711
|
+
"to preserve the user's existing command-output workflow."
|
|
712
|
+
),
|
|
713
|
+
)
|
|
714
|
+
parser.add_argument("--skip-compact-prompt", action="store_true", help="Do not install Codex compact prompt")
|
|
715
|
+
parser.add_argument("--force-compact-prompt", action="store_true", help="Replace existing compact-prompt settings")
|
|
716
|
+
parser.add_argument(
|
|
717
|
+
"--enable-bash-compression",
|
|
718
|
+
action="store_true",
|
|
719
|
+
help="Compress eligible inspection commands through Codex updatedInput; preserves full originals and failures",
|
|
720
|
+
)
|
|
721
|
+
parser.add_argument("--disable-bash-compression", action="store_true", help="Deprecated no-op; Bash compression is off by default")
|
|
722
|
+
parser.add_argument("--enable-hot-path-hooks", action="store_true", help="Opt into visible PostToolUse tool-output hooks")
|
|
723
|
+
parser.add_argument(
|
|
724
|
+
"--enable-prompt-hooks",
|
|
725
|
+
action="store_true",
|
|
726
|
+
help="Add visible SessionStart/UserPromptSubmit hooks when using --profile quiet; balanced already includes them",
|
|
727
|
+
)
|
|
728
|
+
parser.add_argument(
|
|
729
|
+
"--enable-subagent-hooks",
|
|
730
|
+
action="store_true",
|
|
731
|
+
help="Add SubagentStart/SubagentStop hooks for real-time subagent sprawl nudges when using --profile quiet; balanced/aggressive include them",
|
|
732
|
+
)
|
|
733
|
+
parser.add_argument(
|
|
734
|
+
"--no-subagent-hooks",
|
|
735
|
+
action="store_true",
|
|
736
|
+
help="Install without SubagentStart/SubagentStop hooks even on balanced/aggressive profiles",
|
|
737
|
+
)
|
|
738
|
+
parser.add_argument("--enable-status-line", action="store_true", help="Opt into Codex CLI context/status visibility")
|
|
739
|
+
parser.add_argument("--force-status-line", action="store_true", help="Replace existing Codex [tui] status_line settings")
|
|
740
|
+
parser.add_argument("--json", action="store_true", help="Emit machine-readable output")
|
|
741
|
+
return parser
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
def main(argv: list[str] | None = None) -> int:
|
|
745
|
+
args = build_parser().parse_args(argv)
|
|
746
|
+
if args.decode_launcher is not None:
|
|
747
|
+
decoded = decode_launcher_command(args.decode_launcher)
|
|
748
|
+
if decoded is None:
|
|
749
|
+
if _LAUNCHER_MARKER in args.decode_launcher:
|
|
750
|
+
# Launcher-file shape: the invoked .py IS the audit trail.
|
|
751
|
+
print(
|
|
752
|
+
"[Token Optimizer] launcher-file command: nothing embedded "
|
|
753
|
+
"to decode -- audit the plain source at the invoked "
|
|
754
|
+
f"{_LAUNCHER_FILENAME} path"
|
|
755
|
+
)
|
|
756
|
+
return 0
|
|
757
|
+
print("[Token Optimizer] not a generated windows-launcher command", file=sys.stderr)
|
|
758
|
+
return 1
|
|
759
|
+
print(decoded, end="")
|
|
760
|
+
return 0
|
|
761
|
+
is_global = args.project is None
|
|
762
|
+
try:
|
|
763
|
+
project = Path(".") if is_global else _resolve_project(Path(args.project))
|
|
764
|
+
if args.uninstall:
|
|
765
|
+
path, action, details = uninstall(project, is_global=is_global, dry_run=args.dry_run)
|
|
766
|
+
else:
|
|
767
|
+
enable_prompt_hooks = args.enable_prompt_hooks or args.profile in {"balanced", "aggressive"}
|
|
768
|
+
enable_hot_path_hooks = args.enable_hot_path_hooks or args.profile in {"telemetry", "aggressive"}
|
|
769
|
+
# Command rewriting is supported by current Codex. Keep its activation
|
|
770
|
+
# explicit because it changes the model-visible output of commands.
|
|
771
|
+
enable_bash_compression = args.enable_bash_compression
|
|
772
|
+
enable_subagent_hooks = (
|
|
773
|
+
args.enable_subagent_hooks or args.profile in {"balanced", "aggressive"}
|
|
774
|
+
) and not args.no_subagent_hooks
|
|
775
|
+
path, action, details = install(
|
|
776
|
+
project,
|
|
777
|
+
is_global=is_global,
|
|
778
|
+
dry_run=args.dry_run,
|
|
779
|
+
skip_compact_prompt=args.skip_compact_prompt,
|
|
780
|
+
force_compact_prompt=args.force_compact_prompt,
|
|
781
|
+
enable_bash_compression=enable_bash_compression,
|
|
782
|
+
enable_hot_path_hooks=enable_hot_path_hooks,
|
|
783
|
+
enable_prompt_hooks=enable_prompt_hooks,
|
|
784
|
+
enable_subagent_hooks=enable_subagent_hooks,
|
|
785
|
+
enable_status_line=args.enable_status_line,
|
|
786
|
+
force_status_line=args.force_status_line,
|
|
787
|
+
)
|
|
788
|
+
details["profile"] = args.profile
|
|
789
|
+
except ValueError as exc:
|
|
790
|
+
print(f"[Token Optimizer] {exc}", file=sys.stderr)
|
|
791
|
+
return 1
|
|
792
|
+
|
|
793
|
+
target = "global" if is_global else str(project)
|
|
794
|
+
payload = {
|
|
795
|
+
"action": action,
|
|
796
|
+
"target": target,
|
|
797
|
+
"hooks_path": str(path),
|
|
798
|
+
"dry_run": args.dry_run,
|
|
799
|
+
"details": details,
|
|
800
|
+
}
|
|
801
|
+
if args.json:
|
|
802
|
+
print(json.dumps(payload, indent=2))
|
|
803
|
+
else:
|
|
804
|
+
prefix = "Would update" if args.dry_run else "Updated"
|
|
805
|
+
print(f"[Token Optimizer] {prefix} {path} ({action})")
|
|
806
|
+
return 0
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
if __name__ == "__main__":
|
|
810
|
+
raise SystemExit(main())
|