warlockcode-wartools-ai 0.1.1__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.
Files changed (52) hide show
  1. warlockcode_wartools_ai/__init__.py +21 -0
  2. warlockcode_wartools_ai/_generated/__init__.py +1 -0
  3. warlockcode_wartools_ai/_generated/shared_data.py +5 -0
  4. warlockcode_wartools_ai/_lib/__init__.py +0 -0
  5. warlockcode_wartools_ai/_lib/canonical.py +96 -0
  6. warlockcode_wartools_ai/_lib/common.py +54 -0
  7. warlockcode_wartools_ai/_lib/errors.py +9 -0
  8. warlockcode_wartools_ai/_lib/html.py +32 -0
  9. warlockcode_wartools_ai/_lib/net.py +132 -0
  10. warlockcode_wartools_ai/_lib/patchapply.py +144 -0
  11. warlockcode_wartools_ai/_lib/sandbox.py +42 -0
  12. warlockcode_wartools_ai/_lib/textkit.py +59 -0
  13. warlockcode_wartools_ai/_lib/timekit.py +59 -0
  14. warlockcode_wartools_ai/_lib/udiff.py +117 -0
  15. warlockcode_wartools_ai/_lib/unicode.py +93 -0
  16. warlockcode_wartools_ai/handlers/__init__.py +43 -0
  17. warlockcode_wartools_ai/handlers/catalog.py +27 -0
  18. warlockcode_wartools_ai/handlers/context.py +35 -0
  19. warlockcode_wartools_ai/handlers/crypto.py +61 -0
  20. warlockcode_wartools_ai/handlers/csv.py +132 -0
  21. warlockcode_wartools_ai/handlers/doc.py +77 -0
  22. warlockcode_wartools_ai/handlers/doc_detect.py +55 -0
  23. warlockcode_wartools_ai/handlers/encoding.py +57 -0
  24. warlockcode_wartools_ai/handlers/fs.py +110 -0
  25. warlockcode_wartools_ai/handlers/json.py +220 -0
  26. warlockcode_wartools_ai/handlers/kv.py +103 -0
  27. warlockcode_wartools_ai/handlers/math.py +223 -0
  28. warlockcode_wartools_ai/handlers/scratchpad.py +82 -0
  29. warlockcode_wartools_ai/handlers/security.py +50 -0
  30. warlockcode_wartools_ai/handlers/state.py +40 -0
  31. warlockcode_wartools_ai/handlers/text.py +183 -0
  32. warlockcode_wartools_ai/handlers/text_patch.py +24 -0
  33. warlockcode_wartools_ai/handlers/text_rerank.py +50 -0
  34. warlockcode_wartools_ai/handlers/time.py +103 -0
  35. warlockcode_wartools_ai/handlers/time_business.py +109 -0
  36. warlockcode_wartools_ai/handlers/trace.py +33 -0
  37. warlockcode_wartools_ai/handlers/validate.py +58 -0
  38. warlockcode_wartools_ai/handlers/web.py +81 -0
  39. warlockcode_wartools_ai/mcp.py +106 -0
  40. warlockcode_wartools_ai/models.py +118 -0
  41. warlockcode_wartools_ai/py.typed +0 -0
  42. warlockcode_wartools_ai/registry.py +196 -0
  43. warlockcode_wartools_ai/runtime/__init__.py +4 -0
  44. warlockcode_wartools_ai/runtime/pipeline.py +149 -0
  45. warlockcode_wartools_ai/runtime/policy_store.py +63 -0
  46. warlockcode_wartools_ai/stores.py +267 -0
  47. warlockcode_wartools_ai/tools.py +66 -0
  48. warlockcode_wartools_ai-0.1.1.dist-info/METADATA +34 -0
  49. warlockcode_wartools_ai-0.1.1.dist-info/RECORD +52 -0
  50. warlockcode_wartools_ai-0.1.1.dist-info/WHEEL +5 -0
  51. warlockcode_wartools_ai-0.1.1.dist-info/entry_points.txt +2 -0
  52. warlockcode_wartools_ai-0.1.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ from .models import SecurityConfig, WarToolEnvelope, WarToolError, WarToolMeta
2
+ from .registry import WarTools, load_manifest
3
+ from .runtime import MemoryPolicyStateStore, PolicyStateStore
4
+ from .stores import FileTraceSink, JsonFileKvStore, KvStore, MemoryKvStore, MemoryTraceSink, TraceSink
5
+
6
+ __all__ = [
7
+ "WarTools",
8
+ "SecurityConfig",
9
+ "WarToolEnvelope",
10
+ "WarToolError",
11
+ "WarToolMeta",
12
+ "KvStore",
13
+ "MemoryKvStore",
14
+ "JsonFileKvStore",
15
+ "TraceSink",
16
+ "MemoryTraceSink",
17
+ "FileTraceSink",
18
+ "load_manifest",
19
+ "PolicyStateStore",
20
+ "MemoryPolicyStateStore",
21
+ ]
@@ -0,0 +1 @@
1
+ # AUTO-GENERATED by scripts/gen-shared-data.py from spec/data/*.json. DO NOT EDIT.
@@ -0,0 +1,5 @@
1
+ # AUTO-GENERATED by scripts/gen-shared-data.py from spec/data/*.json. DO NOT EDIT.
2
+ # ruff: noqa
3
+ import json as _json
4
+
5
+ EXAMPLE = _json.loads("{\"greeting\":\"hola\",\"emoji\":\"\\ud83d\\ude00\",\"pattern\":\"[0-9]+\"}")
File without changes
@@ -0,0 +1,96 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import math
6
+ import re
7
+ from typing import Any, Dict, NoReturn
8
+
9
+ # JS numbers are IEEE doubles; .NET reads numbers with GetDouble(). Integers beyond 2^53 must be rounded the same way.
10
+ _MAX_SAFE_INT = 2**53
11
+ _SURROGATES = re.compile("[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]")
12
+
13
+
14
+ def _invalid(message: str) -> NoReturn:
15
+ # Lazy import: _lib must not import the tools facade at module load time (circular import).
16
+ from ..tools import ToolExecutionError
17
+
18
+ raise ToolExecutionError("INVALID_INPUT", message)
19
+
20
+
21
+ def _es_float(v: float) -> str:
22
+ """ECMAScript Number::toString from Python's shortest round-trip repr (same algorithm as .NET CanonicalJson.Number)."""
23
+ if math.isnan(v) or math.isinf(v):
24
+ _invalid("Non-finite number cannot be canonicalized.")
25
+ if v == 0:
26
+ return "0"
27
+ neg = v < 0
28
+ mant, _, exp = repr(abs(v)).partition("e")
29
+ e = int(exp) if exp else 0
30
+ ip, _, fp = mant.partition(".")
31
+ digits = ip + fp
32
+ n = len(ip) + e
33
+ stripped = digits.lstrip("0")
34
+ n -= len(digits) - len(stripped)
35
+ digits = stripped.rstrip("0") or "0"
36
+ k = len(digits)
37
+ if k <= n <= 21:
38
+ body = digits + "0" * (n - k)
39
+ elif 0 < n <= 21:
40
+ body = digits[:n] + "." + digits[n:]
41
+ elif -6 < n <= 0:
42
+ body = "0." + "0" * (-n) + digits
43
+ else:
44
+ ee = n - 1
45
+ es = ("+" if ee >= 0 else "-") + str(abs(ee))
46
+ body = digits + "e" + es if k == 1 else digits[0] + "." + digits[1:] + "e" + es
47
+ return "-" + body if neg else body
48
+
49
+
50
+ def _num(v: Any) -> str:
51
+ if isinstance(v, int):
52
+ if abs(v) <= _MAX_SAFE_INT:
53
+ return str(v)
54
+ try:
55
+ v = float(v)
56
+ except OverflowError:
57
+ _invalid("Non-finite number cannot be canonicalized.")
58
+ return _es_float(float(v))
59
+
60
+
61
+ def _fix_surrogates(m: "re.Match[str]") -> str:
62
+ t = m.group()
63
+ if len(t) == 2:
64
+ return chr(0x10000 + ((ord(t[0]) - 0xD800) << 10) + (ord(t[1]) - 0xDC00))
65
+ return "\\u%04x" % ord(t)
66
+
67
+
68
+ def _str(s: str) -> str:
69
+ # Same as JSON.stringify / .NET writer: no non-ASCII escaping, lone surrogates escaped as lowercase \uXXXX.
70
+ return _SURROGATES.sub(_fix_surrogates, json.dumps(s, ensure_ascii=False))
71
+
72
+
73
+ def canonicalize(value: Any) -> str:
74
+ """Canonical JSON (JCS-style): keys sorted by UTF-16 code units, ES number format, no non-ASCII escaping."""
75
+ if value is None:
76
+ return "null"
77
+ if value is True:
78
+ return "true"
79
+ if value is False:
80
+ return "false"
81
+ if isinstance(value, str):
82
+ return _str(value)
83
+ if isinstance(value, (int, float)):
84
+ return _num(value)
85
+ if isinstance(value, (list, tuple)):
86
+ return "[" + ",".join(canonicalize(x) for x in value) + "]"
87
+ if isinstance(value, dict):
88
+ keys = sorted(value.keys(), key=lambda k: str(k).encode("utf-16-be", "surrogatepass"))
89
+ return "{" + ",".join(_str(str(k)) + ":" + canonicalize(value[k]) for k in keys) + "}"
90
+ _invalid("Unsupported value type for canonical JSON.")
91
+
92
+
93
+ def args_hash(inp: Dict[str, Any]) -> str:
94
+ """sha256(canon(args without sessionId/approvalId)) first 16 hex chars."""
95
+ copy = {k: v for k, v in (inp or {}).items() if k not in ("sessionId", "approvalId")}
96
+ return hashlib.sha256(canonicalize(copy).encode("utf-8", "surrogatepass")).hexdigest()[:16]
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime, timedelta, timezone
4
+ from typing import Any, Dict
5
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
6
+
7
+ from .errors import ToolExecutionError
8
+
9
+
10
+ def clean_number(v: float) -> Any:
11
+ if isinstance(v, float) and v.is_integer():
12
+ return int(v)
13
+ return v
14
+
15
+
16
+ def format_in_timezone(dt: datetime, tz_name: str) -> Dict[str, str]:
17
+ try:
18
+ tz = ZoneInfo(tz_name)
19
+ except ZoneInfoNotFoundError:
20
+ raise ToolExecutionError("INVALID_TIMEZONE", f'Unknown IANA timezone "{tz_name}".')
21
+ local_dt = dt.astimezone(tz)
22
+ offset = local_dt.utcoffset() or timedelta(0)
23
+ total_mins = int(offset.total_seconds() // 60)
24
+ if total_mins == 0:
25
+ offset_iso = "Z"
26
+ else:
27
+ sign = "+" if total_mins >= 0 else "-"
28
+ abs_m = abs(total_mins)
29
+ offset_iso = f"{sign}{abs_m // 60:02d}:{abs_m % 60:02d}"
30
+ date_str = local_dt.strftime("%Y-%m-%d")
31
+ time_str = local_dt.strftime("%H:%M:%S")
32
+ weekday = local_dt.strftime("%A")
33
+ return {
34
+ "iso": f"{date_str}T{time_str}{offset_iso}",
35
+ "date": date_str,
36
+ "time": time_str,
37
+ "weekday": weekday,
38
+ "offsetIso": offset_iso,
39
+ }
40
+
41
+
42
+ def parse_iso_datetime(raw: str) -> datetime:
43
+ if not raw or not isinstance(raw, str):
44
+ raise ToolExecutionError("INVALID_INPUT", "Timestamp must be a valid ISO-8601 string.")
45
+ s = raw.strip()
46
+ if s.endswith("Z"):
47
+ s = s[:-1] + "+00:00"
48
+ try:
49
+ dt = datetime.fromisoformat(s)
50
+ except ValueError:
51
+ raise ToolExecutionError("INVALID_INPUT", f'Invalid ISO-8601 timestamp "{raw}".')
52
+ if dt.tzinfo is None:
53
+ dt = dt.replace(tzinfo=timezone.utc)
54
+ return dt
@@ -0,0 +1,9 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class ToolExecutionError(Exception):
5
+ def __init__(self, code: str, message: str, recoverable: bool = True) -> None:
6
+ super().__init__(message)
7
+ self.code = code
8
+ self.message = message
9
+ self.recoverable = recoverable
@@ -0,0 +1,32 @@
1
+ from __future__ import annotations
2
+
3
+ import html as html_lib
4
+ import re
5
+ from typing import Tuple
6
+
7
+
8
+ def strip_html(raw_html: str) -> str:
9
+ s = re.sub(r"<script[\s\S]*?</script>", " ", raw_html, flags=re.IGNORECASE)
10
+ s = re.sub(r"<style[\s\S]*?</style>", " ", s, flags=re.IGNORECASE)
11
+ s = re.sub(r"<nav[\s\S]*?</nav>", " ", s, flags=re.IGNORECASE)
12
+ s = re.sub(r"<[^>]+>", " ", s)
13
+ return re.sub(r"\s+", " ", s).strip()
14
+
15
+
16
+ def html_to_markdown(raw_html: str, include_links: bool = True) -> Tuple[str, str]:
17
+ title_match = re.search(r"<title[^>]*>([\s\S]*?)</title>", raw_html, flags=re.IGNORECASE)
18
+ title = strip_html(title_match.group(1)) if title_match else "Untitled"
19
+ clean = re.sub(r"<script[\s\S]*?</script>", "", raw_html, flags=re.IGNORECASE)
20
+ clean = re.sub(r"<style[\s\S]*?</style>", "", clean, flags=re.IGNORECASE)
21
+ clean = re.sub(r"<nav[\s\S]*?</nav>", "", clean, flags=re.IGNORECASE)
22
+ clean = re.sub(r"<h1[^>]*>([\s\S]*?)</h1>", r"\n# \1\n", clean, flags=re.IGNORECASE)
23
+ clean = re.sub(r"<h2[^>]*>([\s\S]*?)</h2>", r"\n## \1\n", clean, flags=re.IGNORECASE)
24
+ clean = re.sub(r"<h3[^>]*>([\s\S]*?)</h3>", r"\n### \1\n", clean, flags=re.IGNORECASE)
25
+ clean = re.sub(r"<li[^>]*>([\s\S]*?)</li>", r"\n- \1", clean, flags=re.IGNORECASE)
26
+ clean = re.sub(r"<p[^>]*>([\s\S]*?)</p>", r"\n\1\n", clean, flags=re.IGNORECASE)
27
+ if include_links:
28
+ clean = re.sub(r'<a[^>]*href=["\']([^"\']+)["\'][^>]*>([\s\S]*?)</a>', r"[\2](\1)", clean, flags=re.IGNORECASE)
29
+ clean = re.sub(r"<[^>]+>", "", clean)
30
+ clean = html_lib.unescape(clean)
31
+ clean = re.sub(r"\n{3,}", "\n\n", clean).strip()
32
+ return title, clean
@@ -0,0 +1,132 @@
1
+ from __future__ import annotations
2
+
3
+ import ipaddress
4
+ import socket
5
+ import urllib.error
6
+ import urllib.parse
7
+ import urllib.request
8
+ from typing import Any, Dict, List, Optional
9
+
10
+ from ..models import SecurityConfig
11
+ from .errors import ToolExecutionError
12
+
13
+
14
+ def is_private_ip(ip_str: str) -> bool:
15
+ try:
16
+ ip = ipaddress.ip_address(ip_str)
17
+ except ValueError:
18
+ return False
19
+ return bool(ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_unspecified or ip.is_reserved)
20
+
21
+
22
+ def domain_matches(hostname: str, patterns: List[str]) -> bool:
23
+ host = hostname.lower()
24
+ for pat in patterns:
25
+ clean = pat.strip().lower()
26
+ if not clean:
27
+ continue
28
+ if clean == "*":
29
+ return True
30
+ if host == clean or host.endswith(f".{clean}"):
31
+ return True
32
+ return False
33
+
34
+
35
+ class _RedirectStop(Exception):
36
+ def __init__(self, location: str) -> None:
37
+ self.location = location
38
+
39
+
40
+ class _NoAutoRedirectHandler(urllib.request.HTTPRedirectHandler):
41
+ def redirect_request(self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str) -> None:
42
+ raise _RedirectStop(headers.get("Location") or newurl)
43
+
44
+
45
+ def safe_fetch_text(
46
+ raw_url: str,
47
+ security: SecurityConfig,
48
+ headers: Optional[Dict[str, Any]] = None,
49
+ override_timeout_ms: Optional[float] = None,
50
+ ) -> Dict[str, Any]:
51
+ try:
52
+ parsed = urllib.parse.urlparse(raw_url)
53
+ except Exception:
54
+ raise ToolExecutionError("INVALID_INPUT", "Provided URL is not valid.")
55
+
56
+ if not parsed.scheme or not parsed.netloc:
57
+ raise ToolExecutionError("INVALID_INPUT", "Provided URL is not valid.")
58
+
59
+ timeout_ms = min(float(override_timeout_ms or security.timeout_ms or 10000), 15000.0)
60
+ timeout_sec = max(0.01, timeout_ms / 1000.0)
61
+ current_url = raw_url
62
+ opener = urllib.request.build_opener(_NoAutoRedirectHandler())
63
+
64
+ for _ in range(4):
65
+ p = urllib.parse.urlparse(current_url)
66
+ if p.scheme not in ("http", "https"):
67
+ raise ToolExecutionError("UNSUPPORTED_PROTOCOL", "Only http and https URLs are permitted.")
68
+
69
+ host = (p.hostname or "").lower()
70
+ if security.http_block_domains and domain_matches(host, security.http_block_domains):
71
+ raise ToolExecutionError("DOMAIN_NOT_ALLOWED", f'Domain "{host}" is explicitly blocklisted.')
72
+ if not domain_matches(host, security.http_allow_domains):
73
+ raise ToolExecutionError("DOMAIN_NOT_ALLOWED", f'Domain "{host}" is not in security.httpAllowDomains.')
74
+
75
+ allow_test_loopback = bool(security.allow_private_test_loopback)
76
+ is_literal_ip = False
77
+ try:
78
+ ipaddress.ip_address(host)
79
+ is_literal_ip = True
80
+ except ValueError:
81
+ is_literal_ip = False
82
+
83
+ if is_literal_ip:
84
+ if is_private_ip(host) and not (allow_test_loopback and host in ("127.0.0.1", "::1")):
85
+ raise ToolExecutionError("PRIVATE_NETWORK_BLOCKED", "Private or loopback IP targets are blocked.")
86
+ else:
87
+ try:
88
+ infos = socket.getaddrinfo(host, None)
89
+ ips = {info[4][0] for info in infos if info[4]}
90
+ except socket.gaierror:
91
+ raise ToolExecutionError("DNS_RESOLUTION_FAILED", f'Could not resolve hostname "{host}".')
92
+ if not ips:
93
+ raise ToolExecutionError("DNS_RESOLUTION_FAILED", f'Could not resolve hostname "{host}".')
94
+ if any(is_private_ip(ip) for ip in ips):
95
+ raise ToolExecutionError("PRIVATE_NETWORK_BLOCKED", "Target resolved to a private or loopback IP.")
96
+
97
+ req_headers = {"User-Agent": "WarToolsAI/0.1"}
98
+ if isinstance(headers, dict):
99
+ for k, v in headers.items():
100
+ req_headers[str(k)] = str(v)
101
+
102
+ req = urllib.request.Request(current_url, headers=req_headers, method="GET")
103
+ try:
104
+ with opener.open(req, timeout=timeout_sec) as resp:
105
+ max_bytes = max(security.max_output_chars * 4, 64000)
106
+ raw_bytes = resp.read(max_bytes + 1)[:max_bytes]
107
+ content_type = resp.headers.get("Content-Type") or "text/plain"
108
+ return {
109
+ "statusCode": int(resp.status),
110
+ "contentType": content_type,
111
+ "body": raw_bytes.decode("utf-8", errors="replace"),
112
+ "finalUrl": current_url,
113
+ }
114
+ except _RedirectStop as redir:
115
+ if not redir.location:
116
+ raise ToolExecutionError("REDIRECT_ERROR", "Redirect response missing Location header.")
117
+ current_url = urllib.parse.urljoin(current_url, redir.location)
118
+ continue
119
+ except urllib.error.URLError as err:
120
+ if isinstance(err.reason, (socket.timeout, TimeoutError)) or "timed out" in str(err.reason).lower():
121
+ raise ToolExecutionError("TIMEOUT", f"HTTP request exceeded {int(timeout_ms)}ms timeout.")
122
+ raise ToolExecutionError("HTTP_REQUEST_FAILED", str(err.reason))
123
+ except (socket.timeout, TimeoutError):
124
+ raise ToolExecutionError("TIMEOUT", f"HTTP request exceeded {int(timeout_ms)}ms timeout.")
125
+ except ToolExecutionError:
126
+ raise
127
+ except Exception as exc:
128
+ if "timed out" in str(exc).lower():
129
+ raise ToolExecutionError("TIMEOUT", f"HTTP request exceeded {int(timeout_ms)}ms timeout.")
130
+ raise ToolExecutionError("HTTP_REQUEST_FAILED", str(exc))
131
+
132
+ raise ToolExecutionError("TOO_MANY_REDIRECTS", "Exceeded maximum allowed redirects.")
@@ -0,0 +1,144 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import List, Tuple
5
+
6
+ _HDR = re.compile(r"^@@ -([0-9]+)(?:,([0-9]+))? \+([0-9]+)(?:,([0-9]+))? @@")
7
+
8
+
9
+ class PatchError(Exception):
10
+ def __init__(self, kind: str, message: str) -> None:
11
+ super().__init__(message)
12
+ self.kind = kind
13
+
14
+
15
+ def _split_keep(s: str) -> List[str]:
16
+ parts = s.split("\n")
17
+ out = [p + "\n" for p in parts[:-1]]
18
+ if parts[-1]:
19
+ out.append(parts[-1])
20
+ return out
21
+
22
+
23
+ def _body(l: str) -> str:
24
+ if l.endswith("\n"):
25
+ l = l[:-1]
26
+ if l.endswith("\r"):
27
+ l = l[:-1]
28
+ return l
29
+
30
+
31
+ def parse_patch(patch: str) -> List[dict]:
32
+ pl = [_body(x) for x in _split_keep(patch)]
33
+ hunks: List[dict] = []
34
+ i = 0
35
+ while i < len(pl):
36
+ m = _HDR.match(pl[i])
37
+ if not m:
38
+ if pl[i].startswith("@@"):
39
+ raise PatchError("invalid", f"Malformed hunk header: {pl[i]}")
40
+ i += 1
41
+ continue
42
+ old_count = 1 if m.group(2) is None else int(m.group(2))
43
+ new_count = 1 if m.group(4) is None else int(m.group(4))
44
+ h = {"oldStart": int(m.group(1)), "oldCount": old_count, "lines": []}
45
+ lines = h["lines"]
46
+ i += 1
47
+ o = 0
48
+ n = 0
49
+ while (o < old_count or n < new_count) and i < len(pl):
50
+ l = pl[i]
51
+ if l.startswith("\\"):
52
+ if lines:
53
+ lines[-1][2] = True
54
+ i += 1
55
+ continue
56
+ if l == "":
57
+ lines.append([" ", "", False])
58
+ o += 1
59
+ n += 1
60
+ elif l[0] == " ":
61
+ lines.append([" ", l[1:], False])
62
+ o += 1
63
+ n += 1
64
+ elif l[0] == "-":
65
+ lines.append(["-", l[1:], False])
66
+ o += 1
67
+ elif l[0] == "+":
68
+ lines.append(["+", l[1:], False])
69
+ n += 1
70
+ else:
71
+ raise PatchError("invalid", f"Unexpected line in hunk: {l}")
72
+ i += 1
73
+ if o != old_count or n != new_count:
74
+ raise PatchError("invalid", "Hunk line counts do not match its header.")
75
+ while i < len(pl) and pl[i].startswith("\\"):
76
+ if lines:
77
+ lines[-1][2] = True
78
+ i += 1
79
+ hunks.append(h)
80
+ if not hunks:
81
+ raise PatchError("invalid", "Patch contains no hunks.")
82
+ return hunks
83
+
84
+
85
+ def apply_patch(original: str, hunks: List[dict]) -> Tuple[str, int, int]:
86
+ orig = _split_keep(original)
87
+ n = len(orig)
88
+ out: List[str] = []
89
+ cursor = 0
90
+ additions = 0
91
+ deletions = 0
92
+ for hi, h in enumerate(hunks):
93
+ old_t = [l[1] for l in h["lines"] if l[0] != "+"]
94
+ expected = h["oldStart"] if h["oldCount"] == 0 else h["oldStart"] - 1
95
+ mx = n - len(old_t)
96
+
97
+ def matches(p: int) -> bool:
98
+ for k, t in enumerate(old_t):
99
+ if _body(orig[p + k]) != t:
100
+ return False
101
+ return True
102
+
103
+ found = -1
104
+ d = 0
105
+ while d <= n + 1 and found < 0:
106
+ cands = [expected] if d == 0 else [expected + d, expected - d]
107
+ for p in cands:
108
+ if p < cursor or p > mx:
109
+ continue
110
+ if matches(p):
111
+ found = p
112
+ break
113
+ d += 1
114
+ if found < 0:
115
+ raise PatchError("conflict", f"Hunk {hi + 1} does not match the original text.")
116
+ while cursor < found:
117
+ out.append(orig[cursor])
118
+ cursor += 1
119
+ if found < n:
120
+ ref = orig[found]
121
+ elif found - 1 >= 0 and found - 1 < n:
122
+ ref = orig[found - 1]
123
+ else:
124
+ ref = ""
125
+ eol = "\r\n" if ref.endswith("\r\n") else "\n"
126
+ idx = found
127
+ for t, text, no_eol in h["lines"]:
128
+ if t == " ":
129
+ out.append(orig[idx])
130
+ idx += 1
131
+ elif t == "-":
132
+ idx += 1
133
+ deletions += 1
134
+ else:
135
+ out.append(text + ("" if no_eol else eol))
136
+ additions += 1
137
+ cursor = idx
138
+ while cursor < n:
139
+ out.append(orig[cursor])
140
+ cursor += 1
141
+ for i in range(len(out) - 1):
142
+ if not out[i].endswith("\n"):
143
+ out[i] += "\n"
144
+ return "".join(out), additions, deletions
@@ -0,0 +1,42 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from typing import List, Tuple
5
+
6
+ from .errors import ToolExecutionError
7
+
8
+
9
+ def resolve_sandbox_path(fs_root: str, relative_path: str = ".", for_write: bool = False) -> Tuple[str, str, str]:
10
+ rel_input = relative_path or "."
11
+ if "\x00" in rel_input:
12
+ raise ToolExecutionError("SANDBOX_PATH_DENIED", "Null bytes are not permitted in sandbox paths.")
13
+ if os.path.isabs(rel_input):
14
+ raise ToolExecutionError("SANDBOX_PATH_DENIED", "Absolute paths are not permitted inside sandbox.")
15
+
16
+ root_candidate = os.path.abspath(fs_root or "./workspace")
17
+ os.makedirs(root_candidate, exist_ok=True)
18
+ real_root = os.path.realpath(root_candidate)
19
+ candidate = os.path.abspath(os.path.join(real_root, rel_input))
20
+ initial_rel = os.path.relpath(candidate, real_root)
21
+
22
+ if initial_rel.startswith("..") or os.path.isabs(initial_rel):
23
+ raise ToolExecutionError("SANDBOX_PATH_DENIED", "Requested path escapes configured fsRoot.")
24
+
25
+ check_path = candidate
26
+ missing: List[str] = []
27
+ while True:
28
+ if os.path.lexists(check_path):
29
+ if os.path.islink(check_path) and not os.path.exists(check_path):
30
+ raise ToolExecutionError("SANDBOX_PATH_DENIED", "Symlink target escapes configured fsRoot.")
31
+ real_checked = os.path.realpath(check_path)
32
+ rel_real = os.path.relpath(real_checked, real_root)
33
+ if rel_real.startswith("..") or os.path.isabs(rel_real):
34
+ raise ToolExecutionError("SANDBOX_PATH_DENIED", "Symlink target escapes configured fsRoot.")
35
+ target = os.path.join(real_checked, *reversed(missing)) if missing else real_checked
36
+ display_rel = "." if initial_rel == "." else initial_rel.replace("\\", "/")
37
+ return real_root, target, display_rel
38
+ parent = os.path.dirname(check_path)
39
+ if parent == check_path:
40
+ raise ToolExecutionError("SANDBOX_PATH_DENIED", "Invalid sandbox path.")
41
+ missing.append(os.path.basename(check_path))
42
+ check_path = parent
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import unicodedata
5
+ from typing import Dict, List
6
+
7
+
8
+ def round4(x: float) -> float:
9
+ return math.floor(x * 1e4 + 0.5) / 1e4
10
+
11
+
12
+ def fold_case(s: str) -> str:
13
+ t = unicodedata.normalize("NFD", unicodedata.normalize("NFKC", s).lower())
14
+ t = "".join(ch for ch in t if unicodedata.category(ch) != "Mn")
15
+ return t.replace("\u03c2", "\u03c3")
16
+
17
+
18
+ def tokenize(s: str) -> List[str]:
19
+ out: List[str] = []
20
+ cur: List[str] = []
21
+ for ch in fold_case(s):
22
+ cat = unicodedata.category(ch)
23
+ if cat[0] in ("L", "N"):
24
+ cur.append(ch)
25
+ elif cur:
26
+ out.append("".join(cur))
27
+ cur = []
28
+ if cur:
29
+ out.append("".join(cur))
30
+ return out
31
+
32
+
33
+ def bm25_scores(query_tokens: List[str], docs: List[List[str]], k1: float = 1.2, b: float = 0.75) -> List[float]:
34
+ n = len(docs)
35
+ total = sum(len(d) for d in docs)
36
+ avgdl = total / n if total > 0 else 1.0
37
+ terms: List[str] = []
38
+ for t in query_tokens:
39
+ if t not in terms:
40
+ terms.append(t)
41
+ tfs: List[Dict[str, int]] = []
42
+ for d in docs:
43
+ m: Dict[str, int] = {}
44
+ for t in d:
45
+ m[t] = m.get(t, 0) + 1
46
+ tfs.append(m)
47
+ df = {term: sum(1 for m in tfs if term in m) for term in terms}
48
+ scores: List[float] = []
49
+ for i, d in enumerate(docs):
50
+ score = 0.0
51
+ for term in terms:
52
+ tf = tfs[i].get(term, 0)
53
+ if tf == 0:
54
+ continue
55
+ nn = df[term]
56
+ idf = math.log(1 + (n - nn + 0.5) / (nn + 0.5))
57
+ score += (idf * tf * (k1 + 1)) / (tf + k1 * (1 - b + (b * len(d)) / avgdl))
58
+ scores.append(score)
59
+ return scores
@@ -0,0 +1,59 @@
1
+ """TimeKit (A10): strict ISO date parsing and civil-calendar arithmetic (no datetime, no timezones)."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from typing import Optional, Tuple
6
+
7
+ _DATE_RE = re.compile(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})$")
8
+
9
+
10
+ def is_leap(y: int) -> bool:
11
+ return (y % 4 == 0 and y % 100 != 0) or y % 400 == 0
12
+
13
+
14
+ def days_in_month(y: int, m: int) -> int:
15
+ if m == 2:
16
+ return 29 if is_leap(y) else 28
17
+ return 30 if m in (4, 6, 9, 11) else 31
18
+
19
+
20
+ def days_from_civil(y: int, m: int, d: int) -> int:
21
+ if m <= 2:
22
+ y -= 1
23
+ era = y // 400
24
+ yoe = y - era * 400
25
+ doy = (153 * (m + (-3 if m > 2 else 9)) + 2) // 5 + d - 1
26
+ doe = yoe * 365 + yoe // 4 - yoe // 100 + doy
27
+ return era * 146097 + doe - 719468
28
+
29
+
30
+ def civil_from_days(z: int) -> Tuple[int, int, int]:
31
+ z += 719468
32
+ era = z // 146097
33
+ doe = z - era * 146097
34
+ yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365
35
+ y = yoe + era * 400
36
+ doy = doe - (365 * yoe + yoe // 4 - yoe // 100)
37
+ mp = (5 * doy + 2) // 153
38
+ d = doy - (153 * mp + 2) // 5 + 1
39
+ m = mp + 3 if mp < 10 else mp - 9
40
+ return (y + 1 if m <= 2 else y, m, d)
41
+
42
+
43
+ def parse_iso_date(s: str) -> Optional[int]:
44
+ mt = _DATE_RE.match(s)
45
+ if not mt or s.endswith("\n"):
46
+ return None
47
+ y, m, d = int(mt.group(1)), int(mt.group(2)), int(mt.group(3))
48
+ if m < 1 or m > 12 or d < 1 or d > days_in_month(y, m):
49
+ return None
50
+ return days_from_civil(y, m, d)
51
+
52
+
53
+ def format_iso_date(days: int) -> str:
54
+ y, m, d = civil_from_days(days)
55
+ return f"{y:04d}-{m:02d}-{d:02d}"
56
+
57
+
58
+ def weekday_iso(days: int) -> int:
59
+ return ((days + 3) % 7) + 1