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
@@ -20,6 +20,7 @@ import os
20
20
  import re
21
21
  from dataclasses import dataclass, field
22
22
  from typing import Dict, Iterable, List, Optional, Sequence, Tuple
23
+ from tokensafe.call_context import check_cancelled
23
24
 
24
25
  # Callee names that are syntax, not project functions.
25
26
  _NON_CALLEES = frozenset({
@@ -423,6 +424,7 @@ _CODE_EXTS = frozenset({
423
424
  def _walk_code_files(root: str, limit: int = 3000) -> List[str]:
424
425
  out: List[str] = []
425
426
  for dirpath, dirnames, filenames in os.walk(root):
427
+ check_cancelled() # cooperative: stops a cancelled/timed-out tools/call
426
428
  dirnames[:] = [d for d in dirnames if d not in _NOISE_DIRS and not d.startswith(".")]
427
429
  for name in filenames:
428
430
  if os.path.splitext(name)[1].lower() in _CODE_EXTS:
@@ -62,6 +62,7 @@ def build_savings_report(tracker: Optional[MetricsTracker] = None) -> Dict[str,
62
62
  "saved_tokens": int(event.get("saved_tokens") or 0),
63
63
  "original_tokens": int(event.get("original_tokens") or 0),
64
64
  "optimized_tokens": int(event.get("optimized_tokens") or 0),
65
+ "measurement": event.get("measurement") or "measured",
65
66
  }
66
67
 
67
68
  return {
@@ -73,15 +74,22 @@ def build_savings_report(tracker: Optional[MetricsTracker] = None) -> Dict[str,
73
74
  "saved_tokens_live": live_saved,
74
75
  "saved_tokens_measured": int(summary.get("total_saved_tokens_measured", 0)),
75
76
  "saved_tokens_estimated": int(summary.get("total_saved_tokens_estimated", 0)),
77
+ "saved_tokens_legacy_unclassified": int(summary.get("total_saved_tokens_legacy", 0)),
76
78
  "saved_tokens_basis": summary.get("total_saved_tokens_basis", "estimated"),
77
79
  "pruned_synced_saved_tokens": pruned["saved_tokens"],
78
80
  "cumulative_saved_tokens": cumulative,
79
81
  "usd_saved_approx": summary.get("total_usd_saved", 0.0),
82
+ "usd_saved_measured_approx": summary.get("total_usd_saved_measured", 0.0),
83
+ "usd_saved_estimated_approx": summary.get("total_usd_saved_estimated", 0.0),
80
84
  "reduction_pct": summary.get("overall_reduction_pct", 0.0),
85
+ "measured_reduction_pct": summary.get("measured_reduction_pct", 0.0),
81
86
  "last_event": last_event,
82
87
  "note": (
83
- "cumulative = live events incl. locally pruned rollups; pruned_synced_* "
84
- "is the already-synced subset, not additive; "
88
+ "quote saved_tokens_measured as the savings figure; "
89
+ "saved_tokens_estimated is counterfactual and saved_tokens_legacy_unclassified "
90
+ "is pre-split rollup mass, both reported apart, never added to the measured figure; "
91
+ "cumulative = measured + estimated + legacy (all sources) incl. locally pruned rollups; "
92
+ "pruned_synced_* is the already-synced subset, not additive; "
85
93
  "per-turn delta must be read from last_event, never guessed"
86
94
  ),
87
95
  }
@@ -9,6 +9,7 @@ import stat
9
9
  import fnmatch
10
10
  import time
11
11
  from typing import Dict, List, Optional, Any, Tuple
12
+ from tokensafe.call_context import check_cancelled
12
13
 
13
14
  IGNORED_DIRS = {
14
15
  ".git", ".hg", ".svn", "node_modules", ".venv", "venv", "__pycache__", "dist", "build",
@@ -26,6 +27,10 @@ IGNORED_EXTENSIONS = {
26
27
  ".sqlite3", ".wasm"
27
28
  }
28
29
 
30
+ # Obvious regex syntax in a query sent as a literal: an unescaped '|', a
31
+ # backslash class or escaped metachar (\b \d \w \s \( \. ...), or '.*' / '.+'.
32
+ _REGEX_SYNTAX_HINT = re.compile(r"(?<!\\)\||\\[dwsbDWSB().\[\]{}+*?^$]|\.[*+]")
33
+
29
34
  LOCKFILES = {
30
35
  "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock",
31
36
  "Pipfile.lock", "composer.lock", "Cargo.lock", "flake.lock"
@@ -337,6 +342,76 @@ class ScopedSearch:
337
342
  "markdown": f"Regex compilation error: {str(e)}"
338
343
  }
339
344
 
345
+ res = cls._dispatch(
346
+ query, root_dir, scope, pattern, regex_mode, auto_regex,
347
+ case_sensitive, max_results, per_file, target_file,
348
+ )
349
+ # A literal pass that found nothing for a pattern written in regex
350
+ # syntax ('A|B', '\bfoo', 'a.*b') almost always meant the regex: retry
351
+ # once as regex and label it, instead of a silent "0 matches". An
352
+ # explicit use_regex=False keeps its literal contract and gets a hint.
353
+ if (
354
+ not regex_mode
355
+ and res.get("success", True)
356
+ and not res.get("total_matches")
357
+ and not res.get("partial")
358
+ and cls.looks_like_intended_regex(query)
359
+ ):
360
+ if use_regex is False:
361
+ res["markdown"] = (
362
+ str(res.get("markdown") or "")
363
+ + f"\n_0 matches for literal '{query}'; pass use_regex=true "
364
+ "(mode='regex') for alternation/regex syntax._"
365
+ )
366
+ return res
367
+ retry = cls._dispatch(
368
+ query, root_dir, scope, re.compile(query, flags), True, False,
369
+ case_sensitive, max_results, per_file, target_file,
370
+ timeout_seconds=2.5,
371
+ )
372
+ if retry.get("success", True) and retry.get("total_matches"):
373
+ retry["retried_as_regex"] = True
374
+ retry["markdown"] = (
375
+ f"_[auto-retried as regex: literal '{query}' had 0 matches]_\n"
376
+ + str(retry.get("markdown") or "")
377
+ )
378
+ return retry
379
+ res["markdown"] = (
380
+ str(res.get("markdown") or "")
381
+ + f"\n_0 matches for '{query}' as literal and as regex._"
382
+ )
383
+ return res
384
+
385
+ @classmethod
386
+ def looks_like_intended_regex(cls, query: str) -> bool:
387
+ """True when a literal query is written in obvious regex syntax and
388
+ compiles: an unescaped '|', a backslash class/escape (\\b, \\d, \\(, \\.),
389
+ or a quantified dot ('.*', '.+'). Used only after a literal pass found
390
+ nothing, so a literal that genuinely occurs is never reinterpreted."""
391
+ if not query or not _REGEX_SYNTAX_HINT.search(query):
392
+ return False
393
+ try:
394
+ re.compile(query)
395
+ except re.error:
396
+ return False
397
+ return True
398
+
399
+ @classmethod
400
+ def _dispatch(
401
+ cls,
402
+ query: str,
403
+ root_dir: str,
404
+ scope: str,
405
+ pattern: Any,
406
+ regex_mode: bool,
407
+ auto_regex: bool,
408
+ case_sensitive: bool,
409
+ max_results: int,
410
+ per_file: int,
411
+ target_file: Optional[str],
412
+ timeout_seconds: float = 4.0,
413
+ ) -> Dict[str, Any]:
414
+ """Runs one compiled pattern: single file, symbol index + text, or text."""
340
415
  # `path` pointing at a file must search that file, never its parent
341
416
  # directory: the old dirname fallback returned sibling hits as if they
342
417
  # matched the requested file.
@@ -364,6 +439,7 @@ class ScopedSearch:
364
439
  return cls._text_search(
365
440
  query, root_dir, scope, pattern, regex_mode, auto_regex,
366
441
  case_sensitive, max_results, per_file,
442
+ timeout_seconds=timeout_seconds,
367
443
  )
368
444
  if len(symbol_result["matches"]) >= max_results:
369
445
  return symbol_result
@@ -477,6 +553,7 @@ class ScopedSearch:
477
553
  stopped_reason = "complete"
478
554
 
479
555
  for dirpath, dirnames, filenames in os.walk(root_dir):
556
+ check_cancelled() # cooperative: stops a cancelled/timed-out tools/call
480
557
  if time.monotonic() - start_time > timeout_seconds:
481
558
  timed_out = True
482
559
  stopped_reason = "time_budget"
@@ -16,7 +16,7 @@ import json
16
16
  import os
17
17
  from typing import Any, Dict, List, Optional
18
18
 
19
- from tokensafe.backend_release import BACKEND_RELEASE_TAG
19
+ from tokensafe.backend_release import BACKEND_NPM_VERSION, BACKEND_RELEASE_TAG
20
20
 
21
21
  MAX_BRIEF_CHARS = 1200
22
22
 
@@ -288,7 +288,15 @@ def _activation(workspace: str, stack: Dict[str, Any]) -> List[str]:
288
288
  return hints
289
289
 
290
290
  readiness = doctor.get("adapter_readiness") or {}
291
- for profile, item in readiness.items():
291
+ for slot, item in readiness.items():
292
+ # The entry's own profile: Next.js fills the frontend slot but runs on the
293
+ # Node backend adapter, so `tokensafe dev` is the wrong hint for it.
294
+ profile = item.get("profile") or slot
295
+ if item.get("stale"):
296
+ hints.append(
297
+ f"{profile} runtime descriptor is stale ({item.get('runtime_reason') or 'no live handshake'}); "
298
+ "restart the dev server or `tokensafe oumv doctor --prune`"
299
+ )
292
300
  if item.get("ready"):
293
301
  continue
294
302
  framework = str(item.get("framework") or "")
@@ -314,6 +322,13 @@ def _activation(workspace: str, stack: Dict[str, Any]) -> List[str]:
314
322
  hints.append("activate frontend: run `tokensafe dev` (installs nothing into the repo)")
315
323
  elif framework in ("fastapi", "starlette"):
316
324
  hints.append('activate backend: `pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python"` then run the server via `tokensafe run-backend ...`')
325
+ elif item.get("provider") in ("node", "elysia", "bun"):
326
+ hints.append(
327
+ f"activate {profile}: `npm install -D tokensafe-backend-node@{BACKEND_NPM_VERSION}` "
328
+ "then `tokensafe inject` (reversible)"
329
+ )
330
+ elif item.get("provider") == "dotnet":
331
+ hints.append("activate backend: `tokensafe inject` (adds the TokenSafe.Oumv.AspNetCore package and one reversible block)")
317
332
  elif item.get("provider") == "go":
318
333
  hints.append(
319
334
  f"activate backend: `go get github.com/tokensafe-dev/tokensafe-backend/go@{BACKEND_RELEASE_TAG}` "
@@ -0,0 +1,73 @@
1
+ """Compact view of ``detect_project_stack`` output for agent-facing responses.
2
+
3
+ ``oumv(action='status')`` used to embed the detector's full result: every
4
+ package row with ``adapter: null``, the same "no supported framework" reason on
5
+ each tooling package, and a ``detected_files`` list that repeats the package
6
+ paths. On a 10-package monorepo that was ~3k tokens, most of it rows an agent
7
+ cannot act on. This view keeps every actionable row verbatim and folds the rest
8
+ into one line per role. The detector output itself is untouched: path→package
9
+ classification and config generation still read the full ``packages`` list.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from typing import Any, Dict, List
14
+
15
+ # Rows an agent can do something with through OUMV (supported now, or one step
16
+ # away such as `needs-vite`/`manual`). Everything else is summarized.
17
+ _ACTIONABLE_ROLES = ("frontend", "backend")
18
+ _ROW_KEYS = ("role", "path", "framework", "provider", "adapter", "vite", "oumvSupported", "status", "reason")
19
+
20
+
21
+ def _compact_row(row: Dict[str, Any]) -> Dict[str, Any]:
22
+ return {k: row[k] for k in _ROW_KEYS if k in row and row[k] is not None}
23
+
24
+
25
+ def compact_detected_stack(stack: Dict[str, Any]) -> Dict[str, Any]:
26
+ """Returns a token-lean copy of a detected stack (input is not modified).
27
+
28
+ Kept verbatim: ``workspace``, ``frontend``, ``backend``, ``package_managers``
29
+ and every frontend/backend package row (minus null fields). Folded:
30
+ ``package`` / ``library`` / ``worker`` rows become one entry per role with
31
+ the paths and a single reason; ``detected_files`` is dropped when every
32
+ manifest is already named by a package path.
33
+ """
34
+ if not isinstance(stack, dict):
35
+ return stack
36
+ out: Dict[str, Any] = {
37
+ key: stack[key]
38
+ for key in ("workspace", "frontend", "backend", "package_managers")
39
+ if key in stack
40
+ }
41
+ packages = stack.get("packages") or []
42
+ rows: List[Dict[str, Any]] = []
43
+ folded: Dict[str, Dict[str, Any]] = {}
44
+ for row in packages:
45
+ if not isinstance(row, dict):
46
+ continue
47
+ role = str(row.get("role") or "package")
48
+ if role in _ACTIONABLE_ROLES:
49
+ rows.append(_compact_row(row))
50
+ continue
51
+ group = folded.setdefault(role, {"count": 0, "paths": [], "oumvSupported": False})
52
+ group["count"] += 1
53
+ group["paths"].append(row.get("path"))
54
+ if row.get("oumvSupported"):
55
+ group["oumvSupported"] = True
56
+ reason = row.get("reason")
57
+ if reason and "reason" not in group:
58
+ group["reason"] = reason
59
+ out["packages"] = rows
60
+ if folded:
61
+ out["otherPackages"] = folded
62
+
63
+ detected = list(stack.get("detected_files") or [])
64
+ package_dirs = {str(row.get("path") or ".") for row in packages if isinstance(row, dict)}
65
+ unexplained = []
66
+ for rel in detected:
67
+ rel_s = str(rel).replace("\\", "/")
68
+ parent = rel_s.rsplit("/", 1)[0] if "/" in rel_s else "."
69
+ if parent not in package_dirs:
70
+ unexplained.append(rel)
71
+ if unexplained:
72
+ out["detected_files"] = unexplained
73
+ return out
@@ -55,12 +55,18 @@ def check_syntax(abs_path: str, content: str) -> Dict[str, str]:
55
55
  try:
56
56
  with os.fdopen(tmp_fd, "w", encoding="utf-8") as f:
57
57
  f.write(content)
58
- proc = subprocess.run(
58
+ # Reachable from write handlers (apply_edits, oumv mutate): cancellable
59
+ # with the tools/call, and a timeout stops the whole process group.
60
+ from tokensafe.proc_run import run_cancellable
61
+ proc = run_cancellable(
59
62
  [node_bin, "--check", tmp_path],
60
- capture_output=True,
63
+ stdout=subprocess.PIPE,
64
+ stderr=subprocess.PIPE,
61
65
  text=True,
62
66
  timeout=_NODE_TIMEOUT_SEC,
63
67
  )
68
+ if proc.status != "exited":
69
+ return {"status": "skipped", "tool": "node-check", "error": proc.status}
64
70
  if proc.returncode == 0:
65
71
  return {"status": "passed", "tool": "node --check"}
66
72
  err_lines = (proc.stderr or proc.stdout or "").strip().splitlines()
@@ -341,7 +341,7 @@ class TelemetrySync:
341
341
  current_last_id = last_id
342
342
  headers = {
343
343
  "Content-Type": "application/json",
344
- "User-Agent": "TokenSafe-Sync/5.0.0"
344
+ "User-Agent": "TokenSafe-Sync/5.0.2"
345
345
  }
346
346
  if active_key:
347
347
  headers["Authorization"] = f"Bearer {active_key}"
@@ -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 = "5.0.0"
20
+ CURRENT_VERSION = "5.0.2"
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
@@ -147,6 +147,55 @@ class _HTMLToMarkdownParser(HTMLParser):
147
147
  return cleaned
148
148
 
149
149
 
150
+ _DNS_TIMEOUT_SEC = 3.0
151
+
152
+
153
+ def _getaddrinfo_bounded(host, port, timeout: float = _DNS_TIMEOUT_SEC, **kwargs):
154
+ """socket.getaddrinfo with a deadline (the resolver has none of its own).
155
+
156
+ The lookup runs on a daemon thread; past `timeout` the caller gets an
157
+ OSError instead of waiting on a hung resolver.
158
+ """
159
+ box: Dict[str, Any] = {}
160
+
161
+ def _run() -> None:
162
+ try:
163
+ box["infos"] = socket.getaddrinfo(host, port, **kwargs)
164
+ except BaseException as exc: # handed back to the caller below
165
+ box["error"] = exc
166
+
167
+ worker = threading.Thread(target=_run, name="tokensafe-dns", daemon=True)
168
+ worker.start()
169
+ worker.join(max(0.05, float(timeout)))
170
+ if worker.is_alive():
171
+ # gaierror (an OSError): callers that fail closed on an unresolvable
172
+ # host treat a hung resolver the same way.
173
+ raise socket.gaierror(socket.EAI_AGAIN, f"TokenSafe: DNS lookup for {host} exceeded {timeout:.1f}s")
174
+ if "error" in box:
175
+ raise box["error"]
176
+ return box["infos"]
177
+
178
+
179
+ def _read_bounded(resp, max_bytes: int, timeout: float) -> bytes:
180
+ """Reads at most `max_bytes` with an overall deadline.
181
+
182
+ urllib's timeout bounds each socket read, not the body: a server that
183
+ trickles a byte at a time kept a read going indefinitely.
184
+ """
185
+ deadline = time.monotonic() + max(0.1, float(timeout))
186
+ chunks: List[bytes] = []
187
+ total = 0
188
+ while total < max_bytes:
189
+ if time.monotonic() >= deadline:
190
+ raise TimeoutError(f"TokenSafe: response body exceeded {timeout:.1f}s")
191
+ chunk = resp.read(min(64 * 1024, max_bytes - total))
192
+ if not chunk:
193
+ break
194
+ chunks.append(chunk)
195
+ total += len(chunk)
196
+ return b"".join(chunks)
197
+
198
+
150
199
  def _guarded_create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, *args, **kwargs):
151
200
  """socket.create_connection that refuses non-public addresses at connect time.
152
201
 
@@ -157,7 +206,7 @@ def _guarded_create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
157
206
  the connection's host, not the IP).
158
207
  """
159
208
  host, port = address[0], address[1]
160
- infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
209
+ infos = _getaddrinfo_bounded(host, port, type=socket.SOCK_STREAM)
161
210
  checked = []
162
211
  for family, socktype, proto, _canon, sockaddr in infos:
163
212
  ip = ipaddress.ip_address(str(sockaddr[0]).split("%", 1)[0])
@@ -484,7 +533,7 @@ class WebReader:
484
533
  pass # hostname, not a literal IP
485
534
  # DNS SSRF protection: reject hostnames resolving to internal/private IPs
486
535
  try:
487
- infos = socket.getaddrinfo(raw_host, None, type=socket.SOCK_STREAM)
536
+ infos = _getaddrinfo_bounded(raw_host, None, type=socket.SOCK_STREAM)
488
537
  for info in infos:
489
538
  sockaddr = info[4]
490
539
  addr = str(sockaddr[0]).split("%", 1)[0]
@@ -559,7 +608,7 @@ class WebReader:
559
608
  if status >= 400:
560
609
  return "", False, f"HTTP Error {status}"
561
610
  content_type = resp.headers.get("Content-Type", "").lower()
562
- raw_bytes = resp.read(2 * 1024 * 1024) # 2MB max
611
+ raw_bytes = _read_bounded(resp, 2 * 1024 * 1024, timeout) # 2MB max, whole-body deadline
563
612
  charset = "utf-8"
564
613
  if "charset=" in content_type:
565
614
  charset = content_type.split("charset=")[-1].split(";")[0].strip()
@@ -605,7 +654,7 @@ class WebReader:
605
654
  opener = _safe_opener()
606
655
  with opener.open(req, timeout=timeout) as resp:
607
656
  status = int(getattr(resp, "status", 0) or 0)
608
- raw = resp.read(max_bytes + 1)
657
+ raw = _read_bounded(resp, max_bytes + 1, timeout)
609
658
  if len(raw) > max_bytes:
610
659
  raw = raw[:max_bytes]
611
660
  hdrs = {k.lower(): v for k, v in resp.headers.items()}
@@ -57,9 +57,86 @@ def reset_roots(paths: Iterable[Any] = ()) -> List[str]:
57
57
  """Replaces the registry (tests and a host that re-sends workspacePaths)."""
58
58
  with _LOCK:
59
59
  _ROOTS.clear()
60
+ _CLIENT_ROOTS.clear()
60
61
  return register_roots(paths)
61
62
 
62
63
 
64
+ # Roots the MCP client itself declared for THIS connection: the `roots/list`
65
+ # answer (MCP roots capability) or a multi-root initialize payload. They are
66
+ # per-connection truth, unlike the machine-wide `.active_workspace` marker,
67
+ # which the hooks of every concurrent session rewrite. A server launched by a
68
+ # GUI host with cwd `/` used to fall straight through to that marker and serve
69
+ # another session's project as its own root.
70
+ _CLIENT_ROOTS: List[str] = []
71
+
72
+
73
+ def _root_to_path(value: Any) -> Optional[str]:
74
+ """A root entry (`{"uri": "file:///x"}`, a file:// URI or a plain path) as a path."""
75
+ if isinstance(value, dict):
76
+ value = value.get("uri") or value.get("path")
77
+ text = str(value or "").strip()
78
+ if not text:
79
+ return None
80
+ if text.lower().startswith("file://"):
81
+ from urllib.parse import unquote, urlparse
82
+
83
+ text = unquote(urlparse(text).path or "")
84
+ # file:///C:/repo parses to /C:/repo on Windows.
85
+ if os.name == "nt" and len(text) >= 3 and text[0] == "/" and text[2] == ":":
86
+ text = text[1:]
87
+ elif "://" in text:
88
+ return None # only file roots name a local workspace
89
+ return text or None
90
+
91
+
92
+ def roots_from_list_result(result: Any) -> List[str]:
93
+ """Paths from a `roots/list` result (`{"roots": [{"uri": ...}, ...]}`), in order."""
94
+ entries = result.get("roots") if isinstance(result, dict) else None
95
+ if not isinstance(entries, list):
96
+ return []
97
+ out: List[str] = []
98
+ for entry in entries:
99
+ if not isinstance(entry, dict):
100
+ continue # the spec's Root is an object with a `uri`
101
+ path = _root_to_path(entry.get("uri"))
102
+ if path and path not in out:
103
+ out.append(path)
104
+ return out
105
+
106
+
107
+ def set_client_roots(values: Iterable[Any]) -> List[str]:
108
+ """Replaces the client-declared roots (a fresh `roots/list` answer or
109
+ `notifications/roots/list_changed`) and puts them first in the registry.
110
+
111
+ Returns the usable roots, primary first. An empty or unusable answer clears
112
+ the client roots, so a stale list never outlives the client's own update."""
113
+ cleaned: List[str] = []
114
+ for value in values or ():
115
+ path = _clean(_root_to_path(value))
116
+ if path and path not in cleaned:
117
+ cleaned.append(path)
118
+ with _LOCK:
119
+ _CLIENT_ROOTS[:] = cleaned
120
+ for path in reversed(cleaned):
121
+ if path in _ROOTS:
122
+ _ROOTS.remove(path)
123
+ _ROOTS.insert(0, path)
124
+ return list(cleaned)
125
+
126
+
127
+ def client_roots() -> List[str]:
128
+ with _LOCK:
129
+ return list(_CLIENT_ROOTS)
130
+
131
+
132
+ def primary_client_root() -> Optional[str]:
133
+ """The first client-declared root that still exists, else None."""
134
+ for root in client_roots():
135
+ if os.path.isdir(root):
136
+ return root
137
+ return None
138
+
139
+
63
140
  def _within(root: str, path: str) -> bool:
64
141
  return is_within(root, path)
65
142
 
@@ -93,6 +170,43 @@ def _not_found_error(raw: str, tried: List[str], roots: List[str]) -> str:
93
170
  )
94
171
 
95
172
 
173
+ def _is_fs_root(path: str) -> bool:
174
+ """`/` (or a drive root): never a base for a relative path.
175
+
176
+ An MCP server spawned by a GUI host often runs with cwd `/`, and an empty
177
+ root normalizes to it too; joining a repo-relative path there produced
178
+ `/tokensafe/batch_search.py` instead of the file under the explicit cwd.
179
+ """
180
+ try:
181
+ p = os.path.abspath(path)
182
+ except (TypeError, ValueError):
183
+ return False
184
+ return os.path.dirname(p) == p
185
+
186
+
187
+ def _ordered_bases(base: Any) -> List[str]:
188
+ """Explicit base(s) in caller order: one value or a list (cwd/root first,
189
+ then the session root). Empty values and filesystem roots are dropped."""
190
+ raw_bases = base if isinstance(base, (list, tuple)) else [base]
191
+ out: List[str] = []
192
+ for item in raw_bases:
193
+ text = str(item or "").strip()
194
+ if not text:
195
+ continue
196
+ if text.lower().startswith("file://"):
197
+ # Hosts report roots as file:// URIs; a bare join would treat the
198
+ # scheme as a directory name.
199
+ from urllib.parse import unquote, urlparse
200
+ text = unquote(urlparse(text).path or "")
201
+ if not text:
202
+ continue
203
+ b = os.path.abspath(os.path.expanduser(text))
204
+ if _is_fs_root(b) or b in out:
205
+ continue
206
+ out.append(b)
207
+ return out
208
+
209
+
96
210
  def resolve_input_path(
97
211
  raw: Any,
98
212
  *,
@@ -103,8 +217,10 @@ def resolve_input_path(
103
217
  ) -> Tuple[Optional[str], Dict[str, Any], Optional[str]]:
104
218
  """Resolves one caller-supplied path to an absolute path.
105
219
 
106
- Resolution order: explicit ``base``, the server's process cwd, then exactly
107
- one registered root. An absolute path is accepted only inside a registered
220
+ Resolution order: explicit ``base`` (one path, or a list tried in order:
221
+ the call's cwd/root, then the session root), the server's process cwd, then
222
+ exactly one registered root. A filesystem root (``/``) or an empty value is
223
+ never a base for a relative path. An absolute path is accepted only inside a registered
108
224
  root (or the explicit base) when ``mode='write'``. Ambiguity is an error,
109
225
  never a silent pick: a relative path that exists under two open folders
110
226
  cannot be guessed correctly.
@@ -121,10 +237,11 @@ def resolve_input_path(
121
237
  real = os.path.abspath(raw_s)
122
238
  if mode == "write":
123
239
  root = None
124
- if base:
125
- b = _clean(base) or os.path.abspath(os.path.expanduser(str(base)))
240
+ for explicit in _ordered_bases(base):
241
+ b = _clean(explicit) or explicit
126
242
  if _within(b, real):
127
243
  root = b
244
+ break
128
245
  if not root:
129
246
  root = next((r for r in sorted(known, key=len, reverse=True) if _within(r, real)), None)
130
247
  if not root:
@@ -135,11 +252,12 @@ def resolve_input_path(
135
252
  return real, _meta(real, next((r for r in known if _within(r, real)), None), raw_s, True), None
136
253
 
137
254
  tried: List[str] = []
138
- bases: List[str] = []
139
- if base:
140
- bases.append(os.path.abspath(os.path.expanduser(str(base))))
141
- cwd = os.getcwd()
142
- if cwd and os.path.isdir(cwd):
255
+ bases: List[str] = _ordered_bases(base)
256
+ try:
257
+ cwd = os.getcwd()
258
+ except OSError:
259
+ cwd = ""
260
+ if cwd and os.path.isdir(cwd) and not _is_fs_root(cwd):
143
261
  real_cwd = os.path.realpath(cwd)
144
262
  if real_cwd not in bases:
145
263
  bases.append(real_cwd)
Binary file