tokensafe 5.0.0 → 5.0.2

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 (53) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/assets/logo.svg +1 -13
  5. package/hooks/claude_code_hook.py +5 -1
  6. package/hooks/cursor_hook.py +1 -1
  7. package/kimi.plugin.json +3 -2
  8. package/package.json +1 -1
  9. package/plugin.json +1 -1
  10. package/rules/AGENTS.md +4 -3
  11. package/server.json +3 -3
  12. package/skills/oumv-protocol/SKILL.md +59 -0
  13. package/skills/token-optimizer/SKILL.md +5 -3
  14. package/skills/token-optimizer/references/mcp-tools.md +1 -1
  15. package/tokensafe/adapter_core.py +62 -18
  16. package/tokensafe/atomic_io.py +20 -16
  17. package/tokensafe/auto_inject.py +2 -2
  18. package/tokensafe/backend_release.py +3 -3
  19. package/tokensafe/batch_editor.py +299 -10
  20. package/tokensafe/batch_search.py +53 -0
  21. package/tokensafe/bounded_flock.py +60 -0
  22. package/tokensafe/burn_monitor.py +60 -2
  23. package/tokensafe/call_context.py +158 -0
  24. package/tokensafe/cli.py +41 -13
  25. package/tokensafe/compactor.py +87 -5
  26. package/tokensafe/context_index.py +3 -0
  27. package/tokensafe/dashboard.py +119 -43
  28. package/tokensafe/environment_auditor.py +30 -2
  29. package/tokensafe/fts_index.py +3 -0
  30. package/tokensafe/graph_engine.py +246 -29
  31. package/tokensafe/installer.py +72 -13
  32. package/tokensafe/loop_detector.py +8 -20
  33. package/tokensafe/mcp_server.py +1084 -188
  34. package/tokensafe/metrics.py +173 -46
  35. package/tokensafe/oumv_brief.py +144 -8
  36. package/tokensafe/oumv_gateway.py +689 -222
  37. package/tokensafe/oumv_home.py +259 -0
  38. package/tokensafe/oumv_policy.py +64 -1
  39. package/tokensafe/proc_run.py +162 -0
  40. package/tokensafe/proxy.py +78 -8
  41. package/tokensafe/retrofit.py +484 -82
  42. package/tokensafe/route_index.py +2 -0
  43. package/tokensafe/savings.py +10 -2
  44. package/tokensafe/scoped_search.py +77 -0
  45. package/tokensafe/session_brief.py +17 -2
  46. package/tokensafe/stack_summary.py +73 -0
  47. package/tokensafe/syntax_guard.py +8 -2
  48. package/tokensafe/telemetry_sync.py +1 -1
  49. package/tokensafe/version_checker.py +1 -1
  50. package/tokensafe/web_reader.py +53 -4
  51. package/tokensafe/workspace_roots.py +127 -9
  52. package/assets/social/linkedin_banner.png +0 -0
  53. package/assets/social/tokensafe_logo_square.png +0 -0
@@ -232,8 +232,10 @@ def compact_for_injection(prompt: str, agent: str, session_id: str, transcript_p
232
232
 
233
233
  def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "", transcript_path: str = "") -> Dict[str, Any]:
234
234
  """Pre-execution shell guard. Returns:
235
- {decision: allow|deny|ask, reason, saved_tokens} where saved_tokens is the
236
- MEASURED mass of blocked output (0 for allowed commands)."""
235
+ {decision: allow|deny|ask, reason, saved_tokens} where saved_tokens is an
236
+ ESTIMATED floor for the blocked call (0 for allowed commands): the output a
237
+ blocked command would have produced is unknowable, so the event records
238
+ max(50, len(cmd)/4) labelled estimated, never measured."""
237
239
  result = {"decision": "allow", "reason": "", "saved_tokens": 0}
238
240
  if not command or not command.strip():
239
241
  return result
@@ -241,7 +243,7 @@ def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "",
241
243
  text = cmd
242
244
 
243
245
  def blocked(kind: str, reason: str, decision: str = "deny"):
244
- est = max(50, len(cmd) // 4) # blocked mass never reaches the model
246
+ est = max(50, len(cmd) // 4) # floor: the blocked output size is unknowable
245
247
  tracker = _get_tracker()
246
248
  if tracker:
247
249
  try:
@@ -251,7 +253,9 @@ def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "",
251
253
  original_tokens=est,
252
254
  optimized_tokens=0,
253
255
  details={"agent": agent, "command": cmd[:120],
256
+ "estimate_basis": "command_length_floor",
254
257
  "model": resolve_event_model(transcript_path, session_id)},
258
+ measurement="estimated",
255
259
  )
256
260
  except Exception:
257
261
  pass
@@ -290,16 +294,39 @@ def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "",
290
294
  return result
291
295
 
292
296
 
293
- def guard_read(file_path: str, agent: str, session_id: str = "", transcript_path: str = "") -> Dict[str, Any]:
297
+ # Counterfactual for a blocked junk read. The read never ran, so the figure is
298
+ # always labelled estimated: bytes/4 of the real file when it can be stat'ed,
299
+ # capped at what one host Read returns (Claude Code truncates a single Read at
300
+ # ~25k tokens), else the historic 4,000-token lockfile floor.
301
+ _JUNK_READ_FALLBACK_TOKENS = 4000
302
+ _JUNK_READ_CAP_TOKENS = 25_000
303
+
304
+
305
+ def _junk_read_counterfactual(file_path: str, cwd: str = "") -> Tuple[int, str]:
306
+ """Returns (tokens, basis) for a blocked junk read: basis is
307
+ 'file_size_bytes/4' when the file exists, else 'constant_floor'."""
308
+ try:
309
+ path = os.path.expanduser(file_path)
310
+ if not os.path.isabs(path) and cwd:
311
+ path = os.path.join(cwd, path)
312
+ if os.path.isfile(path):
313
+ return min(_JUNK_READ_CAP_TOKENS, os.path.getsize(path) // 4), "file_size_bytes/4"
314
+ except Exception:
315
+ pass
316
+ return _JUNK_READ_FALLBACK_TOKENS, "constant_floor"
317
+
318
+
319
+ def guard_read(file_path: str, agent: str, session_id: str = "", transcript_path: str = "", cwd: str = "") -> Dict[str, Any]:
294
320
  """Pre-read guard: denies lockfiles/bundles/dist junk that would burn the
295
- context window. Blocked reads are recorded as measured savings."""
321
+ context window. Blocked reads are recorded as ESTIMATED savings (the read
322
+ never ran): the blocked file's size when known, else a constant floor."""
296
323
  result = {"decision": "allow", "reason": "", "saved_tokens": 0}
297
324
  if not file_path:
298
325
  return result
299
326
  normalized = file_path.replace("\\", "/")
300
327
  for pat in _JUNK_READ_PATTERNS:
301
328
  if re.search(pat, normalized):
302
- est = 4000 # typical lockfile dump size floor
329
+ est, basis = _junk_read_counterfactual(file_path, cwd)
303
330
  tracker = _get_tracker()
304
331
  if tracker:
305
332
  try:
@@ -309,14 +336,17 @@ def guard_read(file_path: str, agent: str, session_id: str = "", transcript_path
309
336
  original_tokens=est,
310
337
  optimized_tokens=0,
311
338
  details={"agent": agent, "file": os.path.basename(normalized),
339
+ "estimate_basis": basis,
312
340
  "model": resolve_event_model(transcript_path, session_id)},
341
+ measurement="estimated",
313
342
  )
314
343
  except Exception:
315
344
  pass
345
+ size_hint = f"~{est / 1000:.1f}k tokens" if est >= 1000 else f"~{est} tokens"
316
346
  result.update({
317
347
  "decision": "deny",
318
348
  "reason": f"TokenSafe: '{os.path.basename(normalized)}' is machine-generated bulk "
319
- f"(~{est // 1000}k tokens). Inspect it via 'tokensafe:scoped_search' or grep a symbol instead.",
349
+ f"({size_hint}). Inspect it via 'tokensafe:scoped_search' or grep a symbol instead.",
320
350
  "saved_tokens": est,
321
351
  })
322
352
  return result
@@ -880,7 +910,7 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
880
910
 
881
911
  if canon == "read":
882
912
  file_path = _extract_path(tool_input)
883
- verdict = guard_read(file_path, agent, session_id, transcript_path=tp)
913
+ verdict = guard_read(file_path, agent, session_id, transcript_path=tp, cwd=cwd)
884
914
  if verdict["decision"] == "deny":
885
915
  return _cc_decision("deny", verdict["reason"])
886
916
  advisories = [
@@ -905,27 +935,41 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
905
935
  return {}
906
936
 
907
937
 
938
+ def _fmt_tokens(n: int) -> str:
939
+ if n >= 1_000_000:
940
+ return f"{n / 1_000_000:.2f}M"
941
+ if n >= 1_000:
942
+ return f"{n / 1_000:.1f}K"
943
+ return f"{n:,}"
944
+
945
+
908
946
  def format_cumulative_banner(tracker: Optional[Any] = None) -> str:
909
- """One-line cumulative savings summary injected once at SessionStart."""
947
+ """One-line cumulative savings summary injected once at SessionStart.
948
+
949
+ Leads with MEASURED savings (the number a model may quote); estimated
950
+ (counterfactual) and legacy-unclassified mass are named apart and never
951
+ summed into the headline."""
910
952
  try:
911
953
  tr = tracker or _get_tracker()
912
954
  if not tr:
913
955
  return ""
914
956
  s = tr.get_summary()
915
- saved = int(s.get("total_saved_tokens") or 0)
916
- if saved <= 0:
957
+ measured = int(s.get("total_saved_tokens_measured") or 0)
958
+ estimated = int(s.get("total_saved_tokens_estimated") or 0)
959
+ legacy = int(s.get("total_saved_tokens_legacy") or 0)
960
+ if measured + estimated + legacy <= 0:
917
961
  return ""
918
962
  steps = int(s.get("total_events") or 0)
919
- if saved >= 1_000_000:
920
- tok_str = f"{saved / 1_000_000:.2f}M"
921
- elif saved >= 1_000:
922
- tok_str = f"{saved / 1_000:.1f}K"
923
- else:
924
- tok_str = f"{saved:,}"
963
+ extras = []
964
+ if estimated:
965
+ extras.append(f"+{_fmt_tokens(estimated)} estimated, not measured")
966
+ if legacy:
967
+ extras.append(f"+{_fmt_tokens(legacy)} legacy unclassified")
968
+ extra_str = f" ({'; '.join(extras)})" if extras else ""
925
969
  # Tokens and steps only: no dollar estimate is shown, since a saved
926
970
  # token is a counterfactual delta whose price depends on the provider
927
971
  # (cache hit vs miss vs output) and is not knowable locally.
928
972
  suffix = f" | {steps:,} step" + ("" if steps == 1 else "s") if steps else ""
929
- return f"[TokenSafe Cumulative: {tok_str} tokens saved{suffix}]"
973
+ return f"[TokenSafe Cumulative: {_fmt_tokens(measured)} measured tokens saved{extra_str}{suffix}]"
930
974
  except Exception:
931
975
  return ""
@@ -49,23 +49,27 @@ def write_atomic(path: str, data: Union[bytes, str], *, mode: Optional[int] = No
49
49
  mode = None
50
50
 
51
51
  payload = data.encode("utf-8") if isinstance(data, str) else data
52
- fd, tmp_path = tempfile.mkstemp(prefix=".tokensafe_atomic_", dir=directory)
53
- try:
54
- with os.fdopen(fd, "wb") as handle:
55
- handle.write(payload)
56
- handle.flush()
57
- if fsync:
58
- os.fsync(handle.fileno())
59
- os.chmod(tmp_path, mode if mode is not None else 0o600)
60
- os.replace(tmp_path, abs_path)
61
- except BaseException:
52
+ # The MCP server never exits, restarts or stops draining while a write/rename
53
+ # is inside this section (see call_context.write_io).
54
+ from tokensafe.call_context import write_io
55
+ with write_io():
56
+ fd, tmp_path = tempfile.mkstemp(prefix=".tokensafe_atomic_", dir=directory)
62
57
  try:
63
- os.unlink(tmp_path)
64
- except OSError:
65
- pass
66
- raise
67
- if fsync:
68
- _fsync_directory(directory)
58
+ with os.fdopen(fd, "wb") as handle:
59
+ handle.write(payload)
60
+ handle.flush()
61
+ if fsync:
62
+ os.fsync(handle.fileno())
63
+ os.chmod(tmp_path, mode if mode is not None else 0o600)
64
+ os.replace(tmp_path, abs_path)
65
+ except BaseException:
66
+ try:
67
+ os.unlink(tmp_path)
68
+ except OSError:
69
+ pass
70
+ raise
71
+ if fsync:
72
+ _fsync_directory(directory)
69
73
  return abs_path
70
74
 
71
75
 
@@ -1977,12 +1977,12 @@ _SIDECARS = {
1977
1977
  "spring": (
1978
1978
  "java/src/dev/tokensafe/oumv/OumvSpring.java",
1979
1979
  "OumvSpring.java",
1980
- "6d99e1165b62a8053dcb3ae08bebeb5f6dd7d092e9b39eb98deaf596afd3c4e7",
1980
+ "be638a8886fa6ef4dbe061cf4bb1b18655dce53ca81cc593c2eab4e3098954bf",
1981
1981
  ),
1982
1982
  "php": (
1983
1983
  "php/bin/oumv-php",
1984
1984
  "oumv-php",
1985
- "a075372d575c394d42134b5af62f0f228c271a1ce95984bf4dae9811808945fd",
1985
+ "78cbc1a38c6f4b56387ced827d6ec867d60c66c9d2ecf700204bc19630d7efcd",
1986
1986
  ),
1987
1987
  }
1988
1988
 
@@ -10,7 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  # Backend tag (`vX.Y.Z`); the Go module resolves against the matching `go/vX.Y.Z`,
12
12
  # which the backend release workflow creates alongside it.
13
- BACKEND_RELEASE_TAG = "v0.22.1"
13
+ BACKEND_RELEASE_TAG = "v0.22.2"
14
14
 
15
15
  # Wire version that tag speaks. Printed in briefs so an agent never mixes a
16
16
  # backend release with an older protocol line.
@@ -19,9 +19,9 @@ BACKEND_WIRE_VERSION = "1.8.0"
19
19
  # npm release of `tokensafe-backend-node` that ships the same adapters. The
20
20
  # package has its own semver line (`node/package.json`), so it is pinned
21
21
  # separately from the Go tag; `tokensafe inject` installs exactly this version.
22
- BACKEND_NPM_VERSION = "0.16.0"
22
+ BACKEND_NPM_VERSION = "0.16.1"
23
23
 
24
24
  # NuGet release of `TokenSafe.Oumv.AspNetCore`. It has its own semver line too
25
25
  # (`dotnet/src/TokenSafe.Oumv/TokenSafe.Oumv.csproj`), so tying it to the Go tag
26
26
  # would ask NuGet for a version that does not exist.
27
- BACKEND_DOTNET_VERSION = "0.8.0"
27
+ BACKEND_DOTNET_VERSION = "0.8.1"