tokensafe 4.6.4 → 4.7.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.
- package/.codex-plugin/plugin.json +2 -2
- package/LICENSE +202 -21
- package/README.md +8 -4
- package/hooks/claude_code_hook.py +2 -2
- package/hooks/pre_invocation.py +7 -12
- package/kimi.plugin.json +2 -2
- package/package.json +2 -2
- package/plugin.json +2 -1
- package/server.json +3 -3
- package/src/acp/__init__.py +15 -0
- package/src/acp/server.py +328 -0
- package/src/agent/__init__.py +11 -0
- package/src/agent/context.py +99 -0
- package/src/agent/loop.py +385 -0
- package/src/agent/pricing.py +77 -0
- package/src/agent/providers.py +486 -0
- package/src/agent/tools.py +98 -0
- package/src/bench/__init__.py +1 -0
- package/src/bench/driver.py +219 -0
- package/src/bench/go_target.py +360 -0
- package/src/bench/react_target.py +234 -0
- package/src/bench/runner.py +247 -0
- package/src/cli.py +125 -0
- package/src/history_compactor.py +200 -2
- package/src/mcp_server.py +56 -13
- package/src/paths.py +41 -2
- package/src/session_context.py +124 -0
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/src/history_compactor.py
CHANGED
|
@@ -10,10 +10,97 @@ from typing import Dict, Any, Optional, List, Tuple
|
|
|
10
10
|
from src.tokenizer import count_tokens
|
|
11
11
|
|
|
12
12
|
|
|
13
|
+
def _block_text(content: Any) -> str:
|
|
14
|
+
"""Plain text of a message content (plain string or typed block list)."""
|
|
15
|
+
if isinstance(content, str):
|
|
16
|
+
return content
|
|
17
|
+
if not isinstance(content, list):
|
|
18
|
+
return ""
|
|
19
|
+
parts: List[str] = []
|
|
20
|
+
for block in content:
|
|
21
|
+
if not isinstance(block, dict):
|
|
22
|
+
continue
|
|
23
|
+
btype = str(block.get("type") or "")
|
|
24
|
+
if btype in ("text", "thinking", "reasoning"):
|
|
25
|
+
text = block.get("text") or block.get("thinking")
|
|
26
|
+
if isinstance(text, str) and text:
|
|
27
|
+
parts.append(text)
|
|
28
|
+
elif btype == "tool_result":
|
|
29
|
+
nested = _block_text(block.get("content"))
|
|
30
|
+
if nested:
|
|
31
|
+
parts.append(nested)
|
|
32
|
+
return " ".join(parts)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _model_io_parts(step: dict) -> Tuple[str, List[Tuple[str, dict]], str]:
|
|
36
|
+
"""Normalize a ZCode `model_io` record into (text, tool_calls, user_prompt).
|
|
37
|
+
|
|
38
|
+
One record is one provider call: `request.messages` carries either only the
|
|
39
|
+
new messages (`messagesKind: "delta"`) or a window ending with the newest
|
|
40
|
+
message, while `response` holds that call's assistant output. Only the newest
|
|
41
|
+
message is new state, so folding stays linear instead of re-counting the
|
|
42
|
+
cumulative conversation once per record. `user_prompt` is non-empty when the
|
|
43
|
+
record sits on a turn boundary (the digest's active goal).
|
|
44
|
+
"""
|
|
45
|
+
request = step.get("request") if isinstance(step.get("request"), dict) else {}
|
|
46
|
+
response = step.get("response") if isinstance(step.get("response"), dict) else {}
|
|
47
|
+
|
|
48
|
+
messages = request.get("messages") if isinstance(request.get("messages"), list) else []
|
|
49
|
+
newest: dict = messages[-1] if messages and isinstance(messages[-1], dict) else {}
|
|
50
|
+
newest_role = str(newest.get("role") or "")
|
|
51
|
+
newest_text = _block_text(newest.get("content"))
|
|
52
|
+
|
|
53
|
+
user_prompt = ""
|
|
54
|
+
if newest_role == "user":
|
|
55
|
+
candidate = newest_text.strip()
|
|
56
|
+
if candidate and not _is_injected_prompt(candidate):
|
|
57
|
+
user_prompt = candidate
|
|
58
|
+
if not user_prompt and request.get("messagesKind") in ("full", "delta"):
|
|
59
|
+
# Complete (or purely new) windows: the newest user message is this
|
|
60
|
+
# turn's prompt even when trailing tool results follow it.
|
|
61
|
+
for item in reversed(messages):
|
|
62
|
+
if not isinstance(item, dict) or item.get("role") != "user":
|
|
63
|
+
continue
|
|
64
|
+
candidate = _block_text(item.get("content")).strip()
|
|
65
|
+
if candidate and not _is_injected_prompt(candidate):
|
|
66
|
+
user_prompt = candidate
|
|
67
|
+
break
|
|
68
|
+
|
|
69
|
+
assistant_text = response.get("text")
|
|
70
|
+
if not isinstance(assistant_text, str):
|
|
71
|
+
assistant_text = ""
|
|
72
|
+
reasoning_text = response.get("reasoningText")
|
|
73
|
+
if not isinstance(reasoning_text, str):
|
|
74
|
+
reasoning_text = ""
|
|
75
|
+
|
|
76
|
+
parts: List[str] = []
|
|
77
|
+
if newest_role == "user" and newest_text.strip():
|
|
78
|
+
parts.append(newest_text) # the prompt itself leads the step
|
|
79
|
+
elif user_prompt:
|
|
80
|
+
parts.append(user_prompt) # prompt recovered from deeper in the window
|
|
81
|
+
if assistant_text.strip():
|
|
82
|
+
parts.append(assistant_text)
|
|
83
|
+
if reasoning_text.strip():
|
|
84
|
+
parts.append(reasoning_text)
|
|
85
|
+
if newest_role != "user" and newest_text.strip():
|
|
86
|
+
parts.append(newest_text)
|
|
87
|
+
|
|
88
|
+
calls: List[Tuple[str, dict]] = []
|
|
89
|
+
for call in response.get("toolCalls") or []:
|
|
90
|
+
if not isinstance(call, dict):
|
|
91
|
+
continue
|
|
92
|
+
args = call.get("input")
|
|
93
|
+
calls.append((str(call.get("name") or ""), args if isinstance(args, dict) else {}))
|
|
94
|
+
|
|
95
|
+
return "\n".join(part for part in parts if part), calls, user_prompt
|
|
96
|
+
|
|
97
|
+
|
|
13
98
|
def _extract_step_text(step: dict) -> str:
|
|
14
99
|
"""Step text in any supported transcript format (Antigravity string/list, Claude Code text/thinking/tool_result)."""
|
|
15
100
|
if not isinstance(step, dict):
|
|
16
101
|
return ""
|
|
102
|
+
if step.get("type") == "model_io":
|
|
103
|
+
return _model_io_parts(step)[0]
|
|
17
104
|
content = step.get("content")
|
|
18
105
|
if isinstance(content, str) and content:
|
|
19
106
|
return content
|
|
@@ -23,6 +110,61 @@ def _extract_step_text(step: dict) -> str:
|
|
|
23
110
|
for b in content
|
|
24
111
|
if isinstance(b, dict)
|
|
25
112
|
).strip()
|
|
113
|
+
# ZCode event log: {"type": "...", "payload": {...}}
|
|
114
|
+
payload = step.get("payload")
|
|
115
|
+
if isinstance(payload, dict):
|
|
116
|
+
pcontent = payload.get("content")
|
|
117
|
+
if isinstance(pcontent, str) and pcontent:
|
|
118
|
+
return pcontent
|
|
119
|
+
if isinstance(pcontent, list):
|
|
120
|
+
parts = [
|
|
121
|
+
str(b.get("text") or b.get("thinking") or "")
|
|
122
|
+
for b in pcontent
|
|
123
|
+
if isinstance(b, dict)
|
|
124
|
+
]
|
|
125
|
+
joined = " ".join(parts).strip()
|
|
126
|
+
if joined:
|
|
127
|
+
return joined
|
|
128
|
+
pinput = payload.get("input")
|
|
129
|
+
if isinstance(pinput, str) and pinput:
|
|
130
|
+
return pinput
|
|
131
|
+
if step.get("type") == "turn_started" and isinstance(pinput, dict):
|
|
132
|
+
text = pinput.get("text") or pinput.get("prompt")
|
|
133
|
+
if isinstance(text, str) and text:
|
|
134
|
+
return text
|
|
135
|
+
|
|
136
|
+
# ZCode model-io log: {request:{body:{messages}}, response:{body:{choices}}}
|
|
137
|
+
response = step.get("response")
|
|
138
|
+
if isinstance(response, dict):
|
|
139
|
+
try:
|
|
140
|
+
msg = response["body"]["choices"][0]["message"]
|
|
141
|
+
except Exception:
|
|
142
|
+
msg = None
|
|
143
|
+
if isinstance(msg, dict):
|
|
144
|
+
content = msg.get("content")
|
|
145
|
+
if isinstance(content, str) and content:
|
|
146
|
+
return content
|
|
147
|
+
if isinstance(content, list):
|
|
148
|
+
joined = " ".join(
|
|
149
|
+
str(b.get("text") or "")
|
|
150
|
+
for b in content
|
|
151
|
+
if isinstance(b, dict)
|
|
152
|
+
).strip()
|
|
153
|
+
if joined:
|
|
154
|
+
return joined
|
|
155
|
+
request = step.get("request")
|
|
156
|
+
if isinstance(request, dict):
|
|
157
|
+
try:
|
|
158
|
+
messages = request["body"]["messages"]
|
|
159
|
+
except Exception:
|
|
160
|
+
messages = None
|
|
161
|
+
if isinstance(messages, list):
|
|
162
|
+
for item in reversed(messages):
|
|
163
|
+
if isinstance(item, dict) and item.get("role") == "user":
|
|
164
|
+
content = item.get("content")
|
|
165
|
+
if isinstance(content, str) and content:
|
|
166
|
+
return content
|
|
167
|
+
|
|
26
168
|
message = step.get("message")
|
|
27
169
|
if not isinstance(message, dict):
|
|
28
170
|
return ""
|
|
@@ -80,12 +222,40 @@ def _extract_step_tool_calls(step: dict) -> List[Tuple[str, dict]]:
|
|
|
80
222
|
calls: List[Tuple[str, dict]] = []
|
|
81
223
|
if not isinstance(step, dict):
|
|
82
224
|
return calls
|
|
225
|
+
if step.get("type") == "model_io":
|
|
226
|
+
return _model_io_parts(step)[1]
|
|
83
227
|
tc_list = step.get("tool_calls")
|
|
84
228
|
if isinstance(tc_list, list):
|
|
85
229
|
for tc in tc_list:
|
|
86
230
|
if isinstance(tc, dict):
|
|
87
231
|
args = tc.get("args")
|
|
88
232
|
calls.append((str(tc.get("name", "")), args if isinstance(args, dict) else {}))
|
|
233
|
+
response = step.get("response")
|
|
234
|
+
if isinstance(response, dict):
|
|
235
|
+
try:
|
|
236
|
+
message = response["body"]["choices"][0]["message"]
|
|
237
|
+
except Exception:
|
|
238
|
+
message = None
|
|
239
|
+
if isinstance(message, dict):
|
|
240
|
+
for tc in message.get("tool_calls") or []:
|
|
241
|
+
fn = (tc or {}).get("function") or {}
|
|
242
|
+
name = str(fn.get("name") or "")
|
|
243
|
+
raw_args = fn.get("arguments")
|
|
244
|
+
args = {}
|
|
245
|
+
if isinstance(raw_args, str):
|
|
246
|
+
try:
|
|
247
|
+
args = json.loads(raw_args)
|
|
248
|
+
except Exception:
|
|
249
|
+
args = {}
|
|
250
|
+
elif isinstance(raw_args, dict):
|
|
251
|
+
args = raw_args
|
|
252
|
+
calls.append((name, args if isinstance(args, dict) else {}))
|
|
253
|
+
|
|
254
|
+
payload = step.get("payload")
|
|
255
|
+
if isinstance(payload, dict) and step.get("type") == "tool_call_scheduled":
|
|
256
|
+
args = payload.get("input")
|
|
257
|
+
calls.append((str(payload.get("toolName", "")), args if isinstance(args, dict) else {}))
|
|
258
|
+
|
|
89
259
|
message = step.get("message")
|
|
90
260
|
if isinstance(message, dict):
|
|
91
261
|
mc = message.get("content")
|
|
@@ -96,6 +266,21 @@ def _extract_step_tool_calls(step: dict) -> List[Tuple[str, dict]]:
|
|
|
96
266
|
calls.append((str(block.get("name", "")), inp if isinstance(inp, dict) else {}))
|
|
97
267
|
return calls
|
|
98
268
|
|
|
269
|
+
_INJECTED_PROMPT_MARKERS = (
|
|
270
|
+
"<system-reminder",
|
|
271
|
+
"critical: respond with text",
|
|
272
|
+
"respond with text only",
|
|
273
|
+
"[tokensafe",
|
|
274
|
+
"[oumv",
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _is_injected_prompt(text: str) -> bool:
|
|
279
|
+
"""True for harness-injected reminders that arrive as user-role messages."""
|
|
280
|
+
lowered = text.lower()
|
|
281
|
+
return any(marker in lowered for marker in _INJECTED_PROMPT_MARKERS)
|
|
282
|
+
|
|
283
|
+
|
|
99
284
|
def _clean_goal_text(text: str) -> str:
|
|
100
285
|
"""Extracts a clean, single-sentence goal from raw user text or prompt."""
|
|
101
286
|
if not text:
|
|
@@ -143,6 +328,8 @@ class HistoryCompactor:
|
|
|
143
328
|
|
|
144
329
|
if source == "USER_EXPLICIT" or stype == "USER_INPUT" or role == "user":
|
|
145
330
|
raw_txt = _extract_step_text(step)
|
|
331
|
+
if _is_injected_prompt(raw_txt):
|
|
332
|
+
continue
|
|
146
333
|
cleaned = _clean_goal_text(raw_txt)
|
|
147
334
|
if cleaned:
|
|
148
335
|
active_goal = cleaned
|
|
@@ -152,6 +339,8 @@ class HistoryCompactor:
|
|
|
152
339
|
# Fallback to key turns if any
|
|
153
340
|
for step in steps:
|
|
154
341
|
raw_txt = _extract_step_text(step)
|
|
342
|
+
if _is_injected_prompt(raw_txt):
|
|
343
|
+
continue
|
|
155
344
|
cleaned = _clean_goal_text(raw_txt)
|
|
156
345
|
if cleaned and len(cleaned) > 15:
|
|
157
346
|
active_goal = cleaned
|
|
@@ -261,9 +450,18 @@ class HistoryCompactor:
|
|
|
261
450
|
line = line.strip()
|
|
262
451
|
if line:
|
|
263
452
|
try:
|
|
264
|
-
|
|
453
|
+
parsed = json.loads(line)
|
|
265
454
|
except Exception:
|
|
266
|
-
|
|
455
|
+
continue
|
|
456
|
+
# A model-io record whose newest message is the user's
|
|
457
|
+
# prompt is the turn boundary the digest looks for.
|
|
458
|
+
if (
|
|
459
|
+
isinstance(parsed, dict)
|
|
460
|
+
and parsed.get("type") == "model_io"
|
|
461
|
+
and _model_io_parts(parsed)[2]
|
|
462
|
+
):
|
|
463
|
+
parsed["role"] = "user"
|
|
464
|
+
steps.append(parsed)
|
|
267
465
|
except Exception:
|
|
268
466
|
return None, 0, 0, {}
|
|
269
467
|
|
package/src/mcp_server.py
CHANGED
|
@@ -39,10 +39,11 @@ from src.guard import TokenSafeGuard
|
|
|
39
39
|
from src.scoped_search import ScopedSearch
|
|
40
40
|
from src.license_manager import LicenseManager
|
|
41
41
|
from src.paths import get_active_workspace, is_plugin_or_system_dir
|
|
42
|
+
from src.session_context import current_root, current_session_id
|
|
42
43
|
|
|
43
44
|
SERVER_INFO = {
|
|
44
45
|
"name": "tokensafe-mcp",
|
|
45
|
-
"version": "4.
|
|
46
|
+
"version": "4.7.0"
|
|
46
47
|
}
|
|
47
48
|
|
|
48
49
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -65,9 +66,25 @@ def _set_mcp_client(name: str):
|
|
|
65
66
|
|
|
66
67
|
|
|
67
68
|
def _mcp_session_id() -> str:
|
|
69
|
+
"""Metrics key for the current call.
|
|
70
|
+
|
|
71
|
+
An explicit session scope (ACP agent server, in-process loop, tests) wins:
|
|
72
|
+
one process can own several sessions, and mixing their metrics or pointer
|
|
73
|
+
caches together is what the legacy global client name did."""
|
|
74
|
+
scoped = current_session_id()
|
|
75
|
+
if scoped:
|
|
76
|
+
return scoped
|
|
68
77
|
return f"mcp:{_MCP_CLIENT_NAME}" if _MCP_CLIENT_NAME else "mcp_session"
|
|
69
78
|
|
|
70
79
|
|
|
80
|
+
def _workspace_root() -> Optional[str]:
|
|
81
|
+
"""Project root for relative-path resolution.
|
|
82
|
+
|
|
83
|
+
Session scope first, then the machine-wide marker written by lifecycle
|
|
84
|
+
hooks. Never returns scratch space (``get_active_workspace`` filters it)."""
|
|
85
|
+
return current_root() or get_active_workspace()
|
|
86
|
+
|
|
87
|
+
|
|
71
88
|
def _client_supports_pointers() -> bool:
|
|
72
89
|
"""Out-of-the-box capability detection (zero env vars): returns True once the
|
|
73
90
|
MCP client has fetched tools/list (seeing force_full) or identified as an
|
|
@@ -981,7 +998,7 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
|
|
|
981
998
|
Safely resolves the target project root without falling back to system root dirs or plugin dirs.
|
|
982
999
|
"""
|
|
983
1000
|
target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory")
|
|
984
|
-
active_ws =
|
|
1001
|
+
active_ws = _workspace_root()
|
|
985
1002
|
|
|
986
1003
|
if target:
|
|
987
1004
|
if not os.path.isabs(target):
|
|
@@ -1265,7 +1282,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
1265
1282
|
or ("monthly limit (" in text_out and "optimizations paused" in text_out)
|
|
1266
1283
|
)
|
|
1267
1284
|
if text_out and path and not is_ranged and not is_quota_truncated:
|
|
1268
|
-
active_ws =
|
|
1285
|
+
active_ws = _workspace_root()
|
|
1269
1286
|
if not os.path.isabs(path) and active_ws and os.path.exists(os.path.join(active_ws, path)):
|
|
1270
1287
|
abs_path = os.path.abspath(os.path.join(active_ws, path))
|
|
1271
1288
|
else:
|
|
@@ -1356,6 +1373,21 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1356
1373
|
elif args.get("package_name") and not (args.get("path") or args.get("file_path") or args.get("file")):
|
|
1357
1374
|
name = "slice_external_type"
|
|
1358
1375
|
elif name == "scoped_search":
|
|
1376
|
+
# Schema contract: `path` is "Directory path (default project root)",
|
|
1377
|
+
# while `queries[].path` is a sub-scope. When the caller passes an
|
|
1378
|
+
# absolute directory and no explicit root, promote it to the root.
|
|
1379
|
+
# Without this, batch_search validated the path against the machine-wide
|
|
1380
|
+
# active-workspace marker (which may belong to another repo or a stale
|
|
1381
|
+
# temp dir) and rejected a path that is demonstrably inside the project.
|
|
1382
|
+
_raw_path = args.get("path")
|
|
1383
|
+
if (
|
|
1384
|
+
_raw_path
|
|
1385
|
+
and not (args.get("cwd") or args.get("project_path"))
|
|
1386
|
+
and os.path.isabs(str(_raw_path))
|
|
1387
|
+
and os.path.isdir(str(_raw_path))
|
|
1388
|
+
):
|
|
1389
|
+
args = dict(args, project_path=str(_raw_path))
|
|
1390
|
+
args.pop("path", None)
|
|
1359
1391
|
mode = str(args.get("mode") or "").strip().lower()
|
|
1360
1392
|
if args.get("queries"):
|
|
1361
1393
|
name = "batch_search"
|
|
@@ -1444,7 +1476,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1444
1476
|
if start_line is not None:
|
|
1445
1477
|
start_line = max(1, start_line)
|
|
1446
1478
|
|
|
1447
|
-
active_ws =
|
|
1479
|
+
active_ws = _workspace_root()
|
|
1448
1480
|
if path and not os.path.isabs(path):
|
|
1449
1481
|
if active_ws and os.path.exists(os.path.join(active_ws, path)):
|
|
1450
1482
|
path = os.path.abspath(os.path.join(active_ws, path))
|
|
@@ -1770,7 +1802,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1770
1802
|
inc_deps, _eff_dep_mode = _resolve_dep_mode(args)
|
|
1771
1803
|
max_tokens = _safe_int(os.environ.get("TOKENSAFE_BUNDLE_MAX_TOKENS"), 6000, lo=1000, hi=50000)
|
|
1772
1804
|
|
|
1773
|
-
active_ws =
|
|
1805
|
+
active_ws = _workspace_root()
|
|
1774
1806
|
by_file: Dict[str, List[str]] = {}
|
|
1775
1807
|
for t in targets:
|
|
1776
1808
|
if not isinstance(t, dict) or not str(t.get("path") or "").strip():
|
|
@@ -2283,7 +2315,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2283
2315
|
return _fallback_error("list_dir", "missing required 'path' argument")
|
|
2284
2316
|
|
|
2285
2317
|
# Resolve path relative to active workspace, cwd, or absolute
|
|
2286
|
-
active_ws =
|
|
2318
|
+
active_ws = _workspace_root()
|
|
2287
2319
|
if not os.path.isabs(path):
|
|
2288
2320
|
if active_ws and os.path.isdir(os.path.join(active_ws, path)):
|
|
2289
2321
|
abs_path = os.path.abspath(os.path.join(active_ws, path))
|
|
@@ -2323,7 +2355,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2323
2355
|
|
|
2324
2356
|
raw_scope = str(args.get("scope") or "all").strip()
|
|
2325
2357
|
raw_path = args.get("project_path") or args.get("path") or args.get("root_dir") or args.get("directory")
|
|
2326
|
-
active_ws =
|
|
2358
|
+
active_ws = _workspace_root()
|
|
2327
2359
|
|
|
2328
2360
|
# 1. Resolve base directory safely without scanning plugin or system roots
|
|
2329
2361
|
if raw_path:
|
|
@@ -2459,7 +2491,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2459
2491
|
pkg = str(args.get("package_name") or args.get("package") or "").strip()
|
|
2460
2492
|
lock_p = str(args.get("lockfile_path") or args.get("path") or "").strip() or None
|
|
2461
2493
|
if lock_p and not os.path.isabs(lock_p):
|
|
2462
|
-
active_ws =
|
|
2494
|
+
active_ws = _workspace_root()
|
|
2463
2495
|
if active_ws and os.path.exists(os.path.join(active_ws, lock_p)):
|
|
2464
2496
|
lock_p = os.path.abspath(os.path.join(active_ws, lock_p))
|
|
2465
2497
|
if not pkg:
|
|
@@ -2467,7 +2499,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2467
2499
|
try:
|
|
2468
2500
|
from src.format_parsers.lockfiles import LockfileReducer
|
|
2469
2501
|
if not lock_p:
|
|
2470
|
-
active_ws =
|
|
2502
|
+
active_ws = _workspace_root()
|
|
2471
2503
|
if active_ws and hasattr(LockfileReducer, "find_lockfile"):
|
|
2472
2504
|
orig_cwd = os.getcwd()
|
|
2473
2505
|
try:
|
|
@@ -2672,7 +2704,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2672
2704
|
verify = args.get("verify")
|
|
2673
2705
|
verify_timeout = int(args.get("verify_timeout_sec") or 30)
|
|
2674
2706
|
raw_cwd = args.get("cwd")
|
|
2675
|
-
active_ws =
|
|
2707
|
+
active_ws = _workspace_root()
|
|
2676
2708
|
if raw_cwd:
|
|
2677
2709
|
if not os.path.isabs(str(raw_cwd)) and active_ws and os.path.isdir(os.path.join(active_ws, str(raw_cwd))):
|
|
2678
2710
|
cwd = os.path.abspath(os.path.join(active_ws, str(raw_cwd)))
|
|
@@ -2792,7 +2824,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2792
2824
|
return _fallback_error("batch_search", "missing required 'queries' list")
|
|
2793
2825
|
|
|
2794
2826
|
raw_cwd = args.get("cwd") or args.get("project_path") or args.get("path")
|
|
2795
|
-
active_ws =
|
|
2827
|
+
active_ws = _workspace_root()
|
|
2796
2828
|
if raw_cwd:
|
|
2797
2829
|
if not os.path.isabs(raw_cwd) and active_ws and os.path.isdir(os.path.join(active_ws, raw_cwd)):
|
|
2798
2830
|
cwd = os.path.abspath(os.path.join(active_ws, raw_cwd))
|
|
@@ -2815,12 +2847,23 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2815
2847
|
sub_p = q_copy.get("path")
|
|
2816
2848
|
if sub_p:
|
|
2817
2849
|
sub_abs = os.path.realpath(os.path.normpath(os.path.join(cwd, str(sub_p))))
|
|
2850
|
+
if is_plugin_or_system_dir(sub_abs):
|
|
2851
|
+
return _fallback_error(
|
|
2852
|
+
"batch_search",
|
|
2853
|
+
f"refusing subquery path in a system/plugin dir '{sub_abs}' "
|
|
2854
|
+
f"(project root '{real_cwd}')",
|
|
2855
|
+
)
|
|
2818
2856
|
try:
|
|
2819
2857
|
inside = os.path.commonpath([real_cwd, sub_abs]) == real_cwd
|
|
2820
2858
|
except ValueError:
|
|
2821
2859
|
inside = False
|
|
2822
|
-
if not inside
|
|
2823
|
-
return _fallback_error(
|
|
2860
|
+
if not inside:
|
|
2861
|
+
return _fallback_error(
|
|
2862
|
+
"batch_search",
|
|
2863
|
+
f"subquery path '{sub_p}' resolves to '{sub_abs}', outside project root "
|
|
2864
|
+
f"'{real_cwd}'. Pass the repo root as project_path and a repo-relative "
|
|
2865
|
+
f"path, or omit path entirely.",
|
|
2866
|
+
)
|
|
2824
2867
|
if is_quota_exceeded:
|
|
2825
2868
|
q_copy["max_results"] = min(_safe_int(q_copy.get("max_results"), 3, lo=1, hi=100), 3)
|
|
2826
2869
|
safe_queries.append(q_copy)
|
package/src/paths.py
CHANGED
|
@@ -127,12 +127,47 @@ def is_plugin_or_system_dir(path: str) -> bool:
|
|
|
127
127
|
return False
|
|
128
128
|
|
|
129
129
|
|
|
130
|
+
_TRANSIENT_ROOTS = ("/tmp", "/var/tmp", "/private/tmp", "/var/folders", "/private/var/folders")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def is_transient_dir(path: str) -> bool:
|
|
134
|
+
"""True for OS scratch space (tempfile/TMPDIR, /tmp, /var/folders).
|
|
135
|
+
|
|
136
|
+
A temp directory is a legitimate workspace for a test process, but it must
|
|
137
|
+
never become the machine-wide active-project marker: every other agent
|
|
138
|
+
session would then validate real repo paths against a directory that is
|
|
139
|
+
about to disappear, and reject them as "outside project root".
|
|
140
|
+
"""
|
|
141
|
+
if not path:
|
|
142
|
+
return True
|
|
143
|
+
real = os.path.realpath(os.path.abspath(path))
|
|
144
|
+
roots = [os.path.realpath(p) for p in _TRANSIENT_ROOTS]
|
|
145
|
+
try:
|
|
146
|
+
import tempfile
|
|
147
|
+
roots.append(os.path.realpath(tempfile.gettempdir()))
|
|
148
|
+
except Exception:
|
|
149
|
+
pass
|
|
150
|
+
for root in roots:
|
|
151
|
+
if not root or root == os.sep:
|
|
152
|
+
continue
|
|
153
|
+
if real == root:
|
|
154
|
+
return True
|
|
155
|
+
try:
|
|
156
|
+
if os.path.commonpath([real, root]) == root:
|
|
157
|
+
return True
|
|
158
|
+
except ValueError:
|
|
159
|
+
continue
|
|
160
|
+
return False
|
|
161
|
+
|
|
162
|
+
|
|
130
163
|
def save_active_workspace(path: str) -> None:
|
|
131
164
|
"""Records the active user workspace directory observed by lifecycle hooks."""
|
|
132
165
|
if not path or not os.path.isabs(path) or not os.path.isdir(path):
|
|
133
166
|
return
|
|
134
167
|
if is_plugin_or_system_dir(path):
|
|
135
168
|
return
|
|
169
|
+
if is_transient_dir(path):
|
|
170
|
+
return
|
|
136
171
|
try:
|
|
137
172
|
import threading
|
|
138
173
|
data_dir = resolve_data_dir()
|
|
@@ -147,7 +182,11 @@ def save_active_workspace(path: str) -> None:
|
|
|
147
182
|
|
|
148
183
|
|
|
149
184
|
def get_active_workspace() -> Optional[str]:
|
|
150
|
-
"""Retrieves the last known active user workspace directory.
|
|
185
|
+
"""Retrieves the last known active user workspace directory.
|
|
186
|
+
|
|
187
|
+
A marker pointing at scratch space (already-poisoned installs, test
|
|
188
|
+
leftovers) is ignored rather than returned: it is never a usable project
|
|
189
|
+
root for a search or a read."""
|
|
151
190
|
try:
|
|
152
191
|
data_dir = resolve_data_dir()
|
|
153
192
|
marker = os.path.join(data_dir, ".active_workspace")
|
|
@@ -155,7 +194,7 @@ def get_active_workspace() -> Optional[str]:
|
|
|
155
194
|
with open(marker, "r", encoding="utf-8") as f:
|
|
156
195
|
path = f.read().strip()
|
|
157
196
|
if path and os.path.isabs(path) and os.path.isdir(path):
|
|
158
|
-
if not is_plugin_or_system_dir(path):
|
|
197
|
+
if not is_plugin_or_system_dir(path) and not is_transient_dir(path):
|
|
159
198
|
return path
|
|
160
199
|
except Exception:
|
|
161
200
|
pass
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Explicit per-session state: workspace root + metrics session id.
|
|
2
|
+
|
|
3
|
+
TokenSafe historically resolved both from process-global state: the machine-wide
|
|
4
|
+
``~/.tokensafe/data/.active_workspace`` marker and the module-level MCP client
|
|
5
|
+
name. That is fine for a one-shot hook process, but it breaks as soon as a
|
|
6
|
+
single process owns several sessions — the MCP server serving two editor
|
|
7
|
+
windows, or the ACP agent server running one prompt per thread. A search that
|
|
8
|
+
is demonstrably scoped to repo A gets validated against repo B (or a leftover
|
|
9
|
+
temp directory) and rejected as "outside project root".
|
|
10
|
+
|
|
11
|
+
This module makes the context explicit and cheap:
|
|
12
|
+
|
|
13
|
+
* ``SessionContext`` is immutable and carries root + session id + agent.
|
|
14
|
+
* ``session_scope(...)`` binds it to the current thread/task via a
|
|
15
|
+
ContextVar, so it propagates through the call stack without threading a
|
|
16
|
+
parameter through every handler.
|
|
17
|
+
* Consumers call ``current_root()`` / ``current_session_id(default)`` and
|
|
18
|
+
fall back to the legacy global marker only when no scope is active, which
|
|
19
|
+
keeps hook processes behaving exactly as before.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import os
|
|
25
|
+
from contextlib import contextmanager
|
|
26
|
+
from contextvars import ContextVar, Token
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from typing import Any, Dict, Iterator, Optional
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class SessionContext:
|
|
33
|
+
"""One agent session: where it works and how its metrics are keyed."""
|
|
34
|
+
|
|
35
|
+
session_id: str = "ephemeral"
|
|
36
|
+
root: Optional[str] = None
|
|
37
|
+
agent: str = ""
|
|
38
|
+
data: Dict[str, Any] = field(default_factory=dict)
|
|
39
|
+
|
|
40
|
+
def __post_init__(self) -> None:
|
|
41
|
+
if self.root:
|
|
42
|
+
object.__setattr__(self, "root", os.path.realpath(os.path.abspath(self.root)))
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def valid_root(self) -> Optional[str]:
|
|
46
|
+
"""Root only if it still exists on disk (temp dirs may be gone)."""
|
|
47
|
+
root = self.root
|
|
48
|
+
return root if root and os.path.isdir(root) else None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
_CURRENT: ContextVar[Optional[SessionContext]] = ContextVar(
|
|
52
|
+
"tokensafe_session_context", default=None
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def current() -> Optional[SessionContext]:
|
|
57
|
+
"""The active session context, or None when running outside a scope."""
|
|
58
|
+
return _CURRENT.get()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def current_root() -> Optional[str]:
|
|
62
|
+
"""Active workspace root, or None when no scope is bound."""
|
|
63
|
+
ctx = _CURRENT.get()
|
|
64
|
+
return ctx.valid_root if ctx else None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def current_session_id(default: str = "") -> str:
|
|
68
|
+
"""Active session id, or ``default`` when no scope is bound."""
|
|
69
|
+
ctx = _CURRENT.get()
|
|
70
|
+
if ctx and ctx.session_id:
|
|
71
|
+
return ctx.session_id
|
|
72
|
+
return default
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def activate(ctx: SessionContext) -> Token:
|
|
76
|
+
"""Bind ``ctx`` to the current context; returns a token for ``deactivate``."""
|
|
77
|
+
return _CURRENT.set(ctx)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def deactivate(token: Token) -> None:
|
|
81
|
+
"""Restore the previous context. Always pair with ``activate`` in ``finally``."""
|
|
82
|
+
_CURRENT.reset(token)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@contextmanager
|
|
86
|
+
def session_scope(
|
|
87
|
+
root: Optional[str] = None,
|
|
88
|
+
session_id: str = "ephemeral",
|
|
89
|
+
agent: str = "",
|
|
90
|
+
data: Optional[Dict[str, Any]] = None,
|
|
91
|
+
) -> Iterator[SessionContext]:
|
|
92
|
+
"""Bind a session for the duration of the block.
|
|
93
|
+
|
|
94
|
+
Threads do not inherit ContextVars, so a worker must open its own scope
|
|
95
|
+
(the ACP server does this per prompt).
|
|
96
|
+
"""
|
|
97
|
+
ctx = SessionContext(
|
|
98
|
+
session_id=session_id or "ephemeral",
|
|
99
|
+
root=root,
|
|
100
|
+
agent=agent,
|
|
101
|
+
data=dict(data or {}),
|
|
102
|
+
)
|
|
103
|
+
token = _CURRENT.set(ctx)
|
|
104
|
+
try:
|
|
105
|
+
yield ctx
|
|
106
|
+
finally:
|
|
107
|
+
_CURRENT.reset(token)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def resolve_path(path: str, root: Optional[str] = None) -> str:
|
|
111
|
+
"""Resolve ``path`` against an explicit root, then the active session root.
|
|
112
|
+
|
|
113
|
+
Absolute paths pass through unchanged. Unlike ``os.path.abspath`` this never
|
|
114
|
+
silently resolves against the process cwd, which is what the MCP server's
|
|
115
|
+
global-marker fallback used to do.
|
|
116
|
+
"""
|
|
117
|
+
if not path or os.path.isabs(path):
|
|
118
|
+
return path
|
|
119
|
+
base = root or current_root()
|
|
120
|
+
if base:
|
|
121
|
+
candidate = os.path.join(base, path)
|
|
122
|
+
if os.path.exists(candidate):
|
|
123
|
+
return os.path.abspath(candidate)
|
|
124
|
+
return os.path.abspath(path)
|
package/src/telemetry_sync.py
CHANGED
|
@@ -311,7 +311,7 @@ class TelemetrySync:
|
|
|
311
311
|
current_last_id = last_id
|
|
312
312
|
headers = {
|
|
313
313
|
"Content-Type": "application/json",
|
|
314
|
-
"User-Agent": "TokenSafe-Sync/4.
|
|
314
|
+
"User-Agent": "TokenSafe-Sync/4.7.0"
|
|
315
315
|
}
|
|
316
316
|
if active_key:
|
|
317
317
|
headers["Authorization"] = f"Bearer {active_key}"
|
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.7.0"
|
|
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
|