@alexgreensh/token-optimizer 5.13.57 → 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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/hooks.json +16 -16
- package/hooks/python-launcher.sh +10 -0
- package/hooks/stop_runner.py +27 -4
- package/hooks/windows-launcher.py +57 -3
- package/package.json +1 -1
- package/skills/fleet-auditor/scripts/shared.py +29 -1
- package/skills/token-optimizer/pricing/prices.json +13 -1
- package/skills/token-optimizer/scripts/codex_doctor.py +78 -1
- package/skills/token-optimizer/scripts/codex_install.py +379 -41
- package/skills/token-optimizer/scripts/codex_session.py +38 -8
- package/skills/token-optimizer/scripts/copilot_doctor.py +129 -6
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +62 -14
- package/skills/token-optimizer/scripts/copilot_install.py +56 -4
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +18 -4
- package/skills/token-optimizer/scripts/deterministic_candidates.py +55 -15
- package/skills/token-optimizer/scripts/devin_source.py +1 -1
- package/skills/token-optimizer/scripts/hermes_doctor.py +177 -1
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +190 -0
- package/skills/token-optimizer/scripts/hermes_install.py +43 -0
- package/skills/token-optimizer/scripts/hermes_session.py +133 -0
- package/skills/token-optimizer/scripts/hermes_state.py +58 -0
- package/skills/token-optimizer/scripts/hermes_tool_hooks.py +291 -0
- package/skills/token-optimizer/scripts/measure.py +1302 -319
- package/skills/token-optimizer/scripts/plugin_env.py +18 -0
- package/skills/token-optimizer/scripts/recovery_output.py +15 -2
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +36 -1
- package/skills/token-optimizer/scripts/runtime_env.py +5 -1
|
@@ -90,6 +90,7 @@ import tempfile
|
|
|
90
90
|
import textwrap
|
|
91
91
|
import time
|
|
92
92
|
import types
|
|
93
|
+
import unicodedata
|
|
93
94
|
import platform
|
|
94
95
|
import posixpath
|
|
95
96
|
import shutil
|
|
@@ -148,6 +149,13 @@ def _redirect_bytecode_out_of_repo():
|
|
|
148
149
|
# main-guard line must appear only once in this file, see below.)
|
|
149
150
|
if __name__ in ("__main__",):
|
|
150
151
|
_redirect_bytecode_out_of_repo()
|
|
152
|
+
# A leading `--runtime NAME` must reach the environment BEFORE plugin_env
|
|
153
|
+
# (imported just below) fixes its data directories from the active
|
|
154
|
+
# runtime at import. Applied later, the flag changed hints but every
|
|
155
|
+
# archive, checkpoint and trends path still pointed at the default
|
|
156
|
+
# runtime (`measure.py --runtime hermes expand <id>` found nothing).
|
|
157
|
+
from runtime_env import consume_runtime_flag as _consume_runtime_flag_early
|
|
158
|
+
sys.argv[:] = _consume_runtime_flag_early(sys.argv, os.environ)
|
|
151
159
|
|
|
152
160
|
from hook_io import read_stdin_hook_input as _read_stdin_hook_input_shared
|
|
153
161
|
from hook_runtime import (
|
|
@@ -2102,6 +2110,178 @@ def _safe_int(value):
|
|
|
2102
2110
|
return 0
|
|
2103
2111
|
|
|
2104
2112
|
|
|
2113
|
+
def _context_usage(usage):
|
|
2114
|
+
"""Select live executor usage, leaving aggregate usage for billing.
|
|
2115
|
+
|
|
2116
|
+
Advisor/server-tool responses can sum several executor reads in the
|
|
2117
|
+
top-level usage. Only the final message iteration describes occupancy.
|
|
2118
|
+
An unusable final executor falls back to the aggregate, never an older
|
|
2119
|
+
executor (which may describe a different context). Ignore advisor tails.
|
|
2120
|
+
"""
|
|
2121
|
+
if isinstance(usage, dict) and isinstance(usage.get("iterations"), list):
|
|
2122
|
+
for iteration in reversed(usage["iterations"]):
|
|
2123
|
+
if isinstance(iteration, dict) and iteration.get("type") == "message":
|
|
2124
|
+
if (_valid_context_usage(iteration)
|
|
2125
|
+
and _context_token_count(iteration) > 0):
|
|
2126
|
+
return iteration
|
|
2127
|
+
break
|
|
2128
|
+
return usage
|
|
2129
|
+
|
|
2130
|
+
|
|
2131
|
+
def _valid_context_usage(usage):
|
|
2132
|
+
"""Reject corrupt present executor buckets before lossy int coercion.
|
|
2133
|
+
|
|
2134
|
+
Missing buckets are optional. TTL splits matter only when the flat
|
|
2135
|
+
cache-write count is absent or zero, matching _context_token_count.
|
|
2136
|
+
"""
|
|
2137
|
+
values = [usage[key] for key in ("input_tokens", "cache_read_input_tokens",
|
|
2138
|
+
"cache_creation_input_tokens") if key in usage]
|
|
2139
|
+
if not _safe_int(usage.get("cache_creation_input_tokens")):
|
|
2140
|
+
nested = usage.get("cache_creation", {})
|
|
2141
|
+
if not isinstance(nested, dict):
|
|
2142
|
+
return False
|
|
2143
|
+
for key in ("ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"):
|
|
2144
|
+
if key in nested:
|
|
2145
|
+
values.append(nested[key])
|
|
2146
|
+
if not nested.get(key) and key in usage:
|
|
2147
|
+
values.append(usage[key])
|
|
2148
|
+
try:
|
|
2149
|
+
return all(math.isfinite(float(value)) and float(value) >= 0
|
|
2150
|
+
for value in values)
|
|
2151
|
+
except (TypeError, ValueError, OverflowError):
|
|
2152
|
+
return False
|
|
2153
|
+
|
|
2154
|
+
|
|
2155
|
+
def _resume_usage(usage):
|
|
2156
|
+
"""The first executor tests whether the cache survived the pause.
|
|
2157
|
+
|
|
2158
|
+
Later executors may read cache written earlier in this same response;
|
|
2159
|
+
that is not evidence that a keep-warm ping avoided the initial rewrite.
|
|
2160
|
+
Unusable first-executor data keeps the aggregate comparison, not a later
|
|
2161
|
+
executor that could hide a paid rewrite.
|
|
2162
|
+
"""
|
|
2163
|
+
if isinstance(usage, dict) and isinstance(usage.get("iterations"), list):
|
|
2164
|
+
for iteration in usage["iterations"]:
|
|
2165
|
+
if isinstance(iteration, dict) and iteration.get("type") == "message":
|
|
2166
|
+
if (_valid_context_usage(iteration)
|
|
2167
|
+
and _context_token_count(iteration) > 0):
|
|
2168
|
+
return iteration
|
|
2169
|
+
break
|
|
2170
|
+
return usage
|
|
2171
|
+
|
|
2172
|
+
|
|
2173
|
+
_USAGE_BUCKET_KEYS = ("inp", "out", "cr", "cc", "cc_1h", "cc_5m")
|
|
2174
|
+
|
|
2175
|
+
|
|
2176
|
+
def _usage_buckets(usage):
|
|
2177
|
+
"""Billing buckets of one usage dict (or iteration), never raising."""
|
|
2178
|
+
if not isinstance(usage, dict):
|
|
2179
|
+
return dict.fromkeys(_USAGE_BUCKET_KEYS, 0)
|
|
2180
|
+
nested = usage.get("cache_creation", {})
|
|
2181
|
+
if not isinstance(nested, dict):
|
|
2182
|
+
nested = {}
|
|
2183
|
+
cc_1h = _safe_int(nested.get("ephemeral_1h_input_tokens", 0)
|
|
2184
|
+
or usage.get("ephemeral_1h_input_tokens", 0))
|
|
2185
|
+
cc_5m = _safe_int(nested.get("ephemeral_5m_input_tokens", 0)
|
|
2186
|
+
or usage.get("ephemeral_5m_input_tokens", 0))
|
|
2187
|
+
return {
|
|
2188
|
+
"inp": max(0, _safe_int(usage.get("input_tokens", 0))),
|
|
2189
|
+
"out": max(0, _safe_int(usage.get("output_tokens", 0))),
|
|
2190
|
+
"cr": max(0, _safe_int(usage.get("cache_read_input_tokens", 0))),
|
|
2191
|
+
"cc": max(0, _safe_int(usage.get("cache_creation_input_tokens", 0))
|
|
2192
|
+
or (cc_1h + cc_5m)),
|
|
2193
|
+
"cc_1h": max(0, cc_1h),
|
|
2194
|
+
"cc_5m": max(0, cc_5m),
|
|
2195
|
+
}
|
|
2196
|
+
|
|
2197
|
+
|
|
2198
|
+
def _billed_usage_parts(usage, model, tier=None):
|
|
2199
|
+
"""Split one response's usage into [(price_model, buckets), ...].
|
|
2200
|
+
|
|
2201
|
+
The first part is the executor (priced at the response model). Advisor
|
|
2202
|
+
iterations (type "advisor_message") run on the advisor's own model, so
|
|
2203
|
+
each becomes its own part priced at that model when the rate card knows
|
|
2204
|
+
it, else at the executor model. Tokens are never dropped: when the
|
|
2205
|
+
top-level usage already covers the advisor tokens they are moved out of
|
|
2206
|
+
the executor part, otherwise (the documented shape, top-level is the
|
|
2207
|
+
executor sum only) they are added on top.
|
|
2208
|
+
"""
|
|
2209
|
+
agg = _usage_buckets(usage)
|
|
2210
|
+
iterations = usage.get("iterations") if isinstance(usage, dict) else None
|
|
2211
|
+
if not isinstance(iterations, list):
|
|
2212
|
+
return [(model, agg)]
|
|
2213
|
+
executor_sum = dict.fromkeys(_USAGE_BUCKET_KEYS, 0)
|
|
2214
|
+
advisor_sum = dict.fromkeys(_USAGE_BUCKET_KEYS, 0)
|
|
2215
|
+
advisors = []
|
|
2216
|
+
for iteration in iterations:
|
|
2217
|
+
if not isinstance(iteration, dict):
|
|
2218
|
+
continue
|
|
2219
|
+
kind = iteration.get("type")
|
|
2220
|
+
if kind == "message":
|
|
2221
|
+
for k, v in _usage_buckets(iteration).items():
|
|
2222
|
+
executor_sum[k] += v
|
|
2223
|
+
elif kind == "advisor_message":
|
|
2224
|
+
buckets = _usage_buckets(iteration)
|
|
2225
|
+
if not any(buckets.values()):
|
|
2226
|
+
continue
|
|
2227
|
+
adv_model = iteration.get("model")
|
|
2228
|
+
if not (isinstance(adv_model, str) and adv_model
|
|
2229
|
+
and _is_priced_model(adv_model, tier)):
|
|
2230
|
+
adv_model = model
|
|
2231
|
+
advisors.append((adv_model, buckets))
|
|
2232
|
+
for k, v in buckets.items():
|
|
2233
|
+
advisor_sum[k] += v
|
|
2234
|
+
if not advisors:
|
|
2235
|
+
return [(model, agg)]
|
|
2236
|
+
executor = dict(agg)
|
|
2237
|
+
if all(agg[k] >= executor_sum[k] + advisor_sum[k] for k in _USAGE_BUCKET_KEYS):
|
|
2238
|
+
executor = {k: agg[k] - advisor_sum[k] for k in _USAGE_BUCKET_KEYS}
|
|
2239
|
+
return [(model, executor)] + advisors
|
|
2240
|
+
|
|
2241
|
+
|
|
2242
|
+
def _price_usage_parts(parts, tier=None, per_request=False, ttl_split=True):
|
|
2243
|
+
"""USD for _billed_usage_parts output; cache writes priced by TTL split."""
|
|
2244
|
+
total = 0.0
|
|
2245
|
+
for part_model, b in parts:
|
|
2246
|
+
if ttl_split and (b["cc_1h"] or b["cc_5m"]):
|
|
2247
|
+
total += _get_model_cost(part_model, b["inp"], b["out"], b["cr"], b["cc"],
|
|
2248
|
+
tier=tier, cache_create_1h=b["cc_1h"],
|
|
2249
|
+
cache_create_5m=b["cc_5m"], per_request=per_request)
|
|
2250
|
+
else:
|
|
2251
|
+
total += _get_model_cost(part_model, b["inp"], b["out"], b["cr"], b["cc"],
|
|
2252
|
+
tier=tier, per_request=per_request)
|
|
2253
|
+
return total
|
|
2254
|
+
|
|
2255
|
+
|
|
2256
|
+
def _turn_prefix_cached(turn):
|
|
2257
|
+
"""Cached prefix a turn leaves behind: final executor when known (#287)."""
|
|
2258
|
+
if "ctx_cache" in turn:
|
|
2259
|
+
return max(0, _safe_int(turn.get("ctx_cache")))
|
|
2260
|
+
return _safe_int(turn.get("cache_read")) + _safe_int(turn.get("cache_creation"))
|
|
2261
|
+
|
|
2262
|
+
|
|
2263
|
+
def _turn_resume_write(turn):
|
|
2264
|
+
"""Cache written when a turn starts: first executor when known (#287)."""
|
|
2265
|
+
if "resume_cache_creation" in turn:
|
|
2266
|
+
return max(0, _safe_int(turn.get("resume_cache_creation")))
|
|
2267
|
+
return _safe_int(turn.get("cache_creation"))
|
|
2268
|
+
|
|
2269
|
+
|
|
2270
|
+
def _context_token_count(usage):
|
|
2271
|
+
"""Input footprint, including flat or TTL-split cache writes."""
|
|
2272
|
+
if not isinstance(usage, dict):
|
|
2273
|
+
return 0
|
|
2274
|
+
creation = _safe_int(usage.get("cache_creation_input_tokens"))
|
|
2275
|
+
if not creation:
|
|
2276
|
+
nested = usage.get("cache_creation")
|
|
2277
|
+
if not isinstance(nested, dict):
|
|
2278
|
+
nested = {}
|
|
2279
|
+
creation = sum(_safe_int(nested.get(key) or usage.get(key)) for key in (
|
|
2280
|
+
"ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"))
|
|
2281
|
+
return (_safe_int(usage.get("input_tokens"))
|
|
2282
|
+
+ _safe_int(usage.get("cache_read_input_tokens")) + creation)
|
|
2283
|
+
|
|
2284
|
+
|
|
2105
2285
|
def estimate_tokens_from_file(filepath):
|
|
2106
2286
|
"""Estimate tokens by reading file content (character count / 4)."""
|
|
2107
2287
|
try:
|
|
@@ -2354,12 +2534,9 @@ def get_session_baselines(limit=10):
|
|
|
2354
2534
|
if "message" in data and isinstance(data["message"], dict):
|
|
2355
2535
|
msg = data["message"]
|
|
2356
2536
|
if "usage" in msg:
|
|
2357
|
-
|
|
2358
|
-
first_usage = (
|
|
2359
|
-
|
|
2360
|
-
+ u.get("cache_creation_input_tokens", 0)
|
|
2361
|
-
+ u.get("cache_read_input_tokens", 0)
|
|
2362
|
-
)
|
|
2537
|
+
# Context size, not the advisor-summed bill (#287).
|
|
2538
|
+
first_usage = _context_token_count(
|
|
2539
|
+
_context_usage(msg["usage"]))
|
|
2363
2540
|
break
|
|
2364
2541
|
except (json.JSONDecodeError, KeyError, TypeError):
|
|
2365
2542
|
continue
|
|
@@ -7166,9 +7343,16 @@ def _collect_copilot_hook_status_for_dashboard():
|
|
|
7166
7343
|
return {
|
|
7167
7344
|
"copilot_hooks": {
|
|
7168
7345
|
"installed": _ok("TO hook config"),
|
|
7169
|
-
|
|
7346
|
+
# Installed stays tied to the hook config; a dead legacy `stop` entry
|
|
7347
|
+
# or a bridge that cannot find measure.py (session-end refresh paused), or a
|
|
7348
|
+
# damaged hook payload (missing bridge modules) is installed-but-partial,
|
|
7349
|
+
# not healthy.
|
|
7350
|
+
"partial": any(
|
|
7351
|
+
by_name.get(n, {}).get("status") == "warn"
|
|
7352
|
+
for n in ("TO hook config", "TO session-end hook", "session-end refresh")
|
|
7353
|
+
) or by_name.get("hook payload", {}).get("status") in ("warn", "fail"),
|
|
7170
7354
|
"label": "Copilot CLI Hooks",
|
|
7171
|
-
"description": "Wires Token Optimizer into ~/.copilot/hooks/: sessionStart continuity restore, preToolUse bash compression (capability-gated), postToolUse crash-recovery tally + nudges,
|
|
7355
|
+
"description": "Wires Token Optimizer into ~/.copilot/hooks/: sessionStart continuity restore, preToolUse bash compression (capability-gated), postToolUse crash-recovery tally + nudges, session-end rollup.",
|
|
7172
7356
|
"install_cmd": install_cmd,
|
|
7173
7357
|
"uninstall_cmd": f"{_runtime_cli('copilot')} copilot-uninstall",
|
|
7174
7358
|
},
|
|
@@ -8737,6 +8921,59 @@ def _session_refresh_due(min_interval_seconds=120):
|
|
|
8737
8921
|
HOOK_STATUS_FILE = RUNTIME_DIR / "token-optimizer" / "hook-status.json"
|
|
8738
8922
|
|
|
8739
8923
|
|
|
8924
|
+
def _pid_is_running(pid):
|
|
8925
|
+
"""True when process ``pid`` exists, on every OS. Never raises.
|
|
8926
|
+
|
|
8927
|
+
``os.kill(pid, 0)`` is a liveness probe only on POSIX. On Windows signal 0
|
|
8928
|
+
is CTRL_C_EVENT: Python calls GenerateConsoleCtrlEvent, which fails for
|
|
8929
|
+
any pid when the caller has no console (hooks run detached, so a live lock
|
|
8930
|
+
owner read as dead) and, with a console, interrupts the whole console
|
|
8931
|
+
group. Windows asks the process table instead. When the answer is unknown
|
|
8932
|
+
the process counts as running, so a lock is never stolen from a live owner.
|
|
8933
|
+
"""
|
|
8934
|
+
try:
|
|
8935
|
+
pid = int(pid)
|
|
8936
|
+
except (TypeError, ValueError):
|
|
8937
|
+
return False
|
|
8938
|
+
if pid <= 0:
|
|
8939
|
+
return False
|
|
8940
|
+
if os.name == "nt":
|
|
8941
|
+
return _win_pid_is_running(pid)
|
|
8942
|
+
try:
|
|
8943
|
+
os.kill(pid, 0)
|
|
8944
|
+
except ProcessLookupError:
|
|
8945
|
+
return False
|
|
8946
|
+
except PermissionError:
|
|
8947
|
+
return True # exists, owned by someone else
|
|
8948
|
+
except OSError:
|
|
8949
|
+
return False
|
|
8950
|
+
return True
|
|
8951
|
+
|
|
8952
|
+
|
|
8953
|
+
def _win_pid_is_running(pid):
|
|
8954
|
+
try:
|
|
8955
|
+
import ctypes
|
|
8956
|
+
from ctypes import wintypes
|
|
8957
|
+
|
|
8958
|
+
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
8959
|
+
kernel32.OpenProcess.restype = wintypes.HANDLE
|
|
8960
|
+
kernel32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
|
|
8961
|
+
handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
|
|
8962
|
+
if not handle:
|
|
8963
|
+
# 5 = access denied: the process exists but is not ours.
|
|
8964
|
+
# 87 = invalid parameter: no such process.
|
|
8965
|
+
return ctypes.get_last_error() != 87
|
|
8966
|
+
try:
|
|
8967
|
+
code = wintypes.DWORD()
|
|
8968
|
+
if not kernel32.GetExitCodeProcess(handle, ctypes.byref(code)):
|
|
8969
|
+
return True
|
|
8970
|
+
return code.value == 259 # STILL_ACTIVE
|
|
8971
|
+
finally:
|
|
8972
|
+
kernel32.CloseHandle(handle)
|
|
8973
|
+
except Exception:
|
|
8974
|
+
return True
|
|
8975
|
+
|
|
8976
|
+
|
|
8740
8977
|
def _record_hook_status(key, result):
|
|
8741
8978
|
"""Remember the last outcome of a background hook job, for the doctor.
|
|
8742
8979
|
|
|
@@ -8760,6 +8997,39 @@ def _record_hook_status(key, result):
|
|
|
8760
8997
|
pass
|
|
8761
8998
|
|
|
8762
8999
|
|
|
9000
|
+
def _flush_capture_checkpoint(args):
|
|
9001
|
+
"""The checkpoint step of the deferred Stop/SessionEnd flush worker.
|
|
9002
|
+
|
|
9003
|
+
The worker has no stdin, so the Stop runner hands it the session identity
|
|
9004
|
+
the host gave the hook as ``--session-id`` / ``--transcript-path``. On Codex
|
|
9005
|
+
with no identity from the host or the environment, no checkpoint is
|
|
9006
|
+
written: an anonymous "unknown" file can outrank real ones on restore
|
|
9007
|
+
(issue #278). Returns the checkpoint path or None.
|
|
9008
|
+
"""
|
|
9009
|
+
flush_trigger = "end"
|
|
9010
|
+
sid = None
|
|
9011
|
+
transcript = None
|
|
9012
|
+
for i, a in enumerate(args):
|
|
9013
|
+
if a == "--trigger" and i + 1 < len(args):
|
|
9014
|
+
flush_trigger = args[i + 1]
|
|
9015
|
+
elif a == "--session-id" and i + 1 < len(args):
|
|
9016
|
+
sid = args[i + 1]
|
|
9017
|
+
elif a == "--transcript-path" and i + 1 < len(args):
|
|
9018
|
+
transcript = args[i + 1]
|
|
9019
|
+
if (_use_codex_session_adapter() and not sid and not transcript
|
|
9020
|
+
and _find_current_session_jsonl() is None):
|
|
9021
|
+
_record_hook_status(
|
|
9022
|
+
"stop_capture",
|
|
9023
|
+
"skipped: the Stop hook payload and environment carried no session id")
|
|
9024
|
+
return None
|
|
9025
|
+
path = compact_capture(trigger=flush_trigger, backfill_tools=True,
|
|
9026
|
+
session_id=sid, transcript_path=transcript)
|
|
9027
|
+
_record_hook_status(
|
|
9028
|
+
"stop_capture",
|
|
9029
|
+
"ok: checkpoint written" if path else "no checkpoint written (session transcript not found)")
|
|
9030
|
+
return path
|
|
9031
|
+
|
|
9032
|
+
|
|
8763
9033
|
def _run_session_end_flush_worker(args, budget_seconds=20):
|
|
8764
9034
|
"""Run heavyweight Stop-hook work outside Codex's visible hook budget.
|
|
8765
9035
|
|
|
@@ -8844,11 +9114,7 @@ def _run_session_end_flush_worker(args, budget_seconds=20):
|
|
|
8844
9114
|
except Exception:
|
|
8845
9115
|
pass
|
|
8846
9116
|
try:
|
|
8847
|
-
|
|
8848
|
-
for i, a in enumerate(args):
|
|
8849
|
-
if a == "--trigger" and i + 1 < len(args):
|
|
8850
|
-
flush_trigger = args[i + 1]
|
|
8851
|
-
compact_capture(trigger=flush_trigger, backfill_tools=True)
|
|
9117
|
+
_flush_capture_checkpoint(args)
|
|
8852
9118
|
except Exception:
|
|
8853
9119
|
pass
|
|
8854
9120
|
# Data-retention enforcement (enterprise compliance)
|
|
@@ -10432,7 +10698,8 @@ def _deterministic_candidates_data(days=30, budget_s=_DETCAND_COACH_BUDGET_S,
|
|
|
10432
10698
|
if _sidechain_path_reason(jf) is None]
|
|
10433
10699
|
return deterministic_candidates.run(
|
|
10434
10700
|
runtime, files, price, days=days, budget_s=budget_s, max_sessions=max_sessions,
|
|
10435
|
-
cache_dir=SNAPSHOT_DIR, tier=tier, use_cache=use_cache, progress=progress
|
|
10701
|
+
cache_dir=SNAPSHOT_DIR, tier=tier, use_cache=use_cache, progress=progress,
|
|
10702
|
+
split_usage=lambda model, usage: _billed_usage_parts(usage, model, tier=tier))
|
|
10436
10703
|
except Exception as exc: # never break coach --json
|
|
10437
10704
|
return {"status": "error", "runtime": runtime, "partial": True, "candidates": [],
|
|
10438
10705
|
"basis": deterministic_candidates.BASIS,
|
|
@@ -11825,21 +12092,14 @@ def _extract_costly_prompts(jsonl_path, tier=None, top_n=5):
|
|
|
11825
12092
|
if is_sidechain:
|
|
11826
12093
|
continue
|
|
11827
12094
|
content = msg.get("content") if isinstance(msg, dict) else msg
|
|
11828
|
-
|
|
11829
|
-
if isinstance(content, str):
|
|
11830
|
-
text = content
|
|
11831
|
-
elif isinstance(content, list):
|
|
12095
|
+
if isinstance(content, list):
|
|
11832
12096
|
# Skip if all items are tool_result
|
|
11833
12097
|
types = [i.get("type") for i in content if isinstance(i, dict)]
|
|
11834
12098
|
if types and all(t == "tool_result" for t in types):
|
|
11835
12099
|
continue
|
|
11836
|
-
|
|
11837
|
-
|
|
11838
|
-
|
|
11839
|
-
break
|
|
11840
|
-
elif isinstance(block, str):
|
|
11841
|
-
text = block
|
|
11842
|
-
break
|
|
12100
|
+
# Same filter as checkpoints: harness text (meta records,
|
|
12101
|
+
# compact summaries, command caveats) is not a prompt.
|
|
12102
|
+
text = _task_user_text(record)
|
|
11843
12103
|
if text and len(text) > 5:
|
|
11844
12104
|
pending_prompt = {
|
|
11845
12105
|
"text": text[:300],
|
|
@@ -11857,8 +12117,9 @@ def _extract_costly_prompts(jsonl_path, tier=None, top_n=5):
|
|
|
11857
12117
|
cr = _safe_int(usage.get("cache_read_input_tokens", 0))
|
|
11858
12118
|
cc = _safe_int(usage.get("cache_creation_input_tokens", 0))
|
|
11859
12119
|
model = _record_model(msg)
|
|
11860
|
-
cost =
|
|
11861
|
-
|
|
12120
|
+
cost = _price_usage_parts(
|
|
12121
|
+
_billed_usage_parts(usage, model, tier=tier),
|
|
12122
|
+
tier=tier, per_request=True, ttl_split=False)
|
|
11862
12123
|
pending_prompt["tokens_in"] = inp + cr + cc
|
|
11863
12124
|
pending_prompt["tokens_out"] = out
|
|
11864
12125
|
pending_prompt["fresh_input"] = inp
|
|
@@ -12198,22 +12459,10 @@ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
|
|
|
12198
12459
|
|
|
12199
12460
|
rec_type = record.get("type")
|
|
12200
12461
|
|
|
12201
|
-
#
|
|
12462
|
+
# Topic and checkpoint task share a human-task-only view. Keep
|
|
12463
|
+
# raw user text for message scoring and slash-skill accounting.
|
|
12202
12464
|
if rec_type == "user" and topic is None:
|
|
12203
|
-
|
|
12204
|
-
content = msg.get("content") if isinstance(msg, dict) else msg
|
|
12205
|
-
if isinstance(content, str):
|
|
12206
|
-
topic = _extract_topic(content)
|
|
12207
|
-
elif isinstance(content, list):
|
|
12208
|
-
for block in content:
|
|
12209
|
-
if isinstance(block, dict) and block.get("type") == "text":
|
|
12210
|
-
topic = _extract_topic(block.get("text", ""))
|
|
12211
|
-
if topic:
|
|
12212
|
-
break
|
|
12213
|
-
elif isinstance(block, str):
|
|
12214
|
-
topic = _extract_topic(block)
|
|
12215
|
-
if topic:
|
|
12216
|
-
break
|
|
12465
|
+
topic = _extract_topic(_task_user_text(record))
|
|
12217
12466
|
|
|
12218
12467
|
if rec_type in ("user", "assistant"):
|
|
12219
12468
|
_conversation_records += 1
|
|
@@ -12256,6 +12505,8 @@ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
|
|
|
12256
12505
|
isinstance(b, dict) and b.get("type") == "tool_result" for b in _c
|
|
12257
12506
|
):
|
|
12258
12507
|
pass # tool output, not a human turn
|
|
12508
|
+
elif record.get("isMeta") or record.get("isCompactSummary"):
|
|
12509
|
+
pass # harness-written, not a human turn
|
|
12259
12510
|
else:
|
|
12260
12511
|
message_count += 1
|
|
12261
12512
|
|
|
@@ -12355,26 +12606,31 @@ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
|
|
|
12355
12606
|
# each other — use the map's own size as a monotonic
|
|
12356
12607
|
# per-session counter.
|
|
12357
12608
|
key = req_id if req_id else f"__noreq__{len(request_usage_map)}"
|
|
12358
|
-
|
|
12359
|
-
|
|
12360
|
-
|
|
12361
|
-
|
|
12362
|
-
|
|
12363
|
-
|
|
12364
|
-
|
|
12365
|
-
|
|
12366
|
-
|
|
12367
|
-
|
|
12368
|
-
|
|
12369
|
-
|
|
12370
|
-
|
|
12371
|
-
|
|
12372
|
-
|
|
12373
|
-
|
|
12374
|
-
|
|
12375
|
-
|
|
12376
|
-
|
|
12377
|
-
|
|
12609
|
+
# Advisor iterations bill at the advisor's own model:
|
|
12610
|
+
# each is a separate entry under "<request>#advisor<n>"
|
|
12611
|
+
# so streamed copies still dedup by MAX per entry.
|
|
12612
|
+
parts = _billed_usage_parts(usage, model)
|
|
12613
|
+
for part_index, (part_model, b) in enumerate(parts):
|
|
12614
|
+
part_key = key if part_index == 0 else f"{key}#advisor{part_index}"
|
|
12615
|
+
prev = request_usage_map.get(part_key)
|
|
12616
|
+
if prev is None:
|
|
12617
|
+
request_usage_map[part_key] = {
|
|
12618
|
+
"inp": b["inp"], "out": b["out"], "cr": b["cr"],
|
|
12619
|
+
"cc": b["cc"], "cc_1h": b["cc_1h"],
|
|
12620
|
+
"cc_5m": b["cc_5m"], "model": part_model,
|
|
12621
|
+
"ts": ts_str,
|
|
12622
|
+
}
|
|
12623
|
+
if part_index:
|
|
12624
|
+
request_usage_map[part_key]["advisor"] = True
|
|
12625
|
+
else:
|
|
12626
|
+
# Streaming: keep MAX of each token category.
|
|
12627
|
+
# Model + timestamp: prefer later (non-empty) values.
|
|
12628
|
+
for field in _USAGE_BUCKET_KEYS:
|
|
12629
|
+
prev[field] = max(prev[field], b[field])
|
|
12630
|
+
if part_model and part_model != "unknown":
|
|
12631
|
+
prev["model"] = part_model
|
|
12632
|
+
if ts_str:
|
|
12633
|
+
prev["ts"] = ts_str
|
|
12378
12634
|
|
|
12379
12635
|
except (PermissionError, OSError):
|
|
12380
12636
|
return None
|
|
@@ -12401,9 +12657,11 @@ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
|
|
|
12401
12657
|
total_cache_create += u["cc"]
|
|
12402
12658
|
total_cache_create_1h += u["cc_1h"]
|
|
12403
12659
|
total_cache_create_5m += u["cc_5m"]
|
|
12404
|
-
api_calls += 1
|
|
12405
12660
|
ts_s = u.get("ts")
|
|
12406
|
-
if
|
|
12661
|
+
if not u.get("advisor"):
|
|
12662
|
+
# An advisor part belongs to its request: not another API call.
|
|
12663
|
+
api_calls += 1
|
|
12664
|
+
if ts_s and isinstance(ts_s, str) and not u.get("advisor"):
|
|
12407
12665
|
try:
|
|
12408
12666
|
api_call_timestamps.append(datetime.fromisoformat(ts_s.replace("Z", "+00:00")))
|
|
12409
12667
|
except (ValueError, TypeError):
|
|
@@ -12599,14 +12857,8 @@ def parse_session_turns(filepath):
|
|
|
12599
12857
|
prev_call_ts = call_ts
|
|
12600
12858
|
except (ValueError, TypeError):
|
|
12601
12859
|
pass
|
|
12602
|
-
|
|
12603
|
-
|
|
12604
|
-
cost = _get_model_cost(model, inp_tok, out_tok, cr, cc, tier=tier,
|
|
12605
|
-
cache_create_1h=cc_1h, cache_create_5m=cc_5m,
|
|
12606
|
-
per_request=True)
|
|
12607
|
-
else:
|
|
12608
|
-
cost = _get_model_cost(model, inp_tok, out_tok, cr, cc, tier=tier,
|
|
12609
|
-
per_request=True)
|
|
12860
|
+
cost = _price_usage_parts(_billed_usage_parts(usage, model, tier=tier),
|
|
12861
|
+
tier=tier, per_request=True)
|
|
12610
12862
|
|
|
12611
12863
|
turns.append({
|
|
12612
12864
|
"turn_index": turn_index,
|
|
@@ -12623,6 +12875,22 @@ def parse_session_turns(filepath):
|
|
|
12623
12875
|
"tools_used": tools,
|
|
12624
12876
|
"cost_usd": round(cost, 6),
|
|
12625
12877
|
})
|
|
12878
|
+
ctx_usage = _context_usage(usage)
|
|
12879
|
+
if ctx_usage is not usage:
|
|
12880
|
+
# Cached prefix the next turn can reuse: the final executor
|
|
12881
|
+
# only, matching the live keep-warm arm (#287).
|
|
12882
|
+
turns[-1]["ctx_cache"] = (
|
|
12883
|
+
_context_token_count(ctx_usage)
|
|
12884
|
+
- _safe_int(ctx_usage.get("input_tokens")))
|
|
12885
|
+
resume_usage = _resume_usage(usage)
|
|
12886
|
+
if resume_usage is not usage:
|
|
12887
|
+
# Billing stays aggregate; pause warmth uses the first
|
|
12888
|
+
# executor, before any cache writes inside this response.
|
|
12889
|
+
resume_read = _safe_int(resume_usage.get("cache_read_input_tokens"))
|
|
12890
|
+
turns[-1]["resume_cache_read"] = resume_read
|
|
12891
|
+
turns[-1]["resume_cache_creation"] = (
|
|
12892
|
+
_context_token_count(resume_usage) - resume_read
|
|
12893
|
+
- _safe_int(resume_usage.get("input_tokens")))
|
|
12626
12894
|
turn_index += 1
|
|
12627
12895
|
|
|
12628
12896
|
except (PermissionError, OSError):
|
|
@@ -13417,6 +13685,32 @@ def _origin_insert_parts(conn, table):
|
|
|
13417
13685
|
return "", "", ()
|
|
13418
13686
|
|
|
13419
13687
|
|
|
13688
|
+
def _claude_projects_like_patterns() -> tuple:
|
|
13689
|
+
"""Prefix LIKE patterns (ESCAPE '!') for transcripts under the resolved
|
|
13690
|
+
Claude config's projects/ dir, or () when that is the default ~/.claude
|
|
13691
|
+
(the literal pattern already covers it) or unresolvable.
|
|
13692
|
+
|
|
13693
|
+
Anchored at the start of the path, so a "copilot:"/"hermes:" dedup key or
|
|
13694
|
+
a path that merely contains the folder name further down never matches.
|
|
13695
|
+
Forward slashes only: callers match it against _PLATFORM_PATH_SQL, which
|
|
13696
|
+
folds the backslashes of rows written on Windows to forward slashes.
|
|
13697
|
+
"""
|
|
13698
|
+
try:
|
|
13699
|
+
projects = Path(CLAUDE_DIR) / "projects"
|
|
13700
|
+
if projects == Path(HOME) / ".claude" / "projects":
|
|
13701
|
+
return ()
|
|
13702
|
+
form = str(projects).replace("\\", "/")
|
|
13703
|
+
esc = form.replace("!", "!!").replace("%", "!%").replace("_", "!_")
|
|
13704
|
+
return (esc + "/%",)
|
|
13705
|
+
except Exception:
|
|
13706
|
+
return ()
|
|
13707
|
+
|
|
13708
|
+
|
|
13709
|
+
# session_log.jsonl_path with Windows backslashes folded to forward slashes,
|
|
13710
|
+
# so one path pattern matches rows written on every OS (the platform backfill).
|
|
13711
|
+
_PLATFORM_PATH_SQL = "REPLACE(jsonl_path, '\\', '/')"
|
|
13712
|
+
|
|
13713
|
+
|
|
13420
13714
|
def _init_trends_db():
|
|
13421
13715
|
"""Initialize the trends SQLite DB. Returns a connection.
|
|
13422
13716
|
|
|
@@ -13586,52 +13880,47 @@ def _init_trends_db():
|
|
|
13586
13880
|
# running collector.
|
|
13587
13881
|
_platform_patterns = ("%/.claude/projects/%", "%/.codex/sessions/%", "%/.codex/archived_sessions/%",
|
|
13588
13882
|
"hermes:%", "copilot:%", "cursor:%", "antigravity:%")
|
|
13883
|
+
# A relocated Claude config (CLAUDE_CONFIG_DIR) keeps its transcripts under
|
|
13884
|
+
# <config>/projects/, which the literal ~/.claude pattern above misses.
|
|
13885
|
+
_claude_cfg_patterns = _claude_projects_like_patterns()
|
|
13886
|
+
# Paths are matched with backslashes folded to '/', so a row written on
|
|
13887
|
+
# Windows (C:\Users\me\.claude\projects\...) is tagged like a POSIX one.
|
|
13888
|
+
_p = _PLATFORM_PATH_SQL
|
|
13889
|
+
_cfg_where = " OR ".join([f"{_p} LIKE ? ESCAPE '!'"] * len(_claude_cfg_patterns))
|
|
13589
13890
|
try:
|
|
13590
13891
|
_needs_platform = conn.execute(
|
|
13591
13892
|
"SELECT 1 FROM session_log WHERE platform IS NULL AND ("
|
|
13592
|
-
+ " OR ".join(["
|
|
13593
|
-
|
|
13893
|
+
+ " OR ".join([f"{_p} LIKE ?"] * len(_platform_patterns))
|
|
13894
|
+
+ (" OR " + _cfg_where if _cfg_where else "") + ") LIMIT 1",
|
|
13895
|
+
_platform_patterns + _claude_cfg_patterns,
|
|
13594
13896
|
).fetchone()
|
|
13595
13897
|
except sqlite3.Error:
|
|
13596
13898
|
_needs_platform = True
|
|
13597
13899
|
try:
|
|
13598
13900
|
if not _needs_platform:
|
|
13599
13901
|
raise _SkipMigration
|
|
13600
|
-
|
|
13601
|
-
|
|
13602
|
-
|
|
13603
|
-
|
|
13604
|
-
|
|
13605
|
-
|
|
13606
|
-
|
|
13607
|
-
|
|
13608
|
-
|
|
13609
|
-
|
|
13610
|
-
|
|
13611
|
-
|
|
13612
|
-
|
|
13613
|
-
|
|
13614
|
-
|
|
13615
|
-
|
|
13616
|
-
|
|
13617
|
-
|
|
13618
|
-
|
|
13619
|
-
|
|
13620
|
-
|
|
13621
|
-
|
|
13622
|
-
"WHERE platform IS NULL "
|
|
13623
|
-
"AND jsonl_path LIKE 'copilot:%'"
|
|
13624
|
-
)
|
|
13625
|
-
conn.execute(
|
|
13626
|
-
"UPDATE session_log SET platform = 'cursor' "
|
|
13627
|
-
"WHERE platform IS NULL "
|
|
13628
|
-
"AND jsonl_path LIKE 'cursor:%'"
|
|
13629
|
-
)
|
|
13630
|
-
conn.execute(
|
|
13631
|
-
"UPDATE session_log SET platform = 'antigravity' "
|
|
13632
|
-
"WHERE platform IS NULL "
|
|
13633
|
-
"AND jsonl_path LIKE 'antigravity:%'"
|
|
13634
|
-
)
|
|
13902
|
+
for _platform, _pattern in (("claude", "%/.claude/projects/%"),
|
|
13903
|
+
("codex", "%/.codex/sessions/%"),
|
|
13904
|
+
("codex", "%/.codex/archived_sessions/%"),
|
|
13905
|
+
("hermes", "hermes:%"),
|
|
13906
|
+
("copilot", "copilot:%"),
|
|
13907
|
+
("cursor", "cursor:%"),
|
|
13908
|
+
("antigravity", "antigravity:%")):
|
|
13909
|
+
conn.execute(
|
|
13910
|
+
f"UPDATE session_log SET platform = ? WHERE platform IS NULL AND {_p} LIKE ?",
|
|
13911
|
+
(_platform, _pattern),
|
|
13912
|
+
)
|
|
13913
|
+
# Last, so every other runtime's definitive pattern has claimed its rows
|
|
13914
|
+
# first; the Codex path patterns are excluded again so a config dir
|
|
13915
|
+
# that happens to sit inside a Codex home can never tag a Codex file.
|
|
13916
|
+
if _cfg_where:
|
|
13917
|
+
conn.execute(
|
|
13918
|
+
"UPDATE session_log SET platform = 'claude' "
|
|
13919
|
+
"WHERE platform IS NULL AND (" + _cfg_where + ") "
|
|
13920
|
+
f"AND {_p} NOT LIKE '%/.codex/sessions/%' "
|
|
13921
|
+
f"AND {_p} NOT LIKE '%/.codex/archived_sessions/%'",
|
|
13922
|
+
_claude_cfg_patterns,
|
|
13923
|
+
)
|
|
13635
13924
|
conn.commit()
|
|
13636
13925
|
except _SkipMigration:
|
|
13637
13926
|
pass
|
|
@@ -15573,21 +15862,10 @@ def _keepwarm_prefix_proxy(usage):
|
|
|
15573
15862
|
cache_creation may be the flat int field OR a nested object (sum its ephemeral
|
|
15574
15863
|
splits). Falls back to 0 on malformed input.
|
|
15575
15864
|
"""
|
|
15865
|
+
usage = _context_usage(usage)
|
|
15576
15866
|
if not isinstance(usage, dict):
|
|
15577
15867
|
return 0
|
|
15578
|
-
|
|
15579
|
-
cc = usage.get("cache_creation_input_tokens", 0)
|
|
15580
|
-
if cc is None:
|
|
15581
|
-
cc = 0
|
|
15582
|
-
cc = int(cc or 0)
|
|
15583
|
-
if cc == 0:
|
|
15584
|
-
nested = usage.get("cache_creation", {})
|
|
15585
|
-
if isinstance(nested, dict):
|
|
15586
|
-
cc = int(
|
|
15587
|
-
(nested.get("ephemeral_1h_input_tokens", 0) or 0)
|
|
15588
|
-
+ (nested.get("ephemeral_5m_input_tokens", 0) or 0)
|
|
15589
|
-
)
|
|
15590
|
-
return cr + cc
|
|
15868
|
+
return _context_token_count(usage) - _safe_int(usage.get("input_tokens"))
|
|
15591
15869
|
|
|
15592
15870
|
|
|
15593
15871
|
def _keepwarm_iso_to_epoch(ts):
|
|
@@ -16417,6 +16695,10 @@ def _keepwarm_resolve_claude_bin():
|
|
|
16417
16695
|
Path("/usr/local/bin/claude"),
|
|
16418
16696
|
home / ".local" / "bin" / "claude",
|
|
16419
16697
|
]
|
|
16698
|
+
# Claude Code's local installer lives under its config dir, so a relocated
|
|
16699
|
+
# CLAUDE_CONFIG_DIR moves it off ~/.claude/local.
|
|
16700
|
+
if CLAUDE_DIR / "local" / "claude" not in candidates:
|
|
16701
|
+
candidates.insert(1, CLAUDE_DIR / "local" / "claude")
|
|
16420
16702
|
for cand in candidates:
|
|
16421
16703
|
try:
|
|
16422
16704
|
if cand.is_file() and os.access(str(cand), os.X_OK):
|
|
@@ -16440,13 +16722,7 @@ def _keepwarm_scheduler_install_lock(soft_fail=False):
|
|
|
16440
16722
|
max_age = 10 * 60
|
|
16441
16723
|
|
|
16442
16724
|
def _pid_alive(pid):
|
|
16443
|
-
|
|
16444
|
-
return False
|
|
16445
|
-
try:
|
|
16446
|
-
os.kill(pid, 0)
|
|
16447
|
-
return True
|
|
16448
|
-
except OSError:
|
|
16449
|
-
return False
|
|
16725
|
+
return _pid_is_running(pid)
|
|
16450
16726
|
|
|
16451
16727
|
def _try_reclaim_stale():
|
|
16452
16728
|
try:
|
|
@@ -17349,15 +17625,7 @@ def _keepwarm_acquire_ping_lock(session_id, now=None):
|
|
|
17349
17625
|
owner_pid = None
|
|
17350
17626
|
alive = False
|
|
17351
17627
|
if owner_pid and owner_pid > 0:
|
|
17352
|
-
|
|
17353
|
-
os.kill(owner_pid, 0)
|
|
17354
|
-
alive = True
|
|
17355
|
-
except ProcessLookupError:
|
|
17356
|
-
alive = False
|
|
17357
|
-
except PermissionError:
|
|
17358
|
-
alive = True # exists but not ours -> treat as live
|
|
17359
|
-
except OSError:
|
|
17360
|
-
alive = False
|
|
17628
|
+
alive = _pid_is_running(owner_pid)
|
|
17361
17629
|
if not alive and age > _KEEPWARM_STALE_LOCK_SECONDS:
|
|
17362
17630
|
try:
|
|
17363
17631
|
os.unlink(str(lock_path))
|
|
@@ -17831,15 +18099,7 @@ def _keepwarm_tick_singleton():
|
|
|
17831
18099
|
owner = None
|
|
17832
18100
|
alive = False
|
|
17833
18101
|
if owner and owner > 0:
|
|
17834
|
-
|
|
17835
|
-
os.kill(owner, 0)
|
|
17836
|
-
alive = True
|
|
17837
|
-
except ProcessLookupError:
|
|
17838
|
-
alive = False
|
|
17839
|
-
except PermissionError:
|
|
17840
|
-
alive = True
|
|
17841
|
-
except OSError:
|
|
17842
|
-
alive = False
|
|
18102
|
+
alive = _pid_is_running(owner)
|
|
17843
18103
|
if not alive and (now - st.st_mtime) > _KEEPWARM_STALE_LOCK_SECONDS:
|
|
17844
18104
|
try:
|
|
17845
18105
|
os.unlink(str(lock_path))
|
|
@@ -18218,9 +18478,10 @@ def _keepwarm_reconstruct_session_events(turns, now):
|
|
|
18218
18478
|
gap = cur_epoch - prev_epoch
|
|
18219
18479
|
if gap <= boundary:
|
|
18220
18480
|
continue
|
|
18221
|
-
|
|
18222
|
-
|
|
18223
|
-
|
|
18481
|
+
# Executor occupancy, not the advisor-summed aggregate (#287), so
|
|
18482
|
+
# replay agrees with the live arm path.
|
|
18483
|
+
prev_cached = _turn_prefix_cached(prev_turn)
|
|
18484
|
+
cc = _turn_resume_write(cur_turn)
|
|
18224
18485
|
if prev_cached <= 0:
|
|
18225
18486
|
continue
|
|
18226
18487
|
rewrote = cc >= _CACHE_REWRITE_PREFIX_FRACTION * prev_cached
|
|
@@ -18237,8 +18498,7 @@ def _keepwarm_reconstruct_session_events(turns, now):
|
|
|
18237
18498
|
})
|
|
18238
18499
|
|
|
18239
18500
|
last_epoch, last_turn = parsed[-1]
|
|
18240
|
-
last_cached = (
|
|
18241
|
-
+ int(last_turn.get("cache_creation", 0) or 0))
|
|
18501
|
+
last_cached = _turn_prefix_cached(last_turn)
|
|
18242
18502
|
tail = None
|
|
18243
18503
|
# Only a tail that idled past the boundary AND had a cacheable prefix is a
|
|
18244
18504
|
# ping candidate (matches the live arm eligibility floor downstream).
|
|
@@ -18955,8 +19215,8 @@ def keepwarm_resume_is_warm(turn, prefix_proxy):
|
|
|
18955
19215
|
prefix = 0
|
|
18956
19216
|
if prefix <= 0 or not isinstance(turn, dict):
|
|
18957
19217
|
return None
|
|
18958
|
-
cr = int(turn.get("cache_read", 0) or 0)
|
|
18959
|
-
cc = int(turn.get("cache_creation", 0) or 0)
|
|
19218
|
+
cr = int(turn.get("resume_cache_read", turn.get("cache_read", 0)) or 0)
|
|
19219
|
+
cc = int(turn.get("resume_cache_creation", turn.get("cache_creation", 0)) or 0)
|
|
18960
19220
|
warm = (cr >= _KEEPWARM_WARM_READ_FRACTION * prefix
|
|
18961
19221
|
and cc < _KEEPWARM_WARM_WRITE_FRACTION * prefix)
|
|
18962
19222
|
return bool(warm)
|
|
@@ -20955,7 +21215,9 @@ def subagent_cache_payoff(days=30, now=None, since_ts=None,
|
|
|
20955
21215
|
reqs = []
|
|
20956
21216
|
for u in (parsed.get("request_usage") or {}).values():
|
|
20957
21217
|
ts_s = u.get("ts")
|
|
20958
|
-
if not ts_s or not isinstance(ts_s, str):
|
|
21218
|
+
if u.get("advisor") or not ts_s or not isinstance(ts_s, str):
|
|
21219
|
+
# Advisor parts run on the advisor's own cache, not this
|
|
21220
|
+
# subagent's prefix.
|
|
20959
21221
|
continue
|
|
20960
21222
|
try:
|
|
20961
21223
|
ts = datetime.fromisoformat(ts_s.replace("Z", "+00:00")).timestamp()
|
|
@@ -22466,13 +22728,15 @@ def _detect_explicit_ttl(turns, tier_data, profile, dominant_model=None, detail_
|
|
|
22466
22728
|
first_write_tokens = cc
|
|
22467
22729
|
if prev is not None:
|
|
22468
22730
|
gap = turn.get("gap_since_prev_seconds")
|
|
22469
|
-
|
|
22731
|
+
# Threshold basis is executor occupancy (#287); the dollars below
|
|
22732
|
+
# stay on the billed aggregate `cc`.
|
|
22733
|
+
prev_cached = _turn_prefix_cached(prev)
|
|
22470
22734
|
if (
|
|
22471
22735
|
gap is not None
|
|
22472
22736
|
and boundary is not None
|
|
22473
22737
|
and gap > boundary
|
|
22474
22738
|
and prev_cached > 0
|
|
22475
|
-
and
|
|
22739
|
+
and _turn_resume_write(turn) >= _CACHE_REWRITE_PREFIX_FRACTION * prev_cached
|
|
22476
22740
|
):
|
|
22477
22741
|
if cc_1h or cc_5m:
|
|
22478
22742
|
split_1h = min(cc_1h, cc)
|
|
@@ -24073,6 +24337,68 @@ def _migrate_streaming_dedup(conn, quiet=False):
|
|
|
24073
24337
|
print(f" [Token Optimizer] migration failed: {e}", file=sys.stderr)
|
|
24074
24338
|
|
|
24075
24339
|
|
|
24340
|
+
def _hermes_refresh_session_totals(conn, dedup_key, parsed):
|
|
24341
|
+
"""Refresh an existing Hermes row's per-session numbers from a newer snapshot.
|
|
24342
|
+
|
|
24343
|
+
Returns True when the row was updated. The rule is monotonic: Hermes's
|
|
24344
|
+
state.db message and token counters only grow during a session, so the new
|
|
24345
|
+
snapshot wins only when it is >= the stored row on every counter and > on
|
|
24346
|
+
at least one. Quality and skills columns keep their own rules (they need a
|
|
24347
|
+
rollup's live reading) and are not touched here.
|
|
24348
|
+
"""
|
|
24349
|
+
stored = conn.execute(
|
|
24350
|
+
"SELECT message_count, input_tokens, output_tokens, api_calls "
|
|
24351
|
+
"FROM session_log WHERE jsonl_path = ?",
|
|
24352
|
+
(dedup_key,),
|
|
24353
|
+
).fetchone()
|
|
24354
|
+
if stored is None:
|
|
24355
|
+
return False
|
|
24356
|
+
new = (
|
|
24357
|
+
int(parsed.get("message_count") or 0),
|
|
24358
|
+
int(parsed.get("total_input_tokens") or 0),
|
|
24359
|
+
int(parsed.get("total_output_tokens") or 0),
|
|
24360
|
+
int(parsed.get("api_calls") or 0),
|
|
24361
|
+
)
|
|
24362
|
+
old = tuple(int(v or 0) for v in stored)
|
|
24363
|
+
if any(n < o for n, o in zip(new, old)) or new == old:
|
|
24364
|
+
return False
|
|
24365
|
+
conn.execute(
|
|
24366
|
+
"""UPDATE session_log
|
|
24367
|
+
SET duration_minutes = ?, input_tokens = ?, output_tokens = ?,
|
|
24368
|
+
message_count = ?, api_calls = ?, cache_hit_rate = ?,
|
|
24369
|
+
cache_create_1h_tokens = ?, cache_create_5m_tokens = ?,
|
|
24370
|
+
avg_call_gap_seconds = ?, max_call_gap_seconds = ?,
|
|
24371
|
+
p95_call_gap_seconds = ?, subagents_json = ?, tool_calls_json = ?,
|
|
24372
|
+
model_usage_json = ?, all_model_usage_json = ?,
|
|
24373
|
+
model_usage_breakdown_json = ?, version = ?, topic = ?,
|
|
24374
|
+
collected_at = ?
|
|
24375
|
+
WHERE jsonl_path = ?""",
|
|
24376
|
+
(
|
|
24377
|
+
parsed["duration_minutes"],
|
|
24378
|
+
parsed["total_input_tokens"],
|
|
24379
|
+
parsed["total_output_tokens"],
|
|
24380
|
+
parsed["message_count"],
|
|
24381
|
+
parsed.get("api_calls", 0),
|
|
24382
|
+
parsed["cache_hit_rate"],
|
|
24383
|
+
parsed.get("total_cache_create_1h", 0),
|
|
24384
|
+
parsed.get("total_cache_create_5m", 0),
|
|
24385
|
+
parsed.get("avg_call_gap_seconds"),
|
|
24386
|
+
parsed.get("max_call_gap_seconds"),
|
|
24387
|
+
parsed.get("p95_call_gap_seconds"),
|
|
24388
|
+
json.dumps(parsed.get("subagents_used", {})),
|
|
24389
|
+
json.dumps(parsed.get("tool_calls", {})),
|
|
24390
|
+
json.dumps(parsed.get("model_usage", {})),
|
|
24391
|
+
json.dumps(parsed.get("model_usage", {})),
|
|
24392
|
+
json.dumps(parsed.get("model_usage_breakdown", {})),
|
|
24393
|
+
parsed.get("version"),
|
|
24394
|
+
parsed.get("topic"),
|
|
24395
|
+
datetime.now().isoformat(),
|
|
24396
|
+
dedup_key,
|
|
24397
|
+
),
|
|
24398
|
+
)
|
|
24399
|
+
return True
|
|
24400
|
+
|
|
24401
|
+
|
|
24076
24402
|
def _collect_hermes_sessions(days=90, quiet=False, rebuild=False):
|
|
24077
24403
|
"""Collect Hermes sessions from state.db into the trends DB.
|
|
24078
24404
|
|
|
@@ -24115,6 +24441,11 @@ def _collect_hermes_sessions(days=90, quiet=False, rebuild=False):
|
|
|
24115
24441
|
parsed = hermes_session.normalize_session(row, context_tokens=live_context_tokens)
|
|
24116
24442
|
if not parsed:
|
|
24117
24443
|
continue
|
|
24444
|
+
# Skill loads the plugin counted from Hermes's on_skill_lifecycle
|
|
24445
|
+
# hook (state.db does not record them).
|
|
24446
|
+
rollup_skills = globals().get("_HERMES_ROLLUP_SKILLS", {}).get(session_id)
|
|
24447
|
+
if rollup_skills:
|
|
24448
|
+
parsed["skills_used"] = dict(rollup_skills)
|
|
24118
24449
|
|
|
24119
24450
|
slug = parsed.get("slug") or ""
|
|
24120
24451
|
dedup_key = f"hermes:{slug}" if slug else None
|
|
@@ -24122,6 +24453,17 @@ def _collect_hermes_sessions(days=90, quiet=False, rebuild=False):
|
|
|
24122
24453
|
continue
|
|
24123
24454
|
|
|
24124
24455
|
if _is_file_collected(conn, dedup_key):
|
|
24456
|
+
# A collect that ran while the session was still live stored
|
|
24457
|
+
# its totals at that point. Hermes's state.db counters only
|
|
24458
|
+
# grow, so refresh the per-session numbers whenever this
|
|
24459
|
+
# snapshot is at least as far along on every counter and ahead
|
|
24460
|
+
# on one. A snapshot behind on any counter is stale (e.g. a
|
|
24461
|
+
# dashboard collect that read state.db before a finished
|
|
24462
|
+
# rollup wrote) and never overwrites the newer row. Totals are
|
|
24463
|
+
# replaced, never added, and the aggregates are rebuilt from
|
|
24464
|
+
# session_log, so a refresh cannot double count.
|
|
24465
|
+
if _hermes_refresh_session_totals(conn, dedup_key, parsed):
|
|
24466
|
+
updated_count += 1
|
|
24125
24467
|
# A rollup carries the session's live occupancy, which an
|
|
24126
24468
|
# earlier mid-session collect could not see. Refresh the stored
|
|
24127
24469
|
# grade in place so the first write does not freeze a
|
|
@@ -24139,6 +24481,12 @@ def _collect_hermes_sessions(days=90, quiet=False, rebuild=False):
|
|
|
24139
24481
|
),
|
|
24140
24482
|
)
|
|
24141
24483
|
updated_count += 1
|
|
24484
|
+
if rollup_skills:
|
|
24485
|
+
conn.execute(
|
|
24486
|
+
"UPDATE session_log SET skills_json = ? WHERE jsonl_path = ?",
|
|
24487
|
+
(json.dumps(parsed["skills_used"]), dedup_key),
|
|
24488
|
+
)
|
|
24489
|
+
updated_count += 1
|
|
24142
24490
|
continue
|
|
24143
24491
|
|
|
24144
24492
|
started_at = row.get("started_at")
|
|
@@ -24212,6 +24560,44 @@ def _collect_hermes_sessions(days=90, quiet=False, rebuild=False):
|
|
|
24212
24560
|
return new_count
|
|
24213
24561
|
|
|
24214
24562
|
|
|
24563
|
+
_HERMES_SKILLS_MAX = 200
|
|
24564
|
+
|
|
24565
|
+
|
|
24566
|
+
def _parse_hermes_rollup_skills(args):
|
|
24567
|
+
"""Parse ``--session`` + ``--skills-json`` out of hermes-rollup CLI args.
|
|
24568
|
+
|
|
24569
|
+
Returns ``{session_id: {skill_name: loads}}`` or ``{}``. The JSON comes
|
|
24570
|
+
from the plugin's in-memory count; anything malformed is dropped, names
|
|
24571
|
+
are capped at 128 characters and counts must be positive integers.
|
|
24572
|
+
"""
|
|
24573
|
+
session = ""
|
|
24574
|
+
raw = ""
|
|
24575
|
+
i = 0
|
|
24576
|
+
while i < len(args):
|
|
24577
|
+
if args[i] == "--session" and i + 1 < len(args):
|
|
24578
|
+
session = args[i + 1]
|
|
24579
|
+
i += 2
|
|
24580
|
+
elif args[i] == "--skills-json" and i + 1 < len(args):
|
|
24581
|
+
raw = args[i + 1]
|
|
24582
|
+
i += 2
|
|
24583
|
+
else:
|
|
24584
|
+
i += 1
|
|
24585
|
+
if not session or not raw or len(raw) > 65_536:
|
|
24586
|
+
return {}
|
|
24587
|
+
try:
|
|
24588
|
+
data = json.loads(raw)
|
|
24589
|
+
except ValueError:
|
|
24590
|
+
return {}
|
|
24591
|
+
if not isinstance(data, dict):
|
|
24592
|
+
return {}
|
|
24593
|
+
skills = {}
|
|
24594
|
+
for name, count in list(data.items())[:_HERMES_SKILLS_MAX]:
|
|
24595
|
+
if (isinstance(name, str) and name.strip() and isinstance(count, int)
|
|
24596
|
+
and not isinstance(count, bool) and count > 0):
|
|
24597
|
+
skills[name.strip()[:128]] = min(count, 1_000_000)
|
|
24598
|
+
return {session: skills} if skills else {}
|
|
24599
|
+
|
|
24600
|
+
|
|
24215
24601
|
def _parse_hermes_rollup_context(args):
|
|
24216
24602
|
"""Parse ``--session``/``--context-tokens`` out of hermes-rollup CLI args.
|
|
24217
24603
|
|
|
@@ -24243,6 +24629,186 @@ def _parse_hermes_rollup_context(args):
|
|
|
24243
24629
|
return {session: context_tokens} if session and context_tokens is not None else {}
|
|
24244
24630
|
|
|
24245
24631
|
|
|
24632
|
+
# Private scratch dir for the short-lived transcript a Hermes checkpoint is
|
|
24633
|
+
# built from. Files are removed right after use; stragglers from a killed run
|
|
24634
|
+
# are swept after a day.
|
|
24635
|
+
_HERMES_TRANSCRIPT_STALE_SECONDS = 24 * 3600
|
|
24636
|
+
|
|
24637
|
+
|
|
24638
|
+
def _hermes_transcript_dir():
|
|
24639
|
+
return CHECKPOINT_DIR.parent / "hermes-transcripts"
|
|
24640
|
+
|
|
24641
|
+
|
|
24642
|
+
def _sweep_hermes_transcripts(directory, now=None):
|
|
24643
|
+
now = time.time() if now is None else now
|
|
24644
|
+
try:
|
|
24645
|
+
for p in directory.glob("*.jsonl"):
|
|
24646
|
+
try:
|
|
24647
|
+
if not p.is_symlink() and now - p.stat().st_mtime > _HERMES_TRANSCRIPT_STALE_SECONDS:
|
|
24648
|
+
p.unlink()
|
|
24649
|
+
except OSError:
|
|
24650
|
+
continue
|
|
24651
|
+
except OSError:
|
|
24652
|
+
pass
|
|
24653
|
+
|
|
24654
|
+
|
|
24655
|
+
def hermes_checkpoint(session_id, trigger="stop", fill_pct=None, cwd=None):
|
|
24656
|
+
"""Write a session checkpoint for a Hermes session.
|
|
24657
|
+
|
|
24658
|
+
Hermes keeps its transcript in state.db, not a JSONL file. Read the
|
|
24659
|
+
session's messages read-only, translate them into the record shape the
|
|
24660
|
+
shared checkpoint engine reads, and hand that to ``compact_capture``. The
|
|
24661
|
+
translated file lives in Token Optimizer's own private directory for the
|
|
24662
|
+
duration of the call only.
|
|
24663
|
+
|
|
24664
|
+
Returns the checkpoint path, or None (no session id, no messages, or the
|
|
24665
|
+
engine declined). Never falls back to guessing another transcript: a
|
|
24666
|
+
Claude Code session on the same machine must never become a Hermes
|
|
24667
|
+
checkpoint.
|
|
24668
|
+
"""
|
|
24669
|
+
sid = str(session_id or "").strip()
|
|
24670
|
+
if not sid:
|
|
24671
|
+
return None
|
|
24672
|
+
try:
|
|
24673
|
+
import hermes_state as _hs # noqa: PLC0415
|
|
24674
|
+
import hermes_session as _hsess # noqa: PLC0415
|
|
24675
|
+
except Exception:
|
|
24676
|
+
return None
|
|
24677
|
+
records = _hsess.messages_to_transcript_records(_hs.session_messages(sid, limit=500))
|
|
24678
|
+
if not records:
|
|
24679
|
+
return None
|
|
24680
|
+
if not cwd:
|
|
24681
|
+
# The session's own working directory, so the checkpoint's git line
|
|
24682
|
+
# describes the user's project, not wherever this process started.
|
|
24683
|
+
row_cwd = (_hs.get_session(sid, live=True) or {}).get("cwd")
|
|
24684
|
+
try:
|
|
24685
|
+
if isinstance(row_cwd, str) and row_cwd and Path(row_cwd).is_dir():
|
|
24686
|
+
cwd = row_cwd
|
|
24687
|
+
except (OSError, ValueError):
|
|
24688
|
+
cwd = None
|
|
24689
|
+
directory = _hermes_transcript_dir()
|
|
24690
|
+
try:
|
|
24691
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
24692
|
+
try:
|
|
24693
|
+
os.chmod(str(directory), 0o700)
|
|
24694
|
+
except OSError:
|
|
24695
|
+
pass
|
|
24696
|
+
except OSError:
|
|
24697
|
+
return None
|
|
24698
|
+
_sweep_hermes_transcripts(directory)
|
|
24699
|
+
fd, tmp_name = tempfile.mkstemp(prefix=".hermes-", suffix=".jsonl", dir=str(directory))
|
|
24700
|
+
tmp_path = Path(tmp_name)
|
|
24701
|
+
try:
|
|
24702
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
24703
|
+
for record in records:
|
|
24704
|
+
fh.write(json.dumps(record, ensure_ascii=False) + "\n")
|
|
24705
|
+
return compact_capture(
|
|
24706
|
+
session_id=sid,
|
|
24707
|
+
trigger=trigger,
|
|
24708
|
+
cwd=cwd,
|
|
24709
|
+
fill_pct=fill_pct,
|
|
24710
|
+
_trusted_transcript=tmp_path,
|
|
24711
|
+
)
|
|
24712
|
+
finally:
|
|
24713
|
+
try:
|
|
24714
|
+
tmp_path.unlink()
|
|
24715
|
+
except OSError:
|
|
24716
|
+
pass
|
|
24717
|
+
|
|
24718
|
+
|
|
24719
|
+
def _hermes_checkpoint_cli(args):
|
|
24720
|
+
"""``hermes-checkpoint --session <id> [--trigger T] [--fill-pct N] [--cwd DIR] [--quiet]``."""
|
|
24721
|
+
sid = ""
|
|
24722
|
+
trigger = "stop"
|
|
24723
|
+
fill_pct = None
|
|
24724
|
+
cwd = None
|
|
24725
|
+
i = 0
|
|
24726
|
+
while i < len(args):
|
|
24727
|
+
a = args[i]
|
|
24728
|
+
if a == "--session" and i + 1 < len(args):
|
|
24729
|
+
sid = args[i + 1]
|
|
24730
|
+
i += 2
|
|
24731
|
+
elif a == "--trigger" and i + 1 < len(args):
|
|
24732
|
+
trigger = args[i + 1]
|
|
24733
|
+
i += 2
|
|
24734
|
+
elif a == "--fill-pct" and i + 1 < len(args):
|
|
24735
|
+
try:
|
|
24736
|
+
fill_pct = float(args[i + 1])
|
|
24737
|
+
except ValueError:
|
|
24738
|
+
fill_pct = None
|
|
24739
|
+
i += 2
|
|
24740
|
+
elif a == "--cwd" and i + 1 < len(args):
|
|
24741
|
+
cwd = args[i + 1] or None
|
|
24742
|
+
i += 2
|
|
24743
|
+
else:
|
|
24744
|
+
i += 1
|
|
24745
|
+
quiet = "--quiet" in args or "-q" in args
|
|
24746
|
+
if cwd is not None:
|
|
24747
|
+
try:
|
|
24748
|
+
if not Path(cwd).is_dir():
|
|
24749
|
+
cwd = None
|
|
24750
|
+
except (OSError, ValueError):
|
|
24751
|
+
cwd = None
|
|
24752
|
+
result = hermes_checkpoint(sid, trigger=trigger, fill_pct=fill_pct, cwd=cwd)
|
|
24753
|
+
if result and not quiet:
|
|
24754
|
+
print(f"[Token Optimizer] Checkpoint saved: {result}")
|
|
24755
|
+
return result
|
|
24756
|
+
|
|
24757
|
+
|
|
24758
|
+
def hermes_turn_context(payload):
|
|
24759
|
+
"""Per-turn model context for a Hermes session, in one process.
|
|
24760
|
+
|
|
24761
|
+
Same engines Claude Code's SessionStart / UserPromptSubmit hooks run:
|
|
24762
|
+
- first turn: the new-session checkpoint pointer (compact_restore)
|
|
24763
|
+
- every turn: the topic-matched prior-session hint (_continuity_prompt_hint)
|
|
24764
|
+
- when the plugin passes a live fill reading: the lean-output nudge
|
|
24765
|
+
(_verbosity_nudge_text). Hermes has no session-efficiency signal, so
|
|
24766
|
+
only the strong tier (75-89% fill) can apply; the plugin paces it.
|
|
24767
|
+
|
|
24768
|
+
``payload`` keys: session_id, prompt, first_turn, fill_pct, score.
|
|
24769
|
+
Returns {"parts": [...], "verbosity": bool}. Never raises.
|
|
24770
|
+
"""
|
|
24771
|
+
out = {"parts": [], "verbosity": False}
|
|
24772
|
+
if not isinstance(payload, dict):
|
|
24773
|
+
return out
|
|
24774
|
+
sid = str(payload.get("session_id") or "").strip()
|
|
24775
|
+
if not sid:
|
|
24776
|
+
return out
|
|
24777
|
+
if payload.get("first_turn"):
|
|
24778
|
+
from contextlib import redirect_stdout as _redirect_stdout # noqa: PLC0415
|
|
24779
|
+
|
|
24780
|
+
buf = io.StringIO()
|
|
24781
|
+
try:
|
|
24782
|
+
with _redirect_stdout(buf):
|
|
24783
|
+
compact_restore(session_id=sid, new_session_only=True)
|
|
24784
|
+
except Exception:
|
|
24785
|
+
pass
|
|
24786
|
+
pointer = buf.getvalue().strip()
|
|
24787
|
+
if pointer:
|
|
24788
|
+
out["parts"].append(pointer)
|
|
24789
|
+
prompt = str(payload.get("prompt") or "").strip()
|
|
24790
|
+
if prompt:
|
|
24791
|
+
try:
|
|
24792
|
+
hint = (_continuity_prompt_hint(prompt_text=prompt[:4000], session_id=sid) or "").strip()
|
|
24793
|
+
except Exception:
|
|
24794
|
+
hint = ""
|
|
24795
|
+
if hint:
|
|
24796
|
+
out["parts"].append(hint)
|
|
24797
|
+
fill = payload.get("fill_pct")
|
|
24798
|
+
if isinstance(fill, (int, float)) and not isinstance(fill, bool):
|
|
24799
|
+
score = payload.get("score")
|
|
24800
|
+
score = float(score) if isinstance(score, (int, float)) and not isinstance(score, bool) else 100.0
|
|
24801
|
+
# No efficiency signal on Hermes: 100 keeps the gentle tier off.
|
|
24802
|
+
window = payload.get("context_window")
|
|
24803
|
+
cached = ({"model_context_window": int(window)}
|
|
24804
|
+
if isinstance(window, int) and not isinstance(window, bool) and window > 0 else {})
|
|
24805
|
+
nudge = _verbosity_nudge_text(float(fill), score, 100, cached)
|
|
24806
|
+
if nudge:
|
|
24807
|
+
out["parts"].append(nudge)
|
|
24808
|
+
out["verbosity"] = True
|
|
24809
|
+
return out
|
|
24810
|
+
|
|
24811
|
+
|
|
24246
24812
|
def _resolve_copilot_home_wsl_aware(mnt_root=None):
|
|
24247
24813
|
"""Resolve the Copilot home with a WSL-root /mnt/ exception.
|
|
24248
24814
|
|
|
@@ -29061,6 +29627,10 @@ def _resolve_runtime_bin(process_name):
|
|
|
29061
29627
|
Path("/usr/local/bin") / process_name,
|
|
29062
29628
|
home / ".bun" / "bin" / process_name,
|
|
29063
29629
|
]
|
|
29630
|
+
# Claude Code's local installer lives under its config dir, so a relocated
|
|
29631
|
+
# CLAUDE_CONFIG_DIR moves it off ~/.claude/local.
|
|
29632
|
+
if process_name == "claude" and CLAUDE_DIR / "local" / process_name not in candidates:
|
|
29633
|
+
candidates.insert(2, CLAUDE_DIR / "local" / process_name)
|
|
29064
29634
|
for cand in candidates:
|
|
29065
29635
|
try:
|
|
29066
29636
|
if cand.is_file() and os.access(str(cand), os.X_OK):
|
|
@@ -30829,7 +31399,7 @@ def _maybe_self_heal_sessionend_fossils_on_hook():
|
|
|
30829
31399
|
_clear_hook_budget(deadline)
|
|
30830
31400
|
|
|
30831
31401
|
|
|
30832
|
-
def setup_hook(dry_run=False, uninstall=False):
|
|
31402
|
+
def setup_hook(dry_run=False, uninstall=False, user_initiated=False):
|
|
30833
31403
|
"""Install or uninstall the SessionEnd hook for automatic usage collection.
|
|
30834
31404
|
|
|
30835
31405
|
``uninstall=True`` removes ONLY Token Optimizer's own SessionEnd hook
|
|
@@ -30885,7 +31455,7 @@ def setup_hook(dry_run=False, uninstall=False):
|
|
|
30885
31455
|
import shutil
|
|
30886
31456
|
shutil.copy2(str(SETTINGS_PATH), str(backup_path))
|
|
30887
31457
|
try:
|
|
30888
|
-
if not _write_settings_atomic(settings):
|
|
31458
|
+
if not _write_settings_atomic(settings, user_initiated=user_initiated):
|
|
30889
31459
|
print("[Error] settings.json write was refused; no SessionEnd hooks were removed.", file=sys.stderr)
|
|
30890
31460
|
return
|
|
30891
31461
|
print(f"[Token Optimizer] Removed {removed} Token Optimizer SessionEnd hook(s) from settings.json.")
|
|
@@ -30977,7 +31547,7 @@ def setup_hook(dry_run=False, uninstall=False):
|
|
|
30977
31547
|
|
|
30978
31548
|
# Write atomically
|
|
30979
31549
|
try:
|
|
30980
|
-
if not _write_settings_atomic(settings):
|
|
31550
|
+
if not _write_settings_atomic(settings, user_initiated=user_initiated):
|
|
30981
31551
|
print("[Error] settings.json write was refused; SessionEnd hook was not installed.", file=sys.stderr)
|
|
30982
31552
|
return
|
|
30983
31553
|
action = "upgraded" if upgrading else "installed"
|
|
@@ -33244,13 +33814,7 @@ def _daemon_install_lock(soft_fail=False):
|
|
|
33244
33814
|
MAX_LOCK_AGE = 10 * 60 # 10 minutes
|
|
33245
33815
|
|
|
33246
33816
|
def _pid_alive(pid):
|
|
33247
|
-
|
|
33248
|
-
return False
|
|
33249
|
-
try:
|
|
33250
|
-
os.kill(pid, 0)
|
|
33251
|
-
return True
|
|
33252
|
-
except OSError:
|
|
33253
|
-
return False
|
|
33817
|
+
return _pid_is_running(pid)
|
|
33254
33818
|
|
|
33255
33819
|
def _try_reclaim_stale():
|
|
33256
33820
|
"""Return True if we successfully reaped a stale lock, False otherwise."""
|
|
@@ -34045,6 +34609,11 @@ def _generate_windows_launcher_cmd(daemon_script_path, log_dir):
|
|
|
34045
34609
|
|
|
34046
34610
|
return (
|
|
34047
34611
|
"@echo off\r\n"
|
|
34612
|
+
# cmd.exe reads a batch file in the console (OEM) code page, but this
|
|
34613
|
+
# file is written as UTF-8: a profile path like C:\Users\Jos\u00e9 was
|
|
34614
|
+
# garbled and the daemon never started. Switch to UTF-8 first; this
|
|
34615
|
+
# line and everything above it is plain ASCII.
|
|
34616
|
+
"chcp 65001\r\n"
|
|
34048
34617
|
"REM Token Optimizer dashboard daemon launcher (v5.3.2+).\r\n"
|
|
34049
34618
|
"REM Auto-generated. Resolves Python at runtime so interpreter upgrades\r\n"
|
|
34050
34619
|
"REM do not break the scheduled task.\r\n"
|
|
@@ -34058,7 +34627,7 @@ def _generate_windows_launcher_cmd(daemon_script_path, log_dir):
|
|
|
34058
34627
|
f'set "STDOUT_LOG={log_dir}\\stdout.log"\r\n'
|
|
34059
34628
|
f'set "STDERR_LOG={log_dir}\\stderr.log"\r\n'
|
|
34060
34629
|
'if not exist "%DAEMON_SCRIPT%" (\r\n'
|
|
34061
|
-
' echo [%DATE% %TIME%] daemon script missing: %DAEMON_SCRIPT% >> "%STDERR_LOG%"\r\n'
|
|
34630
|
+
' echo [%DATE% %TIME%] daemon script missing: "%DAEMON_SCRIPT%" >> "%STDERR_LOG%"\r\n'
|
|
34062
34631
|
" exit /b 1\r\n"
|
|
34063
34632
|
")\r\n"
|
|
34064
34633
|
'set "PYW_EXE="\r\n'
|
|
@@ -35057,6 +35626,15 @@ def _retained_paths() -> list[tuple[str, Path]]:
|
|
|
35057
35626
|
pass
|
|
35058
35627
|
# Always include the resolved snapshot dir even under a sandbox override.
|
|
35059
35628
|
paths.append(("session data (this install)", SNAPSHOT_DIR))
|
|
35629
|
+
# Compaction checkpoints (conversation-context captures) live under the
|
|
35630
|
+
# per-session state base, which on a script install is NOT inside
|
|
35631
|
+
# SNAPSHOT_DIR (#106 named them as undisclosed). Disclose them too.
|
|
35632
|
+
try:
|
|
35633
|
+
listed = {p for _, p in paths}
|
|
35634
|
+
if CHECKPOINT_DIR not in listed:
|
|
35635
|
+
paths.append(("checkpoints (this install)", CHECKPOINT_DIR))
|
|
35636
|
+
except NameError:
|
|
35637
|
+
pass
|
|
35060
35638
|
return paths
|
|
35061
35639
|
|
|
35062
35640
|
|
|
@@ -35133,6 +35711,9 @@ def _remove_our_settings_entries(settings: dict) -> list[str]:
|
|
|
35133
35711
|
``quality-cache`` (our cache hook).
|
|
35134
35712
|
- ``SessionEnd`` hook entries that are ours (reuses
|
|
35135
35713
|
_remove_token_optimizer_session_end_hooks).
|
|
35714
|
+
- ``compactInstructions`` when it is the block setup-smart-compact
|
|
35715
|
+
generated (removed) or holds our appended section (only that section
|
|
35716
|
+
is removed; the user's own text stays).
|
|
35136
35717
|
|
|
35137
35718
|
Foreign statusLines, foreign hooks, and every other settings key are left
|
|
35138
35719
|
byte-identical. Returns a list of human-readable descriptions of what was
|
|
@@ -35200,6 +35781,10 @@ def _remove_our_settings_entries(settings: dict) -> list[str]:
|
|
|
35200
35781
|
n_session_end = _remove_token_optimizer_session_end_hooks(settings)
|
|
35201
35782
|
if n_session_end:
|
|
35202
35783
|
removed.append(f"{n_session_end} SessionEnd hook(s)")
|
|
35784
|
+
# compactInstructions written by setup-smart-compact (#106: it outlived
|
|
35785
|
+
# cleanup). Only our generated block / appended section is removed.
|
|
35786
|
+
if _remove_our_compact_instructions(settings):
|
|
35787
|
+
removed.append("compactInstructions (token-optimizer)")
|
|
35203
35788
|
return removed
|
|
35204
35789
|
|
|
35205
35790
|
|
|
@@ -35248,6 +35833,24 @@ def cleanup(dry_run=False, this_install_only=False):
|
|
|
35248
35833
|
# the preview stays side-effect-free.
|
|
35249
35834
|
if not dry_run:
|
|
35250
35835
|
_unlink_if_exists(PLIST_PATH)
|
|
35836
|
+
# Same reasoning for the other platforms' per-identity daemon files:
|
|
35837
|
+
# each platform's uninstaller sweeps only its own launcher, so a HOME
|
|
35838
|
+
# synced or migrated from another OS kept dashboard-launcher.cmd /
|
|
35839
|
+
# .schtasks-daemon.xml (Windows) or the Linux launcher after cleanup
|
|
35840
|
+
# (#106). They are plain files once the scheduler job is gone.
|
|
35841
|
+
if not _daemon_snapshot_sandboxed():
|
|
35842
|
+
for _snap in _daemon_identity_snapshot_dirs(this_install_only):
|
|
35843
|
+
_gone, _ = _sweep_identity_daemon_files(
|
|
35844
|
+
_snap, ("daemon_script", "daemon_token", "daemon_host",
|
|
35845
|
+
"windows_launcher", "linux_launcher"))
|
|
35846
|
+
try:
|
|
35847
|
+
for _xml in _snap.glob("*schtasks-daemon*.xml"):
|
|
35848
|
+
if _unlink_if_exists(_xml):
|
|
35849
|
+
_gone.append(str(_xml))
|
|
35850
|
+
except OSError:
|
|
35851
|
+
pass
|
|
35852
|
+
for _path in _gone:
|
|
35853
|
+
print(f" Deleted: {_path}")
|
|
35251
35854
|
print()
|
|
35252
35855
|
|
|
35253
35856
|
# 2. settings.json
|
|
@@ -35297,7 +35900,14 @@ def cleanup(dry_run=False, this_install_only=False):
|
|
|
35297
35900
|
# silent no-op. Reporting "Removed" for a write that never
|
|
35298
35901
|
# landed leaves the user with the dangling statusLine this
|
|
35299
35902
|
# command exists to clear, so surface it instead.
|
|
35300
|
-
|
|
35903
|
+
# user_initiated: cleanup is an explicit user command. Under
|
|
35904
|
+
# the hook cohort throttle any Token Optimizer settings
|
|
35905
|
+
# write in the previous ~10s (a SessionStart heal, a setup
|
|
35906
|
+
# command) made this write lose the lease, and the whole
|
|
35907
|
+
# removal was skipped (#106 leftovers).
|
|
35908
|
+
if _write_settings_atomic(
|
|
35909
|
+
fresh, allow_removing_keys={"statusLine", "compactInstructions"},
|
|
35910
|
+
user_initiated=True):
|
|
35301
35911
|
for entry in our_entries:
|
|
35302
35912
|
print(f" Removed: {entry}")
|
|
35303
35913
|
print(f" Backup: {backed}")
|
|
@@ -36544,7 +37154,8 @@ def _external_memory_present() -> bool:
|
|
|
36544
37154
|
without touching the filesystem.
|
|
36545
37155
|
2. A neutral coordination marker file, whose mere existence means an
|
|
36546
37156
|
external durable-memory tool is active:
|
|
36547
|
-
``${TO_EXTERNAL_MEMORY_MARKER
|
|
37157
|
+
``${TO_EXTERNAL_MEMORY_MARKER:-<claude home>/durable-memory.json}``, where the
|
|
37158
|
+
Claude home honors CLAUDE_CONFIG_DIR (CLAUDE_DIR / claude_home()).
|
|
36548
37159
|
|
|
36549
37160
|
The external tool writes the marker once (set-and-forget), so detection is
|
|
36550
37161
|
automatic with no per-session configuration. Cached in a module global so
|
|
@@ -36568,7 +37179,7 @@ def _external_memory_present() -> bool:
|
|
|
36568
37179
|
marker = (
|
|
36569
37180
|
Path(marker_env).expanduser()
|
|
36570
37181
|
if marker_env
|
|
36571
|
-
else
|
|
37182
|
+
else CLAUDE_DIR / "durable-memory.json"
|
|
36572
37183
|
)
|
|
36573
37184
|
try:
|
|
36574
37185
|
if marker.exists():
|
|
@@ -36647,6 +37258,100 @@ def _extract_user_text(record):
|
|
|
36647
37258
|
return ""
|
|
36648
37259
|
|
|
36649
37260
|
|
|
37261
|
+
_HARNESS_TASK_PREFIXES = (
|
|
37262
|
+
"<local-command-caveat>", "<local-command-stdout>",
|
|
37263
|
+
"<local-command-stderr>", "<task-notification>",
|
|
37264
|
+
"[SYSTEM NOTIFICATION", "[Request interrupted by user",
|
|
37265
|
+
"Your response above was cut off mid-stream",
|
|
37266
|
+
)
|
|
37267
|
+
# Built-in commands that only change the session or UI. Run bare, they are not
|
|
37268
|
+
# a task. With arguments, or when an installed skill owns the name, they are.
|
|
37269
|
+
_LOCAL_SLASH_COMMANDS = frozenset((
|
|
37270
|
+
"add-dir", "agents", "bug", "config", "context", "continue", "cost",
|
|
37271
|
+
"doctor", "exit", "export", "fast", "feedback", "help", "hooks", "ide",
|
|
37272
|
+
"init", "login", "logout", "mcp", "memory", "model", "output-style",
|
|
37273
|
+
"permissions", "privacy-settings", "quit", "release-notes", "resume",
|
|
37274
|
+
"rewind", "settings", "stats", "status", "statusline", "terminal-setup",
|
|
37275
|
+
"theme", "upgrade", "usage", "vim",
|
|
37276
|
+
))
|
|
37277
|
+
_COMMAND_TASK_TAG_RE = re.compile(r"\s*<command-(name|message|args)>")
|
|
37278
|
+
|
|
37279
|
+
|
|
37280
|
+
def _command_task_text(text):
|
|
37281
|
+
"""Unwrap a complete command once, with bounded, non-backtracking scans."""
|
|
37282
|
+
fields = {}
|
|
37283
|
+
pos = 0
|
|
37284
|
+
while pos < len(text):
|
|
37285
|
+
if not text[pos:].strip():
|
|
37286
|
+
break
|
|
37287
|
+
tag = _COMMAND_TASK_TAG_RE.match(text, pos)
|
|
37288
|
+
if tag is None or tag.group(1) in fields:
|
|
37289
|
+
return ""
|
|
37290
|
+
name = tag.group(1)
|
|
37291
|
+
close = "</command-" + name + ">"
|
|
37292
|
+
end = text.find(close, tag.end())
|
|
37293
|
+
if end < 0:
|
|
37294
|
+
return ""
|
|
37295
|
+
fields[name] = text[tag.end():end]
|
|
37296
|
+
pos = end + len(close)
|
|
37297
|
+
command = _SLASH_COMMAND_RE.fullmatch(
|
|
37298
|
+
"<command-name>" + fields.get("name", "") + "</command-name>")
|
|
37299
|
+
if command is None:
|
|
37300
|
+
return ""
|
|
37301
|
+
name = command.group(1)
|
|
37302
|
+
if name.lower() in ("compact", "clear"):
|
|
37303
|
+
return ""
|
|
37304
|
+
# Some versions omit an empty <command-args>: treat a missing tag as empty.
|
|
37305
|
+
args = fields.get("args", "").strip()
|
|
37306
|
+
if (not args and name.lower() in _LOCAL_SLASH_COMMANDS
|
|
37307
|
+
and not _resolve_installed_skill(name)):
|
|
37308
|
+
return ""
|
|
37309
|
+
return "/" + name + (" " + args if args else "")
|
|
37310
|
+
|
|
37311
|
+
|
|
37312
|
+
def _task_user_text(record):
|
|
37313
|
+
"""Task text for continuity only, excluding harness/meta/tool transport.
|
|
37314
|
+
|
|
37315
|
+
A slash-command wrapper is transport, but its name and arguments can be
|
|
37316
|
+
a real task. Preserve those without changing raw scoring/skill-use input.
|
|
37317
|
+
"""
|
|
37318
|
+
if record.get("isMeta") or record.get("isCompactSummary"):
|
|
37319
|
+
return ""
|
|
37320
|
+
message = record.get("message", {})
|
|
37321
|
+
content = message.get("content") if isinstance(message, dict) else message
|
|
37322
|
+
if isinstance(content, str):
|
|
37323
|
+
parts = [content]
|
|
37324
|
+
elif isinstance(content, list):
|
|
37325
|
+
parts = [
|
|
37326
|
+
block if isinstance(block, str) else block.get("text", "")
|
|
37327
|
+
for block in content
|
|
37328
|
+
if isinstance(block, str) or (
|
|
37329
|
+
isinstance(block, dict) and block.get("type") == "text")
|
|
37330
|
+
]
|
|
37331
|
+
else:
|
|
37332
|
+
return ""
|
|
37333
|
+
texts = []
|
|
37334
|
+
for part in parts:
|
|
37335
|
+
if not isinstance(part, str):
|
|
37336
|
+
continue
|
|
37337
|
+
text = part.strip()
|
|
37338
|
+
# A <system-reminder> block can lead a real prompt: drop the block,
|
|
37339
|
+
# keep what follows. An unclosed block is all harness.
|
|
37340
|
+
while text.startswith("<system-reminder>"):
|
|
37341
|
+
end = text.find("</system-reminder>")
|
|
37342
|
+
text = "" if end < 0 else text[end + len("</system-reminder>"):].strip()
|
|
37343
|
+
if not text or text.startswith(_HARNESS_TASK_PREFIXES):
|
|
37344
|
+
continue
|
|
37345
|
+
if text.startswith(("<command-name>", "<command-message>", "<command-args>")):
|
|
37346
|
+
# Only a complete wrapper is an invocation. Do not turn malformed
|
|
37347
|
+
# harness markup into a recovered task, or strip tags from prose.
|
|
37348
|
+
text = _command_task_text(text)
|
|
37349
|
+
if not text:
|
|
37350
|
+
continue
|
|
37351
|
+
texts.append(text)
|
|
37352
|
+
return "\n".join(texts)
|
|
37353
|
+
|
|
37354
|
+
|
|
36650
37355
|
def _read_stdin_hook_input(max_bytes=65536):
|
|
36651
37356
|
"""Thin wrapper: measure.py callers default to 64KB (PreToolUse payloads)."""
|
|
36652
37357
|
return _read_stdin_hook_input_shared(max_bytes)
|
|
@@ -36809,9 +37514,7 @@ def _parse_jsonl_for_quality(filepath):
|
|
|
36809
37514
|
# raise and abort the whole parse (losing all quality data).
|
|
36810
37515
|
usage = msg.get("usage")
|
|
36811
37516
|
if isinstance(usage, dict):
|
|
36812
|
-
tok = (
|
|
36813
|
-
+ _safe_int(usage.get("cache_creation_input_tokens"))
|
|
36814
|
-
+ _safe_int(usage.get("cache_read_input_tokens")))
|
|
37517
|
+
tok = _context_token_count(_context_usage(usage))
|
|
36815
37518
|
if tok > 0:
|
|
36816
37519
|
context_tokens = tok
|
|
36817
37520
|
model_str = msg.get("model")
|
|
@@ -39837,6 +40540,78 @@ def _log_reexpand_debit(session_id, tool_use_id, response_text):
|
|
|
39837
40540
|
pass
|
|
39838
40541
|
|
|
39839
40542
|
|
|
40543
|
+
def _find_archive_entry(archive_roots, tool_use_id, session_id=None, strict=False):
|
|
40544
|
+
"""First ``<root>/<session>/<tool_use_id>.json`` that exists, or None.
|
|
40545
|
+
|
|
40546
|
+
*tool_use_id* must already have passed expand's ``[a-zA-Z0-9_-]+`` check, so
|
|
40547
|
+
the filename can never leave its session dir. *strict* (the cross-runtime
|
|
40548
|
+
fallback) additionally requires a regular, non-symlink file whose resolved
|
|
40549
|
+
path stays inside its archive root.
|
|
40550
|
+
"""
|
|
40551
|
+
for archive_root in archive_roots:
|
|
40552
|
+
if session_id:
|
|
40553
|
+
sid = sanitize_session_id(session_id)
|
|
40554
|
+
if sid == "unknown":
|
|
40555
|
+
continue
|
|
40556
|
+
session_dirs = [archive_root / sid]
|
|
40557
|
+
elif archive_root.is_dir() and not archive_root.is_symlink():
|
|
40558
|
+
try:
|
|
40559
|
+
session_dirs = [d for d in archive_root.iterdir()
|
|
40560
|
+
if d.is_dir() and not d.is_symlink()]
|
|
40561
|
+
except OSError:
|
|
40562
|
+
continue
|
|
40563
|
+
else:
|
|
40564
|
+
continue
|
|
40565
|
+
for sd in session_dirs:
|
|
40566
|
+
entry_path = sd / f"{tool_use_id}.json"
|
|
40567
|
+
try:
|
|
40568
|
+
if not entry_path.exists():
|
|
40569
|
+
continue
|
|
40570
|
+
if strict:
|
|
40571
|
+
if (archive_root.is_symlink() or sd.is_symlink()
|
|
40572
|
+
or entry_path.is_symlink() or not entry_path.is_file()):
|
|
40573
|
+
continue
|
|
40574
|
+
entry_path.resolve(strict=True).relative_to(archive_root.resolve(strict=True))
|
|
40575
|
+
except (OSError, ValueError):
|
|
40576
|
+
continue
|
|
40577
|
+
return entry_path
|
|
40578
|
+
return None
|
|
40579
|
+
|
|
40580
|
+
|
|
40581
|
+
# Every runtime whose archive an unpinned expand may fall back to, in lookup order.
|
|
40582
|
+
_EXPAND_FALLBACK_RUNTIMES = ("claude", "codex", "hermes", "copilot", "cursor",
|
|
40583
|
+
"opencode", "antigravity", "grok", "devin")
|
|
40584
|
+
|
|
40585
|
+
|
|
40586
|
+
def _expand_may_cross_runtimes():
|
|
40587
|
+
"""True for a bare expand: no --runtime / TOKEN_OPTIMIZER_RUNTIME pin and
|
|
40588
|
+
no sandbox snapshot override."""
|
|
40589
|
+
return not (os.environ.get("TOKEN_OPTIMIZER_RUNTIME", "").strip()
|
|
40590
|
+
or os.environ.get("TOKEN_OPTIMIZER_SNAPSHOT_DIR", "").strip())
|
|
40591
|
+
|
|
40592
|
+
|
|
40593
|
+
def _cross_runtime_archive_roots(exclude):
|
|
40594
|
+
"""tool-archive dirs under every other runtime's home. Never raises."""
|
|
40595
|
+
roots = []
|
|
40596
|
+
seen = set(exclude)
|
|
40597
|
+
try:
|
|
40598
|
+
from runtime_env import runtime_home_for
|
|
40599
|
+
from plugin_env import snapshot_roots_for_home
|
|
40600
|
+
except Exception:
|
|
40601
|
+
return roots
|
|
40602
|
+
for runtime in _EXPAND_FALLBACK_RUNTIMES:
|
|
40603
|
+
try:
|
|
40604
|
+
home = runtime_home_for(runtime)
|
|
40605
|
+
for snapshot_root in snapshot_roots_for_home(home):
|
|
40606
|
+
root = snapshot_root / "tool-archive"
|
|
40607
|
+
if root not in seen:
|
|
40608
|
+
seen.add(root)
|
|
40609
|
+
roots.append(root)
|
|
40610
|
+
except Exception:
|
|
40611
|
+
continue
|
|
40612
|
+
return roots
|
|
40613
|
+
|
|
40614
|
+
|
|
39840
40615
|
def expand_archived(tool_use_id=None, session_id=None, list_all=False):
|
|
39841
40616
|
"""Retrieve an archived tool result, or list all archived results.
|
|
39842
40617
|
|
|
@@ -39909,48 +40684,43 @@ def expand_archived(tool_use_id=None, session_id=None, list_all=False):
|
|
|
39909
40684
|
print("[Error] Invalid tool_use_id format.", file=sys.stderr)
|
|
39910
40685
|
sys.exit(1)
|
|
39911
40686
|
|
|
39912
|
-
|
|
40687
|
+
entry_path = _find_archive_entry(archive_roots, tool_use_id, session_id)
|
|
40688
|
+
if entry_path is None and _expand_may_cross_runtimes():
|
|
40689
|
+
# Not in this runtime's archive. A pointer printed by Claude Code is
|
|
40690
|
+
# never pinned, so a shell that detects another runtime (or a scan
|
|
40691
|
+
# that failed open to Claude Code when the archive was written under
|
|
40692
|
+
# another runtime) would otherwise miss an entry that exists. Only an
|
|
40693
|
+
# unpinned expand falls back; an explicit --runtime stays strict.
|
|
40694
|
+
fallback_roots = _cross_runtime_archive_roots(archive_roots)
|
|
40695
|
+
entry_path = _find_archive_entry(fallback_roots, tool_use_id, session_id, strict=True)
|
|
40696
|
+
if entry_path is None and not any(root.is_dir() for root in archive_roots):
|
|
40697
|
+
archive_roots = archive_roots + [r for r in fallback_roots if r.is_dir()]
|
|
40698
|
+
|
|
40699
|
+
if entry_path is None and not any(root.is_dir() for root in archive_roots):
|
|
39913
40700
|
print("[Error] No archive directory found. No results have been archived yet.", file=sys.stderr)
|
|
39914
40701
|
sys.exit(1)
|
|
39915
40702
|
|
|
39916
|
-
|
|
39917
|
-
|
|
39918
|
-
|
|
39919
|
-
|
|
39920
|
-
|
|
39921
|
-
if
|
|
39922
|
-
|
|
39923
|
-
|
|
39924
|
-
|
|
39925
|
-
|
|
39926
|
-
|
|
39927
|
-
|
|
39928
|
-
|
|
39929
|
-
|
|
39930
|
-
|
|
39931
|
-
|
|
39932
|
-
|
|
39933
|
-
entry_path = sd / f"{tool_use_id}.json"
|
|
39934
|
-
if entry_path.exists():
|
|
39935
|
-
try:
|
|
39936
|
-
data = json.loads(entry_path.read_text(encoding="utf-8"))
|
|
39937
|
-
response = data.get("response", "")
|
|
39938
|
-
if response:
|
|
39939
|
-
# B6 integrity: re-popping an archived result means it did NOT
|
|
39940
|
-
# stay collapsed, so reverse its tool_archive credit. Log the
|
|
39941
|
-
# re-popped tokens as a debit (netted in _get_savings_summary),
|
|
39942
|
-
# deduped per item so a second expand never double-debits.
|
|
39943
|
-
_log_reexpand_debit(sd.name, tool_use_id, response)
|
|
39944
|
-
# No added newline: expand returns the stored text as stored.
|
|
39945
|
-
sys.stdout.write(response)
|
|
39946
|
-
sys.stdout.flush()
|
|
39947
|
-
return
|
|
39948
|
-
else:
|
|
39949
|
-
print(f"[Error] Archived entry found but response is empty: {entry_path}", file=sys.stderr)
|
|
39950
|
-
sys.exit(1)
|
|
39951
|
-
except (json.JSONDecodeError, OSError) as e:
|
|
39952
|
-
print(f"[Error] Failed to read archived result: {e}", file=sys.stderr)
|
|
40703
|
+
if entry_path is not None:
|
|
40704
|
+
sd = entry_path.parent
|
|
40705
|
+
try:
|
|
40706
|
+
data = json.loads(entry_path.read_text(encoding="utf-8"))
|
|
40707
|
+
response = data.get("response", "")
|
|
40708
|
+
if response:
|
|
40709
|
+
# B6 integrity: re-popping an archived result means it did NOT
|
|
40710
|
+
# stay collapsed, so reverse its tool_archive credit. Log the
|
|
40711
|
+
# re-popped tokens as a debit (netted in _get_savings_summary),
|
|
40712
|
+
# deduped per item so a second expand never double-debits.
|
|
40713
|
+
_log_reexpand_debit(sd.name, tool_use_id, response)
|
|
40714
|
+
# No added newline: expand returns the stored text as stored.
|
|
40715
|
+
sys.stdout.write(response)
|
|
40716
|
+
sys.stdout.flush()
|
|
40717
|
+
return
|
|
40718
|
+
else:
|
|
40719
|
+
print(f"[Error] Archived entry found but response is empty: {entry_path}", file=sys.stderr)
|
|
39953
40720
|
sys.exit(1)
|
|
40721
|
+
except (json.JSONDecodeError, OSError) as e:
|
|
40722
|
+
print(f"[Error] Failed to read archived result: {e}", file=sys.stderr)
|
|
40723
|
+
sys.exit(1)
|
|
39954
40724
|
|
|
39955
40725
|
print(f"[Error] Tool result not found: {tool_use_id}", file=sys.stderr)
|
|
39956
40726
|
if not session_id:
|
|
@@ -40182,11 +40952,9 @@ def _purge_all_data(confirm=False, force=False):
|
|
|
40182
40952
|
try:
|
|
40183
40953
|
raw = pid_file.read_text(encoding="utf-8").strip()
|
|
40184
40954
|
candidate_pid = int(raw)
|
|
40185
|
-
|
|
40186
|
-
os.kill(candidate_pid, 0)
|
|
40955
|
+
if _pid_is_running(candidate_pid):
|
|
40187
40956
|
running_pid = candidate_pid
|
|
40188
|
-
|
|
40189
|
-
pass # process not alive; PID file is stale
|
|
40957
|
+
# else: process not alive; PID file is stale
|
|
40190
40958
|
except (OSError, ValueError):
|
|
40191
40959
|
pass
|
|
40192
40960
|
|
|
@@ -40202,9 +40970,14 @@ def _purge_all_data(confirm=False, force=False):
|
|
|
40202
40970
|
# Verify PID identity before SIGTERM to avoid killing a recycled PID
|
|
40203
40971
|
is_ours = False
|
|
40204
40972
|
try:
|
|
40205
|
-
|
|
40206
|
-
|
|
40207
|
-
|
|
40973
|
+
if os.name == "nt":
|
|
40974
|
+
# No `ps` on Windows: the daemon was never stopped there, and
|
|
40975
|
+
# the purge then hit the files it still held open.
|
|
40976
|
+
proc_name = ((_windows_process_names() or {}).get(running_pid) or (0, ""))[1]
|
|
40977
|
+
else:
|
|
40978
|
+
result = _sp.run(["ps", "-p", str(running_pid), "-o", "comm="],
|
|
40979
|
+
capture_output=True, text=True, timeout=3)
|
|
40980
|
+
proc_name = result.stdout.strip().lower()
|
|
40208
40981
|
is_ours = "python" in proc_name or "measure" in proc_name
|
|
40209
40982
|
except Exception:
|
|
40210
40983
|
is_ours = False
|
|
@@ -40394,9 +41167,8 @@ def _security_report(as_json=False):
|
|
|
40394
41167
|
pid_file = DAEMON_LOG_DIR / "daemon.pid"
|
|
40395
41168
|
if pid_file.exists():
|
|
40396
41169
|
try:
|
|
40397
|
-
daemon_pid = int(pid_file.read_text().strip())
|
|
40398
|
-
|
|
40399
|
-
daemon_running = True
|
|
41170
|
+
daemon_pid = int(pid_file.read_text(encoding="utf-8").strip())
|
|
41171
|
+
daemon_running = _pid_is_running(daemon_pid)
|
|
40400
41172
|
except (ValueError, OSError):
|
|
40401
41173
|
pass
|
|
40402
41174
|
|
|
@@ -40642,7 +41414,7 @@ def _extract_session_state(filepath, tail_lines=500):
|
|
|
40642
41414
|
|
|
40643
41415
|
# User messages
|
|
40644
41416
|
if rec_type == "user":
|
|
40645
|
-
text = _ingest_redact(
|
|
41417
|
+
text = _ingest_redact(_task_user_text(record))
|
|
40646
41418
|
if text.strip():
|
|
40647
41419
|
last_user_msg = text.strip()
|
|
40648
41420
|
# Check for questions
|
|
@@ -40865,13 +41637,22 @@ def _redaction_skip_notice(session_id):
|
|
|
40865
41637
|
return None
|
|
40866
41638
|
|
|
40867
41639
|
|
|
40868
|
-
|
|
41640
|
+
class _SkipTranscriptQuality(Exception):
|
|
41641
|
+
"""Internal: leave the transcript-derived quality block out of a checkpoint."""
|
|
41642
|
+
|
|
41643
|
+
|
|
41644
|
+
def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=None, fill_pct=None, quality_score=None, backfill_tools=False, _trusted_transcript=None):
|
|
40869
41645
|
"""Capture structured session state before compaction or session end.
|
|
40870
41646
|
|
|
40871
41647
|
Writes a markdown checkpoint to CHECKPOINT_DIR.
|
|
40872
41648
|
Called by PreCompact, Stop, and SessionEnd hooks via CLI.
|
|
40873
41649
|
Progressive checkpoints pass fill_pct and trigger="progressive-{band}".
|
|
40874
41650
|
|
|
41651
|
+
``_trusted_transcript`` is for internal callers only: a transcript Token
|
|
41652
|
+
Optimizer built itself in its own private directory (the Hermes adapter
|
|
41653
|
+
translates Hermes's state.db messages into one). It skips the confinement
|
|
41654
|
+
meant for hook-supplied paths. Never pass hook input through it.
|
|
41655
|
+
|
|
40875
41656
|
Returns the checkpoint file path, or None on failure.
|
|
40876
41657
|
"""
|
|
40877
41658
|
# Validate trigger before it flows into the checkpoint filename.
|
|
@@ -40893,7 +41674,9 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
|
|
|
40893
41674
|
ts = now.strftime("%Y-%m-%dT%H:%M:%S%z")
|
|
40894
41675
|
ts_file = now.strftime("%Y%m%d-%H%M%S")
|
|
40895
41676
|
|
|
40896
|
-
if
|
|
41677
|
+
if _trusted_transcript is not None:
|
|
41678
|
+
filepath = Path(_trusted_transcript)
|
|
41679
|
+
elif transcript_path:
|
|
40897
41680
|
# A supplied path that fails confinement is a forged hook input — do
|
|
40898
41681
|
# not checkpoint from it, and do not fall through to inference (which
|
|
40899
41682
|
# would let a bad pointer silently capture a different session).
|
|
@@ -40911,6 +41694,20 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
|
|
|
40911
41694
|
trigger_suffix = f"-{trigger}" if trigger and trigger != "auto" else ""
|
|
40912
41695
|
|
|
40913
41696
|
if not filepath or not filepath.exists():
|
|
41697
|
+
if _use_codex_session_adapter(transcript_path or None):
|
|
41698
|
+
# Codex with no readable transcript: a "No transcript data
|
|
41699
|
+
# available" placeholder (named "unknown" when the host sent no
|
|
41700
|
+
# session id) holds nothing to restore, can outrank real
|
|
41701
|
+
# checkpoints, and hides that capture failed (issue #278). Say
|
|
41702
|
+
# why instead, for the doctor; never the id or path themselves.
|
|
41703
|
+
_record_hook_status(
|
|
41704
|
+
"stop_capture" if trigger in ("stop", "end") else "checkpoint_capture",
|
|
41705
|
+
"skipped: " + (
|
|
41706
|
+
"the transcript path the host sent is outside the Codex sessions folder or unreadable"
|
|
41707
|
+
if transcript_path else
|
|
41708
|
+
"no Codex transcript matches the session id the host sent" if session_id else
|
|
41709
|
+
"the hook payload and environment carried no session id"))
|
|
41710
|
+
return None
|
|
40914
41711
|
# Write minimal checkpoint with safe permissions
|
|
40915
41712
|
sid = sanitize_session_id(session_id)
|
|
40916
41713
|
checkpoint_path = CHECKPOINT_DIR / f"{sid}-{ts_file}{trigger_suffix}.md"
|
|
@@ -40967,6 +41764,11 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
|
|
|
40967
41764
|
sid = sanitize_session_id(session_id) if session_id else sanitize_session_id(filepath.stem)
|
|
40968
41765
|
quality_summary = None
|
|
40969
41766
|
try:
|
|
41767
|
+
if _trusted_transcript is not None:
|
|
41768
|
+
# A translated transcript carries no usage data, so scoring it
|
|
41769
|
+
# would print a fake perfect grade. The caller passes the real
|
|
41770
|
+
# fill instead; the quality block is simply left out.
|
|
41771
|
+
raise _SkipTranscriptQuality()
|
|
40970
41772
|
# Prefer the per-session quality cache over re-parsing the whole transcript.
|
|
40971
41773
|
# _parse_jsonl_for_quality is O(file): a ~200MB session costs ~8s, and this
|
|
40972
41774
|
# runs on the synchronous Stop hook, so an unbounded reparse shows up as
|
|
@@ -41010,7 +41812,12 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
|
|
|
41010
41812
|
pass
|
|
41011
41813
|
fill_info = f" | Fill: {fill_pct:.0f}%" if fill_pct is not None else ""
|
|
41012
41814
|
quality_info = f" | Quality: {quality_score:.1f}" if quality_score is not None else ""
|
|
41013
|
-
|
|
41815
|
+
if _trusted_transcript is not None and not cwd:
|
|
41816
|
+
# No known working directory: this process's own cwd is not the
|
|
41817
|
+
# session's project, so its git state would be someone else's.
|
|
41818
|
+
git_branch, git_sha = None, None
|
|
41819
|
+
else:
|
|
41820
|
+
git_branch, git_sha = _capture_git_state(cwd)
|
|
41014
41821
|
git_line = ""
|
|
41015
41822
|
if git_branch or git_sha:
|
|
41016
41823
|
git_line = f" | Git: {git_branch or '?'}@{git_sha or '?'}"
|
|
@@ -42606,27 +43413,42 @@ _RESUME_TOPIC_STOPWORDS = frozenset({
|
|
|
42606
43413
|
|
|
42607
43414
|
|
|
42608
43415
|
# --- Non-English topic tokenizer — single source of truth on the Python side ---
|
|
42609
|
-
# Two branches: an ASCII/accented-Latin run, OR a whole non-ASCII run
|
|
42610
|
-
#
|
|
43416
|
+
# Two branches: an ASCII/accented-Latin run, OR a whole non-ASCII run as one token, so a token
|
|
43417
|
+
# never mixes ASCII and non-ASCII ("measure.py를" -> "measure.py" + "를").
|
|
42611
43418
|
# The Latin-1/Extended-A ranges deliberately skip U+00D7 (×) and U+00F7 (÷): they sit inside
|
|
42612
43419
|
# the block but are math symbols, not letters. U+0100–U+024F is Latin Extended-A/B, all letters.
|
|
42613
43420
|
_TOPIC_TOKEN_RE = re.compile(r"[a-zA-Z0-9_.:À-ÖØ-öø-ÿĀ-ɏ/-]+|[^\x00-\x7F]+")
|
|
42614
|
-
# Script-aware length floor
|
|
42615
|
-
#
|
|
42616
|
-
#
|
|
42617
|
-
#
|
|
42618
|
-
|
|
43421
|
+
# Script-aware length floor, defined by fixed code-point ranges so Python, OpenClaw and
|
|
43422
|
+
# OpenCode classify every character the same way on any Unicode version.
|
|
43423
|
+
# * Any char at or above U+3000 (Han, Kana, Hangul, fullwidth forms): a 2-char word such as
|
|
43424
|
+
# 결제 (payment) or 모듈 (module) is a full topic, so keep len>=2.
|
|
43425
|
+
# * Other non-Latin letters (Cyrillic, Greek, Arabic, Hebrew, Indic...): keep len>=3, which
|
|
43426
|
+
# keeps "кот" but drops 2-letter function words such as "на", "في", "של".
|
|
43427
|
+
# * Latin (ASCII, accented, extended, letterlike): the len>3 English stopword heuristic.
|
|
43428
|
+
# Combining marks (accents, niqqud, harakat) never count toward the length.
|
|
43429
|
+
_TOPIC_WIDE_MIN = 0x3000
|
|
43430
|
+
_TOPIC_LATIN_RANGES = (
|
|
43431
|
+
(0x0000, 0x036F), (0x1D00, 0x1DFF), (0x1E00, 0x1EFF), (0x2000, 0x214F),
|
|
43432
|
+
(0x2C60, 0x2C7F), (0xA720, 0xA7FF), (0xAB30, 0xAB6F),
|
|
43433
|
+
)
|
|
43434
|
+
_TOPIC_MARK_RANGES = (
|
|
43435
|
+
(0x0300, 0x036F), (0x0483, 0x0489), (0x0591, 0x05C7), (0x0610, 0x061A), (0x064B, 0x065F),
|
|
43436
|
+
(0x0670, 0x0670), (0x06D6, 0x06ED), (0x1AB0, 0x1AFF), (0x1DC0, 0x1DFF), (0x200B, 0x200F),
|
|
43437
|
+
(0x20D0, 0x20FF), (0xFE00, 0xFE0F), (0xFE20, 0xFE2F),
|
|
43438
|
+
)
|
|
42619
43439
|
|
|
42620
43440
|
|
|
42621
|
-
def
|
|
42622
|
-
|
|
42623
|
-
return any(ord(ch) >= _CJK_MIN for ch in w)
|
|
43441
|
+
def _in_ranges(cp, ranges):
|
|
43442
|
+
return any(lo <= cp <= hi for lo, hi in ranges)
|
|
42624
43443
|
|
|
42625
43444
|
|
|
42626
43445
|
def _topic_token_kept(w):
|
|
42627
|
-
if
|
|
42628
|
-
|
|
42629
|
-
|
|
43446
|
+
cps = [ord(ch) for ch in w if not _in_ranges(ord(ch), _TOPIC_MARK_RANGES)]
|
|
43447
|
+
if any(cp >= _TOPIC_WIDE_MIN for cp in cps):
|
|
43448
|
+
return len(cps) >= 2
|
|
43449
|
+
if any(not _in_ranges(cp, _TOPIC_LATIN_RANGES) for cp in cps):
|
|
43450
|
+
return len(cps) >= 3
|
|
43451
|
+
return len(cps) > 3
|
|
42630
43452
|
|
|
42631
43453
|
|
|
42632
43454
|
def _topic_tokens(text, stopwords=frozenset()):
|
|
@@ -43741,9 +44563,7 @@ def _transcript_last_turn(sid_safe):
|
|
|
43741
44563
|
u = msg.get("usage") or {}
|
|
43742
44564
|
if not isinstance(u, dict):
|
|
43743
44565
|
continue
|
|
43744
|
-
ctx = (
|
|
43745
|
-
+ _safe_int(u.get("cache_read_input_tokens"))
|
|
43746
|
-
+ _safe_int(u.get("cache_creation_input_tokens")))
|
|
44566
|
+
ctx = _context_token_count(_context_usage(u))
|
|
43747
44567
|
if ctx <= 0:
|
|
43748
44568
|
continue
|
|
43749
44569
|
model = _normalize_model_name(msg.get("model"))
|
|
@@ -43902,7 +44722,65 @@ def checkpoint_trigger(milestone=None, session_id=None, transcript_path=None, qu
|
|
|
43902
44722
|
return cp_path
|
|
43903
44723
|
|
|
43904
44724
|
|
|
43905
|
-
|
|
44725
|
+
_COMPACT_INSTR_HEAD = "When summarizing this session, pay special attention to:"
|
|
44726
|
+
_COMPACT_INSTR_TAIL = (
|
|
44727
|
+
"Always include the specific next step with enough detail to continue without asking."
|
|
44728
|
+
)
|
|
44729
|
+
_COMPACT_INSTR_BULLETS = frozenset({
|
|
44730
|
+
"- Architectural decisions and their reasoning",
|
|
44731
|
+
"- Skill invocations and their outcomes",
|
|
44732
|
+
"- External service interactions and their results",
|
|
44733
|
+
"- Modified file paths with line ranges",
|
|
44734
|
+
"- Error-fix sequences (what was tried, what failed, what worked)",
|
|
44735
|
+
"- Open questions and unresolved TODOs",
|
|
44736
|
+
"- Agent/team state (task assignments, completion status)",
|
|
44737
|
+
})
|
|
44738
|
+
# Separator used when our instructions are appended to the user's own text.
|
|
44739
|
+
_COMPACT_INSTR_MARKER = "\n\n# Token Optimizer additions:\n"
|
|
44740
|
+
|
|
44741
|
+
|
|
44742
|
+
def _compact_instructions_generated(text):
|
|
44743
|
+
"""True when ``text`` is exactly a block generate_compact_instructions writes."""
|
|
44744
|
+
if not isinstance(text, str):
|
|
44745
|
+
return False
|
|
44746
|
+
lines = text.strip().split("\n")
|
|
44747
|
+
if len(lines) < 2 or lines[0] != _COMPACT_INSTR_HEAD or lines[-1] != _COMPACT_INSTR_TAIL:
|
|
44748
|
+
return False
|
|
44749
|
+
return all(line in _COMPACT_INSTR_BULLETS for line in lines[1:-1])
|
|
44750
|
+
|
|
44751
|
+
|
|
44752
|
+
def _split_compact_instructions(text):
|
|
44753
|
+
"""Split a ``compactInstructions`` value into (user_part, ours_present).
|
|
44754
|
+
|
|
44755
|
+
Ours is either the whole value (a block we generated) or a section we
|
|
44756
|
+
appended after the user's own text behind ``_COMPACT_INSTR_MARKER``.
|
|
44757
|
+
Anything else is the user's and is returned untouched.
|
|
44758
|
+
"""
|
|
44759
|
+
if not isinstance(text, str):
|
|
44760
|
+
return text, False
|
|
44761
|
+
if _COMPACT_INSTR_MARKER in text:
|
|
44762
|
+
return text.split(_COMPACT_INSTR_MARKER, 1)[0].rstrip(), True
|
|
44763
|
+
if _compact_instructions_generated(text):
|
|
44764
|
+
return "", True
|
|
44765
|
+
return text, False
|
|
44766
|
+
|
|
44767
|
+
|
|
44768
|
+
def _remove_our_compact_instructions(settings):
|
|
44769
|
+
"""Drop our compactInstructions (keeping any user-written part). True if changed."""
|
|
44770
|
+
if not isinstance(settings, dict) or "compactInstructions" not in settings:
|
|
44771
|
+
return False
|
|
44772
|
+
user_part, ours = _split_compact_instructions(settings.get("compactInstructions"))
|
|
44773
|
+
if not ours:
|
|
44774
|
+
return False
|
|
44775
|
+
if user_part:
|
|
44776
|
+
settings["compactInstructions"] = user_part
|
|
44777
|
+
else:
|
|
44778
|
+
del settings["compactInstructions"]
|
|
44779
|
+
return True
|
|
44780
|
+
|
|
44781
|
+
|
|
44782
|
+
def generate_compact_instructions(as_json=False, install=False, dry_run=False,
|
|
44783
|
+
user_initiated=False):
|
|
43906
44784
|
"""Generate project-specific Compact Instructions.
|
|
43907
44785
|
|
|
43908
44786
|
Analyzes CLAUDE.md, recent session patterns, and common loss patterns
|
|
@@ -43913,7 +44791,7 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
|
|
|
43913
44791
|
"""
|
|
43914
44792
|
components = measure_components()
|
|
43915
44793
|
instructions_parts = [
|
|
43916
|
-
|
|
44794
|
+
_COMPACT_INSTR_HEAD,
|
|
43917
44795
|
]
|
|
43918
44796
|
|
|
43919
44797
|
# Analyze CLAUDE.md content for project priorities
|
|
@@ -43936,7 +44814,7 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
|
|
|
43936
44814
|
"- Modified file paths with line ranges",
|
|
43937
44815
|
"- Error-fix sequences (what was tried, what failed, what worked)",
|
|
43938
44816
|
"- Open questions and unresolved TODOs",
|
|
43939
|
-
|
|
44817
|
+
_COMPACT_INSTR_TAIL,
|
|
43940
44818
|
])
|
|
43941
44819
|
|
|
43942
44820
|
# Check for agent usage in recent sessions
|
|
@@ -43968,14 +44846,20 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
|
|
|
43968
44846
|
)
|
|
43969
44847
|
return instructions_text
|
|
43970
44848
|
existing = settings.get("compactInstructions", "")
|
|
44849
|
+
user_part, ours_present = _split_compact_instructions(existing)
|
|
43971
44850
|
|
|
43972
|
-
if existing and
|
|
44851
|
+
if existing and ours_present:
|
|
44852
|
+
# Refresh only our part. A value that also holds the user's own
|
|
44853
|
+
# text keeps it: replacing the whole value used to erase it.
|
|
43973
44854
|
if dry_run:
|
|
43974
44855
|
print(f"\n [Dry run] Would update existing compact instructions in {settings_path}")
|
|
43975
44856
|
print(f"\n Compact instructions preview:\n {instructions_text}\n")
|
|
43976
44857
|
return instructions_text
|
|
43977
|
-
settings["compactInstructions"] =
|
|
43978
|
-
|
|
44858
|
+
settings["compactInstructions"] = (
|
|
44859
|
+
user_part + _COMPACT_INSTR_MARKER + instructions_text
|
|
44860
|
+
if user_part else instructions_text
|
|
44861
|
+
)
|
|
44862
|
+
if not _write_settings_atomic(settings, user_initiated=user_initiated):
|
|
43979
44863
|
print("[Error] settings.json write was refused; compact instructions were not updated.", file=sys.stderr)
|
|
43980
44864
|
return instructions_text
|
|
43981
44865
|
print(f"[Token Optimizer] Compact Instructions updated in {settings_path}")
|
|
@@ -43983,7 +44867,7 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
|
|
|
43983
44867
|
|
|
43984
44868
|
if existing:
|
|
43985
44869
|
# User has their own instructions, append ours
|
|
43986
|
-
combined = existing.rstrip() +
|
|
44870
|
+
combined = existing.rstrip() + _COMPACT_INSTR_MARKER + instructions_text
|
|
43987
44871
|
if dry_run:
|
|
43988
44872
|
print(f"\n [Dry run] Would append to existing compact instructions in {settings_path}")
|
|
43989
44873
|
print(f"\n Appended:\n {instructions_text}\n")
|
|
@@ -43996,7 +44880,7 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
|
|
|
43996
44880
|
return instructions_text
|
|
43997
44881
|
settings["compactInstructions"] = instructions_text
|
|
43998
44882
|
|
|
43999
|
-
if not _write_settings_atomic(settings):
|
|
44883
|
+
if not _write_settings_atomic(settings, user_initiated=user_initiated):
|
|
44000
44884
|
print("[Error] settings.json write was refused; compact instructions were not installed.", file=sys.stderr)
|
|
44001
44885
|
return instructions_text
|
|
44002
44886
|
print(f"[Token Optimizer] Compact Instructions installed to {settings_path}")
|
|
@@ -44695,16 +45579,30 @@ def _smart_compact_hook_commands():
|
|
|
44695
45579
|
resolved to), the hook exits 0 silently instead of erroring on every event.
|
|
44696
45580
|
Mirrors the launcher guard in hooks.json.
|
|
44697
45581
|
"""
|
|
44698
|
-
mp = _get_measure_py_path()
|
|
44699
|
-
guard = f"[ -r
|
|
45582
|
+
py, mp = _settings_hook_python_and_script(_get_measure_py_path())
|
|
45583
|
+
guard = f"[ -r {mp} ] || exit 0; "
|
|
44700
45584
|
return {
|
|
44701
|
-
"PreCompact": f"{guard}
|
|
44702
|
-
"SessionStart": f"{guard}
|
|
44703
|
-
"Stop": f"{guard}
|
|
44704
|
-
"SessionEnd": f"{guard}
|
|
45585
|
+
"PreCompact": f"{guard}{py} {mp} compact-capture --trigger auto",
|
|
45586
|
+
"SessionStart": f"{guard}{py} {mp} compact-restore",
|
|
45587
|
+
"Stop": f"{guard}{py} {mp} compact-capture --trigger stop",
|
|
45588
|
+
"SessionEnd": f"{guard}{py} {mp} compact-capture --trigger end",
|
|
44705
45589
|
}
|
|
44706
45590
|
|
|
44707
45591
|
|
|
45592
|
+
def _settings_hook_python_and_script(mp):
|
|
45593
|
+
"""(interpreter, script) shell tokens for a settings.json hook command.
|
|
45594
|
+
|
|
45595
|
+
Claude Code runs these through Git Bash on Windows, where bare ``python3``
|
|
45596
|
+
is often missing or the Microsoft Store stub (exit 9009 on every event),
|
|
45597
|
+
so Windows names the running interpreter with forward slashes, quoted for
|
|
45598
|
+
bash (an apostrophe in the path is safe). POSIX keeps ``python3 '<mp>'``.
|
|
45599
|
+
"""
|
|
45600
|
+
if sys.platform == "win32":
|
|
45601
|
+
return (shlex.quote(str(sys.executable).replace("\\", "/")),
|
|
45602
|
+
shlex.quote(str(mp).replace("\\", "/")))
|
|
45603
|
+
return "python3", f"'{mp}'"
|
|
45604
|
+
|
|
45605
|
+
|
|
44708
45606
|
def _is_smart_compact_installed(settings=None):
|
|
44709
45607
|
"""Check which smart compact hooks are installed.
|
|
44710
45608
|
|
|
@@ -44757,7 +45655,8 @@ def _is_smart_compact_installed(settings=None):
|
|
|
44757
45655
|
return status
|
|
44758
45656
|
|
|
44759
45657
|
|
|
44760
|
-
def setup_smart_compact(dry_run=False, uninstall=False, status_only=False
|
|
45658
|
+
def setup_smart_compact(dry_run=False, uninstall=False, status_only=False,
|
|
45659
|
+
user_initiated=False):
|
|
44761
45660
|
"""Install, uninstall, or check status of smart compaction hooks.
|
|
44762
45661
|
|
|
44763
45662
|
Appends to existing hooks (never overwrites). Safe to run multiple times.
|
|
@@ -44822,10 +45721,16 @@ def setup_smart_compact(dry_run=False, uninstall=False, status_only=False):
|
|
|
44822
45721
|
return
|
|
44823
45722
|
|
|
44824
45723
|
settings["hooks"] = hooks
|
|
44825
|
-
|
|
45724
|
+
# setup-smart-compact also installed compactInstructions; take ours
|
|
45725
|
+
# back out (a user-written part stays).
|
|
45726
|
+
ci_removed = _remove_our_compact_instructions(settings)
|
|
45727
|
+
if not _write_settings_atomic(settings, allow_removing_keys={"compactInstructions"},
|
|
45728
|
+
user_initiated=user_initiated):
|
|
44826
45729
|
print("[Error] settings.json write was refused; smart compact hooks were not removed.", file=sys.stderr)
|
|
44827
45730
|
return
|
|
44828
45731
|
print(f"[Token Optimizer] Removed smart compact hooks. {removed} hook(s) removed.")
|
|
45732
|
+
if ci_removed:
|
|
45733
|
+
print("[Token Optimizer] Removed Token Optimizer compact instructions.")
|
|
44829
45734
|
return
|
|
44830
45735
|
|
|
44831
45736
|
# Install
|
|
@@ -44916,7 +45821,7 @@ def setup_smart_compact(dry_run=False, uninstall=False, status_only=False):
|
|
|
44916
45821
|
return
|
|
44917
45822
|
|
|
44918
45823
|
settings["hooks"] = hooks
|
|
44919
|
-
if not _write_settings_atomic(settings):
|
|
45824
|
+
if not _write_settings_atomic(settings, user_initiated=user_initiated):
|
|
44920
45825
|
print("[Error] settings.json write was refused; smart compact hooks were not installed.", file=sys.stderr)
|
|
44921
45826
|
return
|
|
44922
45827
|
|
|
@@ -44927,7 +45832,7 @@ def setup_smart_compact(dry_run=False, uninstall=False, status_only=False):
|
|
|
44927
45832
|
|
|
44928
45833
|
# Also install compact instructions (tells Claude WHAT to preserve)
|
|
44929
45834
|
print()
|
|
44930
|
-
generate_compact_instructions(install=True)
|
|
45835
|
+
generate_compact_instructions(install=True, user_initiated=user_initiated)
|
|
44931
45836
|
|
|
44932
45837
|
print("\n What happens now:")
|
|
44933
45838
|
print(" Compact Instructions: Guides Claude on what to preserve during compaction")
|
|
@@ -45761,6 +46666,9 @@ def _verbosity_nudge_min_fill() -> int:
|
|
|
45761
46666
|
|
|
45762
46667
|
_VERBOSITY_NUDGE_MIN_FILL = _verbosity_nudge_min_fill()
|
|
45763
46668
|
_VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD = 75
|
|
46669
|
+
# Lean-output nudge pacing: at most this many per session, this far apart.
|
|
46670
|
+
_VERBOSITY_MAX_NUDGES = 3
|
|
46671
|
+
_VERBOSITY_COOLDOWN_SEC = 300
|
|
45764
46672
|
_NUDGE_SESSION_CAP = 3
|
|
45765
46673
|
# Fresh-session nudge: when a session is BOTH long (high fill) and degraded
|
|
45766
46674
|
# (quality < threshold), suggest starting a fresh session -- cold-resume-lean
|
|
@@ -46518,7 +47426,9 @@ def quality_cache(throttle_seconds=120, warn_threshold=70, quiet=False, session_
|
|
|
46518
47426
|
result["session_start_ts"] = _extract_session_start_ts(filepath)
|
|
46519
47427
|
result["active_agents"] = _extract_active_agents(filepath)
|
|
46520
47428
|
|
|
46521
|
-
# Cache hit rate for statusline (v5.4.27)
|
|
47429
|
+
# Cache hit rate for statusline (v5.4.27). A billing ratio, so it reads
|
|
47430
|
+
# the top-level (advisor-summed) usage on purpose, unlike context fill,
|
|
47431
|
+
# which uses _context_usage (#287).
|
|
46522
47432
|
try:
|
|
46523
47433
|
total_input_all = 0
|
|
46524
47434
|
total_cache_read = 0
|
|
@@ -48007,7 +48917,8 @@ def _get_v5_savings_recommendation():
|
|
|
48007
48917
|
}
|
|
48008
48918
|
|
|
48009
48919
|
|
|
48010
|
-
def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=False, quiet=False
|
|
48920
|
+
def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=False, quiet=False,
|
|
48921
|
+
user_initiated=False):
|
|
48011
48922
|
"""Install, uninstall, or check quality bar (status line + cache hook).
|
|
48012
48923
|
|
|
48013
48924
|
Installs:
|
|
@@ -48026,6 +48937,12 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
|
|
|
48026
48937
|
every turn. The advisory is only shown on an explicit,
|
|
48027
48938
|
interactive `setup-quality-bar` run.
|
|
48028
48939
|
|
|
48940
|
+
user_initiated=True is passed only by the `setup-quality-bar` CLI command
|
|
48941
|
+
(the same for setup-hook / setup-smart-compact / compact-instructions):
|
|
48942
|
+
an explicit command takes the settings lease past the hook-herd
|
|
48943
|
+
reservation, so commands typed back to back are not refused. The
|
|
48944
|
+
automatic heal callers keep the default and the non-blocking lease.
|
|
48945
|
+
|
|
48029
48946
|
Side-effects on config.json:
|
|
48030
48947
|
install -> clears "quality_bar_disabled" (explicit opt-in)
|
|
48031
48948
|
--uninstall -> sets "quality_bar_disabled" (sticky opt-out)
|
|
@@ -48126,7 +49043,8 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
|
|
|
48126
49043
|
settings["hooks"] = hooks
|
|
48127
49044
|
# Deliberate top-level removal: declare it so the choke-point guard
|
|
48128
49045
|
# allows this one and only this one.
|
|
48129
|
-
if not _write_settings_atomic(settings, allow_removing_keys={"statusLine"}
|
|
49046
|
+
if not _write_settings_atomic(settings, allow_removing_keys={"statusLine"},
|
|
49047
|
+
user_initiated=user_initiated):
|
|
48130
49048
|
print("[Error] settings.json write was refused; Quality Bar was not removed.", file=sys.stderr)
|
|
48131
49049
|
return
|
|
48132
49050
|
_set_quality_bar_disabled(True)
|
|
@@ -48152,7 +49070,8 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
|
|
|
48152
49070
|
skipped.append("cache hook")
|
|
48153
49071
|
else:
|
|
48154
49072
|
hooks = settings.setdefault("hooks", {})
|
|
48155
|
-
|
|
49073
|
+
_py, _mp = _settings_hook_python_and_script(mp)
|
|
49074
|
+
hook_cmd = f"{_py} {_mp} quality-cache --quiet"
|
|
48156
49075
|
hook_entry = {"type": "command", "command": hook_cmd}
|
|
48157
49076
|
hook_group = {"hooks": [hook_entry]}
|
|
48158
49077
|
hooks.setdefault("UserPromptSubmit", []).append(hook_group)
|
|
@@ -48170,13 +49089,16 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
|
|
|
48170
49089
|
# is a clobber rather than an intentional choice).
|
|
48171
49090
|
try:
|
|
48172
49091
|
_rt_seg = RUNTIME_DIR.relative_to(HOME).as_posix()
|
|
49092
|
+
_rt_base = f"os.homedir(), '{_rt_seg}'"
|
|
48173
49093
|
except ValueError:
|
|
48174
|
-
|
|
49094
|
+
# Runtime dir outside HOME (e.g. CLAUDE_CONFIG_DIR on a
|
|
49095
|
+
# relocated volume): print its absolute path, never ~/.claude.
|
|
49096
|
+
_rt_base = json.dumps(RUNTIME_DIR.as_posix())
|
|
48175
49097
|
warnings.append(
|
|
48176
49098
|
"You already have a custom status line configured.\n"
|
|
48177
49099
|
" To integrate quality scoring, add this to your status line script:\n\n"
|
|
48178
49100
|
" // Read context quality score\n"
|
|
48179
|
-
f" const qFile = path.join(
|
|
49101
|
+
f" const qFile = path.join({_rt_base}, 'token-optimizer', 'quality-cache.json');\n"
|
|
48180
49102
|
" let qScore = '';\n"
|
|
48181
49103
|
" if (fs.existsSync(qFile)) {\n"
|
|
48182
49104
|
" try {\n"
|
|
@@ -48193,7 +49115,10 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
|
|
|
48193
49115
|
else:
|
|
48194
49116
|
settings["statusLine"] = {
|
|
48195
49117
|
"type": "command",
|
|
48196
|
-
|
|
49118
|
+
# A plain '...' wrap broke on an apostrophe in the path
|
|
49119
|
+
# (C:\Users\O'Brien). Keep the familiar form otherwise.
|
|
49120
|
+
"command": (f"node '{sl_path}'" if "'" not in str(sl_path)
|
|
49121
|
+
else f"node {shlex.quote(str(sl_path))}"),
|
|
48197
49122
|
}
|
|
48198
49123
|
installed.append("status line")
|
|
48199
49124
|
|
|
@@ -48221,7 +49146,7 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
|
|
|
48221
49146
|
return
|
|
48222
49147
|
|
|
48223
49148
|
if installed:
|
|
48224
|
-
if not _write_settings_atomic(settings):
|
|
49149
|
+
if not _write_settings_atomic(settings, user_initiated=user_initiated):
|
|
48225
49150
|
if not quiet:
|
|
48226
49151
|
print("[Error] settings.json write was refused; Quality Bar was not installed.", file=sys.stderr)
|
|
48227
49152
|
return
|
|
@@ -53921,7 +54846,11 @@ def _advice_session_data(path):
|
|
|
53921
54846
|
turns per-request context size (input + cache_read + cache_creation)
|
|
53922
54847
|
of each main-thread assistant usage row, in order; streamed
|
|
53923
54848
|
chunks sharing a requestId collapse to the largest row.
|
|
53924
|
-
cache_reads cache_read_input_tokens per turn (same indexing).
|
|
54849
|
+
cache_reads cache_read_input_tokens per turn (same indexing). This is
|
|
54850
|
+
the billed aggregate, while `turns` is executor occupancy
|
|
54851
|
+
(#287). On advisor sessions avoided reads (derived from
|
|
54852
|
+
`turns`) are measured against the larger billed total, so
|
|
54853
|
+
avoided_share_pct can only understate the saving.
|
|
53925
54854
|
boundaries indexes in `turns` that directly follow a compact_boundary.
|
|
53926
54855
|
model newest model id on a main-thread row, or None.
|
|
53927
54856
|
post_compact_ctx context size of the first request after each recorded
|
|
@@ -53976,9 +54905,10 @@ def _advice_session_data(path):
|
|
|
53976
54905
|
u = msg.get("usage")
|
|
53977
54906
|
if not isinstance(u, dict):
|
|
53978
54907
|
continue
|
|
54908
|
+
# Cache-read traffic is billed aggregate usage; occupancy is
|
|
54909
|
+
# only the final executor iteration of an advisor response.
|
|
53979
54910
|
cr = _safe_int(u.get("cache_read_input_tokens"))
|
|
53980
|
-
ctx = (
|
|
53981
|
-
+ _safe_int(u.get("cache_creation_input_tokens")))
|
|
54911
|
+
ctx = _context_token_count(_context_usage(u))
|
|
53982
54912
|
if ctx <= 0:
|
|
53983
54913
|
continue
|
|
53984
54914
|
m = msg.get("model")
|
|
@@ -57118,11 +58048,9 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
|
|
|
57118
58048
|
_now = _vs_time.time()
|
|
57119
58049
|
_nudge_count = cached.get("nudge_count", 0) or 0
|
|
57120
58050
|
_last_nudge = cached.get("last_nudge_time", 0) or 0
|
|
57121
|
-
|
|
57122
|
-
_MAX_NUDGES = 3
|
|
57123
|
-
if _nudge_count >= _MAX_NUDGES:
|
|
58051
|
+
if _nudge_count >= _VERBOSITY_MAX_NUDGES:
|
|
57124
58052
|
return ""
|
|
57125
|
-
if _now - _last_nudge <
|
|
58053
|
+
if _now - _last_nudge < _VERBOSITY_COOLDOWN_SEC:
|
|
57126
58054
|
return ""
|
|
57127
58055
|
|
|
57128
58056
|
# At 90%+ fill, don't add more tokens
|
|
@@ -57134,44 +58062,8 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
|
|
|
57134
58062
|
)
|
|
57135
58063
|
return ""
|
|
57136
58064
|
|
|
57137
|
-
|
|
57138
|
-
|
|
57139
|
-
# The spartan/ADHD phrasing is used verbatim because it produced the
|
|
57140
|
-
# largest reduction in verbose output across multiple models while
|
|
57141
|
-
# maintaining answer quality. Notes on what the data showed:
|
|
57142
|
-
# - Word ceilings were REMOVED. An earlier draft capped answers at
|
|
57143
|
-
# 80/120 words. A cap makes a model either truncate a genuinely
|
|
57144
|
-
# complex answer or ignore the nudge, and a nudge that gets ignored
|
|
57145
|
-
# is the original failure this rewrite exists to fix.
|
|
57146
|
-
# - The real waste is elaboration, not preamble. The padding-focused
|
|
57147
|
-
# wording targeted preamble and restatement and cut half as much,
|
|
57148
|
-
# because verbose answers mostly repeat themselves rather than
|
|
57149
|
-
# restate the question.
|
|
57150
|
-
# - Quality held. On the hardest fixture (prompt-caching explainer,
|
|
57151
|
-
# 1159 -> 759 words) the spartan answer kept every concept and
|
|
57152
|
-
# covered TTL MORE; what it dropped was the same point made six
|
|
57153
|
-
# times instead of three.
|
|
57154
|
-
# - Reasoning and deliverables are fenced off explicitly, because the
|
|
57155
|
-
# nudge fires mid-task where "spartan" could otherwise be read as
|
|
57156
|
-
# "write less code".
|
|
57157
|
-
# - Opus is roughly half as responsive as Sonnet here. Do not quote
|
|
57158
|
-
# the Sonnet figure as the product number.
|
|
57159
|
-
if fill_pct >= 75:
|
|
57160
|
-
nudge = (
|
|
57161
|
-
f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, resource health {score:.0f}/100. "
|
|
57162
|
-
"Answer in a focused and spartan way, as if the user has ADHD. Cut everything "
|
|
57163
|
-
"that is not the answer itself. Think as long as you need, and size code, "
|
|
57164
|
-
"diffs and file contents to the task."
|
|
57165
|
-
)
|
|
57166
|
-
elif (fill_pct >= _VERBOSITY_NUDGE_MIN_FILL
|
|
57167
|
-
and session_efficiency < _VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD):
|
|
57168
|
-
nudge = (
|
|
57169
|
-
f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, "
|
|
57170
|
-
f"session efficiency {session_efficiency:.0f}/100. "
|
|
57171
|
-
"Answer in a focused and spartan way, as if the user has ADHD. "
|
|
57172
|
-
"Think as long as you need, and size code, diffs and file contents to the task."
|
|
57173
|
-
)
|
|
57174
|
-
else:
|
|
58065
|
+
nudge = _verbosity_nudge_text(fill_pct, score, session_efficiency, cached)
|
|
58066
|
+
if not nudge:
|
|
57175
58067
|
return ""
|
|
57176
58068
|
|
|
57177
58069
|
payload = json.dumps({
|
|
@@ -57248,6 +58140,62 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
|
|
|
57248
58140
|
return ""
|
|
57249
58141
|
|
|
57250
58142
|
|
|
58143
|
+
def _verbosity_nudge_text(fill_pct, score, session_efficiency, cached):
|
|
58144
|
+
"""The lean-output nudge for a fill level, or "" when none applies.
|
|
58145
|
+
|
|
58146
|
+
Shared by Claude Code / Codex (run_verbosity_steer) and Hermes
|
|
58147
|
+
(hermes-turn-context), so every runtime gets the same tiers and wording.
|
|
58148
|
+
``cached`` is the quality-cache dict (or a small stand-in with
|
|
58149
|
+
``model_context_window``) that ``_format_context_fill`` reads.
|
|
58150
|
+
|
|
58151
|
+
Tiers:
|
|
58152
|
+
90%+ fill -> "" (adding tokens makes it worse)
|
|
58153
|
+
75-89% fill -> strong nudge
|
|
58154
|
+
_VERBOSITY_NUDGE_MIN_FILL-74% and session efficiency below
|
|
58155
|
+
_VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD -> gentle nudge
|
|
58156
|
+
"""
|
|
58157
|
+
if fill_pct >= 90:
|
|
58158
|
+
return ""
|
|
58159
|
+
# Determine nudge tier.
|
|
58160
|
+
#
|
|
58161
|
+
# The spartan/ADHD phrasing is used verbatim because it produced the
|
|
58162
|
+
# largest reduction in verbose output across multiple models while
|
|
58163
|
+
# maintaining answer quality. Notes on what the data showed:
|
|
58164
|
+
# - Word ceilings were REMOVED. An earlier draft capped answers at
|
|
58165
|
+
# 80/120 words. A cap makes a model either truncate a genuinely
|
|
58166
|
+
# complex answer or ignore the nudge, and a nudge that gets ignored
|
|
58167
|
+
# is the original failure this rewrite exists to fix.
|
|
58168
|
+
# - The real waste is elaboration, not preamble. The padding-focused
|
|
58169
|
+
# wording targeted preamble and restatement and cut half as much,
|
|
58170
|
+
# because verbose answers mostly repeat themselves rather than
|
|
58171
|
+
# restate the question.
|
|
58172
|
+
# - Quality held. On the hardest fixture (prompt-caching explainer,
|
|
58173
|
+
# 1159 -> 759 words) the spartan answer kept every concept and
|
|
58174
|
+
# covered TTL MORE; what it dropped was the same point made six
|
|
58175
|
+
# times instead of three.
|
|
58176
|
+
# - Reasoning and deliverables are fenced off explicitly, because the
|
|
58177
|
+
# nudge fires mid-task where "spartan" could otherwise be read as
|
|
58178
|
+
# "write less code".
|
|
58179
|
+
# - Opus is roughly half as responsive as Sonnet here. Do not quote
|
|
58180
|
+
# the Sonnet figure as the product number.
|
|
58181
|
+
if fill_pct >= 75:
|
|
58182
|
+
return (
|
|
58183
|
+
f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, resource health {score:.0f}/100. "
|
|
58184
|
+
"Answer in a focused and spartan way, as if the user has ADHD. Cut everything "
|
|
58185
|
+
"that is not the answer itself. Think as long as you need, and size code, "
|
|
58186
|
+
"diffs and file contents to the task."
|
|
58187
|
+
)
|
|
58188
|
+
if (fill_pct >= _VERBOSITY_NUDGE_MIN_FILL
|
|
58189
|
+
and session_efficiency < _VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD):
|
|
58190
|
+
return (
|
|
58191
|
+
f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, "
|
|
58192
|
+
f"session efficiency {session_efficiency:.0f}/100. "
|
|
58193
|
+
"Answer in a focused and spartan way, as if the user has ADHD. "
|
|
58194
|
+
"Think as long as you need, and size code, diffs and file contents to the task."
|
|
58195
|
+
)
|
|
58196
|
+
return ""
|
|
58197
|
+
|
|
58198
|
+
|
|
57251
58199
|
if __name__ == "__main__":
|
|
57252
58200
|
# On a non-UTF-8 host locale, re-exec under Python UTF-8 mode FIRST so every
|
|
57253
58201
|
# subprocess(text=True) decode (ps/git session detection), default open(), and
|
|
@@ -57448,7 +58396,7 @@ if __name__ == "__main__":
|
|
|
57448
58396
|
sys.exit(0)
|
|
57449
58397
|
elif args[0] == "copilot-rollup":
|
|
57450
58398
|
# Ingest recent Copilot sessions (CLI + VS Code planes) into trends.db.
|
|
57451
|
-
# Fired by the
|
|
58399
|
+
# Fired by the sessionEnd hook via copilot_hook_bridge.handle_session_end(); extra
|
|
57452
58400
|
# flags are silently consumed (INSERT OR IGNORE keeps this idempotent).
|
|
57453
58401
|
# Wall-clock backstop: this dispatch is spawned fire-and-forget by the
|
|
57454
58402
|
# Stop hook bridge (start_new_session=True, DEVNULL, no PID tracking),
|
|
@@ -57578,7 +58526,8 @@ if __name__ == "__main__":
|
|
|
57578
58526
|
# plugin's on_session_end hook via hermes_hook_bridge.run_rollup().
|
|
57579
58527
|
# --session <id> and --platform / --reason are accepted and silently
|
|
57580
58528
|
# consumed so the bridge's exact call signature never causes an error;
|
|
57581
|
-
# a full recent collect is always run (
|
|
58529
|
+
# a full recent collect is always run (idempotent: rows are keyed per
|
|
58530
|
+
# session and only refreshed when state.db has moved further along).
|
|
57582
58531
|
# Wall-clock backstop: same rationale as copilot-rollup above -- the
|
|
57583
58532
|
# Hermes bridge spawns this fire-and-forget with start_new_session=True
|
|
57584
58533
|
# and no PID tracking, so the parent hook deadline never propagates.
|
|
@@ -57586,6 +58535,7 @@ if __name__ == "__main__":
|
|
|
57586
58535
|
# session re-collects idempotently), a frozen orphan is not.
|
|
57587
58536
|
quiet = "--quiet" in args or "-q" in args
|
|
57588
58537
|
_HERMES_ROLLUP_CONTEXT = _parse_hermes_rollup_context(args[1:])
|
|
58538
|
+
_HERMES_ROLLUP_SKILLS = _parse_hermes_rollup_skills(args[1:])
|
|
57589
58539
|
_tok_hook_deadline = _install_hook_budget(60)
|
|
57590
58540
|
try:
|
|
57591
58541
|
_collect_hermes_sessions(days=90, quiet=quiet)
|
|
@@ -57596,6 +58546,36 @@ if __name__ == "__main__":
|
|
|
57596
58546
|
finally:
|
|
57597
58547
|
_clear_hook_budget(_tok_hook_deadline)
|
|
57598
58548
|
sys.exit(0)
|
|
58549
|
+
elif args[0] == "hermes-checkpoint":
|
|
58550
|
+
# Session checkpoint for a Hermes session, built from Hermes's own
|
|
58551
|
+
# state.db messages (read-only). Spawned detached by the Hermes plugin
|
|
58552
|
+
# at fill bands, before compaction, before subagent fan-out, after edit
|
|
58553
|
+
# batches, at turn end and at session end. Same 60s backstop as
|
|
58554
|
+
# hermes-rollup: a skipped checkpoint is invisible, a frozen orphan is not.
|
|
58555
|
+
_tok_hook_deadline = _install_hook_budget(60)
|
|
58556
|
+
try:
|
|
58557
|
+
_hermes_checkpoint_cli(args[1:])
|
|
58558
|
+
except _HookTimeout:
|
|
58559
|
+
pass
|
|
58560
|
+
except Exception:
|
|
58561
|
+
pass
|
|
58562
|
+
finally:
|
|
58563
|
+
_clear_hook_budget(_tok_hook_deadline)
|
|
58564
|
+
sys.exit(0)
|
|
58565
|
+
elif args[0] == "hermes-turn-context":
|
|
58566
|
+
# One child process per Hermes turn for continuity + lean-output (see
|
|
58567
|
+
# hermes_turn_context). Reads a JSON payload on stdin, prints one JSON
|
|
58568
|
+
# object. Same 8s budget as the Claude Code prompt hooks.
|
|
58569
|
+
_tok_hook_deadline = _install_hook_budget(8)
|
|
58570
|
+
try:
|
|
58571
|
+
print(json.dumps(hermes_turn_context(_read_stdin_hook_input())))
|
|
58572
|
+
except _HookTimeout:
|
|
58573
|
+
pass
|
|
58574
|
+
except Exception:
|
|
58575
|
+
pass
|
|
58576
|
+
finally:
|
|
58577
|
+
_clear_hook_budget(_tok_hook_deadline)
|
|
58578
|
+
sys.exit(0)
|
|
57599
58579
|
elif args[0] == "hermes-summary":
|
|
57600
58580
|
# Print a brief usage summary for the most recent Hermes sessions.
|
|
57601
58581
|
# Called by hermes_hook_bridge.run_summary() on /token-optimizer command.
|
|
@@ -57991,7 +58971,7 @@ if __name__ == "__main__":
|
|
|
57991
58971
|
elif args[0] == "setup-hook":
|
|
57992
58972
|
dry = "--dry-run" in args
|
|
57993
58973
|
uninstall = "--uninstall" in args
|
|
57994
|
-
setup_hook(dry_run=dry, uninstall=uninstall)
|
|
58974
|
+
setup_hook(dry_run=dry, uninstall=uninstall, user_initiated=True)
|
|
57995
58975
|
elif args[0] == "setup-all-hooks":
|
|
57996
58976
|
dry = "--dry-run" in args
|
|
57997
58977
|
verbose = "--verbose" in args or "-v" in args
|
|
@@ -58735,7 +59715,8 @@ if __name__ == "__main__":
|
|
|
58735
59715
|
output_json = "--json" in args
|
|
58736
59716
|
install = "--install" in args
|
|
58737
59717
|
dry = "--dry-run" in args
|
|
58738
|
-
generate_compact_instructions(as_json=output_json, install=install, dry_run=dry
|
|
59718
|
+
generate_compact_instructions(as_json=output_json, install=install, dry_run=dry,
|
|
59719
|
+
user_initiated=True)
|
|
58739
59720
|
elif args[0] == "dynamic-compact-instructions":
|
|
58740
59721
|
hook_input = _read_stdin_hook_input()
|
|
58741
59722
|
sid = hook_input.get("session_id") or os.environ.get("CLAUDE_SESSION_ID", "")
|
|
@@ -58744,7 +59725,8 @@ if __name__ == "__main__":
|
|
|
58744
59725
|
dry = "--dry-run" in args
|
|
58745
59726
|
uninstall = "--uninstall" in args
|
|
58746
59727
|
status = "--status" in args
|
|
58747
|
-
setup_smart_compact(dry_run=dry, uninstall=uninstall, status_only=status
|
|
59728
|
+
setup_smart_compact(dry_run=dry, uninstall=uninstall, status_only=status,
|
|
59729
|
+
user_initiated=True)
|
|
58748
59730
|
elif args[0] == "daemon-revive":
|
|
58749
59731
|
# Detached child spawned by _daemon_midsession_pulse. Revives a dead
|
|
58750
59732
|
# dashboard daemon OFF the hot path: force=True bypasses the 24h
|
|
@@ -59316,7 +60298,8 @@ if __name__ == "__main__":
|
|
|
59316
60298
|
dry = "--dry-run" in args
|
|
59317
60299
|
uninstall = "--uninstall" in args
|
|
59318
60300
|
status = "--status" in args
|
|
59319
|
-
setup_quality_bar(dry_run=dry, uninstall=uninstall, status_only=status
|
|
60301
|
+
setup_quality_bar(dry_run=dry, uninstall=uninstall, status_only=status,
|
|
60302
|
+
user_initiated=True)
|
|
59320
60303
|
elif args[0] == "setup-vscode-extension":
|
|
59321
60304
|
# Manage the VS Code status-bar extension auto-install.
|
|
59322
60305
|
# --uninstall : sticky opt-out (+ remove the extension if a CLI is present)
|