contextgate-core 0.6.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,442 @@
1
+ """
2
+ Compression gateway proxy for OpenAI-compatible (/v1/chat/completions) and Anthropic (/v1/messages) APIs. Point any SDK
3
+ or agent at it; requests are gated, forwarded, relayed (streaming included), post-audited and recorded in the ledger.
4
+
5
+ python gateway.py --upstream https://api.openai.com # OpenAI-compatible: base_url=http://127.0.0.1:8787/v1
6
+ python gateway.py --upstream https://api.anthropic.com # Anthropic / Claude Code: ANTHROPIC_BASE_URL=http://127.0.0.1:8787
7
+
8
+ Guarantees: fail-open (any gate error forwards the original request); credentials (Authorization, x-api-key, ...) are
9
+ forwarded untouched and never logged or stored; the ledger stores counts only; binds to loopback unless --allow-remote;
10
+ the response relayed to the client is exactly what the upstream sent (the gateway only ADDS X-ContextGate-* headers);
11
+ SIGTERM waits for in-flight requests so their ledger rows are not lost. Stdlib only.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import gzip
18
+ import http.client
19
+ import json
20
+ import os
21
+ import signal
22
+ import ssl
23
+ import sys
24
+ import time
25
+ import urllib.parse
26
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
27
+ from typing import Any
28
+
29
+ from . import gate
30
+ from . import ledger as lg
31
+ from . import pipeline as _p
32
+ from .data_contracts import OptimizationTrace
33
+ from .protocol import __version__
34
+
35
+ HOP_BY_HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailers",
36
+ "transfer-encoding", "upgrade"}
37
+ MAX_BODY = 64 * 1024 * 1024
38
+ _REMINDER_RE = __import__("re").compile(r"<system-reminder>.*?</system-reminder>", __import__("re").S)
39
+
40
+
41
+ class Config:
42
+ def __init__(self, upstream: str, profile: str = "strict", ledger: lg.Ledger | None = None, record_path: str | None = None,
43
+ timeout: float = 600.0, force_usage: bool = False, audit: bool = True, verbose: bool = False,
44
+ max_body: int = MAX_BODY) -> None:
45
+ u = urllib.parse.urlsplit(upstream)
46
+ if u.scheme not in ("http", "https") or not u.hostname:
47
+ raise ValueError(f"--upstream must be an http(s) URL, got {upstream!r}")
48
+ if profile not in gate.PROFILES:
49
+ raise ValueError(f"unknown profile {profile!r}; choose from {', '.join(gate.PROFILES)}")
50
+ self.upstream, self.scheme, self.host, self.port = upstream, u.scheme, u.hostname, u.port or (443 if u.scheme == "https" else 80)
51
+ self.base_path = u.path.rstrip("/")
52
+ self.profile, self.ledger, self.record_path = profile, ledger, record_path
53
+ self.timeout, self.force_usage, self.audit, self.verbose, self.max_body = timeout, force_usage, audit, verbose, max_body
54
+
55
+
56
+ # ── per-API knowledge (route, text for audit, usage, stream events) ───────────
57
+ def route_kind(method: str, path: str) -> str | None:
58
+ """'openai' | 'anthropic' | None (anything else is relayed untouched; count_tokens and batches are not gated)."""
59
+ if method != "POST":
60
+ return None
61
+ p = urllib.parse.urlsplit(path).path.rstrip("/")
62
+ if p.endswith("/chat/completions"):
63
+ return "openai"
64
+ if p.endswith("/messages"):
65
+ return "anthropic"
66
+ return None
67
+
68
+
69
+ def _user_text(body: dict, kind: str) -> str:
70
+ """The user's own typed instruction: for Anthropic the newest user message that has plain text (tool results and
71
+ <system-reminder> wrappers do not count), for OpenAI the newest user message."""
72
+ for msg in reversed(body.get("messages") or []):
73
+ if not (isinstance(msg, dict) and msg.get("role") == "user"):
74
+ continue
75
+ c = msg.get("content")
76
+ if isinstance(c, str):
77
+ text = c
78
+ elif isinstance(c, list):
79
+ text = "\n".join(p.get("text", "") for p in c if isinstance(p, dict) and p.get("type") == "text")
80
+ else:
81
+ continue
82
+ text = _REMINDER_RE.sub("", text).strip() if kind == "anthropic" else text
83
+ if text:
84
+ return text
85
+ if kind == "openai":
86
+ return ""
87
+ return ""
88
+
89
+
90
+ def audit_response(original_body: dict, response_text: str, kind: str = "openai") -> dict[str, Any] | None:
91
+ """Deterministic post-audit against constraints found in the ORIGINAL user instruction. Transparent mode has no
92
+ intent routing, so format checks do not apply; the negation check is the heuristic one in pipeline.audit_agent_response
93
+ (it detects slicing and recursion violations only). entity_ok is therefore None (not applicable)."""
94
+ if not response_text:
95
+ return None
96
+ text = _user_text(original_body, kind)
97
+ trace = OptimizationTrace()
98
+ trace.negations = _p._extract_negations(text)
99
+ trace.extracted_entities = _p._extract_entities(text, text)
100
+ res = _p.audit_agent_response(response_text, trace)
101
+ neg = next((c["passed"] for c in res["checks"] if c["check"].startswith("Negation")), None)
102
+ return {"score": res["compliance_score"], "neg_ok": neg, "entity_ok": None}
103
+
104
+
105
+ def parse_response(kind: str, payload: dict) -> tuple[str, dict]:
106
+ """(assistant text, normalised usage {prompt, completion, cache_read, cache_write}) from a non-streaming reply."""
107
+ text, usage = "", payload.get("usage") if isinstance(payload.get("usage"), dict) else {}
108
+ if kind == "anthropic":
109
+ text = "".join(b.get("text", "") for b in payload.get("content") or [] if isinstance(b, dict) and b.get("type") == "text")
110
+ return text, _anthropic_usage(usage)
111
+ try:
112
+ text = payload["choices"][0]["message"].get("content") or ""
113
+ except (KeyError, IndexError, TypeError, AttributeError):
114
+ pass
115
+ return text if isinstance(text, str) else "", _openai_usage(usage)
116
+
117
+
118
+ def _openai_usage(u: dict) -> dict:
119
+ cached = (u.get("prompt_tokens_details") or {}).get("cached_tokens") if isinstance(u.get("prompt_tokens_details"), dict) else None
120
+ return {"prompt": u.get("prompt_tokens"), "completion": u.get("completion_tokens"), "cache_read": cached, "cache_write": None}
121
+
122
+
123
+ def _anthropic_usage(u: dict) -> dict:
124
+ """prompt = fresh input + cache reads + cache writes, so it is comparable to the estimate of the WHOLE request."""
125
+ if not u:
126
+ return {"prompt": None, "completion": None, "cache_read": None, "cache_write": None}
127
+ rd, wr = u.get("cache_read_input_tokens") or 0, u.get("cache_creation_input_tokens") or 0
128
+ inp = u.get("input_tokens")
129
+ return {"prompt": (inp + rd + wr) if isinstance(inp, int) else None, "completion": u.get("output_tokens"),
130
+ "cache_read": rd, "cache_write": wr}
131
+
132
+
133
+ class StreamState:
134
+ """Accumulates assistant text and usage from SSE events (OpenAI deltas or Anthropic typed events)."""
135
+
136
+ def __init__(self, kind: str) -> None:
137
+ self.kind, self.text, self.usage = kind, [], {}
138
+
139
+ def feed(self, line: bytes) -> None:
140
+ if not line.startswith(b"data:") or b"[DONE]" in line:
141
+ return
142
+ try:
143
+ ev = json.loads(line[5:].decode("utf-8", "replace"))
144
+ except ValueError:
145
+ return
146
+ if not isinstance(ev, dict):
147
+ return
148
+ if self.kind == "anthropic":
149
+ t = ev.get("type")
150
+ if t == "message_start":
151
+ self.usage = {**self.usage, **((ev.get("message") or {}).get("usage") or {})}
152
+ elif t == "message_delta":
153
+ self.usage = {**self.usage, **(ev.get("usage") or {})}
154
+ elif t == "content_block_delta" and (ev.get("delta") or {}).get("type") == "text_delta":
155
+ self.text.append(ev["delta"].get("text") or "")
156
+ else:
157
+ if isinstance(ev.get("usage"), dict):
158
+ self.usage = ev["usage"]
159
+ choice = (ev.get("choices") or [{}])[0] if isinstance(ev.get("choices"), list) and ev.get("choices") else {}
160
+ delta = (choice.get("delta") or {}).get("content")
161
+ if isinstance(delta, str):
162
+ self.text.append(delta)
163
+
164
+ def result(self) -> tuple[str, dict]:
165
+ return "".join(self.text), (_anthropic_usage(self.usage) if self.kind == "anthropic" else _openai_usage(self.usage))
166
+
167
+
168
+ class BadRequest(Exception):
169
+ pass
170
+
171
+
172
+ def _read_request_body(handler: BaseHTTPRequestHandler, limit: int) -> bytes | None:
173
+ """Body bytes, None if over `limit`; raises BadRequest on malformed framing."""
174
+ te = (handler.headers.get("Transfer-Encoding") or "").lower()
175
+ if te and handler.headers.get("Content-Length") is not None:
176
+ raise BadRequest("both Transfer-Encoding and Content-Length") # request-smuggling shape
177
+ if "chunked" in te:
178
+ data = b""
179
+ while True:
180
+ line = handler.rfile.readline(1024)
181
+ try:
182
+ size = int(line.split(b";")[0].strip(), 16)
183
+ except ValueError:
184
+ raise BadRequest("bad chunk size") from None
185
+ if size < 0:
186
+ raise BadRequest("bad chunk size")
187
+ if size == 0:
188
+ handler.rfile.readline(1024)
189
+ return data
190
+ if len(data) + size > limit:
191
+ return None # checked BEFORE reading the chunk
192
+ data += handler.rfile.read(size)
193
+ handler.rfile.readline(1024)
194
+ raw = (handler.headers.get("Content-Length") or "0").strip()
195
+ if not raw.isdigit():
196
+ raise BadRequest("bad Content-Length")
197
+ n = int(raw)
198
+ if n > limit:
199
+ return None
200
+ return handler.rfile.read(n) if n else b""
201
+
202
+
203
+ def _valid_target(path: str) -> bool:
204
+ """Origin-form only (no absolute URL / authority), no CR/LF/NUL, no dot-segments (also percent-encoded)."""
205
+ if not path.startswith("/") or path.startswith("//") or any(c in path for c in "\r\n\0\\"):
206
+ return False
207
+ p = urllib.parse.unquote(urllib.parse.urlsplit(path).path)
208
+ return ".." not in p.split("/") and "\\" not in p and "\0" not in p
209
+
210
+
211
+ def make_server(host: str, port: int, cfg: Config) -> ThreadingHTTPServer:
212
+ class Handler(BaseHTTPRequestHandler):
213
+ server_version = f"nlp-smarty-gateway/{__version__}"
214
+ timeout = 60 # client socket read timeout: a stalled/slow-loris client cannot pin a thread forever
215
+
216
+ def log_message(self, fmt: str, *args: Any) -> None: # request lines only, never bodies or headers
217
+ if cfg.verbose:
218
+ sys.stderr.write("[gateway] " + (fmt % args).replace("\r", "?").replace("\n", "?")[:300] + "\n")
219
+
220
+ # every verb goes through the same relay
221
+ def do_GET(self) -> None: self._handle()
222
+ def do_POST(self) -> None: self._handle()
223
+ def do_PUT(self) -> None: self._handle()
224
+ def do_PATCH(self) -> None: self._handle()
225
+ def do_DELETE(self) -> None: self._handle()
226
+ def do_OPTIONS(self) -> None: self._handle()
227
+
228
+ def _send_error_json(self, status: int, message: str, kind: str) -> None:
229
+ body = json.dumps({"error": {"message": message, "type": kind}}).encode()
230
+ self.send_response(status)
231
+ self.send_header("Content-Type", "application/json")
232
+ self.send_header("Content-Length", str(len(body)))
233
+ self.end_headers()
234
+ self.wfile.write(body)
235
+
236
+ def _handle(self) -> None:
237
+ t_req = time.perf_counter()
238
+ if not _valid_target(self.path):
239
+ self.close_connection = True
240
+ return self._send_error_json(400, "invalid request target", "contextgate_bad_request")
241
+ try:
242
+ raw = _read_request_body(self, cfg.max_body) if self.command in ("POST", "PUT", "PATCH") else b""
243
+ except (BadRequest, OSError):
244
+ self.close_connection = True
245
+ return self._send_error_json(400, "malformed request framing", "contextgate_bad_request")
246
+ if raw is None:
247
+ self.close_connection = True
248
+ return self._send_error_json(413, "request body too large", "contextgate_request_too_large")
249
+ path = self.path
250
+ kind = route_kind(self.command, path)
251
+ original: dict | None = None
252
+ forward_body, res, error = raw, None, ""
253
+ if kind:
254
+ try:
255
+ parsed = json.loads(raw.decode("utf-8"))
256
+ original = parsed if isinstance(parsed, dict) else None
257
+ except (ValueError, UnicodeDecodeError, RecursionError):
258
+ original = None
259
+ if original is not None:
260
+ try:
261
+ res = gate.gate_request(original, cfg.profile, kind)
262
+ send = res.body
263
+ if kind == "openai" and cfg.force_usage and original.get("stream") and "stream_options" not in send:
264
+ send = {**send, "stream_options": {"include_usage": True}}
265
+ if res.applied or send is not res.body:
266
+ forward_body = json.dumps(send, ensure_ascii=False).encode("utf-8")
267
+ error = res.error
268
+ if cfg.record_path:
269
+ self._record(original)
270
+ except Exception as exc: # fail open: forward exactly what we received
271
+ res, forward_body, error = None, raw, f"{type(exc).__name__}"
272
+ gate_ms = (time.perf_counter() - t_req) * 1000
273
+ self._relay(path, forward_body, original, res, gate_ms, error, kind)
274
+
275
+ def _record(self, body: dict) -> None:
276
+ fd = os.open(cfg.record_path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
277
+ try:
278
+ os.fchmod(fd, 0o600) # tighten a pre-existing, looser file too
279
+ except (AttributeError, OSError):
280
+ pass
281
+ with os.fdopen(fd, "a", encoding="utf-8") as f:
282
+ f.write(json.dumps({"ts": time.time(), "body": body}, ensure_ascii=False) + "\n")
283
+
284
+ def _relay(self, path: str, body: bytes, original: dict | None, res: Any, gate_ms: float, error: str, kind: str | None) -> None:
285
+ headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP_BY_HOP | {"host", "content-length", "accept-encoding"}}
286
+ headers["Host"] = cfg.host if cfg.port in (80, 443) else f"{cfg.host}:{cfg.port}"
287
+ headers["Accept-Encoding"] = "identity"
288
+ if body or self.command in ("POST", "PUT", "PATCH"):
289
+ headers["Content-Length"] = str(len(body))
290
+ row = dict(route=urllib.parse.urlsplit(path).path, host=cfg.host, model=(original or {}).get("model"), profile=cfg.profile,
291
+ stream=bool((original or {}).get("stream")), applied=bool(res and res.applied), api=kind,
292
+ raw_tokens=res.raw_tokens if res else None, fwd_tokens=res.fwd_tokens if res else None,
293
+ gate_ms=gate_ms, fallbacks=res.fallbacks if res else 0, protected_ok=res.protected_ok if res else True,
294
+ error=error or None)
295
+ t_up = time.perf_counter()
296
+ conn = None
297
+ try:
298
+ if cfg.scheme == "https":
299
+ conn = http.client.HTTPSConnection(cfg.host, cfg.port, timeout=cfg.timeout, context=ssl.create_default_context())
300
+ else:
301
+ conn = http.client.HTTPConnection(cfg.host, cfg.port, timeout=cfg.timeout)
302
+ conn.request(self.command, cfg.base_path + path, body=body if (body or self.command in ("POST", "PUT", "PATCH")) else None,
303
+ headers=headers)
304
+ resp = conn.getresponse()
305
+ except Exception as exc:
306
+ self._send_error_json(502, f"upstream unreachable: {type(exc).__name__}", "contextgate_upstream_error")
307
+ row.update(status=502, error=f"upstream {type(exc).__name__}", upstream_ms=(time.perf_counter() - t_up) * 1000)
308
+ self._ledger(kind, row)
309
+ if conn:
310
+ conn.close()
311
+ return
312
+ streaming = "text/event-stream" in (resp.getheader("Content-Type") or "").lower()
313
+ self.send_response(resp.status, resp.reason)
314
+ for k, v in resp.getheaders():
315
+ if k.lower() in HOP_BY_HOP or k.lower() == "content-length":
316
+ continue
317
+ self.send_header(k, v)
318
+ if res is not None:
319
+ self.send_header("X-ContextGate-Profile", cfg.profile)
320
+ self.send_header("X-ContextGate-Applied", "1" if res.applied else "0")
321
+ self.send_header("X-ContextGate-Tokens-Saved-Est", str(max(0, res.saved)))
322
+ row["status"] = resp.status
323
+ try:
324
+ text, usage = "", {}
325
+ if streaming:
326
+ self.end_headers()
327
+ st = StreamState(kind or "openai")
328
+ while True:
329
+ line = resp.readline()
330
+ if not line:
331
+ break
332
+ self.wfile.write(line)
333
+ self.wfile.flush()
334
+ if kind:
335
+ st.feed(line)
336
+ text, usage = st.result()
337
+ else:
338
+ data = resp.read()
339
+ self.send_header("Content-Length", str(len(data)))
340
+ self.end_headers()
341
+ self.wfile.write(data)
342
+ enc = (resp.getheader("Content-Encoding") or "").lower()
343
+ if kind and resp.status == 200 and enc in ("", "identity", "gzip"):
344
+ try:
345
+ payload = json.loads((gzip.decompress(data) if enc == "gzip" else data).decode("utf-8"))
346
+ text, usage = parse_response(kind, payload)
347
+ except (ValueError, OSError, UnicodeDecodeError):
348
+ pass
349
+ row["upstream_ms"] = (time.perf_counter() - t_up) * 1000
350
+ row["up_prompt_tokens"], row["up_completion_tokens"] = usage.get("prompt"), usage.get("completion")
351
+ row["up_cache_read_tokens"], row["up_cache_write_tokens"] = usage.get("cache_read"), usage.get("cache_write")
352
+ if cfg.audit and kind and original is not None and resp.status == 200:
353
+ try:
354
+ a = audit_response(original, text, kind)
355
+ if a:
356
+ row.update(audit_score=a["score"], neg_ok=a["neg_ok"], entity_ok=a["entity_ok"])
357
+ except Exception:
358
+ row["error"] = row.get("error") or "AuditError"
359
+ except (BrokenPipeError, ConnectionResetError):
360
+ row["error"] = row.get("error") or "client_disconnected"
361
+ row["upstream_ms"] = (time.perf_counter() - t_up) * 1000
362
+ finally:
363
+ conn.close()
364
+ self._ledger(kind, row)
365
+
366
+ def _ledger(self, kind: str | None, row: dict) -> None:
367
+ if cfg.ledger is not None and kind:
368
+ try:
369
+ cfg.ledger.record(**row)
370
+ except Exception:
371
+ pass
372
+
373
+ srv = ThreadingHTTPServer((host, port), Handler)
374
+ srv.daemon_threads = False # server_close() then WAITS for in-flight requests, so their ledger rows are never lost
375
+ srv.block_on_close = True
376
+ return srv
377
+
378
+
379
+ def serve(host: str, port: int, cfg: Config) -> None:
380
+ if cfg.scheme == "http" and cfg.host not in ("127.0.0.1", "localhost", "::1"):
381
+ print(f"warning: upstream {cfg.upstream} is plain http on a non-loopback host; API keys travel unencrypted", file=sys.stderr)
382
+ srv = make_server(host, port, cfg)
383
+ print(f"gateway listening on http://{host}:{srv.server_address[1]} -> {cfg.upstream} (profile: {cfg.profile}, "
384
+ f"ledger: {cfg.ledger.path if cfg.ledger else 'off'})", file=sys.stderr)
385
+ print(f"OpenAI-compatible: base_url=http://{host}:{srv.server_address[1]}/v1 Anthropic: ANTHROPIC_BASE_URL=http://{host}:{srv.server_address[1]}",
386
+ file=sys.stderr)
387
+
388
+ def _stop(*_: Any) -> None: # SIGTERM (docker stop, systemd, kill) shuts down gracefully like Ctrl-C
389
+ raise KeyboardInterrupt
390
+
391
+ try:
392
+ signal.signal(signal.SIGTERM, _stop)
393
+ except ValueError: # not the main thread (embedded use): the caller owns shutdown
394
+ pass
395
+ try:
396
+ srv.serve_forever()
397
+ except KeyboardInterrupt:
398
+ pass
399
+ finally:
400
+ srv.server_close() # waits for in-flight handler threads
401
+ if cfg.ledger is not None:
402
+ cfg.ledger.close()
403
+
404
+
405
+ def build_parser() -> argparse.ArgumentParser:
406
+ ap = argparse.ArgumentParser(prog="gateway", description="OpenAI-compatible and Anthropic compression gateway")
407
+ ap.add_argument("--upstream", default=os.environ.get("SMARTY_UPSTREAM"), required=not os.environ.get("SMARTY_UPSTREAM"),
408
+ help="upstream base URL, e.g. https://api.openai.com, https://api.anthropic.com or https://router.huggingface.co")
409
+ ap.add_argument("--host", default="127.0.0.1")
410
+ ap.add_argument("--port", type=int, default=8787)
411
+ ap.add_argument("--allow-remote", action="store_true", help="allow binding to a non-loopback address (credentials pass through!)")
412
+ ap.add_argument("--profile", default="strict", choices=sorted(gate.PROFILES))
413
+ ap.add_argument("--ledger", default=lg.DEFAULT_PATH)
414
+ ap.add_argument("--no-ledger", action="store_true")
415
+ ap.add_argument("--record", help="append ORIGINAL request bodies to this JSONL file for offline `bench` (contains your prompts!)")
416
+ ap.add_argument("--force-usage", action="store_true", help="OpenAI only: add stream_options.include_usage to streaming requests")
417
+ ap.add_argument("--no-audit", action="store_true")
418
+ ap.add_argument("--timeout", type=float, default=600.0)
419
+ ap.add_argument("--verbose", action="store_true")
420
+ return ap
421
+
422
+
423
+ def main(argv: list[str] | None = None) -> int:
424
+ a = build_parser().parse_args(argv)
425
+ if a.host not in ("127.0.0.1", "localhost", "::1") and not a.allow_remote:
426
+ print("error: refusing to bind to a non-loopback address without --allow-remote "
427
+ "(the gateway forwards your API credentials)", file=sys.stderr)
428
+ return 2
429
+ try:
430
+ cfg = Config(a.upstream, a.profile, None if a.no_ledger else lg.Ledger(a.ledger), a.record, a.timeout,
431
+ a.force_usage, not a.no_audit, a.verbose)
432
+ except ValueError as exc:
433
+ print(f"error: {exc}", file=sys.stderr)
434
+ return 2
435
+ if a.record:
436
+ print(f"WARNING: recording original request bodies (your prompts) to {a.record}", file=sys.stderr)
437
+ serve(a.host, a.port, cfg)
438
+ return 0
439
+
440
+
441
+ if __name__ == "__main__":
442
+ sys.exit(main())
@@ -0,0 +1,116 @@
1
+ """
2
+ Claude Code `UserPromptSubmit` hook: injects a budgeted <retrieved_context> capsule before Turn 1.
3
+
4
+ stdin : hook JSON {"session_id", "prompt", "cwd", ...}
5
+ stdout: {"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": "..."}} or nothing
6
+ Design rules: fail-open (always exit 0, never block a prompt), stdlib-only fast path (no spaCy/pipeline import),
7
+ session ledger so a symbol is never injected twice, silence below the confidence gate.
8
+
9
+ Register in .claude/settings.json:
10
+ {"hooks": {"UserPromptSubmit": [{"hooks": [{"type": "command", "command": "python3 /abs/path/smarty_hook.py"}]}]}}
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import re
18
+ import sys
19
+ import time
20
+
21
+ os.environ.setdefault("SMARTY_LIGHT_TOKENS", "1") # must precede repo_indexer: skip the heavy BPE estimator import
22
+
23
+ from . import repo_indexer as ri # noqa: E402
24
+
25
+ FIRST_TURN_BUDGET = 450
26
+ FOLLOWUP_BUDGET = 250
27
+ MIN_QUERY_TERMS = 2
28
+ MAX_LEDGER = 200
29
+ LEDGER_TTL_S = 7 * 24 * 3600
30
+
31
+
32
+ def _ledger_path(root: str, session_id: str) -> str:
33
+ sid = re.sub(r"[^A-Za-z0-9_.-]", "_", session_id or "default")[:64]
34
+ d = os.path.join(root, ri.INDEX_DIR, "sessions")
35
+ os.makedirs(d, exist_ok=True)
36
+ return os.path.join(d, f"{sid}.json")
37
+
38
+
39
+ def _load(path: str) -> dict:
40
+ try:
41
+ with open(path) as f:
42
+ data = json.load(f)
43
+ if isinstance(data, dict) and isinstance(data.get("delivered"), list):
44
+ return data
45
+ except (OSError, ValueError):
46
+ pass
47
+ return {"turns": 0, "delivered": []}
48
+
49
+
50
+ def _gc(root: str) -> None:
51
+ d = os.path.join(root, ri.INDEX_DIR, "sessions")
52
+ now = time.time()
53
+ try:
54
+ for fn in os.listdir(d):
55
+ p = os.path.join(d, fn)
56
+ if now - os.path.getmtime(p) > LEDGER_TTL_S:
57
+ os.remove(p)
58
+ except OSError:
59
+ pass
60
+
61
+
62
+ _WRAPPERS = re.compile(r"<(system-reminder|ide_[a-z_]+|command-[a-z-]+)>.*?</\1>", re.S)
63
+
64
+
65
+ def clean_prompt(prompt: str) -> str:
66
+ """Drop harness-injected wrappers (worktree notices, IDE context, ...) so only what the user typed is searched."""
67
+ return _WRAPPERS.sub(" ", prompt).strip()
68
+
69
+
70
+ def process(event: dict) -> dict | None:
71
+ """Return the hook output dict, or None to stay silent."""
72
+ prompt = event.get("prompt")
73
+ if isinstance(prompt, str):
74
+ prompt = clean_prompt(prompt)
75
+ cwd = event.get("cwd") or os.getcwd()
76
+ if not isinstance(prompt, str) or not prompt.strip() or prompt.lstrip().startswith("/"):
77
+ return None
78
+ # project root: explicit override > Claude Code's project dir (cwd may be a subdirectory) > event cwd
79
+ root = os.path.abspath(os.environ.get("SMARTY_ROOT") or os.environ.get("CLAUDE_PROJECT_DIR") or cwd)
80
+ if len(ri.tokenize(prompt, drop_stop=True)) < MIN_QUERY_TERMS:
81
+ return None
82
+
83
+ lp = _ledger_path(root, str(event.get("session_id") or "default"))
84
+ ledger = _load(lp)
85
+ first = ledger["turns"] == 0
86
+ delivered = [tuple(x) for x in ledger["delivered"] if isinstance(x, list) and len(x) == 2]
87
+ out = ri.build_capsule(root, prompt, token_budget=FIRST_TURN_BUDGET if first else FOLLOWUP_BUDGET,
88
+ k=5 if first else 3, exclude=delivered)
89
+ ledger["turns"] += 1
90
+ if out["reason"] == "ok":
91
+ ledger["delivered"] = (ledger["delivered"] + [list(d) for d in out.get("delivered", [])])[-MAX_LEDGER:]
92
+ try:
93
+ with open(lp, "w") as f:
94
+ json.dump(ledger, f)
95
+ if first:
96
+ _gc(root)
97
+ except OSError:
98
+ pass
99
+ if out["reason"] != "ok" or not out["capsule"]:
100
+ return None
101
+ return {"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": out["capsule"]}}
102
+
103
+
104
+ def main() -> int:
105
+ try:
106
+ event = json.loads(sys.stdin.read() or "{}")
107
+ result = process(event if isinstance(event, dict) else {})
108
+ if result:
109
+ sys.stdout.write(json.dumps(result))
110
+ except Exception as exc: # fail-open: a broken hook must never block the user's prompt
111
+ sys.stderr.write(f"[nlp-smarty hook] ignored error: {exc}\n")
112
+ return 0
113
+
114
+
115
+ if __name__ == "__main__":
116
+ sys.exit(main())