warlockcode-wartools-ai 0.1.1__tar.gz
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.
- warlockcode_wartools_ai-0.1.1/PKG-INFO +34 -0
- warlockcode_wartools_ai-0.1.1/README.md +24 -0
- warlockcode_wartools_ai-0.1.1/pyproject.toml +24 -0
- warlockcode_wartools_ai-0.1.1/setup.cfg +4 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/__init__.py +21 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_generated/__init__.py +1 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_generated/shared_data.py +5 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_lib/__init__.py +0 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_lib/canonical.py +96 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_lib/common.py +54 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_lib/errors.py +9 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_lib/html.py +32 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_lib/net.py +132 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_lib/patchapply.py +144 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_lib/sandbox.py +42 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_lib/textkit.py +59 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_lib/timekit.py +59 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_lib/udiff.py +117 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/_lib/unicode.py +93 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/__init__.py +43 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/catalog.py +27 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/context.py +35 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/crypto.py +61 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/csv.py +132 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/doc.py +77 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/doc_detect.py +55 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/encoding.py +57 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/fs.py +110 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/json.py +220 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/kv.py +103 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/math.py +223 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/scratchpad.py +82 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/security.py +50 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/state.py +40 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/text.py +183 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/text_patch.py +24 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/text_rerank.py +50 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/time.py +103 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/time_business.py +109 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/trace.py +33 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/validate.py +58 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/handlers/web.py +81 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/mcp.py +106 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/models.py +118 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/py.typed +0 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/registry.py +196 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/runtime/__init__.py +4 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/runtime/pipeline.py +149 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/runtime/policy_store.py +63 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/stores.py +267 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai/tools.py +66 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai.egg-info/PKG-INFO +34 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai.egg-info/SOURCES.txt +58 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai.egg-info/dependency_links.txt +1 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai.egg-info/entry_points.txt +2 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai.egg-info/requires.txt +1 -0
- warlockcode_wartools_ai-0.1.1/src/warlockcode_wartools_ai.egg-info/top_level.txt +1 -0
- warlockcode_wartools_ai-0.1.1/tests/test_contracts.py +282 -0
- warlockcode_wartools_ai-0.1.1/tests/test_handler_registry.py +88 -0
- warlockcode_wartools_ai-0.1.1/tests/test_unicode_kit.py +60 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: warlockcode-wartools-ai
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Modular, Default-Off tool runtime and MCP server for AI agents.
|
|
5
|
+
Author: WarlockCode
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: pydantic>=2.0
|
|
10
|
+
|
|
11
|
+
# `warlockcode-wartools-ai`
|
|
12
|
+
|
|
13
|
+
Modular, Default-Off tool runtime and MCP server for Python >= 3.10.
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pip install warlockcode-wartools-ai
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Quick Start (Default-Off)
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from warlockcode_wartools_ai import WarTools, JsonFileKvStore, SecurityConfig
|
|
25
|
+
|
|
26
|
+
kit = WarTools.create(
|
|
27
|
+
preset="none",
|
|
28
|
+
enable=["time.now", "kv.*"],
|
|
29
|
+
security=SecurityConfig(fs_root="./workspace", http_allow_domains=["api.github.com"]),
|
|
30
|
+
store=JsonFileKvStore("./.wartools-store.json"),
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
envelope = kit.execute("time.now", {"timezone": "America/Bogota"})
|
|
34
|
+
```
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# `warlockcode-wartools-ai`
|
|
2
|
+
|
|
3
|
+
Modular, Default-Off tool runtime and MCP server for Python >= 3.10.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install warlockcode-wartools-ai
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start (Default-Off)
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from warlockcode_wartools_ai import WarTools, JsonFileKvStore, SecurityConfig
|
|
15
|
+
|
|
16
|
+
kit = WarTools.create(
|
|
17
|
+
preset="none",
|
|
18
|
+
enable=["time.now", "kv.*"],
|
|
19
|
+
security=SecurityConfig(fs_root="./workspace", http_allow_domains=["api.github.com"]),
|
|
20
|
+
store=JsonFileKvStore("./.wartools-store.json"),
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
envelope = kit.execute("time.now", {"timezone": "America/Bogota"})
|
|
24
|
+
```
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "warlockcode-wartools-ai"
|
|
7
|
+
version = "0.1.1"
|
|
8
|
+
description = "Modular, Default-Off tool runtime and MCP server for AI agents."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "WarlockCode" }]
|
|
13
|
+
dependencies = [
|
|
14
|
+
"pydantic>=2.0",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[project.scripts]
|
|
18
|
+
wartools-ai = "warlockcode_wartools_ai.mcp:main"
|
|
19
|
+
|
|
20
|
+
[tool.setuptools.packages.find]
|
|
21
|
+
where = ["src"]
|
|
22
|
+
|
|
23
|
+
[tool.setuptools.package-data]
|
|
24
|
+
warlockcode_wartools_ai = ["py.typed", "registry-manifest.json"]
|
|
@@ -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.
|
|
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,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
|