@alexgreensh/token-optimizer 5.13.62 → 5.13.63

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.
@@ -0,0 +1,94 @@
1
+ """Hook command text for adapters whose host runs the command through a shell
2
+ (Antigravity, Cursor, Grok).
3
+
4
+ macOS / Linux: ``TOKEN_OPTIMIZER_RUNTIME=<rt> '<python>' [flags] '<bridge>' <event>``,
5
+ POSIX-quoted.
6
+
7
+ Native Windows: the host may run the command through PowerShell or cmd.exe, so
8
+ the text must parse the same in both. That means a bare first token, double-
9
+ quoted arguments and no ``VAR=value`` prefix (cmd.exe and PowerShell both reject
10
+ it). The bridges set TOKEN_OPTIMIZER_RUNTIME themselves, so the prefix is not
11
+ needed. Paths holding a character either shell expands go through their 8.3
12
+ short names, using the same rules as the Codex hooks.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import ntpath
17
+ import os
18
+ import posixpath
19
+ import shlex
20
+
21
+
22
+ def _is_windows(windows: bool | None) -> bool:
23
+ return (os.name == "nt") if windows is None else windows
24
+
25
+
26
+ def build(python: str, bridge: str, event: str, *, runtime: str,
27
+ python_flags: tuple[str, ...] = (), windows: bool | None = None) -> str:
28
+ """The persisted hook command. Raises RuntimeError on Windows when no
29
+ spelling runs the same under PowerShell and cmd.exe."""
30
+ if not _is_windows(windows):
31
+ parts = [f"TOKEN_OPTIMIZER_RUNTIME={runtime}", shlex.quote(python), *python_flags,
32
+ shlex.quote(bridge), event]
33
+ return " ".join(parts)
34
+ from codex_install import _neutral_child_arg, _shell_neutral_exe # noqa: PLC0415
35
+
36
+ exe = _shell_neutral_exe(python)
37
+ parent, leaf = ntpath.split(bridge)
38
+ bridge_arg = _neutral_child_arg(parent, leaf) if parent and leaf else None
39
+ if exe is None or bridge_arg is None:
40
+ bad = python if exe is None else bridge
41
+ raise RuntimeError(
42
+ f"cannot write a Windows hook command for {bad}: the path holds a character "
43
+ "PowerShell or cmd.exe would expand ($, backtick, %, !) and has no 8.3 short "
44
+ "name. Move it to a plain folder, or set TOKEN_OPTIMIZER_PYTHON to a python "
45
+ "in a plain folder, and re-run the install."
46
+ )
47
+ return " ".join([exe, *python_flags, bridge_arg, event])
48
+
49
+
50
+ def parse(command: str, *, runtime: str, events, python_flags: tuple[str, ...] = (),
51
+ windows: bool | None = None) -> list | None:
52
+ """Parse a command written by build() into ``[python, bridge, event]``, or
53
+ None when it is not exactly that shape. Strict on purpose: doctors replay
54
+ these commands, so a corrupted or foreign entry must never be accepted."""
55
+ win = _is_windows(windows)
56
+ try:
57
+ # posix=False keeps Windows backslashes; the double quotes stay on the
58
+ # token and are stripped below.
59
+ tokens = shlex.split(command, posix=not win)
60
+ except ValueError:
61
+ return None
62
+ pin = f"TOKEN_OPTIMIZER_RUNTIME={runtime}"
63
+ if win:
64
+ tokens = [t[1:-1] if len(t) >= 2 and t[0] == t[-1] == '"' else t for t in tokens]
65
+ # Older installs wrote the POSIX shape with Windows paths; still ours.
66
+ if tokens and tokens[0] == pin:
67
+ tokens = tokens[1:]
68
+ else:
69
+ if not tokens or tokens[0] != pin:
70
+ return None
71
+ tokens = tokens[1:]
72
+ n = len(python_flags)
73
+ if len(tokens) != 3 + n or tuple(tokens[1:1 + n]) != tuple(python_flags):
74
+ return None
75
+ py, bridge, event = tokens[0], tokens[1 + n], tokens[2 + n]
76
+ isabs = ntpath.isabs if win else posixpath.isabs
77
+ if not isabs(py) or not isabs(bridge) or event not in events:
78
+ return None
79
+ return [py, bridge, event]
80
+
81
+
82
+ def path_spellings(path: str, *, windows: bool | None = None) -> set[str]:
83
+ """Every spelling build() may have written for ``path``: the path itself
84
+ and, on Windows, the form through its folder's 8.3 short name. Use this
85
+ to recognise our own entries in a shared hooks file."""
86
+ out = {path}
87
+ if _is_windows(windows):
88
+ from codex_install import _short_path # noqa: PLC0415
89
+
90
+ parent, leaf = ntpath.split(path)
91
+ short = _short_path(parent) if parent else None
92
+ if short:
93
+ out.add(short.rstrip("\\/") + "\\" + leaf)
94
+ return out
@@ -33,6 +33,7 @@ from pathlib import Path
33
33
  _SCRIPT_DIR = Path(__file__).resolve().parent
34
34
  sys.path.insert(0, str(_SCRIPT_DIR))
35
35
 
36
+ import adapter_hook_command # noqa: E402
36
37
  from runtime_env import antigravity_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
37
38
 
38
39
  DAEMON_PORT = 24847
@@ -196,6 +197,17 @@ def _plugin_checks() -> list:
196
197
  expected = {"PreInvocation", "PreToolUse", "Stop"}
197
198
  if not expected <= set(events):
198
199
  raise ValueError(f"missing events: {sorted(expected - set(events))}")
200
+ # Every hook must call the bridge inside this plugin dir. Installs
201
+ # before 5.13.63 named a temporary staging dir that no longer exists.
202
+ bridge = str(pdir / "antigravity_hook_bridge.py")
203
+ spellings = adapter_hook_command.path_spellings(bridge)
204
+ for name in sorted(expected):
205
+ entries = group.get(name) or []
206
+ handlers = [h for e in entries if isinstance(e, dict)
207
+ for h in (e.get("hooks") if isinstance(e.get("hooks"), list) else [e])]
208
+ cmds = [h.get("command", "") for h in handlers if isinstance(h, dict)]
209
+ if not any(isinstance(c, str) and any(s in c for s in spellings) for c in cmds):
210
+ raise ValueError(f"{name} hook does not call {bridge}")
199
211
  checks.append(
200
212
  _check(
201
213
  "ok", "plugin hooks", f"{hooks_path} (events: {', '.join(events)})"
@@ -466,6 +466,10 @@ def main(argv=None) -> int:
466
466
  except Exception:
467
467
  pass
468
468
 
469
+ # Pinned here as well as in the hook command: the Windows command cannot
470
+ # carry an env prefix, and the bridge must never process-scan to guess.
471
+ os.environ.setdefault("TOKEN_OPTIMIZER_RUNTIME", "antigravity")
472
+
469
473
  event = ""
470
474
  if argv:
471
475
  event = argv[0]
@@ -26,7 +26,6 @@ import argparse
26
26
  import json
27
27
  import os
28
28
  import stat as _stat
29
- import shlex
30
29
  import shutil
31
30
  import sys
32
31
  from pathlib import Path
@@ -34,6 +33,7 @@ from pathlib import Path
34
33
  _SCRIPT_DIR = Path(__file__).resolve().parent
35
34
  sys.path.insert(0, str(_SCRIPT_DIR))
36
35
 
36
+ import adapter_hook_command # noqa: E402
37
37
  from py_trust import py_path_is_trusted, py_trust_reason # noqa: E402
38
38
  from runtime_env import antigravity_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
39
39
 
@@ -132,16 +132,16 @@ def _hooks_config(bridge_path: Path) -> dict:
132
132
  docs): a JSON object keyed by hook NAME; PreToolUse uses a matcher group,
133
133
  PreInvocation/Stop are flat handler lists."""
134
134
  py = _resolve_safe_python()
135
- py_q = shlex.quote(py)
136
- bridge_q = shlex.quote(str(bridge_path))
137
135
 
138
136
  def cmd(event: str, timeout: int) -> dict:
139
137
  return {
140
138
  "type": "command",
141
139
  # -E -s: ignore PYTHONPATH + user site so an inherited env cannot
142
- # hijack payload imports (R16). TOKEN_OPTIMIZER_RUNTIME is pinned so
143
- # the bridge never process-scans on the hot path.
144
- "command": f"TOKEN_OPTIMIZER_RUNTIME=antigravity {py_q} -E -s {bridge_q} {event}",
140
+ # hijack payload imports (R16). The runtime is pinned (env prefix on
141
+ # POSIX, set by the bridge itself on Windows) so the bridge never
142
+ # process-scans on the hot path.
143
+ "command": adapter_hook_command.build(
144
+ py, str(bridge_path), event, runtime="antigravity", python_flags=("-E", "-s")),
145
145
  "timeout": timeout,
146
146
  }
147
147
 
@@ -192,16 +192,6 @@ def _write_consent(home: Path) -> None:
192
192
 
193
193
  def install(*, dry_run: bool = False, home: Path | None = None) -> dict:
194
194
  """Install the adapter. Returns a summary dict of actions taken."""
195
- # Windows refusal (deferred quoting: cmd.exe would not parse shlex.quote,
196
- # and the env-prefix form of the persisted hook command is POSIX-only).
197
- # Refuse loudly rather than register hooks that can never fire.
198
- if os.name == "nt":
199
- raise RuntimeError(
200
- "Antigravity install on native Windows is not supported yet: the "
201
- "persisted hook command is POSIX-shell quoted and cmd.exe would "
202
- "not parse it. Install from a POSIX shell or WSL."
203
- )
204
-
205
195
  root = home if home is not None else antigravity_home()
206
196
  actions = {
207
197
  "copied": [],
@@ -270,9 +260,10 @@ def install(*, dry_run: bool = False, home: Path | None = None) -> dict:
270
260
  )
271
261
 
272
262
  # Write hooks.json, then plugin.json LAST so a partial payload
273
- # never registers hooks (R1/U5).
263
+ # never registers hooks (R1/U5). The commands name the FINAL
264
+ # plugin dir: the staging dir is renamed away below.
274
265
  (staging / "hooks.json").write_text(
275
- json.dumps(_hooks_config(staging / "antigravity_hook_bridge.py"), indent=2)
266
+ json.dumps(_hooks_config(pdir / "antigravity_hook_bridge.py"), indent=2)
276
267
  + "\n",
277
268
  encoding="utf-8",
278
269
  )
@@ -53,6 +53,8 @@ _GEMINI_CARD_IDS = (
53
53
  "gemini-2.5-flash-lite",
54
54
  )
55
55
 
56
+ _GEMINI_SNAPSHOT_SUFFIX = re.compile(r"\d{3}|\d{8}|\d{4}-\d{2}-\d{2}")
57
+
56
58
 
57
59
  def _safe_int(value: Any, default: int = 0) -> int:
58
60
  try:
@@ -82,8 +84,12 @@ def model_id_for_display_name(name: str) -> Optional[str]:
82
84
  if not s:
83
85
  return None
84
86
  if s.startswith("gemini-"):
87
+ # A card id, optionally followed by a numeric snapshot suffix (-001,
88
+ # -20260101, -2026-01-01). Any other variant (an unlisted -lite, -image
89
+ # or -live model) has no card of its own and is left unpriced.
85
90
  for card_id in _GEMINI_CARD_IDS:
86
- if s == card_id or s.startswith(card_id + "-"):
91
+ if s == card_id or (s.startswith(card_id + "-")
92
+ and _GEMINI_SNAPSHOT_SUFFIX.fullmatch(s[len(card_id) + 1:])):
87
93
  return card_id
88
94
  return None
89
95
  if "claude" in s or "sonnet" in s or "opus" in s or "haiku" in s:
@@ -292,18 +298,36 @@ def normalize_session(raw: dict) -> Optional[dict]:
292
298
  not_fully_idle = bool(raw.get("not_fully_idle"))
293
299
  end_reason = "killed" if killed else ("not_fully_idle" if not_fully_idle else "")
294
300
 
295
- # Per-model usage: single model id for the whole conversation (highest
296
- # volume was resolved upstream in antigravity_state.model_display_name).
297
- billable = total_input + total_output
298
- model_usage = {model: billable} if model not in ("", _UNKNOWN_MODEL) else {}
299
301
  model_usage_breakdown = {}
300
- if model_usage:
302
+ complete_generations = all(isinstance(g, dict) and all(k in g for k in (
303
+ "input_tokens", "output_tokens", "cache_read_tokens", "model_display_name")) for g in generations)
304
+ complete_generations = bool(generations) and complete_generations and not _safe_int(raw.get("undecodable_rows")) and all(
305
+ sum(max(0, _safe_int(g.get(k))) for g in generations) == total
306
+ for k, total in (("input_tokens", input_tokens), ("output_tokens", output_tokens),
307
+ ("cache_read_tokens", cache_read))
308
+ )
309
+ if complete_generations:
310
+ for g in generations:
311
+ name = str(g.get("model_display_name") or _UNKNOWN_MODEL)
312
+ key = model_id_for_display_name(name) or name
313
+ parts = model_usage_breakdown.setdefault(key, {"fresh_input": 0, "cache_read": 0, "cache_create": 0, "output": 0, "requests": []})
314
+ request = {"fresh_input": max(0, _safe_int(g.get("input_tokens"))),
315
+ "cache_read": max(0, _safe_int(g.get("cache_read_tokens"))),
316
+ "output": max(0, _safe_int(g.get("output_tokens")))}
317
+ for field, value in request.items():
318
+ parts[field] += value
319
+ parts["requests"].append(request)
320
+ elif model not in ("", _UNKNOWN_MODEL):
301
321
  model_usage_breakdown[model] = {
302
322
  "fresh_input": total_input - total_cache_read,
303
323
  "cache_read": total_cache_read,
304
324
  "cache_create": 0,
305
325
  "output": total_output,
306
326
  }
327
+ model_usage = {name: parts["fresh_input"] + parts["cache_create"] + parts["output"]
328
+ for name, parts in model_usage_breakdown.items()}
329
+ if credits is None and any(model_id_for_display_name(name) for name in model_usage):
330
+ cost_source = "antigravity_list_price_estimate"
307
331
 
308
332
  session = _base_canonical(str(conversation_id))
309
333
  session.update(
@@ -326,6 +350,7 @@ def normalize_session(raw: dict) -> Optional[dict]:
326
350
  "model_id": model_id,
327
351
  "model_usage": model_usage,
328
352
  "model_usage_breakdown": model_usage_breakdown,
353
+ "generation_details_complete": complete_generations,
329
354
  "message_count": user_inputs,
330
355
  "api_calls": len(generations),
331
356
  "tool_calls": {"total": tool_calls},
@@ -83,9 +83,11 @@ def _cmd_quote(token: str) -> str:
83
83
  return quoted if quoted.startswith('"') else f'"{quoted}"'
84
84
 
85
85
 
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_.:\\/+~-]+$")
86
+ # Characters a path may carry and still parse the same in cmd.exe, Windows
87
+ # PowerShell 5.1 and PowerShell 7 when written as a bare first token. ``@`` is
88
+ # literal inside a token (user names and package dirs such as ``python@3.14``
89
+ # carry it) but starts a splat in PowerShell, so it never leads the token.
90
+ _SHELL_NEUTRAL_EXE_RE = re.compile(r"^[A-Za-z0-9_.:\\/+~-][A-Za-z0-9_.:\\/+~@-]*$")
89
91
 
90
92
 
91
93
  def _short_path(path: str) -> str | None:
@@ -25,7 +25,6 @@ from __future__ import annotations
25
25
  import argparse
26
26
  import json
27
27
  import os
28
- import shlex
29
28
  import shutil
30
29
  import subprocess
31
30
  import sys
@@ -35,6 +34,7 @@ from pathlib import Path
35
34
  _SCRIPT_DIR = Path(__file__).resolve().parent
36
35
  sys.path.insert(0, str(_SCRIPT_DIR))
37
36
 
37
+ import adapter_hook_command # noqa: E402
38
38
  from runtime_env import cursor_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
39
39
  from cursor_install import _py_path_is_trusted # noqa: E402
40
40
 
@@ -420,10 +420,11 @@ def _installed_commands() -> dict:
420
420
  # own (the installed plugin copy, or the sibling checkout bridge in dev)
421
421
  # qualify, so a corrupted entry pointing at /tmp/evil/cursor_hook_bridge.py
422
422
  # is never replayed by --probe.
423
- ours = {
424
- str(cursor_home() / "token-optimizer" / "plugin" / "cursor_hook_bridge.py"),
425
- str(_SCRIPT_DIR / "cursor_hook_bridge.py"),
426
- }
423
+ ours = set().union(*(
424
+ adapter_hook_command.path_spellings(str(p)) for p in (
425
+ cursor_home() / "token-optimizer" / "plugin" / "cursor_hook_bridge.py",
426
+ _SCRIPT_DIR / "cursor_hook_bridge.py",
427
+ )))
427
428
  out = {}
428
429
  for event in _WIRED_EVENTS:
429
430
  for cmd in commands.get(event, []):
@@ -435,30 +436,14 @@ def _installed_commands() -> dict:
435
436
 
436
437
 
437
438
  def _parse_hook_command(command: str) -> list | None:
438
- """Parse a persisted hooks.json command into argv, or None if malformed.
439
+ """Parse a persisted hook command into ``[python, bridge, event]``, or None.
439
440
 
440
- The installer writes exactly ``TOKEN_OPTIMIZER_RUNTIME=cursor <abs-py>
441
- <abs-bridge> <event>``. Anything else (extra tokens, relative paths, an
442
- unknown event, shell metacharacters that survive shlex) is rejected rather
443
- than executed: hooks.json is shared with other tools, and --probe must never
444
- become an injection vector for a corrupted or malicious entry.
441
+ Only the exact shape the installer writes is accepted (see
442
+ adapter_hook_command): runtime pin on POSIX, absolute python and bridge, a
443
+ wired event. Anything else is rejected rather than executed, so --probe
444
+ never becomes an injection vector for a corrupted or foreign entry.
445
445
  """
446
- try:
447
- # posix=False on Windows: shlex's POSIX mode eats backslashes, so
448
- # C:\Python314\python.exe would parse as "C:Python314python.exe".
449
- tokens = shlex.split(command, posix=(os.name != "nt"))
450
- except ValueError:
451
- return None
452
- if len(tokens) != 4:
453
- return None
454
- runtime, py, bridge, event = tokens
455
- if runtime != "TOKEN_OPTIMIZER_RUNTIME=cursor":
456
- return None
457
- if not os.path.isabs(py) or not os.path.isabs(bridge):
458
- return None
459
- if event not in _WIRED_EVENTS:
460
- return None
461
- return tokens[1:]
446
+ return adapter_hook_command.parse(command, runtime="cursor", events=_WIRED_EVENTS)
462
447
 
463
448
 
464
449
  def _run_probe_command(command: str, payload: dict, probe_home: Path) -> dict:
@@ -9,9 +9,9 @@ Wires Token Optimizer into Cursor's shared user hooks file:
9
9
  tools are preserved verbatim; only entries whose ``command`` points at our
10
10
  bridge path are replaced. Cursor has one shared hooks.json (no per-plugin
11
11
  file like Copilot), so clobbering it would destroy other people's hooks.
12
- 3. Refuses on native Windows (``os.name == "nt"``): the persisted ``command``
13
- string is POSIX-shell quoted and cmd.exe would not parse it. Windows work is
14
- deferred rather than silently writing a no-op hook.
12
+ 3. Writes a hook command each platform's shell parses: POSIX-quoted on
13
+ macOS/Linux, a form PowerShell and cmd.exe both run on native Windows
14
+ (see adapter_hook_command).
15
15
 
16
16
  Idempotent: re-running refreshes the payload and replaces only OUR entries.
17
17
  Uninstall removes only OUR entries and the payload dir; session data stays.
@@ -26,7 +26,6 @@ from __future__ import annotations
26
26
  import argparse
27
27
  import json
28
28
  import os
29
- import shlex
30
29
  import shutil
31
30
  import stat as _stat
32
31
  import sys
@@ -36,6 +35,7 @@ from pathlib import Path
36
35
  _SCRIPT_DIR = Path(__file__).resolve().parent
37
36
  sys.path.insert(0, str(_SCRIPT_DIR))
38
37
 
38
+ import adapter_hook_command # noqa: E402
39
39
  from py_trust import py_path_is_trusted, py_trust_reason # noqa: E402
40
40
  from runtime_env import cursor_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
41
41
 
@@ -145,16 +145,15 @@ def _hook_entries(bridge_path: Path) -> dict:
145
145
  """The hook entries TO appends to ~/.cursor/hooks.json.
146
146
 
147
147
  Cursor's per-hook schema is ``{command, type, matcher?, timeout,
148
- failClosed?, loop_limit?}`` (verified 2026-09-01). ``command`` is assumed to
149
- run through a POSIX shell, so the two paths are shlex-quoted and the runtime
150
- is pinned so the bridge never process-scans on the hot path.
148
+ failClosed?, loop_limit?}`` (verified 2026-09-01). ``command`` runs through
149
+ the platform shell (see adapter_hook_command); the runtime is pinned so the
150
+ bridge never process-scans on the hot path.
151
151
  """
152
- py_q = shlex.quote(_resolve_safe_python())
153
- bridge_q = shlex.quote(str(bridge_path))
152
+ py = _resolve_safe_python()
154
153
 
155
154
  def entry(event: str, *, matcher: str | None = None) -> dict:
156
155
  e = {
157
- "command": f"TOKEN_OPTIMIZER_RUNTIME=cursor {py_q} {bridge_q} {event}",
156
+ "command": adapter_hook_command.build(py, str(bridge_path), event, runtime="cursor"),
158
157
  "type": "command",
159
158
  "timeout": HOOK_TIMEOUT_SEC,
160
159
  }
@@ -178,7 +177,8 @@ def _is_ours(entry, bridge_path: Path) -> bool:
178
177
  if not isinstance(entry, dict):
179
178
  return False
180
179
  cmd = entry.get("command")
181
- return isinstance(cmd, str) and str(bridge_path) in cmd
180
+ return isinstance(cmd, str) and any(
181
+ spelling in cmd for spelling in adapter_hook_command.path_spellings(str(bridge_path)))
182
182
 
183
183
 
184
184
  def _read_hooks(path: Path) -> dict:
@@ -271,14 +271,6 @@ def _copy_no_follow(src: Path, dest: Path) -> None:
271
271
 
272
272
  def install(*, dry_run: bool = False, home: Path = None) -> dict:
273
273
  """Install the adapter. Returns a summary dict of actions taken."""
274
- # Windows refusal (deferred quoting: cmd.exe would not parse shlex.quote).
275
- if os.name == "nt":
276
- raise RuntimeError(
277
- "Cursor install on native Windows is not supported yet: the persisted "
278
- "hook command is POSIX-shell quoted and cmd.exe would not parse it. "
279
- "Install from a POSIX shell or WSL."
280
- )
281
-
282
274
  root = home if home is not None else cursor_home()
283
275
  actions = {"copied": [], "hook_file": None, "skipped": [], "dry_run": dry_run}
284
276
  plugin_dir = _plugin_dir(root)
@@ -16,7 +16,7 @@ ALLOWED_MODULES = frozenset(Path(name).stem for name in PAYLOAD)
16
16
 
17
17
  # Repo names outside the installed closure must never fall back to sys.path.
18
18
  REPO_MODULES = frozenset((
19
- 'activity_tracker', 'antigravity_doctor', 'antigravity_hook_bridge', 'antigravity_install',
19
+ 'activity_tracker', 'adapter_hook_command', 'antigravity_doctor', 'antigravity_hook_bridge', 'antigravity_install',
20
20
  'antigravity_proto', 'antigravity_session', 'antigravity_state', 'archive_result',
21
21
  'bash_compress', 'bash_compress_hook', 'bash_hook', 'bash_whitelist', 'benchmark', 'cloud_kit',
22
22
  'build_output_compress', 'codex_command_compress', 'codex_compact_prompt', 'codex_doctor',
@@ -30,7 +30,6 @@ from __future__ import annotations
30
30
  import argparse
31
31
  import json
32
32
  import os
33
- import shlex
34
33
  import shutil
35
34
  import subprocess
36
35
  import sys
@@ -40,6 +39,7 @@ from pathlib import Path
40
39
  _SCRIPT_DIR = Path(__file__).resolve().parent
41
40
  sys.path.insert(0, str(_SCRIPT_DIR))
42
41
 
42
+ import adapter_hook_command # noqa: E402
43
43
  from runtime_env import grok_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
44
44
  from py_trust import py_path_is_trusted # noqa: E402
45
45
 
@@ -383,10 +383,11 @@ def _installed_commands() -> dict:
383
383
  # Identity, not substring: only entries whose bridge token is a bridge we
384
384
  # own qualify, so a corrupted entry pointing at /tmp/evil/grok_hook_bridge.py
385
385
  # is never replayed by --probe.
386
- ours = {
387
- str(grok_home() / "token-optimizer" / "plugin" / "grok_hook_bridge.py"),
388
- str(_SCRIPT_DIR / "grok_hook_bridge.py"),
389
- }
386
+ ours = set().union(*(
387
+ adapter_hook_command.path_spellings(str(p)) for p in (
388
+ grok_home() / "token-optimizer" / "plugin" / "grok_hook_bridge.py",
389
+ _SCRIPT_DIR / "grok_hook_bridge.py",
390
+ )))
390
391
  out = {}
391
392
  by_event = {event: [c for e, c in _iter_commands(config) if e == event]
392
393
  for event in _WIRED_EVENTS}
@@ -400,27 +401,14 @@ def _installed_commands() -> dict:
400
401
 
401
402
 
402
403
  def _parse_hook_command(command: str) -> list | None:
403
- """Parse a persisted hook command into argv, or None if malformed.
404
+ """Parse a persisted hook command into ``[python, bridge, event]``, or None.
404
405
 
405
- The installer writes exactly ``TOKEN_OPTIMIZER_RUNTIME=grok <abs-py>
406
- <abs-bridge> <Event>``. Anything else is rejected rather than executed:
407
- the hooks file is user-writable, and --probe must never become an injection
408
- vector for a corrupted or malicious entry.
406
+ Only the exact shape the installer writes is accepted (see
407
+ adapter_hook_command): runtime pin on POSIX, absolute python and bridge, a
408
+ wired event. Anything else is rejected rather than executed, so --probe
409
+ never becomes an injection vector for a corrupted or foreign entry.
409
410
  """
410
- try:
411
- tokens = shlex.split(command, posix=(os.name != "nt"))
412
- except ValueError:
413
- return None
414
- if len(tokens) != 4:
415
- return None
416
- runtime, py, bridge, event = tokens
417
- if runtime != "TOKEN_OPTIMIZER_RUNTIME=grok":
418
- return None
419
- if not os.path.isabs(py) or not os.path.isabs(bridge):
420
- return None
421
- if event not in _WIRED_EVENTS:
422
- return None
423
- return tokens[1:]
411
+ return adapter_hook_command.parse(command, runtime="grok", events=_WIRED_EVENTS)
424
412
 
425
413
 
426
414
  def _run_probe_command(command: str, payload: dict, probe_home: Path) -> dict:
@@ -9,8 +9,9 @@ Wires Token Optimizer into Grok Build's hooks system:
9
9
  (Grok scans ``~/.grok/hooks/*.json`` as a DIRECTORY of files — unlike
10
10
  Cursor's single shared hooks.json — so TO owns its file outright and never
11
11
  merges with, or clobbers, another tool's hooks).
12
- 3. Refuses on native Windows (``os.name == "nt"``): the persisted ``command``
13
- string is POSIX-shell quoted and cmd.exe would not parse it.
12
+ 3. Writes a hook command each platform's shell parses: POSIX-quoted on
13
+ macOS/Linux, a form PowerShell and cmd.exe both run on native Windows
14
+ (see adapter_hook_command).
14
15
 
15
16
  The hooks JSON format is Grok's documented shape (10-hooks.md "The Hook JSON
16
17
  Format"): ``{"hooks": {<Event>: [{matcher?, hooks: [{type, command, timeout}]}]}}``.
@@ -28,7 +29,6 @@ from __future__ import annotations
28
29
  import argparse
29
30
  import json
30
31
  import os
31
- import shlex
32
32
  import shutil
33
33
  import sys
34
34
  from contextlib import contextmanager
@@ -37,6 +37,7 @@ from pathlib import Path
37
37
  _SCRIPT_DIR = Path(__file__).resolve().parent
38
38
  sys.path.insert(0, str(_SCRIPT_DIR))
39
39
 
40
+ import adapter_hook_command # noqa: E402
40
41
  from py_trust import py_path_is_trusted, py_trust_reason # noqa: E402
41
42
  from runtime_env import grok_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
42
43
 
@@ -134,17 +135,16 @@ def _resolve_safe_python() -> str:
134
135
  def _hook_entries(bridge_path: Path) -> dict:
135
136
  """The hook entries TO writes to $GROK_HOME/hooks/token-optimizer.json.
136
137
 
137
- Format is Grok's documented 10-hooks.md shape. ``command`` is assumed to run
138
- through a POSIX shell, so the two paths are shlex-quoted and the runtime is
139
- pinned so the bridge never process-scans on the hot path.
138
+ Format is Grok's documented 10-hooks.md shape. ``command`` runs through the
139
+ platform shell (see adapter_hook_command); the runtime is pinned so the
140
+ bridge never process-scans on the hot path.
140
141
  """
141
- py_q = shlex.quote(_resolve_safe_python())
142
- bridge_q = shlex.quote(str(bridge_path))
142
+ py = _resolve_safe_python()
143
143
 
144
144
  def handler(event: str, timeout: int) -> dict:
145
145
  return {
146
146
  "type": "command",
147
- "command": f"TOKEN_OPTIMIZER_RUNTIME=grok {py_q} {bridge_q} {event}",
147
+ "command": adapter_hook_command.build(py, str(bridge_path), event, runtime="grok"),
148
148
  "timeout": timeout,
149
149
  }
150
150
 
@@ -274,13 +274,6 @@ def _copy_no_follow(src: Path, dest: Path) -> None:
274
274
 
275
275
  def install(*, dry_run: bool = False, home: Path | None = None) -> dict:
276
276
  """Install the adapter. Returns a summary dict of actions taken."""
277
- if os.name == "nt":
278
- raise RuntimeError(
279
- "Grok install on native Windows is not supported yet: the persisted "
280
- "hook command is POSIX-shell quoted and cmd.exe would not parse it. "
281
- "Install from a POSIX shell or WSL."
282
- )
283
-
284
277
  root = home if home is not None else grok_home()
285
278
  actions = {"copied": [], "hook_file": None, "skipped": [], "dry_run": dry_run}
286
279
  plugin_dir = _plugin_dir(root)