@alexgreensh/token-optimizer 5.13.57 → 5.13.60
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 +258 -16
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +229 -9
- 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 +76 -9
- package/skills/token-optimizer/scripts/hermes_tool_hooks.py +291 -0
- package/skills/token-optimizer/scripts/measure.py +1340 -321
- 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,216 @@ 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
|
+
_HERMES_PROFILE_HELP = (
|
|
24720
|
+
"\nProfiles: reads and writes the Hermes home in HERMES_HOME (default ~/.hermes).\n"
|
|
24721
|
+
"For a profile: HERMES_HOME=~/.hermes/profiles/<name> measure.py <command>"
|
|
24722
|
+
)
|
|
24723
|
+
_HERMES_SUBCOMMAND_HELP = {
|
|
24724
|
+
"hermes-rollup": (
|
|
24725
|
+
"usage: measure.py hermes-rollup [--quiet] [--session ID] [--platform P] [--reason R]\n"
|
|
24726
|
+
" [--context-tokens N] [--skills-json JSON]\n\n"
|
|
24727
|
+
"Ingest the last 90 days of Hermes sessions from state.db into trends.db.\n"
|
|
24728
|
+
"Run by the Hermes plugin at session end; safe to run by hand (idempotent).\n"
|
|
24729
|
+
"--session, --platform and --reason are accepted for the plugin's call shape;\n"
|
|
24730
|
+
"every recent session is collected either way." + _HERMES_PROFILE_HELP
|
|
24731
|
+
),
|
|
24732
|
+
"hermes-checkpoint": (
|
|
24733
|
+
"usage: measure.py hermes-checkpoint --session ID [--trigger T] [--fill-pct N]\n"
|
|
24734
|
+
" [--cwd DIR] [--quiet]\n\n"
|
|
24735
|
+
"Write a checkpoint for a Hermes session from its state.db messages." + _HERMES_PROFILE_HELP
|
|
24736
|
+
),
|
|
24737
|
+
"hermes-turn-context": (
|
|
24738
|
+
"usage: measure.py hermes-turn-context < payload.json\n\n"
|
|
24739
|
+
"Per-turn context for the Hermes plugin (continuity pointer, prior-session hint,\n"
|
|
24740
|
+
"lean-output nudge). Reads one JSON payload on stdin, prints one JSON object." + _HERMES_PROFILE_HELP
|
|
24741
|
+
),
|
|
24742
|
+
"hermes-summary": (
|
|
24743
|
+
"usage: measure.py hermes-summary [--days N] [--quiet] [--session ID]\n\n"
|
|
24744
|
+
"Ingest recent Hermes sessions, then print usage trends." + _HERMES_PROFILE_HELP
|
|
24745
|
+
),
|
|
24746
|
+
}
|
|
24747
|
+
|
|
24748
|
+
|
|
24749
|
+
def _hermes_checkpoint_cli(args):
|
|
24750
|
+
"""``hermes-checkpoint --session <id> [--trigger T] [--fill-pct N] [--cwd DIR] [--quiet]``."""
|
|
24751
|
+
sid = ""
|
|
24752
|
+
trigger = "stop"
|
|
24753
|
+
fill_pct = None
|
|
24754
|
+
cwd = None
|
|
24755
|
+
i = 0
|
|
24756
|
+
while i < len(args):
|
|
24757
|
+
a = args[i]
|
|
24758
|
+
if a == "--session" and i + 1 < len(args):
|
|
24759
|
+
sid = args[i + 1]
|
|
24760
|
+
i += 2
|
|
24761
|
+
elif a == "--trigger" and i + 1 < len(args):
|
|
24762
|
+
trigger = args[i + 1]
|
|
24763
|
+
i += 2
|
|
24764
|
+
elif a == "--fill-pct" and i + 1 < len(args):
|
|
24765
|
+
try:
|
|
24766
|
+
fill_pct = float(args[i + 1])
|
|
24767
|
+
except ValueError:
|
|
24768
|
+
fill_pct = None
|
|
24769
|
+
i += 2
|
|
24770
|
+
elif a == "--cwd" and i + 1 < len(args):
|
|
24771
|
+
cwd = args[i + 1] or None
|
|
24772
|
+
i += 2
|
|
24773
|
+
else:
|
|
24774
|
+
i += 1
|
|
24775
|
+
quiet = "--quiet" in args or "-q" in args
|
|
24776
|
+
if cwd is not None:
|
|
24777
|
+
try:
|
|
24778
|
+
if not Path(cwd).is_dir():
|
|
24779
|
+
cwd = None
|
|
24780
|
+
except (OSError, ValueError):
|
|
24781
|
+
cwd = None
|
|
24782
|
+
result = hermes_checkpoint(sid, trigger=trigger, fill_pct=fill_pct, cwd=cwd)
|
|
24783
|
+
if result and not quiet:
|
|
24784
|
+
print(f"[Token Optimizer] Checkpoint saved: {result}")
|
|
24785
|
+
return result
|
|
24786
|
+
|
|
24787
|
+
|
|
24788
|
+
def hermes_turn_context(payload):
|
|
24789
|
+
"""Per-turn model context for a Hermes session, in one process.
|
|
24790
|
+
|
|
24791
|
+
Same engines Claude Code's SessionStart / UserPromptSubmit hooks run:
|
|
24792
|
+
- first turn: the new-session checkpoint pointer (compact_restore)
|
|
24793
|
+
- every turn: the topic-matched prior-session hint (_continuity_prompt_hint)
|
|
24794
|
+
- when the plugin passes a live fill reading: the lean-output nudge
|
|
24795
|
+
(_verbosity_nudge_text). Hermes has no session-efficiency signal, so
|
|
24796
|
+
only the strong tier (75-89% fill) can apply; the plugin paces it.
|
|
24797
|
+
|
|
24798
|
+
``payload`` keys: session_id, prompt, first_turn, fill_pct, score.
|
|
24799
|
+
Returns {"parts": [...], "verbosity": bool}. Never raises.
|
|
24800
|
+
"""
|
|
24801
|
+
out = {"parts": [], "verbosity": False}
|
|
24802
|
+
if not isinstance(payload, dict):
|
|
24803
|
+
return out
|
|
24804
|
+
sid = str(payload.get("session_id") or "").strip()
|
|
24805
|
+
if not sid:
|
|
24806
|
+
return out
|
|
24807
|
+
if payload.get("first_turn"):
|
|
24808
|
+
from contextlib import redirect_stdout as _redirect_stdout # noqa: PLC0415
|
|
24809
|
+
|
|
24810
|
+
buf = io.StringIO()
|
|
24811
|
+
try:
|
|
24812
|
+
with _redirect_stdout(buf):
|
|
24813
|
+
compact_restore(session_id=sid, new_session_only=True)
|
|
24814
|
+
except Exception:
|
|
24815
|
+
pass
|
|
24816
|
+
pointer = buf.getvalue().strip()
|
|
24817
|
+
if pointer:
|
|
24818
|
+
out["parts"].append(pointer)
|
|
24819
|
+
prompt = str(payload.get("prompt") or "").strip()
|
|
24820
|
+
if prompt:
|
|
24821
|
+
try:
|
|
24822
|
+
hint = (_continuity_prompt_hint(prompt_text=prompt[:4000], session_id=sid) or "").strip()
|
|
24823
|
+
except Exception:
|
|
24824
|
+
hint = ""
|
|
24825
|
+
if hint:
|
|
24826
|
+
out["parts"].append(hint)
|
|
24827
|
+
fill = payload.get("fill_pct")
|
|
24828
|
+
if isinstance(fill, (int, float)) and not isinstance(fill, bool):
|
|
24829
|
+
score = payload.get("score")
|
|
24830
|
+
score = float(score) if isinstance(score, (int, float)) and not isinstance(score, bool) else 100.0
|
|
24831
|
+
# No efficiency signal on Hermes: 100 keeps the gentle tier off.
|
|
24832
|
+
window = payload.get("context_window")
|
|
24833
|
+
cached = ({"model_context_window": int(window)}
|
|
24834
|
+
if isinstance(window, int) and not isinstance(window, bool) and window > 0 else {})
|
|
24835
|
+
nudge = _verbosity_nudge_text(float(fill), score, 100, cached)
|
|
24836
|
+
if nudge:
|
|
24837
|
+
out["parts"].append(nudge)
|
|
24838
|
+
out["verbosity"] = True
|
|
24839
|
+
return out
|
|
24840
|
+
|
|
24841
|
+
|
|
24246
24842
|
def _resolve_copilot_home_wsl_aware(mnt_root=None):
|
|
24247
24843
|
"""Resolve the Copilot home with a WSL-root /mnt/ exception.
|
|
24248
24844
|
|
|
@@ -27573,7 +28169,7 @@ def usage_trends(days=30, as_json=False):
|
|
|
27573
28169
|
|
|
27574
28170
|
print(f"\nUSAGE TRENDS (last {days} days)")
|
|
27575
28171
|
print("=" * 55)
|
|
27576
|
-
print(f"\n Sessions: {session_count} | Avg duration: {avg_dur:.0f} min | Avg tokens/session: {_fmt_tokens(avg_in)} in / {_fmt_tokens(avg_out)} out")
|
|
28172
|
+
print(f"\n Sessions: {session_count} | Avg duration: {avg_dur:.0f} min | Avg tokens/session: {_fmt_tokens(avg_in)} in (incl. cache reads) / {_fmt_tokens(avg_out)} out")
|
|
27577
28173
|
|
|
27578
28174
|
skill_sessions = trends["skills"]["used"]
|
|
27579
28175
|
installed_count = trends["skills"]["installed_count"]
|
|
@@ -27615,7 +28211,9 @@ def usage_trends(days=30, as_json=False):
|
|
|
27615
28211
|
|
|
27616
28212
|
total_model_tokens = trends["model_mix"]
|
|
27617
28213
|
if total_model_tokens:
|
|
27618
|
-
|
|
28214
|
+
# Model shares count fresh input + output (cache reads excluded), unlike
|
|
28215
|
+
# the per-session average above; say so, or the two read as contradictory.
|
|
28216
|
+
print("\nMODEL MIX (share of tokens, excl. cache reads)")
|
|
27619
28217
|
grand_total = sum(total_model_tokens.values())
|
|
27620
28218
|
for model, tokens in sorted(total_model_tokens.items(), key=lambda x: -x[1]):
|
|
27621
28219
|
pct = tokens / grand_total * 100 if grand_total else 0
|
|
@@ -29061,6 +29659,10 @@ def _resolve_runtime_bin(process_name):
|
|
|
29061
29659
|
Path("/usr/local/bin") / process_name,
|
|
29062
29660
|
home / ".bun" / "bin" / process_name,
|
|
29063
29661
|
]
|
|
29662
|
+
# Claude Code's local installer lives under its config dir, so a relocated
|
|
29663
|
+
# CLAUDE_CONFIG_DIR moves it off ~/.claude/local.
|
|
29664
|
+
if process_name == "claude" and CLAUDE_DIR / "local" / process_name not in candidates:
|
|
29665
|
+
candidates.insert(2, CLAUDE_DIR / "local" / process_name)
|
|
29064
29666
|
for cand in candidates:
|
|
29065
29667
|
try:
|
|
29066
29668
|
if cand.is_file() and os.access(str(cand), os.X_OK):
|
|
@@ -30829,7 +31431,7 @@ def _maybe_self_heal_sessionend_fossils_on_hook():
|
|
|
30829
31431
|
_clear_hook_budget(deadline)
|
|
30830
31432
|
|
|
30831
31433
|
|
|
30832
|
-
def setup_hook(dry_run=False, uninstall=False):
|
|
31434
|
+
def setup_hook(dry_run=False, uninstall=False, user_initiated=False):
|
|
30833
31435
|
"""Install or uninstall the SessionEnd hook for automatic usage collection.
|
|
30834
31436
|
|
|
30835
31437
|
``uninstall=True`` removes ONLY Token Optimizer's own SessionEnd hook
|
|
@@ -30885,7 +31487,7 @@ def setup_hook(dry_run=False, uninstall=False):
|
|
|
30885
31487
|
import shutil
|
|
30886
31488
|
shutil.copy2(str(SETTINGS_PATH), str(backup_path))
|
|
30887
31489
|
try:
|
|
30888
|
-
if not _write_settings_atomic(settings):
|
|
31490
|
+
if not _write_settings_atomic(settings, user_initiated=user_initiated):
|
|
30889
31491
|
print("[Error] settings.json write was refused; no SessionEnd hooks were removed.", file=sys.stderr)
|
|
30890
31492
|
return
|
|
30891
31493
|
print(f"[Token Optimizer] Removed {removed} Token Optimizer SessionEnd hook(s) from settings.json.")
|
|
@@ -30977,7 +31579,7 @@ def setup_hook(dry_run=False, uninstall=False):
|
|
|
30977
31579
|
|
|
30978
31580
|
# Write atomically
|
|
30979
31581
|
try:
|
|
30980
|
-
if not _write_settings_atomic(settings):
|
|
31582
|
+
if not _write_settings_atomic(settings, user_initiated=user_initiated):
|
|
30981
31583
|
print("[Error] settings.json write was refused; SessionEnd hook was not installed.", file=sys.stderr)
|
|
30982
31584
|
return
|
|
30983
31585
|
action = "upgraded" if upgrading else "installed"
|
|
@@ -33244,13 +33846,7 @@ def _daemon_install_lock(soft_fail=False):
|
|
|
33244
33846
|
MAX_LOCK_AGE = 10 * 60 # 10 minutes
|
|
33245
33847
|
|
|
33246
33848
|
def _pid_alive(pid):
|
|
33247
|
-
|
|
33248
|
-
return False
|
|
33249
|
-
try:
|
|
33250
|
-
os.kill(pid, 0)
|
|
33251
|
-
return True
|
|
33252
|
-
except OSError:
|
|
33253
|
-
return False
|
|
33849
|
+
return _pid_is_running(pid)
|
|
33254
33850
|
|
|
33255
33851
|
def _try_reclaim_stale():
|
|
33256
33852
|
"""Return True if we successfully reaped a stale lock, False otherwise."""
|
|
@@ -34045,6 +34641,11 @@ def _generate_windows_launcher_cmd(daemon_script_path, log_dir):
|
|
|
34045
34641
|
|
|
34046
34642
|
return (
|
|
34047
34643
|
"@echo off\r\n"
|
|
34644
|
+
# cmd.exe reads a batch file in the console (OEM) code page, but this
|
|
34645
|
+
# file is written as UTF-8: a profile path like C:\Users\Jos\u00e9 was
|
|
34646
|
+
# garbled and the daemon never started. Switch to UTF-8 first; this
|
|
34647
|
+
# line and everything above it is plain ASCII.
|
|
34648
|
+
"chcp 65001\r\n"
|
|
34048
34649
|
"REM Token Optimizer dashboard daemon launcher (v5.3.2+).\r\n"
|
|
34049
34650
|
"REM Auto-generated. Resolves Python at runtime so interpreter upgrades\r\n"
|
|
34050
34651
|
"REM do not break the scheduled task.\r\n"
|
|
@@ -34058,7 +34659,7 @@ def _generate_windows_launcher_cmd(daemon_script_path, log_dir):
|
|
|
34058
34659
|
f'set "STDOUT_LOG={log_dir}\\stdout.log"\r\n'
|
|
34059
34660
|
f'set "STDERR_LOG={log_dir}\\stderr.log"\r\n'
|
|
34060
34661
|
'if not exist "%DAEMON_SCRIPT%" (\r\n'
|
|
34061
|
-
' echo [%DATE% %TIME%] daemon script missing: %DAEMON_SCRIPT% >> "%STDERR_LOG%"\r\n'
|
|
34662
|
+
' echo [%DATE% %TIME%] daemon script missing: "%DAEMON_SCRIPT%" >> "%STDERR_LOG%"\r\n'
|
|
34062
34663
|
" exit /b 1\r\n"
|
|
34063
34664
|
")\r\n"
|
|
34064
34665
|
'set "PYW_EXE="\r\n'
|
|
@@ -35057,6 +35658,15 @@ def _retained_paths() -> list[tuple[str, Path]]:
|
|
|
35057
35658
|
pass
|
|
35058
35659
|
# Always include the resolved snapshot dir even under a sandbox override.
|
|
35059
35660
|
paths.append(("session data (this install)", SNAPSHOT_DIR))
|
|
35661
|
+
# Compaction checkpoints (conversation-context captures) live under the
|
|
35662
|
+
# per-session state base, which on a script install is NOT inside
|
|
35663
|
+
# SNAPSHOT_DIR (#106 named them as undisclosed). Disclose them too.
|
|
35664
|
+
try:
|
|
35665
|
+
listed = {p for _, p in paths}
|
|
35666
|
+
if CHECKPOINT_DIR not in listed:
|
|
35667
|
+
paths.append(("checkpoints (this install)", CHECKPOINT_DIR))
|
|
35668
|
+
except NameError:
|
|
35669
|
+
pass
|
|
35060
35670
|
return paths
|
|
35061
35671
|
|
|
35062
35672
|
|
|
@@ -35133,6 +35743,9 @@ def _remove_our_settings_entries(settings: dict) -> list[str]:
|
|
|
35133
35743
|
``quality-cache`` (our cache hook).
|
|
35134
35744
|
- ``SessionEnd`` hook entries that are ours (reuses
|
|
35135
35745
|
_remove_token_optimizer_session_end_hooks).
|
|
35746
|
+
- ``compactInstructions`` when it is the block setup-smart-compact
|
|
35747
|
+
generated (removed) or holds our appended section (only that section
|
|
35748
|
+
is removed; the user's own text stays).
|
|
35136
35749
|
|
|
35137
35750
|
Foreign statusLines, foreign hooks, and every other settings key are left
|
|
35138
35751
|
byte-identical. Returns a list of human-readable descriptions of what was
|
|
@@ -35200,6 +35813,10 @@ def _remove_our_settings_entries(settings: dict) -> list[str]:
|
|
|
35200
35813
|
n_session_end = _remove_token_optimizer_session_end_hooks(settings)
|
|
35201
35814
|
if n_session_end:
|
|
35202
35815
|
removed.append(f"{n_session_end} SessionEnd hook(s)")
|
|
35816
|
+
# compactInstructions written by setup-smart-compact (#106: it outlived
|
|
35817
|
+
# cleanup). Only our generated block / appended section is removed.
|
|
35818
|
+
if _remove_our_compact_instructions(settings):
|
|
35819
|
+
removed.append("compactInstructions (token-optimizer)")
|
|
35203
35820
|
return removed
|
|
35204
35821
|
|
|
35205
35822
|
|
|
@@ -35248,6 +35865,24 @@ def cleanup(dry_run=False, this_install_only=False):
|
|
|
35248
35865
|
# the preview stays side-effect-free.
|
|
35249
35866
|
if not dry_run:
|
|
35250
35867
|
_unlink_if_exists(PLIST_PATH)
|
|
35868
|
+
# Same reasoning for the other platforms' per-identity daemon files:
|
|
35869
|
+
# each platform's uninstaller sweeps only its own launcher, so a HOME
|
|
35870
|
+
# synced or migrated from another OS kept dashboard-launcher.cmd /
|
|
35871
|
+
# .schtasks-daemon.xml (Windows) or the Linux launcher after cleanup
|
|
35872
|
+
# (#106). They are plain files once the scheduler job is gone.
|
|
35873
|
+
if not _daemon_snapshot_sandboxed():
|
|
35874
|
+
for _snap in _daemon_identity_snapshot_dirs(this_install_only):
|
|
35875
|
+
_gone, _ = _sweep_identity_daemon_files(
|
|
35876
|
+
_snap, ("daemon_script", "daemon_token", "daemon_host",
|
|
35877
|
+
"windows_launcher", "linux_launcher"))
|
|
35878
|
+
try:
|
|
35879
|
+
for _xml in _snap.glob("*schtasks-daemon*.xml"):
|
|
35880
|
+
if _unlink_if_exists(_xml):
|
|
35881
|
+
_gone.append(str(_xml))
|
|
35882
|
+
except OSError:
|
|
35883
|
+
pass
|
|
35884
|
+
for _path in _gone:
|
|
35885
|
+
print(f" Deleted: {_path}")
|
|
35251
35886
|
print()
|
|
35252
35887
|
|
|
35253
35888
|
# 2. settings.json
|
|
@@ -35297,7 +35932,14 @@ def cleanup(dry_run=False, this_install_only=False):
|
|
|
35297
35932
|
# silent no-op. Reporting "Removed" for a write that never
|
|
35298
35933
|
# landed leaves the user with the dangling statusLine this
|
|
35299
35934
|
# command exists to clear, so surface it instead.
|
|
35300
|
-
|
|
35935
|
+
# user_initiated: cleanup is an explicit user command. Under
|
|
35936
|
+
# the hook cohort throttle any Token Optimizer settings
|
|
35937
|
+
# write in the previous ~10s (a SessionStart heal, a setup
|
|
35938
|
+
# command) made this write lose the lease, and the whole
|
|
35939
|
+
# removal was skipped (#106 leftovers).
|
|
35940
|
+
if _write_settings_atomic(
|
|
35941
|
+
fresh, allow_removing_keys={"statusLine", "compactInstructions"},
|
|
35942
|
+
user_initiated=True):
|
|
35301
35943
|
for entry in our_entries:
|
|
35302
35944
|
print(f" Removed: {entry}")
|
|
35303
35945
|
print(f" Backup: {backed}")
|
|
@@ -36544,7 +37186,8 @@ def _external_memory_present() -> bool:
|
|
|
36544
37186
|
without touching the filesystem.
|
|
36545
37187
|
2. A neutral coordination marker file, whose mere existence means an
|
|
36546
37188
|
external durable-memory tool is active:
|
|
36547
|
-
``${TO_EXTERNAL_MEMORY_MARKER
|
|
37189
|
+
``${TO_EXTERNAL_MEMORY_MARKER:-<claude home>/durable-memory.json}``, where the
|
|
37190
|
+
Claude home honors CLAUDE_CONFIG_DIR (CLAUDE_DIR / claude_home()).
|
|
36548
37191
|
|
|
36549
37192
|
The external tool writes the marker once (set-and-forget), so detection is
|
|
36550
37193
|
automatic with no per-session configuration. Cached in a module global so
|
|
@@ -36568,7 +37211,7 @@ def _external_memory_present() -> bool:
|
|
|
36568
37211
|
marker = (
|
|
36569
37212
|
Path(marker_env).expanduser()
|
|
36570
37213
|
if marker_env
|
|
36571
|
-
else
|
|
37214
|
+
else CLAUDE_DIR / "durable-memory.json"
|
|
36572
37215
|
)
|
|
36573
37216
|
try:
|
|
36574
37217
|
if marker.exists():
|
|
@@ -36647,6 +37290,100 @@ def _extract_user_text(record):
|
|
|
36647
37290
|
return ""
|
|
36648
37291
|
|
|
36649
37292
|
|
|
37293
|
+
_HARNESS_TASK_PREFIXES = (
|
|
37294
|
+
"<local-command-caveat>", "<local-command-stdout>",
|
|
37295
|
+
"<local-command-stderr>", "<task-notification>",
|
|
37296
|
+
"[SYSTEM NOTIFICATION", "[Request interrupted by user",
|
|
37297
|
+
"Your response above was cut off mid-stream",
|
|
37298
|
+
)
|
|
37299
|
+
# Built-in commands that only change the session or UI. Run bare, they are not
|
|
37300
|
+
# a task. With arguments, or when an installed skill owns the name, they are.
|
|
37301
|
+
_LOCAL_SLASH_COMMANDS = frozenset((
|
|
37302
|
+
"add-dir", "agents", "bug", "config", "context", "continue", "cost",
|
|
37303
|
+
"doctor", "exit", "export", "fast", "feedback", "help", "hooks", "ide",
|
|
37304
|
+
"init", "login", "logout", "mcp", "memory", "model", "output-style",
|
|
37305
|
+
"permissions", "privacy-settings", "quit", "release-notes", "resume",
|
|
37306
|
+
"rewind", "settings", "stats", "status", "statusline", "terminal-setup",
|
|
37307
|
+
"theme", "upgrade", "usage", "vim",
|
|
37308
|
+
))
|
|
37309
|
+
_COMMAND_TASK_TAG_RE = re.compile(r"\s*<command-(name|message|args)>")
|
|
37310
|
+
|
|
37311
|
+
|
|
37312
|
+
def _command_task_text(text):
|
|
37313
|
+
"""Unwrap a complete command once, with bounded, non-backtracking scans."""
|
|
37314
|
+
fields = {}
|
|
37315
|
+
pos = 0
|
|
37316
|
+
while pos < len(text):
|
|
37317
|
+
if not text[pos:].strip():
|
|
37318
|
+
break
|
|
37319
|
+
tag = _COMMAND_TASK_TAG_RE.match(text, pos)
|
|
37320
|
+
if tag is None or tag.group(1) in fields:
|
|
37321
|
+
return ""
|
|
37322
|
+
name = tag.group(1)
|
|
37323
|
+
close = "</command-" + name + ">"
|
|
37324
|
+
end = text.find(close, tag.end())
|
|
37325
|
+
if end < 0:
|
|
37326
|
+
return ""
|
|
37327
|
+
fields[name] = text[tag.end():end]
|
|
37328
|
+
pos = end + len(close)
|
|
37329
|
+
command = _SLASH_COMMAND_RE.fullmatch(
|
|
37330
|
+
"<command-name>" + fields.get("name", "") + "</command-name>")
|
|
37331
|
+
if command is None:
|
|
37332
|
+
return ""
|
|
37333
|
+
name = command.group(1)
|
|
37334
|
+
if name.lower() in ("compact", "clear"):
|
|
37335
|
+
return ""
|
|
37336
|
+
# Some versions omit an empty <command-args>: treat a missing tag as empty.
|
|
37337
|
+
args = fields.get("args", "").strip()
|
|
37338
|
+
if (not args and name.lower() in _LOCAL_SLASH_COMMANDS
|
|
37339
|
+
and not _resolve_installed_skill(name)):
|
|
37340
|
+
return ""
|
|
37341
|
+
return "/" + name + (" " + args if args else "")
|
|
37342
|
+
|
|
37343
|
+
|
|
37344
|
+
def _task_user_text(record):
|
|
37345
|
+
"""Task text for continuity only, excluding harness/meta/tool transport.
|
|
37346
|
+
|
|
37347
|
+
A slash-command wrapper is transport, but its name and arguments can be
|
|
37348
|
+
a real task. Preserve those without changing raw scoring/skill-use input.
|
|
37349
|
+
"""
|
|
37350
|
+
if record.get("isMeta") or record.get("isCompactSummary"):
|
|
37351
|
+
return ""
|
|
37352
|
+
message = record.get("message", {})
|
|
37353
|
+
content = message.get("content") if isinstance(message, dict) else message
|
|
37354
|
+
if isinstance(content, str):
|
|
37355
|
+
parts = [content]
|
|
37356
|
+
elif isinstance(content, list):
|
|
37357
|
+
parts = [
|
|
37358
|
+
block if isinstance(block, str) else block.get("text", "")
|
|
37359
|
+
for block in content
|
|
37360
|
+
if isinstance(block, str) or (
|
|
37361
|
+
isinstance(block, dict) and block.get("type") == "text")
|
|
37362
|
+
]
|
|
37363
|
+
else:
|
|
37364
|
+
return ""
|
|
37365
|
+
texts = []
|
|
37366
|
+
for part in parts:
|
|
37367
|
+
if not isinstance(part, str):
|
|
37368
|
+
continue
|
|
37369
|
+
text = part.strip()
|
|
37370
|
+
# A <system-reminder> block can lead a real prompt: drop the block,
|
|
37371
|
+
# keep what follows. An unclosed block is all harness.
|
|
37372
|
+
while text.startswith("<system-reminder>"):
|
|
37373
|
+
end = text.find("</system-reminder>")
|
|
37374
|
+
text = "" if end < 0 else text[end + len("</system-reminder>"):].strip()
|
|
37375
|
+
if not text or text.startswith(_HARNESS_TASK_PREFIXES):
|
|
37376
|
+
continue
|
|
37377
|
+
if text.startswith(("<command-name>", "<command-message>", "<command-args>")):
|
|
37378
|
+
# Only a complete wrapper is an invocation. Do not turn malformed
|
|
37379
|
+
# harness markup into a recovered task, or strip tags from prose.
|
|
37380
|
+
text = _command_task_text(text)
|
|
37381
|
+
if not text:
|
|
37382
|
+
continue
|
|
37383
|
+
texts.append(text)
|
|
37384
|
+
return "\n".join(texts)
|
|
37385
|
+
|
|
37386
|
+
|
|
36650
37387
|
def _read_stdin_hook_input(max_bytes=65536):
|
|
36651
37388
|
"""Thin wrapper: measure.py callers default to 64KB (PreToolUse payloads)."""
|
|
36652
37389
|
return _read_stdin_hook_input_shared(max_bytes)
|
|
@@ -36809,9 +37546,7 @@ def _parse_jsonl_for_quality(filepath):
|
|
|
36809
37546
|
# raise and abort the whole parse (losing all quality data).
|
|
36810
37547
|
usage = msg.get("usage")
|
|
36811
37548
|
if isinstance(usage, dict):
|
|
36812
|
-
tok = (
|
|
36813
|
-
+ _safe_int(usage.get("cache_creation_input_tokens"))
|
|
36814
|
-
+ _safe_int(usage.get("cache_read_input_tokens")))
|
|
37549
|
+
tok = _context_token_count(_context_usage(usage))
|
|
36815
37550
|
if tok > 0:
|
|
36816
37551
|
context_tokens = tok
|
|
36817
37552
|
model_str = msg.get("model")
|
|
@@ -39837,6 +40572,78 @@ def _log_reexpand_debit(session_id, tool_use_id, response_text):
|
|
|
39837
40572
|
pass
|
|
39838
40573
|
|
|
39839
40574
|
|
|
40575
|
+
def _find_archive_entry(archive_roots, tool_use_id, session_id=None, strict=False):
|
|
40576
|
+
"""First ``<root>/<session>/<tool_use_id>.json`` that exists, or None.
|
|
40577
|
+
|
|
40578
|
+
*tool_use_id* must already have passed expand's ``[a-zA-Z0-9_-]+`` check, so
|
|
40579
|
+
the filename can never leave its session dir. *strict* (the cross-runtime
|
|
40580
|
+
fallback) additionally requires a regular, non-symlink file whose resolved
|
|
40581
|
+
path stays inside its archive root.
|
|
40582
|
+
"""
|
|
40583
|
+
for archive_root in archive_roots:
|
|
40584
|
+
if session_id:
|
|
40585
|
+
sid = sanitize_session_id(session_id)
|
|
40586
|
+
if sid == "unknown":
|
|
40587
|
+
continue
|
|
40588
|
+
session_dirs = [archive_root / sid]
|
|
40589
|
+
elif archive_root.is_dir() and not archive_root.is_symlink():
|
|
40590
|
+
try:
|
|
40591
|
+
session_dirs = [d for d in archive_root.iterdir()
|
|
40592
|
+
if d.is_dir() and not d.is_symlink()]
|
|
40593
|
+
except OSError:
|
|
40594
|
+
continue
|
|
40595
|
+
else:
|
|
40596
|
+
continue
|
|
40597
|
+
for sd in session_dirs:
|
|
40598
|
+
entry_path = sd / f"{tool_use_id}.json"
|
|
40599
|
+
try:
|
|
40600
|
+
if not entry_path.exists():
|
|
40601
|
+
continue
|
|
40602
|
+
if strict:
|
|
40603
|
+
if (archive_root.is_symlink() or sd.is_symlink()
|
|
40604
|
+
or entry_path.is_symlink() or not entry_path.is_file()):
|
|
40605
|
+
continue
|
|
40606
|
+
entry_path.resolve(strict=True).relative_to(archive_root.resolve(strict=True))
|
|
40607
|
+
except (OSError, ValueError):
|
|
40608
|
+
continue
|
|
40609
|
+
return entry_path
|
|
40610
|
+
return None
|
|
40611
|
+
|
|
40612
|
+
|
|
40613
|
+
# Every runtime whose archive an unpinned expand may fall back to, in lookup order.
|
|
40614
|
+
_EXPAND_FALLBACK_RUNTIMES = ("claude", "codex", "hermes", "copilot", "cursor",
|
|
40615
|
+
"opencode", "antigravity", "grok", "devin")
|
|
40616
|
+
|
|
40617
|
+
|
|
40618
|
+
def _expand_may_cross_runtimes():
|
|
40619
|
+
"""True for a bare expand: no --runtime / TOKEN_OPTIMIZER_RUNTIME pin and
|
|
40620
|
+
no sandbox snapshot override."""
|
|
40621
|
+
return not (os.environ.get("TOKEN_OPTIMIZER_RUNTIME", "").strip()
|
|
40622
|
+
or os.environ.get("TOKEN_OPTIMIZER_SNAPSHOT_DIR", "").strip())
|
|
40623
|
+
|
|
40624
|
+
|
|
40625
|
+
def _cross_runtime_archive_roots(exclude):
|
|
40626
|
+
"""tool-archive dirs under every other runtime's home. Never raises."""
|
|
40627
|
+
roots = []
|
|
40628
|
+
seen = set(exclude)
|
|
40629
|
+
try:
|
|
40630
|
+
from runtime_env import runtime_home_for
|
|
40631
|
+
from plugin_env import snapshot_roots_for_home
|
|
40632
|
+
except Exception:
|
|
40633
|
+
return roots
|
|
40634
|
+
for runtime in _EXPAND_FALLBACK_RUNTIMES:
|
|
40635
|
+
try:
|
|
40636
|
+
home = runtime_home_for(runtime)
|
|
40637
|
+
for snapshot_root in snapshot_roots_for_home(home):
|
|
40638
|
+
root = snapshot_root / "tool-archive"
|
|
40639
|
+
if root not in seen:
|
|
40640
|
+
seen.add(root)
|
|
40641
|
+
roots.append(root)
|
|
40642
|
+
except Exception:
|
|
40643
|
+
continue
|
|
40644
|
+
return roots
|
|
40645
|
+
|
|
40646
|
+
|
|
39840
40647
|
def expand_archived(tool_use_id=None, session_id=None, list_all=False):
|
|
39841
40648
|
"""Retrieve an archived tool result, or list all archived results.
|
|
39842
40649
|
|
|
@@ -39909,48 +40716,43 @@ def expand_archived(tool_use_id=None, session_id=None, list_all=False):
|
|
|
39909
40716
|
print("[Error] Invalid tool_use_id format.", file=sys.stderr)
|
|
39910
40717
|
sys.exit(1)
|
|
39911
40718
|
|
|
39912
|
-
|
|
40719
|
+
entry_path = _find_archive_entry(archive_roots, tool_use_id, session_id)
|
|
40720
|
+
if entry_path is None and _expand_may_cross_runtimes():
|
|
40721
|
+
# Not in this runtime's archive. A pointer printed by Claude Code is
|
|
40722
|
+
# never pinned, so a shell that detects another runtime (or a scan
|
|
40723
|
+
# that failed open to Claude Code when the archive was written under
|
|
40724
|
+
# another runtime) would otherwise miss an entry that exists. Only an
|
|
40725
|
+
# unpinned expand falls back; an explicit --runtime stays strict.
|
|
40726
|
+
fallback_roots = _cross_runtime_archive_roots(archive_roots)
|
|
40727
|
+
entry_path = _find_archive_entry(fallback_roots, tool_use_id, session_id, strict=True)
|
|
40728
|
+
if entry_path is None and not any(root.is_dir() for root in archive_roots):
|
|
40729
|
+
archive_roots = archive_roots + [r for r in fallback_roots if r.is_dir()]
|
|
40730
|
+
|
|
40731
|
+
if entry_path is None and not any(root.is_dir() for root in archive_roots):
|
|
39913
40732
|
print("[Error] No archive directory found. No results have been archived yet.", file=sys.stderr)
|
|
39914
40733
|
sys.exit(1)
|
|
39915
40734
|
|
|
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)
|
|
40735
|
+
if entry_path is not None:
|
|
40736
|
+
sd = entry_path.parent
|
|
40737
|
+
try:
|
|
40738
|
+
data = json.loads(entry_path.read_text(encoding="utf-8"))
|
|
40739
|
+
response = data.get("response", "")
|
|
40740
|
+
if response:
|
|
40741
|
+
# B6 integrity: re-popping an archived result means it did NOT
|
|
40742
|
+
# stay collapsed, so reverse its tool_archive credit. Log the
|
|
40743
|
+
# re-popped tokens as a debit (netted in _get_savings_summary),
|
|
40744
|
+
# deduped per item so a second expand never double-debits.
|
|
40745
|
+
_log_reexpand_debit(sd.name, tool_use_id, response)
|
|
40746
|
+
# No added newline: expand returns the stored text as stored.
|
|
40747
|
+
sys.stdout.write(response)
|
|
40748
|
+
sys.stdout.flush()
|
|
40749
|
+
return
|
|
40750
|
+
else:
|
|
40751
|
+
print(f"[Error] Archived entry found but response is empty: {entry_path}", file=sys.stderr)
|
|
39953
40752
|
sys.exit(1)
|
|
40753
|
+
except (json.JSONDecodeError, OSError) as e:
|
|
40754
|
+
print(f"[Error] Failed to read archived result: {e}", file=sys.stderr)
|
|
40755
|
+
sys.exit(1)
|
|
39954
40756
|
|
|
39955
40757
|
print(f"[Error] Tool result not found: {tool_use_id}", file=sys.stderr)
|
|
39956
40758
|
if not session_id:
|
|
@@ -40182,11 +40984,9 @@ def _purge_all_data(confirm=False, force=False):
|
|
|
40182
40984
|
try:
|
|
40183
40985
|
raw = pid_file.read_text(encoding="utf-8").strip()
|
|
40184
40986
|
candidate_pid = int(raw)
|
|
40185
|
-
|
|
40186
|
-
os.kill(candidate_pid, 0)
|
|
40987
|
+
if _pid_is_running(candidate_pid):
|
|
40187
40988
|
running_pid = candidate_pid
|
|
40188
|
-
|
|
40189
|
-
pass # process not alive; PID file is stale
|
|
40989
|
+
# else: process not alive; PID file is stale
|
|
40190
40990
|
except (OSError, ValueError):
|
|
40191
40991
|
pass
|
|
40192
40992
|
|
|
@@ -40202,9 +41002,14 @@ def _purge_all_data(confirm=False, force=False):
|
|
|
40202
41002
|
# Verify PID identity before SIGTERM to avoid killing a recycled PID
|
|
40203
41003
|
is_ours = False
|
|
40204
41004
|
try:
|
|
40205
|
-
|
|
40206
|
-
|
|
40207
|
-
|
|
41005
|
+
if os.name == "nt":
|
|
41006
|
+
# No `ps` on Windows: the daemon was never stopped there, and
|
|
41007
|
+
# the purge then hit the files it still held open.
|
|
41008
|
+
proc_name = ((_windows_process_names() or {}).get(running_pid) or (0, ""))[1]
|
|
41009
|
+
else:
|
|
41010
|
+
result = _sp.run(["ps", "-p", str(running_pid), "-o", "comm="],
|
|
41011
|
+
capture_output=True, text=True, timeout=3)
|
|
41012
|
+
proc_name = result.stdout.strip().lower()
|
|
40208
41013
|
is_ours = "python" in proc_name or "measure" in proc_name
|
|
40209
41014
|
except Exception:
|
|
40210
41015
|
is_ours = False
|
|
@@ -40394,9 +41199,8 @@ def _security_report(as_json=False):
|
|
|
40394
41199
|
pid_file = DAEMON_LOG_DIR / "daemon.pid"
|
|
40395
41200
|
if pid_file.exists():
|
|
40396
41201
|
try:
|
|
40397
|
-
daemon_pid = int(pid_file.read_text().strip())
|
|
40398
|
-
|
|
40399
|
-
daemon_running = True
|
|
41202
|
+
daemon_pid = int(pid_file.read_text(encoding="utf-8").strip())
|
|
41203
|
+
daemon_running = _pid_is_running(daemon_pid)
|
|
40400
41204
|
except (ValueError, OSError):
|
|
40401
41205
|
pass
|
|
40402
41206
|
|
|
@@ -40642,7 +41446,7 @@ def _extract_session_state(filepath, tail_lines=500):
|
|
|
40642
41446
|
|
|
40643
41447
|
# User messages
|
|
40644
41448
|
if rec_type == "user":
|
|
40645
|
-
text = _ingest_redact(
|
|
41449
|
+
text = _ingest_redact(_task_user_text(record))
|
|
40646
41450
|
if text.strip():
|
|
40647
41451
|
last_user_msg = text.strip()
|
|
40648
41452
|
# Check for questions
|
|
@@ -40865,13 +41669,22 @@ def _redaction_skip_notice(session_id):
|
|
|
40865
41669
|
return None
|
|
40866
41670
|
|
|
40867
41671
|
|
|
40868
|
-
|
|
41672
|
+
class _SkipTranscriptQuality(Exception):
|
|
41673
|
+
"""Internal: leave the transcript-derived quality block out of a checkpoint."""
|
|
41674
|
+
|
|
41675
|
+
|
|
41676
|
+
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
41677
|
"""Capture structured session state before compaction or session end.
|
|
40870
41678
|
|
|
40871
41679
|
Writes a markdown checkpoint to CHECKPOINT_DIR.
|
|
40872
41680
|
Called by PreCompact, Stop, and SessionEnd hooks via CLI.
|
|
40873
41681
|
Progressive checkpoints pass fill_pct and trigger="progressive-{band}".
|
|
40874
41682
|
|
|
41683
|
+
``_trusted_transcript`` is for internal callers only: a transcript Token
|
|
41684
|
+
Optimizer built itself in its own private directory (the Hermes adapter
|
|
41685
|
+
translates Hermes's state.db messages into one). It skips the confinement
|
|
41686
|
+
meant for hook-supplied paths. Never pass hook input through it.
|
|
41687
|
+
|
|
40875
41688
|
Returns the checkpoint file path, or None on failure.
|
|
40876
41689
|
"""
|
|
40877
41690
|
# Validate trigger before it flows into the checkpoint filename.
|
|
@@ -40893,7 +41706,9 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
|
|
|
40893
41706
|
ts = now.strftime("%Y-%m-%dT%H:%M:%S%z")
|
|
40894
41707
|
ts_file = now.strftime("%Y%m%d-%H%M%S")
|
|
40895
41708
|
|
|
40896
|
-
if
|
|
41709
|
+
if _trusted_transcript is not None:
|
|
41710
|
+
filepath = Path(_trusted_transcript)
|
|
41711
|
+
elif transcript_path:
|
|
40897
41712
|
# A supplied path that fails confinement is a forged hook input — do
|
|
40898
41713
|
# not checkpoint from it, and do not fall through to inference (which
|
|
40899
41714
|
# would let a bad pointer silently capture a different session).
|
|
@@ -40911,6 +41726,20 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
|
|
|
40911
41726
|
trigger_suffix = f"-{trigger}" if trigger and trigger != "auto" else ""
|
|
40912
41727
|
|
|
40913
41728
|
if not filepath or not filepath.exists():
|
|
41729
|
+
if _use_codex_session_adapter(transcript_path or None):
|
|
41730
|
+
# Codex with no readable transcript: a "No transcript data
|
|
41731
|
+
# available" placeholder (named "unknown" when the host sent no
|
|
41732
|
+
# session id) holds nothing to restore, can outrank real
|
|
41733
|
+
# checkpoints, and hides that capture failed (issue #278). Say
|
|
41734
|
+
# why instead, for the doctor; never the id or path themselves.
|
|
41735
|
+
_record_hook_status(
|
|
41736
|
+
"stop_capture" if trigger in ("stop", "end") else "checkpoint_capture",
|
|
41737
|
+
"skipped: " + (
|
|
41738
|
+
"the transcript path the host sent is outside the Codex sessions folder or unreadable"
|
|
41739
|
+
if transcript_path else
|
|
41740
|
+
"no Codex transcript matches the session id the host sent" if session_id else
|
|
41741
|
+
"the hook payload and environment carried no session id"))
|
|
41742
|
+
return None
|
|
40914
41743
|
# Write minimal checkpoint with safe permissions
|
|
40915
41744
|
sid = sanitize_session_id(session_id)
|
|
40916
41745
|
checkpoint_path = CHECKPOINT_DIR / f"{sid}-{ts_file}{trigger_suffix}.md"
|
|
@@ -40967,6 +41796,11 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
|
|
|
40967
41796
|
sid = sanitize_session_id(session_id) if session_id else sanitize_session_id(filepath.stem)
|
|
40968
41797
|
quality_summary = None
|
|
40969
41798
|
try:
|
|
41799
|
+
if _trusted_transcript is not None:
|
|
41800
|
+
# A translated transcript carries no usage data, so scoring it
|
|
41801
|
+
# would print a fake perfect grade. The caller passes the real
|
|
41802
|
+
# fill instead; the quality block is simply left out.
|
|
41803
|
+
raise _SkipTranscriptQuality()
|
|
40970
41804
|
# Prefer the per-session quality cache over re-parsing the whole transcript.
|
|
40971
41805
|
# _parse_jsonl_for_quality is O(file): a ~200MB session costs ~8s, and this
|
|
40972
41806
|
# runs on the synchronous Stop hook, so an unbounded reparse shows up as
|
|
@@ -41010,7 +41844,12 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
|
|
|
41010
41844
|
pass
|
|
41011
41845
|
fill_info = f" | Fill: {fill_pct:.0f}%" if fill_pct is not None else ""
|
|
41012
41846
|
quality_info = f" | Quality: {quality_score:.1f}" if quality_score is not None else ""
|
|
41013
|
-
|
|
41847
|
+
if _trusted_transcript is not None and not cwd:
|
|
41848
|
+
# No known working directory: this process's own cwd is not the
|
|
41849
|
+
# session's project, so its git state would be someone else's.
|
|
41850
|
+
git_branch, git_sha = None, None
|
|
41851
|
+
else:
|
|
41852
|
+
git_branch, git_sha = _capture_git_state(cwd)
|
|
41014
41853
|
git_line = ""
|
|
41015
41854
|
if git_branch or git_sha:
|
|
41016
41855
|
git_line = f" | Git: {git_branch or '?'}@{git_sha or '?'}"
|
|
@@ -42606,27 +43445,42 @@ _RESUME_TOPIC_STOPWORDS = frozenset({
|
|
|
42606
43445
|
|
|
42607
43446
|
|
|
42608
43447
|
# --- 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
|
-
#
|
|
43448
|
+
# Two branches: an ASCII/accented-Latin run, OR a whole non-ASCII run as one token, so a token
|
|
43449
|
+
# never mixes ASCII and non-ASCII ("measure.py를" -> "measure.py" + "를").
|
|
42611
43450
|
# The Latin-1/Extended-A ranges deliberately skip U+00D7 (×) and U+00F7 (÷): they sit inside
|
|
42612
43451
|
# the block but are math symbols, not letters. U+0100–U+024F is Latin Extended-A/B, all letters.
|
|
42613
43452
|
_TOPIC_TOKEN_RE = re.compile(r"[a-zA-Z0-9_.:À-ÖØ-öø-ÿĀ-ɏ/-]+|[^\x00-\x7F]+")
|
|
42614
|
-
# Script-aware length floor
|
|
42615
|
-
#
|
|
42616
|
-
#
|
|
42617
|
-
#
|
|
42618
|
-
|
|
43453
|
+
# Script-aware length floor, defined by fixed code-point ranges so Python, OpenClaw and
|
|
43454
|
+
# OpenCode classify every character the same way on any Unicode version.
|
|
43455
|
+
# * Any char at or above U+3000 (Han, Kana, Hangul, fullwidth forms): a 2-char word such as
|
|
43456
|
+
# 결제 (payment) or 모듈 (module) is a full topic, so keep len>=2.
|
|
43457
|
+
# * Other non-Latin letters (Cyrillic, Greek, Arabic, Hebrew, Indic...): keep len>=3, which
|
|
43458
|
+
# keeps "кот" but drops 2-letter function words such as "на", "في", "של".
|
|
43459
|
+
# * Latin (ASCII, accented, extended, letterlike): the len>3 English stopword heuristic.
|
|
43460
|
+
# Combining marks (accents, niqqud, harakat) never count toward the length.
|
|
43461
|
+
_TOPIC_WIDE_MIN = 0x3000
|
|
43462
|
+
_TOPIC_LATIN_RANGES = (
|
|
43463
|
+
(0x0000, 0x036F), (0x1D00, 0x1DFF), (0x1E00, 0x1EFF), (0x2000, 0x214F),
|
|
43464
|
+
(0x2C60, 0x2C7F), (0xA720, 0xA7FF), (0xAB30, 0xAB6F),
|
|
43465
|
+
)
|
|
43466
|
+
_TOPIC_MARK_RANGES = (
|
|
43467
|
+
(0x0300, 0x036F), (0x0483, 0x0489), (0x0591, 0x05C7), (0x0610, 0x061A), (0x064B, 0x065F),
|
|
43468
|
+
(0x0670, 0x0670), (0x06D6, 0x06ED), (0x1AB0, 0x1AFF), (0x1DC0, 0x1DFF), (0x200B, 0x200F),
|
|
43469
|
+
(0x20D0, 0x20FF), (0xFE00, 0xFE0F), (0xFE20, 0xFE2F),
|
|
43470
|
+
)
|
|
42619
43471
|
|
|
42620
43472
|
|
|
42621
|
-
def
|
|
42622
|
-
|
|
42623
|
-
return any(ord(ch) >= _CJK_MIN for ch in w)
|
|
43473
|
+
def _in_ranges(cp, ranges):
|
|
43474
|
+
return any(lo <= cp <= hi for lo, hi in ranges)
|
|
42624
43475
|
|
|
42625
43476
|
|
|
42626
43477
|
def _topic_token_kept(w):
|
|
42627
|
-
if
|
|
42628
|
-
|
|
42629
|
-
|
|
43478
|
+
cps = [ord(ch) for ch in w if not _in_ranges(ord(ch), _TOPIC_MARK_RANGES)]
|
|
43479
|
+
if any(cp >= _TOPIC_WIDE_MIN for cp in cps):
|
|
43480
|
+
return len(cps) >= 2
|
|
43481
|
+
if any(not _in_ranges(cp, _TOPIC_LATIN_RANGES) for cp in cps):
|
|
43482
|
+
return len(cps) >= 3
|
|
43483
|
+
return len(cps) > 3
|
|
42630
43484
|
|
|
42631
43485
|
|
|
42632
43486
|
def _topic_tokens(text, stopwords=frozenset()):
|
|
@@ -43741,9 +44595,7 @@ def _transcript_last_turn(sid_safe):
|
|
|
43741
44595
|
u = msg.get("usage") or {}
|
|
43742
44596
|
if not isinstance(u, dict):
|
|
43743
44597
|
continue
|
|
43744
|
-
ctx = (
|
|
43745
|
-
+ _safe_int(u.get("cache_read_input_tokens"))
|
|
43746
|
-
+ _safe_int(u.get("cache_creation_input_tokens")))
|
|
44598
|
+
ctx = _context_token_count(_context_usage(u))
|
|
43747
44599
|
if ctx <= 0:
|
|
43748
44600
|
continue
|
|
43749
44601
|
model = _normalize_model_name(msg.get("model"))
|
|
@@ -43902,7 +44754,65 @@ def checkpoint_trigger(milestone=None, session_id=None, transcript_path=None, qu
|
|
|
43902
44754
|
return cp_path
|
|
43903
44755
|
|
|
43904
44756
|
|
|
43905
|
-
|
|
44757
|
+
_COMPACT_INSTR_HEAD = "When summarizing this session, pay special attention to:"
|
|
44758
|
+
_COMPACT_INSTR_TAIL = (
|
|
44759
|
+
"Always include the specific next step with enough detail to continue without asking."
|
|
44760
|
+
)
|
|
44761
|
+
_COMPACT_INSTR_BULLETS = frozenset({
|
|
44762
|
+
"- Architectural decisions and their reasoning",
|
|
44763
|
+
"- Skill invocations and their outcomes",
|
|
44764
|
+
"- External service interactions and their results",
|
|
44765
|
+
"- Modified file paths with line ranges",
|
|
44766
|
+
"- Error-fix sequences (what was tried, what failed, what worked)",
|
|
44767
|
+
"- Open questions and unresolved TODOs",
|
|
44768
|
+
"- Agent/team state (task assignments, completion status)",
|
|
44769
|
+
})
|
|
44770
|
+
# Separator used when our instructions are appended to the user's own text.
|
|
44771
|
+
_COMPACT_INSTR_MARKER = "\n\n# Token Optimizer additions:\n"
|
|
44772
|
+
|
|
44773
|
+
|
|
44774
|
+
def _compact_instructions_generated(text):
|
|
44775
|
+
"""True when ``text`` is exactly a block generate_compact_instructions writes."""
|
|
44776
|
+
if not isinstance(text, str):
|
|
44777
|
+
return False
|
|
44778
|
+
lines = text.strip().split("\n")
|
|
44779
|
+
if len(lines) < 2 or lines[0] != _COMPACT_INSTR_HEAD or lines[-1] != _COMPACT_INSTR_TAIL:
|
|
44780
|
+
return False
|
|
44781
|
+
return all(line in _COMPACT_INSTR_BULLETS for line in lines[1:-1])
|
|
44782
|
+
|
|
44783
|
+
|
|
44784
|
+
def _split_compact_instructions(text):
|
|
44785
|
+
"""Split a ``compactInstructions`` value into (user_part, ours_present).
|
|
44786
|
+
|
|
44787
|
+
Ours is either the whole value (a block we generated) or a section we
|
|
44788
|
+
appended after the user's own text behind ``_COMPACT_INSTR_MARKER``.
|
|
44789
|
+
Anything else is the user's and is returned untouched.
|
|
44790
|
+
"""
|
|
44791
|
+
if not isinstance(text, str):
|
|
44792
|
+
return text, False
|
|
44793
|
+
if _COMPACT_INSTR_MARKER in text:
|
|
44794
|
+
return text.split(_COMPACT_INSTR_MARKER, 1)[0].rstrip(), True
|
|
44795
|
+
if _compact_instructions_generated(text):
|
|
44796
|
+
return "", True
|
|
44797
|
+
return text, False
|
|
44798
|
+
|
|
44799
|
+
|
|
44800
|
+
def _remove_our_compact_instructions(settings):
|
|
44801
|
+
"""Drop our compactInstructions (keeping any user-written part). True if changed."""
|
|
44802
|
+
if not isinstance(settings, dict) or "compactInstructions" not in settings:
|
|
44803
|
+
return False
|
|
44804
|
+
user_part, ours = _split_compact_instructions(settings.get("compactInstructions"))
|
|
44805
|
+
if not ours:
|
|
44806
|
+
return False
|
|
44807
|
+
if user_part:
|
|
44808
|
+
settings["compactInstructions"] = user_part
|
|
44809
|
+
else:
|
|
44810
|
+
del settings["compactInstructions"]
|
|
44811
|
+
return True
|
|
44812
|
+
|
|
44813
|
+
|
|
44814
|
+
def generate_compact_instructions(as_json=False, install=False, dry_run=False,
|
|
44815
|
+
user_initiated=False):
|
|
43906
44816
|
"""Generate project-specific Compact Instructions.
|
|
43907
44817
|
|
|
43908
44818
|
Analyzes CLAUDE.md, recent session patterns, and common loss patterns
|
|
@@ -43913,7 +44823,7 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
|
|
|
43913
44823
|
"""
|
|
43914
44824
|
components = measure_components()
|
|
43915
44825
|
instructions_parts = [
|
|
43916
|
-
|
|
44826
|
+
_COMPACT_INSTR_HEAD,
|
|
43917
44827
|
]
|
|
43918
44828
|
|
|
43919
44829
|
# Analyze CLAUDE.md content for project priorities
|
|
@@ -43936,7 +44846,7 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
|
|
|
43936
44846
|
"- Modified file paths with line ranges",
|
|
43937
44847
|
"- Error-fix sequences (what was tried, what failed, what worked)",
|
|
43938
44848
|
"- Open questions and unresolved TODOs",
|
|
43939
|
-
|
|
44849
|
+
_COMPACT_INSTR_TAIL,
|
|
43940
44850
|
])
|
|
43941
44851
|
|
|
43942
44852
|
# Check for agent usage in recent sessions
|
|
@@ -43968,14 +44878,20 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
|
|
|
43968
44878
|
)
|
|
43969
44879
|
return instructions_text
|
|
43970
44880
|
existing = settings.get("compactInstructions", "")
|
|
44881
|
+
user_part, ours_present = _split_compact_instructions(existing)
|
|
43971
44882
|
|
|
43972
|
-
if existing and
|
|
44883
|
+
if existing and ours_present:
|
|
44884
|
+
# Refresh only our part. A value that also holds the user's own
|
|
44885
|
+
# text keeps it: replacing the whole value used to erase it.
|
|
43973
44886
|
if dry_run:
|
|
43974
44887
|
print(f"\n [Dry run] Would update existing compact instructions in {settings_path}")
|
|
43975
44888
|
print(f"\n Compact instructions preview:\n {instructions_text}\n")
|
|
43976
44889
|
return instructions_text
|
|
43977
|
-
settings["compactInstructions"] =
|
|
43978
|
-
|
|
44890
|
+
settings["compactInstructions"] = (
|
|
44891
|
+
user_part + _COMPACT_INSTR_MARKER + instructions_text
|
|
44892
|
+
if user_part else instructions_text
|
|
44893
|
+
)
|
|
44894
|
+
if not _write_settings_atomic(settings, user_initiated=user_initiated):
|
|
43979
44895
|
print("[Error] settings.json write was refused; compact instructions were not updated.", file=sys.stderr)
|
|
43980
44896
|
return instructions_text
|
|
43981
44897
|
print(f"[Token Optimizer] Compact Instructions updated in {settings_path}")
|
|
@@ -43983,7 +44899,7 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
|
|
|
43983
44899
|
|
|
43984
44900
|
if existing:
|
|
43985
44901
|
# User has their own instructions, append ours
|
|
43986
|
-
combined = existing.rstrip() +
|
|
44902
|
+
combined = existing.rstrip() + _COMPACT_INSTR_MARKER + instructions_text
|
|
43987
44903
|
if dry_run:
|
|
43988
44904
|
print(f"\n [Dry run] Would append to existing compact instructions in {settings_path}")
|
|
43989
44905
|
print(f"\n Appended:\n {instructions_text}\n")
|
|
@@ -43996,7 +44912,7 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
|
|
|
43996
44912
|
return instructions_text
|
|
43997
44913
|
settings["compactInstructions"] = instructions_text
|
|
43998
44914
|
|
|
43999
|
-
if not _write_settings_atomic(settings):
|
|
44915
|
+
if not _write_settings_atomic(settings, user_initiated=user_initiated):
|
|
44000
44916
|
print("[Error] settings.json write was refused; compact instructions were not installed.", file=sys.stderr)
|
|
44001
44917
|
return instructions_text
|
|
44002
44918
|
print(f"[Token Optimizer] Compact Instructions installed to {settings_path}")
|
|
@@ -44695,16 +45611,30 @@ def _smart_compact_hook_commands():
|
|
|
44695
45611
|
resolved to), the hook exits 0 silently instead of erroring on every event.
|
|
44696
45612
|
Mirrors the launcher guard in hooks.json.
|
|
44697
45613
|
"""
|
|
44698
|
-
mp = _get_measure_py_path()
|
|
44699
|
-
guard = f"[ -r
|
|
45614
|
+
py, mp = _settings_hook_python_and_script(_get_measure_py_path())
|
|
45615
|
+
guard = f"[ -r {mp} ] || exit 0; "
|
|
44700
45616
|
return {
|
|
44701
|
-
"PreCompact": f"{guard}
|
|
44702
|
-
"SessionStart": f"{guard}
|
|
44703
|
-
"Stop": f"{guard}
|
|
44704
|
-
"SessionEnd": f"{guard}
|
|
45617
|
+
"PreCompact": f"{guard}{py} {mp} compact-capture --trigger auto",
|
|
45618
|
+
"SessionStart": f"{guard}{py} {mp} compact-restore",
|
|
45619
|
+
"Stop": f"{guard}{py} {mp} compact-capture --trigger stop",
|
|
45620
|
+
"SessionEnd": f"{guard}{py} {mp} compact-capture --trigger end",
|
|
44705
45621
|
}
|
|
44706
45622
|
|
|
44707
45623
|
|
|
45624
|
+
def _settings_hook_python_and_script(mp):
|
|
45625
|
+
"""(interpreter, script) shell tokens for a settings.json hook command.
|
|
45626
|
+
|
|
45627
|
+
Claude Code runs these through Git Bash on Windows, where bare ``python3``
|
|
45628
|
+
is often missing or the Microsoft Store stub (exit 9009 on every event),
|
|
45629
|
+
so Windows names the running interpreter with forward slashes, quoted for
|
|
45630
|
+
bash (an apostrophe in the path is safe). POSIX keeps ``python3 '<mp>'``.
|
|
45631
|
+
"""
|
|
45632
|
+
if sys.platform == "win32":
|
|
45633
|
+
return (shlex.quote(str(sys.executable).replace("\\", "/")),
|
|
45634
|
+
shlex.quote(str(mp).replace("\\", "/")))
|
|
45635
|
+
return "python3", f"'{mp}'"
|
|
45636
|
+
|
|
45637
|
+
|
|
44708
45638
|
def _is_smart_compact_installed(settings=None):
|
|
44709
45639
|
"""Check which smart compact hooks are installed.
|
|
44710
45640
|
|
|
@@ -44757,7 +45687,8 @@ def _is_smart_compact_installed(settings=None):
|
|
|
44757
45687
|
return status
|
|
44758
45688
|
|
|
44759
45689
|
|
|
44760
|
-
def setup_smart_compact(dry_run=False, uninstall=False, status_only=False
|
|
45690
|
+
def setup_smart_compact(dry_run=False, uninstall=False, status_only=False,
|
|
45691
|
+
user_initiated=False):
|
|
44761
45692
|
"""Install, uninstall, or check status of smart compaction hooks.
|
|
44762
45693
|
|
|
44763
45694
|
Appends to existing hooks (never overwrites). Safe to run multiple times.
|
|
@@ -44822,10 +45753,16 @@ def setup_smart_compact(dry_run=False, uninstall=False, status_only=False):
|
|
|
44822
45753
|
return
|
|
44823
45754
|
|
|
44824
45755
|
settings["hooks"] = hooks
|
|
44825
|
-
|
|
45756
|
+
# setup-smart-compact also installed compactInstructions; take ours
|
|
45757
|
+
# back out (a user-written part stays).
|
|
45758
|
+
ci_removed = _remove_our_compact_instructions(settings)
|
|
45759
|
+
if not _write_settings_atomic(settings, allow_removing_keys={"compactInstructions"},
|
|
45760
|
+
user_initiated=user_initiated):
|
|
44826
45761
|
print("[Error] settings.json write was refused; smart compact hooks were not removed.", file=sys.stderr)
|
|
44827
45762
|
return
|
|
44828
45763
|
print(f"[Token Optimizer] Removed smart compact hooks. {removed} hook(s) removed.")
|
|
45764
|
+
if ci_removed:
|
|
45765
|
+
print("[Token Optimizer] Removed Token Optimizer compact instructions.")
|
|
44829
45766
|
return
|
|
44830
45767
|
|
|
44831
45768
|
# Install
|
|
@@ -44916,7 +45853,7 @@ def setup_smart_compact(dry_run=False, uninstall=False, status_only=False):
|
|
|
44916
45853
|
return
|
|
44917
45854
|
|
|
44918
45855
|
settings["hooks"] = hooks
|
|
44919
|
-
if not _write_settings_atomic(settings):
|
|
45856
|
+
if not _write_settings_atomic(settings, user_initiated=user_initiated):
|
|
44920
45857
|
print("[Error] settings.json write was refused; smart compact hooks were not installed.", file=sys.stderr)
|
|
44921
45858
|
return
|
|
44922
45859
|
|
|
@@ -44927,7 +45864,7 @@ def setup_smart_compact(dry_run=False, uninstall=False, status_only=False):
|
|
|
44927
45864
|
|
|
44928
45865
|
# Also install compact instructions (tells Claude WHAT to preserve)
|
|
44929
45866
|
print()
|
|
44930
|
-
generate_compact_instructions(install=True)
|
|
45867
|
+
generate_compact_instructions(install=True, user_initiated=user_initiated)
|
|
44931
45868
|
|
|
44932
45869
|
print("\n What happens now:")
|
|
44933
45870
|
print(" Compact Instructions: Guides Claude on what to preserve during compaction")
|
|
@@ -45761,6 +46698,9 @@ def _verbosity_nudge_min_fill() -> int:
|
|
|
45761
46698
|
|
|
45762
46699
|
_VERBOSITY_NUDGE_MIN_FILL = _verbosity_nudge_min_fill()
|
|
45763
46700
|
_VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD = 75
|
|
46701
|
+
# Lean-output nudge pacing: at most this many per session, this far apart.
|
|
46702
|
+
_VERBOSITY_MAX_NUDGES = 3
|
|
46703
|
+
_VERBOSITY_COOLDOWN_SEC = 300
|
|
45764
46704
|
_NUDGE_SESSION_CAP = 3
|
|
45765
46705
|
# Fresh-session nudge: when a session is BOTH long (high fill) and degraded
|
|
45766
46706
|
# (quality < threshold), suggest starting a fresh session -- cold-resume-lean
|
|
@@ -46518,7 +47458,9 @@ def quality_cache(throttle_seconds=120, warn_threshold=70, quiet=False, session_
|
|
|
46518
47458
|
result["session_start_ts"] = _extract_session_start_ts(filepath)
|
|
46519
47459
|
result["active_agents"] = _extract_active_agents(filepath)
|
|
46520
47460
|
|
|
46521
|
-
# Cache hit rate for statusline (v5.4.27)
|
|
47461
|
+
# Cache hit rate for statusline (v5.4.27). A billing ratio, so it reads
|
|
47462
|
+
# the top-level (advisor-summed) usage on purpose, unlike context fill,
|
|
47463
|
+
# which uses _context_usage (#287).
|
|
46522
47464
|
try:
|
|
46523
47465
|
total_input_all = 0
|
|
46524
47466
|
total_cache_read = 0
|
|
@@ -48007,7 +48949,8 @@ def _get_v5_savings_recommendation():
|
|
|
48007
48949
|
}
|
|
48008
48950
|
|
|
48009
48951
|
|
|
48010
|
-
def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=False, quiet=False
|
|
48952
|
+
def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=False, quiet=False,
|
|
48953
|
+
user_initiated=False):
|
|
48011
48954
|
"""Install, uninstall, or check quality bar (status line + cache hook).
|
|
48012
48955
|
|
|
48013
48956
|
Installs:
|
|
@@ -48026,6 +48969,12 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
|
|
|
48026
48969
|
every turn. The advisory is only shown on an explicit,
|
|
48027
48970
|
interactive `setup-quality-bar` run.
|
|
48028
48971
|
|
|
48972
|
+
user_initiated=True is passed only by the `setup-quality-bar` CLI command
|
|
48973
|
+
(the same for setup-hook / setup-smart-compact / compact-instructions):
|
|
48974
|
+
an explicit command takes the settings lease past the hook-herd
|
|
48975
|
+
reservation, so commands typed back to back are not refused. The
|
|
48976
|
+
automatic heal callers keep the default and the non-blocking lease.
|
|
48977
|
+
|
|
48029
48978
|
Side-effects on config.json:
|
|
48030
48979
|
install -> clears "quality_bar_disabled" (explicit opt-in)
|
|
48031
48980
|
--uninstall -> sets "quality_bar_disabled" (sticky opt-out)
|
|
@@ -48126,7 +49075,8 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
|
|
|
48126
49075
|
settings["hooks"] = hooks
|
|
48127
49076
|
# Deliberate top-level removal: declare it so the choke-point guard
|
|
48128
49077
|
# allows this one and only this one.
|
|
48129
|
-
if not _write_settings_atomic(settings, allow_removing_keys={"statusLine"}
|
|
49078
|
+
if not _write_settings_atomic(settings, allow_removing_keys={"statusLine"},
|
|
49079
|
+
user_initiated=user_initiated):
|
|
48130
49080
|
print("[Error] settings.json write was refused; Quality Bar was not removed.", file=sys.stderr)
|
|
48131
49081
|
return
|
|
48132
49082
|
_set_quality_bar_disabled(True)
|
|
@@ -48152,7 +49102,8 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
|
|
|
48152
49102
|
skipped.append("cache hook")
|
|
48153
49103
|
else:
|
|
48154
49104
|
hooks = settings.setdefault("hooks", {})
|
|
48155
|
-
|
|
49105
|
+
_py, _mp = _settings_hook_python_and_script(mp)
|
|
49106
|
+
hook_cmd = f"{_py} {_mp} quality-cache --quiet"
|
|
48156
49107
|
hook_entry = {"type": "command", "command": hook_cmd}
|
|
48157
49108
|
hook_group = {"hooks": [hook_entry]}
|
|
48158
49109
|
hooks.setdefault("UserPromptSubmit", []).append(hook_group)
|
|
@@ -48170,13 +49121,16 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
|
|
|
48170
49121
|
# is a clobber rather than an intentional choice).
|
|
48171
49122
|
try:
|
|
48172
49123
|
_rt_seg = RUNTIME_DIR.relative_to(HOME).as_posix()
|
|
49124
|
+
_rt_base = f"os.homedir(), '{_rt_seg}'"
|
|
48173
49125
|
except ValueError:
|
|
48174
|
-
|
|
49126
|
+
# Runtime dir outside HOME (e.g. CLAUDE_CONFIG_DIR on a
|
|
49127
|
+
# relocated volume): print its absolute path, never ~/.claude.
|
|
49128
|
+
_rt_base = json.dumps(RUNTIME_DIR.as_posix())
|
|
48175
49129
|
warnings.append(
|
|
48176
49130
|
"You already have a custom status line configured.\n"
|
|
48177
49131
|
" To integrate quality scoring, add this to your status line script:\n\n"
|
|
48178
49132
|
" // Read context quality score\n"
|
|
48179
|
-
f" const qFile = path.join(
|
|
49133
|
+
f" const qFile = path.join({_rt_base}, 'token-optimizer', 'quality-cache.json');\n"
|
|
48180
49134
|
" let qScore = '';\n"
|
|
48181
49135
|
" if (fs.existsSync(qFile)) {\n"
|
|
48182
49136
|
" try {\n"
|
|
@@ -48193,7 +49147,10 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
|
|
|
48193
49147
|
else:
|
|
48194
49148
|
settings["statusLine"] = {
|
|
48195
49149
|
"type": "command",
|
|
48196
|
-
|
|
49150
|
+
# A plain '...' wrap broke on an apostrophe in the path
|
|
49151
|
+
# (C:\Users\O'Brien). Keep the familiar form otherwise.
|
|
49152
|
+
"command": (f"node '{sl_path}'" if "'" not in str(sl_path)
|
|
49153
|
+
else f"node {shlex.quote(str(sl_path))}"),
|
|
48197
49154
|
}
|
|
48198
49155
|
installed.append("status line")
|
|
48199
49156
|
|
|
@@ -48221,7 +49178,7 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
|
|
|
48221
49178
|
return
|
|
48222
49179
|
|
|
48223
49180
|
if installed:
|
|
48224
|
-
if not _write_settings_atomic(settings):
|
|
49181
|
+
if not _write_settings_atomic(settings, user_initiated=user_initiated):
|
|
48225
49182
|
if not quiet:
|
|
48226
49183
|
print("[Error] settings.json write was refused; Quality Bar was not installed.", file=sys.stderr)
|
|
48227
49184
|
return
|
|
@@ -53921,7 +54878,11 @@ def _advice_session_data(path):
|
|
|
53921
54878
|
turns per-request context size (input + cache_read + cache_creation)
|
|
53922
54879
|
of each main-thread assistant usage row, in order; streamed
|
|
53923
54880
|
chunks sharing a requestId collapse to the largest row.
|
|
53924
|
-
cache_reads cache_read_input_tokens per turn (same indexing).
|
|
54881
|
+
cache_reads cache_read_input_tokens per turn (same indexing). This is
|
|
54882
|
+
the billed aggregate, while `turns` is executor occupancy
|
|
54883
|
+
(#287). On advisor sessions avoided reads (derived from
|
|
54884
|
+
`turns`) are measured against the larger billed total, so
|
|
54885
|
+
avoided_share_pct can only understate the saving.
|
|
53925
54886
|
boundaries indexes in `turns` that directly follow a compact_boundary.
|
|
53926
54887
|
model newest model id on a main-thread row, or None.
|
|
53927
54888
|
post_compact_ctx context size of the first request after each recorded
|
|
@@ -53976,9 +54937,10 @@ def _advice_session_data(path):
|
|
|
53976
54937
|
u = msg.get("usage")
|
|
53977
54938
|
if not isinstance(u, dict):
|
|
53978
54939
|
continue
|
|
54940
|
+
# Cache-read traffic is billed aggregate usage; occupancy is
|
|
54941
|
+
# only the final executor iteration of an advisor response.
|
|
53979
54942
|
cr = _safe_int(u.get("cache_read_input_tokens"))
|
|
53980
|
-
ctx = (
|
|
53981
|
-
+ _safe_int(u.get("cache_creation_input_tokens")))
|
|
54943
|
+
ctx = _context_token_count(_context_usage(u))
|
|
53982
54944
|
if ctx <= 0:
|
|
53983
54945
|
continue
|
|
53984
54946
|
m = msg.get("model")
|
|
@@ -57118,11 +58080,9 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
|
|
|
57118
58080
|
_now = _vs_time.time()
|
|
57119
58081
|
_nudge_count = cached.get("nudge_count", 0) or 0
|
|
57120
58082
|
_last_nudge = cached.get("last_nudge_time", 0) or 0
|
|
57121
|
-
|
|
57122
|
-
_MAX_NUDGES = 3
|
|
57123
|
-
if _nudge_count >= _MAX_NUDGES:
|
|
58083
|
+
if _nudge_count >= _VERBOSITY_MAX_NUDGES:
|
|
57124
58084
|
return ""
|
|
57125
|
-
if _now - _last_nudge <
|
|
58085
|
+
if _now - _last_nudge < _VERBOSITY_COOLDOWN_SEC:
|
|
57126
58086
|
return ""
|
|
57127
58087
|
|
|
57128
58088
|
# At 90%+ fill, don't add more tokens
|
|
@@ -57134,44 +58094,8 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
|
|
|
57134
58094
|
)
|
|
57135
58095
|
return ""
|
|
57136
58096
|
|
|
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:
|
|
58097
|
+
nudge = _verbosity_nudge_text(fill_pct, score, session_efficiency, cached)
|
|
58098
|
+
if not nudge:
|
|
57175
58099
|
return ""
|
|
57176
58100
|
|
|
57177
58101
|
payload = json.dumps({
|
|
@@ -57248,6 +58172,62 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
|
|
|
57248
58172
|
return ""
|
|
57249
58173
|
|
|
57250
58174
|
|
|
58175
|
+
def _verbosity_nudge_text(fill_pct, score, session_efficiency, cached):
|
|
58176
|
+
"""The lean-output nudge for a fill level, or "" when none applies.
|
|
58177
|
+
|
|
58178
|
+
Shared by Claude Code / Codex (run_verbosity_steer) and Hermes
|
|
58179
|
+
(hermes-turn-context), so every runtime gets the same tiers and wording.
|
|
58180
|
+
``cached`` is the quality-cache dict (or a small stand-in with
|
|
58181
|
+
``model_context_window``) that ``_format_context_fill`` reads.
|
|
58182
|
+
|
|
58183
|
+
Tiers:
|
|
58184
|
+
90%+ fill -> "" (adding tokens makes it worse)
|
|
58185
|
+
75-89% fill -> strong nudge
|
|
58186
|
+
_VERBOSITY_NUDGE_MIN_FILL-74% and session efficiency below
|
|
58187
|
+
_VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD -> gentle nudge
|
|
58188
|
+
"""
|
|
58189
|
+
if fill_pct >= 90:
|
|
58190
|
+
return ""
|
|
58191
|
+
# Determine nudge tier.
|
|
58192
|
+
#
|
|
58193
|
+
# The spartan/ADHD phrasing is used verbatim because it produced the
|
|
58194
|
+
# largest reduction in verbose output across multiple models while
|
|
58195
|
+
# maintaining answer quality. Notes on what the data showed:
|
|
58196
|
+
# - Word ceilings were REMOVED. An earlier draft capped answers at
|
|
58197
|
+
# 80/120 words. A cap makes a model either truncate a genuinely
|
|
58198
|
+
# complex answer or ignore the nudge, and a nudge that gets ignored
|
|
58199
|
+
# is the original failure this rewrite exists to fix.
|
|
58200
|
+
# - The real waste is elaboration, not preamble. The padding-focused
|
|
58201
|
+
# wording targeted preamble and restatement and cut half as much,
|
|
58202
|
+
# because verbose answers mostly repeat themselves rather than
|
|
58203
|
+
# restate the question.
|
|
58204
|
+
# - Quality held. On the hardest fixture (prompt-caching explainer,
|
|
58205
|
+
# 1159 -> 759 words) the spartan answer kept every concept and
|
|
58206
|
+
# covered TTL MORE; what it dropped was the same point made six
|
|
58207
|
+
# times instead of three.
|
|
58208
|
+
# - Reasoning and deliverables are fenced off explicitly, because the
|
|
58209
|
+
# nudge fires mid-task where "spartan" could otherwise be read as
|
|
58210
|
+
# "write less code".
|
|
58211
|
+
# - Opus is roughly half as responsive as Sonnet here. Do not quote
|
|
58212
|
+
# the Sonnet figure as the product number.
|
|
58213
|
+
if fill_pct >= 75:
|
|
58214
|
+
return (
|
|
58215
|
+
f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, resource health {score:.0f}/100. "
|
|
58216
|
+
"Answer in a focused and spartan way, as if the user has ADHD. Cut everything "
|
|
58217
|
+
"that is not the answer itself. Think as long as you need, and size code, "
|
|
58218
|
+
"diffs and file contents to the task."
|
|
58219
|
+
)
|
|
58220
|
+
if (fill_pct >= _VERBOSITY_NUDGE_MIN_FILL
|
|
58221
|
+
and session_efficiency < _VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD):
|
|
58222
|
+
return (
|
|
58223
|
+
f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, "
|
|
58224
|
+
f"session efficiency {session_efficiency:.0f}/100. "
|
|
58225
|
+
"Answer in a focused and spartan way, as if the user has ADHD. "
|
|
58226
|
+
"Think as long as you need, and size code, diffs and file contents to the task."
|
|
58227
|
+
)
|
|
58228
|
+
return ""
|
|
58229
|
+
|
|
58230
|
+
|
|
57251
58231
|
if __name__ == "__main__":
|
|
57252
58232
|
# On a non-UTF-8 host locale, re-exec under Python UTF-8 mode FIRST so every
|
|
57253
58233
|
# subprocess(text=True) decode (ps/git session detection), default open(), and
|
|
@@ -57448,7 +58428,7 @@ if __name__ == "__main__":
|
|
|
57448
58428
|
sys.exit(0)
|
|
57449
58429
|
elif args[0] == "copilot-rollup":
|
|
57450
58430
|
# Ingest recent Copilot sessions (CLI + VS Code planes) into trends.db.
|
|
57451
|
-
# Fired by the
|
|
58431
|
+
# Fired by the sessionEnd hook via copilot_hook_bridge.handle_session_end(); extra
|
|
57452
58432
|
# flags are silently consumed (INSERT OR IGNORE keeps this idempotent).
|
|
57453
58433
|
# Wall-clock backstop: this dispatch is spawned fire-and-forget by the
|
|
57454
58434
|
# Stop hook bridge (start_new_session=True, DEVNULL, no PID tracking),
|
|
@@ -57573,12 +58553,17 @@ if __name__ == "__main__":
|
|
|
57573
58553
|
elif args[0] == "hermes-install":
|
|
57574
58554
|
import hermes_install
|
|
57575
58555
|
sys.exit(hermes_install.main(args[1:]))
|
|
58556
|
+
elif args[0] in _HERMES_SUBCOMMAND_HELP and ("--help" in args[1:] or "-h" in args[1:]):
|
|
58557
|
+
# Print usage, never run: `hermes-rollup --help` used to start a rollup.
|
|
58558
|
+
print(_HERMES_SUBCOMMAND_HELP[args[0]])
|
|
58559
|
+
sys.exit(0)
|
|
57576
58560
|
elif args[0] == "hermes-rollup":
|
|
57577
58561
|
# Ingest recent Hermes sessions into trends.db. Called by the Hermes
|
|
57578
58562
|
# plugin's on_session_end hook via hermes_hook_bridge.run_rollup().
|
|
57579
58563
|
# --session <id> and --platform / --reason are accepted and silently
|
|
57580
58564
|
# consumed so the bridge's exact call signature never causes an error;
|
|
57581
|
-
# a full recent collect is always run (
|
|
58565
|
+
# a full recent collect is always run (idempotent: rows are keyed per
|
|
58566
|
+
# session and only refreshed when state.db has moved further along).
|
|
57582
58567
|
# Wall-clock backstop: same rationale as copilot-rollup above -- the
|
|
57583
58568
|
# Hermes bridge spawns this fire-and-forget with start_new_session=True
|
|
57584
58569
|
# and no PID tracking, so the parent hook deadline never propagates.
|
|
@@ -57586,6 +58571,7 @@ if __name__ == "__main__":
|
|
|
57586
58571
|
# session re-collects idempotently), a frozen orphan is not.
|
|
57587
58572
|
quiet = "--quiet" in args or "-q" in args
|
|
57588
58573
|
_HERMES_ROLLUP_CONTEXT = _parse_hermes_rollup_context(args[1:])
|
|
58574
|
+
_HERMES_ROLLUP_SKILLS = _parse_hermes_rollup_skills(args[1:])
|
|
57589
58575
|
_tok_hook_deadline = _install_hook_budget(60)
|
|
57590
58576
|
try:
|
|
57591
58577
|
_collect_hermes_sessions(days=90, quiet=quiet)
|
|
@@ -57596,6 +58582,36 @@ if __name__ == "__main__":
|
|
|
57596
58582
|
finally:
|
|
57597
58583
|
_clear_hook_budget(_tok_hook_deadline)
|
|
57598
58584
|
sys.exit(0)
|
|
58585
|
+
elif args[0] == "hermes-checkpoint":
|
|
58586
|
+
# Session checkpoint for a Hermes session, built from Hermes's own
|
|
58587
|
+
# state.db messages (read-only). Spawned detached by the Hermes plugin
|
|
58588
|
+
# at fill bands, before compaction, before subagent fan-out, after edit
|
|
58589
|
+
# batches, at turn end and at session end. Same 60s backstop as
|
|
58590
|
+
# hermes-rollup: a skipped checkpoint is invisible, a frozen orphan is not.
|
|
58591
|
+
_tok_hook_deadline = _install_hook_budget(60)
|
|
58592
|
+
try:
|
|
58593
|
+
_hermes_checkpoint_cli(args[1:])
|
|
58594
|
+
except _HookTimeout:
|
|
58595
|
+
pass
|
|
58596
|
+
except Exception:
|
|
58597
|
+
pass
|
|
58598
|
+
finally:
|
|
58599
|
+
_clear_hook_budget(_tok_hook_deadline)
|
|
58600
|
+
sys.exit(0)
|
|
58601
|
+
elif args[0] == "hermes-turn-context":
|
|
58602
|
+
# One child process per Hermes turn for continuity + lean-output (see
|
|
58603
|
+
# hermes_turn_context). Reads a JSON payload on stdin, prints one JSON
|
|
58604
|
+
# object. Same 8s budget as the Claude Code prompt hooks.
|
|
58605
|
+
_tok_hook_deadline = _install_hook_budget(8)
|
|
58606
|
+
try:
|
|
58607
|
+
print(json.dumps(hermes_turn_context(_read_stdin_hook_input())))
|
|
58608
|
+
except _HookTimeout:
|
|
58609
|
+
pass
|
|
58610
|
+
except Exception:
|
|
58611
|
+
pass
|
|
58612
|
+
finally:
|
|
58613
|
+
_clear_hook_budget(_tok_hook_deadline)
|
|
58614
|
+
sys.exit(0)
|
|
57599
58615
|
elif args[0] == "hermes-summary":
|
|
57600
58616
|
# Print a brief usage summary for the most recent Hermes sessions.
|
|
57601
58617
|
# Called by hermes_hook_bridge.run_summary() on /token-optimizer command.
|
|
@@ -57991,7 +59007,7 @@ if __name__ == "__main__":
|
|
|
57991
59007
|
elif args[0] == "setup-hook":
|
|
57992
59008
|
dry = "--dry-run" in args
|
|
57993
59009
|
uninstall = "--uninstall" in args
|
|
57994
|
-
setup_hook(dry_run=dry, uninstall=uninstall)
|
|
59010
|
+
setup_hook(dry_run=dry, uninstall=uninstall, user_initiated=True)
|
|
57995
59011
|
elif args[0] == "setup-all-hooks":
|
|
57996
59012
|
dry = "--dry-run" in args
|
|
57997
59013
|
verbose = "--verbose" in args or "-v" in args
|
|
@@ -58735,7 +59751,8 @@ if __name__ == "__main__":
|
|
|
58735
59751
|
output_json = "--json" in args
|
|
58736
59752
|
install = "--install" in args
|
|
58737
59753
|
dry = "--dry-run" in args
|
|
58738
|
-
generate_compact_instructions(as_json=output_json, install=install, dry_run=dry
|
|
59754
|
+
generate_compact_instructions(as_json=output_json, install=install, dry_run=dry,
|
|
59755
|
+
user_initiated=True)
|
|
58739
59756
|
elif args[0] == "dynamic-compact-instructions":
|
|
58740
59757
|
hook_input = _read_stdin_hook_input()
|
|
58741
59758
|
sid = hook_input.get("session_id") or os.environ.get("CLAUDE_SESSION_ID", "")
|
|
@@ -58744,7 +59761,8 @@ if __name__ == "__main__":
|
|
|
58744
59761
|
dry = "--dry-run" in args
|
|
58745
59762
|
uninstall = "--uninstall" in args
|
|
58746
59763
|
status = "--status" in args
|
|
58747
|
-
setup_smart_compact(dry_run=dry, uninstall=uninstall, status_only=status
|
|
59764
|
+
setup_smart_compact(dry_run=dry, uninstall=uninstall, status_only=status,
|
|
59765
|
+
user_initiated=True)
|
|
58748
59766
|
elif args[0] == "daemon-revive":
|
|
58749
59767
|
# Detached child spawned by _daemon_midsession_pulse. Revives a dead
|
|
58750
59768
|
# dashboard daemon OFF the hot path: force=True bypasses the 24h
|
|
@@ -59316,7 +60334,8 @@ if __name__ == "__main__":
|
|
|
59316
60334
|
dry = "--dry-run" in args
|
|
59317
60335
|
uninstall = "--uninstall" in args
|
|
59318
60336
|
status = "--status" in args
|
|
59319
|
-
setup_quality_bar(dry_run=dry, uninstall=uninstall, status_only=status
|
|
60337
|
+
setup_quality_bar(dry_run=dry, uninstall=uninstall, status_only=status,
|
|
60338
|
+
user_initiated=True)
|
|
59320
60339
|
elif args[0] == "setup-vscode-extension":
|
|
59321
60340
|
# Manage the VS Code status-bar extension auto-install.
|
|
59322
60341
|
# --uninstall : sticky opt-out (+ remove the extension if a CLI is present)
|