-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.py
More file actions
1663 lines (1452 loc) · 67 KB
/
Copy pathproxy.py
File metadata and controls
1663 lines (1452 loc) · 67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
OpenAI-compatible proxy for Hermes → opencode-go.
Handles x-opencode-session header injection so Hermes can use provider: custom.
Compresses tool results and compressible content before forwarding upstream.
Env:
UPSTREAM_URL — opencode-go endpoint (default: https://opencode.ai/zen/go/v1)
UPSTREAM_KEY — API key for upstream
PROXY_PORT — port (default: 8787)
SESSION_ID — fixed x-opencode-session value (default: sha256 of UPSTREAM_KEY)
VERBOSE — logging (default: true)
COMPRESS — enable compression (default: true)
"""
import os
import hashlib
from collections import Counter
import re
import json
import time
import sqlite3
import logging
import threading
import asyncio
import uuid
from collections import deque
from contextlib import asynccontextmanager
from dotenv import load_dotenv
load_dotenv()
import httpx
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse, Response, JSONResponse
# ─── Config ────────────────────────────────────────────────────────────────────
UPSTREAM_URL = os.getenv("UPSTREAM_URL", "https://opencode.ai/zen/go/v1").rstrip("/")
UPSTREAM_KEY = os.getenv("UPSTREAM_KEY", "")
PROXY_PORT = int(os.getenv("PROXY_PORT", "8787"))
VERBOSE = os.getenv("VERBOSE", "true").lower() == "true"
COMPRESS_ENABLED = os.getenv("COMPRESS", "true").lower() == "true"
# Turn-of-conversation before which tool results are treated as deep history
# and compressed hard (ratio 0.15 vs normal 0.50). 0 disables.
AGE_SPLIT_TURNS = int(os.getenv("AGE_SPLIT_TURNS", "4"))
# Fix #5: Use SHA256 instead of MD5 for SESSION_ID
SESSION_ID = os.getenv("SESSION_ID", "")
if not SESSION_ID and UPSTREAM_KEY:
SESSION_ID = hashlib.sha256(UPSTREAM_KEY.encode()).hexdigest()[:16]
elif not SESSION_ID:
SESSION_ID = "opencode-tk-proxy"
# ─── Recovery Store (SQLite) ─────────────────────────────────────────────────
_RECOVERY_DB = "/tmp/opencode-tk-proxy-recovery.db"
_recovery_local = threading.local()
def _get_recovery_conn() -> sqlite3.Connection:
"""Thread-safe SQLite connection for recovery store."""
if not hasattr(_recovery_local, "conn") or _recovery_local.conn is None:
conn = sqlite3.connect(_RECOVERY_DB, timeout=5)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("""
CREATE TABLE IF NOT EXISTS originals (
id TEXT PRIMARY KEY,
content BLOB NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.execute("CREATE INDEX IF NOT EXISTS idx_created ON originals(created_at)")
conn.commit()
_recovery_local.conn = conn
return _recovery_local.conn
def _recovery_store(content: str) -> str:
"""Store original content, return handle like 'ccr_<8hex>'."""
if not content:
return ""
content_bytes = content.encode("utf-8")
content_hash = hashlib.sha256(content_bytes).hexdigest()[:16]
handle = f"ccr_{content_hash[:8]}"
try:
conn = _get_recovery_conn()
conn.execute(
"INSERT OR REPLACE INTO originals (id, content, created_at) VALUES (?, ?, ?)",
(handle, content_bytes, time.strftime("%Y-%m-%d %H:%M:%S")),
)
conn.commit()
except Exception as e:
log.warning("Recovery store failed: %s", e)
return handle
def _recovery_get(handle: str) -> str | None:
"""Retrieve original content by handle."""
try:
conn = _get_recovery_conn()
row = conn.execute("SELECT content FROM originals WHERE id = ?", (handle,)).fetchone()
return row[0].decode("utf-8") if row else None
except Exception as e:
log.warning("Recovery get failed: %s", e)
return None
def _recovery_cleanup():
"""Delete entries older than 1 hour."""
try:
conn = _get_recovery_conn()
cutoff = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time() - 3600))
deleted = conn.execute("DELETE FROM originals WHERE created_at < ?", (cutoff,)).rowcount
conn.commit()
if deleted:
log.debug("Recovery cleanup: deleted %d old entries", deleted)
except Exception as e:
log.warning("Recovery cleanup failed: %s", e)
def _recovery_stats() -> dict:
"""Return recovery store stats."""
try:
conn = _get_recovery_conn()
row = conn.execute("SELECT COUNT(*) FROM originals").fetchone()
total = row[0] if row else 0
total_size = conn.execute("SELECT COALESCE(SUM(LENGTH(content)), 0) FROM originals").fetchone()[0]
return {"entries": total, "total_size_bytes": total_size}
except Exception:
return {"entries": 0, "total_size_bytes": 0}
# ─── Stats tracking ──────────────────────────────────────────────────────────
REQUEST_STATS: deque[dict] = deque(maxlen=100)
# ── Token estimation (best-effort, local) ────────────────────────────────────
_TOKEN_ENC = None
def _get_encoder():
"""Lazily load tiktoken o200k encoder; returns None if unavailable."""
global _TOKEN_ENC
if _TOKEN_ENC is None:
try:
import tiktoken
_TOKEN_ENC = tiktoken.get_encoding("o200k_base")
except Exception:
_TOKEN_ENC = False
return _TOKEN_ENC or None
def _estimate_tokens(text: str) -> int:
"""Estimate token count: tiktoken o200k when available, else chars/4 heuristic."""
if not text:
return 0
enc = _get_encoder()
if enc is None:
return max(1, len(text) // 4)
try:
return len(enc.encode(text))
except Exception:
return max(1, len(text) // 4)
def _find_entry(req_id: str) -> dict | None:
"""Find a stats entry by its request id (stats deque is small)."""
for e in REQUEST_STATS:
if e.get("req_id") == req_id:
return e
return None
async def _backfill_token_stats(req_id: str, original: bytes, compressed: bytes):
"""Compute pre/post-compression token estimates off the event loop,
then attach them to the request's stats entry."""
try:
orig_tok = await asyncio.to_thread(_estimate_tokens, original.decode("utf-8", errors="replace"))
comp_tok = await asyncio.to_thread(_estimate_tokens, compressed.decode("utf-8", errors="replace"))
except Exception:
return
entry = _find_entry(req_id)
if entry is not None:
entry["tokens_est_original"] = orig_tok
entry["tokens_est_compressed"] = comp_tok
entry["tokens_est_saved"] = orig_tok - comp_tok
entry["tokens_est_method"] = "tiktoken" if _get_encoder() is not None else "chars4"
logging.basicConfig(
level=logging.DEBUG if VERBOSE else logging.INFO,
format="%(asctime)s %(levelname)s %(message)s"
)
log = logging.getLogger("opencode-tk-proxy")
def _extract_query(payload: dict) -> str | None:
"""Latest user text from Chat/Responses input for query-aware compression."""
sequences = [payload.get("messages"), payload.get("input")]
for items in sequences:
if isinstance(items, str) and len(items) >= 20:
return items[:500]
if not isinstance(items, list):
continue
for item in reversed(items):
if not isinstance(item, dict) or item.get("role") != "user":
continue
content = item.get("content")
if isinstance(content, str) and len(content) >= 20:
return content[:500]
if isinstance(content, list):
text = " ".join(
p.get("text", "") for p in content
if isinstance(p, dict) and p.get("type") in ("text", "input_text")
)
if len(text) >= 20:
return text[:500]
return None
def _canonical_path(path: str) -> str:
"""Normalize a routed API path without changing its upstream endpoint name."""
return path.rstrip("/")
def _upstream_url(path: str, query: str = "") -> str:
"""Join an upstream base and API path without duplicating the /v1 prefix."""
base = UPSTREAM_URL.rstrip("/")
if base.endswith("/v1") and (path == "v1" or path.startswith("v1/")):
base = base[:-3]
url = f"{base}/{path}"
return f"{url}?{query}" if query else url
def _compress_recoverable_text(text: str, role: str, query: str | None = None,
msg_age: int = 0,
recovery_handles: list[str] | None = None) -> tuple[str, int]:
"""Compress text and record its recovery handle outside the model prompt."""
if not text or len(text) <= 200:
return text, 0
label = _classify_message(text, role)
if label != "compressible" and not (role == "tool" and _maybe_json_content(text)):
return text, 0
compressed = _compress_for_role(text, role, query, msg_age)
if len(compressed) >= len(text):
return text, 0
handle = _recovery_store(text)
if recovery_handles is not None:
recovery_handles.append(handle)
return compressed, len(text) - len(compressed)
# ─── Classifier (inlined from context-bridge/classifier.py) ───────────────────
_CODE_PATTERNS = [
re.compile(r"```"), # code blocks
re.compile(r"^\s*\{"), # JSON objects
re.compile(r"^\s*\["), # JSON arrays
re.compile(r"Traceback\s+\(most recent"), # stack traces
re.compile(r"Error:\s"), # error messages
re.compile(r"^\s*def\s+\w+\("), # Python function defs
re.compile(r"^\s*class\s+\w+"), # class definitions
re.compile(r"^\s*(import|from)\s+\w+"), # imports
re.compile(r"tool_use_id"), # tool identifiers
re.compile(r'"type"\s*:\s*"function"'), # tool schemas
re.compile(r'"parameters"\s*:\s*\{'), # JSON schema
re.compile(r"<thinking>"), # thinking blocks
re.compile(r"^\s*curl\s"), # curl commands
re.compile(r"HTTP/\d"), # HTTP responses
]
def _is_verbatim(content: str) -> bool:
"""Check if content contains code/JSON/structured data that must not be altered."""
if not content or len(content) < 50:
return True
for pat in _CODE_PATTERNS:
if pat.search(content):
return True
return False
def _classify_message(content: str, role: str, has_tool_calls: bool = False) -> str:
"""Classify a message: 'verbatim' or 'compressible'."""
if not content:
return "verbatim"
if has_tool_calls:
return "verbatim"
if role == "tool":
if _is_verbatim(content):
return "verbatim"
return "compressible"
if role == "system":
return "compressible"
if _is_verbatim(content):
return "verbatim"
return "compressible"
# ─── Compressor (inlined from context-bridge/compressor.py) ────────────────────
def _compress_text(text: str, ratio: float = 0.50) -> str:
"""Compress text by removing duplicate lines and collapsing whitespace.
Never truncates: no line or paragraph is dropped positionally, so an
important middle section survives. `ratio` is kept for call-site
compatibility and no longer caps the result.
"""
if not text or len(text) < 100:
return text
# Step 1: remove exact duplicate lines (preserving order)
lines = text.split("\n")
seen = set()
deduped = []
for line in lines:
stripped = line.strip()
if not stripped:
deduped.append(line)
continue
if stripped not in seen:
seen.add(stripped)
deduped.append(line)
text = "\n".join(deduped)
# Step 2: collapse multiple blank lines
text = re.sub(r"\n{3,}", "\n\n", text)
return text
def _compress_tool_result(text: str, ratio: float = 0.50) -> str:
"""Specialized compression for tool results."""
if not text or len(text) < 200:
return text
stripped = text.strip()
if stripped.startswith("{") or stripped.startswith("[") or "```" in text:
return text
return _compress_text(text, ratio)
# ─── Content-type auto-detection ────────────────────────────────────────────
_JSON_RE = re.compile(r"^\s*[\[{]")
_LOG_LEVEL_RE = re.compile(r"\b(?:INFO|WARN(?:ING)?|ERROR|DEBUG|FATAL|CRITICAL|NOTICE|TRACE)\b")
_LOG_TS_RE = re.compile(r"\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?\b")
_DIFF_HEADER_RE = re.compile(r"^@@\s+-\d+.*\+\d+.*\s+@@|^---\s+a/|^\+\+\+\s+b/")
_CODE_FUNC_RE = re.compile(r"^\s*def\s+\w+\s*\(|^\s*class\s+\w+|^\s*(?:import|from)\s+\w+|^\s*async\s+def\s+|^\s*try:|^\s*except\s|^\s*for\s+\w+\s+in\s+|^\s*return\s|^\s*yield\s|^\s*if\s+__name__")
_ANSI_FULL_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]|\x1b\].*?\x07")
_PROGRESS_RE = re.compile(r"\[=>+\-# ]*\s*\d+%|\█|▓|░")
_TOOL_SCHEMA_RE = re.compile(r'"type"\s*:\s*"function"|"parameters"\s*:\s*\{|"properties"\s*:\s*\{|"required"\s*:\s*\[')
_HTML_TAG_RE = re.compile(r"<(?:html|div|table|tr|td|th|p|span|body|head|section|article|header|footer|nav|main|form|input|button|img|a |link |script|style)\b", re.IGNORECASE)
def _detect_content_type(text: str) -> str:
"""Classify content into: json, log, terminal, code, diff, tool_schema, html, text. <1ms."""
if not text:
return "text"
trimmed = text.strip()
# diff: check first (very specific pattern)
if _DIFF_HEADER_RE.search(trimmed[:500]):
return "diff"
# terminal: ANSI codes or progress bars
if _ANSI_FULL_RE.search(trimmed[:2000]) or _PROGRESS_RE.search(trimmed[:2000]):
return "terminal"
# html: has HTML tags
if _HTML_TAG_RE.search(trimmed[:500]):
return "html"
# tool_schema: JSON with function/parameters structure
if _JSON_RE.match(trimmed) and _TOOL_SCHEMA_RE.search(trimmed[:2000]):
return "tool_schema"
# json: starts with { or [, has key:value
if _JSON_RE.match(trimmed) and ('"' in trimmed or ':' in trimmed):
return "json"
# log: timestamps + log levels
sample = trimmed[:4000]
has_ts = bool(_LOG_TS_RE.search(sample))
has_level = bool(_LOG_LEVEL_RE.search(sample))
if has_ts and has_level:
return "log"
# Also: many lines with log levels → log
if has_level:
level_count = len(_LOG_LEVEL_RE.findall(sample))
line_count = sample.count('\n') + 1
if line_count > 3 and level_count / max(line_count, 1) > 0.3:
return "log"
# code: function defs, class defs, imports
code_hits = 0
for line in trimmed.split('\n')[:30]:
if _CODE_FUNC_RE.match(line):
code_hits += 1
if code_hits >= 2:
return "code"
return "text"
# ─── Log compressor ──────────────────────────────────────────────────────────
_LOG_LINE_TS_RE = re.compile(r"^\s*(\d{4}-\d{2}-\d{2})[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?\s*")
_KEEP_LEVEL_RE = re.compile(r"\b(?:ERROR|WARN(?:ING)?|FATAL|CRITICAL|PANIC)\b", re.IGNORECASE)
_DROP_LEVEL_RE = re.compile(r"\b(?:DEBUG|TRACE)\b", re.IGNORECASE)
_PATH_LN_RE = re.compile(r"(/[^\s:]+):(\d+)")
def _compress_log(text: str, ratio: float = 0.40) -> str:
"""Compress log files: drop DEBUG, collapse repeats, keep errors. Never truncates."""
if not text or len(text) < 100:
return text
lines = text.split('\n')
# Step 1: Strip timestamps, drop DEBUG/TRACE lines
kept = []
for line in lines:
stripped = line.strip()
if not stripped:
if kept and kept[-1] != "":
kept.append("")
continue
# Always keep ERROR/WARN/FATAL
is_important = bool(_KEEP_LEVEL_RE.search(stripped))
# Drop DEBUG and TRACE
if _DROP_LEVEL_RE.search(stripped) and not is_important:
continue
# Strip timestamp prefix
stripped = _LOG_LINE_TS_RE.sub("", stripped)
# Truncate long lines (>200 chars), preserving file:line
path_match = _PATH_LN_RE.search(stripped)
if len(stripped) > 200:
prefix = f"[{path_match.group(1)}:{path_match.group(2)}] " if path_match else ""
# Keep first 100 + last 50 chars
stripped = stripped[:100] + f"... [...{len(stripped)} chars total] ..." + stripped[-50:]
if prefix and prefix not in stripped:
stripped = prefix + stripped
kept.append(stripped)
# Step 2: Collapse repeated identical lines
collapsed = []
i = 0
while i < len(kept):
current = kept[i]
if current == "":
collapsed.append(current)
i += 1
continue
count = 1
while i + count < len(kept) and kept[i + count] == current:
count += 1
if count > 1:
collapsed.append(f"{current} [×{count}]")
else:
collapsed.append(current)
i += count
# Step 3: Remove consecutive blank lines
deduped = []
prev_blank = False
for line in collapsed:
if line == "":
if not prev_blank:
deduped.append(line)
prev_blank = True
else:
prev_blank = False
deduped.append(line)
result = "\n".join(deduped).strip()
# No truncation: the whole (deduplicated, noise-filtered) log is kept so
# nothing important is dropped positionally.
return result
# ─── Terminal compressor ──────────────────────────────────────────────────────
# Regex patterns for terminal output
_ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]|\x1b\].*?\x07") # ANSI escape codes
_PROGRESS_BAR_RE = re.compile(r"[\[>=.]\s*\d+%\s*[\]>]|█|▓|░|\r") # progress bars
_SPINNER_RE = re.compile(r"[|/\\-]{2,}\s*") # spinner characters repeated
_DOWNLOAD_RE = re.compile(r"\d+\.\d+\s*(MB|KB|GB|bytes|B)/s") # download speeds
_PERCENT_RE = re.compile(r"\d+%") # standalone percentages
# Noise lines: build output, compilations, etc.
_NOISE_PATTERNS = [
re.compile(r"^\s*Compiling\s+\w+", re.IGNORECASE),
re.compile(r"^\s*Building\s+", re.IGNORECASE),
re.compile(r"^\s*Downloading\s+", re.IGNORECASE),
re.compile(r"^\s*Extracting\s+", re.IGNORECASE),
re.compile(r"^\s*Installing\s+", re.IGNORECASE),
re.compile(r"^\s*Fetching\s+", re.IGNORECASE),
re.compile(r"^\s*Resolving\s+", re.IGNORECASE),
re.compile(r"^\s*Generating\s+", re.IGNORECASE),
re.compile(r"^\s*Processing\s+", re.IGNORECASE),
re.compile(r"^\s*Reading\s+", re.IGNORECASE),
re.compile(r"^\s*Writing\s+", re.IGNORECASE),
re.compile(r"^\s*Copying\s+", re.IGNORECASE),
re.compile(r"^\s*Removing\s+", re.IGNORECASE),
re.compile(r"^\s*Cleaning\s+", re.IGNORECASE),
re.compile(r"^\s*Loading\s+", re.IGNORECASE),
re.compile(r"^\s*Scanning\s+", re.IGNORECASE),
re.compile(r"^\s*Checking\s+", re.IGNORECASE),
re.compile(r"^\s*Verifying\s+", re.IGNORECASE),
re.compile(r"^\s*Computing\s+", re.IGNORECASE),
re.compile(r"^\s*Downloading\s+.*\.\.\.", re.IGNORECASE),
]
# Patterns to ALWAYS keep (errors, warnings, important)
_KEEP_PATTERNS = [
re.compile(r"error[:\s]", re.IGNORECASE),
re.compile(r"warning[:\s]", re.IGNORECASE),
re.compile(r"fatal[:\s]", re.IGNORECASE),
re.compile(r"panic[:\s]", re.IGNORECASE),
re.compile(r"failed", re.IGNORECASE),
re.compile(r"fail\b", re.IGNORECASE),
re.compile(r"exception", re.IGNORECASE),
re.compile(r"traceback", re.IGNORECASE),
re.compile(r"exit\s+code[:\s]", re.IGNORECASE),
re.compile(r"returned\s+\d+", re.IGNORECASE),
re.compile(r"\bPASS\b"),
re.compile(r"\bFAIL\b"),
re.compile(r"\bOK\b"),
re.compile(r"test.*passed", re.IGNORECASE),
re.compile(r"test.*failed", re.IGNORECASE),
re.compile(r"all\s+\d+\s+passed", re.IGNORECASE),
re.compile(r"completed", re.IGNORECASE),
re.compile(r"done\b", re.IGNORECASE),
re.compile(r"finished\b", re.IGNORECASE),
]
# File paths with line numbers (keep for debugging)
_PATH_LINE_RE = re.compile(r"(?:[/\\]\w+[\w./\\-]+)\.\w+:\d+")
def _looks_like_terminal(text: str) -> bool:
"""Check if text contains terminal/shell output indicators."""
# Check for ANSI codes
if _ANSI_RE.search(text):
return True
# Check for progress bars
if re.search(r"\[\s*=>?\s*\d+%", text):
return True
# Check for spinner-like repeated chars
if re.search(r"[|/\\-]{3,}", text):
return True
# Check for download speed patterns
if _DOWNLOAD_RE.search(text):
return True
return False
def _compress_terminal(text: str, ratio: float = 0.50) -> str:
"""Compress terminal/shell output: strip ANSI, remove noise, collapse repeats."""
if not text or len(text) < 100:
return text
# Step 1: Strip ANSI escape codes
cleaned = _ANSI_RE.sub("", text)
# Step 2: Split into lines
lines = cleaned.split("\n")
# Step 3: Remove noise lines and progress bars, keep important ones
important_lines = []
for line in lines:
stripped = line.strip()
# Skip empty lines (but preserve single blank)
if not stripped:
if important_lines and important_lines[-1] != "":
important_lines.append("")
continue
# Skip progress bars
if re.search(r"\[\s*=>?\s*\d+%", stripped):
continue
# Skip lines that are JUST a percentage
if re.match(r"^\s*\d+%\s*$", stripped):
continue
# Skip spinner-like lines
if re.match(r"^[|/\\-]{2,}\s*$", stripped):
continue
# Skip download speed lines
if _DOWNLOAD_RE.search(stripped) and len(stripped) < 60:
continue
# Skip common noise patterns
noise = False
for pat in _NOISE_PATTERNS:
if pat.match(stripped):
noise = True
break
if noise:
continue
# Remove inline \r (carriage return) artifacts
stripped = re.sub(r"\r+", "", stripped)
important_lines.append(stripped)
# Step 4: Collapse repeated identical lines
collapsed = []
i = 0
while i < len(important_lines):
current = important_lines[i]
count = 1
while i + count < len(important_lines) and important_lines[i + count] == current:
count += 1
if count > 1:
collapsed.append(f"{current} [×{count} repeated]")
i += count
else:
collapsed.append(current)
i += 1
# Step 5: Remove consecutive blank lines
result_lines = []
prev_blank = False
for line in collapsed:
if line == "":
if not prev_blank:
result_lines.append(line)
prev_blank = True
else:
prev_blank = False
result_lines.append(line)
result = "\n".join(result_lines).strip()
# Step 6: no truncation — return everything that survived noise filtering
return result
def _compress_system_prompt(text: str, ratio: float = 0.50) -> str:
"""System prompt compression preserving section headers."""
if not text or len(text) < 200:
return text
sections = re.split(r"(?m)^(#{1,3}\s+.+)$", text)
if len(sections) <= 1:
return _compress_text(text, ratio)
result = []
for section in sections:
if re.match(r"^#{1,3}\s+", section):
result.append(section)
else:
result.append(_compress_text(section, ratio))
return "\n".join(result)
# ─── Tool Schema compressor ──────────────────────────────────────────────────
def _compress_schema_obj(obj):
"""Recursively compress a JSON schema object: keep keys/types/structure,
truncate verbose description strings. Used by schema and tools compression."""
if isinstance(obj, dict):
compressed = {}
for k, v in obj.items():
if k == "description" and isinstance(v, str):
# Truncate verbose descriptions to first 100 chars
# Remove code blocks (```...```)
v = re.sub(r"```[\s\S]*?```", "[code example removed]", v)
# Remove inline examples
v = re.sub(r"(?:e\.g\.|example|for example)[^.]*\.", "eg.", v, flags=re.IGNORECASE)
if len(v) > 100:
v = v[:97] + "..."
compressed[k] = v
elif isinstance(v, dict):
compressed[k] = _compress_schema_obj(v)
elif isinstance(v, list):
compressed[k] = _compress_schema_obj(v)
else:
# Keep scalar values (type, name, enum, format, default, etc.)
compressed[k] = v
return compressed
elif isinstance(obj, list):
return [_compress_schema_obj(item) for item in obj]
return obj
def _compress_tools(tools: list) -> tuple[list, int]:
"""Compress an OpenAI tools/functions array: truncate long descriptions,
compress parameter-schema descriptions. Names/types/enums/required preserved.
Returns (new_tools, chars_saved)."""
new_tools = []
saved = 0
for tool in tools:
if not isinstance(tool, dict):
new_tools.append(tool)
continue
function = tool.get("function")
if not isinstance(function, dict):
# Responses API flat format: {type:"function", name, description, parameters}
if tool.get("type") == "function" and isinstance(tool.get("name"), str):
function = tool
else:
new_tools.append(tool)
continue
new_function = dict(function)
desc = function.get("description")
if isinstance(desc, str) and len(desc) > 120:
new_function["description"] = desc[:117] + "..."
saved += len(desc) - len(new_function["description"])
params = function.get("parameters")
if isinstance(params, dict):
before = json.dumps(params, separators=(",", ":"))
new_function["parameters"] = _compress_schema_obj(params)
after = json.dumps(new_function["parameters"], separators=(",", ":"))
if len(after) < len(before):
saved += len(before) - len(after)
if function is tool: # flat Responses format — keep flat
new_tools.append(new_function)
else:
new_tools.append(dict(tool, function=new_function))
return new_tools, saved
# Structural JSON compression for large JSON tool results
_MAX_JSON_STRING_LEN = 600
def _maybe_json_content(text: str) -> bool:
"""True when text is large enough to matter and parses as a JSON doc (dict/list)."""
if not text or len(text) < 1000:
return False
if text.lstrip()[:1] not in ("{", "["):
return False
try:
obj = json.loads(text)
except (json.JSONDecodeError, TypeError, ValueError):
return False
return isinstance(obj, (dict, list))
def _compress_json_obj(obj):
"""Recursively shrink long strings in a parsed JSON value; keep keys/types.
Sorts dict keys → structurally identical tool results re-serialize to the
same bytes → upstream prompt-caching sees a stable token tail."""
if isinstance(obj, dict):
return {k: _compress_json_obj(v) for k, v in sorted(obj.items())}
if isinstance(obj, list):
return [_compress_json_obj(v) for v in obj]
if isinstance(obj, str) and len(obj) > _MAX_JSON_STRING_LEN:
return obj[:450] + f"\n[...truncated: {len(obj)} chars...]" + obj[-150:]
return obj
def _compress_json_content(text: str, ratio: float = 0.50) -> str:
"""Structural JSON compression: preserve all keys/numbers/bools, truncate long strings.
Returns original text when JSON is unparseable or there is no size gain."""
try:
obj = json.loads(text)
except (json.JSONDecodeError, TypeError, ValueError):
return text
if not isinstance(obj, (dict, list)):
return text
try:
result = json.dumps(_compress_json_obj(obj), separators=(",", ":"), ensure_ascii=False)
except Exception:
return text
if len(result) / max(len(text), 1) > ratio:
return text
return result
def _compress_tool_schema(text: str, ratio: float = 0.50) -> str:
"""Compress tool schemas: truncate verbose descriptions, keep structure.
- Truncate verbose tool descriptions to first 100 chars
- Keep function names and parameter names
- Keep required parameters marked
- Remove example code blocks from descriptions
- Keep type information
"""
if not text or len(text) < 100:
return text
original_len = len(text)
target_len = int(original_len * ratio)
# Try to parse as JSON to do structural compression
try:
data = json.loads(text)
except (json.JSONDecodeError, TypeError):
# Not valid JSON — fall back to text compression
return _compress_text(text, ratio)
try:
compressed = _compress_schema_obj(data)
result = json.dumps(compressed, separators=(",", ":"))
except Exception:
return _compress_text(text, ratio)
if len(result) > target_len:
# Truncating JSON as text produces unparseable output; no gain → keep original
return text
return result
# ─── Diff compressor ─────────────────────────────────────────────────────────
_DIFF_HUNK_RE = re.compile(r"^@@\s+(-\d+(?:,\d+)?)\s+\+(\d+(?:,\d+)?)\s+@@")
_DIFF_FILE_RE = re.compile(r"^(---|\+\+\+)\s+[\w/.\-]+")
_DIFF_INDEX_RE = re.compile(r"^index\s+")
_DIFF_MODE_RE = re.compile(r"^(?:old|new)\s+mode\s+\d+")
def _compress_diff(text: str, ratio: float = 0.50) -> str:
"""Compress diffs: keep changed lines, collapse unchanged context.
- Strip diff headers (--- a/, +++ b/, index, mode lines)
- Keep only changed lines (+ and - lines)
- Collapse unchanged context lines
- Keep file paths from headers
- Keep line numbers
"""
if not text or len(text) < 100:
return text
lines = text.split("\n")
output_files = []
current_file = ""
current_hunk_start_new = 0
current_hunk_lines = 0
kept_lines = []
unchanged_count = 0
for line in lines:
# Track file paths from diff headers
file_match = _DIFF_FILE_RE.match(line)
if file_match:
path = file_match.group(1).strip()
# Strip b/ prefix for +++ lines
path = re.sub(r"^b/", "", path)
if line.startswith("+++"):
current_file = path
kept_lines.append(f"--- {current_file}")
else:
current_file = path
kept_lines.append(f"--- {current_file}")
continue
# Skip index and mode lines
if _DIFF_INDEX_RE.match(line):
continue
if _DIFF_MODE_RE.match(line):
continue
# Track hunk headers for line numbers
hunk_match = _DIFF_HUNK_RE.match(line)
if hunk_match:
# Flush accumulated unchanged lines
if unchanged_count > 0:
kept_lines.append(f"... {unchanged_lines}")
unchanged_count = 0
unchanged_lines = 0
current_hunk_start_new = int(hunk_match.group(2).split(",")[0])
current_hunk_lines = 0
continue
# Changed lines (+ or -)
if line.startswith("+") or line.startswith("-"):
# Flush unchanged buffer
if unchanged_count > 0:
kept_lines.append(f"... {unchanged_lines} unchanged lines")
unchanged_count = 0
unchanged_lines = 0
current_hunk_lines += 1
kept_lines.append(line)
continue
# Unchanged context line
unchanged_count += 1
unchanged_lines = unchanged_count
# Flush trailing unchanged buffer
if unchanged_count > 0:
kept_lines.append(f"... {unchanged_lines} unchanged lines")
result = "\n".join(kept_lines).strip()
return result
# ─── HTML compressor ─────────────────────────────────────────────────────────
_HTML_SCRIPT_RE = re.compile(r"<script[\s\S]*?</script>", re.IGNORECASE)
_HTML_STYLE_RE = re.compile(r"<style[\s\S]*?</style>", re.IGNORECASE)
_HTML_TAG_RE2 = re.compile(r"<[^>]+>")
_HTML_ATTR_HREF_RE = re.compile(r'\bhref\s*=\s*"([^"]+)"', re.IGNORECASE)
_HTML_ATTR_SRC_RE = re.compile(r'\bsrc\s*=\s*"([^"]+)"', re.IGNORECASE)
_HTML_ATTR_ALT_RE = re.compile(r'\balt\s*=\s*"([^"]+)"', re.IGNORECASE)
_HTML_WS_RE = re.compile(r"\s+")
_HTML_TABLE_OPEN = re.compile(r"<(?:table|tr|td|th|thead|tbody)\b", re.IGNORECASE)
_HTML_TABLE_CLOSE = re.compile(r"</(?:table|tr|td|th|thead|tbody)\b", re.IGNORECASE)
_HTML_BR_RE = re.compile(r"<br\s*/?>", re.IGNORECASE)
_HTML_P_RE = re.compile(r"<(?:p|div|h[1-6]|li|blockquote)\b[^>]*>", re.IGNORECASE)
def _compress_html(text: str, ratio: float = 0.50) -> str:
"""Compress HTML content: strip tags, keep text, preserve links/images.
- Strip HTML tags, keep text content
- Keep href/src attributes as [link:URL]
- Keep alt text from images
- Strip scripts and styles completely
- Collapse whitespace
- Keep table structure indicators
"""
if not text or len(text) < 100:
return text
original_len = len(text)
target_len = int(original_len * ratio)
result = text
# Step 1: Strip scripts and styles completely
result = _HTML_SCRIPT_RE.sub("", result)
result = _HTML_STYLE_RE.sub("", result)
# Step 2: Extract href/src/alt before stripping tags
links = _HTML_ATTR_HREF_RE.findall(result)
sources = _HTML_ATTR_SRC_RE.findall(result)
alts = _HTML_ATTR_ALT_RE.findall(result)
# Step 3: Replace table tags with indicators
result = _HTML_TABLE_OPEN.sub("\n", result)
result = _HTML_TABLE_CLOSE.sub("\n", result)
result = _HTML_BR_RE.sub("\n", result)
result = _HTML_P_RE.sub("\n", result)
# Step 4: Strip all remaining HTML tags
result = _HTML_TAG_RE2.sub("", result)
# Step 5: Add link/image indicators
link_parts = []
for url in links[:20]: # limit to first 20
link_parts.append(f"[link:{url}]")
for src in sources[:10]: # limit to first 10
link_parts.append(f"[src:{src}]")
for alt in alts[:10]: # limit to first 10
link_parts.append(f"[alt:{alt}]")
if link_parts:
result = result + "\n" + " ".join(link_parts)
# Step 6: Collapse whitespace
result = _HTML_WS_RE.sub(" ", result)
result = re.sub(r"\n{3,}", "\n\n", result)
result = result.strip()
return result
# ─── Query-aware compression ──────────────────────────────────────────────────
def _compress_aware(text: str, query: str) -> str:
"""Query-aware compression: keep lines/sections matching query terms.
Falls back to regular compression if no query or text is small."""
if not query or not text:
return text
if len(text) < 300:
return text
# Extract query keywords (split on whitespace, lowercase, filter short)
keywords = [w.lower().strip('",.:;!?') for w in query.split() if len(w) > 2]
if not keywords:
return _compress_text(text)
lines = text.split("\n")
# Score each line by keyword matches
scored = []
for line in lines:
stripped = line.strip()
if not stripped:
scored.append((line, 0))
continue
lower = stripped.lower()
score = sum(1 for kw in keywords if kw in lower)
scored.append((line, score))
# Keep lines with score > 0, plus first 5 and last 5 lines for context
head_count = min(5, len(lines))
tail_count = min(5, len(lines))
head_indices = set(range(head_count))
tail_indices = set(range(max(0, len(lines) - tail_count), len(lines)))
result_lines = []
kept_relevant = 0
for i, (line, score) in enumerate(scored):
if score > 0 or i in head_indices or i in tail_indices:
result_lines.append(line)
if score > 0:
kept_relevant += 1
elif result_lines and result_lines[-1] != "":
# Add blank separator when skipping content
result_lines.append("")
result = "\n".join(result_lines)
# Collapse multiple blanks
result = re.sub(r"\n{3,}", "\n\n", result).strip()
if kept_relevant == 0:
# No matches found — fall back to regular compression
return _compress_text(text, 0.50)
# Add indicator
result += f"\n[query-aware: {kept_relevant}/{len([s for s in scored if s[1] > 0])} matching lines kept]"
# Final size check — if still too large, apply text compression