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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +8 -3
- package/bin/agy-tokens +1 -1
- package/bin/tokensafe +1 -1
- package/bin/tokensafe-acp.js +1 -1
- package/bin/tokensafe-mcp +1 -1
- package/bin/tokensafe.js +1 -1
- package/hooks/claude_code_hook.py +49 -45
- package/hooks/cursor_hook.py +8 -8
- package/hooks/kimi_hook.py +23 -23
- package/hooks/post_tool_use.py +6 -6
- package/hooks/pre_invocation.py +21 -17
- package/hooks/pre_tool_use.py +27 -27
- package/hooks/session_start.py +17 -17
- package/hooks/stop_hook.py +3 -3
- package/hooks/zcode_hook.py +2 -2
- package/kimi.plugin.json +2 -2
- package/mcp_config.json +1 -1
- package/package.json +5 -4
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/__init__.py +9 -5
- package/src/cli.py +11 -2429
- package/src/mcp_server.py +11 -5024
- package/src/proxy.py +11 -1803
- package/tokensafe/__init__.py +6 -0
- package/{src → tokensafe}/acp/__init__.py +2 -2
- package/{src → tokensafe}/acp/server.py +5 -5
- package/{src → tokensafe}/adapter_core.py +42 -17
- package/{src → tokensafe}/agent/__init__.py +1 -1
- package/{src → tokensafe}/agent/context.py +4 -4
- package/{src → tokensafe}/agent/loop.py +4 -4
- package/{src → tokensafe}/agent/providers.py +2 -2
- package/{src → tokensafe}/agent/tools.py +2 -2
- package/{src → tokensafe}/agent_firewall.py +68 -9
- package/{src → tokensafe}/angular_cli.py +4 -4
- package/{src → tokensafe}/auto_inject.py +37 -5
- package/{src → tokensafe}/batch_editor.py +185 -28
- package/tokensafe/batch_search.py +1191 -0
- package/{src → tokensafe}/bench/go_target.py +1 -1
- package/{src → tokensafe}/bench/mechanics.py +1 -1
- package/{src → tokensafe}/bench/react_target.py +1 -1
- package/{src → tokensafe}/bench/runner.py +4 -4
- package/{src → tokensafe}/benchmark.py +12 -12
- package/{src → tokensafe}/benchmark_real.py +18 -18
- package/{src → tokensafe}/build_parsers.py +3 -3
- package/{src → tokensafe}/bundle_probe.py +1 -1
- package/{src → tokensafe}/burn_monitor.py +3 -3
- package/{src → tokensafe}/cache_normalizer.py +1 -1
- package/tokensafe/cli.py +2490 -0
- package/{src → tokensafe}/command_sanitizer.py +94 -26
- package/{src → tokensafe}/compaction_recovery.py +5 -5
- package/{src → tokensafe}/compactor.py +148 -95
- package/{src → tokensafe}/context_index.py +194 -28
- package/{src → tokensafe}/cross_stack.py +2 -2
- package/{src → tokensafe}/dashboard.py +3 -3
- package/{src → tokensafe}/delegation.py +4 -4
- package/{src → tokensafe}/dependency_prefetcher.py +1 -1
- package/{src → tokensafe}/diff_slicer.py +2 -2
- package/{src → tokensafe}/distiller.py +7 -7
- package/{src → tokensafe}/distiller_cache.py +3 -3
- package/{src → tokensafe}/egress_counter.py +1 -1
- package/{src → tokensafe}/environment_auditor.py +7 -7
- package/{src → tokensafe}/file_state.py +2 -2
- package/{src → tokensafe}/format_invariants.py +1 -1
- package/tokensafe/format_parsers/__init__.py +20 -0
- package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
- package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
- package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
- package/{src → tokensafe}/format_parsers/json_log.py +1 -1
- package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
- package/{src → tokensafe}/format_parsers/tabular.py +1 -1
- package/{src → tokensafe}/fts_index.py +20 -11
- package/{src → tokensafe}/governor.py +143 -31
- package/{src → tokensafe}/graph_engine.py +769 -126
- package/{src → tokensafe}/guard.py +80 -25
- package/{src → tokensafe}/history_compactor.py +407 -133
- package/{src → tokensafe}/i18n_catalog.py +39 -14
- package/{src → tokensafe}/image_downscale.py +1 -1
- package/tokensafe/ingress_staging.py +384 -0
- package/{src → tokensafe}/installer.py +118 -61
- package/{src → tokensafe}/license_manager.py +9 -67
- package/{src → tokensafe}/live_relay.py +2 -2
- package/{src → tokensafe}/loop_detector.py +2 -2
- package/{src → tokensafe}/mcp_config_manager.py +2 -2
- package/{src → tokensafe}/mcp_proxy.py +4 -4
- package/tokensafe/mcp_server.py +5664 -0
- package/{src → tokensafe}/metrics.py +56 -21
- package/{src → tokensafe}/mistakes.py +4 -4
- package/{src → tokensafe}/oumv_brief.py +21 -3
- package/{src → tokensafe}/oumv_gateway.py +146 -49
- package/{src → tokensafe}/oumv_policy.py +1 -1
- package/{src → tokensafe}/paths.py +1 -1
- package/{src → tokensafe}/project_memory.py +4 -4
- package/tokensafe/proxy.py +2075 -0
- package/{src → tokensafe}/quality_score.py +4 -4
- package/tokensafe/read_baseline.py +192 -0
- package/tokensafe/repo_compute.py +332 -0
- package/{src → tokensafe}/result_ledger.py +19 -19
- package/{src → tokensafe}/retrofit.py +6 -6
- package/{src → tokensafe}/savings.py +3 -3
- package/tokensafe/schema_slicer.py +1087 -0
- package/{src → tokensafe}/scoped_search.py +144 -6
- package/{src → tokensafe}/secret_redactor.py +22 -0
- package/{src → tokensafe}/session_brief.py +8 -8
- package/{src → tokensafe}/skeletonizer.py +89 -26
- package/{src → tokensafe}/slicer.py +3 -2
- package/{src → tokensafe}/snapshot.py +1 -1
- package/{src → tokensafe}/stash.py +1 -1
- package/{src → tokensafe}/statusline.py +1 -1
- package/{src → tokensafe}/superseded.py +22 -4
- package/{src → tokensafe}/team_cache.py +3 -3
- package/{src → tokensafe}/telemetry_sync.py +63 -11
- package/{src → tokensafe}/test_parsers.py +3 -3
- package/{src → tokensafe}/thinking_fold.py +3 -3
- package/{src → tokensafe}/tokenizer.py +37 -1
- package/{src → tokensafe}/tool_pruner.py +3 -3
- package/{src → tokensafe}/transcript_analyzer.py +1 -1
- package/{src → tokensafe}/transcript_recall.py +8 -8
- package/{src → tokensafe}/type_slicer.py +3 -3
- package/{src → tokensafe}/usage_ledger.py +4 -4
- package/{src → tokensafe}/version_checker.py +6 -6
- package/{src → tokensafe}/web_reader.py +86 -8
- package/{src → tokensafe}/workspace_roots.py +2 -2
- package/src/batch_search.py +0 -589
- package/src/format_parsers/__init__.py +0 -20
- package/src/schema_slicer.py +0 -578
- /package/{src → tokensafe}/agent/pricing.py +0 -0
- /package/{src → tokensafe}/atomic_io.py +0 -0
- /package/{src → tokensafe}/backend_release.py +0 -0
- /package/{src → tokensafe}/bench/__init__.py +0 -0
- /package/{src → tokensafe}/bench/driver.py +0 -0
- /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
- /package/{src → tokensafe}/bench_scenarios.json +0 -0
- /package/{src → tokensafe}/competitors.py +0 -0
- /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
- /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
- /package/{src → tokensafe}/globmatch.py +0 -0
- /package/{src → tokensafe}/host_capabilities.py +0 -0
- /package/{src → tokensafe}/json_repair.py +0 -0
- /package/{src → tokensafe}/route_index.py +0 -0
- /package/{src → tokensafe}/scaffold.py +0 -0
- /package/{src → tokensafe}/session_context.py +0 -0
- /package/{src → tokensafe}/ssl_context.py +0 -0
- /package/{src → tokensafe}/stdio_io.py +0 -0
- /package/{src → tokensafe}/syntax_guard.py +0 -0
- /package/{src → tokensafe}/toml_mcp_config.py +0 -0
- /package/{src → tokensafe}/treesitter_backend.py +0 -0
- /package/{src → tokensafe}/win_paths.py +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""Agent Client Protocol adapter: JSON-RPC 2.0 over stdio for editors.
|
|
2
2
|
|
|
3
3
|
The server module is imported lazily: importing it here would execute the
|
|
4
|
-
module twice under ``python -m
|
|
4
|
+
module twice under ``python -m tokensafe.acp.server`` and confuse the stdio loop.
|
|
5
5
|
"""
|
|
6
6
|
|
|
7
7
|
__all__ = ["AcpServer", "run_acp_server"]
|
|
@@ -9,7 +9,7 @@ __all__ = ["AcpServer", "run_acp_server"]
|
|
|
9
9
|
|
|
10
10
|
def __getattr__(name):
|
|
11
11
|
if name in __all__:
|
|
12
|
-
from
|
|
12
|
+
from tokensafe.acp import server as _server
|
|
13
13
|
|
|
14
14
|
return getattr(_server, name)
|
|
15
15
|
raise AttributeError(name)
|
|
@@ -32,9 +32,9 @@ import uuid
|
|
|
32
32
|
from dataclasses import dataclass, field
|
|
33
33
|
from typing import Any, Callable, Dict, IO, List, Optional, Set
|
|
34
34
|
|
|
35
|
-
from
|
|
36
|
-
from
|
|
37
|
-
from
|
|
35
|
+
from tokensafe.agent.loop import DEFAULT_SYSTEM_PROMPT, AgentConfig, AgentLoop, RunResult
|
|
36
|
+
from tokensafe.agent.providers import Provider, ProviderError, ToolCall, resolve_provider
|
|
37
|
+
from tokensafe.agent.tools import tool_kind
|
|
38
38
|
|
|
39
39
|
PROTOCOL_VERSION = 1
|
|
40
40
|
SERVER_NAME = "tokensafe-agent"
|
|
@@ -433,7 +433,7 @@ def _default_provider(root: str, session_id: str) -> Provider:
|
|
|
433
433
|
|
|
434
434
|
def _version() -> str:
|
|
435
435
|
try:
|
|
436
|
-
from
|
|
436
|
+
from tokensafe.version_checker import CURRENT_VERSION
|
|
437
437
|
return CURRENT_VERSION
|
|
438
438
|
except Exception:
|
|
439
439
|
return "0.0.0"
|
|
@@ -442,7 +442,7 @@ def _version() -> str:
|
|
|
442
442
|
def run_acp_server(provider_factory: Optional[Callable[[str, str], Provider]] = None) -> None:
|
|
443
443
|
# Windows pipes default to the ANSI code page; agent responses routinely
|
|
444
444
|
# carry non-Latin-1 text.
|
|
445
|
-
from
|
|
445
|
+
from tokensafe.stdio_io import ensure_utf8_stdio
|
|
446
446
|
|
|
447
447
|
ensure_utf8_stdio()
|
|
448
448
|
# Editors expect the prompt; headless harnesses set off|all explicitly.
|
|
@@ -19,7 +19,7 @@ import json
|
|
|
19
19
|
import time
|
|
20
20
|
from typing import Dict, Any, List, Optional, Tuple
|
|
21
21
|
|
|
22
|
-
from
|
|
22
|
+
from tokensafe.tokenizer import count_tokens
|
|
23
23
|
|
|
24
24
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
25
25
|
if PROJECT_ROOT not in sys.path:
|
|
@@ -99,7 +99,7 @@ _JUNK_READ_PATTERNS = [
|
|
|
99
99
|
|
|
100
100
|
def _get_tracker():
|
|
101
101
|
try:
|
|
102
|
-
from
|
|
102
|
+
from tokensafe.metrics import MetricsTracker
|
|
103
103
|
return MetricsTracker()
|
|
104
104
|
except Exception:
|
|
105
105
|
return None
|
|
@@ -151,7 +151,7 @@ def _sniff_transcript_model(transcript_path: str) -> str:
|
|
|
151
151
|
|
|
152
152
|
def _read_proxy_state_model() -> str:
|
|
153
153
|
try:
|
|
154
|
-
from
|
|
154
|
+
from tokensafe.paths import resolve_data_dir
|
|
155
155
|
state_path = os.path.join(resolve_data_dir(), "proxy_state.json")
|
|
156
156
|
with open(state_path, "r", encoding="utf-8") as f:
|
|
157
157
|
state = json.load(f)
|
|
@@ -182,9 +182,31 @@ def compact_for_injection(prompt: str, agent: str, session_id: str, transcript_p
|
|
|
182
182
|
meta: Dict[str, Any] = {"agent": agent, "compacted": False}
|
|
183
183
|
if not prompt or len(prompt.strip()) < 5:
|
|
184
184
|
return "", meta
|
|
185
|
+
# Lossless ingress staging: a long prompt gets a compact summary plus a
|
|
186
|
+
# recovery handle, so the exact text stays retrievable instead of being
|
|
187
|
+
# irreversibly summarized.
|
|
185
188
|
try:
|
|
186
|
-
from
|
|
187
|
-
|
|
189
|
+
from tokensafe.ingress_staging import stage as _stage_ingress
|
|
190
|
+
|
|
191
|
+
staged = _stage_ingress(prompt, agent=agent, session_id=session_id)
|
|
192
|
+
if staged:
|
|
193
|
+
meta.update({
|
|
194
|
+
"compacted": True,
|
|
195
|
+
"ingress_staged": True,
|
|
196
|
+
"ingress_hash": staged["hash"],
|
|
197
|
+
"ingress_sections": len(staged["sections"]),
|
|
198
|
+
"original_tokens": staged["original_tokens"],
|
|
199
|
+
"injected_tokens": staged["injected_tokens"],
|
|
200
|
+
"saved_tokens": staged["saved_tokens"],
|
|
201
|
+
"reduction_pct": staged["reduction_pct"],
|
|
202
|
+
"tier": "INGRESS",
|
|
203
|
+
})
|
|
204
|
+
return staged["context_text"], meta
|
|
205
|
+
except Exception:
|
|
206
|
+
pass
|
|
207
|
+
try:
|
|
208
|
+
from tokensafe.compactor import PromptCompactor
|
|
209
|
+
from tokensafe.tokenizer import count_tokens
|
|
188
210
|
compaction = PromptCompactor.compact(prompt, enable_distill=False)
|
|
189
211
|
saved = compaction.get("saved_tokens", 0)
|
|
190
212
|
if saved < 5:
|
|
@@ -250,7 +272,7 @@ def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "",
|
|
|
250
272
|
# raw code search with the MCP-tools guidance) instead of a regex subset.
|
|
251
273
|
# Fail-open on import problems, like every adapter guard path.
|
|
252
274
|
try:
|
|
253
|
-
from
|
|
275
|
+
from tokensafe.guard import TokenSafeGuard
|
|
254
276
|
guard_res = TokenSafeGuard.inspect_command(cmd, cwd=cwd or None)
|
|
255
277
|
except Exception:
|
|
256
278
|
guard_res = None
|
|
@@ -333,7 +355,7 @@ def guard_file_content(file_path: str, content: str, agent: str = "", session_id
|
|
|
333
355
|
if not content or not isinstance(content, str):
|
|
334
356
|
return result
|
|
335
357
|
try:
|
|
336
|
-
from
|
|
358
|
+
from tokensafe.guard import TokenSafeGuard
|
|
337
359
|
guard_res = TokenSafeGuard.inspect_file_write(file_path or "", content)
|
|
338
360
|
except Exception:
|
|
339
361
|
return result
|
|
@@ -639,9 +661,9 @@ def get_oumv_read_edit_advisory(workspace_dir: str, file_path: str, session_id:
|
|
|
639
661
|
if not file_path:
|
|
640
662
|
return None
|
|
641
663
|
try:
|
|
642
|
-
from
|
|
643
|
-
from
|
|
644
|
-
from
|
|
664
|
+
from tokensafe.paths import get_active_workspace, resolve_data_dir
|
|
665
|
+
from tokensafe.retrofit import is_path_in_supported_oumv_scope
|
|
666
|
+
from tokensafe.oumv_gateway import OUMVGateway
|
|
645
667
|
import hashlib
|
|
646
668
|
|
|
647
669
|
ws = workspace_dir or get_active_workspace()
|
|
@@ -737,11 +759,11 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
|
|
|
737
759
|
|
|
738
760
|
# 1. Loop Detector Guard (all tools)
|
|
739
761
|
try:
|
|
740
|
-
from
|
|
762
|
+
from tokensafe.loop_detector import LoopDetector
|
|
741
763
|
is_loop, repeat_count, loop_msg = LoopDetector.check_loop(session_id, tool, tool_input)
|
|
742
764
|
if is_loop:
|
|
743
765
|
try:
|
|
744
|
-
from
|
|
766
|
+
from tokensafe.mistakes import MistakesLedger
|
|
745
767
|
MistakesLedger.record_from_loop(tool, tool_input, repeat_count, project_root=cwd or os.getcwd())
|
|
746
768
|
except Exception:
|
|
747
769
|
pass
|
|
@@ -767,7 +789,7 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
|
|
|
767
789
|
if verdict["decision"] in ("deny", "ask"):
|
|
768
790
|
return _cc_decision(verdict["decision"], verdict["reason"])
|
|
769
791
|
try:
|
|
770
|
-
from
|
|
792
|
+
from tokensafe.mistakes import MistakesLedger
|
|
771
793
|
is_blocked, m_reason = MistakesLedger.should_force_ask(command, action_type="command", project_root=cwd or os.getcwd())
|
|
772
794
|
if is_blocked:
|
|
773
795
|
return _cc_decision("ask", f"[TokenSafe Anti-Stuck Guard] {m_reason}")
|
|
@@ -783,7 +805,7 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
|
|
|
783
805
|
if sec_verdict["decision"] == "deny":
|
|
784
806
|
return _cc_decision("deny", sec_verdict["reason"])
|
|
785
807
|
try:
|
|
786
|
-
from
|
|
808
|
+
from tokensafe.mistakes import MistakesLedger
|
|
787
809
|
is_blocked, m_reason = MistakesLedger.should_force_ask(file_path, action_type="edit_file", project_root=cwd or os.getcwd())
|
|
788
810
|
if is_blocked:
|
|
789
811
|
return _cc_decision("ask", f"[TokenSafe Anti-Stuck Guard] {m_reason}")
|
|
@@ -800,14 +822,14 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
|
|
|
800
822
|
if sec_verdict["decision"] == "deny":
|
|
801
823
|
return _cc_decision("deny", sec_verdict["reason"])
|
|
802
824
|
try:
|
|
803
|
-
from
|
|
825
|
+
from tokensafe.mistakes import MistakesLedger
|
|
804
826
|
is_blocked, m_reason = MistakesLedger.should_force_ask(file_path, action_type="edit_file", project_root=cwd or os.getcwd())
|
|
805
827
|
if is_blocked:
|
|
806
828
|
return _cc_decision("ask", f"[TokenSafe Anti-Stuck Guard] {m_reason}")
|
|
807
829
|
except Exception:
|
|
808
830
|
pass
|
|
809
831
|
try:
|
|
810
|
-
from
|
|
832
|
+
from tokensafe.file_state import FileState
|
|
811
833
|
if file_path and FileState.guard_enabled():
|
|
812
834
|
stale = FileState.check_stale(file_path)
|
|
813
835
|
if stale:
|
|
@@ -868,10 +890,13 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
|
|
|
868
890
|
) if msg
|
|
869
891
|
]
|
|
870
892
|
if advisories:
|
|
893
|
+
# Advisory only: no permissionDecision, so the user's normal Read
|
|
894
|
+
# permission flow still runs. Returning "allow" here auto-approved
|
|
895
|
+
# any large read (even outside the project) just because a hint fired,
|
|
896
|
+
# the same bug the edit branch above already removed.
|
|
871
897
|
return {
|
|
872
898
|
"hookSpecificOutput": {
|
|
873
899
|
"hookEventName": "PreToolUse",
|
|
874
|
-
"permissionDecision": "allow",
|
|
875
900
|
"additionalContext": "\n".join(advisories),
|
|
876
901
|
}
|
|
877
902
|
}
|
|
@@ -5,7 +5,7 @@ TokenSafe reacted to it. This package owns the turn instead — provider router,
|
|
|
5
5
|
streaming, tool dispatch and context governance in one loop — so the same
|
|
6
6
|
kernel can be driven by the ACP server, the CLI, or a test harness.
|
|
7
7
|
|
|
8
|
-
Import cost matters here: nothing in this package imports ``
|
|
8
|
+
Import cost matters here: nothing in this package imports ``tokensafe.mcp_server`` at
|
|
9
9
|
module level, because the MCP server is a large dependency graph and the
|
|
10
10
|
provider layer must stay usable (and testable) without it.
|
|
11
11
|
"""
|
|
@@ -11,10 +11,10 @@ from __future__ import annotations
|
|
|
11
11
|
import json
|
|
12
12
|
from typing import Any, Dict, List, Optional, Tuple
|
|
13
13
|
|
|
14
|
-
from
|
|
15
|
-
from
|
|
16
|
-
from
|
|
17
|
-
from
|
|
14
|
+
from tokensafe.compactor import PromptCompactor
|
|
15
|
+
from tokensafe.governor import ContextBudget, ContextGovernor
|
|
16
|
+
from tokensafe.history_compactor import HistoryCompactor
|
|
17
|
+
from tokensafe.tokenizer import count_tokens
|
|
18
18
|
|
|
19
19
|
# Below this saving a prompt rewrite is noise: it burns a rewrite and changes
|
|
20
20
|
# the model's instructions for less than a line of text.
|
|
@@ -25,10 +25,10 @@ import threading
|
|
|
25
25
|
from dataclasses import dataclass, field
|
|
26
26
|
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
|
|
27
27
|
|
|
28
|
-
from
|
|
29
|
-
from
|
|
30
|
-
from
|
|
31
|
-
from
|
|
28
|
+
from tokensafe.agent import context as kernel
|
|
29
|
+
from tokensafe.agent.providers import Provider, ProviderError, ToolCall, Usage, resolve_provider
|
|
30
|
+
from tokensafe.agent.tools import DEFAULT_TOOL_NAMES, ToolResult, dispatch_tool, tool_kind, tool_schemas
|
|
31
|
+
from tokensafe.session_context import current_root, session_scope
|
|
32
32
|
|
|
33
33
|
EventSink = Callable[[Dict[str, Any]], None]
|
|
34
34
|
|
|
@@ -22,8 +22,8 @@ import urllib.request
|
|
|
22
22
|
from dataclasses import dataclass, field
|
|
23
23
|
from typing import Any, Dict, Iterator, List, Optional
|
|
24
24
|
|
|
25
|
-
from
|
|
26
|
-
from
|
|
25
|
+
from tokensafe.agent.pricing import usd as price_usd
|
|
26
|
+
from tokensafe.json_repair import parse_tool_arguments
|
|
27
27
|
|
|
28
28
|
|
|
29
29
|
class ProviderError(RuntimeError):
|
|
@@ -49,7 +49,7 @@ class ToolResult:
|
|
|
49
49
|
|
|
50
50
|
def tool_schemas(names: Optional[Sequence[str]] = None) -> List[Dict[str, Any]]:
|
|
51
51
|
"""OpenAI/Anthropic-neutral schemas straight from the MCP tool registry."""
|
|
52
|
-
from
|
|
52
|
+
from tokensafe.mcp_server import TOOLS
|
|
53
53
|
|
|
54
54
|
index = {tool["name"]: tool for tool in TOOLS}
|
|
55
55
|
selected = list(names or DEFAULT_TOOL_NAMES)
|
|
@@ -74,7 +74,7 @@ def tool_kind(name: str) -> str:
|
|
|
74
74
|
|
|
75
75
|
def dispatch_tool(name: str, arguments: Dict[str, Any]) -> ToolResult:
|
|
76
76
|
"""Execute one tool call through the canonical MCP handler."""
|
|
77
|
-
from
|
|
77
|
+
from tokensafe.mcp_server import handle_tool_call
|
|
78
78
|
|
|
79
79
|
try:
|
|
80
80
|
result = handle_tool_call(name, dict(arguments or {}))
|
|
@@ -13,9 +13,16 @@ import os
|
|
|
13
13
|
import time
|
|
14
14
|
import sqlite3
|
|
15
15
|
import hashlib
|
|
16
|
+
import threading
|
|
17
|
+
from collections import OrderedDict
|
|
16
18
|
from typing import Tuple, Optional, Dict, Any
|
|
17
|
-
from
|
|
18
|
-
from
|
|
19
|
+
from tokensafe.metrics import MetricsTracker
|
|
20
|
+
from tokensafe.tokenizer import count_tokens
|
|
21
|
+
|
|
22
|
+
_HASH_MEMO_MAX = 512
|
|
23
|
+
_HASH_MEMO: "OrderedDict[tuple, str]" = OrderedDict()
|
|
24
|
+
_HASH_MEMO_LOCK = threading.Lock()
|
|
25
|
+
|
|
19
26
|
|
|
20
27
|
class AgentFirewall:
|
|
21
28
|
"""Manages cross-agent shared file cache within and across sessions."""
|
|
@@ -77,18 +84,50 @@ class AgentFirewall:
|
|
|
77
84
|
key = (symbol or "").strip()
|
|
78
85
|
return f"{key}#{AgentFirewall._SLICE_REVISION}" if key else ""
|
|
79
86
|
|
|
87
|
+
@staticmethod
|
|
88
|
+
def _key_path(file_path: str) -> str:
|
|
89
|
+
"""Cache key for a file: its absolute path, never a relative one.
|
|
90
|
+
|
|
91
|
+
Two worktrees hold the same relative path with different bytes, so the
|
|
92
|
+
caller must pass the path of the file it actually read (resolved
|
|
93
|
+
against the call's root). Symlinks are kept as spelled: the read path
|
|
94
|
+
keys on the caller's logical path (see workspace_roots.resolve_input_path).
|
|
95
|
+
"""
|
|
96
|
+
return os.path.abspath(str(file_path or ""))
|
|
97
|
+
|
|
80
98
|
@staticmethod
|
|
81
99
|
def _file_content_hash(file_path: str) -> str:
|
|
82
|
-
"""sha256 of the file's RAW bytes — streamed in 64KB chunks.
|
|
100
|
+
"""sha256 of the file's RAW bytes — streamed in 64KB chunks.
|
|
101
|
+
|
|
102
|
+
One smart_read_file call asks for this hash several times (delivered
|
|
103
|
+
check, firewall cache, post-read bookkeeping). The digest is memoized
|
|
104
|
+
per file version: (inode, size, mtime_ns, ctime_ns). Any write moves
|
|
105
|
+
ctime, which utime() cannot set back, so a changed file is re-hashed.
|
|
106
|
+
"""
|
|
83
107
|
try:
|
|
84
|
-
h = hashlib.sha256()
|
|
85
108
|
with open(file_path, "rb") as f:
|
|
109
|
+
st = os.fstat(f.fileno())
|
|
110
|
+
key = (os.path.abspath(file_path), st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns)
|
|
111
|
+
with _HASH_MEMO_LOCK:
|
|
112
|
+
hit = _HASH_MEMO.get(key)
|
|
113
|
+
if hit is not None:
|
|
114
|
+
_HASH_MEMO.move_to_end(key)
|
|
115
|
+
return hit
|
|
116
|
+
h = hashlib.sha256()
|
|
86
117
|
while True:
|
|
87
118
|
chunk = f.read(65536)
|
|
88
119
|
if not chunk:
|
|
89
120
|
break
|
|
90
121
|
h.update(chunk)
|
|
91
|
-
|
|
122
|
+
digest = h.hexdigest()
|
|
123
|
+
# A write that raced the read leaves a different stat: don't memoize it.
|
|
124
|
+
after = os.fstat(f.fileno())
|
|
125
|
+
if (after.st_size, after.st_mtime_ns, after.st_ctime_ns) == (st.st_size, st.st_mtime_ns, st.st_ctime_ns):
|
|
126
|
+
with _HASH_MEMO_LOCK:
|
|
127
|
+
_HASH_MEMO[key] = digest
|
|
128
|
+
while len(_HASH_MEMO) > _HASH_MEMO_MAX:
|
|
129
|
+
_HASH_MEMO.popitem(last=False)
|
|
130
|
+
return digest
|
|
92
131
|
except OSError:
|
|
93
132
|
return ""
|
|
94
133
|
|
|
@@ -137,11 +176,12 @@ class AgentFirewall:
|
|
|
137
176
|
cls._ensure_table(tracker)
|
|
138
177
|
|
|
139
178
|
try:
|
|
140
|
-
|
|
179
|
+
st = os.stat(file_path)
|
|
141
180
|
except OSError:
|
|
142
181
|
return False, None, 0
|
|
182
|
+
current_mtime = st.st_mtime
|
|
143
183
|
|
|
144
|
-
abs_path =
|
|
184
|
+
abs_path = cls._key_path(file_path)
|
|
145
185
|
symbol_key = cls._cache_symbol(symbol)
|
|
146
186
|
current_hash = ""
|
|
147
187
|
|
|
@@ -206,7 +246,8 @@ class AgentFirewall:
|
|
|
206
246
|
mtime_iso = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(current_mtime))
|
|
207
247
|
payload = (
|
|
208
248
|
f"// [TokenSafe Subagent Firewall: Pointer Hit for '{os.path.basename(abs_path)}{sym_label}' "
|
|
209
|
-
f"(unchanged, sha256:{short_hash}, mtime={mtime_iso})
|
|
249
|
+
f"(unchanged, sha256:{short_hash}, mtime={mtime_iso}, version={st.st_mtime_ns}:{st.st_size}) "
|
|
250
|
+
f"— reuse the content returned earlier in this session; "
|
|
210
251
|
f"if you are a fresh subagent or your context was compacted, re-call smart_read_file with force_full=true]\n"
|
|
211
252
|
)
|
|
212
253
|
opt_tokens = count_tokens(payload)
|
|
@@ -251,6 +292,24 @@ class AgentFirewall:
|
|
|
251
292
|
|
|
252
293
|
return False, None, 0
|
|
253
294
|
|
|
295
|
+
@classmethod
|
|
296
|
+
def was_delivered(cls, session_id: str, file_path: str, tracker: MetricsTracker = None) -> bool:
|
|
297
|
+
"""Cheap read-history probe (no metrics, no hit increments)."""
|
|
298
|
+
if not session_id or not file_path or not os.path.exists(file_path):
|
|
299
|
+
return False
|
|
300
|
+
try:
|
|
301
|
+
tracker = tracker or MetricsTracker()
|
|
302
|
+
cls._ensure_table(tracker)
|
|
303
|
+
with tracker._get_connection() as conn:
|
|
304
|
+
row = conn.execute(
|
|
305
|
+
"SELECT 1 FROM subagent_file_cache "
|
|
306
|
+
"WHERE session_id = ? AND file_path = ? LIMIT 1",
|
|
307
|
+
(session_id, cls._key_path(file_path)),
|
|
308
|
+
).fetchone()
|
|
309
|
+
return row is not None
|
|
310
|
+
except Exception:
|
|
311
|
+
return False
|
|
312
|
+
|
|
254
313
|
@classmethod
|
|
255
314
|
def record_cache(
|
|
256
315
|
cls,
|
|
@@ -275,7 +334,7 @@ class AgentFirewall:
|
|
|
275
334
|
except OSError:
|
|
276
335
|
mtime = time.time()
|
|
277
336
|
|
|
278
|
-
abs_path =
|
|
337
|
+
abs_path = cls._key_path(file_path)
|
|
279
338
|
symbol_key = cls._cache_symbol(symbol)
|
|
280
339
|
tokens = count_tokens(content)
|
|
281
340
|
now = int(time.time())
|
|
@@ -41,7 +41,7 @@ def _load_state(workspace: str) -> Dict[str, Any]:
|
|
|
41
41
|
|
|
42
42
|
|
|
43
43
|
def _save_state(workspace: str, state: Dict[str, Any]) -> None:
|
|
44
|
-
from
|
|
44
|
+
from tokensafe.atomic_io import write_text_atomic
|
|
45
45
|
|
|
46
46
|
path = _state_path(workspace)
|
|
47
47
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
@@ -59,7 +59,7 @@ def _read_angular_json(app_root: str) -> Optional[Dict[str, Any]]:
|
|
|
59
59
|
|
|
60
60
|
def _ensure_tokensafe_gitignored(app_root: str) -> None:
|
|
61
61
|
try:
|
|
62
|
-
from
|
|
62
|
+
from tokensafe.paths import ensure_tokensafe_gitignore
|
|
63
63
|
|
|
64
64
|
ensure_tokensafe_gitignore(app_root)
|
|
65
65
|
except Exception:
|
|
@@ -129,7 +129,7 @@ def apply(workspace: str, app_root: str, dry_run: bool = False) -> Dict[str, Any
|
|
|
129
129
|
serve["builder"] = BUILDER_ID
|
|
130
130
|
|
|
131
131
|
if not dry_run:
|
|
132
|
-
from
|
|
132
|
+
from tokensafe.atomic_io import write_text_atomic
|
|
133
133
|
|
|
134
134
|
write_text_atomic(_angular_json(app_root), json.dumps(data, indent=2, ensure_ascii=False) + "\n")
|
|
135
135
|
recorded = _load_state(workspace)
|
|
@@ -175,7 +175,7 @@ def revert_all(workspace: str) -> Dict[str, Any]:
|
|
|
175
175
|
serve["builder"] = builder
|
|
176
176
|
changed.append(name)
|
|
177
177
|
if changed:
|
|
178
|
-
from
|
|
178
|
+
from tokensafe.atomic_io import write_text_atomic
|
|
179
179
|
|
|
180
180
|
write_text_atomic(_angular_json(app_root), json.dumps(data, indent=2, ensure_ascii=False) + "\n")
|
|
181
181
|
restored[app_root] = {"status": "reverted", "projects": changed}
|
|
@@ -35,15 +35,15 @@ import hashlib
|
|
|
35
35
|
import json
|
|
36
36
|
import os
|
|
37
37
|
|
|
38
|
-
from
|
|
38
|
+
from tokensafe import angular_cli
|
|
39
39
|
import re
|
|
40
40
|
import shutil
|
|
41
41
|
import subprocess
|
|
42
42
|
from typing import Any, Dict, List, Optional, Tuple
|
|
43
43
|
|
|
44
|
-
from
|
|
45
|
-
from
|
|
46
|
-
from
|
|
44
|
+
from tokensafe import oumv_policy
|
|
45
|
+
from tokensafe.backend_release import BACKEND_DOTNET_VERSION, BACKEND_NPM_VERSION, BACKEND_RELEASE_TAG
|
|
46
|
+
from tokensafe.retrofit import detect_project_stack, generate_config, get_adapters_catalog
|
|
47
47
|
|
|
48
48
|
_PYHOOKS_DIRNAME = "pyhooks"
|
|
49
49
|
_INJECT_DIRNAME = "inject"
|
|
@@ -184,9 +184,41 @@ Inert unless TOKENSAFE_OUMV_AUTOMOUNT=1, which `tokensafe run-backend` sets.
|
|
|
184
184
|
TOKENSAFE_OUMV_READ_ONLY=1 mounts the spec §8.5 read-only deployment: the writing
|
|
185
185
|
methods are not registered at all, so applyEdit/previewEdit/verify/build answer
|
|
186
186
|
-32601 instead of being refused by a handler.
|
|
187
|
+
|
|
188
|
+
Python imports only the first `sitecustomize` on sys.path, and this directory is
|
|
189
|
+
prepended to PYTHONPATH, so the one it shadows (a venv's, a distro's, the
|
|
190
|
+
project's own) is located and run below.
|
|
187
191
|
"""
|
|
188
192
|
import os
|
|
189
193
|
|
|
194
|
+
|
|
195
|
+
def _tokensafe_chain_sitecustomize():
|
|
196
|
+
import sys
|
|
197
|
+
import importlib.machinery
|
|
198
|
+
import importlib.util
|
|
199
|
+
|
|
200
|
+
try:
|
|
201
|
+
here = os.path.dirname(os.path.realpath(__file__))
|
|
202
|
+
except NameError:
|
|
203
|
+
return
|
|
204
|
+
rest = [p for p in sys.path if os.path.realpath(p or os.curdir) != here]
|
|
205
|
+
try:
|
|
206
|
+
spec = importlib.machinery.PathFinder.find_spec("sitecustomize", rest)
|
|
207
|
+
except Exception:
|
|
208
|
+
return
|
|
209
|
+
if spec is None or spec.loader is None or not spec.origin:
|
|
210
|
+
return
|
|
211
|
+
if os.path.realpath(spec.origin) == os.path.realpath(__file__):
|
|
212
|
+
return
|
|
213
|
+
try:
|
|
214
|
+
module = importlib.util.module_from_spec(spec)
|
|
215
|
+
spec.loader.exec_module(module)
|
|
216
|
+
except Exception as exc: # the shadowed hook's own failure stays visible
|
|
217
|
+
print(f"[tokensafe] chained sitecustomize {spec.origin} failed: {exc}", file=sys.stderr)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
_tokensafe_chain_sitecustomize()
|
|
221
|
+
|
|
190
222
|
if os.environ.get("TOKENSAFE_OUMV_AUTOMOUNT") == "1":
|
|
191
223
|
_READ_ONLY = os.environ.get("TOKENSAFE_OUMV_READ_ONLY") in ("1", "true", "yes", "on")
|
|
192
224
|
|
|
@@ -901,7 +933,7 @@ def _node_package_dir(workspace: str, entrypoint: str) -> str:
|
|
|
901
933
|
|
|
902
934
|
def _node_install_command(package_dir: str) -> Tuple[List[str], str]:
|
|
903
935
|
"""(argv, manager) for an exact install of the Node adapter package."""
|
|
904
|
-
from
|
|
936
|
+
from tokensafe.win_paths import resolve_executable
|
|
905
937
|
|
|
906
938
|
package = f"{_NODE_PACKAGE}@{BACKEND_NPM_VERSION}"
|
|
907
939
|
markers = (
|