sipi-bot 0.1.0__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.
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.4
2
+ Name: sipi-bot
3
+ Version: 0.1.0
4
+ Summary: The spend firewall for autonomous AI agents — approve, block, or flag every transaction before a dollar moves.
5
+ Author-email: Sipi <sales@sipiteno.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://sipi.bot
8
+ Project-URL: Repository, https://github.com/kindrat86/sipi-bot
9
+ Project-URL: Live Dashboard, https://sipi.bot/dashboard
10
+ Project-URL: Eval Report, https://sipi.bot/eval
11
+ Keywords: ai-agents,agent-economy,mcp,spend-control,guardrails,agent-safety,x402,autonomous-agents
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Classifier: Topic :: Security
19
+ Requires-Python: >=3.11
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Provides-Extra: mcp
23
+ Requires-Dist: mcp>=1.0.0; extra == "mcp"
24
+ Dynamic: license-file
25
+
26
+ # sipi.bot — the spend firewall for autonomous AI agents
27
+
28
+ > You gave an autonomous agent your credit card and no spending limit.
29
+ > **sipi.bot** is the firewall that approves, blocks, or flags every
30
+ > transaction against *your* rules — before a single dollar moves.
31
+
32
+ One capability, three surfaces:
33
+
34
+ - **MCP tool** — Claude Code / Cursor / Hermes call `evaluate_spend` natively.
35
+ - **HTTP API** — any agent `POST /v1/transactions/evaluate`.
36
+ - **CLI** — verify without an agent.
37
+
38
+ ## 10-second test
39
+
40
+ ```bash
41
+ pip install sipi-bot
42
+ sipi-bot eval --amount 6200 --merchant unknown-gpu.ru --category compute
43
+ # -> {"decision": "BLOCKED", "reason": "Transaction $6,200.00 exceeds per-transaction limit $500.00."}
44
+
45
+ sipi-bot serve --port 8080 # landing + dashboard + API
46
+ ```
47
+
48
+ Or from source:
49
+
50
+ ```bash
51
+ python3.11 -m spendfirewall.cli eval --amount 6200 --merchant unknown-gpu.ru --category compute
52
+ ```
53
+
54
+ Then open http://localhost:8080 (landing), http://localhost:8080/dashboard (control room), http://localhost:8080/pricing (Team $99 / Business $499).
55
+
56
+ **Hosted:** [sipi.bot](https://sipi.bot) · [dashboard](https://sipi.bot/dashboard) · [get an API key →](https://sipi.bot/pricing)
57
+
58
+ ## The core call an agent makes before spending
59
+
60
+ ```bash
61
+ curl -X POST https://sipi.bot/v1/transactions/evaluate \
62
+ -H "Authorization: Bearer sk_live_..." \
63
+ -d '{"amount": 6200, "merchant": "unknown-gpu.ru", "category": "compute"}'
64
+ ```
65
+
66
+ Returns one of: `APPROVED` (go), `BLOCKED` (do not spend), `FLAGGED` (human must approve).
67
+
68
+ ## Rule types
69
+
70
+ `per_transaction`, `daily_total`, `velocity` (runaway protection), `merchant_block`,
71
+ `merchant_allow` (allowlist), `category_limit`, `time_window`, `approval_threshold`.
72
+
73
+ First `BLOCKED` wins. `FLAGGED` is non-blocking (queued for human approval).
74
+
75
+ ## Eval gym (the guarantee + the sales asset)
76
+
77
+ ```bash
78
+ python3.11 -m spendfirewall.eval.run_eval # 53 scenarios -> eval_report.json + .md
79
+ ```
80
+
81
+ 53/53 passing. Served live at `/eval`. This is what backs the guarantee:
82
+ *if the firewall green-lights a spend that breaks your rule, that month is free.*
83
+
84
+ ## MCP config
85
+
86
+ ```json
87
+ { "mcpServers": { "sipi-bot": { "command": "python", "args": ["-m", "spendfirewall.mcp_server"] } } }
88
+ ```
89
+
90
+ ## Framework integrations
91
+
92
+ Drop-in "spend guardrails" recipes — each verified live against https://sipi.bot:
93
+
94
+ - [LangChain & CrewAI](integrations/SPEND_GUARDRAILS_RECIPE.md) — `@tool` / `BaseTool` wrappers + zero-dep `sipi_guard.py` client
95
+ - [OpenAI Agents SDK](integrations/openai-agents-sdk.md) — `@function_tool` guard
96
+ - [Vercel AI SDK](integrations/vercel-ai-sdk.md) — `tool({execute})` guard + `sipiGuard.ts` client
97
+
98
+ The core call is always the same: `evaluate(amount, merchant, category)` → `APPROVED` / `BLOCKED` / `FLAGGED`.
99
+
100
+ ## Deploy (Fly.io)
101
+
102
+ ```bash
103
+ flyctl launch --no-deploy --copy-config --name sipi-bot-firewall
104
+ flyctl volumes create sf_data --size 1 --region iad --yes
105
+ flyctl deploy
106
+ flyctl certs add sipi.bot
107
+ ```
108
+
109
+ Stdlib-only (http.server, sqlite3). No framework, trivial deploy. `pip install mcp` only for the MCP surface.
@@ -0,0 +1,18 @@
1
+ sipi_bot-0.1.0.dist-info/licenses/LICENSE,sha256=kYWGb6dxxrW86NgCVy2OJYAy5u8ZI9Q0LzDTavSc3A8,1072
2
+ spendfirewall/__init__.py,sha256=FWwfHj4s5Uvnzzb4FKxL7HcP8fU9vZ0RwVU4xzu5MyA,214
3
+ spendfirewall/api.py,sha256=UXTtn_teyXESg6MnMHQPIjT1Denl1Xz1_YFxmNTedWA,18499
4
+ spendfirewall/billing.py,sha256=URPrJRjbYzMvfldj7xBc2V04QViwiGFW6hqYMh-6XFI,8085
5
+ spendfirewall/cli.py,sha256=mWnlHwzxAx_ZG4GeseSHo6kAXQs643mlGzd2UwHiAfY,1932
6
+ spendfirewall/core.py,sha256=B_VfhnWqThnNqiBTQuWDyg7SPZBxiC8Eo4A1q7vM-QY,2170
7
+ spendfirewall/engine.py,sha256=8k965eIdaImVAGtd3tyhj8ZrbSHSyL8O6tqtohqq568,9297
8
+ spendfirewall/mcp_server.py,sha256=ajq1Q6FTcueKmHcx__NchqJFoZZeHnBiRNhRtbUAvhQ,2478
9
+ spendfirewall/store.py,sha256=HxmaU6NEtCDm9J8SMz7qcvM5g5SiVNseCmPlsfh0j4s,11568
10
+ spendfirewall/templates.py,sha256=eFSD4UARH1bX_kxIG_vuLQZyWt_vdpw8fGxxmUetKrs,55597
11
+ spendfirewall/eval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ spendfirewall/eval/eval_scenarios.py,sha256=6aKBqZGo9dD9td7ibGgxAg7LIDNncBWvQZ8QNafZMyc,14703
13
+ spendfirewall/eval/run_eval.py,sha256=Y9E7cUlfx_MeIl27H8v4JXP9sMR12EQ6CJ_m1bu75GE,6417
14
+ sipi_bot-0.1.0.dist-info/METADATA,sha256=bOV9qoSliB3WnlRi9arH-uRmhW09JXu31oZd2WraR88,4090
15
+ sipi_bot-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
16
+ sipi_bot-0.1.0.dist-info/entry_points.txt,sha256=YWf94vM_saXJAyFgluo5QN4YpekjZcJozs0T-v61KYc,52
17
+ sipi_bot-0.1.0.dist-info/top_level.txt,sha256=iQ9IUssgjSISyTEG6ojQnVHq7N2DWPomWf2B2Q6vzx8,14
18
+ sipi_bot-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sipi-bot = spendfirewall.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sipi (sipi.bot)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ spendfirewall
@@ -0,0 +1,8 @@
1
+ """Sipi.bot — the spend firewall for autonomous AI agents.
2
+
3
+ We make sure no agent ever spends a dollar you didn't authorize.
4
+ """
5
+
6
+ __version__ = "0.1.0"
7
+ __product__ = "Sipi Spend Firewall"
8
+ __domain__ = "sipi.bot"
spendfirewall/api.py ADDED
@@ -0,0 +1,409 @@
1
+ """api.py — HTTP API + dashboard server + SSE + agent-card + eval report.
2
+
3
+ Stdlib only (http.server). Serves:
4
+ GET / landing page
5
+ GET /dashboard control room
6
+ GET /health {"ok": true}
7
+ GET /.well-known/agent-card.json agent discoverability
8
+ GET /eval last eval report (JSON) — the sales asset
9
+ POST /v1/transactions/evaluate THE core call (auth optional in free mode)
10
+ GET /v1/activity SSE live stream
11
+ GET /api/stats dashboard aggregates
12
+ GET /api/transactions recent txns
13
+ GET /api/approvals pending approvals
14
+ POST /api/approvals/<id> resolve {decision}
15
+ GET /api/rules list rules
16
+ POST /api/rules add rule
17
+ DELETE /api/rules/<id> delete rule
18
+ GET /api/agents list agents
19
+ POST /api/agents register agent -> api key
20
+ POST /subscribe email capture
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import os
26
+ import queue
27
+ import threading
28
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
29
+ from urllib.parse import urlparse
30
+
31
+ from . import __version__, core, store, templates
32
+ from . import billing
33
+
34
+ _SUBSCRIBERS: list[queue.Queue] = []
35
+ _SUB_LOCK = threading.Lock()
36
+ _EVAL_REPORT_PATH = os.environ.get("EVAL_REPORT", os.path.join(os.getcwd(), "eval_report.json"))
37
+ _SUBSCRIBERS_FILE = os.environ.get("SUBS_FILE", os.path.join(os.getcwd(), "subscribers.txt"))
38
+
39
+
40
+ def _broadcast(event: dict) -> None:
41
+ data = json.dumps(event)
42
+ with _SUB_LOCK:
43
+ dead = []
44
+ for q in _SUBSCRIBERS:
45
+ try:
46
+ q.put_nowait(data)
47
+ except Exception:
48
+ dead.append(q)
49
+ for q in dead:
50
+ _SUBSCRIBERS.remove(q)
51
+
52
+
53
+ def agent_card() -> dict:
54
+ return {
55
+ "name": "sipi.bot Spend Firewall",
56
+ "description": "Approves, blocks, or flags every transaction an autonomous AI agent "
57
+ "proposes, against configurable spend rules. The firewall for the agent economy.",
58
+ "version": __version__,
59
+ "url": "https://sipi.bot",
60
+ "provider": {"organization": "sipi.bot", "url": "https://sipi.bot"},
61
+ "capabilities": {"streaming": True},
62
+ "skills": [{
63
+ "id": "evaluate_transaction",
64
+ "name": "Evaluate a spend",
65
+ "description": "Given amount, merchant, category, returns APPROVED, BLOCKED, or FLAGGED.",
66
+ "tags": ["spend-control", "policy", "guardrail", "agent-safety"],
67
+ "examples": ["Can my agent spend $6200 at unknown-gpu.ru?"],
68
+ }],
69
+ "endpoints": {
70
+ "evaluate": "https://sipi.bot/v1/transactions/evaluate",
71
+ "activity": "https://sipi.bot/v1/activity",
72
+ "eval_report": "https://sipi.bot/eval",
73
+ },
74
+ }
75
+
76
+
77
+ class Handler(BaseHTTPRequestHandler):
78
+ protocol_version = "HTTP/1.0"
79
+
80
+ def log_message(self, *a): # quieter logs
81
+ pass
82
+
83
+ def _send(self, code: int, body: bytes, ctype="application/json", noindex=False):
84
+ self.send_response(code)
85
+ self.send_header("Content-Type", ctype)
86
+ if noindex:
87
+ # Machine endpoints (JSON) should not appear in search indexes.
88
+ self.send_header("X-Robots-Tag", "noindex")
89
+ self.send_header("Content-Length", str(len(body)))
90
+ self.send_header("Connection", "close")
91
+ self.send_header("Access-Control-Allow-Origin", "*")
92
+ self.send_header("Access-Control-Allow-Headers", "Authorization,Content-Type")
93
+ self.send_header("Access-Control-Allow-Methods", "GET,POST,DELETE,OPTIONS,HEAD")
94
+ # Security headers (Technical SEO + hardening)
95
+ self.send_header("X-Content-Type-Options", "nosniff")
96
+ self.send_header("X-Frame-Options", "SAMEORIGIN")
97
+ self.send_header("Referrer-Policy", "strict-origin-when-cross-origin")
98
+ self.send_header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
99
+ self.close_connection = True
100
+ self.end_headers()
101
+ if getattr(self, "_head_only", False):
102
+ return
103
+ self.wfile.write(body)
104
+ self.wfile.flush()
105
+
106
+ def do_HEAD(self):
107
+ """Mirror do_GET but suppress the body (fixes 501-on-HEAD; crawlers/audits use HEAD)."""
108
+ self._head_only = True
109
+ try:
110
+ self.do_GET()
111
+ finally:
112
+ self._head_only = False
113
+
114
+ def _json(self, code, obj, noindex=False):
115
+ self._send(code, json.dumps(obj).encode(), "application/json", noindex=noindex)
116
+
117
+ def _html(self, html: str):
118
+ self.send_response(200)
119
+ self.send_header("Content-Type", "text/html; charset=utf-8")
120
+ self.send_header("Cache-Control", "public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800")
121
+ self.send_header("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")
122
+ self.send_header("X-Content-Type-Options", "nosniff")
123
+ self.send_header("X-Frame-Options", "DENY")
124
+ self.send_header("Referrer-Policy", "strict-origin-when-cross-origin")
125
+ self.send_header("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://js.stripe.com https://eu.i.posthog.com https://eu-assets.i.posthog.com https://eu.posthog.com https://checkout.stripe.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://eu.i.posthog.com https://eu-assets.i.posthog.com https://sipi.bot; frame-ancestors 'none'; object-src 'none'; base-uri 'self'; frame-src https://js.stripe.com https://checkout.stripe.com")
126
+ self.send_header("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=(), interest-cohort=()")
127
+ self.end_headers()
128
+ self.wfile.write(html.encode())
129
+
130
+ def _body(self) -> dict:
131
+ try:
132
+ n = int(self.headers.get("Content-Length", 0))
133
+ if n <= 0:
134
+ return {}
135
+ return json.loads(self.rfile.read(n) or b"{}")
136
+ except Exception:
137
+ return {}
138
+
139
+ def do_OPTIONS(self):
140
+ self._send(204, b"")
141
+
142
+ def do_GET(self):
143
+ path = urlparse(self.path).path
144
+
145
+ # SEO: redirect www to apex
146
+ if 'host' in (h.lower() for h in self.headers.keys()):
147
+ host = self.headers.get('Host', '') or self.headers.get('host', '')
148
+ if host.startswith('www.'):
149
+ target = 'https://' + host[4:] + self.path
150
+ self.send_response(301)
151
+ self.send_header('Location', target)
152
+ self.end_headers()
153
+ return
154
+
155
+
156
+ # ── pSEO static pages ──────────────────────────
157
+ try_pseo = self._serve_pseo(path)
158
+ if try_pseo:
159
+ return
160
+ if path == "/" or path == "/index.html":
161
+ return self._html(templates.landing_page_html())
162
+ if path == "/dashboard":
163
+ return self._html(templates.dashboard_html())
164
+ if path == "/health":
165
+ return self._json(200, {"ok": True, "service": "sipi.bot", "version": __version__},
166
+ noindex=True)
167
+ if path == "/BingSiteAuth.xml":
168
+ xml = ('<?xml version="1.0"?>\n<users>\n\t<user>'
169
+ 'FA4E122745948F0CAD16959F59DDCB85</user>\n</users>')
170
+ return self._send(200, xml.encode(), "application/xml")
171
+ if path == "/.well-known/agent-card.json":
172
+ return self._json(200, agent_card())
173
+ if path == "/eval":
174
+ if os.path.exists(_EVAL_REPORT_PATH):
175
+ with open(_EVAL_REPORT_PATH) as f:
176
+ return self._json(200, json.load(f), noindex=True)
177
+ return self._json(200, {"status": "not_run_yet",
178
+ "hint": "run: python -m spendfirewall.eval.run_eval"},
179
+ noindex=True)
180
+ if path == "/api/stats":
181
+ return self._json(200, core.status())
182
+ if path == "/api/transactions":
183
+ return self._json(200, store.recent_transactions(50))
184
+ if path == "/api/approvals":
185
+ return self._json(200, store.list_approvals("pending"))
186
+ if path == "/api/rules":
187
+ return self._json(200, store.list_rules())
188
+ if path == "/api/agents":
189
+ return self._json(200, store.list_agents())
190
+ if path == "/pricing":
191
+ return self._html(templates.pricing_html())
192
+ if path == "/about":
193
+ return self._html(templates.doc_page_html(
194
+ "About", "/about",
195
+ "sipi.bot is the spend firewall for autonomous AI agents — evaluate every transaction against your rules and get approve, block, or flag in under 5ms.",
196
+ templates.ABOUT_BODY))
197
+ if path == "/privacy":
198
+ return self._html(templates.doc_page_html(
199
+ "Privacy Policy", "/privacy",
200
+ "How sipi.bot handles transaction metadata, account data, and analytics. We are a decision layer — we never store card numbers.",
201
+ templates.PRIVACY_BODY))
202
+ if path == "/terms":
203
+ return self._html(templates.doc_page_html(
204
+ "Terms of Service", "/terms",
205
+ "Terms for using sipi.bot, the spend firewall for autonomous AI agents, including the rule-integrity guarantee.",
206
+ templates.TERMS_BODY))
207
+ if path == "/billing/status":
208
+ return self._json(200, billing.status())
209
+ if path.startswith("/checkout/"):
210
+ plan = path.rsplit("/", 1)[-1]
211
+ try:
212
+ url = billing.create_checkout_session(plan)
213
+ except Exception as e:
214
+ return self._json(400, {"error": str(e)})
215
+ self.send_response(302)
216
+ self.send_header("Location", url)
217
+ self.send_header("Content-Length", "0")
218
+ self.send_header("X-Robots-Tag", "noindex, nofollow")
219
+ self.end_headers()
220
+ return
221
+ if path.startswith("/keys/"):
222
+ sess = path.rsplit("/", 1)[-1]
223
+ rec = billing.key_for_session(sess)
224
+ return self._html(templates.key_success_html(rec))
225
+ if path == "/v1/activity":
226
+ return self._sse()
227
+ # Static files from public/ (sitemap.xml, robots.txt, llms.txt, pSEO
228
+ # pages written by the growth engine). Served last, before 404.
229
+ if self._serve_static(path):
230
+ return
231
+ return self._json(404, {"error": "not_found"})
232
+
233
+ def _serve_static(self, path: str) -> bool:
234
+ """Serve a file from the public/ dir if it exists. Path-traversal safe."""
235
+ import mimetypes
236
+ root = os.environ.get("PUBLIC_DIR", os.path.join(os.getcwd(), "public"))
237
+ rel = path.lstrip("/") or "index.html"
238
+ if rel.endswith("/"):
239
+ rel += "index.html"
240
+ target = os.path.normpath(os.path.join(root, rel))
241
+ # containment check: must stay under root
242
+ if not target.startswith(os.path.abspath(root) + os.sep) and target != os.path.abspath(root):
243
+ return False
244
+ if not os.path.isfile(target):
245
+ # try /foo -> /foo/index.html (pSEO cluster pages)
246
+ alt = os.path.normpath(os.path.join(root, rel, "index.html"))
247
+ if os.path.isfile(alt):
248
+ target = alt
249
+ else:
250
+ return False
251
+ ctype = mimetypes.guess_type(target)[0] or "application/octet-stream"
252
+ try:
253
+ with open(target, "rb") as f:
254
+ data = f.read()
255
+ except OSError:
256
+ return False
257
+ self._send(200, data, ctype)
258
+ return True
259
+
260
+ def _sse(self):
261
+ self.send_response(200)
262
+ self.send_header("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://js.stripe.com https://eu.i.posthog.com https://eu-assets.i.posthog.com https://eu.posthog.com https://checkout.stripe.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://eu.i.posthog.com https://eu-assets.i.posthog.com https://sipi.bot; frame-ancestors 'none'; object-src 'none'; base-uri 'self'; frame-src https://js.stripe.com https://checkout.stripe.com")
263
+ self.send_header("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=(), interest-cohort=()")
264
+ self.send_header("Content-Type", "text/event-stream")
265
+ self.send_header("Cache-Control", "no-cache")
266
+ self.send_header("Connection", "keep-alive")
267
+ self.send_header("Access-Control-Allow-Origin", "*")
268
+ self.end_headers()
269
+ q: queue.Queue = queue.Queue()
270
+ with _SUB_LOCK:
271
+ _SUBSCRIBERS.append(q)
272
+ try:
273
+ self.wfile.write(b": connected\n\n")
274
+ self.wfile.flush()
275
+ while True:
276
+ try:
277
+ data = q.get(timeout=15)
278
+ self.wfile.write(f"data: {data}\n\n".encode())
279
+ except queue.Empty:
280
+ self.wfile.write(b"data: ping\n\n")
281
+ self.wfile.flush()
282
+ except Exception:
283
+ pass
284
+ finally:
285
+ with _SUB_LOCK:
286
+ if q in _SUBSCRIBERS:
287
+ _SUBSCRIBERS.remove(q)
288
+
289
+ def do_DELETE(self):
290
+ path = urlparse(self.path).path
291
+ if path.startswith("/api/rules/"):
292
+ rid = path.rsplit("/", 1)[-1]
293
+ return self._json(200, {"deleted": store.delete_rule(rid)})
294
+ return self._json(404, {"error": "not_found"})
295
+
296
+
297
+ def _serve_pseo(self, path):
298
+ """Serve pSEO static HTML pages from vs/ for/ learn/ integrations/ subdirs."""
299
+ import os
300
+ for prefix in ("/vs/", "/for/", "/learn/", "/integrations/", "/glossary/", "/use-cases/", "/faq/"):
301
+ if path.startswith(prefix):
302
+ filepath = os.path.join(os.path.dirname(__file__), "..", path.lstrip("/"), "index.html")
303
+ filepath = os.path.normpath(filepath)
304
+ if os.path.isfile(filepath):
305
+ try:
306
+ with open(filepath, encoding="utf-8") as fh:
307
+ return self._html(fh.read())
308
+ except Exception:
309
+ pass
310
+ return None
311
+ return None
312
+
313
+ def do_POST(self):
314
+ path = urlparse(self.path).path
315
+
316
+ # Stripe webhook must read the RAW body once (before _body parses it)
317
+ # for signature verification.
318
+ if path == "/webhooks/stripe":
319
+ try:
320
+ n = int(self.headers.get("Content-Length", 0))
321
+ raw = self.rfile.read(n) if n > 0 else b"{}"
322
+ except Exception:
323
+ raw = b"{}"
324
+ sig = self.headers.get("Stripe-Signature", "")
325
+ try:
326
+ result = billing.handle_webhook(raw, sig)
327
+ except Exception as e:
328
+ return self._json(400, {"error": str(e)})
329
+ return self._json(200, result)
330
+
331
+ body = self._body()
332
+
333
+ if path == "/v1/transactions/evaluate":
334
+ # Auth optional in free/self-host mode. If a key is provided, tie to agent.
335
+ agent_id = None
336
+ auth = self.headers.get("Authorization", "")
337
+ if auth.startswith("Bearer "):
338
+ agent = store.get_agent_by_key(auth[7:].strip())
339
+ if agent:
340
+ agent_id = agent["id"]
341
+ try:
342
+ result = core.evaluate_transaction(
343
+ amount=body.get("amount", 0),
344
+ merchant=body.get("merchant", ""),
345
+ category=body.get("category", ""),
346
+ description=body.get("description", ""),
347
+ currency=body.get("currency", "USD"),
348
+ timestamp=body.get("timestamp"),
349
+ agent_id=agent_id,
350
+ )
351
+ except Exception as e:
352
+ return self._json(400, {"error": str(e)})
353
+ _broadcast({"type": "transaction", **result})
354
+ return self._json(200, result)
355
+
356
+ if path == "/api/rules":
357
+ r = store.add_rule(
358
+ rule_type=body.get("rule_type", "per_transaction"),
359
+ params=body.get("params", {}),
360
+ action=body.get("action", "BLOCKED"),
361
+ priority=int(body.get("priority", 100)),
362
+ label=body.get("label", ""),
363
+ )
364
+ return self._json(200, r)
365
+
366
+ if path == "/api/agents":
367
+ return self._json(200, store.create_agent(body.get("name", "agent")))
368
+
369
+ if path.startswith("/api/approvals/"):
370
+ aid = path.rsplit("/", 1)[-1]
371
+ ok = store.resolve_approval(aid, body.get("decision", "deny"))
372
+ _broadcast({"type": "approval_resolved", "id": aid})
373
+ return self._json(200, {"resolved": ok})
374
+
375
+ if path == "/admin/reset":
376
+ # Admin-gated: clears transaction + approval history (keeps rules/agents).
377
+ # Used to reset the public demo after testing. Set ADMIN_TOKEN on the server.
378
+ token = os.environ.get("ADMIN_TOKEN", "")
379
+ auth = self.headers.get("Authorization", "")
380
+ given = auth[7:].strip() if auth.startswith("Bearer ") else ""
381
+ if not token or given != token:
382
+ return self._json(403, {"error": "forbidden"})
383
+ n = store.reset_demo_data()
384
+ return self._json(200, {"reset": True, "cleared": n})
385
+
386
+ if path == "/subscribe":
387
+ email = (body.get("email") or "").strip()
388
+ if email and "@" in email:
389
+ try:
390
+ with open(_SUBSCRIBERS_FILE, "a") as f:
391
+ f.write(email + "\n")
392
+ except Exception:
393
+ pass
394
+ return self._json(200, {"ok": True, "message": "You're on the list. We'll email your pilot access."})
395
+ return self._json(400, {"ok": False, "message": "Enter a valid email."})
396
+
397
+ return self._json(404, {"error": "not_found"})
398
+
399
+
400
+ def serve(host="0.0.0.0", port=None):
401
+ port = port or int(os.environ.get("PORT", 8080))
402
+ store.init_db()
403
+ srv = ThreadingHTTPServer((host, port), Handler)
404
+ print(f"sipi.bot spend firewall on http://{host}:{port}")
405
+ srv.serve_forever()
406
+
407
+
408
+ if __name__ == "__main__":
409
+ serve()