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,345 @@
1
+ """
2
+ Persistent JSON-RPC / JSON-Lines Sidecar Bridge for VS Code Extension
3
+ =====================================================================
4
+ Commands supported over stdin/stdout JSON-Lines:
5
+ 1. `"command": "optimize"` -> Runs deterministic 4-stage pipeline (`pipeline.py`)
6
+ 2. `"command": "compare_hf"` -> Runs pipeline + forwards both Raw & Compiled prompts to HuggingFace (`app.py` or built-in HF client)
7
+ 3. `"command": "audit_pair"` -> Deterministically audits Raw vs. Optimized responses generated by VS Code's `vscode.lm`
8
+ 4. `"command": "clear_cache"` -> Clears `PROMPT_CACHE`
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import dataclasses
14
+ import datetime
15
+ import json
16
+ import os
17
+ import re
18
+ import sys
19
+ import time
20
+ import traceback
21
+ import urllib.request
22
+ from typing import Any
23
+
24
+ from .data_contracts import RawRequest, TokenBudget
25
+ from .pipeline import PROMPT_CACHE, audit_agent_response, estimate_tokens, optimize
26
+ from .protocol import (
27
+ E_INTERNAL, E_INVALID_JSON, PROTOCOL_VERSION, ProtocolError,
28
+ capabilities, error_response, validate_request,
29
+ )
30
+
31
+ # Try importing user's custom `app.py` consumer if present; otherwise use built-in HF runner
32
+ try:
33
+ from .downstream import compare_raw_vs_optimized as _external_compare_hf
34
+ except Exception:
35
+ _external_compare_hf = None
36
+
37
+
38
+ DEFAULT_HF_MODEL = os.environ.get("HF_MODEL_ID", "Qwen/Qwen2.5-Coder-32B-Instruct")
39
+
40
+
41
+ def _emit_stderr_audit_log(req_id: str, cmd: str, raw_prompt: str, trace_dict: dict[str, Any]) -> None:
42
+ """
43
+ Writes a structured, human-readable audit log block to sys.stderr (which is
44
+ streamed live into the VS Code 'NLP-Smarty Optimizer' Output Channel). A copy is appended to a FILE only when
45
+ SMARTY_AUDIT_LOG=<path> is set: the block contains previews of the user's prompts, so persisting it to disk
46
+ (and into the extension's install folder, by default) must be an explicit opt-in.
47
+ """
48
+ ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
49
+ raw_preview = raw_prompt if len(raw_prompt) <= 180 else raw_prompt[:180] + "... [truncated in log preview]"
50
+ comp_preview = trace_dict.get("compressed_query_text", "")
51
+ if len(comp_preview) > 180:
52
+ comp_preview = comp_preview[:180] + "... [truncated in log preview]"
53
+
54
+ lines = [
55
+ f"\n================ [ContextGate Audit Log | {ts} | req={req_id} | cmd={cmd}] ================",
56
+ f" RAW PROMPT : {raw_preview!r}",
57
+ f" COMPRESSED CORE : {comp_preview!r}",
58
+ f" INTENT & MODE : {trace_dict.get('detected_intent')} (conf={trace_dict.get('intent_confidence')}, intensity={trace_dict.get('compression_intensity_used')})",
59
+ f" QUERY STATS : {trace_dict.get('raw_token_count')} -> {trace_dict.get('optimized_token_count')} words (-{trace_dict.get('query_token_savings_pct')}%) | est. tokens: {trace_dict.get('raw_bpe_tokens')} -> {trace_dict.get('optimized_bpe_tokens')} toks (-{trace_dict.get('query_bpe_savings_pct')}%)",
60
+ f" CONTEXT MMR : kept chunks {trace_dict.get('kept_context_indices')}/{trace_dict.get('total_context_chunks')} ({trace_dict.get('raw_context_tokens')} -> {trace_dict.get('pruned_context_tokens')} toks, -{trace_dict.get('context_token_savings_pct')}%)",
61
+ f" TOOL SCHEMAS : {trace_dict.get('raw_tools_tokens')} -> {trace_dict.get('compressed_tools_tokens')} toks (saved {trace_dict.get('tool_schema_tokens_saved')} schema toks, injected={trace_dict.get('injected_tool_ids')})",
62
+ f" FEW-SHOT MMR : {trace_dict.get('raw_examples_tokens')} -> {trace_dict.get('selected_examples_tokens')} toks (injected={trace_dict.get('injected_example_ids')})",
63
+ f" TOTAL PAYLOAD : {trace_dict.get('unoptimized_payload_token_count')} -> {trace_dict.get('compiled_payload_token_count')} est. toks vs modeled unpruned template (-{trace_dict.get('payload_token_savings_pct')}%)",
64
+ f" CACHE & LATENCY : hit={trace_dict.get('cache_hit')} ({trace_dict.get('cache_type')}, key={trace_dict.get('cache_key')}) | {trace_dict.get('latency_ms')} ms",
65
+ ]
66
+ for s_log in trace_dict.get("stage_logs") or []:
67
+ lines.append(f" -> {s_log}")
68
+ lines.append("=" * 94)
69
+ block = "\n".join(lines) + "\n"
70
+
71
+ sys.stderr.write(block)
72
+ sys.stderr.flush()
73
+
74
+ log_path = os.environ.get("SMARTY_AUDIT_LOG", "").strip()
75
+ if log_path:
76
+ try:
77
+ with open(os.path.abspath(os.path.expanduser(log_path)), "a", encoding="utf-8") as fh:
78
+ fh.write(block)
79
+ except Exception:
80
+ pass
81
+
82
+
83
+ def _call_hf_or_simulate(prompt_text: str, model_id: str | None = None) -> tuple[str, float, str]:
84
+ """Calls HuggingFace InferenceClient / HTTP Router if HF_TOKEN is set, else deterministic simulator."""
85
+ t0 = time.perf_counter()
86
+ hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN", "")
87
+ target_model = model_id or DEFAULT_HF_MODEL
88
+
89
+ if hf_token:
90
+ try:
91
+ from huggingface_hub import InferenceClient # type: ignore
92
+ client = InferenceClient(model=target_model, token=hf_token)
93
+ res = client.chat_completion(
94
+ messages=[{"role": "user", "content": prompt_text}],
95
+ max_tokens=350,
96
+ temperature=0.1,
97
+ )
98
+ content = res.choices[0].message.content or ""
99
+ return content.strip(), round((time.perf_counter() - t0) * 1000, 2), f"huggingface_hub ({target_model})"
100
+ except ImportError:
101
+ pass
102
+ except Exception as exc:
103
+ return f"[HF API Error: {exc}]", round((time.perf_counter() - t0) * 1000, 2), f"hf_error ({target_model})"
104
+
105
+ try:
106
+ api_url = f"https://router.huggingface.co/hf-inference/models/{target_model}/v1/chat/completions"
107
+ req_body = json.dumps({
108
+ "model": target_model,
109
+ "messages": [{"role": "user", "content": prompt_text}],
110
+ "max_tokens": 350,
111
+ "temperature": 0.1,
112
+ }).encode("utf-8")
113
+ req = urllib.request.Request(
114
+ api_url,
115
+ data=req_body,
116
+ headers={"Authorization": f"Bearer {hf_token}", "Content-Type": "application/json"},
117
+ method="POST",
118
+ )
119
+ with urllib.request.urlopen(req, timeout=30) as resp:
120
+ data = json.loads(resp.read().decode("utf-8"))
121
+ content = data["choices"][0].message.content
122
+ return content.strip(), round((time.perf_counter() - t0) * 1000, 2), f"hf_http ({target_model})"
123
+ except Exception as exc:
124
+ return f"[HF HTTP Error: {exc}]", round((time.perf_counter() - t0) * 1000, 2), f"hf_http_error ({target_model})"
125
+
126
+ # Offline simulation when HF_TOKEN is not set
127
+ is_compiled = "<agent_instructions>" in prompt_text and "<core_task>" in prompt_text
128
+ if is_compiled:
129
+ out = (
130
+ "```python\n"
131
+ "def reverse_string(s: str) -> str:\n"
132
+ " # Complies with <task_metadata> negation: without using slicing\n"
133
+ " chars = []\n"
134
+ " for i in range(len(s) - 1, -1, -1):\n"
135
+ " chars.append(s[i])\n"
136
+ " return ''.join(chars)\n"
137
+ "```"
138
+ )
139
+ else:
140
+ out = (
141
+ "Here is a Python function to reverse a string:\n"
142
+ "def reverse_string(s):\n"
143
+ " return s[::-1] # Unoptimized prompt often violates negation constraint!"
144
+ )
145
+ return out, round((time.perf_counter() - t0) * 1000, 2), "offline_simulator (set HF_TOKEN for live HF API)"
146
+
147
+
148
+ def _builtin_compare_raw_vs_optimized(request: RawRequest, model_id: str | None = None) -> dict[str, Any]:
149
+ if _external_compare_hf is not None:
150
+ try:
151
+ res = _external_compare_hf(request, model_id=model_id)
152
+ if "trace" in res:
153
+ _emit_stderr_audit_log("compare_hf", "compare_hf", request.text, res["trace"])
154
+ return res
155
+ except Exception:
156
+ pass
157
+
158
+ compiled = optimize(request)
159
+ trace_dict = dataclasses.asdict(compiled.trace)
160
+ _emit_stderr_audit_log("compare_hf", "compare_hf", request.text, trace_dict)
161
+
162
+ if compiled.status != "OK":
163
+ return {
164
+ "status": compiled.status,
165
+ "clarification_request": compiled.clarification_request,
166
+ "trace": trace_dict,
167
+ }
168
+
169
+ raw_parts = []
170
+ if request.conversation_history:
171
+ raw_parts.append(
172
+ "Conversation History:\n"
173
+ + "\n".join(f"{t.get('role', 'user')}: {t.get('content', '')}" for t in request.conversation_history)
174
+ )
175
+ if request.context_chunks:
176
+ raw_parts.append("Context:\n" + "\n\n".join(request.context_chunks))
177
+ raw_parts.append(request.text)
178
+ unoptimized_input = "\n\n".join(raw_parts)
179
+
180
+ raw_answer, raw_llm_ms, backend = _call_hf_or_simulate(unoptimized_input, model_id=model_id)
181
+ opt_answer, opt_llm_ms, _ = _call_hf_or_simulate(compiled.payload, model_id=model_id)
182
+
183
+ return {
184
+ "status": "OK",
185
+ "backend": backend,
186
+ "raw_input_tokens": estimate_tokens(unoptimized_input),
187
+ "optimized_input_tokens": compiled.trace.compiled_payload_token_count,
188
+ "raw_response": raw_answer,
189
+ "raw_llm_latency_ms": raw_llm_ms,
190
+ "raw_audit": audit_agent_response(raw_answer, compiled.trace),
191
+ "optimized_payload": compiled.payload,
192
+ "optimized_response": opt_answer,
193
+ "optimized_llm_latency_ms": opt_llm_ms,
194
+ "optimized_audit": audit_agent_response(opt_answer, compiled.trace),
195
+ "trace": trace_dict,
196
+ }
197
+
198
+
199
+ def chunk_workspace_file(path: str, content: str, max_words_per_chunk: int = 45) -> list[str]:
200
+ """
201
+ Splits a real workspace file (code, markdown, logs, JSON) into semantic chunks
202
+ so Stage 3 MMR selects only the relevant slices of real files.
203
+ """
204
+ if not content or not content.strip():
205
+ return []
206
+
207
+ raw_blocks = re.split(r"\n\s*\n|(?=\n(?:def |class |function |export |interface ))", content)
208
+ chunks: list[str] = []
209
+ current_words: list[str] = []
210
+
211
+ for block in raw_blocks:
212
+ block = block.strip()
213
+ if not block:
214
+ continue
215
+ words = block.split()
216
+ if len(current_words) + len(words) <= max_words_per_chunk:
217
+ current_words.extend(words)
218
+ else:
219
+ if current_words:
220
+ chunks.append(f"[{path}] " + " ".join(current_words))
221
+ current_words = []
222
+ for i in range(0, len(words), max_words_per_chunk):
223
+ slice_words = words[i : i + max_words_per_chunk]
224
+ chunks.append(f"[{path}] " + " ".join(slice_words))
225
+
226
+ if current_words:
227
+ chunks.append(f"[{path}] " + " ".join(current_words))
228
+
229
+ return chunks
230
+
231
+
232
+ def _build_raw_request(req_data: dict[str, Any]) -> RawRequest:
233
+ context_chunks: list[str] = list(req_data.get("context_chunks") or [])
234
+ for wf in req_data.get("workspace_files") or []:
235
+ wf_path = wf.get("path", "workspace_file")
236
+ wf_content = wf.get("content", "")
237
+ context_chunks.extend(chunk_workspace_file(wf_path, wf_content))
238
+
239
+ budget = TokenBudget(
240
+ max_total_tokens=int(req_data.get("max_total_tokens", 512)),
241
+ core_query_budget=int(req_data.get("core_query_budget", 120)),
242
+ context_budget=int(req_data.get("context_budget", 160)),
243
+ history_budget=int(req_data.get("history_budget", 80)),
244
+ tools_budget=int(req_data.get("tools_budget", 60)),
245
+ few_shot_budget=int(req_data.get("few_shot_budget", 90)),
246
+ )
247
+
248
+ return RawRequest(
249
+ text=str(req_data.get("text", "")),
250
+ task_hint=str(req_data.get("task_hint", "")),
251
+ context_chunks=context_chunks,
252
+ conversation_history=list(req_data.get("conversation_history") or []),
253
+ token_budget=budget,
254
+ compression_intensity=str(req_data.get("compression_intensity", "AUTO")),
255
+ enable_cache=bool(req_data.get("enable_cache", True)),
256
+ )
257
+
258
+
259
+ def handle_request(req_data: dict[str, Any]) -> dict[str, Any]:
260
+ req_id = req_data.get("id", "0")
261
+ cmd = req_data.get("command", "optimize")
262
+
263
+ if cmd == "clear_cache":
264
+ PROMPT_CACHE.clear()
265
+ sys.stderr.write(f"[ContextGate Audit Log] Cache cleared (req={req_id})\n")
266
+ sys.stderr.flush()
267
+ return {"id": req_id, "ok": True, "message": "Cache cleared"}
268
+
269
+ if cmd == "ping":
270
+ return {"id": req_id, "ok": True, "message": "pong"}
271
+
272
+ if cmd == "capabilities":
273
+ return {"id": req_id, "ok": True, **capabilities()}
274
+
275
+ raw_req = _build_raw_request(req_data)
276
+
277
+ if cmd == "compare_hf":
278
+ model_id = req_data.get("hf_model_id") or None
279
+ comparison = _builtin_compare_raw_vs_optimized(raw_req, model_id=model_id)
280
+ return {"id": req_id, "ok": True, **comparison}
281
+
282
+ if cmd == "audit_pair":
283
+ compiled = optimize(raw_req, few_shot_k=int(req_data.get("few_shot_k", 2)))
284
+ trace_dict = dataclasses.asdict(compiled.trace)
285
+ _emit_stderr_audit_log(req_id, "audit_pair", raw_req.text, trace_dict)
286
+ raw_resp = str(req_data.get("raw_response", ""))
287
+ opt_resp = str(req_data.get("optimized_response", ""))
288
+ return {
289
+ "id": req_id,
290
+ "ok": True,
291
+ "raw_audit": audit_agent_response(raw_resp, compiled.trace),
292
+ "optimized_audit": audit_agent_response(opt_resp, compiled.trace),
293
+ "trace": trace_dict,
294
+ }
295
+
296
+ compiled = optimize(raw_req, few_shot_k=int(req_data.get("few_shot_k", 2)))
297
+ trace_dict = dataclasses.asdict(compiled.trace)
298
+ _emit_stderr_audit_log(req_id, "optimize", raw_req.text, trace_dict)
299
+
300
+ return {
301
+ "id": req_id,
302
+ "ok": True,
303
+ "status": compiled.status,
304
+ "clarification_request": compiled.clarification_request,
305
+ "payload": compiled.payload,
306
+ "trace": trace_dict,
307
+ }
308
+
309
+
310
+ def process_line(line: str) -> dict[str, Any]:
311
+ """Parse, validate and dispatch one JSON-Lines request; never raises."""
312
+ req_id: Any = "unknown"
313
+ try:
314
+ try:
315
+ payload = json.loads(line)
316
+ except json.JSONDecodeError as exc:
317
+ raise ProtocolError(E_INVALID_JSON, f"invalid JSON: {exc}")
318
+ if isinstance(payload, dict):
319
+ req_id = payload.get("id", "unknown")
320
+ validate_request(payload)
321
+ response = handle_request(payload)
322
+ response.setdefault("protocol_version", PROTOCOL_VERSION)
323
+ return response
324
+ except ProtocolError as exc:
325
+ return error_response(req_id, exc.code, exc.message)
326
+ except Exception as exc:
327
+ sys.stderr.write(f"[ContextGate ERROR | req={req_id}] {exc}\n{traceback.format_exc()}\n")
328
+ sys.stderr.flush()
329
+ return error_response(req_id, E_INTERNAL, str(exc), traceback=traceback.format_exc())
330
+
331
+
332
+ def main() -> None:
333
+ sys.stdout.write(json.dumps({"id": "init", "ok": True, "status": "READY", "protocol_version": PROTOCOL_VERSION}) + "\n")
334
+ sys.stdout.flush()
335
+
336
+ for line in sys.stdin:
337
+ line = line.strip()
338
+ if not line:
339
+ continue
340
+ sys.stdout.write(json.dumps(process_line(line)) + "\n")
341
+ sys.stdout.flush()
342
+
343
+
344
+ if __name__ == "__main__":
345
+ main()