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,117 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ MAX_LINES = 2000
6
+ MAX_CELLS = 1_000_000
7
+
8
+ # (text, no_eol, key)
9
+ Line = Tuple[str, bool, str]
10
+
11
+
12
+ def split_lines(s: str) -> List[Line]:
13
+ if s == "":
14
+ return []
15
+ parts = s.split("\n")
16
+ no_eol = True
17
+ if parts[-1] == "":
18
+ parts.pop()
19
+ no_eol = False
20
+ out: List[Line] = []
21
+ for i, t in enumerate(parts):
22
+ ne = no_eol and i == len(parts) - 1
23
+ out.append((t, ne, t + "\x00" if ne else t))
24
+ return out
25
+
26
+
27
+ def _range(start: int, length: int) -> str:
28
+ return str(start) if length == 1 else f"{start},{length}"
29
+
30
+
31
+ def build_unified_diff(original: str, updated: str, context_lines: float = 3) -> Optional[Dict[str, Any]]:
32
+ """Standard unified diff. Returns None when the input is too large."""
33
+ ctx = max(0, min(20, int(context_lines)))
34
+ a = split_lines(original)
35
+ b = split_lines(updated)
36
+ pre = 0
37
+ while pre < len(a) and pre < len(b) and a[pre][2] == b[pre][2]:
38
+ pre += 1
39
+ suf = 0
40
+ while suf < len(a) - pre and suf < len(b) - pre and a[len(a) - 1 - suf][2] == b[len(b) - 1 - suf][2]:
41
+ suf += 1
42
+ am = a[pre:len(a) - suf]
43
+ bm = b[pre:len(b) - suf]
44
+ n = len(am)
45
+ m = len(bm)
46
+ if n > MAX_LINES or m > MAX_LINES or n * m > MAX_CELLS:
47
+ return None
48
+ tbl = [[0] * (m + 1) for _ in range(n + 1)]
49
+ for i in range(n - 1, -1, -1):
50
+ for j in range(m - 1, -1, -1):
51
+ if am[i][2] == bm[j][2]:
52
+ tbl[i][j] = tbl[i + 1][j + 1] + 1
53
+ else:
54
+ tbl[i][j] = max(tbl[i + 1][j], tbl[i][j + 1])
55
+ ops: List[Tuple[str, Line]] = []
56
+ for i in range(pre):
57
+ ops.append((" ", a[i]))
58
+ i = 0
59
+ j = 0
60
+ while i < n and j < m:
61
+ if am[i][2] == bm[j][2]:
62
+ ops.append((" ", am[i]))
63
+ i += 1
64
+ j += 1
65
+ elif tbl[i + 1][j] >= tbl[i][j + 1]:
66
+ ops.append(("-", am[i]))
67
+ i += 1
68
+ else:
69
+ ops.append(("+", bm[j]))
70
+ j += 1
71
+ while i < n:
72
+ ops.append(("-", am[i]))
73
+ i += 1
74
+ while j < m:
75
+ ops.append(("+", bm[j]))
76
+ j += 1
77
+ for k in range(len(a) - suf, len(a)):
78
+ ops.append((" ", a[k]))
79
+
80
+ changes = [idx for idx, o in enumerate(ops) if o[0] != " "]
81
+ additions = sum(1 for o in ops if o[0] == "+")
82
+ deletions = sum(1 for o in ops if o[0] == "-")
83
+ if not changes:
84
+ return {"unifiedDiff": "", "additions": 0, "deletions": 0}
85
+
86
+ out = "--- original\n+++ updated\n"
87
+ k = 0
88
+ while k < len(changes):
89
+ end = k
90
+ while end + 1 < len(changes) and changes[end + 1] - changes[end] - 1 <= 2 * ctx:
91
+ end += 1
92
+ start = max(0, changes[k] - ctx)
93
+ stop = min(len(ops) - 1, changes[end] + ctx)
94
+ old_before = 0
95
+ new_before = 0
96
+ for x in range(start):
97
+ if ops[x][0] != "+":
98
+ old_before += 1
99
+ if ops[x][0] != "-":
100
+ new_before += 1
101
+ old_len = 0
102
+ new_len = 0
103
+ body = ""
104
+ for x in range(start, stop + 1):
105
+ t, line = ops[x]
106
+ if t != "+":
107
+ old_len += 1
108
+ if t != "-":
109
+ new_len += 1
110
+ body += f"{t}{line[0]}\n"
111
+ if line[1]:
112
+ body += "\\n"
113
+ old_start = old_before if old_len == 0 else old_before + 1
114
+ new_start = new_before if new_len == 0 else new_before + 1
115
+ out += f"@@ -{_range(old_start, old_len)} +{_range(new_start, new_len)} @@\n{body}"
116
+ k = end + 1
117
+ return {"unifiedDiff": out, "additions": additions, "deletions": deletions}
@@ -0,0 +1,93 @@
1
+ """UnicodeKit / NumKit: code point helpers, case folding, char classes, round4, stable sort, jaccard.
2
+
3
+ Python strings are indexed by code point, so native offsets equal code point offsets.
4
+ Categories come from ``unicodedata.category`` (Node uses single-character ``\\p{..}`` tests, .NET uses
5
+ ``CharUnicodeInfo``). Results depend on each runtime's Unicode version, so shared vectors use only
6
+ long-assigned code points.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ import unicodedata
13
+ from functools import cmp_to_key
14
+ from typing import Callable, Iterable, List, Optional, TypeVar
15
+
16
+ T = TypeVar("T")
17
+
18
+
19
+ def code_points(s: str) -> List[int]:
20
+ return [ord(c) for c in s]
21
+
22
+
23
+ def from_code_points(cps: Iterable[int]) -> str:
24
+ return "".join(chr(cp) for cp in cps)
25
+
26
+
27
+ def cp_length(s: str) -> int:
28
+ return len(s)
29
+
30
+
31
+ def cp_slice(s: str, start: int = 0, end: Optional[int] = None) -> str:
32
+ n = len(s)
33
+ a = max(0, min(start, n))
34
+ b = n if end is None else max(0, min(end, n))
35
+ return s[a:b] if a < b else ""
36
+
37
+
38
+ def native_to_cp(s: str, native_index: int) -> int:
39
+ return native_index
40
+
41
+
42
+ def cp_to_native(s: str, cp_index: int) -> int:
43
+ return cp_index
44
+
45
+
46
+ def compare_code_points(a: str, b: str) -> int:
47
+ x = code_points(a)
48
+ y = code_points(b)
49
+ if x == y:
50
+ return 0
51
+ return -1 if x < y else 1
52
+
53
+
54
+ def fold_case(s: str) -> str:
55
+ t = unicodedata.normalize("NFKC", s).lower()
56
+ t = unicodedata.normalize("NFD", t)
57
+ t = "".join(c for c in t if unicodedata.category(c) != "Mn")
58
+ return t.replace("\u03c2", "\u03c3")
59
+
60
+
61
+ _CLASS_BY_MAJOR = {"L": "letter", "M": "mark", "Z": "space", "P": "punct", "S": "symbol"}
62
+
63
+
64
+ def char_class(cp: int) -> str:
65
+ if cp == 0x85 or 9 <= cp <= 13:
66
+ return "space"
67
+ if cp < 0 or cp > 0x10FFFF:
68
+ return "other"
69
+ cat = unicodedata.category(chr(cp))
70
+ if cat == "Nd":
71
+ return "digit"
72
+ return _CLASS_BY_MAJOR.get(cat[0], "other")
73
+
74
+
75
+ def round4(x: float) -> float:
76
+ if not math.isfinite(x):
77
+ raise ValueError("round4 requires a finite number")
78
+ r = float(math.floor(x * 1e4 + 0.5)) / 1e4
79
+ return 0.0 if r == 0 else r
80
+
81
+
82
+ def stable_sort(items: Iterable[T], cmp: Callable[[T, T], int]) -> List[T]:
83
+ decorated = list(enumerate(items))
84
+ decorated.sort(key=cmp_to_key(lambda x, y: cmp(x[1], y[1]) or (x[0] - y[0])))
85
+ return [v for _, v in decorated]
86
+
87
+
88
+ def jaccard(a: Iterable[str], b: Iterable[str]) -> float:
89
+ sa = set(a)
90
+ sb = set(b)
91
+ inter = len(sa & sb)
92
+ union = len(sa) + len(sb) - inter
93
+ return 0.0 if union == 0 else round4(inter / union)
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, Optional
4
+
5
+ from .catalog import HANDLERS as _CATALOG
6
+ from .context import Handler, ToolContext
7
+ from .crypto import HANDLERS as _CRYPTO
8
+ from .csv import HANDLERS as _CSV
9
+ from .doc import HANDLERS as _DOC
10
+ from .doc_detect import HANDLERS as _DOC_DETECT
11
+ from .encoding import HANDLERS as _ENCODING
12
+ from .fs import HANDLERS as _FS
13
+ from .json import HANDLERS as _JSON
14
+ from .kv import HANDLERS as _KV
15
+ from .math import HANDLERS as _MATH
16
+ from .scratchpad import HANDLERS as _SCRATCHPAD
17
+ from .security import HANDLERS as _SECURITY
18
+ from .state import HANDLERS as _STATE
19
+ from .text import HANDLERS as _TEXT
20
+ from .text_patch import HANDLERS as _TEXT_PATCH
21
+ from .text_rerank import HANDLERS as _TEXT_RERANK
22
+ from .time import HANDLERS as _TIME
23
+ from .time_business import HANDLERS as _TIME_BUSINESS
24
+ from .trace import HANDLERS as _TRACE
25
+ from .validate import HANDLERS as _VALIDATE
26
+ from .web import HANDLERS as _WEB
27
+
28
+ REGISTRY: Dict[str, Handler] = {}
29
+ for _mod in (
30
+ _TIME, _TIME_BUSINESS, _KV, _SCRATCHPAD, _WEB, _JSON, _TEXT, _TEXT_PATCH, _TEXT_RERANK, _MATH, _CSV, _FS,
31
+ _CRYPTO, _ENCODING, _SECURITY, _VALIDATE, _STATE, _CATALOG, _DOC, _DOC_DETECT, _TRACE,
32
+ ):
33
+ for _name, _handler in _mod.items():
34
+ if _name in REGISTRY:
35
+ raise RuntimeError(f"Duplicate tool handler: {_name}")
36
+ REGISTRY[_name] = _handler
37
+
38
+
39
+ def get_handler(name: str) -> Optional[Handler]:
40
+ return REGISTRY.get(name)
41
+
42
+
43
+ __all__ = ["REGISTRY", "get_handler", "ToolContext", "Handler"]
@@ -0,0 +1,27 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict
4
+
5
+ from .context import Handler, ToolContext
6
+
7
+
8
+ def catalog_search(ctx: ToolContext) -> Any:
9
+ inp, catalog, active_tools = ctx.input, ctx.catalog, ctx.active_tools
10
+ query = str(inp.get("query") or "").lower()
11
+ domain = str(inp.get("domain")).lower() if isinstance(inp.get("domain"), str) and inp.get("domain") else None
12
+ include_disabled = inp.get("includeDisabled") is not False
13
+ results = []
14
+ for t in catalog:
15
+ enabled = t["name"] in active_tools
16
+ if not include_disabled and not enabled:
17
+ continue
18
+ if domain and t["domain"] != domain:
19
+ continue
20
+ if not query or query in t["name"].lower() or query in t["summary"].lower() or query in t["domain"].lower():
21
+ results.append({"name": t["name"], "domain": t["domain"], "enabled": enabled, "summary": t["summary"]})
22
+ return {"results": results}
23
+
24
+
25
+ HANDLERS: Dict[str, Handler] = {
26
+ "catalog.search": catalog_search,
27
+ }
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Callable, Dict, List, Set
5
+
6
+ from ..models import SecurityConfig
7
+ from ..stores import KvStore, TraceSink
8
+
9
+
10
+ @dataclass
11
+ class ToolContext:
12
+ input: Dict[str, Any]
13
+ session_id: str
14
+ security: SecurityConfig
15
+ store: KvStore
16
+ trace_sink: TraceSink
17
+ catalog: List[Dict[str, Any]]
18
+ active_tools: Set[str]
19
+
20
+ @classmethod
21
+ def build(
22
+ cls,
23
+ inp: Dict[str, Any],
24
+ security: SecurityConfig,
25
+ store: KvStore,
26
+ trace_sink: TraceSink,
27
+ catalog: List[Dict[str, Any]],
28
+ active_tools: Set[str],
29
+ ) -> "ToolContext":
30
+ sid = inp.get("sessionId")
31
+ session_id = sid if isinstance(sid, str) and sid else "default"
32
+ return cls(inp, session_id, security, store, trace_sink, catalog, active_tools)
33
+
34
+
35
+ Handler = Callable[[ToolContext], Any]
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import hashlib
5
+ import os
6
+ import time
7
+ import uuid
8
+ from typing import Any, Dict, List
9
+
10
+ from .._lib.errors import ToolExecutionError
11
+ from .context import Handler, ToolContext
12
+
13
+
14
+ def crypto_hash(ctx: ToolContext) -> Any:
15
+ inp = ctx.input
16
+ algo = str(inp.get("algorithm") or "sha256").lower()
17
+ if algo not in {"sha256", "sha384", "sha512"}:
18
+ raise ToolExecutionError("INVALID_INPUT", "algorithm must be sha256, sha384, or sha512.")
19
+ enc = "base64" if inp.get("encoding") == "base64" else "utf8"
20
+ raw_content = str(inp.get("content") or "")
21
+ data_bytes = base64.b64decode(raw_content) if enc == "base64" else raw_content.encode("utf-8")
22
+ digest = hashlib.new(algo, data_bytes).digest()
23
+ return {"algorithm": algo, "hex": digest.hex(), "base64": base64.b64encode(digest).decode("ascii")}
24
+
25
+
26
+ def crypto_uuid(ctx: ToolContext) -> Any:
27
+ inp = ctx.input
28
+ version = inp.get("version")
29
+ if version is None:
30
+ version = "v4"
31
+ if not isinstance(version, str) or version not in ("v4", "v7", "ulid"):
32
+ raise ToolExecutionError("INVALID_INPUT", "version must be v4, v7, or ulid.")
33
+ count = max(1, min(int(inp.get("count") or 1), 50))
34
+ ids: List[str] = []
35
+ for _ in range(count):
36
+ if version == "v7":
37
+ ts_ms = int(time.time() * 1000)
38
+ rand = bytearray(os.urandom(16))
39
+ rand[0:6] = ts_ms.to_bytes(6, "big")
40
+ rand[6] = (rand[6] & 0x0F) | 0x70
41
+ rand[8] = (rand[8] & 0x3F) | 0x80
42
+ h = rand.hex()
43
+ ids.append(f"{h[0:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:32]}")
44
+ elif version == "ulid":
45
+ alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
46
+ t = int(time.time() * 1000)
47
+ tp = ""
48
+ for _ in range(10):
49
+ tp = alphabet[t % 32] + tp
50
+ t //= 32
51
+ rp = "".join(alphabet[b % 32] for b in os.urandom(16))
52
+ ids.append(tp + rp)
53
+ else:
54
+ ids.append(str(uuid.uuid4()))
55
+ return {"ids": ids}
56
+
57
+
58
+ HANDLERS: Dict[str, Handler] = {
59
+ "crypto.hash": crypto_hash,
60
+ "crypto.uuid": crypto_uuid,
61
+ }
@@ -0,0 +1,132 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import re
5
+ from typing import Any, Dict, List, Optional, Tuple
6
+
7
+ from .._lib.common import clean_number
8
+ from .._lib.errors import ToolExecutionError
9
+ from .context import Handler, ToolContext
10
+
11
+
12
+ def parse_csv_lines(csv_text: str, explicit_delimiter: Optional[str] = None) -> Tuple[List[str], List[Dict[str, Any]]]:
13
+ lines = [l for l in csv_text.replace("\r\n", "\n").replace("\r", "\n").split("\n") if l.strip()]
14
+ if not lines:
15
+ return [], []
16
+ delim = explicit_delimiter or ("\t" if "\t" in lines[0] else ";" if ";" in lines[0] else ",")
17
+ reader = csv.reader(lines, delimiter=delim)
18
+ parsed_rows = list(reader)
19
+ headers = [h.strip() for h in parsed_rows[0]]
20
+ rows: List[Dict[str, Any]] = []
21
+ for raw_cols in parsed_rows[1:]:
22
+ row: Dict[str, Any] = {}
23
+ for idx, h in enumerate(headers):
24
+ raw = raw_cols[idx].strip() if idx < len(raw_cols) else ""
25
+ if raw == "":
26
+ row[h] = None
27
+ elif re.match(r"^-?\d+(\.\d+)?$", raw):
28
+ row[h] = float(raw) if "." in raw else int(raw)
29
+ elif raw in ("true", "false"):
30
+ row[h] = raw == "true"
31
+ else:
32
+ row[h] = raw
33
+ rows.append(row)
34
+ return headers, rows
35
+
36
+
37
+ def csv_parse(ctx: ToolContext) -> Any:
38
+ inp = ctx.input
39
+ headers, rows = parse_csv_lines(str(inp.get("csvText") or ""), inp.get("delimiter"))
40
+ offset = max(0, int(inp.get("offset") or 0))
41
+ limit = max(1, min(int(inp.get("limit") or 100), 500))
42
+ sliced = rows[offset : offset + limit]
43
+ return {"headers": headers, "rows": sliced, "totalRows": len(rows), "returnedRows": len(sliced)}
44
+
45
+
46
+ def csv_summarize(ctx: ToolContext) -> Any:
47
+ inp = ctx.input
48
+ if not isinstance(inp.get("csvText"), str):
49
+ raise ToolExecutionError("INVALID_INPUT", "csvText is required and must be a string.")
50
+ sample_size = max(1, min(int(inp.get("sampleSize") or 5), 20))
51
+ headers, rows = parse_csv_lines(str(inp.get("csvText") or ""))
52
+ cols = []
53
+ for name in headers:
54
+ vals = [r.get(name) for r in rows]
55
+ non_null = [v for v in vals if v is not None]
56
+ if not non_null:
57
+ inferred = "unknown"
58
+ elif all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in non_null):
59
+ inferred = "number"
60
+ elif all(isinstance(v, bool) for v in non_null):
61
+ inferred = "boolean"
62
+ else:
63
+ inferred = "string"
64
+ samples: List[Any] = []
65
+ for v in non_null:
66
+ if v not in samples:
67
+ samples.append(v)
68
+ if len(samples) >= sample_size:
69
+ break
70
+ cols.append({"name": name, "inferredType": inferred, "nullCount": len(vals) - len(non_null), "sampleValues": samples})
71
+ return {"rowCount": len(rows), "columns": cols}
72
+
73
+
74
+ def csv_filter_aggregate(ctx: ToolContext) -> Any:
75
+ inp = ctx.input
76
+ if not isinstance(inp.get("csvText"), str):
77
+ raise ToolExecutionError("INVALID_INPUT", "csvText is required and must be a string.")
78
+ _, rows = parse_csv_lines(str(inp.get("csvText") or ""))
79
+ flt = inp.get("filter") if isinstance(inp.get("filter"), dict) else None
80
+ if flt and flt.get("field"):
81
+ field = flt["field"]
82
+ op = flt.get("op")
83
+ target_val = flt.get("value")
84
+ filtered = []
85
+ for r in rows:
86
+ v = r.get(field)
87
+ if op == "eq" and v == target_val:
88
+ filtered.append(r)
89
+ elif op == "gt" and v is not None and float(v) > float(target_val): # type: ignore[arg-type]
90
+ filtered.append(r)
91
+ elif op == "lt" and v is not None and float(v) < float(target_val): # type: ignore[arg-type]
92
+ filtered.append(r)
93
+ elif op == "contains" and str(target_val or "") in str(v or ""):
94
+ filtered.append(r)
95
+ elif op not in ("eq", "gt", "lt", "contains"):
96
+ filtered.append(r)
97
+ else:
98
+ filtered = rows
99
+
100
+ group_by = inp.get("groupBy") if isinstance(inp.get("groupBy"), str) and inp.get("groupBy") else None
101
+ aggs = inp.get("aggregations") if isinstance(inp.get("aggregations"), list) else [{"field": "*", "op": "count"}]
102
+ groups: Dict[str, List[Dict[str, Any]]] = {}
103
+ for r in filtered:
104
+ g_key = str(r.get(group_by)) if group_by else "__all__"
105
+ groups.setdefault(g_key, []).append(r)
106
+ results: List[Dict[str, Any]] = []
107
+ for g_val, g_rows in groups.items():
108
+ row: Dict[str, Any] = {group_by: g_val} if group_by else {}
109
+ for agg in aggs:
110
+ af, aop = agg["field"], agg["op"]
111
+ label = f"{aop}_{af}"
112
+ if aop == "count":
113
+ row[label] = len(g_rows)
114
+ else:
115
+ nums = [float(r[af]) for r in g_rows if isinstance(r.get(af), (int, float))]
116
+ if aop == "sum":
117
+ row[label] = clean_number(sum(nums))
118
+ elif aop == "avg":
119
+ row[label] = clean_number(round(sum(nums) / len(nums), 4)) if nums else 0
120
+ elif aop == "min":
121
+ row[label] = clean_number(min(nums)) if nums else None
122
+ elif aop == "max":
123
+ row[label] = clean_number(max(nums)) if nums else None
124
+ results.append(row)
125
+ return {"results": results, "matchedRows": len(filtered)}
126
+
127
+
128
+ HANDLERS: Dict[str, Handler] = {
129
+ "csv.parse": csv_parse,
130
+ "csv.summarize": csv_summarize,
131
+ "csv.filter_aggregate": csv_filter_aggregate,
132
+ }
@@ -0,0 +1,77 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import Any, Dict, List
5
+
6
+ from .._lib.html import strip_html
7
+ from .context import Handler, ToolContext
8
+
9
+
10
+ def doc_extract_tables(ctx: ToolContext) -> Any:
11
+ inp = ctx.input
12
+ content = str(inp.get("content") or "")
13
+ fmt = str(inp.get("format") or "markdown")
14
+ tables: List[Dict[str, Any]] = []
15
+ if fmt == "markdown":
16
+ lines = [l.strip() for l in content.split("\n")]
17
+ i = 0
18
+ while i < len(lines) - 1:
19
+ if lines[i].startswith("|") and re.match(r"^\|[\s:|-]+\|?$", lines[i + 1]):
20
+ headers = [c.strip() for c in lines[i].split("|")[1:-1]]
21
+ rows: List[Dict[str, str]] = []
22
+ j = i + 2
23
+ while j < len(lines) and lines[j].startswith("|"):
24
+ cells = [c.strip() for c in lines[j].split("|")[1:-1]]
25
+ rows.append({h: (cells[idx] if idx < len(cells) else "") for idx, h in enumerate(headers)})
26
+ j += 1
27
+ tables.append({"headers": headers, "rows": rows})
28
+ i = j
29
+ else:
30
+ i += 1
31
+ else:
32
+ for tbl in re.findall(r"<table[\s\S]*?</table>", content, re.IGNORECASE):
33
+ tr_list = re.findall(r"<tr[\s\S]*?</tr>", tbl, re.IGNORECASE)
34
+ if not tr_list:
35
+ continue
36
+ def _cells(tr: str) -> List[str]:
37
+ return [strip_html(c) for c in re.findall(r"<t[hd][^>]*>([\s\S]*?)</t[hd]>", tr, re.IGNORECASE)]
38
+ headers = _cells(tr_list[0])
39
+ rows = []
40
+ for tr in tr_list[1:]:
41
+ cs = _cells(tr)
42
+ rows.append({h: (cs[idx] if idx < len(cs) else "") for idx, h in enumerate(headers)})
43
+ tables.append({"headers": headers, "rows": rows})
44
+ return {"tables": tables, "tableCount": len(tables)}
45
+
46
+
47
+ def doc_to_markdown_report(ctx: ToolContext) -> Any:
48
+ inp = ctx.input
49
+ title = str(inp.get("title") or "Report")
50
+ summary = inp.get("summary") if isinstance(inp.get("summary"), str) else ""
51
+ sections = inp.get("sections") if isinstance(inp.get("sections"), list) else []
52
+ out = [f"# {title}", ""]
53
+ if summary:
54
+ out.extend([summary, ""])
55
+ for sec in sections:
56
+ if not isinstance(sec, dict):
57
+ continue
58
+ if sec.get("heading"):
59
+ out.extend([f"## {sec['heading']}", ""])
60
+ if sec.get("body"):
61
+ out.extend([str(sec["body"]), ""])
62
+ tbl = sec.get("table")
63
+ if isinstance(tbl, list) and tbl and isinstance(tbl[0], dict):
64
+ cols = list(tbl[0].keys())
65
+ out.append(f"| {' | '.join(cols)} |")
66
+ out.append(f"| {' | '.join('---' for _ in cols)} |")
67
+ for row in tbl:
68
+ out.append(f"| {' | '.join(str(row.get(c, '')) for c in cols)} |")
69
+ out.append("")
70
+ md = "\n".join(out).strip()
71
+ return {"markdown": md, "charCount": len(md)}
72
+
73
+
74
+ HANDLERS: Dict[str, Handler] = {
75
+ "doc.extract_tables": doc_extract_tables,
76
+ "doc.to_markdown_report": doc_to_markdown_report,
77
+ }
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import Any, Dict
5
+
6
+ from .._lib.errors import ToolExecutionError
7
+ from .context import Handler, ToolContext
8
+
9
+ _CODE_START = re.compile(r"^(def |function |class |import |const |let |var |public |private |#include|using |package |return )")
10
+ _KEY = re.compile(r"^[A-Za-z0-9_-]+:( .*)?$")
11
+ _YAML_LINE = re.compile(r"^[ \t]*([A-Za-z0-9_-]+:( .*)?|- .*)$")
12
+ _HEADING = re.compile(r"^#{1,6} ")
13
+
14
+
15
+ def _detect(text: str) -> Dict[str, Any]:
16
+ t = text[:512].strip()
17
+ if not t:
18
+ return {"type": "empty", "suggestedTool": None}
19
+ lower = t.lower()
20
+ lines = [l.rstrip("\r") if l.endswith("\r") else l for l in t.split("\n")]
21
+ nonblank = [l for l in lines if l.strip() != ""]
22
+
23
+ if t[0] == "{" and '"' in t:
24
+ return {"type": "json", "suggestedTool": "json.query"}
25
+ if t[0] == "[":
26
+ rest = t[1:].lstrip()
27
+ if rest and rest[0] in '{["-0123456789tfn]':
28
+ return {"type": "json", "suggestedTool": "json.query"}
29
+ if lower.startswith("<!doctype html") or lower.startswith("<html") or (t[0] == "<" and "</" in lower):
30
+ return {"type": "html", "suggestedTool": "doc.extract_tables"}
31
+ if any(_HEADING.match(l) or l.startswith("```") or (l.startswith("|") and "---" in l) for l in lines) or ("](" in t and "[" in t):
32
+ return {"type": "markdown", "suggestedTool": "doc.extract_tables"}
33
+ if any(_CODE_START.match(l.lstrip()) for l in nonblank) or any(l.endswith(";") or l.endswith("{") for l in nonblank):
34
+ return {"type": "code", "suggestedTool": "text.chunk"}
35
+ first5 = nonblank[:5]
36
+ if len(nonblank) >= 2:
37
+ for d in (",", ";", "\t"):
38
+ k = first5[0].count(d)
39
+ if k >= 1 and all(l.count(d) == k for l in first5):
40
+ return {"type": "csv", "suggestedTool": "csv.parse"}
41
+ if (nonblank[0] == "---" or _KEY.match(nonblank[0])) and all(l == "---" or _YAML_LINE.match(l) for l in first5):
42
+ return {"type": "yaml", "suggestedTool": "text.chunk"}
43
+ return {"type": "text", "suggestedTool": "text.chunk"}
44
+
45
+
46
+ def doc_detect_type(ctx: ToolContext) -> Any:
47
+ text = ctx.input.get("text")
48
+ if not isinstance(text, str):
49
+ raise ToolExecutionError("INVALID_INPUT", "text must be a string.")
50
+ return _detect(text)
51
+
52
+
53
+ HANDLERS: Dict[str, Handler] = {
54
+ "doc.detect_type": doc_detect_type,
55
+ }