@alexgreensh/token-optimizer 5.13.56 → 5.13.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/package.json +1 -1
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +93 -9
- package/skills/token-optimizer/scripts/codex_doctor.py +57 -16
- package/skills/token-optimizer/scripts/codex_install.py +72 -0
- package/skills/token-optimizer/scripts/measure.py +140 -6
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"name": "token-optimizer",
|
|
14
14
|
"source": "./",
|
|
15
15
|
"description": "Audit, fix, and monitor Claude Code context window usage. Find the ghost tokens.",
|
|
16
|
-
"version": "5.13.
|
|
16
|
+
"version": "5.13.57",
|
|
17
17
|
"author": {
|
|
18
18
|
"name": "Alex Greenshpun",
|
|
19
19
|
"url": "https://linkedin.com/in/alexgreensh"
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"name": "token-optimizer-cowork",
|
|
56
56
|
"source": "./cowork/token-optimizer",
|
|
57
57
|
"description": "Token Optimizer for Claude Cowork \u2014 full skills + Cowork-native hooks (beta). Install THIS in Cowork; the standard token-optimizer entry is for desktop Claude Code.",
|
|
58
|
-
"version": "5.13.
|
|
58
|
+
"version": "5.13.57",
|
|
59
59
|
"author": {
|
|
60
60
|
"name": "Alex Greenshpun",
|
|
61
61
|
"url": "https://linkedin.com/in/alexgreensh"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexgreensh/token-optimizer",
|
|
3
|
-
"version": "5.13.
|
|
3
|
+
"version": "5.13.57",
|
|
4
4
|
"description": "Token Optimizer for Claude Code cloud sessions: the real plugin, installed by your cloud environment's setup script.",
|
|
5
5
|
"license": "PolyForm-Noncommercial-1.0.0",
|
|
6
6
|
"author": "Alex Greenshpun (https://linkedin.com/in/alexgreensh)",
|
|
@@ -93,13 +93,62 @@ def _comment_out_setting(pattern: re.Pattern[str], text: str) -> str:
|
|
|
93
93
|
return pattern.sub(r"\1# replaced by Token Optimizer: \2\3", text)
|
|
94
94
|
|
|
95
95
|
|
|
96
|
+
# A TOML table header line: [name] or [[name]], optionally followed by a
|
|
97
|
+
# comment. Candidates only: a line inside a multi-line array can look the same,
|
|
98
|
+
# so _insert_at_root confirms the placement with a real TOML parser when one
|
|
99
|
+
# is available.
|
|
100
|
+
_TABLE_HEADER_RE = re.compile(r"(?m)^[ \t]*\[\[?[^\[\]\n]+\]\]?[ \t]*(?:#.*)?$")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _toml_root_value(config_text: str):
|
|
104
|
+
"""Return (state, root value of the setting). state is "ok", "invalid"
|
|
105
|
+
(the text does not parse) or "unavailable" (no TOML parser, Python < 3.11)."""
|
|
106
|
+
try:
|
|
107
|
+
import tomllib # Python 3.11+
|
|
108
|
+
except ImportError:
|
|
109
|
+
return "unavailable", None
|
|
110
|
+
try:
|
|
111
|
+
data = tomllib.loads(config_text)
|
|
112
|
+
except Exception:
|
|
113
|
+
return "invalid", None
|
|
114
|
+
return "ok", data.get("experimental_compact_prompt_file")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _insert_at_root(config_text: str, block: str, prompt_path: Path) -> str:
|
|
118
|
+
"""Place the managed block at the TOML root, before the first table.
|
|
119
|
+
|
|
120
|
+
Appending at end of file put the key inside whatever table came last
|
|
121
|
+
(issue #276: it landed in a [projects.'...'] table and Codex never saw
|
|
122
|
+
it). The blank-line separator mirrors _MANAGED_BLOCK_RE so uninstall
|
|
123
|
+
stays byte-faithful.
|
|
124
|
+
"""
|
|
125
|
+
# Without a parser, or when the user's file does not parse to begin with,
|
|
126
|
+
# trust the first header-looking line. Otherwise keep only a placement the
|
|
127
|
+
# parser confirms puts the key at the root.
|
|
128
|
+
verify = _toml_root_value(config_text)[0] == "ok"
|
|
129
|
+
candidates = [m.start() for m in _TABLE_HEADER_RE.finditer(config_text)]
|
|
130
|
+
for pos in candidates:
|
|
131
|
+
if pos == 0:
|
|
132
|
+
updated = block + config_text
|
|
133
|
+
else:
|
|
134
|
+
updated = config_text[:pos] + block + "\n" + config_text[pos:]
|
|
135
|
+
if not verify:
|
|
136
|
+
return updated
|
|
137
|
+
state, value = _toml_root_value(updated)
|
|
138
|
+
if state == "ok" and value == str(prompt_path):
|
|
139
|
+
return updated
|
|
140
|
+
suffix = "" if not config_text or config_text.endswith("\n") else "\n"
|
|
141
|
+
return config_text + suffix + "\n" + block
|
|
142
|
+
|
|
143
|
+
|
|
96
144
|
def _replace_or_append_config(config_text: str, prompt_path: Path, *, force: bool) -> tuple[str, str]:
|
|
97
145
|
block = _managed_block(prompt_path)
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
146
|
+
stripped, had_block = _strip_managed_block(config_text)
|
|
147
|
+
if had_block:
|
|
148
|
+
# Re-insert rather than replace in place, so a block an older version
|
|
149
|
+
# appended under a table moves back to the root. A block already at
|
|
150
|
+
# the root lands in the same spot, so this is a no-op for it.
|
|
151
|
+
return _insert_at_root(stripped, block, prompt_path), "updated"
|
|
103
152
|
|
|
104
153
|
if COMPACT_FILE_RE.search(config_text) and not force:
|
|
105
154
|
raise ValueError("config.toml already has experimental_compact_prompt_file; rerun with --force to replace")
|
|
@@ -110,8 +159,40 @@ def _replace_or_append_config(config_text: str, prompt_path: Path, *, force: boo
|
|
|
110
159
|
if INLINE_COMPACT_RE.search(config_text):
|
|
111
160
|
config_text = _comment_out_setting(INLINE_COMPACT_LINE_RE, config_text)
|
|
112
161
|
|
|
113
|
-
|
|
114
|
-
|
|
162
|
+
return _insert_at_root(config_text, block, prompt_path), "installed"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def configured_prompt_state(config_text: str, prompt_path: Path) -> str:
|
|
166
|
+
"""Classify the compact-prompt setting: "ours", "misplaced", "custom", or "none".
|
|
167
|
+
|
|
168
|
+
Compares the decoded path, not raw text: TOML stores Windows backslashes
|
|
169
|
+
escaped, so str(prompt_path) never appears verbatim in the file there.
|
|
170
|
+
"""
|
|
171
|
+
state, value = _toml_root_value(config_text)
|
|
172
|
+
has_block = bool(_MANAGED_BLOCK_RE.search(config_text))
|
|
173
|
+
if state == "ok":
|
|
174
|
+
if value is not None:
|
|
175
|
+
return "ours" if str(value) == str(prompt_path) else "custom"
|
|
176
|
+
if has_block:
|
|
177
|
+
return "misplaced"
|
|
178
|
+
else:
|
|
179
|
+
match = re.search(
|
|
180
|
+
rf"(?ms)^{re.escape(MANAGED_BEGIN)}\s*^\s*experimental_compact_prompt_file\s*=\s*(\"(?:[^\"\\\\]|\\\\.)*\")",
|
|
181
|
+
config_text,
|
|
182
|
+
)
|
|
183
|
+
if match:
|
|
184
|
+
try:
|
|
185
|
+
decoded = json.loads(match.group(1))
|
|
186
|
+
except ValueError:
|
|
187
|
+
decoded = None
|
|
188
|
+
if decoded == str(prompt_path):
|
|
189
|
+
header = _TABLE_HEADER_RE.search(config_text)
|
|
190
|
+
if header is not None and header.start() < match.start():
|
|
191
|
+
return "misplaced"
|
|
192
|
+
return "ours"
|
|
193
|
+
if "compact_prompt" in config_text or "experimental_compact_prompt_file" in config_text:
|
|
194
|
+
return "custom"
|
|
195
|
+
return "none"
|
|
115
196
|
|
|
116
197
|
|
|
117
198
|
def plan_install(force: bool = False) -> dict[str, str | bool]:
|
|
@@ -237,9 +318,12 @@ def status() -> str:
|
|
|
237
318
|
text = config_path.read_text(encoding="utf-8")
|
|
238
319
|
except (OSError, UnicodeDecodeError):
|
|
239
320
|
return f"not configured: {config_path} unreadable"
|
|
240
|
-
|
|
321
|
+
state = configured_prompt_state(text, prompt_path)
|
|
322
|
+
if state == "ours" and prompt_path.exists():
|
|
241
323
|
return f"configured: {prompt_path}"
|
|
242
|
-
if
|
|
324
|
+
if state == "misplaced":
|
|
325
|
+
return "misplaced: setting is inside a table; rerun measure.py codex-compact-prompt --install"
|
|
326
|
+
if state in ("ours", "custom"):
|
|
243
327
|
return "configured: custom compact prompt present"
|
|
244
328
|
return "not configured"
|
|
245
329
|
|
|
@@ -11,6 +11,8 @@ from pathlib import Path
|
|
|
11
11
|
from typing import Any
|
|
12
12
|
|
|
13
13
|
from runtime_env import codex_home, detect_runtime, runtime_home
|
|
14
|
+
import codex_compact_prompt
|
|
15
|
+
import codex_install
|
|
14
16
|
import codex_state
|
|
15
17
|
import codex_statusline
|
|
16
18
|
|
|
@@ -230,13 +232,30 @@ def _compact_prompt_check() -> dict[str, str]:
|
|
|
230
232
|
except UnicodeDecodeError:
|
|
231
233
|
return _check("FAIL", "Compact prompt", f"{config_path} is not valid UTF-8; run measure.py codex-compact-prompt --install")
|
|
232
234
|
expected = codex_home() / "token-optimizer" / "codex-compact-prompt.md"
|
|
233
|
-
|
|
235
|
+
state = codex_compact_prompt.configured_prompt_state(text, expected)
|
|
236
|
+
if state == "ours" and expected.exists():
|
|
234
237
|
return _check("OK", "Compact prompt", str(expected))
|
|
235
|
-
if
|
|
238
|
+
if state == "misplaced":
|
|
239
|
+
return _check("FAIL", "Compact prompt", "setting sits inside a table, so Codex ignores it; rerun measure.py codex-compact-prompt --install to move it")
|
|
240
|
+
if state in ("ours", "custom"):
|
|
236
241
|
return _check("WARN", "Compact prompt", "custom compact prompt configured")
|
|
237
242
|
return _check("FAIL", "Compact prompt", "not configured yet; run measure.py codex-compact-prompt --install")
|
|
238
243
|
|
|
239
244
|
|
|
245
|
+
def _stop_hook_activity_check() -> dict[str, str]:
|
|
246
|
+
"""Report the last Stop-hook refresh, so "registered" and "actually ran"
|
|
247
|
+
are no longer the same line (issue #276)."""
|
|
248
|
+
status_path = runtime_home() / "token-optimizer" / "hook-status.json"
|
|
249
|
+
data, error = _load_json(status_path)
|
|
250
|
+
entry = data.get("stop_flush") if isinstance(data, dict) else None
|
|
251
|
+
if error or not isinstance(entry, dict):
|
|
252
|
+
return _check("WARN", "Stop hook last run", "no run recorded yet; finish one Codex turn, then run the doctor again")
|
|
253
|
+
when = entry.get("at", "unknown time")
|
|
254
|
+
result = str(entry.get("result", "unknown"))
|
|
255
|
+
level = "WARN" if result.startswith("error") else "OK"
|
|
256
|
+
return _check(level, "Stop hook last run", f"{when}: {result}")
|
|
257
|
+
|
|
258
|
+
|
|
240
259
|
def _status_line_check() -> dict[str, str]:
|
|
241
260
|
try:
|
|
242
261
|
state = codex_statusline.status()
|
|
@@ -249,6 +268,16 @@ def _status_line_check() -> dict[str, str]:
|
|
|
249
268
|
return _check("WARN", "Codex CLI status line", "not configured; rerun codex-install with --enable-status-line")
|
|
250
269
|
|
|
251
270
|
|
|
271
|
+
def _has_our_hooks(data: dict[str, Any]) -> bool:
|
|
272
|
+
"""Same ownership test the installer uses. The consolidated runner hooks
|
|
273
|
+
carry no "token-optimizer/scripts" text on POSIX installs, so a substring
|
|
274
|
+
check called a working install "no Token Optimizer hooks"."""
|
|
275
|
+
for groups in data.get("hooks", {}).values():
|
|
276
|
+
if isinstance(groups, list) and any(codex_install._is_token_optimizer_group(g) for g in groups):
|
|
277
|
+
return True
|
|
278
|
+
return False
|
|
279
|
+
|
|
280
|
+
|
|
252
281
|
def _global_hook_check() -> dict[str, str]:
|
|
253
282
|
hooks_path = codex_home() / "hooks.json"
|
|
254
283
|
data, error = _load_json(hooks_path)
|
|
@@ -256,7 +285,7 @@ def _global_hook_check() -> dict[str, str]:
|
|
|
256
285
|
return _check("FAIL", "Global hooks", f"{hooks_path} not found; run measure.py codex-install")
|
|
257
286
|
if not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
|
|
258
287
|
return _check("FAIL", "Global hooks", f"{hooks_path} has no hooks object")
|
|
259
|
-
if
|
|
288
|
+
if _has_our_hooks(data):
|
|
260
289
|
return _check("OK", "Global hooks", str(hooks_path))
|
|
261
290
|
return _check("WARN", "Global hooks", f"no Token Optimizer hooks in {hooks_path}; run measure.py codex-install")
|
|
262
291
|
|
|
@@ -302,32 +331,42 @@ def _project_hook_check(project: Path) -> dict[str, str]:
|
|
|
302
331
|
return _check("WARN", "Project hooks", f"{hooks_path} not found; per-project hooks are optional when global hooks are installed")
|
|
303
332
|
if not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
|
|
304
333
|
return _check("FAIL", "Project hooks", f"{hooks_path} has no hooks object")
|
|
305
|
-
if
|
|
334
|
+
if _has_our_hooks(data):
|
|
306
335
|
return _check("OK", "Project hooks", str(hooks_path))
|
|
307
336
|
return _check("WARN", "Project hooks", f"no Token Optimizer hooks installed in {hooks_path}; manual refresh mode avoids visible Codex hook rows")
|
|
308
337
|
|
|
309
338
|
|
|
310
339
|
def _project_feature_checks(project: Path) -> list[dict[str, str]]:
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
340
|
+
# Features count from the global hooks file AND the project one: the
|
|
341
|
+
# default install is global, so a project-only view reported every
|
|
342
|
+
# feature as missing on a correctly installed machine.
|
|
343
|
+
hooks: dict[str, list] = {}
|
|
344
|
+
for hooks_path in (codex_home() / "hooks.json", project / ".codex" / "hooks.json"):
|
|
345
|
+
data, error = _load_json(hooks_path)
|
|
346
|
+
if error or not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
|
|
347
|
+
continue
|
|
348
|
+
for event, groups in data["hooks"].items():
|
|
349
|
+
if isinstance(groups, list):
|
|
350
|
+
hooks.setdefault(event, []).extend(groups)
|
|
351
|
+
if not hooks:
|
|
314
352
|
return []
|
|
315
353
|
|
|
316
|
-
hooks = data.get("hooks", {})
|
|
317
354
|
checks = []
|
|
318
|
-
if _has_project_hook(hooks, "PreToolUse", "Bash", "bash_hook.py"):
|
|
355
|
+
if _has_project_hook(hooks, "PreToolUse", "Bash", ("codex_command_compress.py", "bash_hook.py")):
|
|
319
356
|
checks.append(_check("OK", "Feature: Bash compression", "enabled for PreToolUse(Bash)"))
|
|
320
357
|
else:
|
|
321
358
|
checks.append(_check("OK", "Feature: Bash compression", "off by default to avoid visible Codex PreToolUse hook spam"))
|
|
322
359
|
|
|
323
360
|
required_features = (
|
|
324
|
-
|
|
361
|
+
# Current installs route through the consolidated runners; the older
|
|
362
|
+
# per-script names still count so a pre-runner install reads right.
|
|
363
|
+
("Session continuity and dashboard refresh", "Stop", None, ("stop_runner.py", "session-end-flush")),
|
|
325
364
|
)
|
|
326
365
|
optional_noisy_features = (
|
|
327
|
-
("Prompt quality nudges", "UserPromptSubmit", None, "codex_hook_bridge.py"),
|
|
328
|
-
("Subagent sprawl tracking", "SubagentStart", None, "subagent-start"),
|
|
329
|
-
("Tool output archive", "PostToolUse", "Bash", "archive_result.py"),
|
|
330
|
-
("Context intelligence", "PostToolUse", "Bash", "context_intel.py"),
|
|
366
|
+
("Prompt quality nudges", "UserPromptSubmit", None, ("userpromptsubmit_runner.py", "codex_hook_bridge.py")),
|
|
367
|
+
("Subagent sprawl tracking", "SubagentStart", None, ("subagent-start",)),
|
|
368
|
+
("Tool output archive", "PostToolUse", "Bash", ("posttooluse_runner.py", "archive_result.py")),
|
|
369
|
+
("Context intelligence", "PostToolUse", "Bash", ("posttooluse_runner.py", "context_intel.py")),
|
|
331
370
|
)
|
|
332
371
|
for feature, event, matcher, needle in required_features:
|
|
333
372
|
if _has_project_hook(hooks, event, matcher, needle):
|
|
@@ -354,7 +393,8 @@ def _project_feature_checks(project: Path) -> list[dict[str, str]]:
|
|
|
354
393
|
return checks
|
|
355
394
|
|
|
356
395
|
|
|
357
|
-
def _has_project_hook(hooks: dict[str, Any], event: str, matcher: str | None, command_needle
|
|
396
|
+
def _has_project_hook(hooks: dict[str, Any], event: str, matcher: str | None, command_needle) -> bool:
|
|
397
|
+
needles = (command_needle,) if isinstance(command_needle, str) else tuple(command_needle)
|
|
358
398
|
groups = hooks.get(event)
|
|
359
399
|
if not isinstance(groups, list):
|
|
360
400
|
return False
|
|
@@ -367,7 +407,7 @@ def _has_project_hook(hooks: dict[str, Any], event: str, matcher: str | None, co
|
|
|
367
407
|
if not isinstance(hook, dict) or hook.get("type") != "command":
|
|
368
408
|
continue
|
|
369
409
|
command = hook.get("command", "")
|
|
370
|
-
if isinstance(command, str) and
|
|
410
|
+
if isinstance(command, str) and any(n in command for n in needles):
|
|
371
411
|
return True
|
|
372
412
|
return False
|
|
373
413
|
|
|
@@ -415,6 +455,7 @@ def run_checks(project: Path | None = None) -> list[dict[str, str]]:
|
|
|
415
455
|
checks.append(_compact_prompt_check())
|
|
416
456
|
checks.append(_status_line_check())
|
|
417
457
|
checks.append(_global_hook_check())
|
|
458
|
+
checks.append(_stop_hook_activity_check())
|
|
418
459
|
checks.extend(_global_hook_config_checks())
|
|
419
460
|
checks.append(_project_hook_check(project))
|
|
420
461
|
checks.extend(_project_feature_checks(project))
|
|
@@ -56,6 +56,9 @@ _LAUNCHER_MARKER = "token-optimizer/scripts/windows-launcher"
|
|
|
56
56
|
# Filename of the readable launcher codex_install copies NEXT TO the
|
|
57
57
|
# versioned install dirs (issue #183); canonical source ships in hooks/.
|
|
58
58
|
_LAUNCHER_FILENAME = "windows-launcher.py"
|
|
59
|
+
# Unquoted first token for the Windows launcher command (see
|
|
60
|
+
# _windows_launcher_command for why the command must not start with a quote).
|
|
61
|
+
_WIN_UNQUOTED_PREFIX = 'set "TOKEN_OPTIMIZER_RUNTIME=codex" &&'
|
|
59
62
|
_LAUNCHER_B64_RE = re.compile(r"b64decode\('([A-Za-z0-9+/=]+)'\)")
|
|
60
63
|
# Sentinel version leaf used when normalizing a launcher for signature
|
|
61
64
|
# comparison (see _launcher_signature).
|
|
@@ -101,7 +104,16 @@ def _windows_launcher_command(root: Path, script: str, args, extra_env: dict) ->
|
|
|
101
104
|
dispatching, so the runner's sys.argv stays exactly [run.py, script,
|
|
102
105
|
*args].
|
|
103
106
|
"""
|
|
107
|
+
# The command must NOT start with a double quote. Codex hands it to
|
|
108
|
+
# cmd.exe as a raw /C string; when that string's first character is a
|
|
109
|
+
# quote, cmd strips the first and the LAST quote on the line (/S rules),
|
|
110
|
+
# which unpairs every quoted path ("The filename, directory name, or
|
|
111
|
+
# volume label syntax is incorrect", issue #276). A leading builtin keeps
|
|
112
|
+
# the line intact whether or not the host wraps it in an outer pair of
|
|
113
|
+
# quotes. The launcher sets this variable too; the prefix is only there
|
|
114
|
+
# to give cmd an unquoted first token.
|
|
104
115
|
parts = [
|
|
116
|
+
_WIN_UNQUOTED_PREFIX,
|
|
105
117
|
_cmd_quote(sys.executable),
|
|
106
118
|
_cmd_quote(str(root.parent / _LAUNCHER_FILENAME)),
|
|
107
119
|
"--baked-root",
|
|
@@ -441,6 +453,17 @@ _WIN_RUNNER_VIA_VAR_RE = re.compile(
|
|
|
441
453
|
)
|
|
442
454
|
|
|
443
455
|
|
|
456
|
+
# The consolidated runners (hooks/<event>_runner.py) carry no
|
|
457
|
+
# "token-optimizer/scripts" text on POSIX marketplace installs, so without this
|
|
458
|
+
# signature a reinstall appended a second copy of each runner hook and uninstall
|
|
459
|
+
# left them all behind. Ours = a runner name AND our hooks/run.py (or
|
|
460
|
+
# python-launcher.sh) AND a path under a token-optimizer folder, together.
|
|
461
|
+
_RUNNER_SCRIPT_RE = re.compile(
|
|
462
|
+
r'hooks[/\\]+(?:sessionstart|userpromptsubmit|posttooluse|stop)_runner\.py'
|
|
463
|
+
)
|
|
464
|
+
_RUNNER_ENTRY_RE = re.compile(r'hooks[/\\]+(?:run\.py|python-launcher\.sh)|\$\{R\}hooks/')
|
|
465
|
+
|
|
466
|
+
|
|
444
467
|
def _is_token_optimizer_group(group: Any) -> bool:
|
|
445
468
|
# The path marker misses generated Windows commands: on versioned
|
|
446
469
|
# marketplace installs the baked paths use backslashes
|
|
@@ -453,6 +476,12 @@ def _is_token_optimizer_group(group: Any) -> bool:
|
|
|
453
476
|
serialized = json.dumps(group, sort_keys=True)
|
|
454
477
|
if TOKEN_OPTIMIZER_MARKER in serialized:
|
|
455
478
|
return True
|
|
479
|
+
if (
|
|
480
|
+
_RUNNER_SCRIPT_RE.search(serialized)
|
|
481
|
+
and _RUNNER_ENTRY_RE.search(serialized)
|
|
482
|
+
and _WIN_TO_DIR_RE.search(serialized)
|
|
483
|
+
):
|
|
484
|
+
return True
|
|
456
485
|
if not _WIN_ROOT_SET_RE.search(serialized):
|
|
457
486
|
return False
|
|
458
487
|
return (
|
|
@@ -662,6 +691,49 @@ def install(
|
|
|
662
691
|
return path, "installed", details
|
|
663
692
|
|
|
664
693
|
|
|
694
|
+
def heal_quoted_launcher_commands(paths=None) -> int:
|
|
695
|
+
"""Repair Windows hook commands that start with a double quote.
|
|
696
|
+
|
|
697
|
+
Versions before 5.13.57 saved launcher commands that open with the quoted
|
|
698
|
+
python.exe path. cmd.exe strips that first quote and the last one, so the
|
|
699
|
+
hook fails before Python starts and can never repair itself (issue #276).
|
|
700
|
+
This rewrites only our own launcher commands, only that one way, and
|
|
701
|
+
returns how many it fixed. Never raises.
|
|
702
|
+
"""
|
|
703
|
+
if paths is None:
|
|
704
|
+
paths = []
|
|
705
|
+
try:
|
|
706
|
+
paths.append(_global_hooks_path())
|
|
707
|
+
except Exception:
|
|
708
|
+
pass
|
|
709
|
+
paths.append(Path.cwd() / ".codex" / "hooks.json")
|
|
710
|
+
fixed = 0
|
|
711
|
+
for path in paths:
|
|
712
|
+
try:
|
|
713
|
+
if not path.is_file():
|
|
714
|
+
continue
|
|
715
|
+
data = _load_hooks(path)
|
|
716
|
+
changed = 0
|
|
717
|
+
for groups in data.get("hooks", {}).values():
|
|
718
|
+
if not isinstance(groups, list):
|
|
719
|
+
continue
|
|
720
|
+
for group in groups:
|
|
721
|
+
if not _is_token_optimizer_group(group):
|
|
722
|
+
continue
|
|
723
|
+
for handler in group.get("hooks", []):
|
|
724
|
+
command = handler.get("command") if isinstance(handler, dict) else None
|
|
725
|
+
if (isinstance(command, str) and command.startswith('"')
|
|
726
|
+
and _LAUNCHER_MARKER in command):
|
|
727
|
+
handler["command"] = f"{_WIN_UNQUOTED_PREFIX} {command}"
|
|
728
|
+
changed += 1
|
|
729
|
+
if changed:
|
|
730
|
+
codex_io.atomic_write_json(path, data)
|
|
731
|
+
fixed += changed
|
|
732
|
+
except Exception:
|
|
733
|
+
continue
|
|
734
|
+
return fixed
|
|
735
|
+
|
|
736
|
+
|
|
665
737
|
def uninstall(project: Path, *, is_global: bool = False, dry_run: bool = False) -> tuple[Path, str, dict[str, Any]]:
|
|
666
738
|
path = _global_hooks_path() if is_global else _hooks_path(project)
|
|
667
739
|
existing = _load_hooks(path)
|
|
@@ -93,7 +93,7 @@ import types
|
|
|
93
93
|
import platform
|
|
94
94
|
import posixpath
|
|
95
95
|
import shutil
|
|
96
|
-
from collections import deque
|
|
96
|
+
from collections import Counter, deque
|
|
97
97
|
from contextlib import contextmanager, nullcontext
|
|
98
98
|
from datetime import datetime, timedelta, timezone
|
|
99
99
|
from pathlib import Path, PureWindowsPath
|
|
@@ -3566,6 +3566,7 @@ def _measure_codex_components():
|
|
|
3566
3566
|
"count": len(plugin_skills),
|
|
3567
3567
|
"tokens": sum(int(item.get("tokens", 0)) for item in plugin_skills),
|
|
3568
3568
|
"names": [item["name"] for item in plugin_skills],
|
|
3569
|
+
"per_plugin": dict(Counter(item.get("plugin") or "other" for item in plugin_skills)),
|
|
3569
3570
|
"plugins": _collect_codex_plugin_inventory(cfg),
|
|
3570
3571
|
"disabled_plugins": [p["name"] for p in _collect_codex_plugin_inventory(cfg) if not p.get("enabled", True)],
|
|
3571
3572
|
"duplicate_skills": {},
|
|
@@ -4118,6 +4119,31 @@ def _resolve_compact_window(model, env=None, settings=None):
|
|
|
4118
4119
|
if not isinstance(settings, dict):
|
|
4119
4120
|
settings = {}
|
|
4120
4121
|
|
|
4122
|
+
if detect_runtime() == "codex":
|
|
4123
|
+
# Codex: the Claude table and Claude's autocompact settings do not
|
|
4124
|
+
# apply. A GPT id fell through to the Claude 1M default, so a 475K
|
|
4125
|
+
# model reported a 967K compaction point (issue #276). Use Codex's
|
|
4126
|
+
# own catalog window, then the runtime's detected window.
|
|
4127
|
+
window = None
|
|
4128
|
+
try:
|
|
4129
|
+
import codex_models
|
|
4130
|
+
window = codex_models.effective_window(model) if model else None
|
|
4131
|
+
except Exception:
|
|
4132
|
+
window = None
|
|
4133
|
+
if not window:
|
|
4134
|
+
try:
|
|
4135
|
+
window = detect_context_window()[0]
|
|
4136
|
+
except Exception:
|
|
4137
|
+
window = None
|
|
4138
|
+
if window:
|
|
4139
|
+
return {
|
|
4140
|
+
"tokens": int(window),
|
|
4141
|
+
"source": f"Codex model window ({model or 'configured model'})",
|
|
4142
|
+
"user_override": False,
|
|
4143
|
+
"model_window": int(window),
|
|
4144
|
+
"default_tokens": int(window),
|
|
4145
|
+
}
|
|
4146
|
+
|
|
4121
4147
|
model_window = _context_window_for_model_str(model)
|
|
4122
4148
|
if not model_window:
|
|
4123
4149
|
try:
|
|
@@ -5749,8 +5775,13 @@ def print_snapshot_summary(snapshot):
|
|
|
5749
5775
|
name = plugin.get("name")
|
|
5750
5776
|
if name:
|
|
5751
5777
|
plugins.append(str(name))
|
|
5752
|
-
|
|
5753
|
-
|
|
5778
|
+
per_plugin = ps.get("per_plugin") or {}
|
|
5779
|
+
if per_plugin:
|
|
5780
|
+
plugin_label = ", ".join(f"{n} {name}" for name, n in sorted(per_plugin.items()))
|
|
5781
|
+
print(f" {'+ Plugin skills':<33s} {ps.get('tokens', 0):>6,} tokens [{ps.get('count', 0)}: {plugin_label}{suffix}]")
|
|
5782
|
+
else:
|
|
5783
|
+
plugin_label = ", ".join(plugins) if plugins else "plugins"
|
|
5784
|
+
print(f" {'+ Plugin skills':<33s} {ps.get('tokens', 0):>6,} tokens [{ps.get('count', 0)} from {plugin_label}{suffix}]")
|
|
5754
5785
|
dupes = ps.get("duplicate_skills", {})
|
|
5755
5786
|
if dupes:
|
|
5756
5787
|
dupe_count = sum(len(v) - 1 for v in dupes.values())
|
|
@@ -7462,11 +7493,40 @@ def _collect_codex_skill_inventory(cfg: dict, *, project: Path) -> dict[str, lis
|
|
|
7462
7493
|
return f"{parts[1]}@{parts[0]}"
|
|
7463
7494
|
return None
|
|
7464
7495
|
|
|
7496
|
+
# The cache keeps old versions after an upgrade, but Codex loads one
|
|
7497
|
+
# version per plugin. Counting every cached copy inflated the plugin
|
|
7498
|
+
# skill total several times over (issue #276).
|
|
7499
|
+
def _version_key(name: str):
|
|
7500
|
+
nums = re.findall(r"\d+", name)
|
|
7501
|
+
return tuple(int(n) for n in nums) if nums else (-1,)
|
|
7502
|
+
|
|
7503
|
+
newest_version: dict[tuple[str, str], str] = {}
|
|
7504
|
+
for path, source in candidates:
|
|
7505
|
+
if source != "plugin":
|
|
7506
|
+
continue
|
|
7507
|
+
try:
|
|
7508
|
+
rel = path.relative_to(plugin_cache)
|
|
7509
|
+
except ValueError:
|
|
7510
|
+
continue
|
|
7511
|
+
if len(rel.parts) >= 6 and rel.parts[-3] == "skills":
|
|
7512
|
+
key = (rel.parts[0], rel.parts[1])
|
|
7513
|
+
current = newest_version.get(key)
|
|
7514
|
+
if current is None or _version_key(rel.parts[2]) > _version_key(current):
|
|
7515
|
+
newest_version[key] = rel.parts[2]
|
|
7516
|
+
|
|
7465
7517
|
active = []
|
|
7466
7518
|
disabled = []
|
|
7467
7519
|
seen: set[str] = set()
|
|
7468
7520
|
mp_cmd = _shell_script_path()
|
|
7469
7521
|
for path, source in candidates:
|
|
7522
|
+
if source == "plugin":
|
|
7523
|
+
try:
|
|
7524
|
+
rel = path.relative_to(plugin_cache)
|
|
7525
|
+
except ValueError:
|
|
7526
|
+
rel = None
|
|
7527
|
+
if (rel is not None and len(rel.parts) >= 6 and rel.parts[-3] == "skills"
|
|
7528
|
+
and newest_version.get((rel.parts[0], rel.parts[1])) != rel.parts[2]):
|
|
7529
|
+
continue
|
|
7470
7530
|
resolved = str(path.expanduser().resolve(strict=False))
|
|
7471
7531
|
if resolved in seen:
|
|
7472
7532
|
continue
|
|
@@ -7483,6 +7543,8 @@ def _collect_codex_skill_inventory(cfg: dict, *, project: Path) -> dict[str, lis
|
|
|
7483
7543
|
"enable_cmd": f"{_runtime_cli('codex')} codex-skill enable --path {shlex.quote(resolved)}",
|
|
7484
7544
|
}
|
|
7485
7545
|
_pkey = _plugin_key_for(resolved)
|
|
7546
|
+
if _pkey is not None:
|
|
7547
|
+
item["plugin"] = _pkey
|
|
7486
7548
|
if resolved in disabled_paths or (_pkey is not None and _pkey in disabled_plugin_keys):
|
|
7487
7549
|
disabled.append(item)
|
|
7488
7550
|
else:
|
|
@@ -8672,6 +8734,32 @@ def _session_refresh_due(min_interval_seconds=120):
|
|
|
8672
8734
|
return True
|
|
8673
8735
|
|
|
8674
8736
|
|
|
8737
|
+
HOOK_STATUS_FILE = RUNTIME_DIR / "token-optimizer" / "hook-status.json"
|
|
8738
|
+
|
|
8739
|
+
|
|
8740
|
+
def _record_hook_status(key, result):
|
|
8741
|
+
"""Remember the last outcome of a background hook job, for the doctor.
|
|
8742
|
+
|
|
8743
|
+
The Stop hook's output goes to NUL and its runner always exits 0, so
|
|
8744
|
+
without this a user cannot tell "ran", "skipped on purpose" and "broke"
|
|
8745
|
+
apart (issue #276). Best effort: never raises.
|
|
8746
|
+
"""
|
|
8747
|
+
try:
|
|
8748
|
+
try:
|
|
8749
|
+
data = json.loads(HOOK_STATUS_FILE.read_text(encoding="utf-8"))
|
|
8750
|
+
if not isinstance(data, dict):
|
|
8751
|
+
data = {}
|
|
8752
|
+
except (OSError, ValueError):
|
|
8753
|
+
data = {}
|
|
8754
|
+
data[key] = {"at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "result": result}
|
|
8755
|
+
HOOK_STATUS_FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
8756
|
+
tmp = HOOK_STATUS_FILE.with_name(HOOK_STATUS_FILE.name + f".{os.getpid()}.tmp")
|
|
8757
|
+
tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
|
8758
|
+
os.replace(tmp, HOOK_STATUS_FILE)
|
|
8759
|
+
except Exception:
|
|
8760
|
+
pass
|
|
8761
|
+
|
|
8762
|
+
|
|
8675
8763
|
def _run_session_end_flush_worker(args, budget_seconds=20):
|
|
8676
8764
|
"""Run heavyweight Stop-hook work outside Codex's visible hook budget.
|
|
8677
8765
|
|
|
@@ -8680,11 +8768,17 @@ def _run_session_end_flush_worker(args, budget_seconds=20):
|
|
|
8680
8768
|
the hook timeout."""
|
|
8681
8769
|
lock_dir = _acquire_session_end_flush_lock()
|
|
8682
8770
|
if lock_dir is None:
|
|
8771
|
+
_record_hook_status("stop_flush", "skipped: another refresh was already running")
|
|
8683
8772
|
return
|
|
8684
8773
|
_lean = _remote_lean_profile()
|
|
8685
8774
|
old_budget = _install_hook_budget(budget_seconds)
|
|
8775
|
+
_flush_result = "error: stopped early"
|
|
8686
8776
|
try:
|
|
8687
|
-
if _session_refresh_due():
|
|
8777
|
+
if not _session_refresh_due():
|
|
8778
|
+
_flush_result = "skipped: last refresh and checkpoint were under 2 minutes ago"
|
|
8779
|
+
else:
|
|
8780
|
+
_flush_result = "ran"
|
|
8781
|
+
if _flush_result.startswith("ran"):
|
|
8688
8782
|
try:
|
|
8689
8783
|
# First-ever collection: DEEP backfill of all history still on disk
|
|
8690
8784
|
# (not just the rolling 90-day window), so a long-time user's baseline
|
|
@@ -8780,7 +8874,10 @@ def _run_session_end_flush_worker(args, budget_seconds=20):
|
|
|
8780
8874
|
except Exception:
|
|
8781
8875
|
pass
|
|
8782
8876
|
except _HookTimeout:
|
|
8783
|
-
|
|
8877
|
+
_flush_result = "timed out: refresh hit its time budget and resumes next turn"
|
|
8878
|
+
except Exception as exc:
|
|
8879
|
+
_flush_result = f"error: {type(exc).__name__}"
|
|
8880
|
+
raise
|
|
8784
8881
|
else:
|
|
8785
8882
|
# Flush work completed without a timeout. M-5: release the flush lock
|
|
8786
8883
|
# BEFORE running post-flush extensions, so a slow/hung extension does
|
|
@@ -8808,6 +8905,7 @@ def _run_session_end_flush_worker(args, budget_seconds=20):
|
|
|
8808
8905
|
if lock_dir is not None:
|
|
8809
8906
|
_release_session_end_flush_lock(lock_dir)
|
|
8810
8907
|
_clear_hook_budget(old_budget)
|
|
8908
|
+
_record_hook_status("stop_flush", _flush_result)
|
|
8811
8909
|
|
|
8812
8910
|
|
|
8813
8911
|
def _run_post_flush_extensions(time_left_fn=None, version="unknown"):
|
|
@@ -10048,7 +10146,8 @@ def generate_auto_recommendations(components, trends=None, days=30):
|
|
|
10048
10146
|
haiku_pct = model_mix.get("haiku", 0) / total_tokens * 100
|
|
10049
10147
|
if opus_pct > 50 and haiku_pct < 15:
|
|
10050
10148
|
# Root cause: hardcoded model in settings.json → split into Quick Win
|
|
10051
|
-
if default_model and "opus" in str(default_model).lower()
|
|
10149
|
+
if (default_model and "opus" in str(default_model).lower()
|
|
10150
|
+
and not _model_routing_handled_elsewhere()):
|
|
10052
10151
|
quick.append(
|
|
10053
10152
|
f"**Remove hardcoded model from settings.json (`\"model\": \"{default_model}\"`)**: "
|
|
10054
10153
|
f"This forces ALL operations to use {default_model}, overriding any CLAUDE.md routing. "
|
|
@@ -47627,6 +47726,28 @@ def _resolve_feature_env(env_var):
|
|
|
47627
47726
|
return _settings_env_value(env_var)
|
|
47628
47727
|
|
|
47629
47728
|
|
|
47729
|
+
def _model_routing_handled_elsewhere():
|
|
47730
|
+
"""True when subagent models are already routed outside settings.json.
|
|
47731
|
+
|
|
47732
|
+
A model-routing plugin sets the model per Agent call, so a pinned main
|
|
47733
|
+
model is a choice, not a leak, and "remove the model key" saves nothing
|
|
47734
|
+
(issue #275). Matches any enabled plugin with "router" in its name, plus
|
|
47735
|
+
an explicit opt-out for routing done some other way.
|
|
47736
|
+
"""
|
|
47737
|
+
if os.environ.get("TOKEN_OPTIMIZER_SKIP_MODEL_PIN_HINT", "").strip().lower() in ("1", "true", "yes"):
|
|
47738
|
+
return True
|
|
47739
|
+
try:
|
|
47740
|
+
plugins = _resolve_settings_value("enabledPlugins", {}) or {}
|
|
47741
|
+
except Exception:
|
|
47742
|
+
return False
|
|
47743
|
+
if not isinstance(plugins, dict):
|
|
47744
|
+
return False
|
|
47745
|
+
return any(
|
|
47746
|
+
enabled and "router" in str(name).split("@", 1)[0].lower()
|
|
47747
|
+
for name, enabled in plugins.items()
|
|
47748
|
+
)
|
|
47749
|
+
|
|
47750
|
+
|
|
47630
47751
|
def _resolve_settings_value(key, default=None):
|
|
47631
47752
|
"""Return a top-level settings.json key (e.g. includeGitInstructions, model)
|
|
47632
47753
|
resolving project local/shared over global local/shared, first match wins.
|
|
@@ -57153,6 +57274,19 @@ if __name__ == "__main__":
|
|
|
57153
57274
|
i += 1
|
|
57154
57275
|
args = _filtered_args
|
|
57155
57276
|
|
|
57277
|
+
# Windows Codex: hooks saved by older versions start with a quote, which
|
|
57278
|
+
# cmd.exe mangles, so they fail before reaching this script and cannot
|
|
57279
|
+
# fix themselves (issue #276). Any Token Optimizer run on that machine
|
|
57280
|
+
# repairs them in place. One small JSON read; never raises.
|
|
57281
|
+
if sys.platform == "win32" and detect_runtime() == "codex":
|
|
57282
|
+
try:
|
|
57283
|
+
import codex_install as _ci
|
|
57284
|
+
_healed = _ci.heal_quoted_launcher_commands()
|
|
57285
|
+
if _healed:
|
|
57286
|
+
print(f"[Token Optimizer] Repaired {_healed} Codex hook command(s) that Windows could not run. Restart Codex to load them.", file=sys.stderr)
|
|
57287
|
+
except Exception:
|
|
57288
|
+
pass
|
|
57289
|
+
|
|
57156
57290
|
# --- Foreign-runtime guardrail (cross-platform universality) -
|
|
57157
57291
|
# OpenCode loads ~/.claude/skills by default, Copilot and Hermes can be
|
|
57158
57292
|
# invoked from their own sessions, so any of them can reach this skill even
|