tokensafe 4.4.3 → 4.4.5

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.
@@ -0,0 +1,280 @@
1
+ """
2
+ Universal OUMV (Observe, Understand, Mutate, Verify) Runtime Gateway for TokenSafe.
3
+ Connects AI coding agents to live Frontend (tokensafe-ui, Vite, React) and Backend
4
+ (FastAPI, Go, Node.js) DevServers via UARP JSON-RPC 2.0.
5
+ """
6
+
7
+ import os
8
+ import json
9
+ import time
10
+ import urllib.request
11
+ import urllib.error
12
+ from concurrent.futures import ThreadPoolExecutor, as_completed
13
+ from typing import Dict, Any, Optional, Tuple, List
14
+ from src.paths import get_active_workspace
15
+
16
+
17
+ class OUMVGateway:
18
+ """Dispatches OUMV protocol calls to live DevServers with zero-config discovery."""
19
+
20
+ _cached_fe: Optional[Dict[str, Any]] = None
21
+ _cached_be: Optional[Dict[str, Any]] = None
22
+ _last_scan_time: float = 0.0
23
+ _SCAN_INTERVAL_SEC: float = 5.0
24
+
25
+ @classmethod
26
+ def get_endpoints(cls, workspace_dir: Optional[str] = None) -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
27
+ """Returns (frontend_endpoint, backend_endpoint) with periodic cache invalidation."""
28
+ now = time.time()
29
+ if (now - cls._last_scan_time > cls._SCAN_INTERVAL_SEC) or (not cls._cached_fe and not cls._cached_be):
30
+ cls.scan(workspace_dir=workspace_dir)
31
+ return cls._cached_fe, cls._cached_be
32
+
33
+ @classmethod
34
+ def scan(cls, workspace_dir: Optional[str] = None):
35
+ """Scans workspace runtime lockfiles and local ports in parallel."""
36
+ cls._last_scan_time = time.time()
37
+ ws = workspace_dir or get_active_workspace()
38
+
39
+ # 1. Check workspace runtime files (.tokensafe/runtime.json or .oumv/runtime.json)
40
+ cls._check_workspace_runtime_files(ws)
41
+
42
+ # 2. Parallel candidate probe for remaining missing endpoints
43
+ env_fe = os.environ.get("TOKENSAFE_FRONTEND_URL")
44
+ fe_candidates = [
45
+ *( [env_fe] if env_fe else [] ),
46
+ "http://localhost:5173/__oumv/rpc",
47
+ "http://localhost:5173/__tokensafe_ui/rpc",
48
+ "http://localhost:5173/__agent_dom/rpc",
49
+ "http://localhost:3000/__oumv/rpc",
50
+ "http://localhost:3000/__tokensafe_ui/rpc",
51
+ "http://localhost:4173/__oumv/rpc",
52
+ "http://localhost:5174/__oumv/rpc",
53
+ "http://localhost:8081/__oumv/rpc",
54
+ ]
55
+
56
+ env_be = os.environ.get("TOKENSAFE_BACKEND_URL")
57
+ be_candidates = [
58
+ *( [env_be] if env_be else [] ),
59
+ "http://localhost:8080/__oumv/rpc",
60
+ "http://localhost:8000/__oumv/rpc",
61
+ "http://localhost:3001/__oumv/rpc",
62
+ "http://localhost:5000/__oumv/rpc",
63
+ "http://localhost:9000/__oumv/rpc",
64
+ "http://localhost:4000/__oumv/rpc",
65
+ ]
66
+
67
+ with ThreadPoolExecutor(max_workers=6) as executor:
68
+ future_fe = executor.submit(cls._probe_candidates, fe_candidates, "frontend") if not cls._cached_fe else None
69
+ future_be = executor.submit(cls._probe_candidates, be_candidates, "backend") if not cls._cached_be else None
70
+
71
+ if future_fe:
72
+ found_fe = future_fe.result()
73
+ if found_fe:
74
+ cls._cached_fe = found_fe
75
+ if future_be:
76
+ found_be = future_be.result()
77
+ if found_be:
78
+ cls._cached_be = found_be
79
+
80
+ @classmethod
81
+ def _check_workspace_runtime_files(cls, workspace_dir: str):
82
+ lock_paths = [
83
+ os.path.join(workspace_dir, ".tokensafe", "runtime.json"),
84
+ os.path.join(workspace_dir, ".oumv", "runtime.json"),
85
+ ]
86
+ for lp in lock_paths:
87
+ if os.path.isfile(lp):
88
+ try:
89
+ with open(lp, "r", encoding="utf-8") as f:
90
+ data = json.load(f)
91
+ fe_info = data.get("frontend")
92
+ if fe_info and fe_info.get("url"):
93
+ cls._cached_fe = {
94
+ "kind": "frontend",
95
+ "name": fe_info.get("name", "tokensafe-ui"),
96
+ "version": fe_info.get("version", "1.0.0"),
97
+ "url": fe_info["url"],
98
+ "healthy": True,
99
+ "capabilities": fe_info.get("capabilities", {}),
100
+ }
101
+ be_info = data.get("backend")
102
+ if be_info and be_info.get("url"):
103
+ cls._cached_be = {
104
+ "kind": "backend",
105
+ "name": be_info.get("name", "tokensafe-backend"),
106
+ "version": be_info.get("version", "1.0.0"),
107
+ "url": be_info["url"],
108
+ "healthy": True,
109
+ "capabilities": be_info.get("capabilities", {}),
110
+ }
111
+ except Exception:
112
+ pass
113
+
114
+ @classmethod
115
+ def _probe_candidates(cls, urls: List[str], kind: str) -> Optional[Dict[str, Any]]:
116
+ for url in urls:
117
+ try:
118
+ res = cls._rpc_call(url, "oumv/handshake", {"protocolVersion": "1.0.0"}, timeout=0.35)
119
+ if res and isinstance(res, dict) and "runtimeInfo" in res:
120
+ return {
121
+ "kind": kind,
122
+ "name": res.get("runtimeInfo", {}).get("name", f"{kind}-runtime"),
123
+ "version": res.get("runtimeInfo", {}).get("version", "1.0.0"),
124
+ "url": url,
125
+ "healthy": True,
126
+ "capabilities": {
127
+ "observeLevels": res.get("capabilities", {}).get("observe", {}).get("levels"),
128
+ "causality": res.get("capabilities", {}).get("understand", {}).get("causality"),
129
+ "occ": res.get("capabilities", {}).get("mutate", {}).get("occ"),
130
+ },
131
+ }
132
+ except Exception:
133
+ continue
134
+ return None
135
+
136
+ @classmethod
137
+ def _rpc_call(cls, endpoint_url: str, method: str, params: Optional[dict] = None, timeout: float = 3.0) -> Any:
138
+ payload = json.dumps({
139
+ "jsonrpc": "2.0",
140
+ "id": 1,
141
+ "method": method,
142
+ "params": params or {},
143
+ }).encode("utf-8")
144
+
145
+ req = urllib.request.Request(
146
+ endpoint_url,
147
+ data=payload,
148
+ headers={"Content-Type": "application/json", "User-Agent": "TokenSafe-Gateway/1.0"},
149
+ method="POST",
150
+ )
151
+
152
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
153
+ data = json.loads(resp.read().decode("utf-8"))
154
+ if "error" in data and data["error"]:
155
+ err = data["error"]
156
+ msg = err.get("message") if isinstance(err, dict) else str(err)
157
+ raise RuntimeError(f"JSON-RPC error from {endpoint_url}: {msg}")
158
+ return data.get("result")
159
+
160
+ @classmethod
161
+ def _resolve_client_url(cls, runtime: str = "auto", target: Optional[str] = None) -> str:
162
+ fe, be = cls.get_endpoints()
163
+
164
+ if runtime == "frontend":
165
+ if not fe:
166
+ raise RuntimeError("No active frontend runtime detected on ports 5173/3000")
167
+ return fe["url"]
168
+ elif runtime == "backend":
169
+ if not be:
170
+ raise RuntimeError("No active backend runtime detected on ports 8080/8000")
171
+ return be["url"]
172
+
173
+ # Auto detection based on target
174
+ if target:
175
+ # Backend hints: HTTP method prefixes, API paths, SQL, handlers
176
+ if any(target.startswith(m) for m in ["GET ", "POST ", "PUT ", "DELETE ", "PATCH "]) or "/api/" in target or target.startswith("/"):
177
+ if be:
178
+ return be["url"]
179
+ # Frontend hints: DOM selectors (#, .), components (<, JSX, Tab)
180
+ if any(target.startswith(c) for c in ["#", ".", "[", "button", "input"]) or target.startswith("<"):
181
+ if fe:
182
+ return fe["url"]
183
+
184
+ # Default fallback: backend if exists else frontend
185
+ if be:
186
+ return be["url"]
187
+ if fe:
188
+ return fe["url"]
189
+ raise RuntimeError("No live OUMV runtime (Frontend or Backend) detected in workspace.")
190
+
191
+ # 1. Tool: oumv_status
192
+ @classmethod
193
+ def status(cls, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
194
+ cls.scan(workspace_dir=workspace_dir)
195
+ fe, be = cls._cached_fe, cls._cached_be
196
+ return {
197
+ "frontend": fe or {"status": "DISCONNECTED", "tip": "Start frontend dev-server (port 5173/3000)"},
198
+ "backend": be or {"status": "DISCONNECTED", "tip": "Start backend dev-server (port 8080/8000)"},
199
+ "workspace": workspace_dir or get_active_workspace(),
200
+ }
201
+
202
+ # 2. Tool: oumv_observe
203
+ @classmethod
204
+ def observe(cls, level: str = "L0", target: Optional[str] = None, runtime: str = "auto") -> Any:
205
+ fe, be = cls.get_endpoints()
206
+
207
+ # Consolidated fullstack L0 pulse (~30 tokens)
208
+ if level.upper() == "L0" and (not target or target == "fullstack") and (runtime in ("auto", "")):
209
+ results = {"mode": "FULLSTACK_PULSE"}
210
+ if fe:
211
+ try:
212
+ results["frontend"] = cls._rpc_call(fe["url"], "oumv/observe", {"level": "L0"})
213
+ except Exception as e:
214
+ results["frontend"] = {"error": str(e)}
215
+ else:
216
+ results["frontend"] = {"status": "DISCONNECTED", "tip": "No active frontend dev-server (port 5173/3000)"}
217
+
218
+ if be:
219
+ try:
220
+ results["backend"] = cls._rpc_call(be["url"], "oumv/observe", {"level": "L0"})
221
+ except Exception as e:
222
+ results["backend"] = {"error": str(e)}
223
+ else:
224
+ results["backend"] = {"status": "DISCONNECTED", "tip": "No active backend dev-server (port 8080/8000)"}
225
+
226
+ return results
227
+
228
+ url = cls._resolve_client_url(runtime=runtime, target=target)
229
+ return cls._rpc_call(url, "oumv/observe", {"level": level, "target": target, "componentId": target})
230
+
231
+ # 3. Tool: oumv_understand
232
+ @classmethod
233
+ def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto") -> Any:
234
+ fe, be = cls.get_endpoints()
235
+
236
+ # Cross-layer causality query
237
+ if query == "causality" and runtime in ("auto", ""):
238
+ report = {
239
+ "query": "causality",
240
+ "target": target,
241
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
242
+ }
243
+ if be:
244
+ try:
245
+ report["backendCausality"] = cls._rpc_call(be["url"], "oumv/understand", {"query": query, "target": target})
246
+ except Exception as e:
247
+ report["backendError"] = str(e)
248
+ if fe:
249
+ try:
250
+ report["frontendCausality"] = cls._rpc_call(fe["url"], "oumv/understand", {"query": query, "target": target, "componentId": target})
251
+ except Exception as e:
252
+ report["frontendError"] = str(e)
253
+ return report
254
+
255
+ url = cls._resolve_client_url(runtime=runtime, target=target)
256
+ return cls._rpc_call(url, "oumv/understand", {"query": query, "target": target, "componentId": target})
257
+
258
+ # 4. Tool: oumv_mutate
259
+ @classmethod
260
+ def mutate(cls, path: str, symbol: Optional[str] = None, replacement: Optional[str] = None, expected_version: Optional[str] = None, runtime: str = "auto") -> Any:
261
+ url = cls._resolve_client_url(runtime=runtime, target=path)
262
+ return cls._rpc_call(url, "oumv/applyEdit", {
263
+ "path": path,
264
+ "filePath": path,
265
+ "symbol": symbol,
266
+ "replacement": replacement,
267
+ "source": replacement,
268
+ "expectedVersion": expected_version,
269
+ })
270
+
271
+ # 5. Tool: oumv_verify
272
+ @classmethod
273
+ def verify(cls, target: str, action: str = "invoke", payload: Optional[dict] = None, runtime: str = "auto") -> Any:
274
+ url = cls._resolve_client_url(runtime=runtime, target=target)
275
+ return cls._rpc_call(url, "oumv/verify", {
276
+ "target": target,
277
+ "componentId": target,
278
+ "action": action,
279
+ "payload": payload or {},
280
+ })