@alexgreensh/token-optimizer 5.13.53 → 5.13.55

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.
@@ -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.53",
16
+ "version": "5.13.55",
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.53",
58
+ "version": "5.13.55",
59
59
  "author": {
60
60
  "name": "Alex Greenshpun",
61
61
  "url": "https://linkedin.com/in/alexgreensh"
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "homepage": "https://github.com/alexgreensh/token-optimizer",
9
9
  "repository": "https://github.com/alexgreensh/token-optimizer",
10
- "version": "5.13.53",
10
+ "version": "5.13.55",
11
11
  "license": "PolyForm-Noncommercial-1.0.0",
12
12
  "keywords": [
13
13
  "token",
@@ -106,6 +106,23 @@ _COLD_COMPILE_WAIT_S = {
106
106
  "measure": 4.0,
107
107
  "codex_hook_bridge": 1.5,
108
108
  }
109
+ # The PreCompact save (measure.py compact-capture --trigger auto) is the one
110
+ # measure.py hook whose skip loses data: no save means the restore after the
111
+ # compaction falls back to an older checkpoint. Its host timeout is 30 s and it
112
+ # runs async, so it can wait far longer than the 4 s the tightest measure.py
113
+ # hook allows. 12 s + its own 15 s budget (hook_runtime.BUDGET_PRECOMPACT_CAPTURE)
114
+ # + start-up stays under the 30 s.
115
+ _COLD_COMPILE_WAIT_PRECOMPACT_SAVE_S = 12.0
116
+
117
+
118
+ def _is_precompact_save(module_name: str, script_args) -> bool:
119
+ args = list(script_args or ())
120
+ if module_name != "measure" or not args or args[0] != "compact-capture":
121
+ return False
122
+ try:
123
+ return args[args.index("--trigger") + 1] == "auto"
124
+ except (ValueError, IndexError):
125
+ return False
109
126
  # Seconds; overrides every wait above. A negative value turns the gate off
110
127
  # (compile inline, the pre-5.13.51 behaviour).
111
128
  _COLD_COMPILE_WAIT_ENV = "TOKEN_OPTIMIZER_COLD_COMPILE_WAIT_S"
@@ -332,10 +349,12 @@ def _measure_bytecode_ready(plugin_scripts: str, wait_s: float) -> bool:
332
349
  time.sleep(0.05)
333
350
 
334
351
 
335
- def _cold_compile_wait(module_name: str):
352
+ def _cold_compile_wait(module_name: str, script_args=()):
336
353
  """Seconds this entry may wait for a background compile, or None when the
337
354
  entry is not gated (it does not import measure.py up front)."""
338
355
  wait = _COLD_COMPILE_WAIT_S.get(module_name)
356
+ if _is_precompact_save(module_name, script_args):
357
+ wait = _COLD_COMPILE_WAIT_PRECOMPACT_SAVE_S
339
358
  if wait is None:
340
359
  return None
341
360
  raw = os.environ.get(_COLD_COMPILE_WAIT_ENV, "").strip()
@@ -386,7 +405,7 @@ def main() -> int:
386
405
 
387
406
  # Before anything imports measure.py: never compile it on the hook's
388
407
  # deadline (#264). See _measure_bytecode_ready.
389
- _wait = _cold_compile_wait(module_name)
408
+ _wait = _cold_compile_wait(module_name, script_args)
390
409
  if _wait is not None:
391
410
  try:
392
411
  if not _measure_bytecode_ready(_plugin_scripts, _wait):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexgreensh/token-optimizer",
3
- "version": "5.13.53",
3
+ "version": "5.13.55",
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)",
@@ -11,22 +11,50 @@ import json
11
11
  import sys
12
12
  import threading
13
13
 
14
+ # The wait for the first byte, and the longest pause allowed while a payload is
15
+ # still arriving. A host that opens stdin and then goes silent costs at most this.
14
16
  _STDIN_TIMEOUT = 0.5
17
+ # Hard ceiling for the whole read. A multi-MB tool result can take longer than
18
+ # _STDIN_TIMEOUT to stream on a loaded machine; reading stops only when the host
19
+ # goes quiet or this ceiling is reached, never mid-stream at the first 0.5 s.
20
+ _STDIN_TOTAL_CAP = 5.0
15
21
 
16
22
 
17
23
  def _read_stdin_windows(timeout: float = _STDIN_TIMEOUT, max_bytes: int = 1_048_576) -> str:
18
- result = [""]
24
+ import time
25
+ chunks = []
26
+ state = {"done": False, "last": time.monotonic()}
19
27
 
20
28
  def _reader() -> None:
21
29
  try:
22
- result[0] = sys.stdin.buffer.read(max_bytes).decode("utf-8", errors="replace")
30
+ buf = sys.stdin.buffer
31
+ read = getattr(buf, "read1", buf.read)
32
+ total = 0
33
+ while total < max_bytes:
34
+ chunk = read(min(65536, max_bytes - total))
35
+ if not chunk:
36
+ break
37
+ chunks.append(chunk)
38
+ total += len(chunk)
39
+ state["last"] = time.monotonic()
23
40
  except Exception:
24
41
  pass
42
+ state["done"] = True
25
43
 
26
44
  t = threading.Thread(target=_reader, daemon=True)
27
45
  t.start()
28
- t.join(timeout)
29
- return result[0]
46
+ start = time.monotonic()
47
+ # Keep waiting while bytes keep arriving; give up after `timeout` of silence
48
+ # or at the total ceiling. A partial payload is not valid JSON, so a cut-off
49
+ # read degrades to {} exactly as a timeout always did.
50
+ while not state["done"]:
51
+ t.join(0.05)
52
+ now = time.monotonic()
53
+ if now - state["last"] >= timeout or now - start >= _STDIN_TOTAL_CAP:
54
+ break
55
+ if not state["done"]:
56
+ return ""
57
+ return b"".join(chunks).decode("utf-8", errors="replace")
30
58
 
31
59
 
32
60
  def read_stdin_hook_input(max_bytes: int = 1_048_576) -> dict:
@@ -49,14 +77,12 @@ def read_stdin_hook_input(max_bytes: int = 1_048_576) -> dict:
49
77
  import os
50
78
  import select
51
79
  import time
52
- # H-7: set the deadline BEFORE the first select. The old code set
53
- # it after, so if the first select() consumed most of the 0.5s
54
- # timeout, the read loop got a FULL additional 0.5s — measured
55
- # 1098ms peak (2.2x the stated 0.5s). One deadline, used for all
56
- # select() calls, so the total budget is _STDIN_TIMEOUT end to end.
57
- deadline = time.monotonic() + _STDIN_TIMEOUT
58
- remaining = deadline - time.monotonic()
59
- if remaining <= 0 or not select.select([sys.stdin], [], [], remaining)[0]:
80
+ # Two clocks: the first byte must arrive within _STDIN_TIMEOUT, and
81
+ # after that each pause may last up to _STDIN_TIMEOUT, all inside
82
+ # one _STDIN_TOTAL_CAP deadline set BEFORE the first select. A
83
+ # payload still streaming is never cut off at the first 0.5 s.
84
+ deadline = time.monotonic() + _STDIN_TOTAL_CAP
85
+ if not select.select([sys.stdin], [], [], _STDIN_TIMEOUT)[0]:
60
86
  return {}
61
87
  try:
62
88
  fd = sys.stdin.fileno()
@@ -68,15 +94,15 @@ def read_stdin_hook_input(max_bytes: int = 1_048_576) -> dict:
68
94
  # host that writes a partial payload and holds the pipe open
69
95
  # defeats the timeout. Read what is actually available in a loop
70
96
  # bounded by the same deadline, assembling chunked payloads
71
- # without ever blocking past _STDIN_TIMEOUT.
97
+ # without ever blocking on a silent pipe past _STDIN_TIMEOUT.
72
98
  chunks = []
73
99
  total = 0
74
100
  while total < max_bytes:
75
101
  remaining = deadline - time.monotonic()
76
102
  if remaining <= 0:
77
103
  break
78
- if not select.select([sys.stdin], [], [], remaining)[0]:
79
- break # timed out with no further data
104
+ if not select.select([sys.stdin], [], [], min(_STDIN_TIMEOUT, remaining))[0]:
105
+ break # the host went quiet: take what arrived
80
106
  chunk = os.read(fd, max_bytes - total)
81
107
  if not chunk:
82
108
  break # EOF: host closed stdin, payload complete
@@ -34904,6 +34904,15 @@ def setup_daemon(dry_run=False, uninstall=False, this_install_only=False, latch_
34904
34904
  # the quality-bar install path. Skipped on dry-run (side-effect-free).
34905
34905
  if not dry_run:
34906
34906
  _set_daemon_disabled(False)
34907
+ # Every platform's uninstall leaves a permanent tombstone the daemon
34908
+ # obeys forever; an explicit install is what clears it. Done here, not
34909
+ # per installer: only the launchd installer cleared it, so on Windows
34910
+ # and Linux `setup-daemon` after `--uninstall` left the daemon dead.
34911
+ try:
34912
+ if DAEMON_THRASH_BREADCRUMB.exists():
34913
+ DAEMON_THRASH_BREADCRUMB.unlink()
34914
+ except OSError:
34915
+ pass
34907
34916
  if system == "Darwin":
34908
34917
  _installed_ok = _install_launchd_daemon(dry_run=dry_run, effective_host=effective_host)
34909
34918
  elif system == "Windows":
@@ -36103,7 +36112,20 @@ def _heal_windows_console_flash():
36103
36112
  if _daemon_resurrection_blocked() is not None:
36104
36113
  return False
36105
36114
  healed_shim = _heal_windows_launcher_shim()
36106
- healed_task = _heal_windows_task_action(stop_first=True, throttle=True)
36115
+ healed_task = False
36116
+ # Reading the task's action costs a `schtasks /Query`. A healthy install
36117
+ # needs no heal, so look at most once per ensure-throttle window instead of
36118
+ # on every SessionStart. Stamped before the read, like the heal throttle.
36119
+ try:
36120
+ last = float(_read_config_flag("last_windows_task_action_check", 0) or 0)
36121
+ except (TypeError, ValueError):
36122
+ last = 0.0
36123
+ if time.time() - last >= _daemon_ensure_throttle_seconds():
36124
+ try:
36125
+ _write_config_flag("last_windows_task_action_check", int(time.time()))
36126
+ except Exception:
36127
+ pass
36128
+ healed_task = _heal_windows_task_action(stop_first=True, throttle=True)
36107
36129
  return bool(healed_shim or healed_task)
36108
36130
 
36109
36131