ctxtrim 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.
ctxtrim/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """ctxtrim — zero-dependency, deterministic context middleware for coding agents.
2
+
3
+ shrink tool outputs before they hit the context, audit them for prompt
4
+ injection, and prove it with a tamper-evident log.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from .audit import Finding, audit, risk_score
9
+ from .budget import allocate, allocate_pairs
10
+ from .journal import Journal, verify
11
+ from .strategies import CompressResult, Step, compress
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = [
16
+ "allocate",
17
+ "allocate_pairs",
18
+ "audit",
19
+ "compress",
20
+ "verify",
21
+ "CompressResult",
22
+ "Finding",
23
+ "Journal",
24
+ "Step",
25
+ "__version__",
26
+ "risk_score",
27
+ ]
ctxtrim/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """python -m ctxtrim entry point."""
2
+ import sys
3
+
4
+ from .cli import main
5
+
6
+ if __name__ == "__main__":
7
+ sys.exit(main())
ctxtrim/audit.py ADDED
@@ -0,0 +1,110 @@
1
+ """ctxtrim.audit — heuristic scan of untrusted text before it enters an
2
+ agent context: prompt-injection phrasing, hidden Unicode, exfiltration
3
+ commands, credential-looking strings, spoofed system tags.
4
+
5
+ These are *heuristics* to draw human attention, not a security guarantee —
6
+ documented as such. Pure pattern matching, no network, fully deterministic.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from dataclasses import dataclass
12
+ from typing import Any, Dict, List, Pattern
13
+
14
+ SEVERITIES = ("low", "medium", "high")
15
+ _ORDER = {s: i for i, s in enumerate(SEVERITIES)}
16
+
17
+
18
+ @dataclass
19
+ class Finding:
20
+ rule: str
21
+ severity: str
22
+ count: int
23
+ lines: List[int] # 1-based line numbers, first 5
24
+ hint: str
25
+
26
+ def as_dict(self) -> Dict[str, Any]:
27
+ return {"rule": self.rule, "severity": self.severity, "count": self.count,
28
+ "lines": self.lines, "hint": self.hint}
29
+
30
+
31
+ def _line_finder(text: str, pattern: "Pattern[str]") -> List[int]:
32
+ hits: List[int] = []
33
+ for i, ln in enumerate(text.split("\n"), 1):
34
+ if pattern.search(ln):
35
+ hits.append(i)
36
+ if len(hits) >= 5:
37
+ break
38
+ return hits
39
+
40
+
41
+ # rule: (severity, compiled regex, hint)
42
+ _RULES: List[tuple] = [
43
+ ("instruction-override", "high",
44
+ re.compile(r"(?i)\b(?:ignore|disregard|forget|override)\b.{0,48}"
45
+ r"\b(?:previous|prior|above|earlier|all|system|developer)\b"
46
+ r".{0,32}\b(?:instructions?|prompts?|rules?|messages?)\b"),
47
+ "Text asks the model to ignore its instructions — classic prompt injection."),
48
+ ("role-hijack", "high",
49
+ re.compile(r"(?i)(?:you are now|new (?:system )?instructions|"
50
+ r"act as (?:the )?(?:system|root|admin)|"
51
+ r"system\s*(?:prompt|message)\s*:)"),
52
+ "Text attempts to re-define the assistant's role or inject a system prompt."),
53
+ ("spoofed-tag", "high",
54
+ re.compile(r"(?im)^\s*(?:\[?system\]?[:>]|</?system>|<\|im_start\|>|"
55
+ r"<\|(?:system|assistant)\|>|BEGIN SYSTEM MESSAGE)"),
56
+ "Looks like a chat-template/system tag pasted into tool output."),
57
+ ("exfiltration-pipe", "high",
58
+ re.compile(r"(?i)\b(?:curl|wget|Invoke-WebRequest|iwr)\b.{0,80}"
59
+ r"\|\s*(?:\s{0,4})?(?:sudo\s+)?(?:ba)?sh\b|\biex\s*\(\s*"
60
+ r"(?:New-Object|Invoke-WebRequest|\(irm)"),
61
+ "Downloads a script and pipes it straight into a shell."),
62
+ ("destructive-command", "high",
63
+ re.compile(r"(?i)\brm\s+-rf\s+(?:/|~|\$HOME)|\bmkfs\b|\bdd\s+if=[^\s]+\s+of=/dev/"
64
+ r"|\bchmod\s+-R\s+777\s+/\b|\bshutdown\b|\breg\s+add\b.{0,40}HKLM"),
65
+ "Destructive system command present."),
66
+ ("credential-literal", "high",
67
+ re.compile(r"(?i)\b(?:api[_-]?key|secret|token|passwd|password)\b\s*[:=]\s*"
68
+ r"[\"']?[A-Za-z0-9_\-]{16,}\b|"
69
+ r"\b(?:sk-[A-Za-z0-9]{16,}|ghp_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|"
70
+ r"AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,})"),
71
+ "Looks like a live credential — do not let it into an LLM context or logs."),
72
+ ("hidden-unicode", "high",
73
+ re.compile(u"[\u200b\u200c\u200d\u200e\u200f\u202a\u202b\u202c\u202d\u202e\u2060\ufeff]"),
74
+ "Invisible/bidi Unicode can change how models and terminals read text."),
75
+ ("encoded-blob", "medium",
76
+ re.compile(r"[A-Za-z0-9+/=]{200,}"),
77
+ "Long base64-like run; may hide payloads from human review."),
78
+ ("unverified-source-fetch", "medium",
79
+ re.compile(r"(?i)\b(?:curl|wget|irm|iwr)\b\s+(?:-L\s+)?https?://"),
80
+ "Fetches remote content at run time — verify the source before trusting it."),
81
+ ]
82
+
83
+ _MAX_LINE_SCAN = int(5e6) # audit at most ~5 MB of lines for each rule
84
+
85
+
86
+ def audit(text: str, min_severity: str = "low") -> List[Finding]:
87
+ """Scan *text* and return findings sorted by severity (worst first)."""
88
+ if min_severity not in _ORDER:
89
+ raise ValueError("min_severity must be one of {}".format(SEVERITIES))
90
+ if len(text) > _MAX_LINE_SCAN:
91
+ text = text[:_MAX_LINE_SCAN]
92
+ findings: List[Finding] = []
93
+ for name, severity, pattern, hint in _RULES:
94
+ lines = _line_finder(text, pattern)
95
+ if lines:
96
+ findings.append(Finding(rule=name, severity=severity,
97
+ count=len(lines), lines=lines, hint=hint))
98
+ floor = _ORDER[min_severity]
99
+ findings = [f for f in findings if _ORDER[f.severity] >= floor]
100
+ findings.sort(key=lambda f: (-_ORDER[f.severity], f.rule))
101
+ return findings
102
+
103
+
104
+ def risk_score(findings: List[Finding]) -> int:
105
+ """0-100 heuristic risk score. Deterministic; not a guarantee."""
106
+ score = 0
107
+ for f in findings:
108
+ w = {"low": 5, "medium": 15, "high": 30}[f.severity]
109
+ score += w * (1 + (f.count - 1) * 0.25)
110
+ return int(min(100, round(score)))
ctxtrim/budget.py ADDED
@@ -0,0 +1,69 @@
1
+ """ctxtrim.budget — share one context budget across several tool outputs
2
+ fairly and deterministically.
3
+
4
+ Policy: satisfy every item's full need when possible; otherwise give every
5
+ item at least `floor` characters and spread the rest proportionally to need.
6
+ Pure integer math, no RNG, stable output order.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from typing import Dict, List
11
+
12
+ MIN_FLOOR = 200 # never hand an item fewer than this many chars
13
+
14
+
15
+ def allocate(needs: List[int], total: int,
16
+ floor: int = MIN_FLOOR) -> List[int]:
17
+ """Return per-item character budgets that sum to <= total.
18
+
19
+ needs : how many chars each item actually occupies (its "want")
20
+ total : overall budget for the whole batch
21
+ floor : minimum guaranteed per item (clamped into [0, total//n])
22
+ """
23
+ n = len(needs)
24
+ if n == 0:
25
+ return []
26
+ if any(x < 0 for x in needs):
27
+ raise ValueError("needs must be non-negative")
28
+ if total < 0:
29
+ raise ValueError("total must be non-negative")
30
+ floor = max(0, min(floor, total // n if n else 0))
31
+
32
+ needs = [int(x) for x in needs]
33
+ sum_needs = sum(needs)
34
+ if sum_needs <= total:
35
+ return list(needs) # everything fits: no trimming needed
36
+
37
+ # everyone gets the floor first, rest spread proportionally to need
38
+ base = [min(x, floor) for x in needs]
39
+ remaining = total - sum(base)
40
+ want = [max(0, x - b) for x, b in zip(needs, base)]
41
+ sum_want = sum(want)
42
+ if sum_want == 0 or remaining <= 0:
43
+ return base
44
+ out = list(base)
45
+ given = 0
46
+ for i, w in enumerate(want):
47
+ share = (w * remaining) // sum_want # integer, deterministic
48
+ out[i] += share
49
+ given += share
50
+ # hand out the rounding remainder to the largest wants, in stable order
51
+ left = remaining - given
52
+ if left > 0:
53
+ order = sorted(range(n), key=lambda i: (-want[i], i))
54
+ for i in order:
55
+ if left <= 0:
56
+ break
57
+ add = min(left, want[i] - (out[i] - base[i]))
58
+ if add > 0:
59
+ out[i] += add
60
+ left -= add
61
+ return out
62
+
63
+
64
+ def allocate_pairs(names: List[str], needs: List[int], total: int,
65
+ floor: int = MIN_FLOOR) -> Dict[str, int]:
66
+ """Same as allocate() but keyed by item name (names must be unique)."""
67
+ if len(set(names)) != len(names):
68
+ raise ValueError("names must be unique")
69
+ return {name: b for name, b in zip(names, allocate(needs, total, floor))}
ctxtrim/cli.py ADDED
@@ -0,0 +1,189 @@
1
+ """ctxtrim CLI — shrink / audit / verify from the terminal.
2
+
3
+ Exit codes:
4
+ 0 success
5
+ 2 audit found at least one finding at or above --min-severity
6
+ 3 usage / input error
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import hashlib
12
+ import json
13
+ import sys
14
+ from typing import Any, List, Optional
15
+
16
+ from . import __version__
17
+ from .audit import SEVERITIES, audit, risk_score
18
+ from .budget import allocate_pairs
19
+ from .journal import Journal, verify
20
+ from .strategies import compress
21
+
22
+
23
+ def _sha256(data: str) -> str:
24
+ return hashlib.sha256(data.encode("utf-8", "replace")).hexdigest()
25
+
26
+
27
+ def _read(path: str) -> str:
28
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
29
+ return fh.read()
30
+
31
+
32
+ def _cmd_shrink(args: argparse.Namespace) -> int:
33
+ if args.stdin:
34
+ text = sys.stdin.read()
35
+ label = "<stdin>"
36
+ else:
37
+ if not args.path:
38
+ print("error: provide a PATH or --stdin", file=sys.stderr)
39
+ return 3
40
+ text = _read(args.path)
41
+ label = args.path
42
+ res = compress(text, budget=args.budget, profile=args.profile)
43
+ input_sha = _sha256(text)
44
+ output_sha = _sha256(res.text)
45
+ if args.journal:
46
+ Journal(args.journal).append(
47
+ kind="shrink", params={"profile": args.profile, "budget": args.budget},
48
+ input_sha256=input_sha, output_sha256=output_sha,
49
+ extra={"path": label, "ratio": round(res.ratio, 4)})
50
+ if args.json:
51
+ print(json.dumps({
52
+ "path": label,
53
+ "original_chars": res.original_chars,
54
+ "final_chars": res.final_chars,
55
+ "ratio": round(res.ratio, 4),
56
+ "input_sha256": input_sha,
57
+ "output_sha256": output_sha,
58
+ "steps": res.trail(),
59
+ "text": res.text,
60
+ }, ensure_ascii=False, indent=2))
61
+ return 0
62
+ print(res.text)
63
+ print("---", file=sys.stderr)
64
+ print("ctxtrim: {} | steps: {}".format(
65
+ res.summary(), "; ".join(
66
+ "{}: {}->{} ({})".format(s.strategy, s.before, s.after, s.note)
67
+ for s in res.steps)), file=sys.stderr)
68
+ if args.journal:
69
+ print("journal: appended -> {}".format(args.journal), file=sys.stderr)
70
+ return 0
71
+
72
+
73
+ def _cmd_audit(args: argparse.Namespace) -> int:
74
+ if not args.stdin and not args.path:
75
+ print("error: provide a PATH or --stdin", file=sys.stderr)
76
+ return 3
77
+ text = sys.stdin.read() if args.stdin else _read(args.path)
78
+ findings = audit(text, min_severity=args.min_severity)
79
+ score = risk_score(findings)
80
+ if args.json:
81
+ print(json.dumps({
82
+ "path": args.path or "<stdin>",
83
+ "risk_score": score,
84
+ "findings": [f.as_dict() for f in findings],
85
+ }, ensure_ascii=False, indent=2))
86
+ else:
87
+ print("ctxtrim audit: risk score {}/100".format(score))
88
+ if not findings:
89
+ print("no findings (heuristics only — not a guarantee)")
90
+ for f in findings:
91
+ print(" [{}] {} x{} lines={} — {}".format(
92
+ f.severity.upper(), f.rule, f.count,
93
+ ",".join(map(str, f.lines))[:60], f.hint))
94
+ return 2 if any(f.severity == "high" for f in findings) else 0
95
+
96
+
97
+ def _cmd_verify(args: argparse.Namespace) -> int:
98
+ res = verify(args.path)
99
+ if args.json:
100
+ print(json.dumps(res, indent=2))
101
+ else:
102
+ state = "OK" if res["ok"] else "TAMPERED"
103
+ print("journal {}: {} record(s){}".format(
104
+ state, res["records"],
105
+ "" if res["ok"] else " — broken at seq {} ({})".format(
106
+ res["broken_at"], res["reason"])))
107
+ return 0 if res["ok"] else 2
108
+
109
+
110
+ def _cmd_split(args: argparse.Namespace) -> int:
111
+ names = [s.strip() for s in args.names.split(",") if s.strip()]
112
+ if not names:
113
+ print("error: --names must be a comma-separated list", file=sys.stderr)
114
+ return 3
115
+ needs: List[int] = []
116
+ for p in args.need:
117
+ needs.append(len(_read(p)))
118
+ out: Any = allocate_pairs(names, needs, args.total)
119
+ if args.json:
120
+ print(json.dumps(out, indent=2))
121
+ else:
122
+ for k, v in out.items():
123
+ print("{}\t{}".format(k, v))
124
+ return 0
125
+
126
+
127
+ def _cmd_serve(args: argparse.Namespace) -> int:
128
+ from .mcp_server import serve
129
+ return serve()
130
+
131
+
132
+ def build_parser() -> argparse.ArgumentParser:
133
+ p = argparse.ArgumentParser(
134
+ prog="ctxtrim",
135
+ description="Deterministic context middleware: shrink tool outputs, "
136
+ "audit them for prompt injection, prove it with a hash-chained log.")
137
+ p.add_argument("--version", action="version",
138
+ version="ctxtrim {}".format(__version__))
139
+ sub = p.add_subparsers(dest="cmd", required=True)
140
+
141
+ sp = sub.add_parser("shrink", help="compress a tool output / log / JSON")
142
+ sp.add_argument("path", nargs="?", help="input file (omit and use --stdin)")
143
+ sp.add_argument("--stdin", action="store_true", help="read from stdin")
144
+ sp.add_argument("--budget", type=int, default=None,
145
+ help="soft character budget (lossy cut only if needed)")
146
+ sp.add_argument("--profile", choices=["safe", "balanced", "tight"],
147
+ default="balanced")
148
+ sp.add_argument("--json", action="store_true", help="machine-readable report")
149
+ sp.add_argument("--journal", default=None,
150
+ help="append a tamper-evident record to this JSONL journal")
151
+ sp.set_defaults(func=_cmd_shrink)
152
+
153
+ ap = sub.add_parser("audit", help="heuristic prompt-injection / safety scan")
154
+ ap.add_argument("path", nargs="?", help="input file (omit and use --stdin)")
155
+ ap.add_argument("--stdin", action="store_true")
156
+ ap.add_argument("--min-severity", choices=list(SEVERITIES), default="low")
157
+ ap.add_argument("--json", action="store_true")
158
+ ap.set_defaults(func=_cmd_audit)
159
+
160
+ vp = sub.add_parser("verify", help="verify a journal's hash chain")
161
+ vp.add_argument("path")
162
+ vp.add_argument("--json", action="store_true")
163
+ vp.set_defaults(func=_cmd_verify)
164
+
165
+ gp = sub.add_parser("split", help="share one budget across several files")
166
+ gp.add_argument("--names", required=True, help="comma-separated item names")
167
+ gp.add_argument("--need", action="append", required=True,
168
+ help="input file (its length = need); repeat per item")
169
+ gp.add_argument("--total", type=int, required=True, help="total char budget")
170
+ gp.add_argument("--json", action="store_true")
171
+ gp.set_defaults(func=_cmd_split)
172
+
173
+ mp = sub.add_parser("serve", help="run ctxtrim as an MCP server (stdio JSON-RPC)")
174
+ mp.set_defaults(func=_cmd_serve)
175
+ return p
176
+
177
+
178
+ def main(argv: Optional[List[str]] = None) -> int:
179
+ parser = build_parser()
180
+ args = parser.parse_args(argv)
181
+ try:
182
+ return int(args.func(args))
183
+ except (OSError, ValueError) as exc:
184
+ print("error: {}".format(exc), file=sys.stderr)
185
+ return 3
186
+
187
+
188
+ if __name__ == "__main__":
189
+ sys.exit(main())
ctxtrim/journal.py ADDED
@@ -0,0 +1,103 @@
1
+ """ctxtrim.journal — append-only, tamper-evident audit log.
2
+
3
+ Each record is a JSON line whose `hash` covers the record plus the previous
4
+ record's hash (blockchain-style chain). Anyone can later re-verify that no
5
+ record was silently edited or removed, with stdlib only.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ from datetime import datetime, timezone
12
+ from typing import Any, Dict, Optional
13
+
14
+ GENESIS = "0" * 64
15
+
16
+
17
+ def _canon(obj: Dict[str, Any]) -> str:
18
+ return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
19
+
20
+
21
+ def _entry_hash(entry: Dict[str, Any], prev_hash: str) -> str:
22
+ payload = dict(entry)
23
+ payload["prev_hash"] = prev_hash
24
+ return hashlib.sha256(_canon(payload).encode("utf-8")).hexdigest()
25
+
26
+
27
+ class Journal:
28
+ """Append-only JSONL journal with a SHA-256 hash chain."""
29
+
30
+ def __init__(self, path: str) -> None:
31
+ self.path = path
32
+ self._prev: Optional[str] = None
33
+ self._seq = 0
34
+
35
+ def _load_tail(self) -> None:
36
+ """Recompute chain position from the file (idempotent appends)."""
37
+ self._prev = GENESIS
38
+ self._seq = 0
39
+ try:
40
+ with open(self.path, "r", encoding="utf-8") as fh:
41
+ for line in fh:
42
+ line = line.strip()
43
+ if not line:
44
+ continue
45
+ rec = json.loads(line)
46
+ self._seq = int(rec.get("seq", self._seq + 1))
47
+ self._prev = str(rec.get("hash", self._prev))
48
+ except FileNotFoundError:
49
+ pass
50
+
51
+ def append(self, kind: str, params: Optional[Dict[str, Any]] = None,
52
+ input_sha256: str = "", output_sha256: str = "",
53
+ extra: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
54
+ if self._prev is None:
55
+ self._load_tail()
56
+ assert self._prev is not None
57
+ entry: Dict[str, Any] = {
58
+ "seq": self._seq + 1,
59
+ "ts": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
60
+ "kind": kind,
61
+ "input_sha256": input_sha256,
62
+ "output_sha256": output_sha256,
63
+ }
64
+ if params:
65
+ entry["params"] = params
66
+ if extra:
67
+ entry["extra"] = extra
68
+ rec = dict(entry)
69
+ rec["prev_hash"] = self._prev
70
+ rec["hash"] = _entry_hash(entry, self._prev)
71
+ with open(self.path, "a", encoding="utf-8") as fh:
72
+ fh.write(json.dumps(rec, ensure_ascii=False, sort_keys=True,
73
+ separators=(",", ":")) + "\n")
74
+ self._seq += 1
75
+ self._prev = rec["hash"]
76
+ return rec
77
+
78
+
79
+ def verify(path: str) -> Dict[str, Any]:
80
+ """Walk the journal and check the hash chain end-to-end.
81
+
82
+ Returns {"ok": bool, "records": int, "broken_at": seq or None,
83
+ "reason": str or ""}.
84
+ """
85
+ prev = GENESIS
86
+ count = 0
87
+ with open(path, "r", encoding="utf-8") as fh:
88
+ for line in fh:
89
+ line = line.strip()
90
+ if not line:
91
+ continue
92
+ rec = json.loads(line)
93
+ count += 1
94
+ claimed = rec.pop("hash", None)
95
+ expected = _entry_hash(rec, prev)
96
+ if claimed != expected:
97
+ return {"ok": False, "records": count, "broken_at": rec.get("seq"),
98
+ "reason": "hash mismatch (record edited)"}
99
+ if rec.get("prev_hash") != prev:
100
+ return {"ok": False, "records": count, "broken_at": rec.get("seq"),
101
+ "reason": "prev_hash mismatch (record inserted/removed)"}
102
+ prev = claimed
103
+ return {"ok": True, "records": count, "broken_at": None, "reason": ""}
ctxtrim/mcp_server.py ADDED
@@ -0,0 +1,180 @@
1
+ """ctxtrim.mcp_server — expose ctxtrim as an MCP (Model Context Protocol) server.
2
+
3
+ Transport: newline-delimited JSON-RPC 2.0 over stdio, per the MCP spec.
4
+ Run `ctxtrim serve` (or `python -m ctxtrim.serve`) and point any MCP client
5
+ at it. Stdlib only; no network; untrusted tool text never leaves the process
6
+ except as the compressed/audited result the caller asked for.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import sys
13
+ from typing import Any, Dict, List, Optional
14
+
15
+ from . import __version__
16
+ from .audit import audit, risk_score
17
+ from .budget import allocate_pairs
18
+ from .strategies import compress
19
+
20
+ PROTOCOL_VERSION = "2024-11-05"
21
+ SERVER_INFO = {"name": "ctxtrim", "version": __version__}
22
+
23
+ TOOLS = [
24
+ {
25
+ "name": "ctxtrim_shrink",
26
+ "description": ("Deterministically shrink a tool output / log / JSON "
27
+ "text before it enters the agent context. Same input "
28
+ "always yields the same output; per-strategy trail included."),
29
+ "inputSchema": {
30
+ "type": "object",
31
+ "properties": {
32
+ "text": {"type": "string", "description": "content to shrink"},
33
+ "budget": {"type": "integer",
34
+ "description": "soft character budget (lossy cut only if needed)"},
35
+ "profile": {"type": "string",
36
+ "enum": ["safe", "balanced", "tight"], "default": "balanced"},
37
+ },
38
+ "required": ["text"],
39
+ },
40
+ },
41
+ {
42
+ "name": "ctxtrim_audit",
43
+ "description": ("Heuristic scan of untrusted text for prompt injection, "
44
+ "hidden Unicode, exfiltration commands and credential-shaped "
45
+ "strings. Advisory, not a guarantee."),
46
+ "inputSchema": {
47
+ "type": "object",
48
+ "properties": {
49
+ "text": {"type": "string"},
50
+ "min_severity": {"type": "string",
51
+ "enum": ["low", "medium", "high"], "default": "low"},
52
+ },
53
+ "required": ["text"],
54
+ },
55
+ },
56
+ {
57
+ "name": "ctxtrim_split",
58
+ "description": "Share one character budget across several tool outputs.",
59
+ "inputSchema": {
60
+ "type": "object",
61
+ "properties": {
62
+ "items": {"type": "array", "items": {
63
+ "type": "object",
64
+ "properties": {"name": {"type": "string"}, "text": {"type": "string"}},
65
+ "required": ["name", "text"]}},
66
+ "total": {"type": "integer"},
67
+ },
68
+ "required": ["items", "total"],
69
+ },
70
+ },
71
+ ]
72
+
73
+
74
+ def _sha(data: str) -> str:
75
+ return hashlib.sha256(data.encode("utf-8", "replace")).hexdigest()
76
+
77
+
78
+ def _tool_shrink(args: Dict[str, Any]) -> str:
79
+ text = args["text"]
80
+ res = compress(text, budget=args.get("budget"), profile=args.get("profile", "balanced"))
81
+ report = {
82
+ "original_chars": res.original_chars,
83
+ "final_chars": res.final_chars,
84
+ "ratio": round(res.ratio, 4),
85
+ "input_sha256": _sha(text),
86
+ "output_sha256": _sha(res.text),
87
+ "steps": res.trail(),
88
+ "text": res.text,
89
+ }
90
+ return json.dumps(report, ensure_ascii=False)
91
+
92
+
93
+ def _tool_audit(args: Dict[str, Any]) -> str:
94
+ findings = audit(args["text"], min_severity=args.get("min_severity", "low"))
95
+ return json.dumps({
96
+ "risk_score": risk_score(findings),
97
+ "findings": [f.as_dict() for f in findings],
98
+ "note": "heuristics only - not a guarantee",
99
+ }, ensure_ascii=False)
100
+
101
+
102
+ def _tool_split(args: Dict[str, Any]) -> str:
103
+ items = args["items"]
104
+ names = [it["name"] for it in items]
105
+ needs = [len(it["text"]) for it in items]
106
+ return json.dumps(allocate_pairs(names, needs, int(args["total"])),
107
+ ensure_ascii=False)
108
+
109
+
110
+ _HANDLERS = {
111
+ "ctxtrim_shrink": _tool_shrink,
112
+ "ctxtrim_audit": _tool_audit,
113
+ "ctxtrim_split": _tool_split,
114
+ }
115
+
116
+
117
+ def _dispatch(msg: Dict[str, Any]) -> Optional[Dict[str, Any]]:
118
+ """Handle one JSON-RPC message; return a response dict or None (notification)."""
119
+ method = msg.get("method", "")
120
+ msg_id = msg.get("id")
121
+ is_notification = "id" not in msg
122
+
123
+ def ok(result: Any) -> Dict[str, Any]:
124
+ return {"jsonrpc": "2.0", "id": msg_id, "result": result}
125
+
126
+ def err(code: int, message: str) -> Dict[str, Any]:
127
+ return {"jsonrpc": "2.0", "id": msg_id,
128
+ "error": {"code": code, "message": message}}
129
+
130
+ if method == "initialize":
131
+ return ok({
132
+ "protocolVersion": PROTOCOL_VERSION,
133
+ "capabilities": {"tools": {}},
134
+ "serverInfo": SERVER_INFO,
135
+ })
136
+ if method.startswith("notifications/"):
137
+ return None
138
+ if method == "ping":
139
+ return ok({})
140
+ if method == "tools/list":
141
+ return ok({"tools": TOOLS})
142
+ if method == "tools/call":
143
+ params = msg.get("params") or {}
144
+ name = params.get("name", "")
145
+ handler = _HANDLERS.get(name)
146
+ if handler is None:
147
+ return err(-32602, "unknown tool: {}".format(name))
148
+ try:
149
+ text_out = handler(params.get("arguments") or {})
150
+ except (KeyError, TypeError, ValueError) as exc:
151
+ return err(-32602, "invalid arguments: {}".format(exc))
152
+ return ok({"content": [{"type": "text", "text": text_out}]})
153
+ if msg_id is None:
154
+ return None
155
+ return err(-32601, "method not found: {}".format(method))
156
+
157
+
158
+ def serve(stdin=None, stdout=None) -> int:
159
+ """Serve MCP over newline-delimited JSON-RPC on stdio until EOF."""
160
+ fin = stdin if stdin is not None else sys.stdin
161
+ fout = stdout if stdout is not None else sys.stdout
162
+ for line in fin:
163
+ line = line.strip()
164
+ if not line:
165
+ continue
166
+ try:
167
+ msg = json.loads(line)
168
+ except ValueError:
169
+ resp = {"jsonrpc": "2.0", "id": None,
170
+ "error": {"code": -32700, "message": "parse error"}}
171
+ else:
172
+ resp = _dispatch(msg)
173
+ if resp is not None:
174
+ fout.write(json.dumps(resp, ensure_ascii=False) + "\n")
175
+ fout.flush()
176
+ return 0
177
+
178
+
179
+ if __name__ == "__main__":
180
+ sys.exit(serve())
ctxtrim/strategies.py ADDED
@@ -0,0 +1,296 @@
1
+ """ctxtrim.strategies — deterministic, auditable context-shrinking pipeline.
2
+
3
+ Every strategy is a pure function: same input -> same output. No LLM calls,
4
+ no network, no global state. Each strategy reports the characters it saved
5
+ so callers can show an exact, per-rule trail.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import re
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Dict, List, Optional, Pattern, Tuple
14
+
15
+ # ---------------------------------------------------------------- data types
16
+
17
+
18
+ @dataclass
19
+ class Step:
20
+ """One applied strategy and what it saved."""
21
+
22
+ strategy: str
23
+ before: int
24
+ after: int
25
+ note: str = ""
26
+
27
+ def as_dict(self) -> Dict[str, Any]:
28
+ return {"strategy": self.strategy, "before": self.before,
29
+ "after": self.after, "note": self.note}
30
+
31
+
32
+ @dataclass
33
+ class CompressResult:
34
+ """Result of a compress() run."""
35
+
36
+ text: str
37
+ original_chars: int
38
+ steps: List[Step] = field(default_factory=list)
39
+
40
+ @property
41
+ def final_chars(self) -> int:
42
+ return len(self.text)
43
+
44
+ @property
45
+ def ratio(self) -> float:
46
+ """0.0 means nothing saved, 0.9 means 90% saved."""
47
+ if self.original_chars == 0:
48
+ return 0.0
49
+ return 1.0 - self.final_chars / self.original_chars
50
+
51
+ def trail(self) -> List[Dict[str, Any]]:
52
+ return [s.as_dict() for s in self.steps]
53
+
54
+ def summary(self) -> str:
55
+ return ("{} -> {} chars ({:.1%} saved, {} strategies)".format(
56
+ self.original_chars, self.final_chars, self.ratio, len(self.steps)))
57
+
58
+
59
+ Mark = str # elision marker template
60
+
61
+
62
+ def _marker(kind: str, detail: str) -> str:
63
+ return "[ctxtrim {} {}]".format(kind, detail)
64
+
65
+
66
+ def _short_sha(data: str) -> str:
67
+ return hashlib.sha256(data.encode("utf-8", "replace")).hexdigest()[:16]
68
+
69
+
70
+ # ---------------------------------------------------------------- strategies
71
+ # Each strategy: f(text, ctx) -> (text, note or ""). Applied in order; each
72
+ # may inspect ctx["profile"]/ctx["budget"]. All must be deterministic.
73
+
74
+
75
+ # --- 1. blob placeholders: giant base64/hex/data-URI payloads -> digest line
76
+ # threshold kept deliberately high (1200+) to avoid false positives on long
77
+ # URLs / paths / repeated words; data URIs are distinctive at any length.
78
+ _BLOB_RE = re.compile(r"[A-Za-z0-9+/=]{1200,}|[a-fA-F0-9]{1200,}")
79
+ _DATAURI_RE = re.compile(r"data:[a-zA-Z0-9.+-]+/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+")
80
+
81
+
82
+ def _blob_placeholder(text: str, ctx: Dict[str, Any]) -> Tuple[str, str]:
83
+ hits = 0
84
+
85
+ def sub(m: "re.Match[str]") -> str: # type: ignore[name-defined]
86
+ nonlocal hits
87
+ hits += 1
88
+ payload = m.group(0)
89
+ return _marker("blob", "{} chars sha256={}".format(len(payload), _short_sha(payload)))
90
+
91
+ text2 = _DATAURI_RE.sub(sub, text)
92
+ text2 = _BLOB_RE.sub(sub, text2)
93
+ note = "{} blob(s) replaced by sha256 digest".format(hits) if hits else ""
94
+ return text2, note
95
+
96
+
97
+ # --- 2. JSON compaction: drop empty fields, shrink long values/arrays
98
+ _ARRAY_KEEP = 10 # keep first/last N items of long arrays
99
+ _VALUE_TRUNCATE = 1600 # max chars kept of any single string value
100
+
101
+
102
+ def _compact_json(node: Any) -> Tuple[Any, int]:
103
+ """Return (new_node, chars_saved). Deterministic; order preserved."""
104
+ saved = 0
105
+ if isinstance(node, dict):
106
+ out = {}
107
+ for k, v in node.items():
108
+ if v is None or v == "" or v == [] or v == {}:
109
+ saved += len(json.dumps({k: v}, ensure_ascii=False)) - 2
110
+ continue
111
+ nv, s = _compact_json(v)
112
+ saved += s
113
+ out[k] = nv
114
+ return out, saved
115
+ if isinstance(node, list):
116
+ if len(node) > _ARRAY_KEEP * 2:
117
+ head = node[:_ARRAY_KEEP]
118
+ tail = node[-_ARRAY_KEEP:]
119
+ elided = len(node) - _ARRAY_KEEP * 2
120
+ kept_head, s1 = _compact_json(head)
121
+ kept_tail, s2 = _compact_json(tail)
122
+ saved += s1 + s2
123
+ dropped = json.dumps(node, ensure_ascii=False)
124
+ marker_list = [{"ctxtrim_elided": elided}]
125
+ saved += len(dropped) - len(json.dumps(kept_head + marker_list + kept_tail,
126
+ ensure_ascii=False))
127
+ return kept_head + marker_list + kept_tail, saved
128
+ out_items = []
129
+ for item in node:
130
+ ni, s = _compact_json(item)
131
+ saved += s
132
+ out_items.append(ni)
133
+ return out_items, saved
134
+ if isinstance(node, str) and len(node) > _VALUE_TRUNCATE:
135
+ kept = node[:_VALUE_TRUNCATE]
136
+ saved += len(node) - len(kept)
137
+ return kept + _marker("string", "+{} chars sha256={}".format(
138
+ len(node) - _VALUE_TRUNCATE, _short_sha(node))), saved
139
+ return node, saved
140
+
141
+
142
+ def _json_compact(text: str, ctx: Dict[str, Any]) -> Tuple[str, str]:
143
+ stripped = text.strip()
144
+ if not (stripped.startswith("{") or stripped.startswith("[")):
145
+ return text, ""
146
+ try:
147
+ node = json.loads(text)
148
+ except ValueError:
149
+ return text, ""
150
+ compact, saved = _compact_json(node)
151
+ if saved <= 0:
152
+ return text, ""
153
+ out = json.dumps(compact, ensure_ascii=False, separators=(",", ":"))
154
+ return out, "JSON compacted (empty fields dropped, arrays/values trimmed)"
155
+
156
+
157
+ # --- 3. log dedupe: collapse consecutive identical lines
158
+ def _log_dedupe(text: str, ctx: Dict[str, Any]) -> Tuple[str, str]:
159
+ lines = text.split("\n")
160
+ out: List[str] = []
161
+ saved_lines = 0
162
+ i = 0
163
+ n = len(lines)
164
+ while i < n:
165
+ j = i
166
+ while j < n and lines[j] == lines[i]:
167
+ j += 1
168
+ run = j - i
169
+ if run >= 3:
170
+ out.append(lines[i])
171
+ out.append(_marker("repeat", "x{} (lines {}-{})".format(run, i + 1, j)))
172
+ saved_lines += run - 1
173
+ else:
174
+ out.extend(lines[i:j])
175
+ i = j
176
+ if saved_lines == 0:
177
+ return text, ""
178
+ note = "collapsed {} duplicated line(s)".format(saved_lines)
179
+ return "\n".join(out), note
180
+
181
+
182
+ # --- 4. whitespace normalize: trailing spaces, blank runs, common indent
183
+ _BLANK_RUN = re.compile(r"\n{4,}")
184
+
185
+
186
+ def _ws_normalize(text: str, ctx: Dict[str, Any]) -> Tuple[str, str]:
187
+ before = len(text)
188
+ if text.startswith(""):
189
+ text = text[1:]
190
+ lines = [ln.rstrip() for ln in text.split("\n")]
191
+ # dedent common indentation (only when every non-blank line shares it)
192
+ indents = [len(ln) - len(ln.lstrip(" ")) for ln in lines if ln.strip()]
193
+ if len(indents) >= 4 and min(indents) > 0:
194
+ common = min(indents)
195
+ lines = [ln[common:] if ln.strip() else ln for ln in lines]
196
+ out = "\n".join(lines)
197
+ out = _BLANK_RUN.sub("\n\n\n", out)
198
+ after = len(out)
199
+ if before - after <= 0:
200
+ return text, ""
201
+ return out, "normalized whitespace ({} chars)".format(before - after)
202
+
203
+
204
+ # --- 5. diff context collapse: long runs of unchanged diff lines
205
+ def _diff_collapse(text: str, ctx: Dict[str, Any]) -> Tuple[str, str]:
206
+ lines = text.split("\n")
207
+ if not any(ln.startswith(("--- ", "+++ ", "@@")) for ln in lines[:80]):
208
+ return text, ""
209
+ out: List[str] = []
210
+ saved = 0
211
+ run: List[str] = []
212
+
213
+ def flush() -> None:
214
+ nonlocal saved
215
+ if len(run) > 8:
216
+ keep = 3
217
+ elided = len(run) - keep * 2
218
+ out.extend(run[:keep])
219
+ out.append(_marker("diff", "unchanged context, {} lines".format(elided)))
220
+ out.extend(run[-keep:])
221
+ saved += elided
222
+ else:
223
+ out.extend(run)
224
+ run.clear()
225
+
226
+ for ln in lines:
227
+ if ln.startswith(" "):
228
+ run.append(ln)
229
+ else:
230
+ flush()
231
+ out.append(ln)
232
+ flush()
233
+ if saved == 0:
234
+ return text, ""
235
+ return "\n".join(out), "collapsed {} unchanged diff context line(s)".format(saved)
236
+
237
+
238
+ # --- 6. head/tail truncate (lossy; only when a budget is set and still over)
239
+ def _head_tail(text: str, ctx: Dict[str, Any]) -> Tuple[str, str]:
240
+ budget = ctx.get("budget")
241
+ if not budget or len(text) <= budget:
242
+ return text, ""
243
+ keep = max(budget - 64, 0) # room for the marker line
244
+ head = int(keep * 0.7)
245
+ tail = keep - head
246
+ elided = len(text) - keep
247
+ out = (text[:head] + "\n" + _marker("elided", "{} chars (head/tail kept)".format(elided))
248
+ + "\n" + (text[-tail:] if tail else ""))
249
+ return out, "truncated to budget ({} -> {})".format(len(text), len(out))
250
+
251
+
252
+ PROFILES: Dict[str, List[str]] = {
253
+ # "safe": lossless-ish only. "balanced": + diff collapse. "tight": + budget cut.
254
+ "safe": ["blob_placeholder", "json_compact", "log_dedupe", "ws_normalize"],
255
+ "balanced": ["blob_placeholder", "json_compact", "log_dedupe", "ws_normalize",
256
+ "diff_collapse"],
257
+ "tight": ["blob_placeholder", "json_compact", "log_dedupe", "ws_normalize",
258
+ "diff_collapse", "head_tail"],
259
+ }
260
+
261
+ _FUNCS = {
262
+ "blob_placeholder": _blob_placeholder,
263
+ "json_compact": _json_compact,
264
+ "log_dedupe": _log_dedupe,
265
+ "ws_normalize": _ws_normalize,
266
+ "diff_collapse": _diff_collapse,
267
+ "head_tail": _head_tail,
268
+ }
269
+
270
+
271
+ # ---------------------------------------------------------------- public API
272
+
273
+
274
+ def compress(text: str, budget: Optional[int] = None,
275
+ profile: str = "balanced") -> CompressResult:
276
+ """Shrink *text* deterministically.
277
+
278
+ budget : soft character budget; only the final (lossy) strategy may
279
+ cut content, and only if earlier strategies were not enough.
280
+ profile : "safe" | "balanced" | "tight" (see PROFILES).
281
+ """
282
+ if profile not in PROFILES:
283
+ raise ValueError("unknown profile: {} (expected one of {})".format(
284
+ profile, ", ".join(sorted(PROFILES))))
285
+ if budget is not None and budget <= 0:
286
+ raise ValueError("budget must be a positive int")
287
+ ctx: Dict[str, Any] = {"budget": budget}
288
+ result = CompressResult(text=text, original_chars=len(text))
289
+ for name in PROFILES[profile]:
290
+ current = result.text
291
+ new_text, note = _FUNCS[name](current, ctx)
292
+ if new_text != current:
293
+ result.text = new_text
294
+ result.steps.append(Step(strategy=name, before=len(current),
295
+ after=len(new_text), note=note))
296
+ return result
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The ctxtrim Authors
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,222 @@
1
+ Metadata-Version: 2.1
2
+ Name: ctxtrim
3
+ Version: 0.1.0
4
+ Summary: Zero-dependency, deterministic context middleware for coding agents: shrink tool outputs before they hit the context, audit them for prompt injection, and prove it with a tamper-evident log.
5
+ Author: The ctxtrim Authors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/ctxtrim/ctxtrim
8
+ Project-URL: Issues, https://github.com/ctxtrim/ctxtrim/issues
9
+ Keywords: llm,agents,context-window,token,prompt-injection,mcp,claude-code,developer-tools
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Topic :: Text Processing :: Filters
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Provides-Extra: dev
27
+
28
+ # ctxtrim
29
+
30
+ **Shrink tool outputs before they hit your agent's context — deterministically, auditably, with zero dependencies.**
31
+ **在工具输出进入 agent 上下文之前把它瘦身——确定性、可审计、零依赖。**
32
+
33
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
34
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9%2B-blue.svg)](pyproject.toml)
35
+ [![Tests](https://github.com/jsk-hash/ctxtrim/actions/workflows/ci.yml/badge.svg)](.github/workflows/ci.yml)
36
+ [![Dependencies](https://img.shields.io/badge/dependencies-0-success.svg)](pyproject.toml)
37
+
38
+ ![ctxtrim terminal demo](docs/demo.gif)
39
+
40
+ ---
41
+
42
+ ## Why / 为什么
43
+
44
+ Coding agents burn their context window on redundant tool output: 50 repeated
45
+ build lines, 3,000-line unchanged diffs, base64 blobs, pretty-printed JSON.
46
+ That means slower agents, higher bills, and worse answers. Existing tools fix
47
+ this with proxies and runtimes tied to one agent.
48
+
49
+ ctxtrim is the missing **library**: pure functions your tool, MCP server, or
50
+ agent harness calls before handing text to an LLM. Same input → same output,
51
+ every time. Every saved character is accounted for, rule by rule. And because
52
+ tool output is untrusted input, ctxtrim also **audits it** for prompt
53
+ injection and hidden payloads, and keeps a **tamper-evident log** of what
54
+ entered the context.
55
+
56
+ 编码 agent 的上下文窗口被冗余的工具输出吃掉:重复 50 遍的构建日志、3000 行未变更的
57
+ diff、base64 大块、格式化过的 JSON。结果是 agent 更慢、更贵、回答更差。现有方案
58
+ 都是绑定单一 agent 的代理或运行时。
59
+
60
+ ctxtrim 补上缺失的**库**这一层:你的工具、MCP server、agent harness 在把文本交给
61
+ LLM 之前调用它。相同输入必得相同输出,每个字符的去向都有逐条规则留痕。工具输出是
62
+ 不可信输入,ctxtrim 顺带**审计**提示注入与隐藏载荷,并保存**防篡改日志**。
63
+
64
+ ## Quick start / 快速开始
65
+
66
+ ```bash
67
+ pip install ctxtrim # or: pip install git+https://github.com/ctxtrim/ctxtrim
68
+ ```
69
+
70
+ ```bash
71
+ # shrink a tool output (deterministic, rule-by-rule trail on stderr)
72
+ $ ctxtrim shrink build.log --profile balanced
73
+ [... compressed output ...]
74
+ ---
75
+ ctxtrim: 1759 -> 372 chars (78.9% saved, 1 strategies)
76
+
77
+ # respect a hard budget (lossy cut only as a last resort)
78
+ $ ctxtrim shrink huge.json --budget 2000 --profile tight
79
+
80
+ # audit untrusted text before it enters your agent's context
81
+ $ ctxtrim audit untrusted.txt
82
+ ctxtrim audit: risk score 60/100
83
+ [HIGH] instruction-override x1 lines=3 — Text asks the model to ignore its instructions...
84
+
85
+ # share one context budget across several tool outputs
86
+ $ ctxtrim split --names log,db --need build.log --need db.json --total 4000
87
+
88
+ # prove later that nothing was edited
89
+ $ ctxtrim verify journal.jsonl
90
+ journal OK: 3 record(s)
91
+ ```
92
+
93
+ ### MCP server / 作为 MCP 服务器运行
94
+
95
+ `ctxtrim serve` speaks MCP (newline-delimited JSON-RPC over stdio), so any
96
+ MCP client can call ctxtrim as tools — add one block to your client config:
97
+
98
+ ```json
99
+ { "mcpServers": { "ctxtrim": { "command": "ctxtrim", "args": ["serve"] } } }
100
+ ```
101
+
102
+ Tools exposed: `ctxtrim_shrink`, `ctxtrim_audit`, `ctxtrim_split`.
103
+
104
+ ```bash
105
+ # or from source
106
+ python -m ctxtrim.mcp_server
107
+ ```
108
+
109
+ ```python
110
+ from ctxtrim import compress, audit, allocate_pairs, Journal
111
+
112
+ res = compress(tool_output, budget=2000, profile="balanced")
113
+ res.ratio # 0.483 — chars saved
114
+ res.trail() # per-strategy accounting, exactly what ran
115
+ res.text # still valid JSON if the input was JSON
116
+
117
+ findings = audit(untrusted_text) # prompt-injection & payload heuristics
118
+ budgets = allocate_pairs(["log", "db"], [len(a), len(b)], 4000)
119
+
120
+ Journal("journal.jsonl").append(kind="shrink",
121
+ input_sha256=sha256(tool_output),
122
+ output_sha256=sha256(res.text))
123
+ ```
124
+
125
+ ## Benchmarks / 基准
126
+
127
+ `python tools/benchmark.py` (bundled & synthetic workloads, budget=2000):
128
+
129
+ | workload | original | ctxtrim | saved | still parses as JSON |
130
+ |---|---:|---:|---:|---|
131
+ | build_log.txt | 1,759 | 372 | **78.9%** | — |
132
+ | tool_output.json | 3,696 | 1,911 | **48.3%** | ✅ yes |
133
+ | test_runner_output | 58,199 | 40,847 | **29.8%** | — |
134
+ | diff_400ctx | 13,177 | 323 | **97.5%** | — |
135
+
136
+ Deterministic end-to-end; the 67-test suite includes a byte-level determinism check.
137
+
138
+ ## How it works / 工作原理
139
+
140
+ Strategies run in a fixed order; each one is optional and reports its own
141
+ savings. Lossless-ish strategies run always; the lossy head/tail cut runs
142
+ only under a budget, only in the `tight` profile.
143
+
144
+ | # | strategy | what it does | lossy? |
145
+ |---|---|---|---|
146
+ | 1 | blob_placeholder | replaces giant base64/hex runs (>1200 chars) with `[ctxtrim blob N chars sha256=…]` | no* |
147
+ | 2 | json_compact | drops null/empty fields, trims arrays to head-10+tail-10 with an elision marker, truncates giant string values — **output stays valid JSON** | near-lossless |
148
+ | 3 | log_dedupe | collapses runs of ≥3 identical consecutive lines to `line + [ctxtrim repeat xN]` | no |
149
+ | 4 | ws_normalize | strips trailing spaces, collapses blank-line runs, dedents common indent | no |
150
+ | 5 | diff_collapse | collapses >8-line runs of unchanged diff context to 3+marker+3 | no* |
151
+ | 6 | head_tail | cuts to budget keeping 70% head / 30% tail with an elision marker | **yes** |
152
+
153
+ Profiles: `safe` (1–4, never loses content), `balanced` (1–5, default),
154
+ `tight` (1–6, budget-aware).
155
+
156
+ \* elided content is replaced by a SHA-256 digest + exact byte count, so the
157
+ omission is explicit, not silent.
158
+
159
+ ### Audit rules / 审计规则
160
+
161
+ `ctxtrim audit` scans untrusted text with deterministic heuristics (regex
162
+ only, no model calls): instruction-override phrasing, role hijacking,
163
+ spoofed system/chat-template tags, `curl … | sh` style exfiltration,
164
+ destructive commands, credential-shaped literals, hidden/bidi Unicode,
165
+ large encoded blobs. Findings carry severity, line numbers and a hint.
166
+ **Heuristics raise attention; they are not a security guarantee** — that
167
+ honesty is part of the design.
168
+
169
+ ### Journal / 审计日志
170
+
171
+ `Journal` appends JSONL records where each record's SHA-256 covers the record
172
+ and the previous record's hash. `verify()` walks the whole chain and reports
173
+ exactly which record was edited or removed. Stdlib only, greppable, diffable.
174
+
175
+ ## Security posture / 安全姿态
176
+
177
+ - **Zero runtime dependencies** — nothing to hijack in a supply chain; CI fails if `dependencies` stops being `[]`.
178
+ - **No network, no process spawning, no dynamic execution** — `eval/exec/compile/__import__/subprocess/socket/urllib/pickle/ctypes` are banned from `src/` and a dedicated test enforces it.
179
+ - **Deterministic transforms** — reviewed line by line; no model-in-the-loop rewriting of your content.
180
+ - See [SECURITY.md](SECURITY.md) for the threat model and reporting policy.
181
+
182
+ ## Comparison / 与同类项目的差异
183
+
184
+ | | proxies / runtimes (rtk, headroom…) | meme tools | **ctxtrim** |
185
+ |---|---|---|---|
186
+ | integration | binds to one agent/workflow | chat-only | **embeddable library + standalone CLI** |
187
+ | transform | varies, often model-assisted | lossy joke | **deterministic rules, per-rule trail** |
188
+ | reproducibility | not guaranteed | no | **same input → same output, tested** |
189
+ | injection auditing | no | no | **built-in heuristics** |
190
+ | tamper evidence | no | no | **hash-chained journal** |
191
+ | dependencies | many | varies | **zero (stdlib only)** |
192
+
193
+ Complementary, not competitive: use ctxtrim *inside* whatever harness you run.
194
+
195
+ ## Requirements / 环境
196
+
197
+ Python 3.9 – 3.13, any OS. Nothing else.
198
+
199
+ ## Roadmap / 路线图
200
+
201
+ - [x] MCP server wrapper (`ctxtrim serve`) exposing shrink/audit/split as tools
202
+ - [ ] Claude Code hook recipe (one-file integration guide)
203
+ - [ ] pluggable custom strategies via entry points
204
+ - [ ] optional token-accurate budgeting (tokenizer adapters, still optional deps)
205
+ - [ ] `--report html` static audit report
206
+
207
+ ## Contributing / 参与
208
+
209
+ PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). Every PR runs the full
210
+ suite including the source-security self-audit.
211
+
212
+ ## License / 协议
213
+
214
+ [MIT](LICENSE) — the most permissive mainstream license. Use it, fork it,
215
+ ship it.
216
+
217
+ ## Acknowledgements / 致谢
218
+
219
+ The problem statement was validated by the 2025–2026 wave of context-cost
220
+ tools (rtk, headroom, context-mode, caveman & friends). ctxtrim takes the
221
+ idea to the library layer with determinism and auditability as first-class
222
+ citizens.
@@ -0,0 +1,14 @@
1
+ ctxtrim/__init__.py,sha256=ujT3lahsveukZ9PQhQ1KraLf04dlqNKbUHIS8dI_2lQ,650
2
+ ctxtrim/__main__.py,sha256=KD56jJPF1VyVaA03YzKe7NjxXl9GUK7jNNeNBpu_4Hw,120
3
+ ctxtrim/audit.py,sha256=KtrqaxfIHCsJJR9V_JmtbeBZRELO0uKK3OIY9H1-SzU,4828
4
+ ctxtrim/budget.py,sha256=TOoez64SVixyDKmXcWm8cjFq3tnfQjOqrsqKeCz9nkE,2479
5
+ ctxtrim/cli.py,sha256=GCYjtTFuElB0Uy6HzZIt1faIOeN_7D9-5Rg9r3hQzV8,6956
6
+ ctxtrim/journal.py,sha256=aqF9fSEs8SE8eL8zBLpLFXoDK4Pu0VztzAs_YGbKmPA,3704
7
+ ctxtrim/mcp_server.py,sha256=UTQbZUxERJB9rm56_WEA6oK30RDJeAHuZhRuft2T86k,6276
8
+ ctxtrim/strategies.py,sha256=PX8_1qZU9qjl1HfGLsT4L-K6S60QagmQ88qKWZfdCl4,10305
9
+ ctxtrim-0.1.0.dist-info/LICENSE,sha256=xYvpdFu6s7o_1Beo-W7ASTUtYEFhgzeZz3DbDcRm9eU,1076
10
+ ctxtrim-0.1.0.dist-info/METADATA,sha256=2F0g3TFqGMUcIzruuH-xQuNCpLKvGnaGz87hqFH0h-Y,9960
11
+ ctxtrim-0.1.0.dist-info/WHEEL,sha256=EWGgdj_eH-g9dwsWZOTG0kmGucEuKPxGzOKD-jAVUHs,92
12
+ ctxtrim-0.1.0.dist-info/entry_points.txt,sha256=29IKEFLHTR2R4NPc0P1XgJzr2ZUn7GjDvaF3Kw5GJCs,45
13
+ ctxtrim-0.1.0.dist-info/top_level.txt,sha256=BbcHycWtcCC15_co1eifMZoONf9z-NCh0kuiG2WyzVA,8
14
+ ctxtrim-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.48.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ctxtrim = ctxtrim.cli:main
@@ -0,0 +1 @@
1
+ ctxtrim