@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50
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 +76 -0
- package/.claude-plugin/plugin.json +21 -0
- package/LICENSE +130 -0
- package/LICENSE-SMALL-BUSINESS.md +62 -0
- package/PRIVACY.md +200 -0
- package/README.md +13 -2
- package/hooks/codex-hooks.json +4 -0
- package/hooks/hooks.json +182 -0
- package/hooks/module_runner.py +149 -0
- package/hooks/posttooluse_runner.py +1110 -0
- package/hooks/python-launcher.sh +816 -0
- package/hooks/run.py +776 -0
- package/hooks/sessionstart_runner.py +629 -0
- package/hooks/stop_runner.py +408 -0
- package/hooks/userpromptsubmit_runner.py +722 -0
- package/hooks/windows-launcher.py +163 -0
- package/install-cloud.sh +23 -0
- package/package.json +29 -4
- package/skills/fleet-auditor/SKILL.md +150 -0
- package/skills/fleet-auditor/references/fleet-systems.md +167 -0
- package/skills/fleet-auditor/references/report-template.md +50 -0
- package/skills/fleet-auditor/references/waste-patterns.md +126 -0
- package/skills/fleet-auditor/scripts/fleet.py +3612 -0
- package/skills/fleet-auditor/scripts/shared.py +277 -0
- package/skills/resume-checkpoint/SKILL.md +52 -0
- package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
- package/skills/token-coach/SKILL.md +129 -0
- package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
- package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
- package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
- package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
- package/skills/token-coach/references/agentic-systems.md +147 -0
- package/skills/token-coach/references/coach-patterns.md +120 -0
- package/skills/token-coach/references/coaching-scripts.md +146 -0
- package/skills/token-coach/references/deterministic-stages.md +102 -0
- package/skills/token-coach/references/keepwarm-consent.md +48 -0
- package/skills/token-coach/references/quick-reference.md +155 -0
- package/skills/token-dashboard/SKILL.md +72 -0
- package/skills/token-optimizer/SKILL.md +150 -0
- package/skills/token-optimizer/assets/dashboard.html +7251 -0
- package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
- package/skills/token-optimizer/examples/hooks-starter.json +179 -0
- package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
- package/skills/token-optimizer/pricing/prices.json +695 -0
- package/skills/token-optimizer/references/agent-prompts.md +687 -0
- package/skills/token-optimizer/references/cli-reference.md +92 -0
- package/skills/token-optimizer/references/codex-workflow.md +188 -0
- package/skills/token-optimizer/references/cursor-workflow.md +74 -0
- package/skills/token-optimizer/references/error-recovery.md +37 -0
- package/skills/token-optimizer/references/implementation-playbook.md +416 -0
- package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
- package/skills/token-optimizer/references/opencode-workflow.md +72 -0
- package/skills/token-optimizer/references/optimization-checklist.md +714 -0
- package/skills/token-optimizer/references/phase0-setup.md +142 -0
- package/skills/token-optimizer/references/presentation-workflow.md +72 -0
- package/skills/token-optimizer/references/session-continuity.md +19 -0
- package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
- package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
- package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
- package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
- package/skills/token-optimizer/scripts/archive_result.py +1725 -0
- package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
- package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
- package/skills/token-optimizer/scripts/bash_hook.py +61 -0
- package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
- package/skills/token-optimizer/scripts/benchmark.py +1765 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
- package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
- package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
- package/skills/token-optimizer/scripts/codex_install.py +810 -0
- package/skills/token-optimizer/scripts/codex_io.py +119 -0
- package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
- package/skills/token-optimizer/scripts/codex_models.py +34 -0
- package/skills/token-optimizer/scripts/codex_session.py +1186 -0
- package/skills/token-optimizer/scripts/codex_state.py +707 -0
- package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
- package/skills/token-optimizer/scripts/command_filters.py +386 -0
- package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
- package/skills/token-optimizer/scripts/compression_log.py +230 -0
- package/skills/token-optimizer/scripts/context_intel.py +331 -0
- package/skills/token-optimizer/scripts/context_pressure.py +115 -0
- package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
- package/skills/token-optimizer/scripts/copilot_install.py +277 -0
- package/skills/token-optimizer/scripts/copilot_session.py +496 -0
- package/skills/token-optimizer/scripts/copilot_state.py +569 -0
- package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
- package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
- package/skills/token-optimizer/scripts/cowork_install.py +380 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
- package/skills/token-optimizer/scripts/cursor_install.py +423 -0
- package/skills/token-optimizer/scripts/cursor_session.py +303 -0
- package/skills/token-optimizer/scripts/cursor_state.py +348 -0
- package/skills/token-optimizer/scripts/delta_diff.py +110 -0
- package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
- package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
- package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
- package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
- package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
- package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
- package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
- package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
- package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
- package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
- package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
- package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
- package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
- package/skills/token-optimizer/scripts/devin_compress.py +790 -0
- package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
- package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
- package/skills/token-optimizer/scripts/devin_install.py +1086 -0
- package/skills/token-optimizer/scripts/devin_source.py +119 -0
- package/skills/token-optimizer/scripts/devin_state.py +330 -0
- package/skills/token-optimizer/scripts/devin_verify.py +67 -0
- package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
- package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
- package/skills/token-optimizer/scripts/grok_install.py +397 -0
- package/skills/token-optimizer/scripts/grok_session.py +317 -0
- package/skills/token-optimizer/scripts/grok_state.py +299 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
- package/skills/token-optimizer/scripts/hermes_install.py +668 -0
- package/skills/token-optimizer/scripts/hermes_session.py +691 -0
- package/skills/token-optimizer/scripts/hermes_state.py +448 -0
- package/skills/token-optimizer/scripts/hook_io.py +120 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
- package/skills/token-optimizer/scripts/injection.py +156 -0
- package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
- package/skills/token-optimizer/scripts/measure.py +58739 -0
- package/skills/token-optimizer/scripts/outline.py +53 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
- package/skills/token-optimizer/scripts/plugin_env.py +562 -0
- package/skills/token-optimizer/scripts/py_trust.py +80 -0
- package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
- package/skills/token-optimizer/scripts/read_cache.py +2489 -0
- package/skills/token-optimizer/scripts/recovery_output.py +110 -0
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
- package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
- package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
- package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
- package/skills/token-optimizer/scripts/session_store.py +979 -0
- package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
- package/skills/token-optimizer/scripts/statusline.js +660 -0
- package/skills/token-optimizer/scripts/structure_map.py +2880 -0
- package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
- package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
- package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
- package/skills/token-optimizer/scripts/token_estimate.py +80 -0
- package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
- package/skills/token-optimizer/scripts/utf8_io.py +219 -0
|
@@ -0,0 +1,1725 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Token Optimizer - PostToolUse Archive Result (standalone entry point).
|
|
3
|
+
|
|
4
|
+
Archives large tool results to disk so they survive compaction.
|
|
5
|
+
Standalone extraction for minimal startup overhead (~40ms vs ~135ms).
|
|
6
|
+
|
|
7
|
+
Security hardening:
|
|
8
|
+
- 0o600 permissions on all written files
|
|
9
|
+
- stdin capped at 1MB
|
|
10
|
+
- Archive entries capped at 5MB with truncation marker
|
|
11
|
+
- Session ID sanitized against path traversal
|
|
12
|
+
- tool_use_id mapped to a safe archive key; unsafe ids hash, never traverse
|
|
13
|
+
|
|
14
|
+
SOURCE OF TRUTH for _sanitize_session_id: session_store.py.
|
|
15
|
+
SOURCE OF TRUTH for read_stdin_hook_input: hook_io.py.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import fnmatch
|
|
21
|
+
import heapq
|
|
22
|
+
import io
|
|
23
|
+
import itertools
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
import shutil
|
|
28
|
+
import sqlite3
|
|
29
|
+
import sys
|
|
30
|
+
import tempfile
|
|
31
|
+
import unicodedata
|
|
32
|
+
from datetime import datetime, timezone
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
import hashlib
|
|
36
|
+
import time
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
from credential_patterns import redact_credentials as _redact_creds_shared
|
|
40
|
+
from credential_patterns import RedactionConfigError, pop_redaction_warning
|
|
41
|
+
except ImportError:
|
|
42
|
+
_redact_creds_shared = None
|
|
43
|
+
RedactionConfigError = None
|
|
44
|
+
pop_redaction_warning = None
|
|
45
|
+
from bash_compress import _TOKEN_PATTERNS
|
|
46
|
+
from hook_io import read_stdin_hook_input
|
|
47
|
+
from hook_runtime import LeaseLock
|
|
48
|
+
from plugin_env import resolve_snapshot_dir, snapshot_dir_candidates
|
|
49
|
+
from refetch_fingerprint import ARGS_HASH_KEY, expand_command, is_live_state_tool, tool_fingerprint
|
|
50
|
+
from recovery_output import is_recovery_output
|
|
51
|
+
from runtime_env import detect_runtime, settings_env_value
|
|
52
|
+
from session_store import SessionStore, _sanitize_session_id as sanitize_sid
|
|
53
|
+
|
|
54
|
+
# ---------------------------------------------------------------------------
|
|
55
|
+
# Constants
|
|
56
|
+
# ---------------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
CHARS_PER_TOKEN = 4.0 # legacy proxy; retained only for the conservative MCP-cap proximity threshold
|
|
59
|
+
try:
|
|
60
|
+
# Calibrated chars/token (~3.3 for code) — shared ratio basis for savings
|
|
61
|
+
# estimates so tool_archive numbers match the rest of the pipeline.
|
|
62
|
+
from token_estimate import CODE_CHARS_PER_TOKEN
|
|
63
|
+
except Exception: # pragma: no cover - fail-open if shared estimator missing
|
|
64
|
+
CODE_CHARS_PER_TOKEN = 3.3
|
|
65
|
+
_ARCHIVE_THRESHOLD = 4096 # chars: only archive results >= this size
|
|
66
|
+
_ARCHIVE_PREVIEW_SIZE = 1500 # chars: preview included in replacement output
|
|
67
|
+
_ARCHIVE_MAX_SIZE = 5_242_880 # 5MB: truncate responses beyond this
|
|
68
|
+
# Read this far past the cap when redacting, so a secret that straddles the cap
|
|
69
|
+
# is whole when the redactor sees it (the cut is applied after redaction).
|
|
70
|
+
_ARCHIVE_CAP_REDACT_OVERSHOOT = 4096
|
|
71
|
+
_STDIN_MAX_BYTES = _ARCHIVE_MAX_SIZE + 262_144 # 5MB response plus JSON overhead
|
|
72
|
+
_ARCHIVE_RETENTION_HOURS_DEFAULT = 24
|
|
73
|
+
_ARCHIVE_RETENTION_MAX_FILES_DEFAULT = 1000
|
|
74
|
+
_ARCHIVE_RETENTION_MAX_BYTES_DEFAULT = 104_857_600 # 100 MiB
|
|
75
|
+
_ARCHIVE_ACTIVE_GRACE_SECONDS_DEFAULT = 86_400
|
|
76
|
+
_ARCHIVE_CLEANUP_INTERVAL_SECONDS_DEFAULT = 60
|
|
77
|
+
|
|
78
|
+
# Best-effort sweep staleness threshold for orphan lease artifacts in
|
|
79
|
+
# ``archive_root/.locks/``. ``HookDeadline._watch`` calls ``os._exit(0)``, which
|
|
80
|
+
# bypasses ``LeaseLock.release()`` (the only unlinker of the candidate hard
|
|
81
|
+
# link), so ``.{sid}.lease.candidate-{nonce}`` files leak. Archive lock sites
|
|
82
|
+
# use ``LeaseLock(..., acquire_timeout=0)`` with NO deadline, so the max lease a
|
|
83
|
+
# candidate can represent is the default ``lease_seconds + reclaim_grace``
|
|
84
|
+
# (10.0 + 0.25 = 10.25s). The sweep reaps candidates older than this; a younger
|
|
85
|
+
# candidate is a live acquisition in flight and is never touched.
|
|
86
|
+
LOCK_SWEEP_STALE_SECONDS = 10.25
|
|
87
|
+
# A reclaim claim is swept on a far longer fuse than a lease candidate, and the
|
|
88
|
+
# asymmetry is deliberate. Reaping a live CANDIDATE is harmless: the acquirer
|
|
89
|
+
# simply fails to acquire and fails open. Reaping a live RECLAIM claim is not --
|
|
90
|
+
# the claim name is deterministic per generation precisely so that concurrent
|
|
91
|
+
# same-generation reclaimers collide and exactly one wins. Free that name while
|
|
92
|
+
# a reclaimer is still mid-sequence and a second reclaimer can take it, so two
|
|
93
|
+
# processes can end up believing they hold the lock. A reclaimer paused past ten
|
|
94
|
+
# seconds is plausible (suspended process, slow NFS, debugger); paused past five
|
|
95
|
+
# minutes is not, and the orphaned-claim deadlock this cures is bounded and rare.
|
|
96
|
+
RECLAIM_SWEEP_STALE_SECONDS = 300.0
|
|
97
|
+
|
|
98
|
+
# WS4: Agent/Task result progressive disclosure — shipped MEASURE-ONLY.
|
|
99
|
+
#
|
|
100
|
+
# A head+tail+pointer treatment WOULD save ~74% of the agent-result pool, but the
|
|
101
|
+
# 2026-06-11 history backfill measured a 39.1% harm proxy: in 39% of cases the
|
|
102
|
+
# parent's NEXT assistant turn quotes (>=20-char verbatim) text from the
|
|
103
|
+
# would-be-elided MIDDLE. Sub-agents put their findings in the middle (head =
|
|
104
|
+
# preamble, tail = usage/continuation block), so an active replacement would lose
|
|
105
|
+
# content the parent needs. Per the configured exception rule the DATA decides: 39.1%
|
|
106
|
+
# >> the 15% gate, so this ships measure-only. We log the would-be saving as an
|
|
107
|
+
# OPPORTUNITY-tier event (never the realized headline) so the dashboard shows the
|
|
108
|
+
# pool + the harm number; the full result is archived for `expand` either way.
|
|
109
|
+
# Re-evaluate active only if a middle-preserving treatment lands a sub-15% proxy.
|
|
110
|
+
_AGENT_RESULT_MIN_CHARS = 8 * 1024 # only measure sub-agent results > 8KB
|
|
111
|
+
_AGENT_RESULT_HEAD_CHARS = 2000
|
|
112
|
+
_AGENT_RESULT_TAIL_CHARS = 2000
|
|
113
|
+
_AGENT_RESULT_TOOL_NAMES = frozenset({"Task", "Agent"})
|
|
114
|
+
_FEATURE_AGENT_RESULT = "agent_result_skeleton"
|
|
115
|
+
_AGENT_RESULT_HARM_PCT = 39.1 # from the 2026-06-11 backfill (surfaced)
|
|
116
|
+
|
|
117
|
+
# Plugin-data-aware paths (env > installed_plugins.json > legacy)
|
|
118
|
+
SNAPSHOT_DIR = resolve_snapshot_dir()
|
|
119
|
+
TRENDS_DB = SNAPSHOT_DIR / "trends.db"
|
|
120
|
+
_SAVINGS_DB_TIMEOUT_SECONDS = 0.05
|
|
121
|
+
_SAVINGS_DB_BUSY_TIMEOUT_MS = 50
|
|
122
|
+
_DEFAULT_SAVINGS_COST_PER_MTOK = 3.0 # Sonnet input rate; safe fallback for hook-only pricing.
|
|
123
|
+
_HOOK_INPUT_COST_PER_MTOK = {
|
|
124
|
+
"gpt-6-astra": 10.0,
|
|
125
|
+
"gpt-5.6-sol": 5.0,
|
|
126
|
+
"gpt-5.6-terra": 2.0,
|
|
127
|
+
"gpt-5.6-luna": 0.20,
|
|
128
|
+
"gpt-5.6": 5.0,
|
|
129
|
+
"gpt-5.5-pro": 30.0,
|
|
130
|
+
"gpt-5.1-codex-mini": 0.25,
|
|
131
|
+
"gpt-4o-mini": 0.15,
|
|
132
|
+
"gpt-5-codex": 1.25,
|
|
133
|
+
"gpt-5.1-codex": 1.25,
|
|
134
|
+
"gpt-5.2-codex": 1.75,
|
|
135
|
+
"gpt-5.3-codex": 1.75,
|
|
136
|
+
"gpt-5-mini": 0.25,
|
|
137
|
+
"gpt-5-nano": 0.05,
|
|
138
|
+
"gpt-5": 1.25,
|
|
139
|
+
"gpt-5.4": 2.5,
|
|
140
|
+
"gpt-5.5": 5.0,
|
|
141
|
+
"gpt-4o": 2.5,
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
# gpt-5.6-sol promotional pricing (date-gated). OpenAI documents the $4/$20 rate
|
|
145
|
+
# as "available at least through November 21, 2026." _HOOK_INPUT_COST_PER_MTOK
|
|
146
|
+
# holds the STANDARD input rate ($5); while the promo window is open we swap the
|
|
147
|
+
# promo rate in so hook savings dollars stay accurate today AND flip back
|
|
148
|
+
# automatically after 2026-11-21. Mirrors measure.py _apply_gpt56_sol_promo_pricing.
|
|
149
|
+
_GPT56_SOL_PROMO_UNTIL = datetime(2026, 11, 21, tzinfo=timezone.utc)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _apply_gpt56_sol_promo_pricing(as_of=None):
|
|
153
|
+
"""Swap the gpt-5.6-sol hook input rate to the promotional rate while active (idempotent)."""
|
|
154
|
+
override = os.environ.get("TOKEN_OPTIMIZER_PRICING_AS_OF")
|
|
155
|
+
if as_of is None and override:
|
|
156
|
+
try:
|
|
157
|
+
as_of = datetime.strptime(override, "%Y-%m-%d")
|
|
158
|
+
except ValueError:
|
|
159
|
+
as_of = None
|
|
160
|
+
d = as_of or datetime.now(timezone.utc)
|
|
161
|
+
if d.tzinfo is None:
|
|
162
|
+
d = d.replace(tzinfo=timezone.utc)
|
|
163
|
+
if d < _GPT56_SOL_PROMO_UNTIL:
|
|
164
|
+
_HOOK_INPUT_COST_PER_MTOK["gpt-5.6-sol"] = 4.0
|
|
165
|
+
_HOOK_INPUT_COST_PER_MTOK["gpt-5.6"] = 4.0
|
|
166
|
+
return True
|
|
167
|
+
_HOOK_INPUT_COST_PER_MTOK["gpt-5.6-sol"] = 5.0
|
|
168
|
+
_HOOK_INPUT_COST_PER_MTOK["gpt-5.6"] = 5.0
|
|
169
|
+
return False
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
_apply_gpt56_sol_promo_pricing()
|
|
173
|
+
|
|
174
|
+
_SAVINGS_SCHEMA = """
|
|
175
|
+
CREATE TABLE IF NOT EXISTS savings_events (
|
|
176
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
177
|
+
timestamp TEXT NOT NULL,
|
|
178
|
+
event_type TEXT NOT NULL,
|
|
179
|
+
tokens_saved INTEGER NOT NULL DEFAULT 0,
|
|
180
|
+
cost_saved_usd REAL NOT NULL DEFAULT 0.0,
|
|
181
|
+
session_id TEXT,
|
|
182
|
+
detail TEXT
|
|
183
|
+
);
|
|
184
|
+
"""
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _chmod_private_file(path: Path) -> None:
|
|
188
|
+
try:
|
|
189
|
+
if path.exists() and not path.is_symlink():
|
|
190
|
+
os.chmod(str(path), 0o600)
|
|
191
|
+
except OSError:
|
|
192
|
+
pass
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# ---------------------------------------------------------------------------
|
|
196
|
+
# Helpers (SOURCE OF TRUTH: measure.py — keep in sync)
|
|
197
|
+
# ---------------------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
def _sanitize_session_id(sid: str | None) -> str:
|
|
200
|
+
return sanitize_sid(sid or "")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
# \Z, not $: "$" also matches before a trailing newline ("abc\n").
|
|
204
|
+
_ARCHIVE_KEY_RE = re.compile(r"^[a-zA-Z0-9_-]+\Z")
|
|
205
|
+
# Longer ids go under a digest too: "<id>.json" must stay under the 255-byte
|
|
206
|
+
# filename limit, or the archive fails and the output passes through unchanged.
|
|
207
|
+
_ARCHIVE_KEY_MAX_LEN = 128
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _safe_archive_key(tool_use_id: str) -> str:
|
|
211
|
+
"""Filesystem-safe archive key for a tool_use_id.
|
|
212
|
+
|
|
213
|
+
Ids outside [a-zA-Z0-9_-] (+, space, /, ., ') or longer than 128
|
|
214
|
+
characters map to a deterministic digest instead of being skipped — the archive still lands, expand's own
|
|
215
|
+
[a-zA-Z0-9_-]+ key validation accepts the digest, and no raw id ever
|
|
216
|
+
reaches a path, so traversal is impossible by construction.
|
|
217
|
+
"""
|
|
218
|
+
if len(tool_use_id) <= _ARCHIVE_KEY_MAX_LEN and _ARCHIVE_KEY_RE.match(tool_use_id):
|
|
219
|
+
return tool_use_id
|
|
220
|
+
digest = hashlib.sha256(
|
|
221
|
+
tool_use_id.encode("utf-8", errors="replace")).hexdigest()[:24]
|
|
222
|
+
return f"h{digest}"
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _archive_dir_for_session(session_id: str) -> Path:
|
|
228
|
+
"""Return the archive directory for a given session."""
|
|
229
|
+
sid = _sanitize_session_id(session_id)
|
|
230
|
+
return SNAPSHOT_DIR / "tool-archive" / sid
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _redact_credentials(text: str, *, command: bool = False) -> str:
|
|
234
|
+
"""Replace credential-matching substrings before archiving.
|
|
235
|
+
|
|
236
|
+
Prefers credential_patterns.redact_credentials (labeled placeholders like
|
|
237
|
+
[CREDENTIAL REDACTED: AWS access key]). Falls back to _TOKEN_PATTERNS
|
|
238
|
+
from bash_compress with generic [REDACTED] if the shared module is
|
|
239
|
+
unavailable. command=True marks shell command text, which also gets the
|
|
240
|
+
command-syntax rules (curl -u user:pass, --token VALUE, user:pass@host...).
|
|
241
|
+
"""
|
|
242
|
+
if _redact_creds_shared is not None:
|
|
243
|
+
return _redact_creds_shared(text, command=command)
|
|
244
|
+
for pattern in _TOKEN_PATTERNS:
|
|
245
|
+
text = pattern.sub("[REDACTED]", text)
|
|
246
|
+
return text
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _int_env(name: str, default: int) -> int:
|
|
250
|
+
"""Read a non-negative integer without adding a heavy config import."""
|
|
251
|
+
try:
|
|
252
|
+
value = int(os.environ.get(name, str(default)))
|
|
253
|
+
return value if value >= 0 else default
|
|
254
|
+
except (TypeError, ValueError):
|
|
255
|
+
return default
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _archive_tree_usage(session_dir: Path) -> tuple[int, int]:
|
|
259
|
+
"""Return (regular-file count, bytes) without following symlinks."""
|
|
260
|
+
files = 0
|
|
261
|
+
total_bytes = 0
|
|
262
|
+
for root, dirnames, filenames in os.walk(session_dir, followlinks=False):
|
|
263
|
+
root_path = Path(root)
|
|
264
|
+
dirnames[:] = [
|
|
265
|
+
name for name in dirnames
|
|
266
|
+
if not (root_path / name).is_symlink()
|
|
267
|
+
]
|
|
268
|
+
for name in filenames:
|
|
269
|
+
path = root_path / name
|
|
270
|
+
try:
|
|
271
|
+
if path.is_symlink() or not path.is_file():
|
|
272
|
+
continue
|
|
273
|
+
files += 1
|
|
274
|
+
total_bytes += os.lstat(path).st_size
|
|
275
|
+
except OSError:
|
|
276
|
+
continue
|
|
277
|
+
return files, total_bytes
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _archive_roots() -> list[Path]:
|
|
281
|
+
"""Return every safe archive root, active identity first."""
|
|
282
|
+
roots: list[Path] = []
|
|
283
|
+
seen: set[str] = set()
|
|
284
|
+
for snapshot_dir in snapshot_dir_candidates():
|
|
285
|
+
archive_root = snapshot_dir / "tool-archive"
|
|
286
|
+
try:
|
|
287
|
+
key = os.path.normcase(str(archive_root.resolve(strict=False)))
|
|
288
|
+
except (OSError, ValueError):
|
|
289
|
+
continue
|
|
290
|
+
if key not in seen:
|
|
291
|
+
roots.append(archive_root)
|
|
292
|
+
seen.add(key)
|
|
293
|
+
return roots
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _session_lock_path(archive_root: Path, session_id: str) -> Path:
|
|
297
|
+
return archive_root / ".locks" / f"{_sanitize_session_id(session_id)}.lease"
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _sweep_stale_lock_candidates(archive_root: Path) -> None:
|
|
301
|
+
"""Best-effort: unlink orphan ``.{sid}.lease.candidate-{nonce}`` and
|
|
302
|
+
``.{sid}.lease.reclaim-{digest}`` artifacts left in
|
|
303
|
+
``archive_root/.locks/`` when ``os._exit`` bypasses ``LeaseLock.release``
|
|
304
|
+
or the ``finally`` that unlinks a reclaim claim.
|
|
305
|
+
|
|
306
|
+
``cleanup_old_archives`` skips dot-dirs as *session* candidates (the
|
|
307
|
+
``.locks`` directory is never pruned as a session); this is a separate,
|
|
308
|
+
bounded scan of its contents. Only artifacts whose ``st_mtime`` is older
|
|
309
|
+
than ``LOCK_SWEEP_STALE_SECONDS`` (the max lease duration for archive locks)
|
|
310
|
+
are reaped, so a live acquisition or in-flight reclaimer is never broken.
|
|
311
|
+
|
|
312
|
+
The reclaim claim name is **deterministic per generation**
|
|
313
|
+
(``sha256("owner:{nonce}")[:32]``); a reclaimer killed between ``os.link``
|
|
314
|
+
and the ``finally`` unlink orphans a claim that, because the name is
|
|
315
|
+
deterministic, permanently deadlocks every future same-generation
|
|
316
|
+
reclaimer (``FileExistsError`` -> fail open forever). Reaping the stale
|
|
317
|
+
claim here bounds that deadlock from *permanent* to *until the next
|
|
318
|
+
cleanup pass* WITHOUT touching the deterministic claim name in
|
|
319
|
+
``hook_runtime._reclaim_path`` (the determinism is load-bearing
|
|
320
|
+
serialization: it is what makes concurrent same-generation reclaimers
|
|
321
|
+
exactly-one-winner). ``OSError`` is swallowed per entry so a locked or
|
|
322
|
+
vanishing file never aborts the hook.
|
|
323
|
+
"""
|
|
324
|
+
locks_dir = archive_root / ".locks"
|
|
325
|
+
try:
|
|
326
|
+
entries = list(locks_dir.iterdir())
|
|
327
|
+
except (OSError, ValueError):
|
|
328
|
+
return
|
|
329
|
+
now = time.time()
|
|
330
|
+
candidate_cutoff = now - LOCK_SWEEP_STALE_SECONDS
|
|
331
|
+
reclaim_cutoff = now - RECLAIM_SWEEP_STALE_SECONDS
|
|
332
|
+
for entry in entries:
|
|
333
|
+
if ".lease.candidate-" in entry.name:
|
|
334
|
+
cutoff = candidate_cutoff
|
|
335
|
+
elif ".lease.reclaim-" in entry.name:
|
|
336
|
+
cutoff = reclaim_cutoff
|
|
337
|
+
else:
|
|
338
|
+
continue
|
|
339
|
+
try:
|
|
340
|
+
if entry.is_dir():
|
|
341
|
+
continue
|
|
342
|
+
if entry.stat().st_mtime < cutoff:
|
|
343
|
+
entry.unlink()
|
|
344
|
+
except OSError:
|
|
345
|
+
pass
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _mark_session_active(session_dir: Path) -> None:
|
|
349
|
+
"""Refresh the bounded activity heartbeat used by aggregate cleanup."""
|
|
350
|
+
marker = session_dir / ".active"
|
|
351
|
+
try:
|
|
352
|
+
marker.touch(mode=0o600, exist_ok=True)
|
|
353
|
+
os.chmod(marker, 0o600)
|
|
354
|
+
except OSError:
|
|
355
|
+
pass
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _session_is_active(session_dir: Path) -> bool:
|
|
359
|
+
grace = _int_env(
|
|
360
|
+
"TOKEN_OPTIMIZER_ARCHIVE_ACTIVE_GRACE_SECONDS",
|
|
361
|
+
_ARCHIVE_ACTIVE_GRACE_SECONDS_DEFAULT,
|
|
362
|
+
)
|
|
363
|
+
try:
|
|
364
|
+
marker = session_dir / ".active"
|
|
365
|
+
return (
|
|
366
|
+
not marker.is_symlink()
|
|
367
|
+
and marker.is_file()
|
|
368
|
+
and time.time() - os.lstat(marker).st_mtime <= grace
|
|
369
|
+
)
|
|
370
|
+
except OSError:
|
|
371
|
+
return True
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _prune_session_entries(
|
|
375
|
+
session_dir: Path,
|
|
376
|
+
*,
|
|
377
|
+
cutoff: float | None = None,
|
|
378
|
+
files_needed: int = 0,
|
|
379
|
+
bytes_needed: int = 0,
|
|
380
|
+
) -> None:
|
|
381
|
+
"""Prune oldest result entries without removing an active session dir."""
|
|
382
|
+
entries: list[tuple[float, Path, int]] = []
|
|
383
|
+
try:
|
|
384
|
+
candidates = list(session_dir.glob("*.json"))
|
|
385
|
+
except OSError:
|
|
386
|
+
return
|
|
387
|
+
for path in candidates:
|
|
388
|
+
try:
|
|
389
|
+
if path.is_symlink() or not path.is_file():
|
|
390
|
+
continue
|
|
391
|
+
stat = os.lstat(path)
|
|
392
|
+
entries.append((stat.st_mtime, path, stat.st_size))
|
|
393
|
+
except OSError:
|
|
394
|
+
continue
|
|
395
|
+
entries.sort(key=lambda item: item[0])
|
|
396
|
+
removed_files = 0
|
|
397
|
+
removed_bytes = 0
|
|
398
|
+
removed_any = False
|
|
399
|
+
for mtime, path, size in entries:
|
|
400
|
+
expired = cutoff is not None and mtime < cutoff
|
|
401
|
+
needed = (
|
|
402
|
+
removed_files < max(0, files_needed)
|
|
403
|
+
or removed_bytes < max(0, bytes_needed)
|
|
404
|
+
)
|
|
405
|
+
if not expired and not needed:
|
|
406
|
+
continue
|
|
407
|
+
try:
|
|
408
|
+
path.unlink()
|
|
409
|
+
removed_files += 1
|
|
410
|
+
removed_bytes += size
|
|
411
|
+
removed_any = True
|
|
412
|
+
except OSError:
|
|
413
|
+
continue
|
|
414
|
+
if not removed_any:
|
|
415
|
+
return
|
|
416
|
+
|
|
417
|
+
# Keep the manifest bounded with the result set. The caller holds the
|
|
418
|
+
# session lease, so replacement cannot race another archive writer.
|
|
419
|
+
manifest = session_dir / "manifest.jsonl"
|
|
420
|
+
try:
|
|
421
|
+
if manifest.is_symlink() or not manifest.is_file():
|
|
422
|
+
return
|
|
423
|
+
retained = {path.stem for path in session_dir.glob("*.json")}
|
|
424
|
+
lines: list[str] = []
|
|
425
|
+
for line in manifest.read_text(encoding="utf-8").splitlines():
|
|
426
|
+
try:
|
|
427
|
+
record = json.loads(line)
|
|
428
|
+
if record.get("tool_use_id") in retained:
|
|
429
|
+
lines.append(line)
|
|
430
|
+
except (TypeError, json.JSONDecodeError):
|
|
431
|
+
continue
|
|
432
|
+
if not lines:
|
|
433
|
+
manifest.unlink()
|
|
434
|
+
return
|
|
435
|
+
fd, tmp_path = tempfile.mkstemp(
|
|
436
|
+
prefix=".manifest.", suffix=".tmp", dir=str(session_dir), text=True
|
|
437
|
+
)
|
|
438
|
+
try:
|
|
439
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
440
|
+
handle.write("\n".join(lines) + "\n")
|
|
441
|
+
os.chmod(tmp_path, 0o600)
|
|
442
|
+
os.replace(tmp_path, manifest)
|
|
443
|
+
except Exception:
|
|
444
|
+
try:
|
|
445
|
+
os.unlink(tmp_path)
|
|
446
|
+
except OSError:
|
|
447
|
+
pass
|
|
448
|
+
raise
|
|
449
|
+
except (OSError, ValueError):
|
|
450
|
+
pass
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def cleanup_old_archives(
|
|
454
|
+
max_age_hours: int | None = None,
|
|
455
|
+
skip_session_id: str | None = None,
|
|
456
|
+
) -> int:
|
|
457
|
+
"""Delete expired archives and enforce aggregate file/byte caps.
|
|
458
|
+
|
|
459
|
+
Best-effort: individual OSError is swallowed so a locked or missing
|
|
460
|
+
directory never aborts the hook. The hot path reads its knobs locally to
|
|
461
|
+
avoid importing measure.py. Returns the count of removed session dirs.
|
|
462
|
+
"""
|
|
463
|
+
if max_age_hours is None:
|
|
464
|
+
max_age_hours = _int_env(
|
|
465
|
+
"TOKEN_OPTIMIZER_ARCHIVE_RETENTION_HOURS",
|
|
466
|
+
_ARCHIVE_RETENTION_HOURS_DEFAULT,
|
|
467
|
+
)
|
|
468
|
+
max_files = _int_env(
|
|
469
|
+
"TOKEN_OPTIMIZER_ARCHIVE_RETENTION_MAX_FILES",
|
|
470
|
+
_ARCHIVE_RETENTION_MAX_FILES_DEFAULT,
|
|
471
|
+
)
|
|
472
|
+
max_bytes = _int_env(
|
|
473
|
+
"TOKEN_OPTIMIZER_ARCHIVE_RETENTION_MAX_BYTES",
|
|
474
|
+
_ARCHIVE_RETENTION_MAX_BYTES_DEFAULT,
|
|
475
|
+
)
|
|
476
|
+
cutoff = time.time() - (max_age_hours * 3600)
|
|
477
|
+
removed = 0
|
|
478
|
+
skip_sid = _sanitize_session_id(skip_session_id) if skip_session_id else None
|
|
479
|
+
sessions: list[tuple[float, Path, Path, int, int, bool]] = []
|
|
480
|
+
for archive_root in _archive_roots():
|
|
481
|
+
if not archive_root.exists() or archive_root.is_symlink():
|
|
482
|
+
continue
|
|
483
|
+
# Sweep orphan ``.lease.candidate-*`` artifacts from ``.locks/`` (a
|
|
484
|
+
# dot-dir the session scan below intentionally skips). Best-effort;
|
|
485
|
+
# OSError-swallowed internally.
|
|
486
|
+
_sweep_stale_lock_candidates(archive_root)
|
|
487
|
+
try:
|
|
488
|
+
candidates = list(archive_root.iterdir())
|
|
489
|
+
except OSError:
|
|
490
|
+
continue
|
|
491
|
+
for session_dir in candidates:
|
|
492
|
+
if session_dir.name.startswith("."):
|
|
493
|
+
continue
|
|
494
|
+
if session_dir.is_symlink() or not session_dir.is_dir():
|
|
495
|
+
continue
|
|
496
|
+
protected = (
|
|
497
|
+
(skip_sid is not None and session_dir.name == skip_sid)
|
|
498
|
+
or _session_is_active(session_dir)
|
|
499
|
+
)
|
|
500
|
+
try:
|
|
501
|
+
mtime = os.lstat(session_dir).st_mtime
|
|
502
|
+
if protected:
|
|
503
|
+
lock = LeaseLock(
|
|
504
|
+
_session_lock_path(archive_root, session_dir.name),
|
|
505
|
+
acquire_timeout=0,
|
|
506
|
+
)
|
|
507
|
+
if lock.acquire():
|
|
508
|
+
try:
|
|
509
|
+
_prune_session_entries(session_dir, cutoff=cutoff)
|
|
510
|
+
finally:
|
|
511
|
+
lock.release()
|
|
512
|
+
elif mtime < cutoff:
|
|
513
|
+
lock = LeaseLock(
|
|
514
|
+
_session_lock_path(archive_root, session_dir.name),
|
|
515
|
+
acquire_timeout=0,
|
|
516
|
+
)
|
|
517
|
+
if lock.acquire():
|
|
518
|
+
try:
|
|
519
|
+
if not _session_is_active(session_dir):
|
|
520
|
+
shutil.rmtree(session_dir, ignore_errors=True)
|
|
521
|
+
if not session_dir.exists():
|
|
522
|
+
removed += 1
|
|
523
|
+
continue
|
|
524
|
+
finally:
|
|
525
|
+
lock.release()
|
|
526
|
+
file_count, byte_count = _archive_tree_usage(session_dir)
|
|
527
|
+
sessions.append((
|
|
528
|
+
mtime,
|
|
529
|
+
archive_root,
|
|
530
|
+
session_dir,
|
|
531
|
+
file_count,
|
|
532
|
+
byte_count,
|
|
533
|
+
protected,
|
|
534
|
+
))
|
|
535
|
+
except OSError:
|
|
536
|
+
pass
|
|
537
|
+
total_files = sum(item[3] for item in sessions)
|
|
538
|
+
total_bytes = sum(item[4] for item in sessions)
|
|
539
|
+
for _mtime, archive_root, session_dir, file_count, byte_count, protected in sorted(
|
|
540
|
+
sessions, key=lambda item: item[0]
|
|
541
|
+
):
|
|
542
|
+
over_files = max_files > 0 and total_files > max_files
|
|
543
|
+
over_bytes = max_bytes > 0 and total_bytes > max_bytes
|
|
544
|
+
if not (over_files or over_bytes):
|
|
545
|
+
break
|
|
546
|
+
if protected:
|
|
547
|
+
lock = LeaseLock(
|
|
548
|
+
_session_lock_path(archive_root, session_dir.name),
|
|
549
|
+
acquire_timeout=0,
|
|
550
|
+
)
|
|
551
|
+
if not lock.acquire():
|
|
552
|
+
continue
|
|
553
|
+
try:
|
|
554
|
+
before_files, before_bytes = _archive_tree_usage(session_dir)
|
|
555
|
+
_prune_session_entries(
|
|
556
|
+
session_dir,
|
|
557
|
+
files_needed=max(0, total_files - max_files)
|
|
558
|
+
if max_files > 0 else 0,
|
|
559
|
+
bytes_needed=max(0, total_bytes - max_bytes)
|
|
560
|
+
if max_bytes > 0 else 0,
|
|
561
|
+
)
|
|
562
|
+
after_files, after_bytes = _archive_tree_usage(session_dir)
|
|
563
|
+
total_files -= max(0, before_files - after_files)
|
|
564
|
+
total_bytes -= max(0, before_bytes - after_bytes)
|
|
565
|
+
finally:
|
|
566
|
+
lock.release()
|
|
567
|
+
continue
|
|
568
|
+
lock = LeaseLock(
|
|
569
|
+
_session_lock_path(archive_root, session_dir.name),
|
|
570
|
+
acquire_timeout=0,
|
|
571
|
+
)
|
|
572
|
+
if not lock.acquire():
|
|
573
|
+
continue
|
|
574
|
+
try:
|
|
575
|
+
if _session_is_active(session_dir):
|
|
576
|
+
continue
|
|
577
|
+
shutil.rmtree(session_dir, ignore_errors=True)
|
|
578
|
+
if not session_dir.exists():
|
|
579
|
+
removed += 1
|
|
580
|
+
total_files -= file_count
|
|
581
|
+
total_bytes -= byte_count
|
|
582
|
+
except OSError:
|
|
583
|
+
pass
|
|
584
|
+
finally:
|
|
585
|
+
lock.release()
|
|
586
|
+
return removed
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def _cleanup_archives_if_due(session_id: str) -> None:
|
|
590
|
+
"""Rate-limit the recursive retention scan on synchronous hook paths."""
|
|
591
|
+
interval = _int_env(
|
|
592
|
+
"TOKEN_OPTIMIZER_ARCHIVE_CLEANUP_INTERVAL_SECONDS",
|
|
593
|
+
_ARCHIVE_CLEANUP_INTERVAL_SECONDS_DEFAULT,
|
|
594
|
+
)
|
|
595
|
+
marker = SNAPSHOT_DIR / ".archive-cleanup.last"
|
|
596
|
+
lock = LeaseLock(
|
|
597
|
+
SNAPSHOT_DIR / ".archive-cleanup.lease",
|
|
598
|
+
acquire_timeout=0,
|
|
599
|
+
)
|
|
600
|
+
if not lock.acquire():
|
|
601
|
+
return
|
|
602
|
+
try:
|
|
603
|
+
try:
|
|
604
|
+
if interval > 0 and time.time() - marker.stat().st_mtime < interval:
|
|
605
|
+
return
|
|
606
|
+
except OSError:
|
|
607
|
+
pass
|
|
608
|
+
try:
|
|
609
|
+
marker.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
610
|
+
marker.touch(mode=0o600, exist_ok=True)
|
|
611
|
+
except OSError:
|
|
612
|
+
return
|
|
613
|
+
cleanup_old_archives(skip_session_id=session_id)
|
|
614
|
+
finally:
|
|
615
|
+
lock.release()
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
# ---------------------------------------------------------------------------
|
|
619
|
+
# Savings event logging (mirrors read_cache.py pattern — self-contained so
|
|
620
|
+
# this hook stays fast without importing measure.py at startup)
|
|
621
|
+
# ---------------------------------------------------------------------------
|
|
622
|
+
|
|
623
|
+
def _log_savings_event(event_type: str, tokens_saved: int, session_id: str | None, detail: str) -> None:
|
|
624
|
+
"""Write a savings event row to the trends DB.
|
|
625
|
+
|
|
626
|
+
This is intentionally self-contained and fail-fast: archive_result.py runs
|
|
627
|
+
in the PostToolUse hot path, so it must never import measure.py or wait on
|
|
628
|
+
a locked dashboard DB. Never raises.
|
|
629
|
+
"""
|
|
630
|
+
if tokens_saved <= 0:
|
|
631
|
+
return
|
|
632
|
+
conn: sqlite3.Connection | None = None
|
|
633
|
+
try:
|
|
634
|
+
SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
635
|
+
os.chmod(str(SNAPSHOT_DIR), 0o700)
|
|
636
|
+
conn = sqlite3.connect(str(TRENDS_DB), timeout=_SAVINGS_DB_TIMEOUT_SECONDS)
|
|
637
|
+
_chmod_private_file(TRENDS_DB)
|
|
638
|
+
conn.execute(f"PRAGMA busy_timeout={_SAVINGS_DB_BUSY_TIMEOUT_MS}")
|
|
639
|
+
# WAL lets a savings write proceed while a dashboard reader holds the DB,
|
|
640
|
+
# instead of silently dropping the event on SQLITE_BUSY under parallel MCP
|
|
641
|
+
# calls. (The -wal/-shm chmod below already assumed WAL; this enables it.)
|
|
642
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
643
|
+
conn.execute("PRAGMA synchronous=NORMAL")
|
|
644
|
+
conn.executescript(_SAVINGS_SCHEMA)
|
|
645
|
+
cost_per_mtok = _estimate_savings_cost_per_mtok()
|
|
646
|
+
cost_saved = tokens_saved * cost_per_mtok / 1_000_000
|
|
647
|
+
# origin (local / cloud / cowork): added in place on an older table;
|
|
648
|
+
# if that cannot happen right now the event is kept without it.
|
|
649
|
+
has_origin = False
|
|
650
|
+
try:
|
|
651
|
+
cols = {r[1] for r in conn.execute("PRAGMA table_info(savings_events)").fetchall()}
|
|
652
|
+
if "origin" not in cols:
|
|
653
|
+
conn.execute("ALTER TABLE savings_events ADD COLUMN origin TEXT")
|
|
654
|
+
has_origin = True
|
|
655
|
+
except sqlite3.Error:
|
|
656
|
+
has_origin = False
|
|
657
|
+
if has_origin:
|
|
658
|
+
conn.execute(
|
|
659
|
+
"INSERT INTO savings_events (timestamp, event_type, tokens_saved, cost_saved_usd, session_id, detail, origin) "
|
|
660
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?)",
|
|
661
|
+
(datetime.now().isoformat(), event_type, tokens_saved, cost_saved, session_id, detail,
|
|
662
|
+
_run_origin()),
|
|
663
|
+
)
|
|
664
|
+
else:
|
|
665
|
+
conn.execute(
|
|
666
|
+
"INSERT INTO savings_events (timestamp, event_type, tokens_saved, cost_saved_usd, session_id, detail) "
|
|
667
|
+
"VALUES (?, ?, ?, ?, ?, ?)",
|
|
668
|
+
(datetime.now().isoformat(), event_type, tokens_saved, cost_saved, session_id, detail),
|
|
669
|
+
)
|
|
670
|
+
conn.commit()
|
|
671
|
+
for suffix in ("", "-wal", "-shm"):
|
|
672
|
+
_chmod_private_file(Path(str(TRENDS_DB) + suffix))
|
|
673
|
+
except Exception:
|
|
674
|
+
pass
|
|
675
|
+
finally:
|
|
676
|
+
if conn is not None:
|
|
677
|
+
try:
|
|
678
|
+
conn.close()
|
|
679
|
+
except Exception:
|
|
680
|
+
pass
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def _run_origin() -> str:
|
|
684
|
+
"""runtime_env.run_origin(), or 'local' if it cannot be imported."""
|
|
685
|
+
try:
|
|
686
|
+
from runtime_env import run_origin
|
|
687
|
+
return run_origin()
|
|
688
|
+
except Exception:
|
|
689
|
+
return "local"
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def _estimate_savings_cost_per_mtok() -> float:
|
|
693
|
+
"""Return a tiny hook-safe input-token price estimate.
|
|
694
|
+
|
|
695
|
+
Full model-aware attribution lives in measure.py. This hot-path hook keeps
|
|
696
|
+
the import graph small and uses only env hints, undercounting to Sonnet when
|
|
697
|
+
the active model is unknown.
|
|
698
|
+
"""
|
|
699
|
+
override = os.environ.get("TOKEN_OPTIMIZER_COST_PER_MTOK", "").strip()
|
|
700
|
+
if override:
|
|
701
|
+
try:
|
|
702
|
+
value = float(override)
|
|
703
|
+
if value > 0:
|
|
704
|
+
return value
|
|
705
|
+
except ValueError:
|
|
706
|
+
pass
|
|
707
|
+
|
|
708
|
+
is_codex = detect_runtime() == 'codex'
|
|
709
|
+
model = (
|
|
710
|
+
os.environ.get("CLAUDE_MODEL")
|
|
711
|
+
or os.environ.get("ANTHROPIC_MODEL")
|
|
712
|
+
or os.environ.get("CODEX_MODEL")
|
|
713
|
+
or os.environ.get("OPENAI_MODEL")
|
|
714
|
+
or os.environ.get("MODEL")
|
|
715
|
+
or ""
|
|
716
|
+
).lower()
|
|
717
|
+
if is_codex:
|
|
718
|
+
model = (os.environ.get('CODEX_MODEL') or os.environ.get('OPENAI_MODEL') or '').lower()
|
|
719
|
+
model = re.sub(r"[\s_]+", "-", model.rsplit("/", 1)[-1].rsplit(":", 1)[-1])
|
|
720
|
+
if "fable" in model:
|
|
721
|
+
return 10.0
|
|
722
|
+
if "opus" in model:
|
|
723
|
+
return 5.0
|
|
724
|
+
if "haiku" in model:
|
|
725
|
+
return 1.0
|
|
726
|
+
for alias, rate in _HOOK_INPUT_COST_PER_MTOK.items():
|
|
727
|
+
if model == alias or model.startswith(alias + "-"):
|
|
728
|
+
return rate
|
|
729
|
+
return 0.0 if is_codex else _DEFAULT_SAVINGS_COST_PER_MTOK
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
# ---------------------------------------------------------------------------
|
|
733
|
+
# MCP output-cap savings estimation
|
|
734
|
+
# ---------------------------------------------------------------------------
|
|
735
|
+
|
|
736
|
+
# Fraction of the cap we assume was saved by the native truncation.
|
|
737
|
+
# Rationale: we cannot know the true pre-cap size (Claude Code truncates before
|
|
738
|
+
# PostToolUse fires). A conservative fixed estimate of 50% of the cap is used:
|
|
739
|
+
# i.e., if the cap is 10 000 tokens and the result is at the cap, we assume the
|
|
740
|
+
# true output was at least 1.5x the cap, so the native cap saved ~0.5x the cap.
|
|
741
|
+
# This deliberately understates rather than overstates; Phase 2 will replace
|
|
742
|
+
# this with actual measurement via a PreToolUse size probe.
|
|
743
|
+
_MCP_CAP_ESTIMATED_RATIO = 0.5 # fraction of cap_tokens logged as saved
|
|
744
|
+
# How close to the cap (in chars) a result must be before we flag it as capped.
|
|
745
|
+
# 90% prevents false positives from MCP tools that naturally return near-cap
|
|
746
|
+
# amounts without being truncated.
|
|
747
|
+
_MCP_CAP_PROXIMITY_PCT = 0.90 # result must be >= 90% of cap_chars to flag
|
|
748
|
+
|
|
749
|
+
_MCP_CAP_CACHE_UNSET = object()
|
|
750
|
+
_MCP_CAP_TOKENS_CACHE = _MCP_CAP_CACHE_UNSET
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
def _resolve_mcp_cap_tokens() -> int | None:
|
|
754
|
+
"""Read explicit MAX_MCP_OUTPUT_TOKENS from env or user settings.json.
|
|
755
|
+
|
|
756
|
+
Resolution order mirrors the Claude Code env injection chain:
|
|
757
|
+
1. Process environment (set by Claude Code from settings.json at startup)
|
|
758
|
+
2. ~/.claude/settings.json "env" block (direct read — for callers running
|
|
759
|
+
outside the Claude Code process, e.g. in tests)
|
|
760
|
+
|
|
761
|
+
Never raises. Returns None when no explicit cap is configured so we do not
|
|
762
|
+
invent savings from an assumed platform default.
|
|
763
|
+
"""
|
|
764
|
+
global _MCP_CAP_TOKENS_CACHE
|
|
765
|
+
if _MCP_CAP_TOKENS_CACHE is not _MCP_CAP_CACHE_UNSET:
|
|
766
|
+
return _MCP_CAP_TOKENS_CACHE
|
|
767
|
+
|
|
768
|
+
# 1. Env var (most common — Claude Code injects this from settings.json)
|
|
769
|
+
env_val = os.environ.get("MAX_MCP_OUTPUT_TOKENS", "").strip()
|
|
770
|
+
if env_val:
|
|
771
|
+
try:
|
|
772
|
+
v = int(env_val)
|
|
773
|
+
if v > 0:
|
|
774
|
+
_MCP_CAP_TOKENS_CACHE = v
|
|
775
|
+
return v
|
|
776
|
+
except ValueError:
|
|
777
|
+
pass
|
|
778
|
+
|
|
779
|
+
# 2. settings.json "env" block — for out-of-process callers
|
|
780
|
+
raw = settings_env_value("MAX_MCP_OUTPUT_TOKENS")
|
|
781
|
+
if raw:
|
|
782
|
+
try:
|
|
783
|
+
v = int(raw)
|
|
784
|
+
if v > 0:
|
|
785
|
+
_MCP_CAP_TOKENS_CACHE = v
|
|
786
|
+
return v
|
|
787
|
+
except ValueError:
|
|
788
|
+
pass
|
|
789
|
+
|
|
790
|
+
_MCP_CAP_TOKENS_CACHE = None
|
|
791
|
+
return None
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
# Built-in exemptions for MCP servers whose whole purpose is returning large
|
|
795
|
+
# verbatim code/docs the agent must read inline — compressing those to a preview
|
|
796
|
+
# defeats the reason they were called. Kept deliberately narrow (only tools whose
|
|
797
|
+
# PRIMARY output is verbatim source/docs) so the optimizer still compresses chatty
|
|
798
|
+
# general MCPs. The user's TOKEN_OPTIMIZER_ARCHIVE_EXEMPT_TOOLS is ADDITIVE to
|
|
799
|
+
# this list, so opting more tools out stays a one-line change. To drop a default,
|
|
800
|
+
# set TOKEN_OPTIMIZER_ARCHIVE_EXEMPT_DEFAULTS=off.
|
|
801
|
+
_DEFAULT_EXEMPT_PATTERNS: tuple[str, ...] = (
|
|
802
|
+
# Scoped to the specific verbatim content-fetch tools only — NOT whole
|
|
803
|
+
# servers. octocode/github/deepwiki also expose search/tree/list tools whose
|
|
804
|
+
# compression is desirable, so exempting the whole server would bloat context
|
|
805
|
+
# and defeat the optimizer. Only tools whose PRIMARY output is verbatim
|
|
806
|
+
# code/docs the agent must read inline are listed.
|
|
807
|
+
"mcp__context7__query-docs", # context7: verbatim library docs
|
|
808
|
+
"mcp__octocode__githubGetFileContent", # octocode: full remote file content
|
|
809
|
+
"mcp__octocode__localGetFileContent", # octocode: full local file content
|
|
810
|
+
"mcp__github__get_file_contents", # official github MCP file fetcher
|
|
811
|
+
"mcp__deepwiki__read_wiki_contents", # deepwiki: verbatim repo docs
|
|
812
|
+
)
|
|
813
|
+
|
|
814
|
+
_EXEMPT_PATTERNS_UNSET: tuple[str, ...] | None = ("\0__unset__",)
|
|
815
|
+
_EXEMPT_PATTERNS_CACHE: tuple[str, ...] | None = _EXEMPT_PATTERNS_UNSET
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
def _resolve_exempt_tool_patterns() -> tuple[str, ...]:
|
|
819
|
+
"""Resolve the per-tool archive allowlist (built-in defaults + user opt-ins).
|
|
820
|
+
|
|
821
|
+
Some tools are *documented* to return large verbatim payloads (source
|
|
822
|
+
fetchers, doc retrievers). Compressing those to a metadata preview defeats
|
|
823
|
+
the reason they were called, so they are exempt from MCP output replacement
|
|
824
|
+
(follow-up to the exempt-tools expansion).
|
|
825
|
+
|
|
826
|
+
The list is the union of ``_DEFAULT_EXEMPT_PATTERNS`` (well-known code/doc
|
|
827
|
+
MCPs, on by default) and the user's ``TOKEN_OPTIMIZER_ARCHIVE_EXEMPT_TOOLS``
|
|
828
|
+
— a comma-separated list of fnmatch globs matched against the full tool name,
|
|
829
|
+
e.g. ``mcp__mytool__*,*my_repo_file``. The user value is ADDITIVE, so opting
|
|
830
|
+
another tool out is a one-line change. Set
|
|
831
|
+
``TOKEN_OPTIMIZER_ARCHIVE_EXEMPT_DEFAULTS=off`` to drop the built-ins.
|
|
832
|
+
Resolution mirrors _resolve_mcp_cap_tokens: process env first, then the
|
|
833
|
+
settings.json "env" block. Never raises.
|
|
834
|
+
"""
|
|
835
|
+
global _EXEMPT_PATTERNS_CACHE
|
|
836
|
+
if _EXEMPT_PATTERNS_CACHE is not _EXEMPT_PATTERNS_UNSET:
|
|
837
|
+
return _EXEMPT_PATTERNS_CACHE
|
|
838
|
+
|
|
839
|
+
raw = os.environ.get("TOKEN_OPTIMIZER_ARCHIVE_EXEMPT_TOOLS", "").strip()
|
|
840
|
+
defaults_flag = os.environ.get("TOKEN_OPTIMIZER_ARCHIVE_EXEMPT_DEFAULTS", "").strip()
|
|
841
|
+
if not raw or not defaults_flag:
|
|
842
|
+
# settings.json "env" block — for out-of-process callers.
|
|
843
|
+
if not raw:
|
|
844
|
+
raw = settings_env_value("TOKEN_OPTIMIZER_ARCHIVE_EXEMPT_TOOLS")
|
|
845
|
+
if not defaults_flag:
|
|
846
|
+
defaults_flag = settings_env_value("TOKEN_OPTIMIZER_ARCHIVE_EXEMPT_DEFAULTS")
|
|
847
|
+
|
|
848
|
+
user_patterns = tuple(p.strip() for p in raw.split(",") if p.strip())
|
|
849
|
+
base = () if defaults_flag.lower() in ("off", "false", "0", "none") else _DEFAULT_EXEMPT_PATTERNS
|
|
850
|
+
# Union, preserving order, defaults first.
|
|
851
|
+
seen: dict[str, None] = {}
|
|
852
|
+
for p in (*base, *user_patterns):
|
|
853
|
+
seen.setdefault(p, None)
|
|
854
|
+
patterns = tuple(seen)
|
|
855
|
+
_EXEMPT_PATTERNS_CACHE = patterns
|
|
856
|
+
return patterns
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
def _is_archive_exempt(tool_name: str) -> bool:
|
|
860
|
+
"""True when tool_name matches any configured allowlist glob."""
|
|
861
|
+
if not tool_name:
|
|
862
|
+
return False
|
|
863
|
+
return any(fnmatch.fnmatch(tool_name, pat) for pat in _resolve_exempt_tool_patterns())
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
def _maybe_log_mcp_cap_savings(tool_name: str, original_char_count: int, session_id: str | None) -> None:
|
|
867
|
+
"""Log estimated native MCP-cap savings independently of archive writes."""
|
|
868
|
+
if "__" not in tool_name:
|
|
869
|
+
return
|
|
870
|
+
cap_tokens = _resolve_mcp_cap_tokens()
|
|
871
|
+
if cap_tokens is None:
|
|
872
|
+
return
|
|
873
|
+
cap_chars = cap_tokens * CHARS_PER_TOKEN
|
|
874
|
+
cap_threshold = int(cap_chars * _MCP_CAP_PROXIMITY_PCT)
|
|
875
|
+
if original_char_count < cap_threshold:
|
|
876
|
+
return
|
|
877
|
+
estimated_saved = max(0, int(cap_tokens * _MCP_CAP_ESTIMATED_RATIO))
|
|
878
|
+
if estimated_saved <= 0:
|
|
879
|
+
return
|
|
880
|
+
_log_savings_event(
|
|
881
|
+
"mcp_cap",
|
|
882
|
+
estimated_saved,
|
|
883
|
+
session_id=session_id,
|
|
884
|
+
detail=(
|
|
885
|
+
f"estimated: {tool_name} result at cap "
|
|
886
|
+
f"({original_char_count:,} chars >= "
|
|
887
|
+
f"{cap_threshold:,} threshold, "
|
|
888
|
+
f"cap={cap_tokens:,} tok, "
|
|
889
|
+
f"assumed saved ~{estimated_saved:,} tok [estimated])"
|
|
890
|
+
),
|
|
891
|
+
)
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
# Content-block types that carry media rather than text. The model needs these
|
|
895
|
+
# verbatim: an archive pointer in place of a screenshot leaves it blind, and
|
|
896
|
+
# counting base64 chars as tokens logs savings that never happened (images are
|
|
897
|
+
# billed by pixel dimensions, not encoded length).
|
|
898
|
+
_MEDIA_BLOCK_TYPES = frozenset({"image", "document", "audio", "video"})
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
def _is_media_block(block) -> bool:
|
|
902
|
+
if not isinstance(block, dict):
|
|
903
|
+
return False
|
|
904
|
+
if block.get("type") in _MEDIA_BLOCK_TYPES:
|
|
905
|
+
return True
|
|
906
|
+
# MCP embedded resource carrying binary: {"type": "resource", "resource": {"blob": ...}}
|
|
907
|
+
res = block.get("resource")
|
|
908
|
+
return isinstance(res, dict) and isinstance(res.get("blob"), str) and bool(res.get("mimeType"))
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
def _contains_media_block(value) -> bool:
|
|
912
|
+
"""True when a raw tool_response holds an image/document/audio block.
|
|
913
|
+
|
|
914
|
+
Only looks where hosts put content blocks: the response itself, a top-level
|
|
915
|
+
list of blocks, or a "content" list (the MCP result shape). It does not
|
|
916
|
+
recurse into arbitrary data, so a Notion or Slack payload that merely
|
|
917
|
+
describes an image node still archives normally. Never raises.
|
|
918
|
+
"""
|
|
919
|
+
try:
|
|
920
|
+
candidates = []
|
|
921
|
+
if isinstance(value, dict):
|
|
922
|
+
candidates.append(value)
|
|
923
|
+
if isinstance(value.get("content"), list):
|
|
924
|
+
candidates.extend(value["content"])
|
|
925
|
+
elif isinstance(value, list):
|
|
926
|
+
for item in value:
|
|
927
|
+
candidates.append(item)
|
|
928
|
+
if isinstance(item, dict) and isinstance(item.get("content"), list):
|
|
929
|
+
candidates.extend(item["content"])
|
|
930
|
+
return any(_is_media_block(c) for c in candidates)
|
|
931
|
+
except Exception:
|
|
932
|
+
return False
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
def _tool_response_to_text(value) -> str:
|
|
936
|
+
"""Normalize Claude PostToolUse response shapes into archiveable text."""
|
|
937
|
+
if value is None:
|
|
938
|
+
return ""
|
|
939
|
+
if isinstance(value, str):
|
|
940
|
+
return value
|
|
941
|
+
if isinstance(value, (int, float, bool)):
|
|
942
|
+
return str(value)
|
|
943
|
+
if isinstance(value, list):
|
|
944
|
+
parts = [_tool_response_to_text(item) for item in value]
|
|
945
|
+
return "\n".join(part for part in parts if part)
|
|
946
|
+
if isinstance(value, dict):
|
|
947
|
+
parts: list[str] = []
|
|
948
|
+
for key in ("stdout", "stderr", "error", "text", "output", "result", "content"):
|
|
949
|
+
if key not in value:
|
|
950
|
+
continue
|
|
951
|
+
text = _tool_response_to_text(value.get(key))
|
|
952
|
+
if not text:
|
|
953
|
+
continue
|
|
954
|
+
if key in ("stdout", "stderr", "error"):
|
|
955
|
+
parts.append(f"{key}:\n{text}")
|
|
956
|
+
else:
|
|
957
|
+
parts.append(text)
|
|
958
|
+
if parts:
|
|
959
|
+
return "\n\n".join(parts)
|
|
960
|
+
try:
|
|
961
|
+
return json.dumps(value, ensure_ascii=False, sort_keys=True)
|
|
962
|
+
except (TypeError, ValueError):
|
|
963
|
+
return str(value)
|
|
964
|
+
return str(value)
|
|
965
|
+
|
|
966
|
+
|
|
967
|
+
def _ensure_private_archive_dir(archive_dir: Path) -> bool:
|
|
968
|
+
try:
|
|
969
|
+
if archive_dir.exists():
|
|
970
|
+
st = archive_dir.lstat()
|
|
971
|
+
if archive_dir.is_symlink() or not archive_dir.is_dir():
|
|
972
|
+
return False
|
|
973
|
+
if getattr(st, "st_nlink", 1) < 1:
|
|
974
|
+
return False
|
|
975
|
+
archive_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
976
|
+
os.chmod(str(archive_dir), 0o700)
|
|
977
|
+
return True
|
|
978
|
+
except OSError:
|
|
979
|
+
return False
|
|
980
|
+
|
|
981
|
+
|
|
982
|
+
def _atomic_write_json(path: Path, payload: dict) -> None:
|
|
983
|
+
if path.exists() and (path.is_symlink() or path.lstat().st_nlink > 1):
|
|
984
|
+
raise OSError("unsafe archive entry path")
|
|
985
|
+
fd, tmp_path = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=str(path.parent), text=True)
|
|
986
|
+
try:
|
|
987
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
988
|
+
json.dump(payload, f)
|
|
989
|
+
os.chmod(tmp_path, 0o600)
|
|
990
|
+
os.replace(tmp_path, path)
|
|
991
|
+
os.chmod(path, 0o600)
|
|
992
|
+
except Exception:
|
|
993
|
+
try:
|
|
994
|
+
os.unlink(tmp_path)
|
|
995
|
+
except OSError:
|
|
996
|
+
pass
|
|
997
|
+
raise
|
|
998
|
+
|
|
999
|
+
|
|
1000
|
+
def _append_manifest_line(path: Path, payload: dict) -> None:
|
|
1001
|
+
if path.exists() and (path.is_symlink() or path.lstat().st_nlink > 1):
|
|
1002
|
+
raise OSError("unsafe archive manifest path")
|
|
1003
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
|
|
1004
|
+
if hasattr(os, "O_NOFOLLOW"):
|
|
1005
|
+
flags |= os.O_NOFOLLOW
|
|
1006
|
+
fd = os.open(str(path), flags, 0o600)
|
|
1007
|
+
try:
|
|
1008
|
+
with os.fdopen(fd, "a", encoding="utf-8") as f:
|
|
1009
|
+
f.write(json.dumps(payload) + "\n")
|
|
1010
|
+
os.chmod(path, 0o600)
|
|
1011
|
+
except Exception:
|
|
1012
|
+
raise
|
|
1013
|
+
|
|
1014
|
+
|
|
1015
|
+
# ---------------------------------------------------------------------------
|
|
1016
|
+
# Progressive-disclosure spine: reusable archive-original + pointer.
|
|
1017
|
+
#
|
|
1018
|
+
# Lets non-MCP / PreToolUse compressors (first-read code, bash, structured
|
|
1019
|
+
# data) persist the FULL original and hand the model a retrievable pointer,
|
|
1020
|
+
# exactly like the MCP eviction path. Cache-safety is structural: these run in
|
|
1021
|
+
# arrival hooks (PreToolUse / PostToolUse) BEFORE the content's first API send,
|
|
1022
|
+
# so they never mutate already-cached context. expand_archived locates an entry
|
|
1023
|
+
# by filename stem, so a derived key retrieves identically to a tool_use_id --
|
|
1024
|
+
# no expand change is needed.
|
|
1025
|
+
# ---------------------------------------------------------------------------
|
|
1026
|
+
|
|
1027
|
+
def derive_archive_key(session_id: str | None, file_path: str, mtime_ns: int) -> str:
|
|
1028
|
+
"""Stable archive key for PreToolUse paths that have no tool_use_id.
|
|
1029
|
+
|
|
1030
|
+
sha256(session_id + file_path + mtime_ns)[:16]. Hex output satisfies
|
|
1031
|
+
expand_archived's [a-zA-Z0-9_-]+ key validation.
|
|
1032
|
+
"""
|
|
1033
|
+
raw = f"{session_id or ''}|{file_path}|{mtime_ns}".encode("utf-8", errors="replace")
|
|
1034
|
+
return hashlib.sha256(raw).hexdigest()[:16]
|
|
1035
|
+
|
|
1036
|
+
|
|
1037
|
+
def _expand_instruction(key: str, tool_name: str | None = None) -> str:
|
|
1038
|
+
"""The actionable retrieval line for an archive footer.
|
|
1039
|
+
|
|
1040
|
+
The prior footer said only "Retrieve with: expand <id>", but `expand` is a
|
|
1041
|
+
measure.py subcommand, not a callable tool — the model had no way to act on it
|
|
1042
|
+
and re-fetched instead. Emit the exact runnable Bash command (shared with the
|
|
1043
|
+
re-fetch guard via expand_command, so the two can never diverge) plus an
|
|
1044
|
+
explicit anti-re-fetch instruction so the correct path is unambiguous.
|
|
1045
|
+
"""
|
|
1046
|
+
if tool_name and is_live_state_tool(tool_name):
|
|
1047
|
+
# A browser/screen read is a snapshot; calling again is how you get the
|
|
1048
|
+
# CURRENT state, so don't tell the model not to.
|
|
1049
|
+
return (
|
|
1050
|
+
"This is a snapshot of that moment; call the tool again for current state. "
|
|
1051
|
+
f"To re-read this snapshot, run in Bash:\n {expand_command(key)}"
|
|
1052
|
+
)
|
|
1053
|
+
dont = f"Do NOT call {tool_name} again" if tool_name else "Do NOT re-run the original tool"
|
|
1054
|
+
return (
|
|
1055
|
+
f"{dont} to get this data — read the saved copy by running this in Bash:\n"
|
|
1056
|
+
f" {expand_command(key)}"
|
|
1057
|
+
)
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
def archive_entry_exists(session_id: str | None, key: str) -> bool:
|
|
1061
|
+
"""True when the archive entry file for ``key`` actually exists on disk.
|
|
1062
|
+
|
|
1063
|
+
Reusable by all pointer producers (archive_result, read_cache, bash_compress)
|
|
1064
|
+
so they can re-check the entry survived a post-write retention prune before
|
|
1065
|
+
emitting a pointer that would send the model to a missing file.
|
|
1066
|
+
Never raises.
|
|
1067
|
+
"""
|
|
1068
|
+
try:
|
|
1069
|
+
if not key:
|
|
1070
|
+
return False
|
|
1071
|
+
entry_path = _archive_dir_for_session(session_id or "unknown") / f"{key}.json"
|
|
1072
|
+
return entry_path.is_file() and not entry_path.is_symlink()
|
|
1073
|
+
except Exception:
|
|
1074
|
+
return False
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def build_archive_pointer(preview: str, original_chars: int, key: str) -> str:
|
|
1078
|
+
"""Standard progressive-disclosure pointer appended after a compressed preview."""
|
|
1079
|
+
return (
|
|
1080
|
+
f"{preview}\n\n"
|
|
1081
|
+
f"[Full result archived ({original_chars:,} chars) — saved to disk, not lost.\n"
|
|
1082
|
+
# The closing bracket sits on its own line so a line-copy of the
|
|
1083
|
+
# command never picks it up (the stale "expand <id>]" copy failed).
|
|
1084
|
+
f"{_expand_instruction(key)}\n]"
|
|
1085
|
+
)
|
|
1086
|
+
|
|
1087
|
+
|
|
1088
|
+
def archive_original(content: str, session_id: str | None, key: str,
|
|
1089
|
+
tool_name: str, quiet: bool = True,
|
|
1090
|
+
file_path: str | None = None,
|
|
1091
|
+
language: str | None = None) -> str | None:
|
|
1092
|
+
"""Persist a full original (credential-redacted) under `key`; return the key.
|
|
1093
|
+
|
|
1094
|
+
Reusable by non-MCP / PreToolUse compressors so nothing is ever lost. Mirrors
|
|
1095
|
+
the MCP archive path (same dir layout + manifest) so expand_archived retrieves
|
|
1096
|
+
it unchanged. Fail-open: returns None on any failure (caller serves raw).
|
|
1097
|
+
|
|
1098
|
+
`file_path`/`language`: when the caller knows which file is being
|
|
1099
|
+
degraded (the first-read skeleton path does), record it so a degraded read is
|
|
1100
|
+
self-identifiable from the archive without transcript archaeology. Additive
|
|
1101
|
+
and always present (null when unknown) so the record schema stays uniform.
|
|
1102
|
+
"""
|
|
1103
|
+
try:
|
|
1104
|
+
if not key or not re.match(r"^[a-zA-Z0-9_-]+$", key):
|
|
1105
|
+
return None
|
|
1106
|
+
archive_dir = _archive_dir_for_session(session_id or "unknown")
|
|
1107
|
+
if not _ensure_private_archive_dir(archive_dir):
|
|
1108
|
+
return None
|
|
1109
|
+
session_lock = LeaseLock(
|
|
1110
|
+
_session_lock_path(archive_dir.parent, session_id or "unknown"),
|
|
1111
|
+
acquire_timeout=0.075,
|
|
1112
|
+
cohort_throttle=False,
|
|
1113
|
+
)
|
|
1114
|
+
if not session_lock.acquire():
|
|
1115
|
+
return None
|
|
1116
|
+
try:
|
|
1117
|
+
safe_response = _redact_credentials(content)
|
|
1118
|
+
# Redact the path too — a path can embed a token/secret (e.g. a URL-ish
|
|
1119
|
+
# segment). Stored uniformly: null when the caller didn't supply one.
|
|
1120
|
+
safe_path = _redact_credentials(file_path) if file_path else None
|
|
1121
|
+
meta = {
|
|
1122
|
+
"tool_name": tool_name,
|
|
1123
|
+
"tool_use_id": key,
|
|
1124
|
+
ARGS_HASH_KEY: None, # non-MCP progressive-disclosure path; guard skips these.
|
|
1125
|
+
"file_path": safe_path,
|
|
1126
|
+
"language": language,
|
|
1127
|
+
"chars": len(safe_response),
|
|
1128
|
+
"original_chars": len(content),
|
|
1129
|
+
"tokens_est": int(len(safe_response) / CODE_CHARS_PER_TOKEN),
|
|
1130
|
+
"truncated": False,
|
|
1131
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
1132
|
+
"archived_from": "compress_with_preservation",
|
|
1133
|
+
}
|
|
1134
|
+
_mark_session_active(archive_dir)
|
|
1135
|
+
entry_path = archive_dir / f"{key}.json"
|
|
1136
|
+
_atomic_write_json(entry_path, {**meta, "response": safe_response})
|
|
1137
|
+
_append_manifest_line(archive_dir / "manifest.jsonl", meta)
|
|
1138
|
+
return key
|
|
1139
|
+
finally:
|
|
1140
|
+
session_lock.release()
|
|
1141
|
+
except Exception:
|
|
1142
|
+
if not quiet:
|
|
1143
|
+
print(f"[Tool Archive] archive_original failed for {tool_name}; serving raw.", file=sys.stderr)
|
|
1144
|
+
return None
|
|
1145
|
+
|
|
1146
|
+
|
|
1147
|
+
def _log_agent_result_opportunity(tool_response: str, session_id: str | None) -> None:
|
|
1148
|
+
"""Record a measure-only opportunity event for a large Agent/Task result.
|
|
1149
|
+
|
|
1150
|
+
The would-be saving is the head+tail+pointer treatment's delta. tier =
|
|
1151
|
+
opportunity so it NEVER reaches the realized savings headline (agent_result_
|
|
1152
|
+
skeleton is not a _V5_COMPRESSION_CATEGORIES feature). Uses the hot-path
|
|
1153
|
+
compression_log writer (no measure.py import). Fail-open.
|
|
1154
|
+
"""
|
|
1155
|
+
head = tool_response[:_AGENT_RESULT_HEAD_CHARS]
|
|
1156
|
+
tail = (tool_response[-_AGENT_RESULT_TAIL_CHARS:]
|
|
1157
|
+
if len(tool_response) > _AGENT_RESULT_TAIL_CHARS else "")
|
|
1158
|
+
orig_tokens = int(len(tool_response) / CODE_CHARS_PER_TOKEN)
|
|
1159
|
+
would_be_tokens = int(len(head + tail) / CODE_CHARS_PER_TOKEN)
|
|
1160
|
+
if orig_tokens <= 0 or would_be_tokens >= orig_tokens:
|
|
1161
|
+
return
|
|
1162
|
+
try:
|
|
1163
|
+
from compression_log import log_compression_event
|
|
1164
|
+
log_compression_event(
|
|
1165
|
+
feature=_FEATURE_AGENT_RESULT,
|
|
1166
|
+
session_id=session_id,
|
|
1167
|
+
command_pattern="agent",
|
|
1168
|
+
tier="opportunity",
|
|
1169
|
+
verified=False,
|
|
1170
|
+
quality_preserved=False, # 39.1% harm proxy: a skeleton WOULD elide value
|
|
1171
|
+
detail=f"would-be head+tail; harm_proxy={_AGENT_RESULT_HARM_PCT}%",
|
|
1172
|
+
original_tokens=orig_tokens,
|
|
1173
|
+
compressed_tokens=would_be_tokens,
|
|
1174
|
+
)
|
|
1175
|
+
except Exception:
|
|
1176
|
+
pass
|
|
1177
|
+
|
|
1178
|
+
|
|
1179
|
+
# ---------------------------------------------------------------------------
|
|
1180
|
+
# Structure-aware MCP output compression
|
|
1181
|
+
# ---------------------------------------------------------------------------
|
|
1182
|
+
|
|
1183
|
+
# Bounds for the synchronous PostToolUse hot path. splitlines() / sort over a
|
|
1184
|
+
# multi-MB MCP payload measured ~865ms (perf regression on a 5MB / 290k-line path
|
|
1185
|
+
# listing); these caps keep classification + preview under the 500ms hook budget.
|
|
1186
|
+
# The FULL result is archived regardless, so `expand` loses nothing.
|
|
1187
|
+
_DETECT_HEAD_CHARS = 16_384 # classify line type from the head slice, not the whole payload
|
|
1188
|
+
_PATHS_SAMPLE_LINES = 10_000 # lines sampled for the path preview
|
|
1189
|
+
|
|
1190
|
+
|
|
1191
|
+
def _is_extend_char(ch: str) -> bool:
|
|
1192
|
+
"""True when ``ch`` continues the grapheme cluster of the char before it:
|
|
1193
|
+
combining marks, variation selectors, emoji modifiers, tag chars."""
|
|
1194
|
+
if not ch:
|
|
1195
|
+
return False
|
|
1196
|
+
if unicodedata.combining(ch) or unicodedata.category(ch) in ("Mn", "Mc", "Me"):
|
|
1197
|
+
return True
|
|
1198
|
+
cp = ord(ch)
|
|
1199
|
+
return (
|
|
1200
|
+
0xFE00 <= cp <= 0xFE0F # variation selectors
|
|
1201
|
+
or 0xE0100 <= cp <= 0xE01EF # supplementary variation selectors
|
|
1202
|
+
or 0x1F3FB <= cp <= 0x1F3FF # emoji modifiers (skin tone)
|
|
1203
|
+
or 0xE0020 <= cp <= 0xE007F # tag chars (subdivision flags)
|
|
1204
|
+
)
|
|
1205
|
+
|
|
1206
|
+
|
|
1207
|
+
def _is_regional_indicator(ch: str) -> bool:
|
|
1208
|
+
return bool(ch) and 0x1F1E6 <= ord(ch) <= 0x1F1FF
|
|
1209
|
+
|
|
1210
|
+
|
|
1211
|
+
def _breaks_cluster(text: str, end: int) -> bool:
|
|
1212
|
+
"""True when cutting ``text`` at ``end`` lands inside a grapheme cluster.
|
|
1213
|
+
|
|
1214
|
+
Covers the common invisible-joiner cases without a dependency: a ZWJ next
|
|
1215
|
+
to the cut (the sequence is one cluster — backing off removes the whole
|
|
1216
|
+
partial emoji rather than rendering a different one), an extend char right
|
|
1217
|
+
after the cut (combining mark, modifier, selector, tag), and an unpaired
|
|
1218
|
+
regional indicator at the tail (half a flag).
|
|
1219
|
+
"""
|
|
1220
|
+
prev = text[end - 1]
|
|
1221
|
+
nxt = text[end] if end < len(text) else ""
|
|
1222
|
+
if prev == "\u200d" or nxt == "\u200d":
|
|
1223
|
+
return True
|
|
1224
|
+
if _is_extend_char(nxt):
|
|
1225
|
+
return True
|
|
1226
|
+
if _is_regional_indicator(prev):
|
|
1227
|
+
run = 0
|
|
1228
|
+
i = end - 1
|
|
1229
|
+
while i >= 0 and _is_regional_indicator(text[i]):
|
|
1230
|
+
run += 1
|
|
1231
|
+
i -= 1
|
|
1232
|
+
if run % 2 == 1:
|
|
1233
|
+
return True
|
|
1234
|
+
return False
|
|
1235
|
+
|
|
1236
|
+
|
|
1237
|
+
def _preview_slice(text: str, limit: int = _ARCHIVE_PREVIEW_SIZE) -> str:
|
|
1238
|
+
"""``text[:limit]`` backed off to a grapheme-cluster boundary.
|
|
1239
|
+
|
|
1240
|
+
A raw codepoint slice can end mid-cluster — a ZWJ sequence cut in two
|
|
1241
|
+
renders a DIFFERENT emoji than the archived one, a combining mark left at
|
|
1242
|
+
the tail attaches to the footer, an odd regional indicator shows half a
|
|
1243
|
+
flag. Walk the cut back while it would split a cluster; a text made of one
|
|
1244
|
+
giant cluster degrades to an empty preview (the pointer still recovers).
|
|
1245
|
+
"""
|
|
1246
|
+
end = min(limit, len(text))
|
|
1247
|
+
while end > 0 and _breaks_cluster(text, end):
|
|
1248
|
+
end -= 1
|
|
1249
|
+
return text[:end]
|
|
1250
|
+
|
|
1251
|
+
|
|
1252
|
+
def _detect_output_type(text: str) -> str:
|
|
1253
|
+
stripped = text.strip()
|
|
1254
|
+
if stripped.startswith("{") or stripped.startswith("["):
|
|
1255
|
+
try:
|
|
1256
|
+
json.loads(stripped[:100_000])
|
|
1257
|
+
return "json"
|
|
1258
|
+
except (json.JSONDecodeError, RecursionError):
|
|
1259
|
+
pass
|
|
1260
|
+
# Bound the scan: splitlines() over a multi-MB payload is a hot-path latency
|
|
1261
|
+
# trap; the first lines in the head slice are enough to classify.
|
|
1262
|
+
lines = stripped[:_DETECT_HEAD_CHARS].splitlines()[:50]
|
|
1263
|
+
if len(lines) > 5:
|
|
1264
|
+
path_like = sum(1 for ln in lines if "/" in ln or "\\" in ln)
|
|
1265
|
+
if path_like > len(lines) * 0.6:
|
|
1266
|
+
return "paths"
|
|
1267
|
+
if len(lines) > 5:
|
|
1268
|
+
sep_count = sum(1 for ln in lines if set(ln.strip()) <= set("-=| +") and ln.strip())
|
|
1269
|
+
if sep_count >= 1:
|
|
1270
|
+
return "table"
|
|
1271
|
+
return "text"
|
|
1272
|
+
|
|
1273
|
+
|
|
1274
|
+
def _compress_mcp_preview(text: str, output_type: str) -> str:
|
|
1275
|
+
if output_type == "json":
|
|
1276
|
+
return _compress_mcp_json(text)
|
|
1277
|
+
if output_type == "paths":
|
|
1278
|
+
return _compress_mcp_paths(text)
|
|
1279
|
+
if output_type == "table":
|
|
1280
|
+
return _compress_mcp_table(text)
|
|
1281
|
+
return _preview_slice(text)
|
|
1282
|
+
|
|
1283
|
+
|
|
1284
|
+
# Value-preserving columnar compression thresholds.
|
|
1285
|
+
_TABULAR_MIN_ROWS = 3 # too few rows to be worth a schema header
|
|
1286
|
+
_TABULAR_MAX_COLS = 40 # wider than this is not really tabular
|
|
1287
|
+
_TABULAR_CELL_CAP = 100 # per-cell char cap (keeps values, bounds width)
|
|
1288
|
+
_TABULAR_TOTAL_CAP = 8192 # if the columnar form exceeds this, evict instead
|
|
1289
|
+
_TABULAR_MIN_REDUCTION = 0.40 # must be >=40% smaller than original to engage
|
|
1290
|
+
|
|
1291
|
+
|
|
1292
|
+
def _compress_mcp_json_tabular(data, original_text: str):
|
|
1293
|
+
"""Value-preserving columnar compression for homogeneous arrays-of-dicts.
|
|
1294
|
+
|
|
1295
|
+
Strips the repeated per-row schema (emit keys once) while KEEPING values, so
|
|
1296
|
+
the model can still read any cell inline instead of paying a full re-expand.
|
|
1297
|
+
Returns the columnar string, or None to fall back to the eviction preview
|
|
1298
|
+
when the data isn't tabular enough or the result isn't a clear win.
|
|
1299
|
+
"""
|
|
1300
|
+
try:
|
|
1301
|
+
if not isinstance(data, list) or len(data) < _TABULAR_MIN_ROWS:
|
|
1302
|
+
return None
|
|
1303
|
+
dict_rows = [r for r in data if isinstance(r, dict)]
|
|
1304
|
+
if len(dict_rows) < max(_TABULAR_MIN_ROWS, int(len(data) * 0.8)):
|
|
1305
|
+
return None # not predominantly homogeneous dicts
|
|
1306
|
+
# Ordered union of keys (first-seen order), bounded width.
|
|
1307
|
+
cols: list[str] = []
|
|
1308
|
+
seen = set()
|
|
1309
|
+
for row in dict_rows:
|
|
1310
|
+
for k in row.keys():
|
|
1311
|
+
if k not in seen:
|
|
1312
|
+
seen.add(k)
|
|
1313
|
+
cols.append(str(k))
|
|
1314
|
+
if not cols or len(cols) > _TABULAR_MAX_COLS:
|
|
1315
|
+
return None
|
|
1316
|
+
|
|
1317
|
+
def _cell(v) -> str:
|
|
1318
|
+
s = v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)
|
|
1319
|
+
s = s.replace("\n", " ").replace("\t", " ")
|
|
1320
|
+
return s[:_TABULAR_CELL_CAP] + ("…" if len(s) > _TABULAR_CELL_CAP else "")
|
|
1321
|
+
|
|
1322
|
+
lines = [
|
|
1323
|
+
f"JSON array ({len(data)} items), columnar (schema-stripped, values preserved):",
|
|
1324
|
+
"cols: " + ", ".join(cols),
|
|
1325
|
+
]
|
|
1326
|
+
for row in data:
|
|
1327
|
+
if isinstance(row, dict):
|
|
1328
|
+
lines.append("- " + " | ".join(_cell(row.get(c, "")) for c in cols))
|
|
1329
|
+
else:
|
|
1330
|
+
lines.append("- " + _cell(row))
|
|
1331
|
+
result = "\n".join(lines)
|
|
1332
|
+
|
|
1333
|
+
# Only engage when it's a clear win and stays within the inline budget.
|
|
1334
|
+
if len(result) > _TABULAR_TOTAL_CAP:
|
|
1335
|
+
return None
|
|
1336
|
+
if len(result) > len(original_text) * (1.0 - _TABULAR_MIN_REDUCTION):
|
|
1337
|
+
return None
|
|
1338
|
+
return result
|
|
1339
|
+
except Exception:
|
|
1340
|
+
return None
|
|
1341
|
+
|
|
1342
|
+
|
|
1343
|
+
def _compress_mcp_json(text: str) -> str:
|
|
1344
|
+
try:
|
|
1345
|
+
data = json.loads(text[:500_000])
|
|
1346
|
+
except (json.JSONDecodeError, RecursionError):
|
|
1347
|
+
return _preview_slice(text)
|
|
1348
|
+
|
|
1349
|
+
# U3: value-preserving columnar path for homogeneous arrays-of-dicts.
|
|
1350
|
+
# Keeps values usable inline so the model rarely needs a full re-expand;
|
|
1351
|
+
# falls through to the eviction preview below when it isn't a clear win.
|
|
1352
|
+
tabular = _compress_mcp_json_tabular(data, text)
|
|
1353
|
+
if tabular is not None:
|
|
1354
|
+
return tabular
|
|
1355
|
+
|
|
1356
|
+
parts: list[str] = []
|
|
1357
|
+
if isinstance(data, dict):
|
|
1358
|
+
parts.append(f"JSON object ({len(data)} keys):")
|
|
1359
|
+
for key in list(data.keys())[:15]:
|
|
1360
|
+
val = data[key]
|
|
1361
|
+
if isinstance(val, list):
|
|
1362
|
+
parts.append(f" {key}: [{len(val)} items]")
|
|
1363
|
+
elif isinstance(val, dict):
|
|
1364
|
+
subkeys = list(val.keys())[:5]
|
|
1365
|
+
suffix = "..." if len(val) > 5 else ""
|
|
1366
|
+
parts.append(f" {key}: {{{', '.join(subkeys)}{suffix}}}")
|
|
1367
|
+
elif isinstance(val, str) and len(val) > 80:
|
|
1368
|
+
parts.append(f' {key}: "{val[:77]}..."')
|
|
1369
|
+
else:
|
|
1370
|
+
parts.append(f" {key}: {json.dumps(val)[:80]}")
|
|
1371
|
+
if len(data) > 15:
|
|
1372
|
+
parts.append(f" ... ({len(data) - 15} more keys)")
|
|
1373
|
+
elif isinstance(data, list):
|
|
1374
|
+
parts.append(f"JSON array ({len(data)} items):")
|
|
1375
|
+
for item in data[:5]:
|
|
1376
|
+
if isinstance(item, dict):
|
|
1377
|
+
keys = list(item.keys())[:5]
|
|
1378
|
+
suffix = "..." if len(item) > 5 else ""
|
|
1379
|
+
parts.append(f" {{{', '.join(keys)}{suffix}}}")
|
|
1380
|
+
else:
|
|
1381
|
+
parts.append(f" {json.dumps(item)[:80]}")
|
|
1382
|
+
if len(data) > 5:
|
|
1383
|
+
parts.append(f" ... ({len(data) - 5} more items)")
|
|
1384
|
+
|
|
1385
|
+
result = "\n".join(parts)
|
|
1386
|
+
return _preview_slice(result) if len(result) > _ARCHIVE_PREVIEW_SIZE else result
|
|
1387
|
+
|
|
1388
|
+
|
|
1389
|
+
def _compress_mcp_paths(text: str) -> str:
|
|
1390
|
+
# Exact total via a single C-level scan (no full materialization), then tally
|
|
1391
|
+
# directories over a bounded SAMPLE of lines so a 290k-line listing can't stall
|
|
1392
|
+
# the synchronous hook. heapq.nlargest avoids sorting the whole dir dict.
|
|
1393
|
+
total_lines = text.count("\n") + 1
|
|
1394
|
+
dirs: dict[str, int] = {}
|
|
1395
|
+
sampled = 0
|
|
1396
|
+
for line in itertools.islice(io.StringIO(text), _PATHS_SAMPLE_LINES):
|
|
1397
|
+
sampled += 1
|
|
1398
|
+
stripped = line.strip()
|
|
1399
|
+
if "/" in stripped:
|
|
1400
|
+
dir_name = stripped.rsplit("/", 1)[0]
|
|
1401
|
+
dirs[dir_name] = dirs.get(dir_name, 0) + 1
|
|
1402
|
+
truncated = total_lines > sampled
|
|
1403
|
+
plus = "+" if truncated else ""
|
|
1404
|
+
|
|
1405
|
+
header = f"{total_lines} paths across {len(dirs)}{plus} directories"
|
|
1406
|
+
if truncated:
|
|
1407
|
+
header += f" (dirs sampled from first {sampled:,} lines)"
|
|
1408
|
+
parts = [header + ":"]
|
|
1409
|
+
for dir_name, count in heapq.nlargest(10, dirs.items(), key=lambda kv: kv[1]):
|
|
1410
|
+
parts.append(f" {dir_name}/ ({count}{plus} files)")
|
|
1411
|
+
if len(dirs) > 10:
|
|
1412
|
+
parts.append(f" ... ({len(dirs) - 10} more directories)")
|
|
1413
|
+
|
|
1414
|
+
result = "\n".join(parts)
|
|
1415
|
+
return _preview_slice(result) if len(result) > _ARCHIVE_PREVIEW_SIZE else result
|
|
1416
|
+
|
|
1417
|
+
|
|
1418
|
+
def _compress_mcp_table(text: str) -> str:
|
|
1419
|
+
lines = text.strip().splitlines()
|
|
1420
|
+
header = lines[:2]
|
|
1421
|
+
data = [ln for ln in lines[2:] if ln.strip()]
|
|
1422
|
+
result = header + data[:10]
|
|
1423
|
+
if len(data) > 10:
|
|
1424
|
+
result.append(f"... ({len(data) - 10} more rows, {len(data)} total)")
|
|
1425
|
+
return _preview_slice("\n".join(result))
|
|
1426
|
+
|
|
1427
|
+
|
|
1428
|
+
# ---------------------------------------------------------------------------
|
|
1429
|
+
# Main logic
|
|
1430
|
+
# ---------------------------------------------------------------------------
|
|
1431
|
+
|
|
1432
|
+
def archive_result(quiet: bool = False) -> None:
|
|
1433
|
+
"""PostToolUse hook handler: archive large tool results to disk.
|
|
1434
|
+
|
|
1435
|
+
Reads hook JSON from stdin. If tool_response >= _ARCHIVE_THRESHOLD chars,
|
|
1436
|
+
saves the full result to disk and (for MCP tools) outputs a trimmed
|
|
1437
|
+
replacement via stdout with updatedMCPToolOutput.
|
|
1438
|
+
|
|
1439
|
+
Logs a savings event only when MCP output is actually replaced. Native
|
|
1440
|
+
Bash/Read/etc. archives are durability metadata unless a PreToolUse path
|
|
1441
|
+
suppresses the original output before it enters context.
|
|
1442
|
+
"""
|
|
1443
|
+
hook_input = read_stdin_hook_input(_STDIN_MAX_BYTES)
|
|
1444
|
+
if not hook_input:
|
|
1445
|
+
return
|
|
1446
|
+
|
|
1447
|
+
tool_name = hook_input.get("tool_name", "")
|
|
1448
|
+
# Recovery must finish in one call: never archive or replace the original again.
|
|
1449
|
+
if is_recovery_output(tool_name, hook_input.get("tool_input", {})):
|
|
1450
|
+
return
|
|
1451
|
+
tool_use_id = hook_input.get("tool_use_id", "")
|
|
1452
|
+
raw_response = hook_input.get("tool_response", "")
|
|
1453
|
+
# Screenshots and other media pass through untouched: no archive, no
|
|
1454
|
+
# replacement, no fingerprint (so the re-fetch guard can never block a
|
|
1455
|
+
# fresh screenshot either).
|
|
1456
|
+
if _contains_media_block(raw_response):
|
|
1457
|
+
return
|
|
1458
|
+
tool_response = _tool_response_to_text(raw_response)
|
|
1459
|
+
session_id = hook_input.get("session_id", "")
|
|
1460
|
+
|
|
1461
|
+
if not tool_response:
|
|
1462
|
+
return
|
|
1463
|
+
|
|
1464
|
+
original_char_count = len(tool_response)
|
|
1465
|
+
_maybe_log_mcp_cap_savings(tool_name, original_char_count, session_id)
|
|
1466
|
+
|
|
1467
|
+
if original_char_count < _ARCHIVE_THRESHOLD:
|
|
1468
|
+
return
|
|
1469
|
+
|
|
1470
|
+
if not tool_use_id or not session_id:
|
|
1471
|
+
if not quiet:
|
|
1472
|
+
print("[Tool Archive] Missing tool_use_id or session_id, skipping.", file=sys.stderr)
|
|
1473
|
+
return
|
|
1474
|
+
|
|
1475
|
+
# Map tool_use_id to a filesystem-safe archive key. Unsafe characters (+,
|
|
1476
|
+
# space, /, ., ') used to skip archiving entirely — the full result passed
|
|
1477
|
+
# through uncompressed with no expand path and nothing on disk. A
|
|
1478
|
+
# deterministic digest keeps the archive, satisfies expand's own key
|
|
1479
|
+
# validation, and makes path traversal impossible by construction.
|
|
1480
|
+
raw_tool_use_id = tool_use_id
|
|
1481
|
+
tool_use_id = _safe_archive_key(tool_use_id)
|
|
1482
|
+
if tool_use_id != raw_tool_use_id and not quiet:
|
|
1483
|
+
print(f"[Tool Archive] tool_use_id {raw_tool_use_id!r} has unsafe "
|
|
1484
|
+
f"characters; archived under key {tool_use_id}", file=sys.stderr)
|
|
1485
|
+
|
|
1486
|
+
now = datetime.now(timezone.utc)
|
|
1487
|
+
truncated = original_char_count > _ARCHIVE_MAX_SIZE
|
|
1488
|
+
|
|
1489
|
+
if truncated:
|
|
1490
|
+
# Redact a window that reaches past the cap BEFORE cutting at it: a
|
|
1491
|
+
# secret straddling the cap is otherwise a prefix no pattern
|
|
1492
|
+
# recognises. If the redactor refuses, fall back to the plain cut; the
|
|
1493
|
+
# redaction below then raises the same way and skips the write.
|
|
1494
|
+
try:
|
|
1495
|
+
tool_response = _redact_credentials(
|
|
1496
|
+
tool_response[:_ARCHIVE_MAX_SIZE + _ARCHIVE_CAP_REDACT_OVERSHOOT]
|
|
1497
|
+
)[:_ARCHIVE_MAX_SIZE]
|
|
1498
|
+
except Exception:
|
|
1499
|
+
tool_response = tool_response[:_ARCHIVE_MAX_SIZE]
|
|
1500
|
+
tool_response += (
|
|
1501
|
+
f"\n\n[TRUNCATED at 5MB. Original size: {original_char_count} chars]"
|
|
1502
|
+
)
|
|
1503
|
+
|
|
1504
|
+
char_count = _ARCHIVE_MAX_SIZE if truncated else original_char_count
|
|
1505
|
+
token_est = int(char_count / CODE_CHARS_PER_TOKEN)
|
|
1506
|
+
|
|
1507
|
+
archive_dir = _archive_dir_for_session(session_id)
|
|
1508
|
+
if not _ensure_private_archive_dir(archive_dir):
|
|
1509
|
+
if not quiet:
|
|
1510
|
+
print(f"[Tool Archive] Unsafe archive directory for {tool_name}; leaving output unchanged.", file=sys.stderr)
|
|
1511
|
+
return
|
|
1512
|
+
|
|
1513
|
+
# Fingerprint the call (name + args) so the PreToolUse re-fetch guard can
|
|
1514
|
+
# detect an identical re-fetch of this result (self-healing).
|
|
1515
|
+
# ONLY for MCP tools whose result we actually replace with a preview. Exempt
|
|
1516
|
+
# allowlisted tools serve their full fresh result (see below), so the guard
|
|
1517
|
+
# must NOT block a re-call of them — record args_hash=None so it never matches.
|
|
1518
|
+
if "__" in tool_name and not _is_archive_exempt(tool_name) and not is_live_state_tool(tool_name):
|
|
1519
|
+
args_hash = tool_fingerprint(tool_name, hook_input.get("tool_input", {}))
|
|
1520
|
+
else:
|
|
1521
|
+
args_hash = None
|
|
1522
|
+
|
|
1523
|
+
meta = {
|
|
1524
|
+
"tool_name": tool_name,
|
|
1525
|
+
"tool_use_id": tool_use_id,
|
|
1526
|
+
ARGS_HASH_KEY: args_hash,
|
|
1527
|
+
"chars": char_count,
|
|
1528
|
+
"original_chars": original_char_count,
|
|
1529
|
+
"tokens_est": token_est,
|
|
1530
|
+
"truncated": truncated,
|
|
1531
|
+
"timestamp": now.isoformat(),
|
|
1532
|
+
"archived_from": "PostToolUse",
|
|
1533
|
+
}
|
|
1534
|
+
if raw_tool_use_id != tool_use_id:
|
|
1535
|
+
# Traceability: the key is the safe digest; keep the host's id readable
|
|
1536
|
+
# (redacted — it is caller text) for debugging joins.
|
|
1537
|
+
try:
|
|
1538
|
+
meta["tool_use_id_raw"] = _redact_credentials(raw_tool_use_id)
|
|
1539
|
+
except Exception:
|
|
1540
|
+
meta["tool_use_id_raw"] = "<untrusted>"
|
|
1541
|
+
|
|
1542
|
+
# Redact credential patterns before writing to disk.
|
|
1543
|
+
# Performed on the (possibly truncated) response so no plaintext secrets
|
|
1544
|
+
# ever reach the archive file, even transiently.
|
|
1545
|
+
try:
|
|
1546
|
+
safe_response = _redact_credentials(tool_response)
|
|
1547
|
+
except Exception as exc:
|
|
1548
|
+
# A configured-but-broken custom pattern file means redaction cannot
|
|
1549
|
+
# be trusted to cover the user's own secret shapes — fail CLOSED: skip
|
|
1550
|
+
# the archive write entirely and let the output pass through in memory.
|
|
1551
|
+
if RedactionConfigError is None or not isinstance(exc, RedactionConfigError):
|
|
1552
|
+
raise
|
|
1553
|
+
if not quiet:
|
|
1554
|
+
print(f"[Tool Archive] {exc}; result not archived.", file=sys.stderr)
|
|
1555
|
+
if pop_redaction_warning is not None:
|
|
1556
|
+
msg = pop_redaction_warning()
|
|
1557
|
+
if msg:
|
|
1558
|
+
# Sole hook output for this run: a single JSON object is a
|
|
1559
|
+
# valid envelope on every host.
|
|
1560
|
+
print(json.dumps({"systemMessage": msg}))
|
|
1561
|
+
return
|
|
1562
|
+
|
|
1563
|
+
session_lock = LeaseLock(
|
|
1564
|
+
_session_lock_path(archive_dir.parent, session_id),
|
|
1565
|
+
acquire_timeout=0.075,
|
|
1566
|
+
cohort_throttle=False,
|
|
1567
|
+
)
|
|
1568
|
+
if not session_lock.acquire():
|
|
1569
|
+
if not quiet:
|
|
1570
|
+
print(f"[Tool Archive] Archive busy for {tool_name}; leaving output unchanged.", file=sys.stderr)
|
|
1571
|
+
return
|
|
1572
|
+
try:
|
|
1573
|
+
_mark_session_active(archive_dir)
|
|
1574
|
+
entry_path = archive_dir / f"{tool_use_id}.json"
|
|
1575
|
+
_atomic_write_json(entry_path, {**meta, "response": safe_response})
|
|
1576
|
+
manifest_path = archive_dir / "manifest.jsonl"
|
|
1577
|
+
_append_manifest_line(manifest_path, meta)
|
|
1578
|
+
except OSError:
|
|
1579
|
+
if not quiet:
|
|
1580
|
+
print(f"[Tool Archive] Failed to archive {tool_name} result; leaving output unchanged.", file=sys.stderr)
|
|
1581
|
+
return
|
|
1582
|
+
finally:
|
|
1583
|
+
session_lock.release()
|
|
1584
|
+
|
|
1585
|
+
# The recursive cross-identity retention pass is throttled and separately
|
|
1586
|
+
# leased, so ordinary synchronous PostToolUse calls do only O(1) metadata
|
|
1587
|
+
# work instead of restatting the full archive tree.
|
|
1588
|
+
try:
|
|
1589
|
+
_cleanup_archives_if_due(session_id)
|
|
1590
|
+
except Exception:
|
|
1591
|
+
pass
|
|
1592
|
+
|
|
1593
|
+
# Re-check that the entry survived the retention pass. _cleanup_archives_if_due
|
|
1594
|
+
# runs AFTER the write and retention ceilings prune even protected sessions
|
|
1595
|
+
# (TOKEN_OPTIMIZER_ARCHIVE_RETENTION_MAX_BYTES=1 reproduces this), so the entry
|
|
1596
|
+
# we just wrote can be gone by the time we build the pointer. When it is, serve
|
|
1597
|
+
# the full result — a missing-entry pointer would strand the model with an
|
|
1598
|
+
# unrecoverable expand.
|
|
1599
|
+
replacement_emitted = False # set below only when the pointer is actually emitted
|
|
1600
|
+
entry_exists = archive_entry_exists(session_id, tool_use_id)
|
|
1601
|
+
if not entry_exists:
|
|
1602
|
+
if not quiet:
|
|
1603
|
+
print(
|
|
1604
|
+
f"[Tool Archive] Entry {tool_use_id} was pruned by retention pass "
|
|
1605
|
+
f"after write; serving full result instead of pointer.",
|
|
1606
|
+
file=sys.stderr,
|
|
1607
|
+
)
|
|
1608
|
+
# Fall through: the MCP replacement path below is skipped because
|
|
1609
|
+
# replacement_emitted stays False, so the hook returns without printing
|
|
1610
|
+
# an updatedMCPToolOutput — the original tool output reaches context.
|
|
1611
|
+
|
|
1612
|
+
if not quiet:
|
|
1613
|
+
print(f"[Tool Archive] Archived {tool_name} result ({char_count:,} chars, ~{token_est:,} tokens): {tool_use_id}", file=sys.stderr)
|
|
1614
|
+
|
|
1615
|
+
# WS4: measure-only opportunity event for large Agent/Task results. We do NOT
|
|
1616
|
+
# replace the output (the 39.1% harm proxy fails the gate), but we record the
|
|
1617
|
+
# would-be saving so coverage/dashboard surface the pool. The full result is
|
|
1618
|
+
# already archived above, so an `expand` path exists regardless. Fail-open.
|
|
1619
|
+
if tool_name in _AGENT_RESULT_TOOL_NAMES and original_char_count >= _AGENT_RESULT_MIN_CHARS:
|
|
1620
|
+
try:
|
|
1621
|
+
_log_agent_result_opportunity(tool_response, session_id)
|
|
1622
|
+
except Exception:
|
|
1623
|
+
pass
|
|
1624
|
+
|
|
1625
|
+
store = None
|
|
1626
|
+
try:
|
|
1627
|
+
tool_type = "mcp" if "__" in tool_name else tool_name.lower()
|
|
1628
|
+
tool_command = hook_input.get("tool_input", {}).get("command")
|
|
1629
|
+
command_or_path = tool_command or hook_input.get("tool_input", {}).get("file_path") or tool_name
|
|
1630
|
+
# Redact before persisting: a command/path can embed a token or secret, and
|
|
1631
|
+
# SessionStore is durable. Hash the REDACTED response so the identity hash
|
|
1632
|
+
# matches the redacted preview/archive rather than pre-redaction plaintext.
|
|
1633
|
+
safe_command_or_path = _redact_credentials(str(command_or_path), command=bool(tool_command))
|
|
1634
|
+
output_hash = hashlib.sha256(safe_response[:10000].encode("utf-8", errors="replace")).hexdigest()[:16]
|
|
1635
|
+
# U5: source lineage tags. When the tool input carried a file_path,
|
|
1636
|
+
# record it (redacted) plus the detected language and the archive
|
|
1637
|
+
# origin so the row is self-identifiable and joinable to the file
|
|
1638
|
+
# archive meta without transcript archaeology.
|
|
1639
|
+
raw_file_path = hook_input.get("tool_input", {}).get("file_path")
|
|
1640
|
+
lineage_source_file = _redact_credentials(str(raw_file_path)) if raw_file_path else None
|
|
1641
|
+
lineage_language = None
|
|
1642
|
+
if lineage_source_file:
|
|
1643
|
+
try:
|
|
1644
|
+
from structure_map import detect_structure_language
|
|
1645
|
+
lineage_language = detect_structure_language(lineage_source_file)
|
|
1646
|
+
except Exception:
|
|
1647
|
+
lineage_language = None
|
|
1648
|
+
store = SessionStore(session_id)
|
|
1649
|
+
store.insert_tool_output(
|
|
1650
|
+
tool_use_id=tool_use_id,
|
|
1651
|
+
tool_name=tool_name,
|
|
1652
|
+
tool_type=tool_type,
|
|
1653
|
+
command_or_path=safe_command_or_path[:500],
|
|
1654
|
+
output_hash=output_hash,
|
|
1655
|
+
output_chars=char_count,
|
|
1656
|
+
output_tokens_est=token_est,
|
|
1657
|
+
compressed_preview=_preview_slice(safe_response),
|
|
1658
|
+
source_file_path=lineage_source_file[:500] if lineage_source_file else None,
|
|
1659
|
+
language=lineage_language,
|
|
1660
|
+
archived_from="PostToolUse",
|
|
1661
|
+
output_text=safe_response[:50000],
|
|
1662
|
+
)
|
|
1663
|
+
except Exception:
|
|
1664
|
+
pass
|
|
1665
|
+
finally:
|
|
1666
|
+
if store is not None:
|
|
1667
|
+
store.close()
|
|
1668
|
+
|
|
1669
|
+
# Allowlisted tools are documented large-payload
|
|
1670
|
+
# fetchers: skip the replacement so the full verbatim result reaches
|
|
1671
|
+
# context. It's still archived to disk above, so `expand <id>` works —
|
|
1672
|
+
# same treatment as _AGENT_RESULT_TOOL_NAMES (archive, don't replace).
|
|
1673
|
+
if "__" in tool_name and _is_archive_exempt(tool_name):
|
|
1674
|
+
if not quiet:
|
|
1675
|
+
print(f"[Tool Archive] {tool_name} is allowlisted; serving full result (archived for expand).", file=sys.stderr)
|
|
1676
|
+
return
|
|
1677
|
+
|
|
1678
|
+
# For MCP tools (tool_name contains "__"): output replacement via stdout
|
|
1679
|
+
# No pressure gate here: the compressed replacement SAVES tokens.
|
|
1680
|
+
# Suppressing it would cause the full uncompressed response to flow through.
|
|
1681
|
+
#
|
|
1682
|
+
# Skip the replacement when the entry was pruned by the retention pass that
|
|
1683
|
+
# ran after write. Emitting a pointer to a missing entry strands the model.
|
|
1684
|
+
if not entry_exists:
|
|
1685
|
+
return
|
|
1686
|
+
|
|
1687
|
+
if "__" in tool_name:
|
|
1688
|
+
output_type = _detect_output_type(safe_response)
|
|
1689
|
+
preview = _compress_mcp_preview(safe_response, output_type)
|
|
1690
|
+
suffix = f" ({output_type})" if output_type != "text" else ""
|
|
1691
|
+
if original_char_count > _ARCHIVE_MAX_SIZE:
|
|
1692
|
+
replacement = preview + (
|
|
1693
|
+
f"\n\n[Full result archived ({original_char_count:,} chars{suffix}, truncated to 5MB) — "
|
|
1694
|
+
f"saved to disk, not lost.\n{_expand_instruction(tool_use_id, tool_name)}\n]"
|
|
1695
|
+
)
|
|
1696
|
+
else:
|
|
1697
|
+
replacement = preview + (
|
|
1698
|
+
f"\n\n[Full result archived ({char_count:,} chars{suffix}) — saved to disk, not lost.\n"
|
|
1699
|
+
f"{_expand_instruction(tool_use_id, tool_name)}\n]"
|
|
1700
|
+
)
|
|
1701
|
+
original_tokens = int(original_char_count / CODE_CHARS_PER_TOKEN)
|
|
1702
|
+
replacement_tokens = int(len(replacement) / CODE_CHARS_PER_TOKEN)
|
|
1703
|
+
tokens_saved = max(0, original_tokens - replacement_tokens)
|
|
1704
|
+
_log_savings_event(
|
|
1705
|
+
"tool_archive",
|
|
1706
|
+
tokens_saved,
|
|
1707
|
+
session_id=session_id,
|
|
1708
|
+
detail=(
|
|
1709
|
+
f"replaced {tool_name} "
|
|
1710
|
+
f"({original_char_count:,} chars -> {len(replacement):,} chars)"
|
|
1711
|
+
),
|
|
1712
|
+
)
|
|
1713
|
+
output = json.dumps({
|
|
1714
|
+
"hookSpecificOutput": {
|
|
1715
|
+
"hookEventName": "PostToolUse",
|
|
1716
|
+
"updatedMCPToolOutput": replacement,
|
|
1717
|
+
}
|
|
1718
|
+
})
|
|
1719
|
+
print(output)
|
|
1720
|
+
|
|
1721
|
+
|
|
1722
|
+
if __name__ == "__main__":
|
|
1723
|
+
args = sys.argv[1:]
|
|
1724
|
+
quiet = "--quiet" in args or "-q" in args
|
|
1725
|
+
archive_result(quiet=quiet)
|