tokensafe 3.2.0 → 4.0.1
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/README.md +60 -28
- package/bin/tokensafe.js +25 -9
- package/hooks/claude_code_hook.py +7 -0
- package/hooks/pre_tool_use.py +24 -0
- package/hooks/session_start.py +8 -0
- package/package.json +2 -2
- package/plugin.json +1 -1
- package/rules/AGENTS.md +13 -7
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +7 -2
- package/skills/token-optimizer/references/cli-reference.md +11 -1
- package/skills/token-optimizer/references/mcp-tools.md +44 -2
- package/src/bench_scenarios.json +376 -0
- package/src/cache_normalizer.py +21 -0
- package/src/cli.py +234 -2
- package/src/command_sanitizer.py +2 -0
- package/src/competitors.py +179 -0
- package/src/environment_auditor.py +110 -1
- package/src/format_parsers/__init__.py +20 -0
- package/src/format_parsers/ansi.py +41 -0
- package/src/format_parsers/compiler_errors.py +159 -0
- package/src/format_parsers/docker_k8s.py +95 -0
- package/src/format_parsers/json_log.py +89 -0
- package/src/format_parsers/lockfiles.py +157 -0
- package/src/format_parsers/tabular.py +175 -0
- package/src/fts_index.py +296 -0
- package/src/graph_engine.py +395 -48
- package/src/image_downscale.py +228 -0
- package/src/loop_detector.py +5 -0
- package/src/mcp_config_manager.py +197 -0
- package/src/mcp_proxy.py +154 -0
- package/src/mcp_server.py +215 -1
- package/src/mistakes.py +203 -0
- package/src/result_ledger.py +8 -1
- package/src/scoped_search.py +32 -0
- package/src/stash.py +199 -0
- package/src/superseded.py +220 -0
- package/src/telemetry_sync.py +1 -1
- package/src/test_parsers.py +271 -0
- package/src/version_checker.py +1 -1
- 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
|
+
}
|
package/src/cache_normalizer.py
CHANGED
|
@@ -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."""
|
package/src/cli.py
CHANGED
|
@@ -105,7 +105,10 @@ def _print_help():
|
|
|
105
105
|
print(" test <prompt> Preview TOCP S-expression prompt compaction")
|
|
106
106
|
print(" digest [--send] [--email=...] Compile (and optionally dispatch) the weekly team digest")
|
|
107
107
|
print(" guard <command> Pre-flight safety check for a shell command")
|
|
108
|
-
print("
|
|
108
|
+
print(" expand-ref <hash> Restore folded tool/command/file result by its 8-char hash")
|
|
109
|
+
print(" wrap <command> Run command with compact output folding (e.g. tests/logs)")
|
|
110
|
+
print(" web <url> Fetch web page/docs and print clean compact Markdown")
|
|
111
|
+
print(" doctor [--cleanup] Audit MCP tool overhead and detect competitor conflicts")
|
|
109
112
|
print(" tests [pytest] [--traceback] Run the unit test suite (compact failure report)")
|
|
110
113
|
print(" prune [--days N | --max N] Compact metrics database (roll old events)")
|
|
111
114
|
print(" vacuum Reclaim SQLite disk space")
|
|
@@ -215,7 +218,7 @@ def main(argv: Optional[List[str]] = None):
|
|
|
215
218
|
pass
|
|
216
219
|
print(dashboard.render_terminal())
|
|
217
220
|
|
|
218
|
-
elif command in ("html", "
|
|
221
|
+
elif command in ("html", "dashboard-html"):
|
|
219
222
|
from src.paths import resolve_data_dir
|
|
220
223
|
tracker = MetricsTracker()
|
|
221
224
|
dashboard = Dashboard(tracker)
|
|
@@ -468,6 +471,36 @@ def main(argv: Optional[List[str]] = None):
|
|
|
468
471
|
print(f"\n\033[32m✔ MCP server '{target}' re-enabled successfully.\033[0m\n")
|
|
469
472
|
else:
|
|
470
473
|
print(f"\n\033[31m✖ Server '{target}' not found in disabled servers.\033[0m\n")
|
|
474
|
+
elif subcmd in ("wrap", "proxy-wrap"):
|
|
475
|
+
from src.mcp_config_manager import MCPConfigManager
|
|
476
|
+
target = args[2].strip() if len(args) > 2 else "--all"
|
|
477
|
+
if target in ("--all", "-a", "all"):
|
|
478
|
+
count = MCPConfigManager.wrap_all()
|
|
479
|
+
print(f"\n\033[32m✔ Wrapped {count} third-party MCP server(s) behind tokensafe mcp-proxy.\033[0m\n")
|
|
480
|
+
else:
|
|
481
|
+
servers = MCPConfigManager.list_servers()
|
|
482
|
+
matched = [s for s in servers if s["server_name"] == target]
|
|
483
|
+
if not matched:
|
|
484
|
+
print(f"\n\033[31m✖ Server '{target}' not found in active agent MCP configs.\033[0m\n")
|
|
485
|
+
else:
|
|
486
|
+
for s in matched:
|
|
487
|
+
MCPConfigManager.wrap_server(s["config_path"], s["server_name"])
|
|
488
|
+
print(f"\n\033[32m✔ Server '{target}' wrapped behind tokensafe mcp-proxy.\033[0m\n")
|
|
489
|
+
elif subcmd in ("unwrap", "restore"):
|
|
490
|
+
from src.mcp_config_manager import MCPConfigManager
|
|
491
|
+
target = args[2].strip() if len(args) > 2 else "--all"
|
|
492
|
+
if target in ("--all", "-a", "all"):
|
|
493
|
+
count = MCPConfigManager.unwrap_all()
|
|
494
|
+
print(f"\n\033[32m✔ Unwrapped {count} MCP server(s) back to direct execution.\033[0m\n")
|
|
495
|
+
else:
|
|
496
|
+
servers = MCPConfigManager.list_servers()
|
|
497
|
+
matched = [s for s in servers if s["server_name"] == target]
|
|
498
|
+
if not matched:
|
|
499
|
+
print(f"\n\033[31m✖ Server '{target}' not found in active agent MCP configs.\033[0m\n")
|
|
500
|
+
else:
|
|
501
|
+
for s in matched:
|
|
502
|
+
MCPConfigManager.unwrap_server(s["config_path"], s["server_name"])
|
|
503
|
+
print(f"\n\033[32m✔ Server '{target}' restored to original command.\033[0m\n")
|
|
471
504
|
elif subcmd in ("list", "ls", "status"):
|
|
472
505
|
from src.environment_auditor import EnvironmentAuditor
|
|
473
506
|
print(EnvironmentAuditor.format_cli_report())
|
|
@@ -475,10 +508,94 @@ def main(argv: Optional[List[str]] = None):
|
|
|
475
508
|
from src.mcp_server import run_mcp_server
|
|
476
509
|
run_mcp_server()
|
|
477
510
|
|
|
511
|
+
elif command in ("mcp-proxy", "mcp_proxy"):
|
|
512
|
+
target_args = list(args[1:])
|
|
513
|
+
if target_args and target_args[0] == "--":
|
|
514
|
+
target_args.pop(0)
|
|
515
|
+
from src.mcp_proxy import run_proxy
|
|
516
|
+
run_proxy(target_args)
|
|
517
|
+
|
|
478
518
|
elif command in ("doctor", "audit", "tax"):
|
|
479
519
|
from src.environment_auditor import EnvironmentAuditor
|
|
480
520
|
print(EnvironmentAuditor.format_cli_report())
|
|
481
521
|
|
|
522
|
+
from src.competitors import CompetitorAuditor
|
|
523
|
+
conflicts = CompetitorAuditor.audit()
|
|
524
|
+
if conflicts:
|
|
525
|
+
print("\n\033[1m\033[33m⚡ DETECTED CONFLICTING OR STALE TOOLS ⚡\033[0m")
|
|
526
|
+
for c in conflicts:
|
|
527
|
+
print(f" • \033[1m{c['name']}\033[0m [{c['class']}]: {c['description']}")
|
|
528
|
+
for tr in c['traces']:
|
|
529
|
+
loc = tr.get('path') or tr.get('file') or tr.get('config')
|
|
530
|
+
print(f" - {tr['kind']}: {loc}")
|
|
531
|
+
print("\n 💡 Tip: Run 'tokensafe doctor --cleanup' to remove conflicting orphan hooks/rules.\n")
|
|
532
|
+
|
|
533
|
+
if "--cleanup" in args:
|
|
534
|
+
for c in conflicts:
|
|
535
|
+
res = CompetitorAuditor.cleanup(c["id"])
|
|
536
|
+
print(f" \033[32m✔ Cleaned {c['name']}: {', '.join(res.get('removed', []))}\033[0m")
|
|
537
|
+
|
|
538
|
+
elif command in ("web", "fetch", "url"):
|
|
539
|
+
if len(args) < 2:
|
|
540
|
+
print("Usage: tokensafe web <url>")
|
|
541
|
+
sys.exit(1)
|
|
542
|
+
url = args[1].strip()
|
|
543
|
+
from src.web_reader import WebReader
|
|
544
|
+
md, ok, err = WebReader.fetch_url(url)
|
|
545
|
+
if not ok:
|
|
546
|
+
print(f"\033[31mError: {err}\033[0m")
|
|
547
|
+
sys.exit(1)
|
|
548
|
+
print(md)
|
|
549
|
+
|
|
550
|
+
elif command in ("search", "find", "fts"):
|
|
551
|
+
if len(args) < 2:
|
|
552
|
+
print("Usage: tokensafe search <query> [--limit 25] [--path <dir>]")
|
|
553
|
+
sys.exit(1)
|
|
554
|
+
query = args[1]
|
|
555
|
+
limit = 25
|
|
556
|
+
target_dir = os.getcwd()
|
|
557
|
+
if "--limit" in args:
|
|
558
|
+
idx = args.index("--limit")
|
|
559
|
+
if idx + 1 < len(args):
|
|
560
|
+
try:
|
|
561
|
+
limit = int(args[idx + 1])
|
|
562
|
+
except ValueError:
|
|
563
|
+
pass
|
|
564
|
+
if "--path" in args:
|
|
565
|
+
idx = args.index("--path")
|
|
566
|
+
if idx + 1 < len(args):
|
|
567
|
+
target_dir = os.path.abspath(args[idx + 1])
|
|
568
|
+
|
|
569
|
+
from src.fts_index import CodeFTSIndex
|
|
570
|
+
idx_engine = CodeFTSIndex(target_dir)
|
|
571
|
+
idx_engine.index_files()
|
|
572
|
+
results = idx_engine.search(query, limit=limit)
|
|
573
|
+
if not results:
|
|
574
|
+
print(f"No matches found for '{query}'.")
|
|
575
|
+
else:
|
|
576
|
+
print(f"\n\033[1m\033[36m⚡ SQLite FTS5 BM25 Search ({len(results)} matches for '{query}'):\033[0m\n")
|
|
577
|
+
for r in results:
|
|
578
|
+
print(f" \033[32m{r['file']}:{r['line']}\033[0m: {r['content']}")
|
|
579
|
+
print()
|
|
580
|
+
|
|
581
|
+
elif command in ("index", "fts-index"):
|
|
582
|
+
target_dir = os.getcwd()
|
|
583
|
+
if len(args) > 1 and not args[1].startswith("-"):
|
|
584
|
+
target_dir = os.path.abspath(args[1])
|
|
585
|
+
from src.fts_index import CodeFTSIndex
|
|
586
|
+
idx_engine = CodeFTSIndex(target_dir)
|
|
587
|
+
if "--clear" in args or "--reset" in args:
|
|
588
|
+
idx_engine.clear()
|
|
589
|
+
print(f"\033[32m✔ Cleared FTS index database for {target_dir}.\033[0m")
|
|
590
|
+
else:
|
|
591
|
+
stats = idx_engine.index_files()
|
|
592
|
+
print(f"\n\033[1m\033[36m⚡ SQLite FTS5 Full-Text Indexer ⚡\033[0m")
|
|
593
|
+
print(f" Scanned files: {stats['scanned_files']}")
|
|
594
|
+
print(f" Updated files: {stats['updated_files']}")
|
|
595
|
+
print(f" Indexed lines: {stats['indexed_lines']:,}")
|
|
596
|
+
print(f" Duration: {stats['duration_ms']:.2f} ms")
|
|
597
|
+
print(f" Index path: {idx_engine.db_path}\n")
|
|
598
|
+
|
|
482
599
|
elif command in ("graph", "nodes"):
|
|
483
600
|
from src.graph_engine import GraphEngine
|
|
484
601
|
target_dir = args[1] if len(args) > 1 else os.getcwd()
|
|
@@ -823,6 +940,40 @@ def main(argv: Optional[List[str]] = None):
|
|
|
823
940
|
print(f"\033[1mCompacted Tokens:\033[0m {res['compact_tokens']}")
|
|
824
941
|
print(f"\033[1mTokens Saved:\033[0m \033[32m\033[1m+{res['saved_tokens']} tokens\033[0m ({render_bar(res['reduction_pct'])})\n")
|
|
825
942
|
|
|
943
|
+
elif command == "wrap":
|
|
944
|
+
if len(args) < 2:
|
|
945
|
+
print("Usage: tokensafe wrap <command>")
|
|
946
|
+
sys.exit(1)
|
|
947
|
+
sub_cmd = " ".join(args[1:])
|
|
948
|
+
try:
|
|
949
|
+
proc = subprocess.run(sub_cmd, shell=True, capture_output=True, text=True)
|
|
950
|
+
raw = (proc.stdout or "") + (proc.stderr or "")
|
|
951
|
+
except Exception as e:
|
|
952
|
+
print(f"Error running command: {e}")
|
|
953
|
+
sys.exit(1)
|
|
954
|
+
|
|
955
|
+
from src.format_parsers.ansi import strip_ansi
|
|
956
|
+
from src.test_parsers import TestOutputParser
|
|
957
|
+
from src.stash import stash_block
|
|
958
|
+
|
|
959
|
+
raw = strip_ansi(raw)
|
|
960
|
+
compacted, was_test = TestOutputParser.compact(raw)
|
|
961
|
+
if was_test:
|
|
962
|
+
print(compacted)
|
|
963
|
+
sys.exit(proc.returncode)
|
|
964
|
+
|
|
965
|
+
lines = raw.splitlines()
|
|
966
|
+
if len(lines) > 40:
|
|
967
|
+
head = lines[:15]
|
|
968
|
+
tail = lines[-15:]
|
|
969
|
+
omitted = len(lines) - 30
|
|
970
|
+
_, marker = stash_block(raw, source="wrap")
|
|
971
|
+
folded = "\n".join(head + [f"... [{omitted} lines omitted by TokenSafe] ..."] + tail + [marker])
|
|
972
|
+
print(folded)
|
|
973
|
+
else:
|
|
974
|
+
print(raw)
|
|
975
|
+
sys.exit(proc.returncode)
|
|
976
|
+
|
|
826
977
|
elif command in ("tests", "testsuite", "unittest"):
|
|
827
978
|
tests_dir = os.path.join(PROJECT_ROOT, "tests")
|
|
828
979
|
if not os.path.isdir(tests_dir):
|
|
@@ -962,6 +1113,87 @@ def main(argv: Optional[List[str]] = None):
|
|
|
962
1113
|
else:
|
|
963
1114
|
print("Tip: Run with --send to dispatch email, or --email=<addr> to target specific team.\n")
|
|
964
1115
|
|
|
1116
|
+
elif command in ("expand-ref", "expand_ref", "expand"):
|
|
1117
|
+
if len(args) < 2:
|
|
1118
|
+
print("Usage: tokensafe expand-ref <hash8>")
|
|
1119
|
+
sys.exit(1)
|
|
1120
|
+
ref_hash = args[1].strip()
|
|
1121
|
+
from src.stash import retrieve_block
|
|
1122
|
+
content = retrieve_block(ref_hash)
|
|
1123
|
+
if content is None:
|
|
1124
|
+
print(f"\033[31mError: Stashed reference '{ref_hash}' not found or expired.\033[0m")
|
|
1125
|
+
sys.exit(1)
|
|
1126
|
+
print(content)
|
|
1127
|
+
|
|
1128
|
+
elif command in ("optimize-image", "image-opt", "image"):
|
|
1129
|
+
if len(args) < 2:
|
|
1130
|
+
print("Usage: tokensafe optimize-image <image_path> [--max-edge 1024]")
|
|
1131
|
+
sys.exit(1)
|
|
1132
|
+
img_path = args[1]
|
|
1133
|
+
max_edge = 1024
|
|
1134
|
+
if "--max-edge" in args:
|
|
1135
|
+
idx = args.index("--max-edge")
|
|
1136
|
+
if idx + 1 < len(args):
|
|
1137
|
+
try:
|
|
1138
|
+
max_edge = int(args[idx + 1])
|
|
1139
|
+
except ValueError:
|
|
1140
|
+
pass
|
|
1141
|
+
from src.image_downscale import ImageDownscaler
|
|
1142
|
+
res = ImageDownscaler.optimize(img_path, max_edge=max_edge)
|
|
1143
|
+
if not res.get("success"):
|
|
1144
|
+
print(f"\033[31mError: {res.get('error')}\033[0m")
|
|
1145
|
+
sys.exit(1)
|
|
1146
|
+
if res.get("was_downscaled"):
|
|
1147
|
+
print(f"\033[32m✔ Downscaled image using {res.get('engine')}:\033[0m {res['orig_dimensions']} ➔ {res['new_dimensions']}")
|
|
1148
|
+
print(f" Saved vision tokens: ~{res['saved_tokens']} tokens")
|
|
1149
|
+
print(f" Optimized image: {res['optimized_path']}")
|
|
1150
|
+
else:
|
|
1151
|
+
print(f"Image within bounds ({res.get('dimensions', 'N/A')} <= {max_edge}px). Using original file.")
|
|
1152
|
+
|
|
1153
|
+
elif command in ("prune-superseded", "prune_superseded"):
|
|
1154
|
+
if len(args) < 2:
|
|
1155
|
+
print("Usage: tokensafe prune-superseded <transcript_path>")
|
|
1156
|
+
sys.exit(1)
|
|
1157
|
+
t_path = args[1]
|
|
1158
|
+
from src.superseded import SupersededPruner
|
|
1159
|
+
res = SupersededPruner.prune_transcript(t_path)
|
|
1160
|
+
if not res.get("success"):
|
|
1161
|
+
print(f"\033[31mError: {res.get('error')}\033[0m")
|
|
1162
|
+
sys.exit(1)
|
|
1163
|
+
print(f"\033[32m✔ Pruned {res['pruned_count']} superseded tool read(s) from transcript.\033[0m")
|
|
1164
|
+
print(f" Saved context: ~{res['saved_tokens']} tokens")
|
|
1165
|
+
|
|
1166
|
+
elif command in ("mistakes", "deadends"):
|
|
1167
|
+
from src.mistakes import MistakesLedger
|
|
1168
|
+
sub = args[1] if len(args) > 1 else "list"
|
|
1169
|
+
if sub in ("clear", "reset"):
|
|
1170
|
+
c = MistakesLedger.clear_mistakes(os.getcwd())
|
|
1171
|
+
print(f"\033[32m✔ Cleared {c} mistake record(s).\033[0m")
|
|
1172
|
+
elif sub in ("record", "add"):
|
|
1173
|
+
reason = "Failed hypothesis"
|
|
1174
|
+
f_path = None
|
|
1175
|
+
if "--reason" in args:
|
|
1176
|
+
idx = args.index("--reason")
|
|
1177
|
+
if idx + 1 < len(args):
|
|
1178
|
+
reason = args[idx + 1]
|
|
1179
|
+
if "--file" in args:
|
|
1180
|
+
idx = args.index("--file")
|
|
1181
|
+
if idx + 1 < len(args):
|
|
1182
|
+
f_path = args[idx + 1]
|
|
1183
|
+
entry = MistakesLedger.record_revert(f_path or "project", reason, project_root=os.getcwd())
|
|
1184
|
+
print(f"\033[32m✔ Recorded mistake: {entry['summary']}\033[0m")
|
|
1185
|
+
else:
|
|
1186
|
+
entries = MistakesLedger.list_mistakes(project_root=os.getcwd())
|
|
1187
|
+
if not entries:
|
|
1188
|
+
print("No recorded dead-ends or reverts for this project.")
|
|
1189
|
+
else:
|
|
1190
|
+
print(f"\n\033[1m\033[36m⚡ TOKENSAFE ANTI-STUCK DEAD-ENDS LEDGER ({len(entries)}) ⚡\033[0m\n")
|
|
1191
|
+
for e in entries:
|
|
1192
|
+
print(f" • \033[1m{e.get('file') or 'project'}\033[0m: {e.get('summary')} [{e.get('source')}]")
|
|
1193
|
+
guard = MistakesLedger.get_guard_prompt(project_root=os.getcwd())
|
|
1194
|
+
if guard:
|
|
1195
|
+
print(f"\n\033[33mActive prompt guard:\033[0m\n{guard}\n")
|
|
1196
|
+
|
|
965
1197
|
elif command == "reset":
|
|
966
1198
|
confirm = input("Are you sure you want to reset all token metrics? [y/N]: ").strip().lower()
|
|
967
1199
|
if confirm == "y":
|