gama-fastpath 0.1.3__py3-none-any.whl

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.
fastpath.py ADDED
@@ -0,0 +1,201 @@
1
+ #!/usr/bin/env python3
2
+ """GAMA FastPath — deterministic pre-LLM gate (offline, 0 model calls).
3
+
4
+ POST /optimize {"text": "..."} -> {"ok":true,"route":"block|math|math_pdv|cache|time|know|llm", ...}
5
+ GET /health, /stats
6
+ """
7
+ import hmac, json, os, re, sqlite3, sys, time
8
+ from decimal import Decimal, ROUND_HALF_UP
9
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
10
+
11
+ # The gate decision, money-field parser, cache key and cacheability policy
12
+ # live in dsc — one copy for the whole pre-LLM stack (see dsc/MIGRATION.md).
13
+ # Pin: requirements.txt.
14
+ from dsc.amount import parse_amount
15
+ from dsc.cachekey import SCHEME as KEY_SCHEME, is_current as is_current_key, request_key
16
+ from dsc.cachepolicy import text_block_reason
17
+ from dsc.gate import check as gate_check
18
+
19
+ PORT = int(os.environ.get("GAMA_FASTPATH_PORT", "8071"))
20
+ DB = os.environ.get("GAMA_FASTPATH_DB", "/tmp/gama_fastpath.db")
21
+ TTL = int(os.environ.get("GAMA_FASTPATH_TTL", "21600"))
22
+ BIND = os.environ.get("GAMA_FASTPATH_BIND", "0.0.0.0")
23
+ MAX_BODY = int(os.environ.get("GAMA_FASTPATH_MAX_BODY", "262144"))
24
+ STORE_TOKEN = os.environ.get("GAMA_FASTPATH_STORE_TOKEN", "")
25
+
26
+ FOLD = str.maketrans("čćžšđČĆŽŠĐ", "cczsdCCZSD")
27
+ STATS = {"calls": 0, "hit": 0, "blocked": 0, "answered": 0}
28
+
29
+ def fold(t): return str(t or "").translate(FOLD)
30
+ def norm(t): return re.sub(r"\s+", " ", fold(t).lower().strip())
31
+
32
+ CACHE_VERSION = KEY_SCHEME # "v2"; v1 rows ("q:" + sha256) can no longer match
33
+
34
+
35
+ def cache_key(text, sid=""):
36
+ """Cache key = ``dsc.cachekey.request_key`` for the full request.
37
+
38
+ Hashing the whole request means two different inputs can never share an
39
+ entry, and the key contains no caller-controlled plaintext. ``sid`` is the
40
+ tenant/session scope: entries from one caller are not served to another.
41
+ ``context`` namespaces this service so a key can never be replayed against
42
+ gama-offline even if the two ever shared a database.
43
+
44
+ Scheme v2: keys are ``v2:<sha256>`` over canonical JSON; pre-v2 rows keep
45
+ their old digest and simply miss (no migration, no stale hit).
46
+ """
47
+ return request_key(text, session=str(sid or ""),
48
+ context={"app": "gama-fastpath"})
49
+
50
+
51
+ def db():
52
+ c = sqlite3.connect(DB, timeout=3)
53
+ c.execute("CREATE TABLE IF NOT EXISTS cache(k TEXT PRIMARY KEY, a TEXT, ts REAL)")
54
+ return c
55
+
56
+ def cache_get(k):
57
+ # Defence in depth: a key from another scheme is never a hit, even if a
58
+ # caller constructs it by hand. Old rows stay in the table untouched and
59
+ # expire by TTL; they are simply unreachable.
60
+ if not is_current_key(k):
61
+ return None
62
+ try:
63
+ c = db(); r = c.execute("SELECT a,ts FROM cache WHERE k=?", (k,)).fetchone(); c.close()
64
+ if r and (time.time() - r[1]) < TTL: return r[0]
65
+ except Exception: pass
66
+ return None
67
+
68
+ def cache_put(k, a, text=""):
69
+ # The freshness/multi-step rule is dsc.cachepolicy (shared with
70
+ # gama-offline). Passing the request text is optional for backwards
71
+ # compatibility, but every in-repo caller does: a clock or stock answer
72
+ # must never enter this store.
73
+ if text_block_reason(text):
74
+ return False
75
+ try:
76
+ c = db(); c.execute("INSERT OR REPLACE INTO cache(k,a,ts) VALUES(?,?,?)", (k, a, time.time()))
77
+ c.commit(); c.close()
78
+ return True
79
+ except Exception: return False
80
+
81
+ def pdv_na_neto(t):
82
+ """PDV_NA_NETO_V2: 'PDV 17% na neto 2.400,00' -> 2808.00 (Decimal, half-up)."""
83
+ m = re.search(r"pdv\s*(\d[\d.,]*)\s*%\s*na\s*neto\s*(\d[\d.,]*)", t, re.I)
84
+ if not m:
85
+ return None
86
+ p = parse_amount(m.group(1)); n = parse_amount(m.group(2))
87
+ return str((n * (Decimal(1) + p / Decimal(100))).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
88
+
89
+
90
+ def pct(t):
91
+ m = re.search(r"(\d[\d.,]*)\s*%\s*(?:od|of)\s*(\d[\d.,]*)", t, re.I)
92
+ if not m:
93
+ return None
94
+ p = parse_amount(m.group(1)); x = parse_amount(m.group(2))
95
+ v = (p / Decimal(100) * x).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
96
+ return "%s%% od %s = %s" % (m.group(1), m.group(2), str(v).replace(".", ","))
97
+
98
+
99
+ def _blocked(code, reason, elapsed):
100
+ STATS["blocked"] += 1
101
+ return {"ok": True, "route": "block", "blocked": True, "code": code,
102
+ "reason": reason, "answer": "Ne mogu to izvrsiti: %s." % reason,
103
+ "ms": elapsed()}
104
+
105
+
106
+ def optimize(text, sid=""):
107
+ t0 = time.time(); STATS["calls"] += 1
108
+ t = str(text or "").strip(); low = norm(t)
109
+ ms = lambda: round((time.time() - t0) * 1000, 2)
110
+ # One deny decision, shared with dsc: structural shell/SQL parse first,
111
+ # then the T1/T2 policy pre-filter (prompt injection, NL intent).
112
+ d = gate_check(t)
113
+ if d:
114
+ return _blocked(d.code, d.reason, ms)
115
+ # Deterministic math is authoritative: it is computed *before* the cache,
116
+ # so a poisoned/cross-tenant entry can never override a numeric answer.
117
+ v = pdv_na_neto(t)
118
+ if v:
119
+ STATS["answered"] += 1
120
+ return {"ok": True, "route": "math_pdv", "answer": v, "ms": ms()}
121
+ v = pct(t)
122
+ if v:
123
+ STATS["answered"] += 1
124
+ return {"ok": True, "route": "math", "answer": v, "ms": ms()}
125
+ k = cache_key(t, sid)
126
+ if text_block_reason(t) is None:
127
+ hit = cache_get(k)
128
+ if hit:
129
+ STATS["hit"] += 1
130
+ return {"ok": True, "route": "cache", "cached": True, "answer": hit, "ms": ms()}
131
+ if re.fullmatch(r"(koje je )?(vrijeme|datum|danas)\??", low):
132
+ return {"ok": True, "route": "time", "answer": time.strftime("%d.%m.%Y %H:%M"), "ms": ms()}
133
+ return {"ok": True, "route": "llm", "ms": ms()}
134
+
135
+ def store_allowed(client_ip, token):
136
+ """Loopback is trusted for local MCP; remote callers need the configured token."""
137
+ if client_ip in ("127.0.0.1", "::1"):
138
+ return True
139
+ return bool(STORE_TOKEN) and hmac.compare_digest(str(token or ""), STORE_TOKEN)
140
+
141
+
142
+ class H(BaseHTTPRequestHandler):
143
+ def log_message(self, *a): pass
144
+ def _send(self, obj, code=200):
145
+ b = json.dumps(obj, ensure_ascii=False).encode()
146
+ self.send_response(code); self.send_header("Content-Type", "application/json; charset=utf-8")
147
+ self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
148
+ def do_GET(self):
149
+ if self.path.startswith("/health"): return self._send({"ok": True, "svc": "gama-fastpath", "port": PORT})
150
+ if self.path.startswith("/stats"): return self._send({"ok": True, **STATS})
151
+ self._send({"ok": False, "err": "not found"}, 404)
152
+ def do_POST(self):
153
+ try:
154
+ n = int(self.headers.get("Content-Length") or 0)
155
+ except Exception:
156
+ return self._send({"ok": False, "err": "bad content-length"}, 400)
157
+ if n > MAX_BODY:
158
+ return self._send({"ok": False, "err": "request too large"}, 413)
159
+ try:
160
+ j = json.loads(self.rfile.read(n) or b"{}")
161
+ except Exception:
162
+ return self._send({"ok": False, "err": "bad json"}, 400)
163
+ sid = str(j.get("sid") or j.get("tenant") or
164
+ self.headers.get("X-Tenant-ID") or "")
165
+ if self.path.startswith("/optimize"):
166
+ return self._send(optimize(j.get("text", ""), sid=sid))
167
+ if self.path.startswith("/store"):
168
+ if not store_allowed(self.client_address[0], self.headers.get("X-Store-Token", "")):
169
+ return self._send({"ok": False, "err": "forbidden"}, 403)
170
+ text = str(j.get("text", ""))
171
+ a = str(j.get("answer", ""))
172
+ reason = text_block_reason(text)
173
+ stored = bool(a) and not reason and cache_put(cache_key(text, sid), a, text)
174
+ out = {"ok": True, "stored": bool(stored)}
175
+ if reason:
176
+ out["reason"] = reason
177
+ return self._send(out)
178
+ self._send({"ok": False, "err": "not found"}, 404)
179
+
180
+ USAGE = "usage: fastpath.py [--check TEXT] (serve :%d by default)" % PORT
181
+
182
+
183
+ def main(argv=None):
184
+ """Exit codes: 0 = allowed/answered, 3 = denied by the gate, 2 = usage."""
185
+ argv = list(sys.argv[1:] if argv is None else argv)
186
+ if argv and argv[0] in ("--check", "-c", "check"):
187
+ if len(argv) < 2:
188
+ print(json.dumps({"ok": False, "err": USAGE}), flush=True)
189
+ return 2
190
+ text = " ".join(argv[1:])
191
+ r = optimize(text)
192
+ print(json.dumps(r, ensure_ascii=False), flush=True)
193
+ return 3 if r.get("blocked") else 0
194
+ if argv and argv[0] not in ("--serve", "serve"):
195
+ print(json.dumps({"ok": False, "err": USAGE}), flush=True)
196
+ return 2
197
+ print("gama-fastpath :%d" % PORT, flush=True)
198
+ ThreadingHTTPServer((BIND, PORT), H).serve_forever()
199
+ return 0
200
+
201
+ if __name__ == "__main__": sys.exit(main())
fastpath_mcp.py ADDED
@@ -0,0 +1,297 @@
1
+ #!/usr/bin/env python3
2
+ """Minimal MCP (Model Context Protocol) server for gama-fastpath.
3
+
4
+ Speaks JSON-RPC 2.0 over stdio, so any MCP client (Claude Desktop, Cursor,
5
+ OpenCode, Glama) can consult the deterministic pre-LLM gate without an SDK and
6
+ without a network hop.
7
+
8
+ Tools:
9
+ fastpath_route — run the gate on one request/command and return the route
10
+ fastpath_rules — the allowlist: every route, what it does, denial codes
11
+ fastpath_health — service, cache DB, counters and listener state
12
+
13
+ Protocol: https://modelcontextprotocol.io/specification (2025-06-18 core,
14
+ stdio transport). No third-party dependencies beyond fastpath's own dsc pin.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import socket
21
+ import sqlite3
22
+ import sys
23
+ from typing import Any, Dict
24
+
25
+ try: # the gate module needs the pinned `dsc`; keep the MCP handshake alive without it
26
+ import fastpath as fp
27
+ FP_ERROR = ""
28
+ except Exception as _exc: # noqa: BLE001 - reported by the route tool
29
+ fp = None # type: ignore[assignment]
30
+ FP_ERROR = str(_exc)
31
+
32
+ GATE_DEP = (
33
+ "dsc @ git+https://github.com/gamai-io/dsc@"
34
+ "7c433d59c848d2853abda639753bcec7042890cf"
35
+ )
36
+ PORT = int(os.environ.get("GAMA_FASTPATH_PORT", "8071"))
37
+ DB = os.environ.get("GAMA_FASTPATH_DB", "/tmp/gama_fastpath.db")
38
+ TTL = int(os.environ.get("GAMA_FASTPATH_TTL", "21600"))
39
+ BIND = os.environ.get("GAMA_FASTPATH_BIND", "0.0.0.0")
40
+
41
+ SERVER_NAME = "gama-fastpath"
42
+ SERVER_VERSION = "0.1.3"
43
+ PROTOCOL = "2025-06-18"
44
+
45
+ ROUTES = [
46
+ {
47
+ "route": "block",
48
+ "decision": "deny",
49
+ "meaning": "structural shell/SQL parse or T1/T2 policy hit; never reaches a model",
50
+ },
51
+ {
52
+ "route": "math_pdv",
53
+ "decision": "answer",
54
+ "meaning": "'PDV <p>% na neto <n>' computed with Decimal, half-up (17%)",
55
+ },
56
+ {
57
+ "route": "math",
58
+ "decision": "answer",
59
+ "meaning": "'<p>% od <n>' computed with Decimal, half-up",
60
+ },
61
+ {
62
+ "route": "cache",
63
+ "decision": "answer",
64
+ "meaning": "previous answer from the SQLite cache, same tenant/session, within TTL",
65
+ },
66
+ {
67
+ "route": "time",
68
+ "decision": "answer",
69
+ "meaning": "clock/date question answered from the local clock, never cached",
70
+ },
71
+ {
72
+ "route": "llm",
73
+ "decision": "pass",
74
+ "meaning": "allowlist miss; forward the request to a model",
75
+ },
76
+ ]
77
+
78
+ DENIAL_CODES = [
79
+ "bulk_mail", "catastrophic_command", "destructive_recursive_delete",
80
+ "destructive_root_delete", "disk_destroy", "find_delete",
81
+ "find_exec_delete", "fork_bomb", "permissions_root",
82
+ "permissions_world_writable", "policy", "remote_code_exec",
83
+ "sensitive_file_read", "sql_delete_without_where", "sql_drop",
84
+ "sql_truncate", "sql_update_without_where",
85
+ ]
86
+
87
+ TOOLS = [
88
+ {
89
+ "name": "fastpath_route",
90
+ "description": (
91
+ "Route one request/command through the deterministic 0-LLM gate: returns "
92
+ "route block|math|math_pdv|cache|time|llm, the decision (deny|answer|pass), "
93
+ "the denial code and reason when blocked, and the computed answer when the "
94
+ "gate can answer without a model. Under 10 ms, no token spent."
95
+ ),
96
+ "inputSchema": {
97
+ "type": "object",
98
+ "properties": {
99
+ "request": {
100
+ "type": "string",
101
+ "description": "the user request or shell/SQL command to route",
102
+ },
103
+ "command": {
104
+ "type": "string",
105
+ "description": "alias for request (a concrete command to check)",
106
+ },
107
+ "sid": {
108
+ "type": "string",
109
+ "description": "tenant/session id used to scope the cache",
110
+ "default": "",
111
+ },
112
+ },
113
+ "anyOf": [{"required": ["request"]}, {"required": ["command"]}],
114
+ },
115
+ },
116
+ {
117
+ "name": "fastpath_rules",
118
+ "description": (
119
+ "List the routing allowlist: each route, whether it answers or passes to an "
120
+ "LLM, the stable denial codes the gate can return, and the cache policy."
121
+ ),
122
+ "inputSchema": {"type": "object", "properties": {}},
123
+ },
124
+ {
125
+ "name": "fastpath_health",
126
+ "description": (
127
+ "Health of the local fastpath: version, port/bind, cache DB path and entry "
128
+ "count, TTL, in-process counters and whether the HTTP listener answers."
129
+ ),
130
+ "inputSchema": {"type": "object", "properties": {}},
131
+ },
132
+ ]
133
+
134
+
135
+ def route(request_text: str, sid: str = "") -> Dict[str, Any]:
136
+ """Run the gate and add the decision + a one-line rationale."""
137
+ if fp is None:
138
+ raise RuntimeError(
139
+ "gate module unavailable (%s); install the pinned gate dependency: "
140
+ "pip install \"%s\"" % (FP_ERROR, GATE_DEP)
141
+ )
142
+ r = fp.optimize(request_text, sid=sid)
143
+ out: Dict[str, Any] = dict(r)
144
+ out["ok"] = bool(r.get("ok", True))
145
+ out["request"] = request_text
146
+ if r.get("blocked"):
147
+ out["decision"] = "deny"
148
+ out["explain"] = (
149
+ "gate denied (%s): no model call, request never executed"
150
+ % r.get("code", "policy")
151
+ )
152
+ elif r.get("route") in ("math", "math_pdv"):
153
+ out["decision"] = "answer"
154
+ out["explain"] = "deterministic arithmetic, Decimal half-up; model never called"
155
+ elif r.get("route") == "cache":
156
+ out["decision"] = "answer"
157
+ out["explain"] = "cache hit within TTL for this tenant/session"
158
+ elif r.get("route") == "time":
159
+ out["decision"] = "answer"
160
+ out["explain"] = "answered from the local clock; never cached"
161
+ else:
162
+ out["decision"] = "pass"
163
+ out["explain"] = "allowlist miss: forward to the model"
164
+ return out
165
+
166
+
167
+ def health() -> Dict[str, Any]:
168
+ out: Dict[str, Any] = {
169
+ "ok": True,
170
+ "svc": SERVER_NAME,
171
+ "mcp_version": SERVER_VERSION,
172
+ "port": PORT,
173
+ "bind": BIND,
174
+ "db": DB,
175
+ "ttl_s": TTL,
176
+ "routes": [r["route"] for r in ROUTES],
177
+ "stats": dict(fp.STATS) if fp is not None else {},
178
+ "gate_ready": fp is not None,
179
+ }
180
+ if FP_ERROR:
181
+ out["gate_error"] = FP_ERROR
182
+ try:
183
+ conn = sqlite3.connect(DB, timeout=1)
184
+ out["cache_entries"] = conn.execute("SELECT count(*) FROM cache").fetchone()[0]
185
+ conn.close()
186
+ out["db_ok"] = True
187
+ except Exception as exc: # noqa: BLE001 - reported, not raised
188
+ out["db_ok"] = False
189
+ out["db_error"] = str(exc)
190
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
191
+ sock.settimeout(0.25)
192
+ try:
193
+ out["http_up"] = sock.connect_ex(("127.0.0.1", PORT)) == 0
194
+ except Exception: # noqa: BLE001
195
+ out["http_up"] = False
196
+ finally:
197
+ sock.close()
198
+ out["ok"] = bool(out.get("db_ok")) and out["http_up"]
199
+ return out
200
+
201
+
202
+ def rules() -> Dict[str, Any]:
203
+ return {
204
+ "ok": True,
205
+ "svc": SERVER_NAME,
206
+ "order": ["block", "math_pdv", "math", "cache", "time", "llm"],
207
+ "routes": ROUTES,
208
+ "denial_codes": DENIAL_CODES,
209
+ "cache": {
210
+ "scheme": fp.CACHE_VERSION if fp is not None else "v2",
211
+ "key": "sha256 over canonical request + tenant/session + app context",
212
+ "ttl_s": TTL,
213
+ "never_cached": ["clock/date", "stock", "price", "multi-step text"],
214
+ },
215
+ }
216
+
217
+
218
+ def call_tool(name: str, args: Dict[str, Any]) -> Dict[str, Any]:
219
+ if name == "fastpath_route":
220
+ text = args.get("request")
221
+ if not text:
222
+ text = args.get("command")
223
+ return route(str(text or ""), sid=str(args.get("sid") or ""))
224
+ if name == "fastpath_rules":
225
+ return rules()
226
+ if name == "fastpath_health":
227
+ return health()
228
+ raise ValueError("unknown tool: %s" % name)
229
+
230
+
231
+ def _reply(msg_id: Any, result: Any) -> None:
232
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": msg_id, "result": result}) + "\n")
233
+ sys.stdout.flush()
234
+
235
+
236
+ def _error(msg_id: Any, code: int, message: str) -> None:
237
+ sys.stdout.write(json.dumps(
238
+ {"jsonrpc": "2.0", "id": msg_id, "error": {"code": code, "message": message}}) + "\n")
239
+ sys.stdout.flush()
240
+
241
+
242
+ def handle(msg: Dict[str, Any]) -> None:
243
+ method = msg.get("method")
244
+ msg_id = msg.get("id")
245
+ params = msg.get("params") or {}
246
+
247
+ if method == "initialize":
248
+ _reply(msg_id, {
249
+ "protocolVersion": PROTOCOL,
250
+ "capabilities": {"tools": {"listChanged": False}},
251
+ "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
252
+ })
253
+ return
254
+ if method in ("notifications/initialized", "notifications/cancelled"):
255
+ return
256
+ if method == "ping":
257
+ _reply(msg_id, {})
258
+ return
259
+ if method == "tools/list":
260
+ _reply(msg_id, {"tools": TOOLS})
261
+ return
262
+ if method == "tools/call":
263
+ name = params.get("name")
264
+ args = params.get("arguments") or {}
265
+ try:
266
+ result = call_tool(str(name), args if isinstance(args, dict) else {})
267
+ _reply(msg_id, {
268
+ "content": [{"type": "text", "text": json.dumps(result, ensure_ascii=False)}],
269
+ "isError": False,
270
+ })
271
+ except Exception as exc: # noqa: BLE001 - surface the error to the client
272
+ _reply(msg_id, {"content": [{"type": "text", "text": "error: %s" % exc}],
273
+ "isError": True})
274
+ return
275
+ if msg_id is not None:
276
+ _error(msg_id, -32601, "method not found: %s" % method)
277
+
278
+
279
+ def main() -> int:
280
+ for line in sys.stdin:
281
+ line = line.strip()
282
+ if not line:
283
+ continue
284
+ try:
285
+ msg = json.loads(line)
286
+ except Exception:
287
+ continue
288
+ if isinstance(msg, list):
289
+ for m in msg:
290
+ handle(m)
291
+ else:
292
+ handle(msg)
293
+ return 0
294
+
295
+
296
+ if __name__ == "__main__":
297
+ raise SystemExit(main())
@@ -0,0 +1,188 @@
1
+ Metadata-Version: 2.4
2
+ Name: gama-fastpath
3
+ Version: 0.1.3
4
+ Summary: Deterministic 0-LLM pre-LLM gate: blocks destructive shell/SQL requests and answers money math offline.
5
+ Author: GAMA
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/gamai-io/gama-fastpath
8
+ Project-URL: Repository, https://github.com/gamai-io/gama-fastpath
9
+ Keywords: mcp,pre-llm,router,guardrail,deterministic,pdv
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ <!-- mcp-name: io.github.gamai-io/gama-fastpath -->
19
+ # gama-fastpath
20
+
21
+ <p align="center"><img src="assets/logo.svg" width="96" alt="GAMA logo"></p>
22
+
23
+ [![CI](https://github.com/gamai-io/gama-fastpath/actions/workflows/ci.yml/badge.svg)](https://github.com/gamai-io/gama-fastpath/actions/workflows/ci.yml)
24
+
25
+ [![Version](https://img.shields.io/badge/version-v0.1.3-22d3ee)](https://github.com/gamai-io/gama-fastpath/releases)
26
+
27
+
28
+ Deterministic **pre-LLM gate**: blocks catastrophic/destructive or env-disclosure
29
+ requests and answers money math without any model call. Offline, stdlib only.
30
+
31
+ - **Structural gate** (`dsc.gate`, pinned as a `dsc` dependency): shell requests
32
+ are split into statements and pipelines, tokenised with `shlex`, wrappers
33
+ (`sudo`, `env`, `xargs`, `timeout`, ...) are unwrapped, and `sh -c` payloads
34
+ plus `$(...)`/backtick substitutions are analysed recursively. Flags may be
35
+ reordered, quoted or abbreviated; it is the parsed argv that decides, not a
36
+ phrase list. This repo no longer carries its own `gate.py`.
37
+ - recursive delete/overwrite of `/`, `/etc`, home (`~`, `$HOME`) — including
38
+ `rm -fr /`, `rm --recursive --force /`, `sudo rm -rf --no-preserve-root /`
39
+ - `find ... -delete` / `find ... -exec rm`
40
+ - SQL `drop` / `truncate`, and `delete`/`update` **without `WHERE`**
41
+ - reads of `/etc/shadow`, `/etc/passwd`, `id_rsa`, `.env`, cloud credentials
42
+ - `curl|wget ... | sh|bash|python`, `sh -c "$(curl ...)"`, `eval $(curl ...)`
43
+ - mass outbound mail (`pošalji mejl svim kupcima`, `send email to all customers`)
44
+ - fork bombs, `mkfs`/`dd of=/dev/sd*`, recursive `chmod`/`chown` on `/`
45
+ - Each denial returns `route:"block"`, `blocked:true`, a stable `code` and a
46
+ human `reason` (e.g. `destructive_root_delete`, `sql_delete_without_where`,
47
+ `sensitive_file_read`, `remote_code_exec`, `bulk_mail`).
48
+ - `T1`/`T2` regexes (`dsc.gate`) remain only as a cheap pre-filter for
49
+ natural-language policy phrases (prompt injection), not as the gate.
50
+ - Math: `PDV 17% na neto 2400` -> **2808.00**; `17% od 1450` -> 246,50 (Decimal, half-up).
51
+ - Diacritics fold: `Obriši` -> `obrisi` (risk match works on Bosnian text).
52
+ - SQLite response cache (TTL 6 h) keyed by a **SHA-256 of the full normalized
53
+ request + tenant/session**, `/stats`. Freshness (clock, stock, price) and
54
+ multi-step text are never read from or written to it — the rules are
55
+ `dsc.cachepolicy`, shared with `gama-offline`.
56
+
57
+ ## Run
58
+ ```bash
59
+ pip install -r requirements.txt # dsc, pinned by commit (gate + amount + cache policy)
60
+ python3 fastpath.py # :8071
61
+ curl -s localhost:8071/optimize -d '{"text":"Obriši sve fajlove u /var/log"}'
62
+ # {"route":"block","blocked":true,"code":"catastrophic_command","reason":"...",...}
63
+ curl -s localhost:8071/optimize -d '{"text":"rm -fr /"}'
64
+ # {"route":"block","blocked":true,"code":"destructive_root_delete",...}
65
+ curl -s localhost:8071/optimize -d '{"text":"PDV 17% na neto 2400"}'
66
+ # {"route":"math_pdv","answer":"2808.00",...}
67
+ ```
68
+ Tests: `python3 -m unittest discover -s tests -v`
69
+
70
+ ## MCP server (stdio, no SDK)
71
+
72
+ The package ships `fastpath_mcp.py`: JSON-RPC 2.0 over stdio, protocol
73
+ `2025-06-18`, stdlib only.
74
+
75
+ ```bash
76
+ pip install gama-fastpath # provides gama-fastpath-mcp
77
+ pip install "dsc @ git+https://github.com/gamai-io/dsc@7c433d59c848d2853abda639753bcec7042890cf" # pinned gate
78
+ gama-fastpath-mcp # MCP server on stdin/stdout
79
+ ```
80
+
81
+ PyPI forbids direct-URL requirements, so `dsc` (pinned by commit in
82
+ `requirements.txt`) is a separate install; without it the handshake still
83
+ works and `fastpath_route` returns the exact install command.
84
+
85
+ ```json
86
+ {"mcpServers": {"gama-fastpath": {"command": "gama-fastpath-mcp", "args": []}}}
87
+ ```
88
+
89
+ Three tools, each returning JSON:
90
+
91
+ | tool | input | returns |
92
+ |------|-------|---------|
93
+ | `fastpath_route` | `{"request": "PDV 17% na neto 2400"}`, `{"command": "rm -fr /"}`, optional `sid` | `route`, `decision` (`deny`/`answer`/`pass`), `code`+`reason` when blocked, `answer`, `ms`, `explain` |
94
+ | `fastpath_rules` | `{}` | the allowlist: every route, its meaning, all stable denial codes, cache policy |
95
+ | `fastpath_health` | `{}` | version, port/bind, cache DB + entry count, TTL, counters, `http_up` |
96
+
97
+ `tools/call` → `fastpath_route {"command": "rm -fr /"}`:
98
+
99
+ ```json
100
+ {"ok":true,"route":"block","blocked":true,"code":"destructive_root_delete",
101
+ "reason":"rekurzivno brisanje korijena ili kucnog direktorija: /",
102
+ "ms":0.16,"decision":"deny",
103
+ "explain":"gate denied (destructive_root_delete): no model call, request never executed"}
104
+ ```
105
+
106
+ `tools/call` → `fastpath_route {"request": "17% od 1450"}`:
107
+
108
+ ```json
109
+ {"ok":true,"route":"math","answer":"17% od 1450 = 246,50","ms":0.4,
110
+ "decision":"answer","explain":"deterministic arithmetic, Decimal half-up; model never called"}
111
+ ```
112
+
113
+
114
+ ### CLI and exit codes
115
+
116
+ ```bash
117
+ python3 fastpath.py --check 'rm -fr /' # prints JSON, exit 3
118
+ python3 fastpath.py --check 'zdravo' # prints JSON, exit 0
119
+ ```
120
+
121
+ | exit | meaning |
122
+ |------|---------|
123
+ | `0` | request allowed/answered (may still route to `llm`) |
124
+ | `3` | denied by the gate (`blocked:true`, with `code` + `reason`) |
125
+ | `2` | usage error (missing `--check` argument) |
126
+
127
+ ## Measured
128
+ - T1 block **0.03 ms**, T2 block **0.06–0.94 ms**, PDV **6.2 ms** cold first
129
+ call (math is recomputed on every request, never served from the cache).
130
+ - LUMI MI250X guarded bench: false_success 19.7% raw -> **0/1,000**; 10k rerun (2026-11-04) **1/10,000 (FAIL)** — earlier 0/10,000 not reproduced; 114.4 rps @ CONC=512 (prior run).
131
+ - Related: https://github.com/gamai-io/crossnode-bench (DOI 10.5281/zenodo.23933835).
132
+
133
+ Apache-2.0.
134
+ ## Tests
135
+ ```bash
136
+ make test
137
+ ```
138
+
139
+ ## Cache safety
140
+
141
+ - The key is `dsc.cachekey.request_key` — **`v2:` + SHA-256** over the canonical
142
+ JSON object `{"v","t","tenant","session","ctx"}`, where `t` is the full
143
+ normalized request and `session` is the optional tenant (`sid` or `tenant` in
144
+ the body, or `X-Tenant-ID`). Fields are JSON values, not `|`-joined
145
+ substrings, so a delimiter in the text cannot collide with another tenant.
146
+ Two different inputs or tenants never share an entry, and caller text is not
147
+ stored in the key. Pre-v2 rows are unreachable (old `q:` keys): they miss
148
+ once and age out by TTL. `cache_get` also refuses any non-v2 key.
149
+ - Deterministic math is computed **before** the cache lookup and is never
150
+ read from it, so a stored answer cannot override `PDV ...` arithmetic
151
+ (regression: storing `0.00` for a PDV query still returns `2808.00`).
152
+ - `dsc.cachepolicy.block_reason` owns "may this be replayed?". `cache_put` and
153
+ `/store` refuse fresh text (clock, stock, price), multi-step chains and
154
+ answers shorter than 15 chars; `/store` answers
155
+ `{"ok": true, "stored": false, "reason": "fresh"}` instead of silently
156
+ writing. `optimize` skips the cache read for the same texts, so a row written
157
+ before this rule existed is ignored rather than served.
158
+
159
+ ## Security / deployment
160
+
161
+ - Default bind is `GAMA_FASTPATH_BIND=0.0.0.0` for LAN/Tailscale callers. On a public
162
+ host, block the port at the firewall (verified on one of our hosts: ufw default-DROP, the port
163
+ unreachable from an external node while 80/443 answer).
164
+ - `POST /store` is **loopback-only**. Remote callers must set `GAMA_FASTPATH_STORE_TOKEN`
165
+ and send it as `X-Store-Token`; without it the endpoint answers `403`.
166
+ - Request bodies are capped by `GAMA_FASTPATH_MAX_BODY` (default 262144 bytes) and
167
+ oversized requests get `413`, so one client cannot exhaust memory.
168
+ - The HTTP handler never echoes parser exceptions back to the caller.
169
+
170
+ ## Money formats
171
+
172
+ `dsc.amount.parse_amount` (imported here, not copied) accepts BHS/EU/US thousands separators
173
+ deterministically (Decimal, half-up): `2400`, `2.400`, `2.400,00`, `1.234.567,89`, `2,400.00`
174
+ all resolve correctly. Regression tests cover these forms; the earlier regex stopped at the
175
+ first separator and returned `2.81` for `2.400,00`.
176
+
177
+ ## How this is sold (and what it saves)
178
+
179
+ The gate is **free to adopt**: it is a deterministic pre-LLM step, and metering it would cost
180
+ more than it earns. What it returns, measured on our traffic (2026-11-23):
181
+
182
+ - `PDV 17% na neto 2400` → **2808.00 in 6.2 ms, 0 tokens**, versus 2.53 s and ~$0.0019 through a model.
183
+ - `rm -rf /`, `drop table`, `obrisi sve` → blocked in **0.03–0.06 ms** before any model runs.
184
+ - Every answer that never reaches the model is a call the customer does not pay for.
185
+
186
+ We charge for the harness and the audit around the gate (evidence receipts, replay), not for the
187
+ arithmetic. A buyer is shown their own intercepted-request count, not a percentage we computed
188
+ on our own workload.
@@ -0,0 +1,8 @@
1
+ fastpath.py,sha256=Eh4xyOMdbHEwjeBcZh38ZBOdpSUWzqArt7D3QmKkVJI,8710
2
+ fastpath_mcp.py,sha256=Zw6Nvm1tBV5V3LS7qjMCWGk_W9jh6Q7YBnyfDRbexcs,10027
3
+ gama_fastpath-0.1.3.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
4
+ gama_fastpath-0.1.3.dist-info/METADATA,sha256=CLfZDWJtD1MfGEZ4bS0G2LCCitX4YsZxALJ4RMOUX4U,9325
5
+ gama_fastpath-0.1.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ gama_fastpath-0.1.3.dist-info/entry_points.txt,sha256=qJIvAHUk7QDfVeWigcA4_qhvknCxbpq2mKIb2BBQVSs,86
7
+ gama_fastpath-0.1.3.dist-info/top_level.txt,sha256=uSB8u9FaDywIjXCkVGXPJLzMNuqmT7Mpo7A1K142TCY,22
8
+ gama_fastpath-0.1.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ gama-fastpath = fastpath:main
3
+ gama-fastpath-mcp = fastpath_mcp:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ fastpath
2
+ fastpath_mcp