tokensafe 4.4.3 → 4.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/kimi.plugin.json +1 -1
- package/mcp_config.json +0 -7
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +1 -0
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +38 -7
- package/src/installer.py +10 -31
- package/src/mcp_server.py +120 -1
- package/src/oumv_gateway.py +274 -0
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.4.
|
|
3
|
+
"version": "4.4.4",
|
|
4
4
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
5
5
|
"homepage": "https://tokensafe.dev",
|
|
6
6
|
"license": "MIT",
|
package/mcp_config.json
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.4.
|
|
4
|
+
"version": "4.4.4",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.4.
|
|
4
|
+
"version": "4.4.4",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"logo": "assets/logo.png",
|
|
7
7
|
"developerName": "TokenSafe",
|
package/rules/AGENTS.md
CHANGED
|
@@ -43,6 +43,7 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
43
43
|
13. **Superseded Output Pruning (`prune_superseded`)**: In long multi-turn sessions, prune obsolete intermediate file reads via `tokensafe:prune_superseded(transcript_path)` to free up context without losing history.
|
|
44
44
|
14. **Anti-Stuck Revert Memory (`get_mistakes`) & Hybrid Escalation**: Consult `tokensafe:get_mistakes` to retrieve persistent records of prior dead-ends, loop guard trips, and git reverts to avoid attempting previously failed solutions. The 2-tier hybrid escalation policy issues a soft advisory warning for 1-2 failures and triggers `force_ask` if an identical action or command fails >2 times within 30 minutes, automatically broadcasting scrubbed failure summaries to the team.
|
|
45
45
|
15. **External Types & Lockfile Point Queries**: Use `tokensafe:slice_external_type(package_name, type_name)` to extract 3rd-party TypeScript interfaces from `node_modules` without crawling directories (-95% tokens, L1/L2/L3 cached). Use `tokensafe:query_dependency(lockfile_path, package_name)` for instant lockfile point lookups in <50 tokens; raw `read_file` on lockfiles without bounds is redirected to an index summary.
|
|
46
|
+
16. **Universal OUMV Protocol (Runtime Introspection & Verification Directives)**: For live Frontend (ports 5173/3000) and Backend (ports 8080/8000) services, inspect connectivity via `tokensafe:oumv_status()`. Observe state progressively: `tokensafe:oumv_observe(level="L0")` for pulse (~20 tokens), `L1` for endpoints/models surface (~150 tokens), `L2` for target contracts or DTO schemas. Never guess state flows or bugs — query runtime causality via `tokensafe:oumv_understand(query="causality")` or `why_state`. Verify actions in-memory inside transactional sandboxes with automatic DB rollback via `tokensafe:oumv_verify(target="POST /api/...", payload={...})` instead of heavy browser runs or blind shell curls. Apply OCC edits with `tokensafe:oumv_mutate(path=..., expectedVersion=...)`.
|
|
46
47
|
|
|
47
48
|
### 4. Turn Token Savings Footer (Proof-of-Savings — always in English)
|
|
48
49
|
At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer:
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
|
|
6
|
-
"version": "4.4.
|
|
6
|
+
"version": "4.4.4",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"registryType": "npm",
|
|
24
24
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
25
25
|
"identifier": "tokensafe",
|
|
26
|
-
"version": "4.4.
|
|
26
|
+
"version": "4.4.4",
|
|
27
27
|
"runtimeHint": "npx",
|
|
28
28
|
"transport": {
|
|
29
29
|
"type": "stdio"
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"registryType": "pypi",
|
|
40
40
|
"registryBaseUrl": "https://pypi.org",
|
|
41
41
|
"identifier": "tokensafe",
|
|
42
|
-
"version": "4.4.
|
|
42
|
+
"version": "4.4.4",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: token-optimizer
|
|
3
3
|
description: >-
|
|
4
|
-
MANDATORY code inspection
|
|
4
|
+
MANDATORY code inspection, architecture navigation, and live runtime verification skill.
|
|
5
5
|
Activate whenever inspecting files, searching code, locating components/functions/classes,
|
|
6
|
-
reading implementations, analyzing dependencies, or
|
|
7
|
-
Replaces wasteful terminal grep/find with zero-loss AST smart slicing (-90% tokens)
|
|
8
|
-
|
|
6
|
+
reading implementations, analyzing dependencies, navigating architecture, or interacting with live systems.
|
|
7
|
+
Replaces wasteful terminal grep/find with zero-loss AST smart slicing (-90% tokens) and enables
|
|
8
|
+
OUMV (Observe, Understand, Mutate, Verify) runtime verification across frontend and backend dev-servers.
|
|
9
9
|
---
|
|
10
10
|
|
|
11
|
-
# TokenSafe Optimization &
|
|
11
|
+
# TokenSafe Optimization, Architecture & OUMV Runtime Skill
|
|
12
12
|
|
|
13
|
-
TokenSafe is the zero-loss token economy, context governor,
|
|
13
|
+
TokenSafe is the zero-loss token economy, context governor, security engine, and runtime verification layer for autonomous AI coding agents.
|
|
14
14
|
It replaces brute-force terminal crawls (`grep`, `find`, `cat`) with deterministic AST symbol extraction,
|
|
15
|
-
folds multi-turn conversation history,
|
|
15
|
+
folds multi-turn conversation history, guards against secret leaks, and standardizes live runtime interaction via the **Universal OUMV Protocol (UARP)**.
|
|
16
16
|
|
|
17
17
|
---
|
|
18
18
|
|
|
@@ -123,6 +123,37 @@ TokenSafe actively maximizes provider KV-cache hit rates alongside token compres
|
|
|
123
123
|
|
|
124
124
|
---
|
|
125
125
|
|
|
126
|
+
## Universal OUMV Protocol (Runtime Introspection & Verification)
|
|
127
|
+
|
|
128
|
+
TokenSafe integrates the **Universal Agent-Runtime Protocol (UARP / OUMV)** to inspect, reason about, edit, and verify running Frontend and Backend services in real time without heavy headless browsers or unconstrained shell curls:
|
|
129
|
+
|
|
130
|
+
1. **LIVE RUNTIME HEALTH (`oumv_status`)**:
|
|
131
|
+
- Call `tokensafe:oumv_status()` to inspect connection status and capabilities of running DevServers (Frontend ports 5173/3000, Backend ports 8080/8000).
|
|
132
|
+
|
|
133
|
+
2. **PROGRESSIVE CONTEXT OBSERVATION (`oumv_observe`)**:
|
|
134
|
+
- Never dump raw HTML or giant JSON payloads. Observe progressively:
|
|
135
|
+
- **L0 (Page Pulse ~20 tokens)**: Status, active route, error counts (`level="L0"`).
|
|
136
|
+
- **L1 (Surface ~150 tokens)**: Interactive map of endpoints, models, buttons, and ARIA roles (`level="L1"`).
|
|
137
|
+
- **L2 (Contract ~80 tokens)**: Targeted component props or API DTO schemas (`level="L2", target="ModelName"`).
|
|
138
|
+
- **L3 (Source)**: Targeted symbol source with line mapping.
|
|
139
|
+
- **L4 (Traces)**: Event stream, signal mutations, and state snapshot.
|
|
140
|
+
|
|
141
|
+
3. **RUNTIME CAUSALITY & WHY-STATE (`oumv_understand`)**:
|
|
142
|
+
- Never guess state flows or assume dependencies.
|
|
143
|
+
- Call `tokensafe:oumv_understand(query="causality", target="POST /api/orders")` to query live dependencies:
|
|
144
|
+
`Route ➔ Handler ➔ ValidatesWith ➔ Model ➔ DB Table` or `Signal ➔ Computed ➔ Effect ➔ DOM Binding`.
|
|
145
|
+
- Call `tokensafe:oumv_understand(query="impact", target="model:User")` before refactoring to know exactly what breaks.
|
|
146
|
+
|
|
147
|
+
4. **SANDBOXED ACTION VERIFICATION (`oumv_verify`)**:
|
|
148
|
+
- Sub-millisecond to low-millisecond local action verification inside transactional sandbox.
|
|
149
|
+
- For backend endpoints: call `tokensafe:oumv_verify(target="POST /api/products", payload={...})` — executes the request in-memory with automatic database rollback (`rolledBack: true`) and returns structured state diffs (`diff`) and HTTP status code.
|
|
150
|
+
- For frontend UI: verifies synthetic events and accessibility surface diffs without spawning browser automation.
|
|
151
|
+
|
|
152
|
+
5. **OPTIMISTIC CONCURRENCY MUTATIONS (`oumv_mutate`)**:
|
|
153
|
+
- Submits surgical edits verified against `expectedVersion` with built-in syntax and security leak guards.
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
126
157
|
## Proof-of-Savings Turn Footer (always in English)
|
|
127
158
|
|
|
128
159
|
At the end of any response where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:
|
package/src/installer.py
CHANGED
|
@@ -64,6 +64,7 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
64
64
|
"At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer. The ENTIRE footer is product-facing copy — 100% English, including the savings breakdown in parentheses, regardless of the chat language:\n"
|
|
65
65
|
"`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown in English>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
|
|
66
66
|
"13. **External Types & Lockfile Point Queries**: Use `tokensafe:slice_external_type(package_name, type_name)` to extract 3rd-party TypeScript interfaces from `node_modules` without crawling directories (-95% tokens, L1/L2/L3 cached). Use `tokensafe:query_dependency(lockfile_path, package_name)` for instant lockfile point lookups in <50 tokens; raw `read_file` on lockfiles without bounds is redirected to an index summary.\n"
|
|
67
|
+
"14. **Universal OUMV Protocol (Runtime Introspection & Verification)**: For live Frontend (ports 5173/3000) and Backend (ports 8080/8000) services, inspect connectivity via `tokensafe:oumv_status()`. Observe state progressively: `tokensafe:oumv_observe(level='L0')` for pulse (~20 tokens), `L1` for endpoints/models surface (~150 tokens), `L2` for target contracts or DTO schemas. Never guess state flows — query runtime causality via `tokensafe:oumv_understand(query='causality')` or `why_state`. Verify actions in-memory inside transactional sandboxes with automatic DB rollback via `tokensafe:oumv_verify(target='POST /api/...', payload={...})` instead of heavy browser runs or blind shell curls.\n"
|
|
67
68
|
)
|
|
68
69
|
|
|
69
70
|
# Short pointer written into PROJECT-level rule files when the full protocol is
|
|
@@ -71,11 +72,12 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
71
72
|
# Keeps every session's meta-context lean: ~110 tokens instead of ~850.
|
|
72
73
|
POINTER_RULE = (
|
|
73
74
|
"## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
|
|
74
|
-
"The full
|
|
75
|
+
"The full 14-point protocol is installed globally in the agent-level instructions "
|
|
75
76
|
"(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, ~/.kimi-code/AGENTS.md) and applies to this project. "
|
|
76
77
|
"Core rules: never raw grep/find or `ls -la` — use `tokensafe:get_architecture_graph(project_path)` first for God Nodes, "
|
|
77
78
|
"`tokensafe:scoped_search`, `tokensafe:smart_read_file(path, symbol)`, `tokensafe:slice_external_type`, `tokensafe:query_dependency`, "
|
|
78
79
|
"`tokensafe:smart_bundle` and `tokensafe:list_dir`; "
|
|
80
|
+
"use `tokensafe:oumv_status`, `tokensafe:oumv_observe(L0/L1/L2)`, `tokensafe:oumv_understand` and `tokensafe:oumv_verify` for live runtime introspection; "
|
|
79
81
|
"sanitize high-output commands via `tokensafe:sanitize_command`; check `tokensafe:context_budget` (Grade S-F) "
|
|
80
82
|
"before large tasks and compact via `tokensafe:compact_conversation` (orientation digest active); never hardcode secret "
|
|
81
83
|
"fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
|
|
@@ -1241,10 +1243,7 @@ WantedBy=default.target
|
|
|
1241
1243
|
"command": PYTHON_BIN,
|
|
1242
1244
|
"args": [MCP_SERVER_PATH]
|
|
1243
1245
|
}
|
|
1244
|
-
data["mcpServers"]
|
|
1245
|
-
"command": "npx",
|
|
1246
|
-
"args": ["-y", "tokensafe-mcp"]
|
|
1247
|
-
}
|
|
1246
|
+
data["mcpServers"].pop("tokensafe-mcp", None)
|
|
1248
1247
|
|
|
1249
1248
|
cls._atomic_write_json(config_file, data)
|
|
1250
1249
|
|
|
@@ -1286,10 +1285,7 @@ WantedBy=default.target
|
|
|
1286
1285
|
"command": PYTHON_BIN,
|
|
1287
1286
|
"args": [MCP_SERVER_PATH]
|
|
1288
1287
|
}
|
|
1289
|
-
data["mcpServers"]
|
|
1290
|
-
"command": "npx",
|
|
1291
|
-
"args": ["-y", "tokensafe-mcp"]
|
|
1292
|
-
}
|
|
1288
|
+
data["mcpServers"].pop("tokensafe-mcp", None)
|
|
1293
1289
|
|
|
1294
1290
|
cls._atomic_write_json(config_file, data)
|
|
1295
1291
|
|
|
@@ -1358,10 +1354,7 @@ WantedBy=default.target
|
|
|
1358
1354
|
"command": PYTHON_BIN,
|
|
1359
1355
|
"args": [MCP_SERVER_PATH]
|
|
1360
1356
|
}
|
|
1361
|
-
data["mcpServers"]
|
|
1362
|
-
"command": "npx",
|
|
1363
|
-
"args": ["-y", "tokensafe-mcp"]
|
|
1364
|
-
}
|
|
1357
|
+
data["mcpServers"].pop("tokensafe-mcp", None)
|
|
1365
1358
|
cls._atomic_write_json(config_file, data)
|
|
1366
1359
|
|
|
1367
1360
|
if "agents_md_path" in info:
|
|
@@ -1386,12 +1379,7 @@ WantedBy=default.target
|
|
|
1386
1379
|
"args": [MCP_SERVER_PATH],
|
|
1387
1380
|
"tools": ["*"]
|
|
1388
1381
|
}
|
|
1389
|
-
data["mcpServers"]
|
|
1390
|
-
"type": "stdio",
|
|
1391
|
-
"command": "npx",
|
|
1392
|
-
"args": ["-y", "tokensafe-mcp"],
|
|
1393
|
-
"tools": ["*"]
|
|
1394
|
-
}
|
|
1382
|
+
data["mcpServers"].pop("tokensafe-mcp", None)
|
|
1395
1383
|
cls._atomic_write_json(config_file, data)
|
|
1396
1384
|
return True, f"Configured MCP for GitHub Copilot in {config_file}"
|
|
1397
1385
|
|
|
@@ -1412,10 +1400,7 @@ WantedBy=default.target
|
|
|
1412
1400
|
"command": PYTHON_BIN,
|
|
1413
1401
|
"args": [MCP_SERVER_PATH]
|
|
1414
1402
|
}
|
|
1415
|
-
data["mcp"]["servers"]
|
|
1416
|
-
"command": "npx",
|
|
1417
|
-
"args": ["-y", "tokensafe-mcp"]
|
|
1418
|
-
}
|
|
1403
|
+
data["mcp"]["servers"].pop("tokensafe-mcp", None)
|
|
1419
1404
|
|
|
1420
1405
|
cls._atomic_write_json(config_file, data)
|
|
1421
1406
|
|
|
@@ -1443,10 +1428,7 @@ WantedBy=default.target
|
|
|
1443
1428
|
"command": PYTHON_BIN,
|
|
1444
1429
|
"args": [MCP_SERVER_PATH]
|
|
1445
1430
|
}
|
|
1446
|
-
data["mcpServers"]
|
|
1447
|
-
"command": "npx",
|
|
1448
|
-
"args": ["-y", "tokensafe-mcp"]
|
|
1449
|
-
}
|
|
1431
|
+
data["mcpServers"].pop("tokensafe-mcp", None)
|
|
1450
1432
|
cls._atomic_write_json(mcp_file, data)
|
|
1451
1433
|
|
|
1452
1434
|
managed_plugin_path = info.get("managed_plugin_path")
|
|
@@ -1940,10 +1922,7 @@ WantedBy=default.target
|
|
|
1940
1922
|
"command": PYTHON_BIN,
|
|
1941
1923
|
"args": [MCP_SERVER_PATH]
|
|
1942
1924
|
}
|
|
1943
|
-
data["mcpServers"]
|
|
1944
|
-
"command": "npx",
|
|
1945
|
-
"args": ["-y", "tokensafe-mcp"]
|
|
1946
|
-
}
|
|
1925
|
+
data["mcpServers"].pop("tokensafe-mcp", None)
|
|
1947
1926
|
cls._atomic_write_json(cursor_mcp, data)
|
|
1948
1927
|
created.append(".cursor/mcp.json")
|
|
1949
1928
|
except Exception:
|
package/src/mcp_server.py
CHANGED
|
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
|
|
|
42
42
|
|
|
43
43
|
SERVER_INFO = {
|
|
44
44
|
"name": "tokensafe-mcp",
|
|
45
|
-
"version": "4.4.
|
|
45
|
+
"version": "4.4.4"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -384,6 +384,69 @@ TOOLS = [
|
|
|
384
384
|
"clear": {"type": "boolean", "description": "If true, clears the mistakes ledger"}
|
|
385
385
|
}
|
|
386
386
|
}
|
|
387
|
+
},
|
|
388
|
+
{
|
|
389
|
+
"name": "oumv_status",
|
|
390
|
+
"description": "Reports live health and capability status of connected Frontend (tokensafe-ui/React) and Backend (FastAPI/Go/Node) OUMV runtimes.",
|
|
391
|
+
"inputSchema": {
|
|
392
|
+
"type": "object",
|
|
393
|
+
"properties": {
|
|
394
|
+
"workspace_dir": {"type": "string", "description": "Optional workspace root directory"}
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
},
|
|
398
|
+
{
|
|
399
|
+
"name": "oumv_observe",
|
|
400
|
+
"description": "Progressive semantic context observation (L0 Pulse ~30 tokens, L1 Surface ~150 tokens, L2 Contract ~80 tokens, L3 Source, L4 Traces) without wasting tokens on raw dumps.",
|
|
401
|
+
"inputSchema": {
|
|
402
|
+
"type": "object",
|
|
403
|
+
"properties": {
|
|
404
|
+
"level": {"type": "string", "enum": ["L0", "L1", "L2", "L3", "L4"], "default": "L0", "description": "Observation level (L0: Pulse, L1: Surface, L2: Contract, L3: Source, L4: Traces)"},
|
|
405
|
+
"target": {"type": "string", "description": "Target route (e.g. 'POST /api/products'), DOM element ('#submit-btn'), or symbol"},
|
|
406
|
+
"runtime": {"type": "string", "enum": ["frontend", "backend", "auto"], "default": "auto", "description": "Target runtime (frontend, backend, or auto-detect)"}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
},
|
|
410
|
+
{
|
|
411
|
+
"name": "oumv_understand",
|
|
412
|
+
"description": "Answers 'Why is state X / why is button disabled?' or performs impact analysis by querying runtime signal & causality graph.",
|
|
413
|
+
"inputSchema": {
|
|
414
|
+
"type": "object",
|
|
415
|
+
"properties": {
|
|
416
|
+
"query": {"type": "string", "enum": ["causality", "impact", "why_state"], "default": "causality", "description": "Query type (causality, impact, why_state)"},
|
|
417
|
+
"target": {"type": "string", "description": "Target endpoint (e.g. 'POST /api/products') or UI element ('#submit-btn')"},
|
|
418
|
+
"runtime": {"type": "string", "enum": ["frontend", "backend", "auto"], "default": "auto", "description": "Target runtime"}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
},
|
|
422
|
+
{
|
|
423
|
+
"name": "oumv_mutate",
|
|
424
|
+
"description": "Applies Optimistic Concurrency Control (OCC) source edit or simulates state mutations with syntax & security guards.",
|
|
425
|
+
"inputSchema": {
|
|
426
|
+
"type": "object",
|
|
427
|
+
"properties": {
|
|
428
|
+
"path": {"type": "string", "description": "File path to modify"},
|
|
429
|
+
"symbol": {"type": "string", "description": "Target symbol to edit"},
|
|
430
|
+
"replacement": {"type": "string", "description": "Replacement source code"},
|
|
431
|
+
"expectedVersion": {"type": "string", "description": "Expected version token for optimistic concurrency"},
|
|
432
|
+
"runtime": {"type": "string", "enum": ["frontend", "backend", "auto"], "default": "auto"}
|
|
433
|
+
},
|
|
434
|
+
"required": ["path"]
|
|
435
|
+
}
|
|
436
|
+
},
|
|
437
|
+
{
|
|
438
|
+
"name": "oumv_verify",
|
|
439
|
+
"description": "Instantly verifies actions in memory (UI synthetic actions or Backend HTTP/DB transactional sandbox) with structured state diffs and rollback.",
|
|
440
|
+
"inputSchema": {
|
|
441
|
+
"type": "object",
|
|
442
|
+
"properties": {
|
|
443
|
+
"target": {"type": "string", "description": "Action target (e.g. 'POST /api/v1/orders' or '#submit-btn')"},
|
|
444
|
+
"action": {"type": "string", "default": "invoke", "description": "Action name (invoke, click, submit)"},
|
|
445
|
+
"payload": {"type": "object", "description": "Request body or action payload"},
|
|
446
|
+
"runtime": {"type": "string", "enum": ["frontend", "backend", "auto"], "default": "auto"}
|
|
447
|
+
},
|
|
448
|
+
"required": ["target"]
|
|
449
|
+
}
|
|
387
450
|
}
|
|
388
451
|
]
|
|
389
452
|
|
|
@@ -1977,6 +2040,62 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1977
2040
|
except Exception as e:
|
|
1978
2041
|
return _fallback_error("get_mistakes", f"error reading mistakes ledger: {e}")
|
|
1979
2042
|
|
|
2043
|
+
elif name == "oumv_status":
|
|
2044
|
+
try:
|
|
2045
|
+
from src.oumv_gateway import OUMVGateway
|
|
2046
|
+
ws = str(args.get("workspace_dir") or "").strip() or None
|
|
2047
|
+
res = OUMVGateway.status(workspace_dir=ws)
|
|
2048
|
+
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
2049
|
+
except Exception as e:
|
|
2050
|
+
return _fallback_error("oumv_status", f"failed to check OUMV status: {e}")
|
|
2051
|
+
|
|
2052
|
+
elif name == "oumv_observe":
|
|
2053
|
+
try:
|
|
2054
|
+
from src.oumv_gateway import OUMVGateway
|
|
2055
|
+
lvl = str(args.get("level") or "L0").strip()
|
|
2056
|
+
tgt = str(args.get("target") or "").strip() or None
|
|
2057
|
+
rt = str(args.get("runtime") or "auto").strip()
|
|
2058
|
+
res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt)
|
|
2059
|
+
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
2060
|
+
except Exception as e:
|
|
2061
|
+
return _fallback_error("oumv_observe", f"failed to observe OUMV runtime: {e}")
|
|
2062
|
+
|
|
2063
|
+
elif name == "oumv_understand":
|
|
2064
|
+
try:
|
|
2065
|
+
from src.oumv_gateway import OUMVGateway
|
|
2066
|
+
qry = str(args.get("query") or "causality").strip()
|
|
2067
|
+
tgt = str(args.get("target") or "").strip() or None
|
|
2068
|
+
rt = str(args.get("runtime") or "auto").strip()
|
|
2069
|
+
res = OUMVGateway.understand(query=qry, target=tgt, runtime=rt)
|
|
2070
|
+
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
2071
|
+
except Exception as e:
|
|
2072
|
+
return _fallback_error("oumv_understand", f"failed to query OUMV understanding: {e}")
|
|
2073
|
+
|
|
2074
|
+
elif name == "oumv_mutate":
|
|
2075
|
+
try:
|
|
2076
|
+
from src.oumv_gateway import OUMVGateway
|
|
2077
|
+
p = str(args.get("path") or "").strip()
|
|
2078
|
+
sym = str(args.get("symbol") or "").strip() or None
|
|
2079
|
+
rep = args.get("replacement")
|
|
2080
|
+
ev = str(args.get("expectedVersion") or "").strip() or None
|
|
2081
|
+
rt = str(args.get("runtime") or "auto").strip()
|
|
2082
|
+
res = OUMVGateway.mutate(path=p, symbol=sym, replacement=rep, expected_version=ev, runtime=rt)
|
|
2083
|
+
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
2084
|
+
except Exception as e:
|
|
2085
|
+
return _fallback_error("oumv_mutate", f"failed to apply OUMV mutation: {e}")
|
|
2086
|
+
|
|
2087
|
+
elif name == "oumv_verify":
|
|
2088
|
+
try:
|
|
2089
|
+
from src.oumv_gateway import OUMVGateway
|
|
2090
|
+
tgt = str(args.get("target") or "").strip()
|
|
2091
|
+
act = str(args.get("action") or "invoke").strip()
|
|
2092
|
+
payload = args.get("payload") if isinstance(args.get("payload"), dict) else None
|
|
2093
|
+
rt = str(args.get("runtime") or "auto").strip()
|
|
2094
|
+
res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt)
|
|
2095
|
+
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
2096
|
+
except Exception as e:
|
|
2097
|
+
return _fallback_error("oumv_verify", f"failed to execute OUMV verification: {e}")
|
|
2098
|
+
|
|
1980
2099
|
return _fallback_error(name, f"unknown tool '{name}'")
|
|
1981
2100
|
|
|
1982
2101
|
|
|
@@ -0,0 +1,274 @@
|
|
|
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:3000/__oumv/rpc",
|
|
48
|
+
"http://localhost:4173/__oumv/rpc",
|
|
49
|
+
"http://localhost:5174/__oumv/rpc",
|
|
50
|
+
"http://localhost:8081/__oumv/rpc",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
env_be = os.environ.get("TOKENSAFE_BACKEND_URL")
|
|
54
|
+
be_candidates = [
|
|
55
|
+
*( [env_be] if env_be else [] ),
|
|
56
|
+
"http://localhost:8080/__oumv/rpc",
|
|
57
|
+
"http://localhost:8000/__oumv/rpc",
|
|
58
|
+
"http://localhost:3001/__oumv/rpc",
|
|
59
|
+
"http://localhost:5000/__oumv/rpc",
|
|
60
|
+
"http://localhost:9000/__oumv/rpc",
|
|
61
|
+
"http://localhost:4000/__oumv/rpc",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
with ThreadPoolExecutor(max_workers=6) as executor:
|
|
65
|
+
future_fe = executor.submit(cls._probe_candidates, fe_candidates, "frontend") if not cls._cached_fe else None
|
|
66
|
+
future_be = executor.submit(cls._probe_candidates, be_candidates, "backend") if not cls._cached_be else None
|
|
67
|
+
|
|
68
|
+
if future_fe:
|
|
69
|
+
found_fe = future_fe.result()
|
|
70
|
+
if found_fe:
|
|
71
|
+
cls._cached_fe = found_fe
|
|
72
|
+
if future_be:
|
|
73
|
+
found_be = future_be.result()
|
|
74
|
+
if found_be:
|
|
75
|
+
cls._cached_be = found_be
|
|
76
|
+
|
|
77
|
+
@classmethod
|
|
78
|
+
def _check_workspace_runtime_files(cls, workspace_dir: str):
|
|
79
|
+
lock_paths = [
|
|
80
|
+
os.path.join(workspace_dir, ".tokensafe", "runtime.json"),
|
|
81
|
+
os.path.join(workspace_dir, ".oumv", "runtime.json"),
|
|
82
|
+
]
|
|
83
|
+
for lp in lock_paths:
|
|
84
|
+
if os.path.isfile(lp):
|
|
85
|
+
try:
|
|
86
|
+
with open(lp, "r", encoding="utf-8") as f:
|
|
87
|
+
data = json.load(f)
|
|
88
|
+
fe_info = data.get("frontend")
|
|
89
|
+
if fe_info and fe_info.get("url"):
|
|
90
|
+
cls._cached_fe = {
|
|
91
|
+
"kind": "frontend",
|
|
92
|
+
"name": fe_info.get("name", "tokensafe-ui"),
|
|
93
|
+
"version": fe_info.get("version", "1.0.0"),
|
|
94
|
+
"url": fe_info["url"],
|
|
95
|
+
"healthy": True,
|
|
96
|
+
"capabilities": fe_info.get("capabilities", {}),
|
|
97
|
+
}
|
|
98
|
+
be_info = data.get("backend")
|
|
99
|
+
if be_info and be_info.get("url"):
|
|
100
|
+
cls._cached_be = {
|
|
101
|
+
"kind": "backend",
|
|
102
|
+
"name": be_info.get("name", "tokensafe-backend"),
|
|
103
|
+
"version": be_info.get("version", "1.0.0"),
|
|
104
|
+
"url": be_info["url"],
|
|
105
|
+
"healthy": True,
|
|
106
|
+
"capabilities": be_info.get("capabilities", {}),
|
|
107
|
+
}
|
|
108
|
+
except Exception:
|
|
109
|
+
pass
|
|
110
|
+
|
|
111
|
+
@classmethod
|
|
112
|
+
def _probe_candidates(cls, urls: List[str], kind: str) -> Optional[Dict[str, Any]]:
|
|
113
|
+
for url in urls:
|
|
114
|
+
try:
|
|
115
|
+
res = cls._rpc_call(url, "oumv/handshake", {"protocolVersion": "1.0.0"}, timeout=0.35)
|
|
116
|
+
if res and isinstance(res, dict) and "runtimeInfo" in res:
|
|
117
|
+
return {
|
|
118
|
+
"kind": kind,
|
|
119
|
+
"name": res.get("runtimeInfo", {}).get("name", f"{kind}-runtime"),
|
|
120
|
+
"version": res.get("runtimeInfo", {}).get("version", "1.0.0"),
|
|
121
|
+
"url": url,
|
|
122
|
+
"healthy": True,
|
|
123
|
+
"capabilities": {
|
|
124
|
+
"observeLevels": res.get("capabilities", {}).get("observe", {}).get("levels"),
|
|
125
|
+
"causality": res.get("capabilities", {}).get("understand", {}).get("causality"),
|
|
126
|
+
"occ": res.get("capabilities", {}).get("mutate", {}).get("occ"),
|
|
127
|
+
},
|
|
128
|
+
}
|
|
129
|
+
except Exception:
|
|
130
|
+
continue
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
@classmethod
|
|
134
|
+
def _rpc_call(cls, endpoint_url: str, method: str, params: Optional[dict] = None, timeout: float = 3.0) -> Any:
|
|
135
|
+
payload = json.dumps({
|
|
136
|
+
"jsonrpc": "2.0",
|
|
137
|
+
"id": 1,
|
|
138
|
+
"method": method,
|
|
139
|
+
"params": params or {},
|
|
140
|
+
}).encode("utf-8")
|
|
141
|
+
|
|
142
|
+
req = urllib.request.Request(
|
|
143
|
+
endpoint_url,
|
|
144
|
+
data=payload,
|
|
145
|
+
headers={"Content-Type": "application/json", "User-Agent": "TokenSafe-Gateway/1.0"},
|
|
146
|
+
method="POST",
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
150
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
151
|
+
if "error" in data and data["error"]:
|
|
152
|
+
err = data["error"]
|
|
153
|
+
msg = err.get("message") if isinstance(err, dict) else str(err)
|
|
154
|
+
raise RuntimeError(f"JSON-RPC error from {endpoint_url}: {msg}")
|
|
155
|
+
return data.get("result")
|
|
156
|
+
|
|
157
|
+
@classmethod
|
|
158
|
+
def _resolve_client_url(cls, runtime: str = "auto", target: Optional[str] = None) -> str:
|
|
159
|
+
fe, be = cls.get_endpoints()
|
|
160
|
+
|
|
161
|
+
if runtime == "frontend":
|
|
162
|
+
if not fe:
|
|
163
|
+
raise RuntimeError("No active frontend runtime detected on ports 5173/3000")
|
|
164
|
+
return fe["url"]
|
|
165
|
+
elif runtime == "backend":
|
|
166
|
+
if not be:
|
|
167
|
+
raise RuntimeError("No active backend runtime detected on ports 8080/8000")
|
|
168
|
+
return be["url"]
|
|
169
|
+
|
|
170
|
+
# Auto detection based on target
|
|
171
|
+
if target:
|
|
172
|
+
# Backend hints: HTTP method prefixes, API paths, SQL, handlers
|
|
173
|
+
if any(target.startswith(m) for m in ["GET ", "POST ", "PUT ", "DELETE ", "PATCH "]) or "/api/" in target or target.startswith("/"):
|
|
174
|
+
if be:
|
|
175
|
+
return be["url"]
|
|
176
|
+
# Frontend hints: DOM selectors (#, .), components (<, JSX, Tab)
|
|
177
|
+
if any(target.startswith(c) for c in ["#", ".", "[", "button", "input"]) or target.startswith("<"):
|
|
178
|
+
if fe:
|
|
179
|
+
return fe["url"]
|
|
180
|
+
|
|
181
|
+
# Default fallback: backend if exists else frontend
|
|
182
|
+
if be:
|
|
183
|
+
return be["url"]
|
|
184
|
+
if fe:
|
|
185
|
+
return fe["url"]
|
|
186
|
+
raise RuntimeError("No live OUMV runtime (Frontend or Backend) detected in workspace.")
|
|
187
|
+
|
|
188
|
+
# 1. Tool: oumv_status
|
|
189
|
+
@classmethod
|
|
190
|
+
def status(cls, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
|
|
191
|
+
cls.scan(workspace_dir=workspace_dir)
|
|
192
|
+
fe, be = cls._cached_fe, cls._cached_be
|
|
193
|
+
return {
|
|
194
|
+
"frontend": fe or {"status": "DISCONNECTED", "tip": "Start frontend dev-server (port 5173/3000)"},
|
|
195
|
+
"backend": be or {"status": "DISCONNECTED", "tip": "Start backend dev-server (port 8080/8000)"},
|
|
196
|
+
"workspace": workspace_dir or get_active_workspace(),
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
# 2. Tool: oumv_observe
|
|
200
|
+
@classmethod
|
|
201
|
+
def observe(cls, level: str = "L0", target: Optional[str] = None, runtime: str = "auto") -> Any:
|
|
202
|
+
fe, be = cls.get_endpoints()
|
|
203
|
+
|
|
204
|
+
# Consolidated fullstack L0 pulse (~30 tokens)
|
|
205
|
+
if level.upper() == "L0" and (not target or target == "fullstack") and (runtime in ("auto", "")):
|
|
206
|
+
results = {"mode": "FULLSTACK_PULSE"}
|
|
207
|
+
if fe:
|
|
208
|
+
try:
|
|
209
|
+
results["frontend"] = cls._rpc_call(fe["url"], "oumv/observe", {"level": "L0"})
|
|
210
|
+
except Exception as e:
|
|
211
|
+
results["frontend"] = {"error": str(e)}
|
|
212
|
+
else:
|
|
213
|
+
results["frontend"] = {"status": "DISCONNECTED", "tip": "No active frontend dev-server (port 5173/3000)"}
|
|
214
|
+
|
|
215
|
+
if be:
|
|
216
|
+
try:
|
|
217
|
+
results["backend"] = cls._rpc_call(be["url"], "oumv/observe", {"level": "L0"})
|
|
218
|
+
except Exception as e:
|
|
219
|
+
results["backend"] = {"error": str(e)}
|
|
220
|
+
else:
|
|
221
|
+
results["backend"] = {"status": "DISCONNECTED", "tip": "No active backend dev-server (port 8080/8000)"}
|
|
222
|
+
|
|
223
|
+
return results
|
|
224
|
+
|
|
225
|
+
url = cls._resolve_client_url(runtime=runtime, target=target)
|
|
226
|
+
return cls._rpc_call(url, "oumv/observe", {"level": level, "target": target})
|
|
227
|
+
|
|
228
|
+
# 3. Tool: oumv_understand
|
|
229
|
+
@classmethod
|
|
230
|
+
def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto") -> Any:
|
|
231
|
+
fe, be = cls.get_endpoints()
|
|
232
|
+
|
|
233
|
+
# Cross-layer causality query
|
|
234
|
+
if query == "causality" and runtime in ("auto", ""):
|
|
235
|
+
report = {
|
|
236
|
+
"query": "causality",
|
|
237
|
+
"target": target,
|
|
238
|
+
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
239
|
+
}
|
|
240
|
+
if be:
|
|
241
|
+
try:
|
|
242
|
+
report["backendCausality"] = cls._rpc_call(be["url"], "oumv/understand", {"query": query, "target": target})
|
|
243
|
+
except Exception as e:
|
|
244
|
+
report["backendError"] = str(e)
|
|
245
|
+
if fe:
|
|
246
|
+
try:
|
|
247
|
+
report["frontendCausality"] = cls._rpc_call(fe["url"], "oumv/understand", {"query": query, "target": target})
|
|
248
|
+
except Exception as e:
|
|
249
|
+
report["frontendError"] = str(e)
|
|
250
|
+
return report
|
|
251
|
+
|
|
252
|
+
url = cls._resolve_client_url(runtime=runtime, target=target)
|
|
253
|
+
return cls._rpc_call(url, "oumv/understand", {"query": query, "target": target})
|
|
254
|
+
|
|
255
|
+
# 4. Tool: oumv_mutate
|
|
256
|
+
@classmethod
|
|
257
|
+
def mutate(cls, path: str, symbol: Optional[str] = None, replacement: Optional[str] = None, expected_version: Optional[str] = None, runtime: str = "auto") -> Any:
|
|
258
|
+
url = cls._resolve_client_url(runtime=runtime, target=path)
|
|
259
|
+
return cls._rpc_call(url, "oumv/applyEdit", {
|
|
260
|
+
"path": path,
|
|
261
|
+
"symbol": symbol,
|
|
262
|
+
"replacement": replacement,
|
|
263
|
+
"expectedVersion": expected_version,
|
|
264
|
+
})
|
|
265
|
+
|
|
266
|
+
# 5. Tool: oumv_verify
|
|
267
|
+
@classmethod
|
|
268
|
+
def verify(cls, target: str, action: str = "invoke", payload: Optional[dict] = None, runtime: str = "auto") -> Any:
|
|
269
|
+
url = cls._resolve_client_url(runtime=runtime, target=target)
|
|
270
|
+
return cls._rpc_call(url, "oumv/verify", {
|
|
271
|
+
"target": target,
|
|
272
|
+
"action": action,
|
|
273
|
+
"payload": payload or {},
|
|
274
|
+
})
|
package/src/telemetry_sync.py
CHANGED
|
@@ -241,7 +241,7 @@ class TelemetrySync:
|
|
|
241
241
|
current_last_id = last_id
|
|
242
242
|
headers = {
|
|
243
243
|
"Content-Type": "application/json",
|
|
244
|
-
"User-Agent": "TokenSafe-Sync/4.4.
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.4.4"
|
|
245
245
|
}
|
|
246
246
|
if active_key:
|
|
247
247
|
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.4.
|
|
20
|
+
CURRENT_VERSION = "4.4.4"
|
|
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
|