@alexgreensh/token-optimizer 5.13.56 → 5.13.59

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 (30) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/hooks.json +16 -16
  4. package/hooks/python-launcher.sh +10 -0
  5. package/hooks/stop_runner.py +27 -4
  6. package/hooks/windows-launcher.py +57 -3
  7. package/package.json +1 -1
  8. package/skills/fleet-auditor/scripts/shared.py +29 -1
  9. package/skills/token-optimizer/pricing/prices.json +13 -1
  10. package/skills/token-optimizer/scripts/codex_compact_prompt.py +93 -9
  11. package/skills/token-optimizer/scripts/codex_doctor.py +134 -16
  12. package/skills/token-optimizer/scripts/codex_install.py +436 -26
  13. package/skills/token-optimizer/scripts/codex_session.py +38 -8
  14. package/skills/token-optimizer/scripts/copilot_doctor.py +129 -6
  15. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +62 -14
  16. package/skills/token-optimizer/scripts/copilot_install.py +56 -4
  17. package/skills/token-optimizer/scripts/detectors/cache_instability.py +18 -4
  18. package/skills/token-optimizer/scripts/deterministic_candidates.py +55 -15
  19. package/skills/token-optimizer/scripts/devin_source.py +1 -1
  20. package/skills/token-optimizer/scripts/hermes_doctor.py +177 -1
  21. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +190 -0
  22. package/skills/token-optimizer/scripts/hermes_install.py +43 -0
  23. package/skills/token-optimizer/scripts/hermes_session.py +133 -0
  24. package/skills/token-optimizer/scripts/hermes_state.py +58 -0
  25. package/skills/token-optimizer/scripts/hermes_tool_hooks.py +291 -0
  26. package/skills/token-optimizer/scripts/measure.py +1442 -325
  27. package/skills/token-optimizer/scripts/plugin_env.py +18 -0
  28. package/skills/token-optimizer/scripts/recovery_output.py +15 -2
  29. package/skills/token-optimizer/scripts/refetch_fingerprint.py +36 -1
  30. package/skills/token-optimizer/scripts/runtime_env.py +5 -1
@@ -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).
@@ -80,28 +83,211 @@ def _cmd_quote(token: str) -> str:
80
83
  return quoted if quoted.startswith('"') else f'"{quoted}"'
81
84
 
82
85
 
83
- def _windows_launcher_command(root: Path, script: str, args, extra_env: dict) -> str:
86
+ # Characters a Windows path may carry and still parse the same in cmd.exe,
87
+ # Windows PowerShell 5.1 and PowerShell 7 when written as a bare first token.
88
+ _SHELL_NEUTRAL_EXE_RE = re.compile(r"^[A-Za-z0-9_.:\\/+~-]+$")
89
+
90
+
91
+ def _short_path(path: str) -> str | None:
92
+ """Windows 8.3 short form of ``path``, or None when there is none."""
93
+ if sys.platform != "win32":
94
+ return None
95
+ try:
96
+ import ctypes
97
+
98
+ buf = ctypes.create_unicode_buffer(32768)
99
+ n = ctypes.windll.kernel32.GetShortPathNameW(path, buf, len(buf))
100
+ if 0 < n < len(buf) and os.path.exists(buf.value):
101
+ return buf.value
102
+ except (AttributeError, ImportError, OSError, ValueError):
103
+ pass
104
+ return None
105
+
106
+
107
+ def _shell_neutral_exe(path: str) -> str | None:
108
+ """Return ``path`` as a bare token every Codex Windows hook shell parses
109
+ identically, or None when no such spelling exists.
110
+
111
+ Codex runs a command hook through the session shell: PowerShell
112
+ (``powershell -NoProfile -Command <cmd>``, preferring pwsh) or, when no
113
+ session shell is known, ``%COMSPEC% /C``. A quoted first token needs ``&``
114
+ in PowerShell and is mangled by cmd's /C quote stripping; a ``set X=Y &&``
115
+ prefix is not PowerShell 5.1 syntax at all (issue #278). A bare first token
116
+ works in both, so a path that needs quoting goes through its 8.3 short name.
117
+ """
118
+ if _SHELL_NEUTRAL_EXE_RE.match(path):
119
+ return path
120
+ short = _short_path(path)
121
+ if short and _SHELL_NEUTRAL_EXE_RE.match(short):
122
+ return short
123
+ return None
124
+
125
+
126
+ # PowerShell also treats the typographic quotes (U+2018..U+201E) as quote
127
+ # characters, so a path holding one would end the double-quoted token early.
128
+ _SHELL_UNSAFE_ARG_CHARS = '"$`%!\r\n\x00\u2018\u2019\u201a\u201b\u201c\u201d\u201e\u201f'
129
+
130
+
131
+ def _shell_neutral_arg(token: str) -> str | None:
132
+ """Double-quote ``token`` so cmd.exe and PowerShell pass it verbatim.
133
+
134
+ Returns None for a token neither shell takes literally inside double
135
+ quotes: ``$`` and the backtick expand in PowerShell, ``%`` and ``!`` can
136
+ expand in cmd, and a literal quote, newline or trailing backslash breaks
137
+ the MSVCRT argv split. PowerShell's typographic quotes are rejected too.
138
+ (A literal ``%`` was already a documented limit.)
139
+ """
140
+ if any(ch in token for ch in _SHELL_UNSAFE_ARG_CHARS) or token.endswith("\\"):
141
+ return None
142
+ return f'"{token}"'
143
+
144
+
145
+ def _neutral_child_arg(parent: str, leaf: str) -> str | None:
146
+ """``parent\\leaf`` as a shell-neutral quoted argument, going through the
147
+ 8.3 short name of ``parent`` when the long one holds a character that
148
+ expands in PowerShell or cmd (``$``, backtick, ``%``, ``!``). Only the parent
149
+ is shortened, so ``leaf`` (a version dir or the launcher file name) keeps
150
+ the exact name the launcher matches on."""
151
+ sep = "/" if "/" in parent and "\\" not in parent else "\\"
152
+ direct = _shell_neutral_arg(parent.rstrip("\\/") + sep + leaf)
153
+ if direct:
154
+ return direct
155
+ short = _short_path(parent)
156
+ if short:
157
+ return _shell_neutral_arg(short.rstrip("\\/") + "\\" + leaf)
158
+ return None
159
+
160
+
161
+ # Base folders the launcher bootstrap may start from. Windows sets the first
162
+ # three for every process; CODEX_HOME only when the user moved Codex's home.
163
+ _BOOTSTRAP_BASES = ("USERPROFILE", "LOCALAPPDATA", "APPDATA", "CODEX_HOME")
164
+ # A folder name inside the bootstrap: anything both shells keep literal inside
165
+ # double quotes that is also legal inside a Python '...' literal.
166
+ _BOOTSTRAP_UNSAFE_CHARS = _SHELL_UNSAFE_ARG_CHARS + "'\\/"
167
+
168
+
169
+ def _launcher_bootstrap(launcher: str) -> str | None:
170
+ """Readable ``python -c`` code that runs ``launcher`` from an environment
171
+ folder, for a launcher path no shell-neutral spelling exists for.
172
+
173
+ A Windows user name holding ``$`` or ``%`` puts that character in every
174
+ per-user path, its 8.3 short name included (both are legal 8.3 characters),
175
+ and PowerShell expands ``$`` inside double quotes while cmd.exe expands
176
+ ``%``. Python reads the folder from the environment instead, so the shell
177
+ never sees the character. Plain source, no encoded payload (issue #183).
178
+ Returns None when no base folder fits.
179
+ """
180
+ import ntpath
181
+
182
+ target = ntpath.normpath(launcher)
183
+ for var in _BOOTSTRAP_BASES:
184
+ base = os.environ.get(var)
185
+ if not base:
186
+ continue
187
+ base_norm = ntpath.normpath(base).rstrip("\\")
188
+ if not ntpath.normcase(target).startswith(ntpath.normcase(base_norm) + "\\"):
189
+ continue
190
+ rel = [c for c in target[len(base_norm) + 1:].split("\\") if c]
191
+ if not rel or any(c in (".", "..") or any(ch in c for ch in _BOOTSTRAP_UNSAFE_CHARS)
192
+ for c in rel):
193
+ continue
194
+ parts = ",".join(f"'{c}'" for c in rel)
195
+ return (f"import os,runpy;runpy.run_path(os.path.join(os.environ['{var}'],{parts}),"
196
+ f"run_name='__main__')")
197
+ return None
198
+
199
+
200
+ def _neutral_launcher_command(exe_path: str, launcher_path: str, baked_root: str,
201
+ env_pairs, script: str, args,
202
+ *, allow_bootstrap: bool = True) -> str | None:
203
+ """The shell-neutral launcher command (see _windows_launcher_command), or
204
+ None when no spelling runs the same in PowerShell 5.1, PowerShell 7 and
205
+ cmd.exe.
206
+
207
+ Paths are tried literally, then through the 8.3 short name of their
208
+ folder. A launcher path neither form can carry is reached through
209
+ ``_launcher_bootstrap``; its --baked-root is then written relative to the
210
+ launcher's own folder (the version dir name is always plain), which the
211
+ launcher resolves. That needs the launcher from this release, so only
212
+ install(), which copies it first, passes ``allow_bootstrap``.
213
+ """
214
+ import ntpath
215
+
216
+ exe = _shell_neutral_exe(exe_path)
217
+ if exe is None:
218
+ return None
219
+ launcher_parent, launcher_name = ntpath.split(launcher_path)
220
+ baked_parent, baked_leaf = ntpath.split(baked_root.rstrip("\\/"))
221
+ launcher = _neutral_child_arg(launcher_parent, launcher_name)
222
+ baked = _neutral_child_arg(baked_parent, baked_leaf)
223
+ head: list[str] | None = None
224
+ if launcher and baked:
225
+ head = [launcher, "--baked-root", baked]
226
+ elif allow_bootstrap and _SEMVER_DIR_RE.match(baked_leaf):
227
+ same_parent = ntpath.normcase(ntpath.normpath(launcher_parent)) == \
228
+ ntpath.normcase(ntpath.normpath(baked_parent))
229
+ code = _launcher_bootstrap(launcher_path) if same_parent else None
230
+ code_arg = _shell_neutral_arg(code) if code else None
231
+ if code_arg:
232
+ head = ["-c", code_arg, "--baked-root", f'"{baked_leaf}"']
233
+ if head is None:
234
+ return None
235
+ env_parts = [_shell_neutral_arg(pair) for pair in env_pairs]
236
+ tail = [_shell_neutral_arg(script), *(_shell_neutral_arg(a) for a in args),
237
+ _shell_neutral_arg(_LAUNCHER_MARKER)]
238
+ if not all(env_parts) or not all(tail):
239
+ return None
240
+ parts = [exe, *head]
241
+ for env_part in env_parts:
242
+ parts += ["--env", env_part]
243
+ parts += ["--", *tail]
244
+ return " ".join(parts)
245
+
246
+
247
+ def _windows_launcher_command(root: Path, script: str, args, extra_env: dict,
248
+ *, silent: bool = False) -> str:
84
249
  """Build the baked Windows hook command for a versioned marketplace root.
85
250
 
86
251
  The command invokes the readable launcher file that install() copies to
87
252
  the STABLE parent of the version dirs (.../token-optimizer/
88
253
  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].
254
+ .../token-optimizer/<X.Y.Z>/ on upgrade) -- issue #183: the retired base64
255
+ `python -c` exec-bootstrap tripped generic-loader antivirus signatures on
256
+ the literal encoded-exec string.
257
+
258
+ Shell contract (issue #278): Codex hands the command to PowerShell on
259
+ native Windows (``-Command``), or to ``%COMSPEC% /C`` when it has no session
260
+ shell. The same text must run in both, so it is ``<python> "<arg>" ...``:
261
+ a bare first token, double-quoted arguments, no ``set ... &&`` prefix, no
262
+ ``>NUL`` redirect (``silent=True`` adds a TOKEN_OPTIMIZER_HOOK_SILENT env
263
+ pair; the launcher then sends stdout/stderr to the null device in-process).
264
+ The launcher sets TOKEN_OPTIMIZER_RUNTIME itself. A path holding a
265
+ character one shell expands (``$``, backtick, ``%``, ``!``) goes through
266
+ its 8.3 short name or, for the launcher, a plain ``python -c`` bootstrap
267
+ that reads the folder from the environment (see _neutral_launcher_command).
268
+ Only when even that fails (the interpreter itself sits at such a path with
269
+ no usable short name) is the cmd.exe-only form of issue #276 returned, so
270
+ the hook still works under cmd; the doctor then says what to change.
271
+ """
272
+ env = dict(extra_env)
273
+ if silent:
274
+ env["TOKEN_OPTIMIZER_HOOK_SILENT"] = "1"
275
+ command = _neutral_launcher_command(
276
+ sys.executable, str(root.parent / _LAUNCHER_FILENAME), str(root),
277
+ [f"{k}={v}" for k, v in env.items()], script, args)
278
+ if command:
279
+ return command
280
+ return _cmd_only_launcher_command(root, script, args, extra_env, silent=silent)
281
+
282
+
283
+ def _cmd_only_launcher_command(root: Path, script: str, args, extra_env: dict,
284
+ *, silent: bool = False) -> str:
285
+ """cmd.exe-only launcher command (issue #276 shape): an unquoted ``set``
286
+ builtin first so cmd's /C quote stripping keeps the quoted paths intact.
287
+ PowerShell cannot run it; used only when no shell-neutral spelling exists.
103
288
  """
104
289
  parts = [
290
+ _WIN_UNQUOTED_PREFIX,
105
291
  _cmd_quote(sys.executable),
106
292
  _cmd_quote(str(root.parent / _LAUNCHER_FILENAME)),
107
293
  "--baked-root",
@@ -111,7 +297,24 @@ def _windows_launcher_command(root: Path, script: str, args, extra_env: dict) ->
111
297
  parts += ["--env", _cmd_quote(f"{key}={value}")]
112
298
  parts += ["--", _cmd_quote(script), *(_cmd_quote(a) for a in args),
113
299
  _cmd_quote(_LAUNCHER_MARKER)]
114
- return " ".join(parts)
300
+ command = " ".join(parts)
301
+ return f"{command} >NUL 2>&1" if silent else command
302
+
303
+
304
+ _SET_PREFIX_RE = re.compile(r"^\s*set\s", re.IGNORECASE)
305
+
306
+
307
+ def is_shell_neutral_command(command: str) -> bool:
308
+ """True when one of our Windows launcher commands runs under both
309
+ PowerShell and cmd.exe (see _windows_launcher_command)."""
310
+ if _LAUNCHER_MARKER not in command or _LAUNCHER_B64_RE.search(command):
311
+ return False
312
+ if command.startswith(('"', "'", "&", "@")) or _SET_PREFIX_RE.match(command):
313
+ return False
314
+ # Only unquoted tokens count: a folder such as "C:\Users\Tom && Jerry"
315
+ # inside a quoted path is not a cmd.exe operator.
316
+ bare = {tok for tok in _CMD_TOKEN_RE.findall(command) if not tok.startswith('"')}
317
+ return not (bare & {"&&", ">NUL", "2>&1"})
115
318
 
116
319
 
117
320
  def decode_launcher_command(command: str) -> str | None:
@@ -162,13 +365,23 @@ def _hook_command(script: str, *args: str, redirect_quiet: bool = False,
162
365
  # already launching, which removes the nested-quoting and
163
366
  # console-codepage problems entirely. Audit by reading the file;
164
367
  # 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]
368
+ return _windows_launcher_command(
369
+ root, script, args, extra_env, silent=redirect_quiet)
370
+ # Development checkout (non-semver root): run the checkout's own
371
+ # launcher pinned to this root. A non-semver --baked-root is never
372
+ # swapped for a sibling, and the same shell-neutral form runs under
373
+ # PowerShell, where the old ``set ... &&`` form exited 1 (issue #278).
374
+ env = dict(extra_env)
375
+ if redirect_quiet:
376
+ env["TOKEN_OPTIMIZER_HOOK_SILENT"] = "1"
377
+ neutral = _neutral_launcher_command(
378
+ sys.executable, str(root / "hooks" / _LAUNCHER_FILENAME), str(root),
379
+ [f"{k}={v}" for k, v in env.items()], script, args, allow_bootstrap=False)
380
+ if neutral:
381
+ return neutral
382
+ prefix = f'set "TOKEN_OPTIMIZER_RUNTIME=codex" && {_win_env}'
383
+ argv = [sys.executable, str(root / "hooks" / "run.py"), script, *args]
169
384
  redirect = " >NUL 2>&1" if redirect_quiet else ""
170
- if _SEMVER_DIR_RE.match(root.name):
171
- return f"{command}{redirect}"
172
385
  return f"{prefix}{subprocess.list2cmdline(argv)}{redirect}"
173
386
 
174
387
  command_args = " ".join(shlex.quote(arg) for arg in (script, *args))
@@ -441,6 +654,17 @@ _WIN_RUNNER_VIA_VAR_RE = re.compile(
441
654
  )
442
655
 
443
656
 
657
+ # The consolidated runners (hooks/<event>_runner.py) carry no
658
+ # "token-optimizer/scripts" text on POSIX marketplace installs, so without this
659
+ # signature a reinstall appended a second copy of each runner hook and uninstall
660
+ # left them all behind. Ours = a runner name AND our hooks/run.py (or
661
+ # python-launcher.sh) AND a path under a token-optimizer folder, together.
662
+ _RUNNER_SCRIPT_RE = re.compile(
663
+ r'hooks[/\\]+(?:sessionstart|userpromptsubmit|posttooluse|stop)_runner\.py'
664
+ )
665
+ _RUNNER_ENTRY_RE = re.compile(r'hooks[/\\]+(?:run\.py|python-launcher\.sh)|\$\{R\}hooks/')
666
+
667
+
444
668
  def _is_token_optimizer_group(group: Any) -> bool:
445
669
  # The path marker misses generated Windows commands: on versioned
446
670
  # marketplace installs the baked paths use backslashes
@@ -453,6 +677,12 @@ def _is_token_optimizer_group(group: Any) -> bool:
453
677
  serialized = json.dumps(group, sort_keys=True)
454
678
  if TOKEN_OPTIMIZER_MARKER in serialized:
455
679
  return True
680
+ if (
681
+ _RUNNER_SCRIPT_RE.search(serialized)
682
+ and _RUNNER_ENTRY_RE.search(serialized)
683
+ and _WIN_TO_DIR_RE.search(serialized)
684
+ ):
685
+ return True
456
686
  if not _WIN_ROOT_SET_RE.search(serialized):
457
687
  return False
458
688
  return (
@@ -479,11 +709,13 @@ def _normalize_baked_root(match: "re.Match[str]") -> str:
479
709
  quoted = value is not None
480
710
  if not quoted:
481
711
  value = match.group("bare")
482
- leaf = re.search(r"^(.*[/\\])\d+\.\d+\.\d+$", value)
712
+ # The prefix is optional: the bootstrap form bakes just the version name.
713
+ leaf = re.search(r"^(.*[/\\])?\d+\.\d+\.\d+$", value)
483
714
  if leaf is None:
484
715
  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
716
+ prefix = leaf.group(1) or ""
717
+ normalized = f"--baked-root {prefix}{_SIGNATURE_VERSION}"
718
+ return f'--baked-root "{prefix}{_SIGNATURE_VERSION}"' if quoted else normalized
487
719
 
488
720
 
489
721
  def _launcher_signature(command):
@@ -571,8 +803,12 @@ def _install_windows_launcher(root: Path) -> str:
571
803
  path. Idempotent (no rewrite when already current) and atomic
572
804
  (unique same-directory temp + replace, always cleaned up), so a
573
805
  concurrent hook run never reads a half-written launcher."""
806
+ return _copy_launcher_to(_windows_launcher_install_path(root))
807
+
808
+
809
+ def _copy_launcher_to(target: Path) -> str:
810
+ """Write this release's launcher to `target` (see _install_windows_launcher)."""
574
811
  source = _repo_root() / "hooks" / _LAUNCHER_FILENAME
575
- target = _windows_launcher_install_path(root)
576
812
  try:
577
813
  content = source.read_bytes()
578
814
  except OSError as exc:
@@ -662,6 +898,180 @@ def install(
662
898
  return path, "installed", details
663
899
 
664
900
 
901
+ _CMD_TOKEN_RE = re.compile(r'"[^"]*"|\S+')
902
+
903
+
904
+ def parse_cmd_only_launcher_command(command: str) -> dict | None:
905
+ """Split one of our cmd.exe-only launcher commands (issue #276 shape or the
906
+ older quoted-first-token shape) into its parts, or None when it does not
907
+ fit that exact generated shape.
908
+
909
+ Shape: optional ``set "TOKEN_OPTIMIZER_RUNTIME=codex" &&`` prefix, quoted
910
+ interpreter, quoted launcher, ``--baked-root`` and its value, ``--env``
911
+ pairs, ``--``, quoted script and args, marker, optional ``>NUL 2>&1``.
912
+ Anything else is left alone rather than guessed at.
913
+ """
914
+ if _LAUNCHER_MARKER not in command or _LAUNCHER_B64_RE.search(command):
915
+ return None
916
+ tokens = _CMD_TOKEN_RE.findall(command.strip())
917
+ silent = False
918
+ if tokens[-2:] == [">NUL", "2>&1"]:
919
+ silent = True
920
+ tokens = tokens[:-2]
921
+ if tokens[:2] == ['set', '"TOKEN_OPTIMIZER_RUNTIME=codex"'] and tokens[2:3] == ["&&"]:
922
+ tokens = tokens[3:]
923
+ if len(tokens) < 6 or tokens[-1] != f'"{_LAUNCHER_MARKER}"':
924
+ return None
925
+ if tokens[0].count('"') not in (0, 2):
926
+ return None
927
+
928
+ def value(tok: str) -> str | None:
929
+ if len(tok) >= 2 and tok.startswith('"') and tok.endswith('"'):
930
+ return tok[1:-1]
931
+ return None
932
+
933
+ exe = tokens[0].strip('"')
934
+ launcher = value(tokens[1])
935
+ if launcher is None or tokens[2] != "--baked-root":
936
+ return None
937
+ baked = value(tokens[3])
938
+ if baked is None:
939
+ return None
940
+ env: list[str] = []
941
+ i = 4
942
+ while i + 1 < len(tokens) and tokens[i] == "--env":
943
+ pair = value(tokens[i + 1])
944
+ if pair is None:
945
+ return None
946
+ env.append(pair)
947
+ i += 2
948
+ if i >= len(tokens) or tokens[i] != "--":
949
+ return None
950
+ rest = [value(t) for t in tokens[i + 1:-1]]
951
+ if not rest or any(v is None for v in rest):
952
+ return None
953
+ return {"exe": exe, "launcher": launcher, "baked_root": baked, "env": env,
954
+ "script": rest[0], "args": rest[1:], "silent": silent}
955
+
956
+
957
+ def neutralize_launcher_command(command: str) -> str | None:
958
+ """Rewrite one of our cmd.exe-only launcher commands into the shell-neutral
959
+ form of issue #278, or return None when it is already neutral, not ours, or
960
+ cannot be written that way (the caller then falls back to the #276 repair).
961
+
962
+ Pure text transform (see parse_cmd_only_launcher_command). It never uses
963
+ the ``python -c`` bootstrap: that form needs the launcher from this
964
+ release, which only a full codex-install puts in place.
965
+ """
966
+ if is_shell_neutral_command(command):
967
+ return None
968
+ parts = parse_cmd_only_launcher_command(command)
969
+ if parts is None:
970
+ return None
971
+ env = list(parts["env"])
972
+ if parts["silent"]:
973
+ env.append("TOKEN_OPTIMIZER_HOOK_SILENT=1")
974
+ return _neutral_launcher_command(
975
+ parts["exe"], parts["launcher"], parts["baked_root"], env,
976
+ parts["script"], parts["args"], allow_bootstrap=False)
977
+
978
+
979
+ def explain_cmd_only_command(command: str) -> str | None:
980
+ """Plain-English next step for a launcher command that could only be
981
+ written in the cmd.exe-only form, or None when it is not one of ours."""
982
+ parts = parse_cmd_only_launcher_command(command)
983
+ if parts is None:
984
+ return None
985
+ if _shell_neutral_exe(parts["exe"]) is None:
986
+ return (f"Python is installed in a folder PowerShell cannot start from a hook "
987
+ f"({parts['exe']}). Install Python in a plain folder such as C:\\Python313 "
988
+ "(no spaces and none of $ ` % !), run that Python's measure.py codex-install "
989
+ "again, then restart Codex")
990
+ allow = _neutral_launcher_command(
991
+ parts["exe"], parts["launcher"], parts["baked_root"], parts["env"],
992
+ parts["script"], parts["args"], allow_bootstrap=True)
993
+ if allow:
994
+ return "run measure.py codex-install again, then restart Codex"
995
+ return (f"the Token Optimizer plugin folder ({parts['launcher']}) has a character "
996
+ "PowerShell or cmd.exe changes ($ ` % !). Set CODEX_HOME to a plain folder such as "
997
+ "C:\\codex, reinstall the plugin there, run measure.py codex-install, then restart Codex")
998
+
999
+
1000
+ def heal_quoted_launcher_commands(paths=None) -> int:
1001
+ """Repair Windows hook commands that PowerShell or cmd.exe cannot run.
1002
+
1003
+ Versions before 5.13.57 saved launcher commands that open with the quoted
1004
+ python.exe path, which cmd.exe mangles (issue #276). 5.13.57 added a cmd-only
1005
+ ``set ... &&`` prefix, which PowerShell -- the shell Codex normally runs
1006
+ hooks in -- cannot parse (issue #278). Either way the hook fails before
1007
+ Python starts and can never repair itself, so any Token Optimizer run
1008
+ rewrites our own launcher commands into the shell-neutral form (or, if no
1009
+ such spelling exists, the cmd-only repair) and returns how many it
1010
+ fixed. Never raises.
1011
+ """
1012
+ if paths is None:
1013
+ paths = []
1014
+ try:
1015
+ paths.append(_global_hooks_path())
1016
+ except Exception:
1017
+ pass
1018
+ paths.append(Path.cwd() / ".codex" / "hooks.json")
1019
+ fixed = 0
1020
+ refreshed: dict[str, bool] = {}
1021
+
1022
+ def launcher_ready(command: str) -> bool:
1023
+ # A rewritten command passes --env TOKEN_OPTIMIZER_HOOK_SILENT=1 where it
1024
+ # used to redirect to NUL. Launchers before 5.13.59 ignore that flag, so
1025
+ # the launcher the command names is refreshed first; if that copy fails
1026
+ # the old command stays (still quiet under cmd.exe).
1027
+ parts = parse_cmd_only_launcher_command(command)
1028
+ if parts is None:
1029
+ return False
1030
+ target = parts["launcher"]
1031
+ if target not in refreshed:
1032
+ ok = False
1033
+ try:
1034
+ path_obj = Path(target)
1035
+ if path_obj.name == _LAUNCHER_FILENAME and path_obj.parent.is_dir():
1036
+ _copy_launcher_to(path_obj)
1037
+ ok = True
1038
+ except Exception:
1039
+ ok = False
1040
+ refreshed[target] = ok
1041
+ return refreshed[target]
1042
+
1043
+ for path in paths:
1044
+ try:
1045
+ if not path.is_file():
1046
+ continue
1047
+ data = _load_hooks(path)
1048
+ changed = 0
1049
+ for groups in data.get("hooks", {}).values():
1050
+ if not isinstance(groups, list):
1051
+ continue
1052
+ for group in groups:
1053
+ if not _is_token_optimizer_group(group):
1054
+ continue
1055
+ for handler in group.get("hooks", []):
1056
+ command = handler.get("command") if isinstance(handler, dict) else None
1057
+ if not isinstance(command, str):
1058
+ continue
1059
+ neutral = neutralize_launcher_command(command)
1060
+ if (neutral is not None and neutral != command
1061
+ and launcher_ready(command)):
1062
+ handler["command"] = neutral
1063
+ changed += 1
1064
+ elif (command.startswith('"') and _LAUNCHER_MARKER in command):
1065
+ handler["command"] = f"{_WIN_UNQUOTED_PREFIX} {command}"
1066
+ changed += 1
1067
+ if changed:
1068
+ codex_io.atomic_write_json(path, data)
1069
+ fixed += changed
1070
+ except Exception:
1071
+ continue
1072
+ return fixed
1073
+
1074
+
665
1075
  def uninstall(project: Path, *, is_global: bool = False, dry_run: bool = False) -> tuple[Path, str, dict[str, Any]]:
666
1076
  path = _global_hooks_path() if is_global else _hooks_path(project)
667
1077
  existing = _load_hooks(path)
@@ -202,6 +202,28 @@ _TOPIC_PREFIXES = (
202
202
  )
203
203
 
204
204
 
205
+ # Codex writes these as role=user messages, but nobody typed them: injected
206
+ # repo instructions, environment context and turn markers. They must never
207
+ # become the session topic or the checkpoint's Active Task (#288).
208
+ _INJECTED_USER_PREFIXES = (
209
+ "# AGENTS.md instructions", "<environment_context>", "<user_instructions>",
210
+ "<turn_aborted>", "<user_action>", "<INSTRUCTIONS>",
211
+ )
212
+
213
+
214
+ def _task_user_text(text: str) -> str:
215
+ """User text a human typed, or "" for injected Codex context."""
216
+ text = str(text or "").strip()
217
+ if not text or text.startswith(_INJECTED_USER_PREFIXES):
218
+ return ""
219
+ return text
220
+
221
+
222
+ def _pick_topic(topics: dict[str, str | None]) -> str | None:
223
+ """Prefer the event_msg user_message over its response_item duplicate."""
224
+ return topics.get("user_message") or topics.get("message")
225
+
226
+
205
227
  def _extract_topic(text: str) -> str | None:
206
228
  text = " ".join(text.split())
207
229
  if not text:
@@ -423,7 +445,7 @@ def _parse_session_records(records, incomplete=False, sampled=False):
423
445
  model_usage_breakdown: dict[str, dict[str, int]] = {}
424
446
  version = None
425
447
  slug = None
426
- topic = None
448
+ topics: dict[str, str | None] = {}
427
449
  first_ts = None
428
450
  last_ts = None
429
451
  message_count = 0
@@ -534,7 +556,10 @@ def _parse_session_records(records, incomplete=False, sampled=False):
534
556
  text_chars = payload.get('_optimizer_chars', len(text))
535
557
  role = payload.get("role")
536
558
  if payload_type == "user_message" or role == "user":
537
- topic = topic or _extract_topic(text)
559
+ if not topics.get(payload_type):
560
+ task = _task_user_text(text)
561
+ if task:
562
+ topics[payload_type] = _extract_topic(task)
538
563
  input_text_chars += text_chars
539
564
  elif payload_type == "agent_message" or role == "assistant":
540
565
  output_text_chars += text_chars
@@ -610,7 +635,7 @@ def _parse_session_records(records, incomplete=False, sampled=False):
610
635
  "scan_mode": "recent_tail" if incomplete else "full",
611
636
  "version": version,
612
637
  "slug": slug,
613
- "topic": topic,
638
+ "topic": _pick_topic(topics),
614
639
  "duration_minutes": duration_minutes,
615
640
  "wall_duration_minutes": wall_duration_minutes,
616
641
  "duration_source": duration_source,
@@ -712,7 +737,7 @@ def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
712
737
  compaction_ratios: list[dict[str, Any]] = []
713
738
  last_usage: dict[str, int] | None = None
714
739
  current_model = _UNKNOWN_MODEL
715
- topic = None
740
+ topics: dict[str, str | None] = {}
716
741
  idx = 0
717
742
  prev_was_compacted = False
718
743
  last_turn_context: int | None = None
@@ -782,8 +807,10 @@ def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
782
807
  elif payload_type in {"user_message", "message", "agent_message"}:
783
808
  text = _extract_text(payload)
784
809
  role = "assistant" if payload_type == "agent_message" else str(payload.get("role") or "user")
785
- if role == "user":
786
- topic = topic or _extract_topic(text)
810
+ if role == "user" and not topics.get(payload_type):
811
+ task = _task_user_text(text)
812
+ if task:
813
+ topics[payload_type] = _extract_topic(task)
787
814
  substantive = len(text.split()) > (20 if role == "assistant" else 10)
788
815
  messages.append((idx, role, len(text), substantive))
789
816
  if re.search(r"\b(chose|decided|because|switched|going with)\b", text, re.IGNORECASE):
@@ -838,7 +865,7 @@ def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
838
865
  "context_tokens": last_turn_context or None,
839
866
  "model_context_window": last_usage["model_context_window"] if last_usage else None,
840
867
  "model": current_model if current_model != _UNKNOWN_MODEL else _DEFAULT_MODEL,
841
- "topic": topic,
868
+ "topic": _pick_topic(topics),
842
869
  }
843
870
 
844
871
 
@@ -959,7 +986,10 @@ def extract_session_state(filepath: str | Path, tail_lines: int = 500, max_files
959
986
  if not text:
960
987
  continue
961
988
  if role == "user":
962
- last_user_msg = text
989
+ if _task_user_text(text):
990
+ last_user_msg = text
991
+ else:
992
+ continue # injected context: not a task, not a question
963
993
  elif role == "assistant":
964
994
  last_assistant_msg = text
965
995
  _append_decisions(text, decisions)