tokensafe 4.16.2 → 5.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 (151) 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/README.md +8 -3
  5. package/bin/agy-tokens +1 -1
  6. package/bin/tokensafe +1 -1
  7. package/bin/tokensafe-acp.js +1 -1
  8. package/bin/tokensafe-mcp +1 -1
  9. package/bin/tokensafe.js +1 -1
  10. package/hooks/claude_code_hook.py +49 -45
  11. package/hooks/cursor_hook.py +8 -8
  12. package/hooks/kimi_hook.py +23 -23
  13. package/hooks/post_tool_use.py +6 -6
  14. package/hooks/pre_invocation.py +21 -17
  15. package/hooks/pre_tool_use.py +27 -27
  16. package/hooks/session_start.py +17 -17
  17. package/hooks/stop_hook.py +3 -3
  18. package/hooks/zcode_hook.py +2 -2
  19. package/kimi.plugin.json +2 -2
  20. package/mcp_config.json +1 -1
  21. package/package.json +5 -4
  22. package/plugin.json +1 -1
  23. package/server.json +3 -3
  24. package/src/__init__.py +9 -5
  25. package/src/cli.py +11 -2429
  26. package/src/mcp_server.py +11 -5024
  27. package/src/proxy.py +11 -1803
  28. package/tokensafe/__init__.py +6 -0
  29. package/{src → tokensafe}/acp/__init__.py +2 -2
  30. package/{src → tokensafe}/acp/server.py +5 -5
  31. package/{src → tokensafe}/adapter_core.py +42 -17
  32. package/{src → tokensafe}/agent/__init__.py +1 -1
  33. package/{src → tokensafe}/agent/context.py +4 -4
  34. package/{src → tokensafe}/agent/loop.py +4 -4
  35. package/{src → tokensafe}/agent/providers.py +2 -2
  36. package/{src → tokensafe}/agent/tools.py +2 -2
  37. package/{src → tokensafe}/agent_firewall.py +68 -9
  38. package/{src → tokensafe}/angular_cli.py +4 -4
  39. package/{src → tokensafe}/auto_inject.py +37 -5
  40. package/{src → tokensafe}/batch_editor.py +185 -28
  41. package/tokensafe/batch_search.py +1191 -0
  42. package/{src → tokensafe}/bench/go_target.py +1 -1
  43. package/{src → tokensafe}/bench/mechanics.py +1 -1
  44. package/{src → tokensafe}/bench/react_target.py +1 -1
  45. package/{src → tokensafe}/bench/runner.py +4 -4
  46. package/{src → tokensafe}/benchmark.py +12 -12
  47. package/{src → tokensafe}/benchmark_real.py +18 -18
  48. package/{src → tokensafe}/build_parsers.py +3 -3
  49. package/{src → tokensafe}/bundle_probe.py +1 -1
  50. package/{src → tokensafe}/burn_monitor.py +3 -3
  51. package/{src → tokensafe}/cache_normalizer.py +1 -1
  52. package/tokensafe/cli.py +2490 -0
  53. package/{src → tokensafe}/command_sanitizer.py +94 -26
  54. package/{src → tokensafe}/compaction_recovery.py +5 -5
  55. package/{src → tokensafe}/compactor.py +148 -95
  56. package/{src → tokensafe}/context_index.py +194 -28
  57. package/{src → tokensafe}/cross_stack.py +2 -2
  58. package/{src → tokensafe}/dashboard.py +3 -3
  59. package/{src → tokensafe}/delegation.py +4 -4
  60. package/{src → tokensafe}/dependency_prefetcher.py +1 -1
  61. package/{src → tokensafe}/diff_slicer.py +2 -2
  62. package/{src → tokensafe}/distiller.py +7 -7
  63. package/{src → tokensafe}/distiller_cache.py +3 -3
  64. package/{src → tokensafe}/egress_counter.py +1 -1
  65. package/{src → tokensafe}/environment_auditor.py +7 -7
  66. package/{src → tokensafe}/file_state.py +2 -2
  67. package/{src → tokensafe}/format_invariants.py +1 -1
  68. package/tokensafe/format_parsers/__init__.py +20 -0
  69. package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
  70. package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
  71. package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
  72. package/{src → tokensafe}/format_parsers/json_log.py +1 -1
  73. package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
  74. package/{src → tokensafe}/format_parsers/tabular.py +1 -1
  75. package/{src → tokensafe}/fts_index.py +20 -11
  76. package/{src → tokensafe}/governor.py +143 -31
  77. package/{src → tokensafe}/graph_engine.py +769 -126
  78. package/{src → tokensafe}/guard.py +80 -25
  79. package/{src → tokensafe}/history_compactor.py +407 -133
  80. package/{src → tokensafe}/i18n_catalog.py +39 -14
  81. package/{src → tokensafe}/image_downscale.py +1 -1
  82. package/tokensafe/ingress_staging.py +384 -0
  83. package/{src → tokensafe}/installer.py +118 -61
  84. package/{src → tokensafe}/license_manager.py +9 -67
  85. package/{src → tokensafe}/live_relay.py +2 -2
  86. package/{src → tokensafe}/loop_detector.py +2 -2
  87. package/{src → tokensafe}/mcp_config_manager.py +2 -2
  88. package/{src → tokensafe}/mcp_proxy.py +4 -4
  89. package/tokensafe/mcp_server.py +5664 -0
  90. package/{src → tokensafe}/metrics.py +56 -21
  91. package/{src → tokensafe}/mistakes.py +4 -4
  92. package/{src → tokensafe}/oumv_brief.py +21 -3
  93. package/{src → tokensafe}/oumv_gateway.py +146 -49
  94. package/{src → tokensafe}/oumv_policy.py +1 -1
  95. package/{src → tokensafe}/paths.py +1 -1
  96. package/{src → tokensafe}/project_memory.py +4 -4
  97. package/tokensafe/proxy.py +2075 -0
  98. package/{src → tokensafe}/quality_score.py +4 -4
  99. package/tokensafe/read_baseline.py +192 -0
  100. package/tokensafe/repo_compute.py +332 -0
  101. package/{src → tokensafe}/result_ledger.py +19 -19
  102. package/{src → tokensafe}/retrofit.py +6 -6
  103. package/{src → tokensafe}/savings.py +3 -3
  104. package/tokensafe/schema_slicer.py +1087 -0
  105. package/{src → tokensafe}/scoped_search.py +144 -6
  106. package/{src → tokensafe}/secret_redactor.py +22 -0
  107. package/{src → tokensafe}/session_brief.py +8 -8
  108. package/{src → tokensafe}/skeletonizer.py +89 -26
  109. package/{src → tokensafe}/slicer.py +3 -2
  110. package/{src → tokensafe}/snapshot.py +1 -1
  111. package/{src → tokensafe}/stash.py +1 -1
  112. package/{src → tokensafe}/statusline.py +1 -1
  113. package/{src → tokensafe}/superseded.py +22 -4
  114. package/{src → tokensafe}/team_cache.py +3 -3
  115. package/{src → tokensafe}/telemetry_sync.py +63 -11
  116. package/{src → tokensafe}/test_parsers.py +3 -3
  117. package/{src → tokensafe}/thinking_fold.py +3 -3
  118. package/{src → tokensafe}/tokenizer.py +37 -1
  119. package/{src → tokensafe}/tool_pruner.py +3 -3
  120. package/{src → tokensafe}/transcript_analyzer.py +1 -1
  121. package/{src → tokensafe}/transcript_recall.py +8 -8
  122. package/{src → tokensafe}/type_slicer.py +3 -3
  123. package/{src → tokensafe}/usage_ledger.py +4 -4
  124. package/{src → tokensafe}/version_checker.py +6 -6
  125. package/{src → tokensafe}/web_reader.py +86 -8
  126. package/{src → tokensafe}/workspace_roots.py +2 -2
  127. package/src/batch_search.py +0 -589
  128. package/src/format_parsers/__init__.py +0 -20
  129. package/src/schema_slicer.py +0 -578
  130. /package/{src → tokensafe}/agent/pricing.py +0 -0
  131. /package/{src → tokensafe}/atomic_io.py +0 -0
  132. /package/{src → tokensafe}/backend_release.py +0 -0
  133. /package/{src → tokensafe}/bench/__init__.py +0 -0
  134. /package/{src → tokensafe}/bench/driver.py +0 -0
  135. /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
  136. /package/{src → tokensafe}/bench_scenarios.json +0 -0
  137. /package/{src → tokensafe}/competitors.py +0 -0
  138. /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
  139. /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
  140. /package/{src → tokensafe}/globmatch.py +0 -0
  141. /package/{src → tokensafe}/host_capabilities.py +0 -0
  142. /package/{src → tokensafe}/json_repair.py +0 -0
  143. /package/{src → tokensafe}/route_index.py +0 -0
  144. /package/{src → tokensafe}/scaffold.py +0 -0
  145. /package/{src → tokensafe}/session_context.py +0 -0
  146. /package/{src → tokensafe}/ssl_context.py +0 -0
  147. /package/{src → tokensafe}/stdio_io.py +0 -0
  148. /package/{src → tokensafe}/syntax_guard.py +0 -0
  149. /package/{src → tokensafe}/toml_mcp_config.py +0 -0
  150. /package/{src → tokensafe}/treesitter_backend.py +0 -0
  151. /package/{src → tokensafe}/win_paths.py +0 -0
@@ -168,12 +168,12 @@ class ContextQualityScore:
168
168
  workspace_root: Optional[str] = None
169
169
  ) -> Dict[str, Any]:
170
170
  """Convenience evaluator that fetches current budget, environment audit, and conflicts."""
171
- from src.governor import ContextBudget
172
- from src.environment_auditor import EnvironmentAuditor
173
- from src.competitors import CompetitorAuditor
171
+ from tokensafe.governor import ContextBudget
172
+ from tokensafe.environment_auditor import EnvironmentAuditor
173
+ from tokensafe.competitors import CompetitorAuditor
174
174
 
175
175
  if tracker is None:
176
- from src.metrics import MetricsTracker
176
+ from tokensafe.metrics import MetricsTracker
177
177
  tracker = MetricsTracker()
178
178
 
179
179
  budget = ContextBudget.estimate(
@@ -0,0 +1,192 @@
1
+ """Session-scoped raw file baselines for diff-on-change reads.
2
+
3
+ `smart_read_file(path, diff_since=...)` needs the raw bytes the caller saw last
4
+ time. The firewall cache stores the *rendered* text (a skeleton, a slice, or a
5
+ truncated body), and `file_state` stores only a hash, so neither can serve as a
6
+ diff base. This table keeps the last plain read's raw text per session.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import time
13
+ from typing import Any, Dict, Optional
14
+
15
+ MAX_CONTENT_BYTES = 128 * 1024
16
+ MAX_ROWS_PER_SESSION = 200
17
+ MAX_TOTAL_BYTES = 16 * 1024 * 1024
18
+
19
+ _TABLE_SQL = """
20
+ CREATE TABLE IF NOT EXISTS file_read_baselines (
21
+ session_id TEXT NOT NULL,
22
+ file_path TEXT NOT NULL,
23
+ mtime_ns INTEGER NOT NULL,
24
+ size INTEGER NOT NULL,
25
+ sha256 TEXT NOT NULL,
26
+ content TEXT NOT NULL,
27
+ created_at INTEGER NOT NULL,
28
+ PRIMARY KEY (session_id, file_path)
29
+ )
30
+ """
31
+
32
+
33
+ def enabled() -> bool:
34
+ return os.environ.get("TOKENSAFE_READ_BASELINE", "1").strip().lower() not in (
35
+ "0", "off", "false", "no", "disabled",
36
+ )
37
+
38
+
39
+ def _tracker(tracker: Optional[Any] = None):
40
+ if tracker is not None:
41
+ return tracker
42
+ from tokensafe.metrics import MetricsTracker
43
+
44
+ return MetricsTracker()
45
+
46
+
47
+ def _ensure_table(tracker) -> None:
48
+ with tracker._get_connection() as conn:
49
+ conn.execute(_TABLE_SQL)
50
+ conn.execute(
51
+ "CREATE INDEX IF NOT EXISTS idx_read_baselines_created "
52
+ "ON file_read_baselines(created_at)"
53
+ )
54
+
55
+
56
+ def _abs(path: str) -> str:
57
+ return os.path.abspath(str(path or ""))
58
+
59
+
60
+ def store(
61
+ session_id: str,
62
+ path: str,
63
+ content: str,
64
+ mtime_ns: int = 0,
65
+ sha256: str = "",
66
+ tracker: Optional[Any] = None,
67
+ ) -> bool:
68
+ """Upsert the raw baseline for one file; False when skipped."""
69
+ if not enabled() or not session_id or not path or content is None:
70
+ return False
71
+ blob = str(content)
72
+ size = len(blob.encode("utf-8", "replace"))
73
+ if size > MAX_CONTENT_BYTES:
74
+ return False
75
+ try:
76
+ tracker = _tracker(tracker)
77
+ _ensure_table(tracker)
78
+ with tracker._get_connection() as conn:
79
+ conn.execute(
80
+ """
81
+ INSERT INTO file_read_baselines
82
+ (session_id, file_path, mtime_ns, size, sha256, content, created_at)
83
+ VALUES (?, ?, ?, ?, ?, ?, ?)
84
+ ON CONFLICT(session_id, file_path) DO UPDATE SET
85
+ mtime_ns=excluded.mtime_ns,
86
+ size=excluded.size,
87
+ sha256=excluded.sha256,
88
+ content=excluded.content,
89
+ created_at=excluded.created_at
90
+ """,
91
+ (
92
+ str(session_id),
93
+ _abs(path),
94
+ int(mtime_ns or 0),
95
+ size,
96
+ str(sha256 or ""),
97
+ blob,
98
+ int(time.time()),
99
+ ),
100
+ )
101
+ _prune_session(conn, str(session_id))
102
+ _prune_total(conn)
103
+ return True
104
+ except Exception:
105
+ return False
106
+
107
+
108
+ def get(session_id: str, path: str, tracker: Optional[Any] = None) -> Optional[Dict[str, Any]]:
109
+ """Return the stored baseline row for (session, file), if any."""
110
+ if not enabled() or not session_id or not path:
111
+ return None
112
+ try:
113
+ tracker = _tracker(tracker)
114
+ _ensure_table(tracker)
115
+ with tracker._get_connection() as conn:
116
+ row = conn.execute(
117
+ "SELECT mtime_ns, size, sha256, content, created_at "
118
+ "FROM file_read_baselines WHERE session_id = ? AND file_path = ?",
119
+ (str(session_id), _abs(path)),
120
+ ).fetchone()
121
+ if row is None:
122
+ return None
123
+ if isinstance(row, dict):
124
+ return dict(row)
125
+ return {
126
+ "mtime_ns": row[0],
127
+ "size": row[1],
128
+ "sha256": row[2],
129
+ "content": row[3],
130
+ "created_at": row[4],
131
+ }
132
+ except Exception:
133
+ return None
134
+
135
+
136
+ def was_read(session_id: str, path: str, tracker: Optional[Any] = None) -> bool:
137
+ """Cheap read-history probe used by the blast-radius hint."""
138
+ if not session_id or not path:
139
+ return False
140
+ try:
141
+ tracker = _tracker(tracker)
142
+ _ensure_table(tracker)
143
+ with tracker._get_connection() as conn:
144
+ row = conn.execute(
145
+ "SELECT 1 FROM file_read_baselines WHERE session_id = ? AND file_path = ? LIMIT 1",
146
+ (str(session_id), _abs(path)),
147
+ ).fetchone()
148
+ return row is not None
149
+ except Exception:
150
+ return False
151
+
152
+
153
+ def _prune_session(conn, session_id: str) -> None:
154
+ try:
155
+ conn.execute(
156
+ """
157
+ DELETE FROM file_read_baselines
158
+ WHERE session_id = ?
159
+ AND file_path NOT IN (
160
+ SELECT file_path FROM file_read_baselines
161
+ WHERE session_id = ?
162
+ ORDER BY created_at DESC
163
+ LIMIT ?
164
+ )
165
+ """,
166
+ (session_id, session_id, MAX_ROWS_PER_SESSION),
167
+ )
168
+ except Exception:
169
+ pass
170
+
171
+
172
+ def _prune_total(conn) -> None:
173
+ try:
174
+ row = conn.execute("SELECT COALESCE(SUM(size), 0) FROM file_read_baselines").fetchone()
175
+ total = int((row[0] if row else 0) or 0)
176
+ if total <= MAX_TOTAL_BYTES:
177
+ return
178
+ target = int(MAX_TOTAL_BYTES * 0.75)
179
+ while total > target:
180
+ oldest = conn.execute(
181
+ "SELECT session_id, file_path, size FROM file_read_baselines "
182
+ "ORDER BY created_at ASC LIMIT 1"
183
+ ).fetchone()
184
+ if oldest is None:
185
+ break
186
+ conn.execute(
187
+ "DELETE FROM file_read_baselines WHERE session_id = ? AND file_path = ?",
188
+ (oldest[0], oldest[1]),
189
+ )
190
+ total -= int(oldest[2] or 0)
191
+ except Exception:
192
+ pass
@@ -0,0 +1,332 @@
1
+ """Out-of-context compute over repository files.
2
+
3
+ A restricted Python program receives already-read file contents in memory and
4
+ returns one JSON result. Inputs never enter the model context; only the result
5
+ does. This is a cooperative sandbox (AST allowlist + restricted builtins +
6
+ rlimits + repo path jail), not a security boundary against a determined escape.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import glob as _glob
13
+ import json
14
+ import os
15
+ import signal
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import time
20
+ from typing import Any, Dict, Iterable, List, Tuple
21
+
22
+ try: # POSIX-only rlimits; the timeout still applies on Windows.
23
+ import resource
24
+ except ImportError: # pragma: no cover - Windows
25
+ resource = None # type: ignore[assignment]
26
+
27
+ MAX_PROGRAM_CHARS = 20_000
28
+ MAX_FILES = 200
29
+ MAX_INPUT_BYTES = 5 * 1024 * 1024
30
+ MAX_RESULT_BYTES = 64 * 1024
31
+ DEFAULT_TIMEOUT_MS = 5000
32
+ MAX_TIMEOUT_MS = 15_000
33
+ MAX_FILE_BYTES = 512 * 1024
34
+
35
+ ALLOWED_IMPORTS = frozenset({
36
+ "json", "re", "math", "statistics", "collections", "itertools", "functools",
37
+ "operator", "string", "datetime", "decimal", "fractions", "heapq", "bisect",
38
+ "textwrap", "unicodedata",
39
+ })
40
+ BANNED_NAMES = frozenset({
41
+ "open", "exec", "eval", "compile", "__import__", "globals", "locals", "vars",
42
+ "getattr", "setattr", "delattr", "input", "breakpoint", "exit", "quit", "help",
43
+ })
44
+ IGNORED_DIRS = frozenset({
45
+ ".git", ".hg", ".svn", "node_modules", ".venv", "venv", "__pycache__",
46
+ "dist", "build", ".next", ".tokensafe", ".mypy_cache", ".pytest_cache",
47
+ })
48
+
49
+ _HARNESS = r'''
50
+ import builtins, json, sys
51
+
52
+ SAFE_IMPORTS = set(json.loads(sys.argv[4]))
53
+ _real_import = builtins.__import__
54
+
55
+
56
+ def _safe_import(name, globals=None, locals=None, fromlist=(), level=0):
57
+ if level != 0 or name.split(".")[0] not in SAFE_IMPORTS:
58
+ raise ImportError("import not allowed: " + str(name))
59
+ return _real_import(name, globals, locals, fromlist, level)
60
+
61
+
62
+ _BUILTIN_NAMES = (
63
+ "abs", "all", "any", "bool", "dict", "enumerate", "filter", "float", "format",
64
+ "frozenset", "int", "isinstance", "issubclass", "iter", "len", "list", "map",
65
+ "max", "min", "next", "ord", "pow", "range", "repr", "reversed", "round", "set",
66
+ "slice", "sorted", "str", "sum", "tuple", "type", "zip", "Exception",
67
+ "ValueError", "TypeError", "KeyError", "IndexError", "RuntimeError",
68
+ "ZeroDivisionError", "AttributeError", "StopIteration",
69
+ )
70
+ SAFE_BUILTINS = {name: getattr(builtins, name) for name in _BUILTIN_NAMES}
71
+ SAFE_BUILTINS["__import__"] = _safe_import
72
+
73
+ with open(sys.argv[1], "r", encoding="utf-8", errors="replace") as _fh:
74
+ INPUT = json.load(_fh)
75
+ with open(sys.argv[2], "r", encoding="utf-8", errors="replace") as _fh:
76
+ _source = _fh.read()
77
+
78
+ _scope = {"INPUT": INPUT, "__builtins__": SAFE_BUILTINS, "__name__": "__compute__"}
79
+ try:
80
+ exec(compile(_source, "<compute>", "exec"), _scope)
81
+ except Exception as _exc:
82
+ print(json.dumps({"ok": False, "error": "program_error",
83
+ "message": type(_exc).__name__ + ": " + str(_exc)}))
84
+ raise SystemExit(0)
85
+ if "RESULT" not in _scope:
86
+ print(json.dumps({"ok": False, "error": "no_result"}))
87
+ raise SystemExit(0)
88
+ try:
89
+ _payload = json.dumps({"ok": True, "result": _scope["RESULT"]},
90
+ ensure_ascii=False, default=str)
91
+ except Exception as _exc:
92
+ print(json.dumps({"ok": False, "error": "invalid_result",
93
+ "message": type(_exc).__name__ + ": " + str(_exc)}))
94
+ raise SystemExit(0)
95
+ _limit = int(sys.argv[3])
96
+ if len(_payload.encode("utf-8", "replace")) > _limit:
97
+ print(json.dumps({"ok": False, "error": "result_too_large"}))
98
+ raise SystemExit(0)
99
+ print(_payload)
100
+ '''
101
+
102
+
103
+ class ComputeError(Exception):
104
+ def __init__(self, code: str, message: str = ""):
105
+ super().__init__(message or code)
106
+ self.code = code
107
+ self.message = message or code
108
+
109
+
110
+ def _validate_program(program: str) -> None:
111
+ if not program or not program.strip():
112
+ raise ComputeError("empty_program")
113
+ if len(program) > MAX_PROGRAM_CHARS:
114
+ raise ComputeError("program_too_large")
115
+ try:
116
+ tree = ast.parse(program, mode="exec")
117
+ except SyntaxError as exc:
118
+ raise ComputeError("syntax_error", f"{exc.msg} at line {exc.lineno}") from exc
119
+ for node in ast.walk(tree):
120
+ if isinstance(node, ast.Import):
121
+ for alias in node.names:
122
+ if alias.name.split(".")[0] not in ALLOWED_IMPORTS:
123
+ raise ComputeError("import_not_allowed", alias.name)
124
+ elif isinstance(node, ast.ImportFrom):
125
+ module = (node.module or "").split(".")[0]
126
+ if node.level != 0 or module not in ALLOWED_IMPORTS:
127
+ raise ComputeError("import_not_allowed", node.module or "<relative>")
128
+ elif isinstance(node, ast.Name) and node.id in BANNED_NAMES:
129
+ raise ComputeError("name_not_allowed", node.id)
130
+ elif isinstance(node, ast.Attribute):
131
+ if node.attr.startswith("__") or node.attr.endswith("__"):
132
+ raise ComputeError("dunder_attribute", node.attr)
133
+
134
+
135
+ def _iter_candidate_paths(root: str, patterns: Iterable[str]) -> List[str]:
136
+ found: List[str] = []
137
+ seen = set()
138
+ for pattern in patterns:
139
+ raw = str(pattern or "").strip()
140
+ if not raw:
141
+ continue
142
+ if os.path.isabs(raw):
143
+ candidates = [raw]
144
+ else:
145
+ candidates = _glob.glob(os.path.join(root, raw), recursive=True)
146
+ for candidate in candidates:
147
+ real = os.path.realpath(candidate)
148
+ if not real.startswith(os.path.realpath(root) + os.sep) and real != os.path.realpath(root):
149
+ raise ComputeError("path_outside_root", raw)
150
+ if not os.path.isfile(real):
151
+ continue
152
+ if any(part in IGNORED_DIRS for part in real.split(os.sep)):
153
+ continue
154
+ if real in seen:
155
+ continue
156
+ seen.add(real)
157
+ found.append(real)
158
+ if len(found) >= MAX_FILES:
159
+ return found
160
+ return found
161
+
162
+
163
+ def _read_inputs(root: str, patterns: Iterable[str]) -> Tuple[List[Dict[str, str]], int, Dict[str, int]]:
164
+ paths = _iter_candidate_paths(root, patterns)
165
+ files: List[Dict[str, str]] = []
166
+ total = 0
167
+ skipped = {"missing": 0, "binary": 0, "too_large": 0}
168
+ for path in paths:
169
+ try:
170
+ size = os.path.getsize(path)
171
+ except OSError:
172
+ skipped["missing"] += 1
173
+ continue
174
+ if size > MAX_FILE_BYTES:
175
+ skipped["too_large"] += 1
176
+ continue
177
+ try:
178
+ with open(path, "rb") as fh:
179
+ blob = fh.read()
180
+ except OSError:
181
+ skipped["missing"] += 1
182
+ continue
183
+ if b"\x00" in blob[:4096]:
184
+ skipped["binary"] += 1
185
+ continue
186
+ total += len(blob)
187
+ if total > MAX_INPUT_BYTES:
188
+ raise ComputeError("input_too_large", f"{total} bytes")
189
+ files.append({
190
+ "path": os.path.relpath(path, root).replace(os.sep, "/"),
191
+ "text": blob.decode("utf-8", "replace"),
192
+ })
193
+ return files, total, skipped
194
+
195
+
196
+ def _limits(timeout_s: int):
197
+ def _apply() -> None:
198
+ if resource is None:
199
+ return
200
+ try:
201
+ resource.setrlimit(resource.RLIMIT_CPU, (timeout_s + 1, timeout_s + 1))
202
+ resource.setrlimit(resource.RLIMIT_AS, (512 * 1024 * 1024, 512 * 1024 * 1024))
203
+ resource.setrlimit(resource.RLIMIT_FSIZE, (1024 * 1024, 1024 * 1024))
204
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
205
+ except Exception:
206
+ pass
207
+
208
+ return _apply
209
+
210
+
211
+ def run(
212
+ program: str,
213
+ paths: Any,
214
+ root: str = "",
215
+ timeout_ms: int = DEFAULT_TIMEOUT_MS,
216
+ max_result_bytes: int = MAX_RESULT_BYTES,
217
+ ) -> Dict[str, Any]:
218
+ """Run one restricted program over repository files; return its JSON result."""
219
+ started = time.time()
220
+ try:
221
+ _validate_program(program)
222
+ root_real = os.path.realpath(str(root or os.getcwd()))
223
+ from tokensafe.paths import is_plugin_or_system_dir
224
+
225
+ if is_plugin_or_system_dir(root_real):
226
+ raise ComputeError("root_refused", root_real)
227
+ if not os.path.isdir(root_real):
228
+ raise ComputeError("invalid_root", root_real)
229
+ if isinstance(paths, str):
230
+ patterns = [paths]
231
+ elif isinstance(paths, (list, tuple)):
232
+ patterns = [str(item) for item in paths if str(item or "").strip()]
233
+ else:
234
+ patterns = []
235
+ if not patterns:
236
+ raise ComputeError("paths_required")
237
+ files, input_bytes, skipped = _read_inputs(root_real, patterns)
238
+ timeout_ms = max(100, min(int(timeout_ms or DEFAULT_TIMEOUT_MS), MAX_TIMEOUT_MS))
239
+ timeout_s = max(1, int(round(timeout_ms / 1000.0)))
240
+ max_result_bytes = max(1024, min(int(max_result_bytes or MAX_RESULT_BYTES), MAX_RESULT_BYTES))
241
+ except ComputeError as exc:
242
+ return {"ok": False, "error": exc.code, "message": exc.message}
243
+
244
+ with tempfile.TemporaryDirectory(prefix="tokensafe-compute-") as tmp:
245
+ harness_path = os.path.join(tmp, "harness.py")
246
+ program_path = os.path.join(tmp, "program.py")
247
+ input_path = os.path.join(tmp, "input.json")
248
+ with open(harness_path, "w", encoding="utf-8") as fh:
249
+ fh.write(_HARNESS)
250
+ with open(program_path, "w", encoding="utf-8") as fh:
251
+ fh.write(program)
252
+ with open(input_path, "w", encoding="utf-8") as fh:
253
+ json.dump({"root": root_real, "files": files}, fh, ensure_ascii=False)
254
+
255
+ env = {
256
+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
257
+ "HOME": tmp,
258
+ "TMPDIR": tmp,
259
+ "LANG": "C.UTF-8",
260
+ "LC_ALL": "C.UTF-8",
261
+ "PYTHONHASHSEED": "0",
262
+ }
263
+ preexec = _limits(timeout_s) if os.name == "posix" else None
264
+ try:
265
+ proc = subprocess.Popen(
266
+ [
267
+ sys.executable, "-I", "-S", harness_path,
268
+ input_path, program_path, str(max_result_bytes),
269
+ json.dumps(sorted(ALLOWED_IMPORTS)),
270
+ ],
271
+ cwd=tmp,
272
+ stdout=subprocess.PIPE,
273
+ stderr=subprocess.PIPE,
274
+ text=True,
275
+ env=env,
276
+ preexec_fn=preexec,
277
+ start_new_session=True,
278
+ )
279
+ except Exception as exc:
280
+ return {"ok": False, "error": "spawn_failed", "message": str(exc)}
281
+
282
+ timed_out = False
283
+ try:
284
+ stdout, stderr = proc.communicate(timeout=timeout_s)
285
+ except subprocess.TimeoutExpired:
286
+ timed_out = True
287
+ try:
288
+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
289
+ except Exception:
290
+ pass
291
+ try:
292
+ stdout, stderr = proc.communicate(timeout=2)
293
+ except Exception:
294
+ stdout, stderr = "", ""
295
+ elapsed_ms = int((time.time() - started) * 1000)
296
+ if timed_out:
297
+ return {
298
+ "ok": False,
299
+ "error": "timeout",
300
+ "files_read": len(files),
301
+ "input_bytes": input_bytes,
302
+ "elapsed_ms": elapsed_ms,
303
+ }
304
+ if len(stdout.encode("utf-8", "replace")) > max_result_bytes + 4096:
305
+ return {"ok": False, "error": "result_too_large", "elapsed_ms": elapsed_ms}
306
+ lines = [line for line in (stdout or "").splitlines() if line.strip()]
307
+ if not lines:
308
+ return {
309
+ "ok": False,
310
+ "error": "program_failed",
311
+ "message": (stderr or "")[:500],
312
+ "files_read": len(files),
313
+ "input_bytes": input_bytes,
314
+ "elapsed_ms": elapsed_ms,
315
+ }
316
+ try:
317
+ payload = json.loads(lines[-1])
318
+ except json.JSONDecodeError:
319
+ return {
320
+ "ok": False,
321
+ "error": "invalid_json",
322
+ "message": (stdout or "")[:500],
323
+ "elapsed_ms": elapsed_ms,
324
+ }
325
+ if not isinstance(payload, dict):
326
+ return {"ok": False, "error": "invalid_json", "elapsed_ms": elapsed_ms}
327
+ payload.setdefault("files_read", len(files))
328
+ payload.setdefault("input_bytes", input_bytes)
329
+ payload.setdefault("result_bytes", len(stdout.encode("utf-8", "replace")))
330
+ payload.setdefault("elapsed_ms", elapsed_ms)
331
+ payload.setdefault("skipped", skipped)
332
+ return payload
@@ -28,7 +28,7 @@ import os
28
28
  import re
29
29
  from typing import Any, Dict, List, Optional, Tuple
30
30
 
31
- from src.tokenizer import count_tokens
31
+ from tokensafe.tokenizer import count_tokens
32
32
 
33
33
  # Deterministic marker used both for idempotence detection and as the model-
34
34
  # visible anchor header. No timestamps, no hit counters (KV-cache stability).
@@ -40,8 +40,8 @@ TAIL_LINES = 12
40
40
 
41
41
  # Tool classification reused from the history compactor (same vocabulary the
42
42
  # whole product uses for read/edit/command tools).
43
- from src.history_compactor import _COMMAND_TOOLS, _READ_TOOLS # noqa: E402
44
- from src.history_compactor import _arg_value, _COMMAND_KEYS, _PATH_KEYS # noqa: E402
43
+ from tokensafe.history_compactor import _COMMAND_TOOLS, _READ_TOOLS # noqa: E402
44
+ from tokensafe.history_compactor import _arg_value, _COMMAND_KEYS, _PATH_KEYS # noqa: E402
45
45
 
46
46
  _LANG_EXT_MAP = {
47
47
  "py": ".py", "python": ".py", "ts": ".ts", "tsx": ".tsx", "js": ".js",
@@ -66,7 +66,7 @@ def _archive_result(text: str, sha: str) -> Optional[str]:
66
66
  if len(text) > MAX_ARCHIVE_CHARS:
67
67
  return None
68
68
  try:
69
- from src.paths import resolve_data_dir
69
+ from tokensafe.paths import resolve_data_dir
70
70
  archive_dir = os.path.join(resolve_data_dir(), ARCHIVE_DIRNAME)
71
71
  os.makedirs(archive_dir, exist_ok=True)
72
72
  path = os.path.join(archive_dir, f"{sha[:16]}.json")
@@ -87,7 +87,7 @@ def prune_archives(max_files: int = 2000, max_age_days: float = 30.0) -> int:
87
87
  import time
88
88
 
89
89
  try:
90
- from src.paths import resolve_data_dir
90
+ from tokensafe.paths import resolve_data_dir
91
91
 
92
92
  archive_dir = os.path.join(resolve_data_dir(), ARCHIVE_DIRNAME)
93
93
  names = os.listdir(archive_dir)
@@ -130,7 +130,7 @@ def _compact_read_result(text: str, path: str) -> Optional[str]:
130
130
  Produces candidates when possible and returns the shortest — the
131
131
  skeleton only wins when it actually compresses substantially."""
132
132
  try:
133
- from src.format_parsers.lockfiles import LockfileReducer
133
+ from tokensafe.format_parsers.lockfiles import LockfileReducer
134
134
  if LockfileReducer.is_lockfile(path):
135
135
  compacted_l, was_l = LockfileReducer.reduce(text, path)
136
136
  if was_l:
@@ -139,7 +139,7 @@ def _compact_read_result(text: str, path: str) -> Optional[str]:
139
139
  pass
140
140
 
141
141
  try:
142
- from src.format_parsers.i18n_strings import StringCatalogReducer
142
+ from tokensafe.format_parsers.i18n_strings import StringCatalogReducer
143
143
  if StringCatalogReducer.is_string_catalog(path):
144
144
  compacted_c, was_c = StringCatalogReducer.reduce(text, path)
145
145
  if was_c:
@@ -152,7 +152,7 @@ def _compact_read_result(text: str, path: str) -> Optional[str]:
152
152
  lines = text.splitlines()
153
153
  if ext and ext in list(_LANG_EXT_MAP.values()) and len(lines) >= 25:
154
154
  try:
155
- from src.skeletonizer import Skeletonizer
155
+ from tokensafe.skeletonizer import Skeletonizer
156
156
  skel = Skeletonizer.skeletonize_code(text, ext)
157
157
  if skel and count_tokens(skel) < count_tokens(text) * 0.6:
158
158
  candidates.append(
@@ -198,7 +198,7 @@ def fold_catalog_results(
198
198
  pass into millions of input tokens. This stage is therefore age-blind,
199
199
  path-aware when the host passes a path, and idempotent by marker.
200
200
  """
201
- from src.format_parsers.i18n_strings import StringCatalogReducer, sniff
201
+ from tokensafe.format_parsers.i18n_strings import StringCatalogReducer, sniff
202
202
 
203
203
  stats: Dict[str, Any] = {"folded": 0, "orig_tokens": 0, "new_tokens": 0, "saved_tokens": 0}
204
204
  if not messages or not _env_flag("TOKENSAFE_TOOL_LEDGER"):
@@ -243,7 +243,7 @@ def fold_catalog_results(
243
243
 
244
244
  if stats["folded"] and record_metrics:
245
245
  try:
246
- from src.metrics import MetricsTracker
246
+ from tokensafe.metrics import MetricsTracker
247
247
  MetricsTracker().record_event(
248
248
  session_id=session_id,
249
249
  event_type="CATALOG_FOLD",
@@ -260,28 +260,28 @@ def fold_catalog_results(
260
260
  def _compact_command_result(text: str) -> Optional[str]:
261
261
  """Test summaries first (PASS: ...), build/docker/log compaction next, log-style head/tail otherwise."""
262
262
  try:
263
- from src.test_parsers import TestOutputParser
263
+ from tokensafe.test_parsers import TestOutputParser
264
264
  compacted, was_test = TestOutputParser.compact(text)
265
265
  if was_test:
266
266
  return compacted
267
267
  except Exception:
268
268
  pass
269
269
  try:
270
- from src.build_parsers import BuildOutputParser
270
+ from tokensafe.build_parsers import BuildOutputParser
271
271
  compacted_b, was_b = BuildOutputParser.compact(text)
272
272
  if was_b:
273
273
  return compacted_b
274
274
  except Exception:
275
275
  pass
276
276
  try:
277
- from src.format_parsers.docker_k8s import ContainerAndK8sReducer
277
+ from tokensafe.format_parsers.docker_k8s import ContainerAndK8sReducer
278
278
  compacted_d, was_d = ContainerAndK8sReducer.reduce_docker_build(text)
279
279
  if was_d:
280
280
  return compacted_d
281
281
  except Exception:
282
282
  pass
283
283
  try:
284
- from src.format_parsers.json_log import JSONLogReducer
284
+ from tokensafe.format_parsers.json_log import JSONLogReducer
285
285
  if JSONLogReducer.is_ndjson_log(text):
286
286
  compacted_j, was_j = JSONLogReducer.reduce(text)
287
287
  if was_j:
@@ -289,7 +289,7 @@ def _compact_command_result(text: str) -> Optional[str]:
289
289
  except Exception:
290
290
  pass
291
291
  try:
292
- from src.command_sanitizer import CommandSanitizer
292
+ from tokensafe.command_sanitizer import CommandSanitizer
293
293
  compacted = CommandSanitizer.compact_test_output(text, 0)
294
294
  if compacted is not text and len(compacted) < len(text) * 0.6:
295
295
  return compacted + "\n[... full output archived]"
@@ -310,10 +310,10 @@ def _maybe_distill_history(text: str) -> Optional[str]:
310
310
  if not _env_flag("TOKENSAFE_HISTORY_DISTILL", "0"):
311
311
  return None
312
312
  try:
313
- from src.distiller import UniversalDistiller
313
+ from tokensafe.distiller import UniversalDistiller
314
314
  tier, _lic = None, None
315
315
  try:
316
- from src.license_manager import LicenseManager
316
+ from tokensafe.license_manager import LicenseManager
317
317
  tier, _lic = LicenseManager.get_active_license()
318
318
  except Exception:
319
319
  return None
@@ -483,7 +483,7 @@ def fold_tool_results(
483
483
 
484
484
  total_saved = sum(max(0, orig_t - new_t) for _, _, _, _, _, orig_t, new_t, _ in pending)
485
485
  earliest_idx = pending[0][0]
486
- from src.burn_monitor import evaluate_fold_roi
486
+ from tokensafe.burn_monitor import evaluate_fold_roi
487
487
  roi = evaluate_fold_roi(
488
488
  messages,
489
489
  earliest_fold_idx=earliest_idx,
@@ -511,7 +511,7 @@ def fold_tool_results(
511
511
 
512
512
  if stats["folded"] and record_metrics:
513
513
  try:
514
- from src.metrics import MetricsTracker
514
+ from tokensafe.metrics import MetricsTracker
515
515
  MetricsTracker().record_event(
516
516
  session_id=session_id,
517
517
  event_type="TOOL_LEDGER",