@alexgreensh/token-optimizer 5.13.61 → 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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/sessionstart_runner.py +20 -4
- package/package.json +1 -1
- package/skills/fleet-auditor/scripts/fleet.py +4 -1
- package/skills/fleet-auditor/scripts/shared.py +31 -14
- package/skills/token-optimizer/assets/dashboard.html +397 -68
- package/skills/token-optimizer/pricing/prices.json +6 -1
- package/skills/token-optimizer/scripts/adapter_hook_command.py +94 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +12 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +4 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +9 -18
- package/skills/token-optimizer/scripts/antigravity_session.py +31 -6
- package/skills/token-optimizer/scripts/codex_install.py +5 -3
- package/skills/token-optimizer/scripts/cursor_doctor.py +12 -27
- package/skills/token-optimizer/scripts/cursor_install.py +11 -19
- package/skills/token-optimizer/scripts/devin_source.py +1 -1
- package/skills/token-optimizer/scripts/grok_doctor.py +12 -24
- package/skills/token-optimizer/scripts/grok_install.py +9 -16
- package/skills/token-optimizer/scripts/measure.py +3887 -616
- package/skills/token-optimizer/scripts/read_cache.py +32 -20
- package/skills/token-optimizer/scripts/refetch_guard.py +9 -3
- package/skills/token-optimizer/scripts/session_store.py +64 -0
|
@@ -36,11 +36,14 @@ from plugin_env import is_v5_flag_enabled, resolve_snapshot_dir
|
|
|
36
36
|
from runtime_env import project_config_value, run_origin, runtime_home
|
|
37
37
|
|
|
38
38
|
try:
|
|
39
|
-
from session_store import SessionStore, cleanup_old_stores
|
|
39
|
+
from session_store import SessionStore, cleanup_old_stores, mark_context_reset
|
|
40
40
|
except ImportError:
|
|
41
41
|
SessionStore = None # type: ignore[assignment,misc]
|
|
42
42
|
cleanup_old_stores = None # type: ignore[assignment]
|
|
43
43
|
|
|
44
|
+
def mark_context_reset(*_a, **_k): # type: ignore[misc]
|
|
45
|
+
return None
|
|
46
|
+
|
|
44
47
|
try:
|
|
45
48
|
from credential_patterns import redact_credentials as _redact_creds
|
|
46
49
|
from credential_patterns import pop_redaction_warning as _pop_redaction_warning
|
|
@@ -1482,10 +1485,16 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
|
|
|
1482
1485
|
# model's context: forget them so this Read is judged a first read.
|
|
1483
1486
|
try:
|
|
1484
1487
|
if _scan_for_compaction(store, hook_input.get("transcript_path")):
|
|
1485
|
-
|
|
1488
|
+
if hook_input.get("agent_id"):
|
|
1489
|
+
# A subagent keeps its own context; only its read ledger follows
|
|
1490
|
+
# the transcript's compaction marker.
|
|
1491
|
+
store.clear_file_entries()
|
|
1492
|
+
else:
|
|
1493
|
+
store.reset_context_state()
|
|
1494
|
+
mark_context_reset(session_id)
|
|
1486
1495
|
if not quiet:
|
|
1487
1496
|
print(
|
|
1488
|
-
f"[Read Cache] Compaction detected;
|
|
1497
|
+
f"[Read Cache] Compaction detected; reset context state for {session_id}",
|
|
1489
1498
|
file=sys.stderr,
|
|
1490
1499
|
)
|
|
1491
1500
|
except Exception:
|
|
@@ -2052,21 +2061,22 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
|
|
|
2052
2061
|
|
|
2053
2062
|
|
|
2054
2063
|
def handle_clear_compacted(hook_input: dict[str, Any], quiet: bool) -> None:
|
|
2055
|
-
"""
|
|
2056
|
-
|
|
2057
|
-
Wired to SessionStart (
|
|
2058
|
-
flag, which reads ``session_id`` from the stdin hook
|
|
2059
|
-
the
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
(``
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2064
|
+
"""Reset ONE session's "already in context" state after a /clear or compaction.
|
|
2065
|
+
|
|
2066
|
+
Wired to SessionStart (sources ``compact`` and ``clear``) via the
|
|
2067
|
+
``--clear-compacted`` flag, which reads ``session_id`` from the stdin hook
|
|
2068
|
+
input. Both events empty the model's context while the session id, and so the
|
|
2069
|
+
session store, lives on. Left alone, an unchanged file whose ``file_reads``
|
|
2070
|
+
row survives is judged redundant on the next Read and served as an outline or
|
|
2071
|
+
a block even though the model no longer holds it, and the same goes for
|
|
2072
|
+
delta baselines, cross-turn command outputs and repeat-command streaks.
|
|
2073
|
+
|
|
2074
|
+
Calls ``store.reset_context_state()`` (and stamps the re-fetch guard's reset
|
|
2075
|
+
marker) for the named session ONLY: other sessions and subagent stores are not
|
|
2076
|
+
touched. It never takes ``handle_clear``'s session-scoped branch, which also
|
|
2077
|
+
unlinks the decisions telemetry log (``_decisions_log_path``) and the legacy
|
|
2078
|
+
cache json; that would delete per-session decision/shadow telemetry on every
|
|
2079
|
+
reset.
|
|
2070
2080
|
|
|
2071
2081
|
Contention-safe: SessionStore connects fail-fast
|
|
2072
2082
|
(``busy_timeout=50ms``), so under a sibling SessionStart compact-restore or
|
|
@@ -2115,7 +2125,7 @@ def handle_clear_compacted(hook_input: dict[str, Any], quiet: bool) -> None:
|
|
|
2115
2125
|
# honored by _connect() for BOTH the schema init and the DELETE, so the
|
|
2116
2126
|
# clear waits out a sibling write lock within the hook budget instead
|
|
2117
2127
|
# of dying at the 50ms fail-fast default during _init_schema.
|
|
2118
|
-
store.
|
|
2128
|
+
store.reset_context_state()
|
|
2119
2129
|
except sqlite3.OperationalError as exc:
|
|
2120
2130
|
# LOUD failure: never a silent exit-0 no-op that resurrects the bug.
|
|
2121
2131
|
print(
|
|
@@ -2126,9 +2136,11 @@ def handle_clear_compacted(hook_input: dict[str, Any], quiet: bool) -> None:
|
|
|
2126
2136
|
return
|
|
2127
2137
|
finally:
|
|
2128
2138
|
store.close()
|
|
2139
|
+
if not hook_input.get("agent_id"):
|
|
2140
|
+
mark_context_reset(session_id)
|
|
2129
2141
|
if not quiet:
|
|
2130
2142
|
print(
|
|
2131
|
-
f"[Read Cache]
|
|
2143
|
+
f"[Read Cache] Reset session context state for {session_id}",
|
|
2132
2144
|
file=sys.stderr,
|
|
2133
2145
|
)
|
|
2134
2146
|
|
|
@@ -40,6 +40,7 @@ try:
|
|
|
40
40
|
)
|
|
41
41
|
from recovery_output import is_recovery_tool
|
|
42
42
|
from session_store import _sanitize_session_id as sanitize_sid
|
|
43
|
+
from session_store import context_reset_at
|
|
43
44
|
except Exception:
|
|
44
45
|
# If our own modules can't load, never block a tool call.
|
|
45
46
|
print(_NEUTRAL)
|
|
@@ -116,17 +117,21 @@ def _entry_is_renderable(archive_dir: Path, tool_use_id: str) -> bool:
|
|
|
116
117
|
return False
|
|
117
118
|
|
|
118
119
|
|
|
119
|
-
def _within_window(timestamp, now: float) -> bool:
|
|
120
|
+
def _within_window(timestamp, now: float, reset_at: float = 0.0) -> bool:
|
|
120
121
|
"""True when an archive entry's ISO timestamp is inside the guard window.
|
|
121
122
|
|
|
122
123
|
An unparseable or missing timestamp counts as OUTSIDE the window: the guard
|
|
123
|
-
only ever denies on proof, so doubt means allow.
|
|
124
|
+
only ever denies on proof, so doubt means allow. A result archived before the
|
|
125
|
+
session's last /clear or compaction is outside the window too: the model no
|
|
126
|
+
longer holds it, so re-running the call is not a loop. Never raises.
|
|
124
127
|
"""
|
|
125
128
|
try:
|
|
126
129
|
from datetime import datetime
|
|
127
130
|
ts = datetime.fromisoformat(str(timestamp)).timestamp()
|
|
128
131
|
except Exception:
|
|
129
132
|
return False
|
|
133
|
+
if ts <= reset_at:
|
|
134
|
+
return False
|
|
130
135
|
return 0 <= now - ts <= _guard_window_seconds()
|
|
131
136
|
|
|
132
137
|
|
|
@@ -159,11 +164,12 @@ def _lookup_archived(session_id: str, tool_name: str, fingerprint: str):
|
|
|
159
164
|
if not manifest.is_file() or manifest.is_symlink():
|
|
160
165
|
return None, 0
|
|
161
166
|
now = time.time()
|
|
167
|
+
reset_at = context_reset_at(session_id)
|
|
162
168
|
for entry in reversed(_read_manifest_tail(manifest)): # newest first
|
|
163
169
|
if entry.get("tool_name") == tool_name and entry.get(ARGS_HASH_KEY) == fingerprint:
|
|
164
170
|
# Newest match is too old: every older one is too, and an old
|
|
165
171
|
# identical call is a deliberate re-check of live data, not a loop.
|
|
166
|
-
if not _within_window(entry.get("timestamp"), now):
|
|
172
|
+
if not _within_window(entry.get("timestamp"), now, reset_at):
|
|
167
173
|
return None, 0
|
|
168
174
|
tool_use_id = entry.get("tool_use_id")
|
|
169
175
|
if tool_use_id and _entry_is_renderable(archive_dir, tool_use_id):
|
|
@@ -575,6 +575,31 @@ class SessionStore:
|
|
|
575
575
|
conn.execute("DELETE FROM file_reads")
|
|
576
576
|
conn.commit()
|
|
577
577
|
|
|
578
|
+
def reset_context_state(self) -> None:
|
|
579
|
+
"""Forget everything that records what the model currently holds.
|
|
580
|
+
|
|
581
|
+
A /clear or a compaction empties the model's context while the session
|
|
582
|
+
id (and so this store) lives on. Every record that later lets a hook say
|
|
583
|
+
"you already have this" must go with it: the read ledger, the delta-read
|
|
584
|
+
baselines, the cross-turn command outputs, the repeat-command streaks, the
|
|
585
|
+
served-hint ledger and the first-read skeleton markers. Nothing here is a
|
|
586
|
+
recovery source: the tool-output archive, activity log, compaction
|
|
587
|
+
cursor and decision notes stay, because they describe the session, not
|
|
588
|
+
the context window. One transaction, so a lock failure leaves the old
|
|
589
|
+
state intact rather than half-cleared.
|
|
590
|
+
"""
|
|
591
|
+
conn = self._connect()
|
|
592
|
+
with conn:
|
|
593
|
+
conn.execute("DELETE FROM file_reads")
|
|
594
|
+
conn.execute("DELETE FROM cached_content")
|
|
595
|
+
conn.execute("DELETE FROM command_outputs")
|
|
596
|
+
conn.execute("DELETE FROM command_run_streaks")
|
|
597
|
+
conn.execute("DELETE FROM hint_serves")
|
|
598
|
+
conn.execute(
|
|
599
|
+
"DELETE FROM session_meta WHERE key GLOB 'shadow_fr:*' "
|
|
600
|
+
"OR key GLOB 'active_fr:*'"
|
|
601
|
+
)
|
|
602
|
+
|
|
578
603
|
# ----- cached_content -----
|
|
579
604
|
|
|
580
605
|
def get_cached_content(self, file_path: str) -> Optional[dict[str, Any]]:
|
|
@@ -960,6 +985,45 @@ class SessionStore:
|
|
|
960
985
|
return [dict(r) for r in rows]
|
|
961
986
|
|
|
962
987
|
|
|
988
|
+
def _context_reset_marker(session_id: str, snapshot_dir: Optional[Path] = None) -> Optional[Path]:
|
|
989
|
+
# An id the archive would not accept maps to no marker, so a malformed id
|
|
990
|
+
# can never fork a stray directory.
|
|
991
|
+
if not session_id or not re.match(r"^[a-zA-Z0-9_-]+\Z", session_id):
|
|
992
|
+
return None
|
|
993
|
+
base = snapshot_dir or resolve_snapshot_dir()
|
|
994
|
+
return base / "tool-archive" / session_id / "context_reset_at"
|
|
995
|
+
|
|
996
|
+
|
|
997
|
+
def mark_context_reset(session_id: str, snapshot_dir: Optional[Path] = None) -> None:
|
|
998
|
+
"""Record that this session's context was emptied now (/clear or compaction).
|
|
999
|
+
|
|
1000
|
+
The re-fetch guard reads this to stop treating archived MCP results from
|
|
1001
|
+
before the reset as data the model still holds. A plain timestamp file, not a
|
|
1002
|
+
database row, because the guard runs on every MCP call and stays free of
|
|
1003
|
+
SQLite. Best-effort: a failed write only means the guard keeps its old
|
|
1004
|
+
behaviour.
|
|
1005
|
+
"""
|
|
1006
|
+
try:
|
|
1007
|
+
marker = _context_reset_marker(session_id, snapshot_dir)
|
|
1008
|
+
if marker is None:
|
|
1009
|
+
return
|
|
1010
|
+
marker.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
1011
|
+
marker.write_text(repr(time.time()), encoding="utf-8")
|
|
1012
|
+
except OSError:
|
|
1013
|
+
pass
|
|
1014
|
+
|
|
1015
|
+
|
|
1016
|
+
def context_reset_at(session_id: str, snapshot_dir: Optional[Path] = None) -> float:
|
|
1017
|
+
"""Epoch seconds of the session's last context reset, or 0.0 if none."""
|
|
1018
|
+
try:
|
|
1019
|
+
marker = _context_reset_marker(session_id, snapshot_dir)
|
|
1020
|
+
if marker is None:
|
|
1021
|
+
return 0.0
|
|
1022
|
+
return float(marker.read_text(encoding="utf-8").strip())
|
|
1023
|
+
except (OSError, ValueError):
|
|
1024
|
+
return 0.0
|
|
1025
|
+
|
|
1026
|
+
|
|
963
1027
|
def cleanup_old_stores(max_age_hours: int = CLEANUP_AGE_HOURS) -> int:
|
|
964
1028
|
"""Delete session store DBs older than max_age_hours. Returns count deleted."""
|
|
965
1029
|
if not SESSION_STORE_DIR.exists():
|