tokensafe 3.1.5 → 4.0.0

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.
Files changed (44) hide show
  1. package/README.md +79 -58
  2. package/bin/tokensafe.js +25 -9
  3. package/hooks/claude_code_hook.py +7 -0
  4. package/hooks/pre_tool_use.py +24 -0
  5. package/hooks/session_start.py +8 -0
  6. package/package.json +3 -3
  7. package/plugin.json +1 -1
  8. package/rules/AGENTS.md +13 -7
  9. package/server.json +3 -3
  10. package/skills/token-optimizer/SKILL.md +7 -2
  11. package/skills/token-optimizer/references/cli-reference.md +11 -1
  12. package/skills/token-optimizer/references/mcp-tools.md +44 -2
  13. package/src/bench_scenarios.json +376 -0
  14. package/src/cache_normalizer.py +21 -0
  15. package/src/cli.py +425 -4
  16. package/src/command_sanitizer.py +2 -0
  17. package/src/compactor.py +1 -1
  18. package/src/competitors.py +179 -0
  19. package/src/environment_auditor.py +110 -1
  20. package/src/format_parsers/__init__.py +20 -0
  21. package/src/format_parsers/ansi.py +41 -0
  22. package/src/format_parsers/compiler_errors.py +159 -0
  23. package/src/format_parsers/docker_k8s.py +95 -0
  24. package/src/format_parsers/json_log.py +89 -0
  25. package/src/format_parsers/lockfiles.py +157 -0
  26. package/src/format_parsers/tabular.py +175 -0
  27. package/src/fts_index.py +296 -0
  28. package/src/graph_engine.py +395 -48
  29. package/src/image_downscale.py +228 -0
  30. package/src/installer.py +47 -1
  31. package/src/license_manager.py +103 -7
  32. package/src/loop_detector.py +5 -0
  33. package/src/mcp_config_manager.py +197 -0
  34. package/src/mcp_proxy.py +154 -0
  35. package/src/mcp_server.py +215 -1
  36. package/src/mistakes.py +203 -0
  37. package/src/result_ledger.py +8 -1
  38. package/src/scoped_search.py +32 -0
  39. package/src/stash.py +199 -0
  40. package/src/superseded.py +220 -0
  41. package/src/telemetry_sync.py +14 -1
  42. package/src/test_parsers.py +271 -0
  43. package/src/version_checker.py +1 -1
  44. package/src/web_reader.py +202 -0
@@ -0,0 +1,376 @@
1
+ {
2
+ "version": 5,
3
+ "created": "2026-11-14",
4
+ "methodology": "Pre-registered real-repo benchmark. Scenarios are committed BEFORE any measurement (anti cherry-picking; v1/v2 rows stay frozen). All token counts are measured with the calibrated BPE tokenizer on real repository bytes. Every scenario carries deterministic zero-loss gates; a gate failure disqualifies the scenario from the savings table. v3 adds: API surface map, KV-cache prefix locking replay, secret-guard interception, junk-read guard, prompt compaction (TOCP). v4 adds: 10 auto-mode repositories across 10 supported languages (TypeScript, JavaScript, Go, Rust, Java, Ruby, PHP, C#, Swift, C) with pre-registered god-node targeting. v5 renames the kv_cache gate prefix_hit_rate_ge_80 -> prefix_stability_ge_95: a raw hit-rate threshold measured hub-file size distribution, not normalizer quality (a repo whose last hub file dominates can never reach 80% under a perfectly byte-stable normalizer; the append-only ceiling is sum(T[i-1])/sum(T[i])). The v5 gate tests the property under test — PromptCacheNormalizer churn — as achieved prefix vs that ceiling; hit_rate stays reported.",
5
+ "metrics": [
6
+ "token_reduction_pct",
7
+ "usd_saved_sonnet_input",
8
+ "usd_saved_sonnet_output",
9
+ "kv_cache_hit_rate_pct",
10
+ "zero_loss_gates"
11
+ ],
12
+ "pricing": {
13
+ "sonnet_input_usd_per_mtok": 3.0,
14
+ "sonnet_cached_usd_per_mtok": 0.3,
15
+ "sonnet_output_usd_per_mtok": 15.0
16
+ },
17
+ "repos": [
18
+ {
19
+ "key": "flask",
20
+ "url": "https://github.com/pallets/flask",
21
+ "clone_depth": 50,
22
+ "raw_search": {
23
+ "pattern": "def test_",
24
+ "dir": "tests"
25
+ },
26
+ "symbol_read": {
27
+ "file": "src/flask/app.py",
28
+ "symbol": "Flask.full_dispatch_request"
29
+ },
30
+ "pytest": {
31
+ "subset_glob": "tests/",
32
+ "deps": [
33
+ "werkzeug",
34
+ "jinja2",
35
+ "itsdangerous",
36
+ "click",
37
+ "blinker"
38
+ ]
39
+ },
40
+ "multiturn_reads": [
41
+ {
42
+ "file": "src/flask/app.py",
43
+ "symbol": "Flask.full_dispatch_request"
44
+ },
45
+ {
46
+ "file": "src/flask/wrappers.py",
47
+ "symbol": "Request.full_path"
48
+ },
49
+ {
50
+ "file": "src/flask/config.py",
51
+ "symbol": "Config.from_pyfile"
52
+ }
53
+ ]
54
+ },
55
+ {
56
+ "key": "requests",
57
+ "url": "https://github.com/psf/requests",
58
+ "clone_depth": 50,
59
+ "raw_search": {
60
+ "pattern": "session",
61
+ "dir": "src"
62
+ },
63
+ "symbol_read": {
64
+ "file": "src/requests/sessions.py",
65
+ "symbol": "Session.request"
66
+ },
67
+ "pytest": {
68
+ "subset_glob": "tests/",
69
+ "deps": [
70
+ "charset_normalizer",
71
+ "idna",
72
+ "urllib3",
73
+ "certifi",
74
+ "pytest-httpbin"
75
+ ]
76
+ },
77
+ "multiturn_reads": [
78
+ {
79
+ "file": "src/requests/sessions.py",
80
+ "symbol": "Session.request"
81
+ },
82
+ {
83
+ "file": "src/requests/models.py",
84
+ "symbol": "Response.iter_content"
85
+ },
86
+ {
87
+ "file": "src/requests/adapters.py",
88
+ "symbol": "HTTPAdapter.send"
89
+ }
90
+ ]
91
+ },
92
+ {
93
+ "key": "fastapi",
94
+ "url": "https://github.com/fastapi/fastapi",
95
+ "clone_depth": 50,
96
+ "raw_search": {
97
+ "pattern": "def get",
98
+ "dir": "fastapi"
99
+ },
100
+ "symbol_read": {
101
+ "file": "fastapi/routing.py",
102
+ "symbol": "APIRouter.add_api_route"
103
+ },
104
+ "pytest": {
105
+ "subset_glob": "tests/",
106
+ "deps": [
107
+ "pydantic",
108
+ "starlette",
109
+ "email-validator",
110
+ "httpx",
111
+ "opentelemetry-sdk",
112
+ "pytest-asyncio"
113
+ ]
114
+ },
115
+ "multiturn_reads": [
116
+ {
117
+ "file": "fastapi/routing.py",
118
+ "symbol": "APIRouter.add_api_route"
119
+ },
120
+ {
121
+ "file": "fastapi/applications.py",
122
+ "symbol": "FastAPI.__init__"
123
+ },
124
+ {
125
+ "file": "fastapi/params.py",
126
+ "symbol": "Param.field_info"
127
+ }
128
+ ]
129
+ },
130
+ {
131
+ "key": "rich",
132
+ "url": "https://github.com/Textualize/rich",
133
+ "clone_depth": 50,
134
+ "raw_search": {
135
+ "pattern": "class ",
136
+ "dir": "rich"
137
+ },
138
+ "symbol_read": {
139
+ "file": "rich/console.py",
140
+ "symbol": "Console.print"
141
+ },
142
+ "pytest": {
143
+ "subset_glob": "tests/",
144
+ "deps": [
145
+ "attrs"
146
+ ]
147
+ },
148
+ "multiturn_reads": [
149
+ {
150
+ "file": "rich/console.py",
151
+ "symbol": "Console.print"
152
+ },
153
+ {
154
+ "file": "rich/table.py",
155
+ "symbol": "Table.add_row"
156
+ },
157
+ {
158
+ "file": "rich/panel.py",
159
+ "symbol": "Panel.render"
160
+ }
161
+ ]
162
+ },
163
+ {
164
+ "key": "httpie",
165
+ "url": "https://github.com/httpie/cli",
166
+ "clone_depth": 50,
167
+ "raw_search": {
168
+ "pattern": "import",
169
+ "dir": "httpie"
170
+ },
171
+ "symbol_read": {
172
+ "file": "httpie/core.py",
173
+ "symbol": "main"
174
+ },
175
+ "pytest": {
176
+ "subset_glob": "tests/",
177
+ "deps": [
178
+ "requests",
179
+ "pygments",
180
+ "multidict",
181
+ "rich",
182
+ "pytest-httpbin",
183
+ "responses"
184
+ ]
185
+ },
186
+ "multiturn_reads": [
187
+ {
188
+ "file": "httpie/core.py",
189
+ "symbol": "main"
190
+ },
191
+ {
192
+ "file": "httpie/cli/definition.py",
193
+ "symbol": "HTTPieArgumentParser"
194
+ },
195
+ {
196
+ "file": "httpie/sessions.py",
197
+ "symbol": "Session"
198
+ }
199
+ ]
200
+ },
201
+ {
202
+ "key": "zod",
203
+ "url": "https://github.com/colinhacks/zod",
204
+ "clone_depth": 50,
205
+ "language": "typescript",
206
+ "auto": true,
207
+ "raw_search": {
208
+ "pattern": "return ",
209
+ "dir": "packages"
210
+ }
211
+ },
212
+ {
213
+ "key": "lodash",
214
+ "url": "https://github.com/lodash/lodash",
215
+ "clone_depth": 50,
216
+ "language": "javascript",
217
+ "auto": true,
218
+ "raw_search": {
219
+ "pattern": "return ",
220
+ "dir": "."
221
+ }
222
+ },
223
+ {
224
+ "key": "gin",
225
+ "url": "https://github.com/gin-gonic/gin",
226
+ "clone_depth": 50,
227
+ "language": "go",
228
+ "auto": true,
229
+ "raw_search": {
230
+ "pattern": "return ",
231
+ "dir": "."
232
+ }
233
+ },
234
+ {
235
+ "key": "serde",
236
+ "url": "https://github.com/serde-rs/serde",
237
+ "clone_depth": 50,
238
+ "language": "rust",
239
+ "auto": true,
240
+ "raw_search": {
241
+ "pattern": "impl ",
242
+ "dir": "serde"
243
+ }
244
+ },
245
+ {
246
+ "key": "retrofit",
247
+ "url": "https://github.com/square/retrofit",
248
+ "clone_depth": 50,
249
+ "language": "java",
250
+ "auto": true,
251
+ "raw_search": {
252
+ "pattern": "public ",
253
+ "dir": "retrofit/src/main/java/retrofit2"
254
+ }
255
+ },
256
+ {
257
+ "key": "sinatra",
258
+ "url": "https://github.com/sinatra/sinatra",
259
+ "clone_depth": 50,
260
+ "language": "ruby",
261
+ "auto": true,
262
+ "raw_search": {
263
+ "pattern": "def ",
264
+ "dir": "lib"
265
+ }
266
+ },
267
+ {
268
+ "key": "composer",
269
+ "url": "https://github.com/composer/composer",
270
+ "clone_depth": 50,
271
+ "language": "php",
272
+ "auto": true,
273
+ "raw_search": {
274
+ "pattern": "function ",
275
+ "dir": "src"
276
+ }
277
+ },
278
+ {
279
+ "key": "newtonsoft",
280
+ "url": "https://github.com/JamesNK/Newtonsoft.Json",
281
+ "clone_depth": 50,
282
+ "language": "csharp",
283
+ "auto": true,
284
+ "raw_search": {
285
+ "pattern": "public ",
286
+ "dir": "Src"
287
+ }
288
+ },
289
+ {
290
+ "key": "alamofire",
291
+ "url": "https://github.com/Alamofire/Alamofire",
292
+ "clone_depth": 50,
293
+ "language": "swift",
294
+ "auto": true,
295
+ "raw_search": {
296
+ "pattern": "func ",
297
+ "dir": "Source"
298
+ }
299
+ },
300
+ {
301
+ "key": "curl",
302
+ "url": "https://github.com/curl/curl",
303
+ "clone_depth": 50,
304
+ "language": "c",
305
+ "auto": true,
306
+ "raw_search": {
307
+ "pattern": "return ",
308
+ "dir": "lib"
309
+ }
310
+ }
311
+ ],
312
+ "injected_failure": {
313
+ "note": "CI-failure triage scenario: a deterministic failing test file is written into the temp clone (never committed upstream) to produce a REAL pytest failure output on real code — standard SWE-bench-style regression injection, pre-registered here.",
314
+ "test_source": "def test_bench_injected_regression():\n assert False, \"bench: pre-registered injected regression\"\n",
315
+ "file": "tests/test_bench_injected.py"
316
+ },
317
+ "secret_guard": {
318
+ "note": "Security scenario: a pre-registered FAKE .env fixture is written into the temp clone (values are synthetic, never real secrets); the guard must deny reading it and leak zero secret values into the model context.",
319
+ "env_content": "# Database credentials (bench fixture — synthetic values)\nDATABASE_URL=postgres://admin:SuperSecret9f3b@db.internal:5432/prod\nAPI_KEY=sk-live-4c9a1f77e2b34d08a91c6d5e7f0b2a3d\nJWT_SECRET=9f3b1c77e2b34d08a91c6d5e7f0b2a3d9f3b\nSTRIPE_WEBHOOK_SECRET=whsec_5f4eecb9821a4c1d9e7f0b2a3d4c5e6f\nSMTP_PASS=P@ssw0rd-bench-7712\n"
320
+ },
321
+ "prompt_compaction": {
322
+ "template": "Please look at {file} and refactor the {symbol} function to handle the following edge cases properly: handle empty and None inputs with clear error messages, validate all incoming parameters before mutating state, add proper error messages, update the docstring, make the logging consistent with the rest of the codebase, keep the public signature backward compatible, avoid breaking existing callers, extract repeated logic into small private helpers, cover every new branch with tests, and make sure the feature flags still work as documented for both the community and the paid tiers of the product."
323
+ },
324
+ "zero_loss_gates": {
325
+ "symbol_read": [
326
+ "symbol_present",
327
+ "valid_python",
328
+ "all_top_level_defs_present",
329
+ "signature_line_match"
330
+ ],
331
+ "test_output": [
332
+ "failing_test_name_present",
333
+ "error_type_present",
334
+ "first_traceback_frame_present"
335
+ ],
336
+ "multiturn": [
337
+ "all_reads_lossless"
338
+ ],
339
+ "architecture": [
340
+ "hub_files_listed",
341
+ "compact_bound"
342
+ ],
343
+ "raw_search": [
344
+ "matches_exist",
345
+ "paths_preserved"
346
+ ],
347
+ "git_diff": [
348
+ "changed_files_preserved"
349
+ ],
350
+ "write_egress": [
351
+ "inserted_line_present",
352
+ "original_signature_in_target"
353
+ ],
354
+ "api_surface": [
355
+ "hub_files_listed",
356
+ "smaller_than_crawl"
357
+ ],
358
+ "kv_cache": [
359
+ "prefix_stability_ge_95",
360
+ "input_reduction_positive"
361
+ ],
362
+ "secret_guard": [
363
+ "deny_decision",
364
+ "no_secret_leak"
365
+ ],
366
+ "junk_read": [
367
+ "capped_output",
368
+ "junk_file_named"
369
+ ],
370
+ "prompt_compaction": [
371
+ "action_extracted",
372
+ "target_file_preserved",
373
+ "savings_positive"
374
+ ]
375
+ }
376
+ }
@@ -113,8 +113,29 @@ class PromptCacheNormalizer:
113
113
  re.compile(r"Conversation ID:\s*[a-f0-9-]{8,36}", re.IGNORECASE),
114
114
  re.compile(r"invocationNum[\"']?\s*[:=]\s*\d+", re.IGNORECASE),
115
115
  re.compile(r"Generated locally at \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", re.IGNORECASE),
116
+ re.compile(r"⚡ \*\*TokenSafe Turn Savings\*\*:.*?(?=\n|$)", re.IGNORECASE),
117
+ re.compile(r"\(TokenSafe: compacted ~?\d[\d,]* prompt tokens.*?\)", re.IGNORECASE),
118
+ re.compile(r"\[TokenSafe: Pointer Hit .*?\]", re.IGNORECASE),
119
+ re.compile(r"Community Edition limit reached.*?(?=\n|$)", re.IGNORECASE),
116
120
  ]
117
121
 
122
+ @classmethod
123
+ def validate_prefix_stability(
124
+ cls,
125
+ messages_a: List[Dict[str, Any]],
126
+ messages_b: List[Dict[str, Any]],
127
+ tools: Optional[List[Dict[str, Any]]] = None,
128
+ ) -> bool:
129
+ """
130
+ Validates that the static system prefix between two consecutive turns
131
+ produces identical prefix hashes to guarantee 100% KV-cache hits.
132
+ """
133
+ _, meta_a = cls.normalize_messages(messages_a, tools=tools)
134
+ _, meta_b = cls.normalize_messages(messages_b, tools=tools)
135
+ hash_a = meta_a.get("prefix_hash") or cls.compute_prefix_hash(json.dumps(meta_a.get("normalized_tools") or []))
136
+ hash_b = meta_b.get("prefix_hash") or cls.compute_prefix_hash(json.dumps(meta_b.get("normalized_tools") or []))
137
+ return hash_a == hash_b
138
+
118
139
  @classmethod
119
140
  def strip_volatile_elements(cls, text: str) -> str:
120
141
  """Removes volatile timestamps, hit counters, and ephemeral IDs from static prefix."""