tokensafe 4.12.3 → 4.13.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/.codex-plugin/plugin.json +1 -1
- package/README.md +8 -6
- package/hooks/pre_invocation.py +8 -4
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +4 -3
- package/server.json +3 -3
- package/src/auto_inject.py +1026 -279
- package/src/backend_release.py +10 -0
- package/src/batch_editor.py +18 -8
- package/src/batch_search.py +39 -16
- package/src/bundle_probe.py +205 -0
- package/src/cli.py +76 -7
- package/src/fts_index.py +9 -0
- package/src/globmatch.py +124 -0
- package/src/governor.py +120 -44
- package/src/graph_engine.py +292 -14
- package/src/installer.py +3 -3
- package/src/mcp_server.py +153 -35
- package/src/metrics.py +7 -0
- package/src/oumv_brief.py +346 -0
- package/src/oumv_gateway.py +132 -43
- package/src/proxy.py +6 -5
- package/src/quality_score.py +46 -24
- package/src/retrofit.py +35 -11
- package/src/savings.py +1 -0
- package/src/scoped_search.py +238 -9
- package/src/session_brief.py +6 -1
- package/src/telemetry_sync.py +1 -1
- package/src/treesitter_backend.py +26 -1
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +42 -0
- package/src/workspace_roots.py +246 -0
|
@@ -427,6 +427,7 @@ class TreeSitterBackend:
|
|
|
427
427
|
lines = code.splitlines()
|
|
428
428
|
imports: List[str] = []
|
|
429
429
|
imported_symbols: List[str] = []
|
|
430
|
+
glob_imports: List[str] = []
|
|
430
431
|
symbols: List[Dict[str, Any]] = []
|
|
431
432
|
seen_keys: Set[str] = set()
|
|
432
433
|
calls: List[Tuple[str, str]] = []
|
|
@@ -440,12 +441,35 @@ class TreeSitterBackend:
|
|
|
440
441
|
ext == ".rb" and ntype == "call"
|
|
441
442
|
and cls._node_text(node, code_bytes).lstrip().startswith(("require", "require_relative"))
|
|
442
443
|
)
|
|
443
|
-
|
|
444
|
+
# `export { X } from './x'` carries an import edge; a plain
|
|
445
|
+
# `export const x = 'literal'` must not be read as one.
|
|
446
|
+
is_export_from = (
|
|
447
|
+
ntype == "export_statement"
|
|
448
|
+
and ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs")
|
|
449
|
+
and bool(re.search(r"\bfrom\s*['\"]", cls._node_text(node, code_bytes)[:400]))
|
|
450
|
+
)
|
|
451
|
+
if ntype in _IMPORT_NODE_TYPES or is_ruby_require or is_export_from:
|
|
444
452
|
mods, syms = cls._extract_imports_from_node(node, code_bytes, ext)
|
|
445
453
|
imports.extend(mods)
|
|
446
454
|
imported_symbols.extend(syms)
|
|
447
455
|
return
|
|
448
456
|
|
|
457
|
+
# Dynamic import and Vite glob calls are call_expressions whose
|
|
458
|
+
# function token is the bare `import`; the import branch above never
|
|
459
|
+
# sees them, so lazy routes had no file->file edge.
|
|
460
|
+
if ntype in ("call_expression", "call") and ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"):
|
|
461
|
+
raw = cls._node_text(node, code_bytes).lstrip()[:2000]
|
|
462
|
+
if re.match(r"^import\s*\(", raw):
|
|
463
|
+
for lit in re.findall(r"""['"]([^'"]+)['"]""", raw[:400]):
|
|
464
|
+
if lit:
|
|
465
|
+
imports.append(lit)
|
|
466
|
+
return
|
|
467
|
+
if re.match(r"^import\s*\.\s*meta\s*\.\s*glob(?:Eager)?\s*\(", raw):
|
|
468
|
+
for lit in re.findall(r"""['"`]([^'"`]+)['"`]""", raw):
|
|
469
|
+
if lit and "${" not in lit:
|
|
470
|
+
glob_imports.append(lit)
|
|
471
|
+
return
|
|
472
|
+
|
|
449
473
|
# Go `type Foo struct { ... }` / `type Foo interface { ... }`
|
|
450
474
|
is_go_type = (
|
|
451
475
|
ext == ".go"
|
|
@@ -522,6 +546,7 @@ class TreeSitterBackend:
|
|
|
522
546
|
return {
|
|
523
547
|
"imports": imports,
|
|
524
548
|
"imported_symbols": imported_symbols,
|
|
549
|
+
"glob_imports": glob_imports,
|
|
525
550
|
"symbols": symbols,
|
|
526
551
|
"calls": calls,
|
|
527
552
|
}
|
package/src/version_checker.py
CHANGED
|
@@ -17,7 +17,7 @@ import urllib.request
|
|
|
17
17
|
import urllib.error
|
|
18
18
|
from typing import Dict, Any, Optional, Tuple
|
|
19
19
|
|
|
20
|
-
CURRENT_VERSION = "4.
|
|
20
|
+
CURRENT_VERSION = "4.13.1"
|
|
21
21
|
CACHE_TTL = 86400 # 24 hours
|
|
22
22
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
23
23
|
# answer for a full day — otherwise an update released right after an outage
|
package/src/web_reader.py
CHANGED
|
@@ -500,5 +500,47 @@ class WebReader:
|
|
|
500
500
|
cls.last_tier = "error"
|
|
501
501
|
return "", False, f"Fetch error: {e}"
|
|
502
502
|
|
|
503
|
+
@classmethod
|
|
504
|
+
def fetch_raw(
|
|
505
|
+
cls,
|
|
506
|
+
url: str,
|
|
507
|
+
timeout: float = 3.0,
|
|
508
|
+
max_bytes: int = 2 * 1024 * 1024,
|
|
509
|
+
accept: str = "*/*",
|
|
510
|
+
) -> Tuple[Optional[int], bytes, Dict[str, str], Optional[str]]:
|
|
511
|
+
"""Fetches exact bytes (no HTML→Markdown, no shared cache).
|
|
512
|
+
|
|
513
|
+
Deploy probes need the raw hashed chunk and the HTTP status; `fetch_url`
|
|
514
|
+
exists to hand clean Markdown to a model. The SSRF and redirect guards
|
|
515
|
+
are shared with `fetch_url`.
|
|
516
|
+
Returns (status, body, headers, error).
|
|
517
|
+
"""
|
|
518
|
+
if not cls.is_safe_url(url):
|
|
519
|
+
return None, b"", {}, f"Refused to fetch potentially unsafe or internal URL: {url}"
|
|
520
|
+
headers = {
|
|
521
|
+
"User-Agent": "Mozilla/5.0 (compatible; TokenSafeProbe/4.13; +https://tokensafe.dev)",
|
|
522
|
+
"Accept": accept,
|
|
523
|
+
"Cache-Control": "no-cache",
|
|
524
|
+
}
|
|
525
|
+
req = urllib.request.Request(url, headers=headers)
|
|
526
|
+
try:
|
|
527
|
+
opener = urllib.request.build_opener(_SafeRedirectHandler)
|
|
528
|
+
with opener.open(req, timeout=timeout) as resp:
|
|
529
|
+
status = int(getattr(resp, "status", 0) or 0)
|
|
530
|
+
raw = resp.read(max_bytes + 1)
|
|
531
|
+
if len(raw) > max_bytes:
|
|
532
|
+
raw = raw[:max_bytes]
|
|
533
|
+
hdrs = {k.lower(): v for k, v in resp.headers.items()}
|
|
534
|
+
return status, raw, hdrs, None
|
|
535
|
+
except urllib.error.HTTPError as e:
|
|
536
|
+
body = b""
|
|
537
|
+
try:
|
|
538
|
+
body = e.read(max_bytes)
|
|
539
|
+
except Exception:
|
|
540
|
+
pass
|
|
541
|
+
return int(getattr(e, "code", 0) or 0), body, {}, f"HTTP Error {getattr(e, 'code', '')}"
|
|
542
|
+
except Exception as e:
|
|
543
|
+
return None, b"", {}, f"Fetch error: {e}"
|
|
544
|
+
|
|
503
545
|
|
|
504
546
|
sanitize_url = WebReader.sanitize_url
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Per-server workspace roots and one path resolver for every MCP tool.
|
|
2
|
+
|
|
3
|
+
Hosts that open several folders (ZCode sends ``workspacePaths``) previously had
|
|
4
|
+
that list consumed only by the routing brief: relative paths resolved against
|
|
5
|
+
the server's spawn cwd, ``apply_edits`` refused absolute paths outright, and the
|
|
6
|
+
error never said which root was tried. This module keeps the roots the host
|
|
7
|
+
declared and resolves every path through one function with one error shape
|
|
8
|
+
(``resolved against: ...`` + ``known roots: ...``).
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import threading
|
|
14
|
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
|
15
|
+
|
|
16
|
+
from src.paths import is_plugin_or_system_dir
|
|
17
|
+
|
|
18
|
+
_LOCK = threading.Lock()
|
|
19
|
+
_ROOTS: List[str] = []
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _clean(path: Any) -> Optional[str]:
|
|
23
|
+
"""Absolute, real, existing directory that may act as a workspace root."""
|
|
24
|
+
try:
|
|
25
|
+
p = os.path.realpath(os.path.abspath(os.path.expanduser(str(path))))
|
|
26
|
+
except (OSError, ValueError, TypeError):
|
|
27
|
+
return None
|
|
28
|
+
if not p or not os.path.isdir(p) or is_plugin_or_system_dir(p):
|
|
29
|
+
return None
|
|
30
|
+
return p
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def register_roots(paths: Iterable[Any]) -> List[str]:
|
|
34
|
+
"""Adds every usable root once; returns the roots added by this call."""
|
|
35
|
+
added: List[str] = []
|
|
36
|
+
with _LOCK:
|
|
37
|
+
for raw in paths or ():
|
|
38
|
+
p = _clean(raw)
|
|
39
|
+
if p and p not in _ROOTS:
|
|
40
|
+
_ROOTS.append(p)
|
|
41
|
+
added.append(p)
|
|
42
|
+
return added
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def register_root(path: Any) -> Optional[str]:
|
|
46
|
+
added = register_roots([path])
|
|
47
|
+
return added[0] if added else None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def known_roots() -> List[str]:
|
|
51
|
+
with _LOCK:
|
|
52
|
+
return list(_ROOTS)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def reset_roots(paths: Iterable[Any] = ()) -> List[str]:
|
|
56
|
+
"""Replaces the registry (tests and a host that re-sends workspacePaths)."""
|
|
57
|
+
with _LOCK:
|
|
58
|
+
_ROOTS.clear()
|
|
59
|
+
return register_roots(paths)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _within(root: str, path: str) -> bool:
|
|
63
|
+
try:
|
|
64
|
+
real_root = os.path.realpath(root)
|
|
65
|
+
real_path = os.path.realpath(path)
|
|
66
|
+
return os.path.commonpath([real_root, real_path]) == real_root
|
|
67
|
+
except (OSError, ValueError):
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _fmt_roots(roots: List[str]) -> str:
|
|
72
|
+
return ", ".join(f"'{r}'" for r in roots) if roots else "none registered"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _meta(resolved_against: Optional[str], root: Optional[str], raw: str, absolute: bool) -> Dict[str, Any]:
|
|
76
|
+
return {
|
|
77
|
+
"input": raw,
|
|
78
|
+
"resolvedAgainst": resolved_against,
|
|
79
|
+
"root": root,
|
|
80
|
+
"absoluteInput": absolute,
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _outside_write_error(raw: str, roots: List[str]) -> str:
|
|
85
|
+
return (
|
|
86
|
+
f"path '{raw}' is outside every known workspace root ({_fmt_roots(roots)}). "
|
|
87
|
+
"Writes are confined to a registered root; pass 'root' (the repo root) plus a "
|
|
88
|
+
"repo-relative path, or an absolute path inside 'root'."
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _not_found_error(raw: str, tried: List[str], roots: List[str]) -> str:
|
|
93
|
+
tried_s = ", ".join(f"'{t}'" for t in tried) if tried else "none"
|
|
94
|
+
return (
|
|
95
|
+
f"path '{raw}' does not exist (resolved against: {tried_s}; known roots: {_fmt_roots(roots)}). "
|
|
96
|
+
"Pass 'root' (the repo root) plus a repo-relative path, or an absolute path."
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def resolve_input_path(
|
|
101
|
+
raw: Any,
|
|
102
|
+
*,
|
|
103
|
+
base: Optional[Any] = None,
|
|
104
|
+
mode: str = "read",
|
|
105
|
+
must_exist: bool = True,
|
|
106
|
+
roots: Optional[List[str]] = None,
|
|
107
|
+
) -> Tuple[Optional[str], Dict[str, Any], Optional[str]]:
|
|
108
|
+
"""Resolves one caller-supplied path to an absolute path.
|
|
109
|
+
|
|
110
|
+
Resolution order: explicit ``base``, the server's process cwd, then exactly
|
|
111
|
+
one registered root. An absolute path is accepted only inside a registered
|
|
112
|
+
root (or the explicit base) when ``mode='write'``. Ambiguity is an error,
|
|
113
|
+
never a silent pick: a relative path that exists under two open folders
|
|
114
|
+
cannot be guessed correctly.
|
|
115
|
+
"""
|
|
116
|
+
raw_s = str(raw or "").strip()
|
|
117
|
+
if not raw_s:
|
|
118
|
+
return None, _meta(None, None, raw_s, False), "empty path"
|
|
119
|
+
known = list(roots) if roots is not None else known_roots()
|
|
120
|
+
absolute = os.path.isabs(raw_s)
|
|
121
|
+
|
|
122
|
+
if absolute:
|
|
123
|
+
# Keep the caller's logical path (do not collapse symlinks): the read
|
|
124
|
+
# cache and the firewall key on the path the caller passed.
|
|
125
|
+
real = os.path.abspath(raw_s)
|
|
126
|
+
if mode == "write":
|
|
127
|
+
root = None
|
|
128
|
+
if base:
|
|
129
|
+
b = _clean(base) or os.path.abspath(os.path.expanduser(str(base)))
|
|
130
|
+
if _within(b, real):
|
|
131
|
+
root = b
|
|
132
|
+
if not root:
|
|
133
|
+
root = next((r for r in sorted(known, key=len, reverse=True) if _within(r, real)), None)
|
|
134
|
+
if not root:
|
|
135
|
+
return None, _meta(None, None, raw_s, True), _outside_write_error(raw_s, known)
|
|
136
|
+
return real, _meta(root, root, raw_s, True), None
|
|
137
|
+
if must_exist and not os.path.exists(real):
|
|
138
|
+
return None, _meta(real, None, raw_s, True), _not_found_error(raw_s, [real], known)
|
|
139
|
+
return real, _meta(real, next((r for r in known if _within(r, real)), None), raw_s, True), None
|
|
140
|
+
|
|
141
|
+
tried: List[str] = []
|
|
142
|
+
bases: List[str] = []
|
|
143
|
+
if base:
|
|
144
|
+
bases.append(os.path.abspath(os.path.expanduser(str(base))))
|
|
145
|
+
cwd = os.getcwd()
|
|
146
|
+
if cwd and os.path.isdir(cwd):
|
|
147
|
+
real_cwd = os.path.realpath(cwd)
|
|
148
|
+
if real_cwd not in bases:
|
|
149
|
+
bases.append(real_cwd)
|
|
150
|
+
|
|
151
|
+
for b in bases:
|
|
152
|
+
cand = os.path.abspath(os.path.join(b, raw_s))
|
|
153
|
+
tried.append(b)
|
|
154
|
+
exists = os.path.exists(cand) if must_exist else os.path.isdir(os.path.dirname(cand))
|
|
155
|
+
if not exists:
|
|
156
|
+
continue
|
|
157
|
+
if mode == "write" and not (_within(b, cand) or any(_within(r, cand) for r in known)):
|
|
158
|
+
continue
|
|
159
|
+
return cand, _meta(b, b if _within(b, cand) else None, raw_s, False), None
|
|
160
|
+
|
|
161
|
+
matches: List[Tuple[str, str]] = []
|
|
162
|
+
for r in known:
|
|
163
|
+
cand = os.path.abspath(os.path.join(r, raw_s))
|
|
164
|
+
tried.append(r)
|
|
165
|
+
exists = os.path.exists(cand) if must_exist else os.path.isdir(os.path.dirname(cand))
|
|
166
|
+
if exists and all(cand != seen for seen, _ in matches):
|
|
167
|
+
matches.append((cand, r))
|
|
168
|
+
|
|
169
|
+
if len(matches) == 1:
|
|
170
|
+
cand, r = matches[0]
|
|
171
|
+
return cand, _meta(r, r, raw_s, False), None
|
|
172
|
+
if len(matches) > 1:
|
|
173
|
+
return None, _meta(None, None, raw_s, False), (
|
|
174
|
+
f"path '{raw_s}' is ambiguous: it exists under {len(matches)} known roots "
|
|
175
|
+
f"({', '.join(repr(r) for _, r in matches)}). Pass 'root' or an absolute path inside one of them."
|
|
176
|
+
)
|
|
177
|
+
return None, _meta(None, None, raw_s, False), _not_found_error(raw_s, tried, known)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def rebase_edits(
|
|
181
|
+
edits: Any,
|
|
182
|
+
*,
|
|
183
|
+
cwd: Optional[Any] = None,
|
|
184
|
+
roots: Optional[List[str]] = None,
|
|
185
|
+
) -> Tuple[Any, Optional[str], Optional[str]]:
|
|
186
|
+
"""Normalizes absolute edit paths to repo-relative under one base.
|
|
187
|
+
|
|
188
|
+
Returns ``(edits, base_dir, error)``. Absolute paths are accepted only when
|
|
189
|
+
they all live inside one root: the explicit ``cwd`` (or the process cwd),
|
|
190
|
+
else a single registered root. Mixed roots are a hard error — one call
|
|
191
|
+
edits one tree, which keeps containment honest.
|
|
192
|
+
"""
|
|
193
|
+
if not isinstance(edits, list):
|
|
194
|
+
return edits, None, None
|
|
195
|
+
known = list(roots) if roots is not None else known_roots()
|
|
196
|
+
absolutes: List[str] = []
|
|
197
|
+
for item in edits:
|
|
198
|
+
if isinstance(item, dict):
|
|
199
|
+
p = str(item.get("path") or "").strip()
|
|
200
|
+
if p and os.path.isabs(p):
|
|
201
|
+
absolutes.append(os.path.realpath(os.path.abspath(p)))
|
|
202
|
+
if not absolutes:
|
|
203
|
+
base = _clean(cwd) if cwd else None
|
|
204
|
+
return edits, base, None
|
|
205
|
+
|
|
206
|
+
base: Optional[str] = None
|
|
207
|
+
if cwd:
|
|
208
|
+
candidate = _clean(cwd) or os.path.realpath(os.path.abspath(os.path.expanduser(str(cwd))))
|
|
209
|
+
outside = [p for p in absolutes if not _within(candidate, p)]
|
|
210
|
+
if outside:
|
|
211
|
+
return edits, None, (
|
|
212
|
+
f"absolute edit path(s) are outside the requested cwd '{candidate}': "
|
|
213
|
+
f"{', '.join(outside)}. Pass a repo-relative path under 'cwd', or set 'cwd' "
|
|
214
|
+
f"to the root that contains them (known roots: {_fmt_roots(known)})."
|
|
215
|
+
)
|
|
216
|
+
base = candidate
|
|
217
|
+
|
|
218
|
+
if not base:
|
|
219
|
+
real_cwd = os.path.realpath(os.getcwd())
|
|
220
|
+
if all(_within(real_cwd, p) for p in absolutes):
|
|
221
|
+
base = real_cwd
|
|
222
|
+
|
|
223
|
+
if not base:
|
|
224
|
+
candidates = [r for r in known if all(_within(r, p) for p in absolutes)]
|
|
225
|
+
if candidates:
|
|
226
|
+
base = sorted(candidates, key=len, reverse=True)[0]
|
|
227
|
+
else:
|
|
228
|
+
return edits, None, (
|
|
229
|
+
"absolute edit path(s) span no single known root: "
|
|
230
|
+
f"{', '.join(absolutes)} (known roots: {_fmt_roots(known)}). "
|
|
231
|
+
"Pass 'cwd' (the repo root) plus repo-relative 'path' values; one call edits one root."
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
normalized: List[Any] = []
|
|
235
|
+
for item in edits:
|
|
236
|
+
if not isinstance(item, dict):
|
|
237
|
+
normalized.append(item)
|
|
238
|
+
continue
|
|
239
|
+
copy = dict(item)
|
|
240
|
+
p = str(copy.get("path") or "").strip()
|
|
241
|
+
if p and os.path.isabs(p):
|
|
242
|
+
copy["path"] = os.path.relpath(
|
|
243
|
+
os.path.realpath(os.path.abspath(p)), base
|
|
244
|
+
).replace("\\", "/")
|
|
245
|
+
normalized.append(copy)
|
|
246
|
+
return normalized, base, None
|